diff --git a/.gitignore b/.gitignore
index c2658d7..b947077 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
node_modules/
+dist/
diff --git a/dist/main.js b/dist/main.js
deleted file mode 100644
index 987933b..0000000
--- a/dist/main.js
+++ /dev/null
@@ -1,658475 +0,0 @@
-// @bun
-var __create = Object.create;
-var __getProtoOf = Object.getPrototypeOf;
-var __defProp = Object.defineProperty;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-function __accessProp(key) {
- return this[key];
-}
-var __reExport = (target, mod2, secondTarget) => {
- var keys = __getOwnPropNames(mod2);
- for (let key of keys)
- if (!__hasOwnProp.call(target, key) && key !== "default")
- __defProp(target, key, {
- get: __accessProp.bind(mod2, key),
- enumerable: true
- });
- if (secondTarget) {
- for (let key of keys)
- if (!__hasOwnProp.call(secondTarget, key) && key !== "default")
- __defProp(secondTarget, key, {
- get: __accessProp.bind(mod2, key),
- enumerable: true
- });
- return secondTarget;
- }
-};
-var __toESMCache_node;
-var __toESMCache_esm;
-var __toESM = (mod2, isNodeMode, target) => {
- var canCache = mod2 != null && typeof mod2 === "object";
- if (canCache) {
- var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
- var cached = cache.get(mod2);
- if (cached)
- return cached;
- }
- target = mod2 != null ? __create(__getProtoOf(mod2)) : {};
- const to = isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target;
- for (let key of __getOwnPropNames(mod2))
- if (!__hasOwnProp.call(to, key))
- __defProp(to, key, {
- get: __accessProp.bind(mod2, key),
- enumerable: true
- });
- if (canCache)
- cache.set(mod2, to);
- return to;
-};
-var __toCommonJS = (from) => {
- var entry = (__moduleCache ??= new WeakMap).get(from), desc;
- if (entry)
- return entry;
- entry = __defProp({}, "__esModule", { value: true });
- if (from && typeof from === "object" || typeof from === "function") {
- for (var key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(entry, key))
- __defProp(entry, key, {
- get: __accessProp.bind(from, key),
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
- });
- }
- __moduleCache.set(from, entry);
- return entry;
-};
-var __moduleCache;
-var __commonJS = (cb, mod2) => () => (mod2 || cb((mod2 = { exports: {} }).exports, mod2), mod2.exports);
-var __returnValue = (v) => v;
-function __exportSetter(name, newValue) {
- this[name] = __returnValue.bind(null, newValue);
-}
-var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, {
- get: all[name],
- enumerable: true,
- configurable: true,
- set: __exportSetter.bind(all, name)
- });
-};
-var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
-var __require = import.meta.require;
-var __using = (stack, value, async) => {
- if (value != null) {
- if (typeof value !== "object" && typeof value !== "function")
- throw TypeError('Object expected to be assigned to "using" declaration');
- let dispose;
- if (async)
- dispose = value[Symbol.asyncDispose];
- if (dispose === undefined)
- dispose = value[Symbol.dispose];
- if (typeof dispose !== "function")
- throw TypeError("Object not disposable");
- stack.push([async, dispose, value]);
- } else if (async) {
- stack.push([async]);
- }
- return value;
-};
-var __callDispose = (stack, error, hasError) => {
- let fail = (e) => error = hasError ? new SuppressedError(e, error, "An error was suppressed during disposal") : (hasError = true, e), next = (it) => {
- while (it = stack.pop()) {
- try {
- var result = it[1] && it[1].call(it[2]);
- if (it[0])
- return Promise.resolve(result).then(next, (e) => (fail(e), next()));
- } catch (e) {
- fail(e);
- }
- }
- if (hasError)
- throw error;
- };
- return next();
-};
-
-// node_modules/lodash-es/_listCacheClear.js
-function listCacheClear() {
- this.__data__ = [];
- this.size = 0;
-}
-var _listCacheClear_default;
-var init__listCacheClear = __esm(() => {
- _listCacheClear_default = listCacheClear;
-});
-
-// node_modules/lodash-es/eq.js
-function eq(value, other) {
- return value === other || value !== value && other !== other;
-}
-var eq_default;
-var init_eq = __esm(() => {
- eq_default = eq;
-});
-
-// node_modules/lodash-es/_assocIndexOf.js
-function assocIndexOf(array, key) {
- var length = array.length;
- while (length--) {
- if (eq_default(array[length][0], key)) {
- return length;
- }
- }
- return -1;
-}
-var _assocIndexOf_default;
-var init__assocIndexOf = __esm(() => {
- init_eq();
- _assocIndexOf_default = assocIndexOf;
-});
-
-// node_modules/lodash-es/_listCacheDelete.js
-function listCacheDelete(key) {
- var data = this.__data__, index = _assocIndexOf_default(data, key);
- if (index < 0) {
- return false;
- }
- var lastIndex = data.length - 1;
- if (index == lastIndex) {
- data.pop();
- } else {
- splice.call(data, index, 1);
- }
- --this.size;
- return true;
-}
-var arrayProto, splice, _listCacheDelete_default;
-var init__listCacheDelete = __esm(() => {
- init__assocIndexOf();
- arrayProto = Array.prototype;
- splice = arrayProto.splice;
- _listCacheDelete_default = listCacheDelete;
-});
-
-// node_modules/lodash-es/_listCacheGet.js
-function listCacheGet(key) {
- var data = this.__data__, index = _assocIndexOf_default(data, key);
- return index < 0 ? undefined : data[index][1];
-}
-var _listCacheGet_default;
-var init__listCacheGet = __esm(() => {
- init__assocIndexOf();
- _listCacheGet_default = listCacheGet;
-});
-
-// node_modules/lodash-es/_listCacheHas.js
-function listCacheHas(key) {
- return _assocIndexOf_default(this.__data__, key) > -1;
-}
-var _listCacheHas_default;
-var init__listCacheHas = __esm(() => {
- init__assocIndexOf();
- _listCacheHas_default = listCacheHas;
-});
-
-// node_modules/lodash-es/_listCacheSet.js
-function listCacheSet(key, value) {
- var data = this.__data__, index = _assocIndexOf_default(data, key);
- if (index < 0) {
- ++this.size;
- data.push([key, value]);
- } else {
- data[index][1] = value;
- }
- return this;
-}
-var _listCacheSet_default;
-var init__listCacheSet = __esm(() => {
- init__assocIndexOf();
- _listCacheSet_default = listCacheSet;
-});
-
-// node_modules/lodash-es/_ListCache.js
-function ListCache(entries) {
- var index = -1, length = entries == null ? 0 : entries.length;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
-}
-var _ListCache_default;
-var init__ListCache = __esm(() => {
- init__listCacheClear();
- init__listCacheDelete();
- init__listCacheGet();
- init__listCacheHas();
- init__listCacheSet();
- ListCache.prototype.clear = _listCacheClear_default;
- ListCache.prototype["delete"] = _listCacheDelete_default;
- ListCache.prototype.get = _listCacheGet_default;
- ListCache.prototype.has = _listCacheHas_default;
- ListCache.prototype.set = _listCacheSet_default;
- _ListCache_default = ListCache;
-});
-
-// node_modules/lodash-es/_stackClear.js
-function stackClear() {
- this.__data__ = new _ListCache_default;
- this.size = 0;
-}
-var _stackClear_default;
-var init__stackClear = __esm(() => {
- init__ListCache();
- _stackClear_default = stackClear;
-});
-
-// node_modules/lodash-es/_stackDelete.js
-function stackDelete(key) {
- var data = this.__data__, result = data["delete"](key);
- this.size = data.size;
- return result;
-}
-var _stackDelete_default;
-var init__stackDelete = __esm(() => {
- _stackDelete_default = stackDelete;
-});
-
-// node_modules/lodash-es/_stackGet.js
-function stackGet(key) {
- return this.__data__.get(key);
-}
-var _stackGet_default;
-var init__stackGet = __esm(() => {
- _stackGet_default = stackGet;
-});
-
-// node_modules/lodash-es/_stackHas.js
-function stackHas(key) {
- return this.__data__.has(key);
-}
-var _stackHas_default;
-var init__stackHas = __esm(() => {
- _stackHas_default = stackHas;
-});
-
-// node_modules/lodash-es/_freeGlobal.js
-var freeGlobal, _freeGlobal_default;
-var init__freeGlobal = __esm(() => {
- freeGlobal = typeof global == "object" && global && global.Object === Object && global;
- _freeGlobal_default = freeGlobal;
-});
-
-// node_modules/lodash-es/_root.js
-var freeSelf, root, _root_default;
-var init__root = __esm(() => {
- init__freeGlobal();
- freeSelf = typeof self == "object" && self && self.Object === Object && self;
- root = _freeGlobal_default || freeSelf || Function("return this")();
- _root_default = root;
-});
-
-// node_modules/lodash-es/_Symbol.js
-var Symbol2, _Symbol_default;
-var init__Symbol = __esm(() => {
- init__root();
- Symbol2 = _root_default.Symbol;
- _Symbol_default = Symbol2;
-});
-
-// node_modules/lodash-es/_getRawTag.js
-function getRawTag(value) {
- var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
- try {
- value[symToStringTag] = undefined;
- var unmasked = true;
- } catch (e) {}
- var result = nativeObjectToString.call(value);
- if (unmasked) {
- if (isOwn) {
- value[symToStringTag] = tag;
- } else {
- delete value[symToStringTag];
- }
- }
- return result;
-}
-var objectProto, hasOwnProperty, nativeObjectToString, symToStringTag, _getRawTag_default;
-var init__getRawTag = __esm(() => {
- init__Symbol();
- objectProto = Object.prototype;
- hasOwnProperty = objectProto.hasOwnProperty;
- nativeObjectToString = objectProto.toString;
- symToStringTag = _Symbol_default ? _Symbol_default.toStringTag : undefined;
- _getRawTag_default = getRawTag;
-});
-
-// node_modules/lodash-es/_objectToString.js
-function objectToString(value) {
- return nativeObjectToString2.call(value);
-}
-var objectProto2, nativeObjectToString2, _objectToString_default;
-var init__objectToString = __esm(() => {
- objectProto2 = Object.prototype;
- nativeObjectToString2 = objectProto2.toString;
- _objectToString_default = objectToString;
-});
-
-// node_modules/lodash-es/_baseGetTag.js
-function baseGetTag(value) {
- if (value == null) {
- return value === undefined ? undefinedTag : nullTag;
- }
- return symToStringTag2 && symToStringTag2 in Object(value) ? _getRawTag_default(value) : _objectToString_default(value);
-}
-var nullTag = "[object Null]", undefinedTag = "[object Undefined]", symToStringTag2, _baseGetTag_default;
-var init__baseGetTag = __esm(() => {
- init__Symbol();
- init__getRawTag();
- init__objectToString();
- symToStringTag2 = _Symbol_default ? _Symbol_default.toStringTag : undefined;
- _baseGetTag_default = baseGetTag;
-});
-
-// node_modules/lodash-es/isObject.js
-function isObject(value) {
- var type = typeof value;
- return value != null && (type == "object" || type == "function");
-}
-var isObject_default;
-var init_isObject = __esm(() => {
- isObject_default = isObject;
-});
-
-// node_modules/lodash-es/isFunction.js
-function isFunction(value) {
- if (!isObject_default(value)) {
- return false;
- }
- var tag = _baseGetTag_default(value);
- return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
-}
-var asyncTag = "[object AsyncFunction]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", proxyTag = "[object Proxy]", isFunction_default;
-var init_isFunction = __esm(() => {
- init__baseGetTag();
- init_isObject();
- isFunction_default = isFunction;
-});
-
-// node_modules/lodash-es/_coreJsData.js
-var coreJsData, _coreJsData_default;
-var init__coreJsData = __esm(() => {
- init__root();
- coreJsData = _root_default["__core-js_shared__"];
- _coreJsData_default = coreJsData;
-});
-
-// node_modules/lodash-es/_isMasked.js
-function isMasked(func) {
- return !!maskSrcKey && maskSrcKey in func;
-}
-var maskSrcKey, _isMasked_default;
-var init__isMasked = __esm(() => {
- init__coreJsData();
- maskSrcKey = function() {
- var uid = /[^.]+$/.exec(_coreJsData_default && _coreJsData_default.keys && _coreJsData_default.keys.IE_PROTO || "");
- return uid ? "Symbol(src)_1." + uid : "";
- }();
- _isMasked_default = isMasked;
-});
-
-// node_modules/lodash-es/_toSource.js
-function toSource(func) {
- if (func != null) {
- try {
- return funcToString.call(func);
- } catch (e) {}
- try {
- return func + "";
- } catch (e) {}
- }
- return "";
-}
-var funcProto, funcToString, _toSource_default;
-var init__toSource = __esm(() => {
- funcProto = Function.prototype;
- funcToString = funcProto.toString;
- _toSource_default = toSource;
-});
-
-// node_modules/lodash-es/_baseIsNative.js
-function baseIsNative(value) {
- if (!isObject_default(value) || _isMasked_default(value)) {
- return false;
- }
- var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor;
- return pattern.test(_toSource_default(value));
-}
-var reRegExpChar, reIsHostCtor, funcProto2, objectProto3, funcToString2, hasOwnProperty2, reIsNative, _baseIsNative_default;
-var init__baseIsNative = __esm(() => {
- init_isFunction();
- init__isMasked();
- init_isObject();
- init__toSource();
- reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
- reIsHostCtor = /^\[object .+?Constructor\]$/;
- funcProto2 = Function.prototype;
- objectProto3 = Object.prototype;
- funcToString2 = funcProto2.toString;
- hasOwnProperty2 = objectProto3.hasOwnProperty;
- reIsNative = RegExp("^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
- _baseIsNative_default = baseIsNative;
-});
-
-// node_modules/lodash-es/_getValue.js
-function getValue(object, key) {
- return object == null ? undefined : object[key];
-}
-var _getValue_default;
-var init__getValue = __esm(() => {
- _getValue_default = getValue;
-});
-
-// node_modules/lodash-es/_getNative.js
-function getNative(object, key) {
- var value = _getValue_default(object, key);
- return _baseIsNative_default(value) ? value : undefined;
-}
-var _getNative_default;
-var init__getNative = __esm(() => {
- init__baseIsNative();
- init__getValue();
- _getNative_default = getNative;
-});
-
-// node_modules/lodash-es/_Map.js
-var Map2, _Map_default;
-var init__Map = __esm(() => {
- init__getNative();
- init__root();
- Map2 = _getNative_default(_root_default, "Map");
- _Map_default = Map2;
-});
-
-// node_modules/lodash-es/_nativeCreate.js
-var nativeCreate, _nativeCreate_default;
-var init__nativeCreate = __esm(() => {
- init__getNative();
- nativeCreate = _getNative_default(Object, "create");
- _nativeCreate_default = nativeCreate;
-});
-
-// node_modules/lodash-es/_hashClear.js
-function hashClear() {
- this.__data__ = _nativeCreate_default ? _nativeCreate_default(null) : {};
- this.size = 0;
-}
-var _hashClear_default;
-var init__hashClear = __esm(() => {
- init__nativeCreate();
- _hashClear_default = hashClear;
-});
-
-// node_modules/lodash-es/_hashDelete.js
-function hashDelete(key) {
- var result = this.has(key) && delete this.__data__[key];
- this.size -= result ? 1 : 0;
- return result;
-}
-var _hashDelete_default;
-var init__hashDelete = __esm(() => {
- _hashDelete_default = hashDelete;
-});
-
-// node_modules/lodash-es/_hashGet.js
-function hashGet(key) {
- var data = this.__data__;
- if (_nativeCreate_default) {
- var result = data[key];
- return result === HASH_UNDEFINED ? undefined : result;
- }
- return hasOwnProperty3.call(data, key) ? data[key] : undefined;
-}
-var HASH_UNDEFINED = "__lodash_hash_undefined__", objectProto4, hasOwnProperty3, _hashGet_default;
-var init__hashGet = __esm(() => {
- init__nativeCreate();
- objectProto4 = Object.prototype;
- hasOwnProperty3 = objectProto4.hasOwnProperty;
- _hashGet_default = hashGet;
-});
-
-// node_modules/lodash-es/_hashHas.js
-function hashHas(key) {
- var data = this.__data__;
- return _nativeCreate_default ? data[key] !== undefined : hasOwnProperty4.call(data, key);
-}
-var objectProto5, hasOwnProperty4, _hashHas_default;
-var init__hashHas = __esm(() => {
- init__nativeCreate();
- objectProto5 = Object.prototype;
- hasOwnProperty4 = objectProto5.hasOwnProperty;
- _hashHas_default = hashHas;
-});
-
-// node_modules/lodash-es/_hashSet.js
-function hashSet(key, value) {
- var data = this.__data__;
- this.size += this.has(key) ? 0 : 1;
- data[key] = _nativeCreate_default && value === undefined ? HASH_UNDEFINED2 : value;
- return this;
-}
-var HASH_UNDEFINED2 = "__lodash_hash_undefined__", _hashSet_default;
-var init__hashSet = __esm(() => {
- init__nativeCreate();
- _hashSet_default = hashSet;
-});
-
-// node_modules/lodash-es/_Hash.js
-function Hash(entries) {
- var index = -1, length = entries == null ? 0 : entries.length;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
-}
-var _Hash_default;
-var init__Hash = __esm(() => {
- init__hashClear();
- init__hashDelete();
- init__hashGet();
- init__hashHas();
- init__hashSet();
- Hash.prototype.clear = _hashClear_default;
- Hash.prototype["delete"] = _hashDelete_default;
- Hash.prototype.get = _hashGet_default;
- Hash.prototype.has = _hashHas_default;
- Hash.prototype.set = _hashSet_default;
- _Hash_default = Hash;
-});
-
-// node_modules/lodash-es/_mapCacheClear.js
-function mapCacheClear() {
- this.size = 0;
- this.__data__ = {
- hash: new _Hash_default,
- map: new (_Map_default || _ListCache_default),
- string: new _Hash_default
- };
-}
-var _mapCacheClear_default;
-var init__mapCacheClear = __esm(() => {
- init__Hash();
- init__ListCache();
- init__Map();
- _mapCacheClear_default = mapCacheClear;
-});
-
-// node_modules/lodash-es/_isKeyable.js
-function isKeyable(value) {
- var type = typeof value;
- return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
-}
-var _isKeyable_default;
-var init__isKeyable = __esm(() => {
- _isKeyable_default = isKeyable;
-});
-
-// node_modules/lodash-es/_getMapData.js
-function getMapData(map, key) {
- var data = map.__data__;
- return _isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
-}
-var _getMapData_default;
-var init__getMapData = __esm(() => {
- init__isKeyable();
- _getMapData_default = getMapData;
-});
-
-// node_modules/lodash-es/_mapCacheDelete.js
-function mapCacheDelete(key) {
- var result = _getMapData_default(this, key)["delete"](key);
- this.size -= result ? 1 : 0;
- return result;
-}
-var _mapCacheDelete_default;
-var init__mapCacheDelete = __esm(() => {
- init__getMapData();
- _mapCacheDelete_default = mapCacheDelete;
-});
-
-// node_modules/lodash-es/_mapCacheGet.js
-function mapCacheGet(key) {
- return _getMapData_default(this, key).get(key);
-}
-var _mapCacheGet_default;
-var init__mapCacheGet = __esm(() => {
- init__getMapData();
- _mapCacheGet_default = mapCacheGet;
-});
-
-// node_modules/lodash-es/_mapCacheHas.js
-function mapCacheHas(key) {
- return _getMapData_default(this, key).has(key);
-}
-var _mapCacheHas_default;
-var init__mapCacheHas = __esm(() => {
- init__getMapData();
- _mapCacheHas_default = mapCacheHas;
-});
-
-// node_modules/lodash-es/_mapCacheSet.js
-function mapCacheSet(key, value) {
- var data = _getMapData_default(this, key), size = data.size;
- data.set(key, value);
- this.size += data.size == size ? 0 : 1;
- return this;
-}
-var _mapCacheSet_default;
-var init__mapCacheSet = __esm(() => {
- init__getMapData();
- _mapCacheSet_default = mapCacheSet;
-});
-
-// node_modules/lodash-es/_MapCache.js
-function MapCache(entries) {
- var index = -1, length = entries == null ? 0 : entries.length;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
-}
-var _MapCache_default;
-var init__MapCache = __esm(() => {
- init__mapCacheClear();
- init__mapCacheDelete();
- init__mapCacheGet();
- init__mapCacheHas();
- init__mapCacheSet();
- MapCache.prototype.clear = _mapCacheClear_default;
- MapCache.prototype["delete"] = _mapCacheDelete_default;
- MapCache.prototype.get = _mapCacheGet_default;
- MapCache.prototype.has = _mapCacheHas_default;
- MapCache.prototype.set = _mapCacheSet_default;
- _MapCache_default = MapCache;
-});
-
-// node_modules/lodash-es/_stackSet.js
-function stackSet(key, value) {
- var data = this.__data__;
- if (data instanceof _ListCache_default) {
- var pairs = data.__data__;
- if (!_Map_default || pairs.length < LARGE_ARRAY_SIZE - 1) {
- pairs.push([key, value]);
- this.size = ++data.size;
- return this;
- }
- data = this.__data__ = new _MapCache_default(pairs);
- }
- data.set(key, value);
- this.size = data.size;
- return this;
-}
-var LARGE_ARRAY_SIZE = 200, _stackSet_default;
-var init__stackSet = __esm(() => {
- init__ListCache();
- init__Map();
- init__MapCache();
- _stackSet_default = stackSet;
-});
-
-// node_modules/lodash-es/_Stack.js
-function Stack(entries) {
- var data = this.__data__ = new _ListCache_default(entries);
- this.size = data.size;
-}
-var _Stack_default;
-var init__Stack = __esm(() => {
- init__ListCache();
- init__stackClear();
- init__stackDelete();
- init__stackGet();
- init__stackHas();
- init__stackSet();
- Stack.prototype.clear = _stackClear_default;
- Stack.prototype["delete"] = _stackDelete_default;
- Stack.prototype.get = _stackGet_default;
- Stack.prototype.has = _stackHas_default;
- Stack.prototype.set = _stackSet_default;
- _Stack_default = Stack;
-});
-
-// node_modules/lodash-es/_setCacheAdd.js
-function setCacheAdd(value) {
- this.__data__.set(value, HASH_UNDEFINED3);
- return this;
-}
-var HASH_UNDEFINED3 = "__lodash_hash_undefined__", _setCacheAdd_default;
-var init__setCacheAdd = __esm(() => {
- _setCacheAdd_default = setCacheAdd;
-});
-
-// node_modules/lodash-es/_setCacheHas.js
-function setCacheHas(value) {
- return this.__data__.has(value);
-}
-var _setCacheHas_default;
-var init__setCacheHas = __esm(() => {
- _setCacheHas_default = setCacheHas;
-});
-
-// node_modules/lodash-es/_SetCache.js
-function SetCache(values) {
- var index = -1, length = values == null ? 0 : values.length;
- this.__data__ = new _MapCache_default;
- while (++index < length) {
- this.add(values[index]);
- }
-}
-var _SetCache_default;
-var init__SetCache = __esm(() => {
- init__MapCache();
- init__setCacheAdd();
- init__setCacheHas();
- SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd_default;
- SetCache.prototype.has = _setCacheHas_default;
- _SetCache_default = SetCache;
-});
-
-// node_modules/lodash-es/_arraySome.js
-function arraySome(array, predicate) {
- var index = -1, length = array == null ? 0 : array.length;
- while (++index < length) {
- if (predicate(array[index], index, array)) {
- return true;
- }
- }
- return false;
-}
-var _arraySome_default;
-var init__arraySome = __esm(() => {
- _arraySome_default = arraySome;
-});
-
-// node_modules/lodash-es/_cacheHas.js
-function cacheHas(cache, key) {
- return cache.has(key);
-}
-var _cacheHas_default;
-var init__cacheHas = __esm(() => {
- _cacheHas_default = cacheHas;
-});
-
-// node_modules/lodash-es/_equalArrays.js
-function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
- if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
- return false;
- }
- var arrStacked = stack.get(array);
- var othStacked = stack.get(other);
- if (arrStacked && othStacked) {
- return arrStacked == other && othStacked == array;
- }
- var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache_default : undefined;
- stack.set(array, other);
- stack.set(other, array);
- while (++index < arrLength) {
- var arrValue = array[index], othValue = other[index];
- if (customizer) {
- var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
- }
- if (compared !== undefined) {
- if (compared) {
- continue;
- }
- result = false;
- break;
- }
- if (seen) {
- if (!_arraySome_default(other, function(othValue2, othIndex) {
- if (!_cacheHas_default(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
- return seen.push(othIndex);
- }
- })) {
- result = false;
- break;
- }
- } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
- result = false;
- break;
- }
- }
- stack["delete"](array);
- stack["delete"](other);
- return result;
-}
-var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2, _equalArrays_default;
-var init__equalArrays = __esm(() => {
- init__SetCache();
- init__arraySome();
- init__cacheHas();
- _equalArrays_default = equalArrays;
-});
-
-// node_modules/lodash-es/_Uint8Array.js
-var Uint8Array2, _Uint8Array_default;
-var init__Uint8Array = __esm(() => {
- init__root();
- Uint8Array2 = _root_default.Uint8Array;
- _Uint8Array_default = Uint8Array2;
-});
-
-// node_modules/lodash-es/_mapToArray.js
-function mapToArray(map) {
- var index = -1, result = Array(map.size);
- map.forEach(function(value, key) {
- result[++index] = [key, value];
- });
- return result;
-}
-var _mapToArray_default;
-var init__mapToArray = __esm(() => {
- _mapToArray_default = mapToArray;
-});
-
-// node_modules/lodash-es/_setToArray.js
-function setToArray(set) {
- var index = -1, result = Array(set.size);
- set.forEach(function(value) {
- result[++index] = value;
- });
- return result;
-}
-var _setToArray_default;
-var init__setToArray = __esm(() => {
- _setToArray_default = setToArray;
-});
-
-// node_modules/lodash-es/_equalByTag.js
-function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
- switch (tag) {
- case dataViewTag:
- if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
- return false;
- }
- object = object.buffer;
- other = other.buffer;
- case arrayBufferTag:
- if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array_default(object), new _Uint8Array_default(other))) {
- return false;
- }
- return true;
- case boolTag:
- case dateTag:
- case numberTag:
- return eq_default(+object, +other);
- case errorTag:
- return object.name == other.name && object.message == other.message;
- case regexpTag:
- case stringTag:
- return object == other + "";
- case mapTag:
- var convert = _mapToArray_default;
- case setTag:
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG2;
- convert || (convert = _setToArray_default);
- if (object.size != other.size && !isPartial) {
- return false;
- }
- var stacked = stack.get(object);
- if (stacked) {
- return stacked == other;
- }
- bitmask |= COMPARE_UNORDERED_FLAG2;
- stack.set(object, other);
- var result = _equalArrays_default(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
- stack["delete"](object);
- return result;
- case symbolTag:
- if (symbolValueOf) {
- return symbolValueOf.call(object) == symbolValueOf.call(other);
- }
- }
- return false;
-}
-var COMPARE_PARTIAL_FLAG2 = 1, COMPARE_UNORDERED_FLAG2 = 2, boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", mapTag = "[object Map]", numberTag = "[object Number]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", symbolProto, symbolValueOf, _equalByTag_default;
-var init__equalByTag = __esm(() => {
- init__Symbol();
- init__Uint8Array();
- init_eq();
- init__equalArrays();
- init__mapToArray();
- init__setToArray();
- symbolProto = _Symbol_default ? _Symbol_default.prototype : undefined;
- symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
- _equalByTag_default = equalByTag;
-});
-
-// node_modules/lodash-es/_arrayPush.js
-function arrayPush(array, values) {
- var index = -1, length = values.length, offset = array.length;
- while (++index < length) {
- array[offset + index] = values[index];
- }
- return array;
-}
-var _arrayPush_default;
-var init__arrayPush = __esm(() => {
- _arrayPush_default = arrayPush;
-});
-
-// node_modules/lodash-es/isArray.js
-var isArray, isArray_default;
-var init_isArray = __esm(() => {
- isArray = Array.isArray;
- isArray_default = isArray;
-});
-
-// node_modules/lodash-es/_baseGetAllKeys.js
-function baseGetAllKeys(object, keysFunc, symbolsFunc) {
- var result = keysFunc(object);
- return isArray_default(object) ? result : _arrayPush_default(result, symbolsFunc(object));
-}
-var _baseGetAllKeys_default;
-var init__baseGetAllKeys = __esm(() => {
- init__arrayPush();
- init_isArray();
- _baseGetAllKeys_default = baseGetAllKeys;
-});
-
-// node_modules/lodash-es/_arrayFilter.js
-function arrayFilter(array, predicate) {
- var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
- while (++index < length) {
- var value = array[index];
- if (predicate(value, index, array)) {
- result[resIndex++] = value;
- }
- }
- return result;
-}
-var _arrayFilter_default;
-var init__arrayFilter = __esm(() => {
- _arrayFilter_default = arrayFilter;
-});
-
-// node_modules/lodash-es/stubArray.js
-function stubArray() {
- return [];
-}
-var stubArray_default;
-var init_stubArray = __esm(() => {
- stubArray_default = stubArray;
-});
-
-// node_modules/lodash-es/_getSymbols.js
-var objectProto6, propertyIsEnumerable, nativeGetSymbols, getSymbols, _getSymbols_default;
-var init__getSymbols = __esm(() => {
- init__arrayFilter();
- init_stubArray();
- objectProto6 = Object.prototype;
- propertyIsEnumerable = objectProto6.propertyIsEnumerable;
- nativeGetSymbols = Object.getOwnPropertySymbols;
- getSymbols = !nativeGetSymbols ? stubArray_default : function(object) {
- if (object == null) {
- return [];
- }
- object = Object(object);
- return _arrayFilter_default(nativeGetSymbols(object), function(symbol) {
- return propertyIsEnumerable.call(object, symbol);
- });
- };
- _getSymbols_default = getSymbols;
-});
-
-// node_modules/lodash-es/_baseTimes.js
-function baseTimes(n, iteratee) {
- var index = -1, result = Array(n);
- while (++index < n) {
- result[index] = iteratee(index);
- }
- return result;
-}
-var _baseTimes_default;
-var init__baseTimes = __esm(() => {
- _baseTimes_default = baseTimes;
-});
-
-// node_modules/lodash-es/isObjectLike.js
-function isObjectLike(value) {
- return value != null && typeof value == "object";
-}
-var isObjectLike_default;
-var init_isObjectLike = __esm(() => {
- isObjectLike_default = isObjectLike;
-});
-
-// node_modules/lodash-es/_baseIsArguments.js
-function baseIsArguments(value) {
- return isObjectLike_default(value) && _baseGetTag_default(value) == argsTag;
-}
-var argsTag = "[object Arguments]", _baseIsArguments_default;
-var init__baseIsArguments = __esm(() => {
- init__baseGetTag();
- init_isObjectLike();
- _baseIsArguments_default = baseIsArguments;
-});
-
-// node_modules/lodash-es/isArguments.js
-var objectProto7, hasOwnProperty5, propertyIsEnumerable2, isArguments, isArguments_default;
-var init_isArguments = __esm(() => {
- init__baseIsArguments();
- init_isObjectLike();
- objectProto7 = Object.prototype;
- hasOwnProperty5 = objectProto7.hasOwnProperty;
- propertyIsEnumerable2 = objectProto7.propertyIsEnumerable;
- isArguments = _baseIsArguments_default(function() {
- return arguments;
- }()) ? _baseIsArguments_default : function(value) {
- return isObjectLike_default(value) && hasOwnProperty5.call(value, "callee") && !propertyIsEnumerable2.call(value, "callee");
- };
- isArguments_default = isArguments;
-});
-
-// node_modules/lodash-es/stubFalse.js
-function stubFalse() {
- return false;
-}
-var stubFalse_default;
-var init_stubFalse = __esm(() => {
- stubFalse_default = stubFalse;
-});
-
-// node_modules/lodash-es/isBuffer.js
-var exports_isBuffer = {};
-__export(exports_isBuffer, {
- default: () => isBuffer_default
-});
-var freeExports, freeModule, moduleExports, Buffer2, nativeIsBuffer, isBuffer, isBuffer_default;
-var init_isBuffer = __esm(() => {
- init__root();
- init_stubFalse();
- freeExports = typeof exports_isBuffer == "object" && exports_isBuffer && !exports_isBuffer.nodeType && exports_isBuffer;
- freeModule = freeExports && typeof module_isBuffer == "object" && module_isBuffer && !module_isBuffer.nodeType && module_isBuffer;
- moduleExports = freeModule && freeModule.exports === freeExports;
- Buffer2 = moduleExports ? _root_default.Buffer : undefined;
- nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : undefined;
- isBuffer = nativeIsBuffer || stubFalse_default;
- isBuffer_default = isBuffer;
-});
-
-// node_modules/lodash-es/_isIndex.js
-function isIndex(value, length) {
- var type = typeof value;
- length = length == null ? MAX_SAFE_INTEGER : length;
- return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
-}
-var MAX_SAFE_INTEGER = 9007199254740991, reIsUint, _isIndex_default;
-var init__isIndex = __esm(() => {
- reIsUint = /^(?:0|[1-9]\d*)$/;
- _isIndex_default = isIndex;
-});
-
-// node_modules/lodash-es/isLength.js
-function isLength(value) {
- return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
-}
-var MAX_SAFE_INTEGER2 = 9007199254740991, isLength_default;
-var init_isLength = __esm(() => {
- isLength_default = isLength;
-});
-
-// node_modules/lodash-es/_baseIsTypedArray.js
-function baseIsTypedArray(value) {
- return isObjectLike_default(value) && isLength_default(value.length) && !!typedArrayTags[_baseGetTag_default(value)];
-}
-var argsTag2 = "[object Arguments]", arrayTag = "[object Array]", boolTag2 = "[object Boolean]", dateTag2 = "[object Date]", errorTag2 = "[object Error]", funcTag2 = "[object Function]", mapTag2 = "[object Map]", numberTag2 = "[object Number]", objectTag = "[object Object]", regexpTag2 = "[object RegExp]", setTag2 = "[object Set]", stringTag2 = "[object String]", weakMapTag = "[object WeakMap]", arrayBufferTag2 = "[object ArrayBuffer]", dataViewTag2 = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]", typedArrayTags, _baseIsTypedArray_default;
-var init__baseIsTypedArray = __esm(() => {
- init__baseGetTag();
- init_isLength();
- init_isObjectLike();
- typedArrayTags = {};
- typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
- typedArrayTags[argsTag2] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag2] = typedArrayTags[boolTag2] = typedArrayTags[dataViewTag2] = typedArrayTags[dateTag2] = typedArrayTags[errorTag2] = typedArrayTags[funcTag2] = typedArrayTags[mapTag2] = typedArrayTags[numberTag2] = typedArrayTags[objectTag] = typedArrayTags[regexpTag2] = typedArrayTags[setTag2] = typedArrayTags[stringTag2] = typedArrayTags[weakMapTag] = false;
- _baseIsTypedArray_default = baseIsTypedArray;
-});
-
-// node_modules/lodash-es/_baseUnary.js
-function baseUnary(func) {
- return function(value) {
- return func(value);
- };
-}
-var _baseUnary_default;
-var init__baseUnary = __esm(() => {
- _baseUnary_default = baseUnary;
-});
-
-// node_modules/lodash-es/_nodeUtil.js
-var exports__nodeUtil = {};
-__export(exports__nodeUtil, {
- default: () => _nodeUtil_default
-});
-var freeExports2, freeModule2, moduleExports2, freeProcess, nodeUtil, _nodeUtil_default;
-var init__nodeUtil = __esm(() => {
- init__freeGlobal();
- freeExports2 = typeof exports__nodeUtil == "object" && exports__nodeUtil && !exports__nodeUtil.nodeType && exports__nodeUtil;
- freeModule2 = freeExports2 && typeof module__nodeUtil == "object" && module__nodeUtil && !module__nodeUtil.nodeType && module__nodeUtil;
- moduleExports2 = freeModule2 && freeModule2.exports === freeExports2;
- freeProcess = moduleExports2 && _freeGlobal_default.process;
- nodeUtil = function() {
- try {
- var types = freeModule2 && freeModule2.require && freeModule2.require("util").types;
- if (types) {
- return types;
- }
- return freeProcess && freeProcess.binding && freeProcess.binding("util");
- } catch (e) {}
- }();
- _nodeUtil_default = nodeUtil;
-});
-
-// node_modules/lodash-es/isTypedArray.js
-var nodeIsTypedArray, isTypedArray, isTypedArray_default;
-var init_isTypedArray = __esm(() => {
- init__baseIsTypedArray();
- init__baseUnary();
- init__nodeUtil();
- nodeIsTypedArray = _nodeUtil_default && _nodeUtil_default.isTypedArray;
- isTypedArray = nodeIsTypedArray ? _baseUnary_default(nodeIsTypedArray) : _baseIsTypedArray_default;
- isTypedArray_default = isTypedArray;
-});
-
-// node_modules/lodash-es/_arrayLikeKeys.js
-function arrayLikeKeys(value, inherited) {
- var isArr = isArray_default(value), isArg = !isArr && isArguments_default(value), isBuff = !isArr && !isArg && isBuffer_default(value), isType = !isArr && !isArg && !isBuff && isTypedArray_default(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes_default(value.length, String) : [], length = result.length;
- for (var key in value) {
- if ((inherited || hasOwnProperty6.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || _isIndex_default(key, length)))) {
- result.push(key);
- }
- }
- return result;
-}
-var objectProto8, hasOwnProperty6, _arrayLikeKeys_default;
-var init__arrayLikeKeys = __esm(() => {
- init__baseTimes();
- init_isArguments();
- init_isArray();
- init_isBuffer();
- init__isIndex();
- init_isTypedArray();
- objectProto8 = Object.prototype;
- hasOwnProperty6 = objectProto8.hasOwnProperty;
- _arrayLikeKeys_default = arrayLikeKeys;
-});
-
-// node_modules/lodash-es/_isPrototype.js
-function isPrototype(value) {
- var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto9;
- return value === proto;
-}
-var objectProto9, _isPrototype_default;
-var init__isPrototype = __esm(() => {
- objectProto9 = Object.prototype;
- _isPrototype_default = isPrototype;
-});
-
-// node_modules/lodash-es/_overArg.js
-function overArg(func, transform) {
- return function(arg) {
- return func(transform(arg));
- };
-}
-var _overArg_default;
-var init__overArg = __esm(() => {
- _overArg_default = overArg;
-});
-
-// node_modules/lodash-es/_nativeKeys.js
-var nativeKeys, _nativeKeys_default;
-var init__nativeKeys = __esm(() => {
- init__overArg();
- nativeKeys = _overArg_default(Object.keys, Object);
- _nativeKeys_default = nativeKeys;
-});
-
-// node_modules/lodash-es/_baseKeys.js
-function baseKeys(object) {
- if (!_isPrototype_default(object)) {
- return _nativeKeys_default(object);
- }
- var result = [];
- for (var key in Object(object)) {
- if (hasOwnProperty7.call(object, key) && key != "constructor") {
- result.push(key);
- }
- }
- return result;
-}
-var objectProto10, hasOwnProperty7, _baseKeys_default;
-var init__baseKeys = __esm(() => {
- init__isPrototype();
- init__nativeKeys();
- objectProto10 = Object.prototype;
- hasOwnProperty7 = objectProto10.hasOwnProperty;
- _baseKeys_default = baseKeys;
-});
-
-// node_modules/lodash-es/isArrayLike.js
-function isArrayLike(value) {
- return value != null && isLength_default(value.length) && !isFunction_default(value);
-}
-var isArrayLike_default;
-var init_isArrayLike = __esm(() => {
- init_isFunction();
- init_isLength();
- isArrayLike_default = isArrayLike;
-});
-
-// node_modules/lodash-es/keys.js
-function keys(object) {
- return isArrayLike_default(object) ? _arrayLikeKeys_default(object) : _baseKeys_default(object);
-}
-var keys_default;
-var init_keys = __esm(() => {
- init__arrayLikeKeys();
- init__baseKeys();
- init_isArrayLike();
- keys_default = keys;
-});
-
-// node_modules/lodash-es/_getAllKeys.js
-function getAllKeys(object) {
- return _baseGetAllKeys_default(object, keys_default, _getSymbols_default);
-}
-var _getAllKeys_default;
-var init__getAllKeys = __esm(() => {
- init__baseGetAllKeys();
- init__getSymbols();
- init_keys();
- _getAllKeys_default = getAllKeys;
-});
-
-// node_modules/lodash-es/_equalObjects.js
-function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG3, objProps = _getAllKeys_default(object), objLength = objProps.length, othProps = _getAllKeys_default(other), othLength = othProps.length;
- if (objLength != othLength && !isPartial) {
- return false;
- }
- var index = objLength;
- while (index--) {
- var key = objProps[index];
- if (!(isPartial ? key in other : hasOwnProperty8.call(other, key))) {
- return false;
- }
- }
- var objStacked = stack.get(object);
- var othStacked = stack.get(other);
- if (objStacked && othStacked) {
- return objStacked == other && othStacked == object;
- }
- var result = true;
- stack.set(object, other);
- stack.set(other, object);
- var skipCtor = isPartial;
- while (++index < objLength) {
- key = objProps[index];
- var objValue = object[key], othValue = other[key];
- if (customizer) {
- var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
- }
- if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
- result = false;
- break;
- }
- skipCtor || (skipCtor = key == "constructor");
- }
- if (result && !skipCtor) {
- var objCtor = object.constructor, othCtor = other.constructor;
- if (objCtor != othCtor && (("constructor" in object) && ("constructor" in other)) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
- result = false;
- }
- }
- stack["delete"](object);
- stack["delete"](other);
- return result;
-}
-var COMPARE_PARTIAL_FLAG3 = 1, objectProto11, hasOwnProperty8, _equalObjects_default;
-var init__equalObjects = __esm(() => {
- init__getAllKeys();
- objectProto11 = Object.prototype;
- hasOwnProperty8 = objectProto11.hasOwnProperty;
- _equalObjects_default = equalObjects;
-});
-
-// node_modules/lodash-es/_DataView.js
-var DataView2, _DataView_default;
-var init__DataView = __esm(() => {
- init__getNative();
- init__root();
- DataView2 = _getNative_default(_root_default, "DataView");
- _DataView_default = DataView2;
-});
-
-// node_modules/lodash-es/_Promise.js
-var Promise2, _Promise_default;
-var init__Promise = __esm(() => {
- init__getNative();
- init__root();
- Promise2 = _getNative_default(_root_default, "Promise");
- _Promise_default = Promise2;
-});
-
-// node_modules/lodash-es/_Set.js
-var Set2, _Set_default;
-var init__Set = __esm(() => {
- init__getNative();
- init__root();
- Set2 = _getNative_default(_root_default, "Set");
- _Set_default = Set2;
-});
-
-// node_modules/lodash-es/_WeakMap.js
-var WeakMap2, _WeakMap_default;
-var init__WeakMap = __esm(() => {
- init__getNative();
- init__root();
- WeakMap2 = _getNative_default(_root_default, "WeakMap");
- _WeakMap_default = WeakMap2;
-});
-
-// node_modules/lodash-es/_getTag.js
-var mapTag3 = "[object Map]", objectTag2 = "[object Object]", promiseTag = "[object Promise]", setTag3 = "[object Set]", weakMapTag2 = "[object WeakMap]", dataViewTag3 = "[object DataView]", dataViewCtorString, mapCtorString, promiseCtorString, setCtorString, weakMapCtorString, getTag, _getTag_default;
-var init__getTag = __esm(() => {
- init__DataView();
- init__Map();
- init__Promise();
- init__Set();
- init__WeakMap();
- init__baseGetTag();
- init__toSource();
- dataViewCtorString = _toSource_default(_DataView_default);
- mapCtorString = _toSource_default(_Map_default);
- promiseCtorString = _toSource_default(_Promise_default);
- setCtorString = _toSource_default(_Set_default);
- weakMapCtorString = _toSource_default(_WeakMap_default);
- getTag = _baseGetTag_default;
- if (_DataView_default && getTag(new _DataView_default(new ArrayBuffer(1))) != dataViewTag3 || _Map_default && getTag(new _Map_default) != mapTag3 || _Promise_default && getTag(_Promise_default.resolve()) != promiseTag || _Set_default && getTag(new _Set_default) != setTag3 || _WeakMap_default && getTag(new _WeakMap_default) != weakMapTag2) {
- getTag = function(value) {
- var result = _baseGetTag_default(value), Ctor = result == objectTag2 ? value.constructor : undefined, ctorString = Ctor ? _toSource_default(Ctor) : "";
- if (ctorString) {
- switch (ctorString) {
- case dataViewCtorString:
- return dataViewTag3;
- case mapCtorString:
- return mapTag3;
- case promiseCtorString:
- return promiseTag;
- case setCtorString:
- return setTag3;
- case weakMapCtorString:
- return weakMapTag2;
- }
- }
- return result;
- };
- }
- _getTag_default = getTag;
-});
-
-// node_modules/lodash-es/_baseIsEqualDeep.js
-function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
- var objIsArr = isArray_default(object), othIsArr = isArray_default(other), objTag = objIsArr ? arrayTag2 : _getTag_default(object), othTag = othIsArr ? arrayTag2 : _getTag_default(other);
- objTag = objTag == argsTag3 ? objectTag3 : objTag;
- othTag = othTag == argsTag3 ? objectTag3 : othTag;
- var objIsObj = objTag == objectTag3, othIsObj = othTag == objectTag3, isSameTag = objTag == othTag;
- if (isSameTag && isBuffer_default(object)) {
- if (!isBuffer_default(other)) {
- return false;
- }
- objIsArr = true;
- objIsObj = false;
- }
- if (isSameTag && !objIsObj) {
- stack || (stack = new _Stack_default);
- return objIsArr || isTypedArray_default(object) ? _equalArrays_default(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag_default(object, other, objTag, bitmask, customizer, equalFunc, stack);
- }
- if (!(bitmask & COMPARE_PARTIAL_FLAG4)) {
- var objIsWrapped = objIsObj && hasOwnProperty9.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty9.call(other, "__wrapped__");
- if (objIsWrapped || othIsWrapped) {
- var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
- stack || (stack = new _Stack_default);
- return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
- }
- }
- if (!isSameTag) {
- return false;
- }
- stack || (stack = new _Stack_default);
- return _equalObjects_default(object, other, bitmask, customizer, equalFunc, stack);
-}
-var COMPARE_PARTIAL_FLAG4 = 1, argsTag3 = "[object Arguments]", arrayTag2 = "[object Array]", objectTag3 = "[object Object]", objectProto12, hasOwnProperty9, _baseIsEqualDeep_default;
-var init__baseIsEqualDeep = __esm(() => {
- init__Stack();
- init__equalArrays();
- init__equalByTag();
- init__equalObjects();
- init__getTag();
- init_isArray();
- init_isBuffer();
- init_isTypedArray();
- objectProto12 = Object.prototype;
- hasOwnProperty9 = objectProto12.hasOwnProperty;
- _baseIsEqualDeep_default = baseIsEqualDeep;
-});
-
-// node_modules/lodash-es/_baseIsEqual.js
-function baseIsEqual(value, other, bitmask, customizer, stack) {
- if (value === other) {
- return true;
- }
- if (value == null || other == null || !isObjectLike_default(value) && !isObjectLike_default(other)) {
- return value !== value && other !== other;
- }
- return _baseIsEqualDeep_default(value, other, bitmask, customizer, baseIsEqual, stack);
-}
-var _baseIsEqual_default;
-var init__baseIsEqual = __esm(() => {
- init__baseIsEqualDeep();
- init_isObjectLike();
- _baseIsEqual_default = baseIsEqual;
-});
-
-// node_modules/lodash-es/_baseIsMatch.js
-function baseIsMatch(object, source, matchData, customizer) {
- var index = matchData.length, length = index, noCustomizer = !customizer;
- if (object == null) {
- return !length;
- }
- object = Object(object);
- while (index--) {
- var data = matchData[index];
- if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
- return false;
- }
- }
- while (++index < length) {
- data = matchData[index];
- var key = data[0], objValue = object[key], srcValue = data[1];
- if (noCustomizer && data[2]) {
- if (objValue === undefined && !(key in object)) {
- return false;
- }
- } else {
- var stack = new _Stack_default;
- if (customizer) {
- var result = customizer(objValue, srcValue, key, object, source, stack);
- }
- if (!(result === undefined ? _baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG5 | COMPARE_UNORDERED_FLAG3, customizer, stack) : result)) {
- return false;
- }
- }
- }
- return true;
-}
-var COMPARE_PARTIAL_FLAG5 = 1, COMPARE_UNORDERED_FLAG3 = 2, _baseIsMatch_default;
-var init__baseIsMatch = __esm(() => {
- init__Stack();
- init__baseIsEqual();
- _baseIsMatch_default = baseIsMatch;
-});
-
-// node_modules/lodash-es/_isStrictComparable.js
-function isStrictComparable(value) {
- return value === value && !isObject_default(value);
-}
-var _isStrictComparable_default;
-var init__isStrictComparable = __esm(() => {
- init_isObject();
- _isStrictComparable_default = isStrictComparable;
-});
-
-// node_modules/lodash-es/_getMatchData.js
-function getMatchData(object) {
- var result = keys_default(object), length = result.length;
- while (length--) {
- var key = result[length], value = object[key];
- result[length] = [key, value, _isStrictComparable_default(value)];
- }
- return result;
-}
-var _getMatchData_default;
-var init__getMatchData = __esm(() => {
- init__isStrictComparable();
- init_keys();
- _getMatchData_default = getMatchData;
-});
-
-// node_modules/lodash-es/_matchesStrictComparable.js
-function matchesStrictComparable(key, srcValue) {
- return function(object) {
- if (object == null) {
- return false;
- }
- return object[key] === srcValue && (srcValue !== undefined || (key in Object(object)));
- };
-}
-var _matchesStrictComparable_default;
-var init__matchesStrictComparable = __esm(() => {
- _matchesStrictComparable_default = matchesStrictComparable;
-});
-
-// node_modules/lodash-es/_baseMatches.js
-function baseMatches(source) {
- var matchData = _getMatchData_default(source);
- if (matchData.length == 1 && matchData[0][2]) {
- return _matchesStrictComparable_default(matchData[0][0], matchData[0][1]);
- }
- return function(object) {
- return object === source || _baseIsMatch_default(object, source, matchData);
- };
-}
-var _baseMatches_default;
-var init__baseMatches = __esm(() => {
- init__baseIsMatch();
- init__getMatchData();
- init__matchesStrictComparable();
- _baseMatches_default = baseMatches;
-});
-
-// node_modules/lodash-es/isSymbol.js
-function isSymbol(value) {
- return typeof value == "symbol" || isObjectLike_default(value) && _baseGetTag_default(value) == symbolTag2;
-}
-var symbolTag2 = "[object Symbol]", isSymbol_default;
-var init_isSymbol = __esm(() => {
- init__baseGetTag();
- init_isObjectLike();
- isSymbol_default = isSymbol;
-});
-
-// node_modules/lodash-es/_isKey.js
-function isKey(value, object) {
- if (isArray_default(value)) {
- return false;
- }
- var type = typeof value;
- if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol_default(value)) {
- return true;
- }
- return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
-}
-var reIsDeepProp, reIsPlainProp, _isKey_default;
-var init__isKey = __esm(() => {
- init_isArray();
- init_isSymbol();
- reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
- reIsPlainProp = /^\w*$/;
- _isKey_default = isKey;
-});
-
-// node_modules/lodash-es/memoize.js
-function memoize(func, resolver) {
- if (typeof func != "function" || resolver != null && typeof resolver != "function") {
- throw new TypeError(FUNC_ERROR_TEXT);
- }
- var memoized = function() {
- var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
- if (cache.has(key)) {
- return cache.get(key);
- }
- var result = func.apply(this, args);
- memoized.cache = cache.set(key, result) || cache;
- return result;
- };
- memoized.cache = new (memoize.Cache || _MapCache_default);
- return memoized;
-}
-var FUNC_ERROR_TEXT = "Expected a function", memoize_default;
-var init_memoize = __esm(() => {
- init__MapCache();
- memoize.Cache = _MapCache_default;
- memoize_default = memoize;
-});
-
-// node_modules/lodash-es/_memoizeCapped.js
-function memoizeCapped(func) {
- var result = memoize_default(func, function(key) {
- if (cache.size === MAX_MEMOIZE_SIZE) {
- cache.clear();
- }
- return key;
- });
- var cache = result.cache;
- return result;
-}
-var MAX_MEMOIZE_SIZE = 500, _memoizeCapped_default;
-var init__memoizeCapped = __esm(() => {
- init_memoize();
- _memoizeCapped_default = memoizeCapped;
-});
-
-// node_modules/lodash-es/_stringToPath.js
-var rePropName, reEscapeChar, stringToPath, _stringToPath_default;
-var init__stringToPath = __esm(() => {
- init__memoizeCapped();
- rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
- reEscapeChar = /\\(\\)?/g;
- stringToPath = _memoizeCapped_default(function(string) {
- var result = [];
- if (string.charCodeAt(0) === 46) {
- result.push("");
- }
- string.replace(rePropName, function(match, number, quote, subString) {
- result.push(quote ? subString.replace(reEscapeChar, "$1") : number || match);
- });
- return result;
- });
- _stringToPath_default = stringToPath;
-});
-
-// node_modules/lodash-es/_arrayMap.js
-function arrayMap(array, iteratee) {
- var index = -1, length = array == null ? 0 : array.length, result = Array(length);
- while (++index < length) {
- result[index] = iteratee(array[index], index, array);
- }
- return result;
-}
-var _arrayMap_default;
-var init__arrayMap = __esm(() => {
- _arrayMap_default = arrayMap;
-});
-
-// node_modules/lodash-es/_baseToString.js
-function baseToString(value) {
- if (typeof value == "string") {
- return value;
- }
- if (isArray_default(value)) {
- return _arrayMap_default(value, baseToString) + "";
- }
- if (isSymbol_default(value)) {
- return symbolToString ? symbolToString.call(value) : "";
- }
- var result = value + "";
- return result == "0" && 1 / value == -INFINITY ? "-0" : result;
-}
-var INFINITY, symbolProto2, symbolToString, _baseToString_default;
-var init__baseToString = __esm(() => {
- init__Symbol();
- init__arrayMap();
- init_isArray();
- init_isSymbol();
- INFINITY = 1 / 0;
- symbolProto2 = _Symbol_default ? _Symbol_default.prototype : undefined;
- symbolToString = symbolProto2 ? symbolProto2.toString : undefined;
- _baseToString_default = baseToString;
-});
-
-// node_modules/lodash-es/toString.js
-function toString(value) {
- return value == null ? "" : _baseToString_default(value);
-}
-var toString_default;
-var init_toString = __esm(() => {
- init__baseToString();
- toString_default = toString;
-});
-
-// node_modules/lodash-es/_castPath.js
-function castPath(value, object) {
- if (isArray_default(value)) {
- return value;
- }
- return _isKey_default(value, object) ? [value] : _stringToPath_default(toString_default(value));
-}
-var _castPath_default;
-var init__castPath = __esm(() => {
- init_isArray();
- init__isKey();
- init__stringToPath();
- init_toString();
- _castPath_default = castPath;
-});
-
-// node_modules/lodash-es/_toKey.js
-function toKey(value) {
- if (typeof value == "string" || isSymbol_default(value)) {
- return value;
- }
- var result = value + "";
- return result == "0" && 1 / value == -INFINITY2 ? "-0" : result;
-}
-var INFINITY2, _toKey_default;
-var init__toKey = __esm(() => {
- init_isSymbol();
- INFINITY2 = 1 / 0;
- _toKey_default = toKey;
-});
-
-// node_modules/lodash-es/_baseGet.js
-function baseGet(object, path) {
- path = _castPath_default(path, object);
- var index = 0, length = path.length;
- while (object != null && index < length) {
- object = object[_toKey_default(path[index++])];
- }
- return index && index == length ? object : undefined;
-}
-var _baseGet_default;
-var init__baseGet = __esm(() => {
- init__castPath();
- init__toKey();
- _baseGet_default = baseGet;
-});
-
-// node_modules/lodash-es/get.js
-function get(object, path, defaultValue) {
- var result = object == null ? undefined : _baseGet_default(object, path);
- return result === undefined ? defaultValue : result;
-}
-var get_default;
-var init_get = __esm(() => {
- init__baseGet();
- get_default = get;
-});
-
-// node_modules/lodash-es/_baseHasIn.js
-function baseHasIn(object, key) {
- return object != null && key in Object(object);
-}
-var _baseHasIn_default;
-var init__baseHasIn = __esm(() => {
- _baseHasIn_default = baseHasIn;
-});
-
-// node_modules/lodash-es/_hasPath.js
-function hasPath(object, path, hasFunc) {
- path = _castPath_default(path, object);
- var index = -1, length = path.length, result = false;
- while (++index < length) {
- var key = _toKey_default(path[index]);
- if (!(result = object != null && hasFunc(object, key))) {
- break;
- }
- object = object[key];
- }
- if (result || ++index != length) {
- return result;
- }
- length = object == null ? 0 : object.length;
- return !!length && isLength_default(length) && _isIndex_default(key, length) && (isArray_default(object) || isArguments_default(object));
-}
-var _hasPath_default;
-var init__hasPath = __esm(() => {
- init__castPath();
- init_isArguments();
- init_isArray();
- init__isIndex();
- init_isLength();
- init__toKey();
- _hasPath_default = hasPath;
-});
-
-// node_modules/lodash-es/hasIn.js
-function hasIn(object, path) {
- return object != null && _hasPath_default(object, path, _baseHasIn_default);
-}
-var hasIn_default;
-var init_hasIn = __esm(() => {
- init__baseHasIn();
- init__hasPath();
- hasIn_default = hasIn;
-});
-
-// node_modules/lodash-es/_baseMatchesProperty.js
-function baseMatchesProperty(path, srcValue) {
- if (_isKey_default(path) && _isStrictComparable_default(srcValue)) {
- return _matchesStrictComparable_default(_toKey_default(path), srcValue);
- }
- return function(object) {
- var objValue = get_default(object, path);
- return objValue === undefined && objValue === srcValue ? hasIn_default(object, path) : _baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG6 | COMPARE_UNORDERED_FLAG4);
- };
-}
-var COMPARE_PARTIAL_FLAG6 = 1, COMPARE_UNORDERED_FLAG4 = 2, _baseMatchesProperty_default;
-var init__baseMatchesProperty = __esm(() => {
- init__baseIsEqual();
- init_get();
- init_hasIn();
- init__isKey();
- init__isStrictComparable();
- init__matchesStrictComparable();
- init__toKey();
- _baseMatchesProperty_default = baseMatchesProperty;
-});
-
-// node_modules/lodash-es/identity.js
-function identity(value) {
- return value;
-}
-var identity_default;
-var init_identity = __esm(() => {
- identity_default = identity;
-});
-
-// node_modules/lodash-es/_baseProperty.js
-function baseProperty(key) {
- return function(object) {
- return object == null ? undefined : object[key];
- };
-}
-var _baseProperty_default;
-var init__baseProperty = __esm(() => {
- _baseProperty_default = baseProperty;
-});
-
-// node_modules/lodash-es/_basePropertyDeep.js
-function basePropertyDeep(path) {
- return function(object) {
- return _baseGet_default(object, path);
- };
-}
-var _basePropertyDeep_default;
-var init__basePropertyDeep = __esm(() => {
- init__baseGet();
- _basePropertyDeep_default = basePropertyDeep;
-});
-
-// node_modules/lodash-es/property.js
-function property(path) {
- return _isKey_default(path) ? _baseProperty_default(_toKey_default(path)) : _basePropertyDeep_default(path);
-}
-var property_default;
-var init_property = __esm(() => {
- init__baseProperty();
- init__basePropertyDeep();
- init__isKey();
- init__toKey();
- property_default = property;
-});
-
-// node_modules/lodash-es/_baseIteratee.js
-function baseIteratee(value) {
- if (typeof value == "function") {
- return value;
- }
- if (value == null) {
- return identity_default;
- }
- if (typeof value == "object") {
- return isArray_default(value) ? _baseMatchesProperty_default(value[0], value[1]) : _baseMatches_default(value);
- }
- return property_default(value);
-}
-var _baseIteratee_default;
-var init__baseIteratee = __esm(() => {
- init__baseMatches();
- init__baseMatchesProperty();
- init_identity();
- init_isArray();
- init_property();
- _baseIteratee_default = baseIteratee;
-});
-
-// node_modules/lodash-es/_baseSum.js
-function baseSum(array, iteratee) {
- var result, index = -1, length = array.length;
- while (++index < length) {
- var current = iteratee(array[index]);
- if (current !== undefined) {
- result = result === undefined ? current : result + current;
- }
- }
- return result;
-}
-var _baseSum_default;
-var init__baseSum = __esm(() => {
- _baseSum_default = baseSum;
-});
-
-// node_modules/lodash-es/sumBy.js
-function sumBy(array, iteratee) {
- return array && array.length ? _baseSum_default(array, _baseIteratee_default(iteratee, 2)) : 0;
-}
-var sumBy_default;
-var init_sumBy = __esm(() => {
- init__baseIteratee();
- init__baseSum();
- sumBy_default = sumBy;
-});
-
-// src/utils/crypto.ts
-import { randomUUID } from "crypto";
-var init_crypto = () => {};
-
-// src/utils/settings/settingsCache.ts
-function getSessionSettingsCache() {
- return sessionSettingsCache;
-}
-function setSessionSettingsCache(value) {
- sessionSettingsCache = value;
-}
-function getCachedSettingsForSource(source) {
- return perSourceCache.has(source) ? perSourceCache.get(source) : undefined;
-}
-function setCachedSettingsForSource(source, value) {
- perSourceCache.set(source, value);
-}
-function getCachedParsedFile(path) {
- return parseFileCache.get(path);
-}
-function setCachedParsedFile(path, value) {
- parseFileCache.set(path, value);
-}
-function resetSettingsCache() {
- sessionSettingsCache = null;
- perSourceCache.clear();
- parseFileCache.clear();
-}
-function getPluginSettingsBase() {
- return pluginSettingsBase;
-}
-function setPluginSettingsBase(settings) {
- pluginSettingsBase = settings;
-}
-function clearPluginSettingsBase() {
- pluginSettingsBase = undefined;
-}
-var sessionSettingsCache = null, perSourceCache, parseFileCache, pluginSettingsBase;
-var init_settingsCache = __esm(() => {
- perSourceCache = new Map;
- parseFileCache = new Map;
-});
-
-// src/utils/signal.ts
-function createSignal() {
- const listeners = new Set;
- return {
- subscribe(listener) {
- listeners.add(listener);
- return () => {
- listeners.delete(listener);
- };
- },
- emit(...args) {
- for (const listener of listeners)
- listener(...args);
- },
- clear() {
- listeners.clear();
- }
- };
-}
-
-// src/bootstrap/state.ts
-var exports_state = {};
-__export(exports_state, {
- waitForScrollIdle: () => waitForScrollIdle,
- updateLastInteractionTime: () => updateLastInteractionTime,
- switchSession: () => switchSession,
- snapshotOutputTokensForTurn: () => snapshotOutputTokensForTurn,
- setUserMsgOptIn: () => setUserMsgOptIn,
- setUseCoworkPlugins: () => setUseCoworkPlugins,
- setTracerProvider: () => setTracerProvider,
- setThinkingClearLatched: () => setThinkingClearLatched,
- setTeleportedSessionInfo: () => setTeleportedSessionInfo,
- setSystemPromptSectionCacheEntry: () => setSystemPromptSectionCacheEntry,
- setStrictToolResultPairing: () => setStrictToolResultPairing,
- setStatsStore: () => setStatsStore,
- setSessionTrustAccepted: () => setSessionTrustAccepted,
- setSessionSource: () => setSessionSource,
- setSessionPersistenceDisabled: () => setSessionPersistenceDisabled,
- setSessionIngressToken: () => setSessionIngressToken,
- setSessionBypassPermissionsMode: () => setSessionBypassPermissionsMode,
- setSdkBetas: () => setSdkBetas,
- setSdkAgentProgressSummariesEnabled: () => setSdkAgentProgressSummariesEnabled,
- setScheduledTasksEnabled: () => setScheduledTasksEnabled,
- setQuestionPreviewFormat: () => setQuestionPreviewFormat,
- setPromptId: () => setPromptId,
- setPromptCache1hEligible: () => setPromptCache1hEligible,
- setPromptCache1hAllowlist: () => setPromptCache1hAllowlist,
- setProjectRoot: () => setProjectRoot,
- setOriginalCwd: () => setOriginalCwd,
- setOauthTokenFromFd: () => setOauthTokenFromFd,
- setNeedsPlanModeExitAttachment: () => setNeedsPlanModeExitAttachment,
- setNeedsAutoModeExitAttachment: () => setNeedsAutoModeExitAttachment,
- setModelStrings: () => setModelStrings,
- setMeterProvider: () => setMeterProvider,
- setMeter: () => setMeter,
- setMainThreadAgentType: () => setMainThreadAgentType,
- setMainLoopModelOverride: () => setMainLoopModelOverride,
- setLspRecommendationShownThisSession: () => setLspRecommendationShownThisSession,
- setLoggerProvider: () => setLoggerProvider,
- setLastMainRequestId: () => setLastMainRequestId,
- setLastEmittedDate: () => setLastEmittedDate,
- setLastClassifierRequests: () => setLastClassifierRequests,
- setLastApiCompletionTimestamp: () => setLastApiCompletionTimestamp,
- setLastAPIRequestMessages: () => setLastAPIRequestMessages,
- setLastAPIRequest: () => setLastAPIRequest,
- setKairosActive: () => setKairosActive,
- setIsRemoteMode: () => setIsRemoteMode,
- setIsInteractive: () => setIsInteractive,
- setInlinePlugins: () => setInlinePlugins,
- setInitialMainLoopModel: () => setInitialMainLoopModel,
- setInitJsonSchema: () => setInitJsonSchema,
- setHasUnknownModelCost: () => setHasUnknownModelCost,
- setHasExitedPlanMode: () => setHasExitedPlanMode,
- setHasDevChannels: () => setHasDevChannels,
- setFlagSettingsPath: () => setFlagSettingsPath,
- setFlagSettingsInline: () => setFlagSettingsInline,
- setFastModeHeaderLatched: () => setFastModeHeaderLatched,
- setEventLogger: () => setEventLogger,
- setDirectConnectServerUrl: () => setDirectConnectServerUrl,
- setCwdState: () => setCwdState,
- setCostStateForRestore: () => setCostStateForRestore,
- setClientType: () => setClientType,
- setChromeFlagOverride: () => setChromeFlagOverride,
- setCachedClaudeMdContent: () => setCachedClaudeMdContent,
- setCacheEditingHeaderLatched: () => setCacheEditingHeaderLatched,
- setApiKeyFromFd: () => setApiKeyFromFd,
- setAllowedSettingSources: () => setAllowedSettingSources,
- setAllowedChannels: () => setAllowedChannels,
- setAfkModeHeaderLatched: () => setAfkModeHeaderLatched,
- setAdditionalDirectoriesForClaudeMd: () => setAdditionalDirectoriesForClaudeMd,
- resetTurnToolDuration: () => resetTurnToolDuration,
- resetTurnHookDuration: () => resetTurnHookDuration,
- resetTurnClassifierDuration: () => resetTurnClassifierDuration,
- resetTotalDurationStateAndCost_FOR_TESTS_ONLY: () => resetTotalDurationStateAndCost_FOR_TESTS_ONLY,
- resetStateForTests: () => resetStateForTests,
- resetSdkInitState: () => resetSdkInitState,
- resetModelStringsForTestingOnly: () => resetModelStringsForTestingOnly,
- resetCostState: () => resetCostState,
- removeSessionCronTasks: () => removeSessionCronTasks,
- registerHookCallbacks: () => registerHookCallbacks,
- regenerateSessionId: () => regenerateSessionId,
- preferThirdPartyAuthentication: () => preferThirdPartyAuthentication,
- onSessionSwitch: () => onSessionSwitch,
- needsPlanModeExitAttachment: () => needsPlanModeExitAttachment,
- needsAutoModeExitAttachment: () => needsAutoModeExitAttachment,
- markScrollActivity: () => markScrollActivity,
- markPostCompaction: () => markPostCompaction,
- markFirstTeleportMessageLogged: () => markFirstTeleportMessageLogged,
- isSessionPersistenceDisabled: () => isSessionPersistenceDisabled,
- incrementBudgetContinuationCount: () => incrementBudgetContinuationCount,
- hasUnknownModelCost: () => hasUnknownModelCost,
- hasShownLspRecommendationThisSession: () => hasShownLspRecommendationThisSession,
- hasExitedPlanModeInSession: () => hasExitedPlanModeInSession,
- handlePlanModeTransition: () => handlePlanModeTransition,
- handleAutoModeTransition: () => handleAutoModeTransition,
- getUserMsgOptIn: () => getUserMsgOptIn,
- getUseCoworkPlugins: () => getUseCoworkPlugins,
- getUsageForModel: () => getUsageForModel,
- getTurnToolDurationMs: () => getTurnToolDurationMs,
- getTurnToolCount: () => getTurnToolCount,
- getTurnOutputTokens: () => getTurnOutputTokens,
- getTurnHookDurationMs: () => getTurnHookDurationMs,
- getTurnHookCount: () => getTurnHookCount,
- getTurnClassifierDurationMs: () => getTurnClassifierDurationMs,
- getTurnClassifierCount: () => getTurnClassifierCount,
- getTracerProvider: () => getTracerProvider,
- getTotalWebSearchRequests: () => getTotalWebSearchRequests,
- getTotalToolDuration: () => getTotalToolDuration,
- getTotalOutputTokens: () => getTotalOutputTokens,
- getTotalLinesRemoved: () => getTotalLinesRemoved,
- getTotalLinesAdded: () => getTotalLinesAdded,
- getTotalInputTokens: () => getTotalInputTokens,
- getTotalDuration: () => getTotalDuration,
- getTotalCostUSD: () => getTotalCostUSD,
- getTotalCacheReadInputTokens: () => getTotalCacheReadInputTokens,
- getTotalCacheCreationInputTokens: () => getTotalCacheCreationInputTokens,
- getTotalAPIDurationWithoutRetries: () => getTotalAPIDurationWithoutRetries,
- getTotalAPIDuration: () => getTotalAPIDuration,
- getTokenCounter: () => getTokenCounter,
- getThinkingClearLatched: () => getThinkingClearLatched,
- getTeleportedSessionInfo: () => getTeleportedSessionInfo,
- getSystemPromptSectionCache: () => getSystemPromptSectionCache,
- getStrictToolResultPairing: () => getStrictToolResultPairing,
- getStatsStore: () => getStatsStore,
- getSlowOperations: () => getSlowOperations,
- getSessionTrustAccepted: () => getSessionTrustAccepted,
- getSessionSource: () => getSessionSource,
- getSessionProjectDir: () => getSessionProjectDir,
- getSessionIngressToken: () => getSessionIngressToken,
- getSessionId: () => getSessionId,
- getSessionCronTasks: () => getSessionCronTasks,
- getSessionCreatedTeams: () => getSessionCreatedTeams,
- getSessionCounter: () => getSessionCounter,
- getSessionBypassPermissionsMode: () => getSessionBypassPermissionsMode,
- getSdkBetas: () => getSdkBetas,
- getSdkAgentProgressSummariesEnabled: () => getSdkAgentProgressSummariesEnabled,
- getScheduledTasksEnabled: () => getScheduledTasksEnabled,
- getRegisteredHooks: () => getRegisteredHooks,
- getQuestionPreviewFormat: () => getQuestionPreviewFormat,
- getPromptId: () => getPromptId,
- getPromptCache1hEligible: () => getPromptCache1hEligible,
- getPromptCache1hAllowlist: () => getPromptCache1hAllowlist,
- getProjectRoot: () => getProjectRoot,
- getPrCounter: () => getPrCounter,
- getPlanSlugCache: () => getPlanSlugCache,
- getParentSessionId: () => getParentSessionId,
- getOriginalCwd: () => getOriginalCwd,
- getOauthTokenFromFd: () => getOauthTokenFromFd,
- getModelUsage: () => getModelUsage,
- getModelStrings: () => getModelStrings,
- getMeterProvider: () => getMeterProvider,
- getMeter: () => getMeter,
- getMainThreadAgentType: () => getMainThreadAgentType,
- getMainLoopModelOverride: () => getMainLoopModelOverride,
- getLoggerProvider: () => getLoggerProvider,
- getLocCounter: () => getLocCounter,
- getLastMainRequestId: () => getLastMainRequestId,
- getLastInteractionTime: () => getLastInteractionTime,
- getLastEmittedDate: () => getLastEmittedDate,
- getLastClassifierRequests: () => getLastClassifierRequests,
- getLastApiCompletionTimestamp: () => getLastApiCompletionTimestamp,
- getLastAPIRequestMessages: () => getLastAPIRequestMessages,
- getLastAPIRequest: () => getLastAPIRequest,
- getKairosActive: () => getKairosActive,
- getIsScrollDraining: () => getIsScrollDraining,
- getIsRemoteMode: () => getIsRemoteMode,
- getIsNonInteractiveSession: () => getIsNonInteractiveSession,
- getIsInteractive: () => getIsInteractive,
- getInvokedSkillsForAgent: () => getInvokedSkillsForAgent,
- getInvokedSkills: () => getInvokedSkills,
- getInlinePlugins: () => getInlinePlugins,
- getInitialMainLoopModel: () => getInitialMainLoopModel,
- getInitJsonSchema: () => getInitJsonSchema,
- getHasDevChannels: () => getHasDevChannels,
- getFlagSettingsPath: () => getFlagSettingsPath,
- getFlagSettingsInline: () => getFlagSettingsInline,
- getFastModeHeaderLatched: () => getFastModeHeaderLatched,
- getEventLogger: () => getEventLogger,
- getDirectConnectServerUrl: () => getDirectConnectServerUrl,
- getCwdState: () => getCwdState,
- getCurrentTurnTokenBudget: () => getCurrentTurnTokenBudget,
- getCostCounter: () => getCostCounter,
- getCommitCounter: () => getCommitCounter,
- getCodeEditToolDecisionCounter: () => getCodeEditToolDecisionCounter,
- getClientType: () => getClientType,
- getChromeFlagOverride: () => getChromeFlagOverride,
- getCachedClaudeMdContent: () => getCachedClaudeMdContent,
- getCacheEditingHeaderLatched: () => getCacheEditingHeaderLatched,
- getBudgetContinuationCount: () => getBudgetContinuationCount,
- getApiKeyFromFd: () => getApiKeyFromFd,
- getAllowedSettingSources: () => getAllowedSettingSources,
- getAllowedChannels: () => getAllowedChannels,
- getAgentColorMap: () => getAgentColorMap,
- getAfkModeHeaderLatched: () => getAfkModeHeaderLatched,
- getAdditionalDirectoriesForClaudeMd: () => getAdditionalDirectoriesForClaudeMd,
- getActiveTimeCounter: () => getActiveTimeCounter,
- flushInteractionTime: () => flushInteractionTime,
- consumePostCompaction: () => consumePostCompaction,
- clearSystemPromptSectionState: () => clearSystemPromptSectionState,
- clearRegisteredPluginHooks: () => clearRegisteredPluginHooks,
- clearRegisteredHooks: () => clearRegisteredHooks,
- clearInvokedSkillsForAgent: () => clearInvokedSkillsForAgent,
- clearInvokedSkills: () => clearInvokedSkills,
- clearBetaHeaderLatches: () => clearBetaHeaderLatches,
- addToTurnHookDuration: () => addToTurnHookDuration,
- addToTurnClassifierDuration: () => addToTurnClassifierDuration,
- addToTotalLinesChanged: () => addToTotalLinesChanged,
- addToTotalDurationState: () => addToTotalDurationState,
- addToTotalCostState: () => addToTotalCostState,
- addToToolDuration: () => addToToolDuration,
- addToInMemoryErrorLog: () => addToInMemoryErrorLog,
- addSlowOperation: () => addSlowOperation,
- addSessionCronTask: () => addSessionCronTask,
- addInvokedSkill: () => addInvokedSkill
-});
-import { realpathSync } from "fs";
-import { cwd } from "process";
-function getInitialState() {
- let resolvedCwd = "";
- if (typeof process !== "undefined" && typeof process.cwd === "function" && typeof realpathSync === "function") {
- const rawCwd = cwd();
- try {
- resolvedCwd = realpathSync(rawCwd).normalize("NFC");
- } catch {
- resolvedCwd = rawCwd.normalize("NFC");
- }
- }
- const state = {
- originalCwd: resolvedCwd,
- projectRoot: resolvedCwd,
- totalCostUSD: 0,
- totalAPIDuration: 0,
- totalAPIDurationWithoutRetries: 0,
- totalToolDuration: 0,
- turnHookDurationMs: 0,
- turnToolDurationMs: 0,
- turnClassifierDurationMs: 0,
- turnToolCount: 0,
- turnHookCount: 0,
- turnClassifierCount: 0,
- startTime: Date.now(),
- lastInteractionTime: Date.now(),
- totalLinesAdded: 0,
- totalLinesRemoved: 0,
- hasUnknownModelCost: false,
- cwd: resolvedCwd,
- modelUsage: {},
- mainLoopModelOverride: undefined,
- initialMainLoopModel: null,
- modelStrings: null,
- isInteractive: false,
- kairosActive: false,
- strictToolResultPairing: false,
- sdkAgentProgressSummariesEnabled: false,
- userMsgOptIn: false,
- clientType: "cli",
- sessionSource: undefined,
- questionPreviewFormat: undefined,
- sessionIngressToken: undefined,
- oauthTokenFromFd: undefined,
- apiKeyFromFd: undefined,
- flagSettingsPath: undefined,
- flagSettingsInline: null,
- allowedSettingSources: [
- "userSettings",
- "projectSettings",
- "localSettings",
- "flagSettings",
- "policySettings"
- ],
- meter: null,
- sessionCounter: null,
- locCounter: null,
- prCounter: null,
- commitCounter: null,
- costCounter: null,
- tokenCounter: null,
- codeEditToolDecisionCounter: null,
- activeTimeCounter: null,
- statsStore: null,
- sessionId: randomUUID(),
- parentSessionId: undefined,
- loggerProvider: null,
- eventLogger: null,
- meterProvider: null,
- tracerProvider: null,
- agentColorMap: new Map,
- agentColorIndex: 0,
- lastAPIRequest: null,
- lastAPIRequestMessages: null,
- lastClassifierRequests: null,
- cachedClaudeMdContent: null,
- inMemoryErrorLog: [],
- inlinePlugins: [],
- chromeFlagOverride: undefined,
- useCoworkPlugins: false,
- sessionBypassPermissionsMode: false,
- scheduledTasksEnabled: false,
- sessionCronTasks: [],
- sessionCreatedTeams: new Set,
- sessionTrustAccepted: false,
- sessionPersistenceDisabled: false,
- hasExitedPlanMode: false,
- needsPlanModeExitAttachment: false,
- needsAutoModeExitAttachment: false,
- lspRecommendationShownThisSession: false,
- initJsonSchema: null,
- registeredHooks: null,
- planSlugCache: new Map,
- teleportedSessionInfo: null,
- invokedSkills: new Map,
- slowOperations: [],
- sdkBetas: undefined,
- mainThreadAgentType: undefined,
- isRemoteMode: false,
- ...process.env.USER_TYPE === "ant" ? {
- replBridgeActive: false
- } : {},
- directConnectServerUrl: undefined,
- systemPromptSectionCache: new Map,
- lastEmittedDate: null,
- additionalDirectoriesForClaudeMd: [],
- allowedChannels: [],
- hasDevChannels: false,
- sessionProjectDir: null,
- promptCache1hAllowlist: null,
- promptCache1hEligible: null,
- afkModeHeaderLatched: null,
- fastModeHeaderLatched: null,
- cacheEditingHeaderLatched: null,
- thinkingClearLatched: null,
- promptId: null,
- lastMainRequestId: undefined,
- lastApiCompletionTimestamp: null,
- pendingPostCompaction: false
- };
- return state;
-}
-function getSessionId() {
- return STATE.sessionId;
-}
-function regenerateSessionId(options = {}) {
- if (options.setCurrentAsParent) {
- STATE.parentSessionId = STATE.sessionId;
- }
- STATE.planSlugCache.delete(STATE.sessionId);
- STATE.sessionId = randomUUID();
- STATE.sessionProjectDir = null;
- return STATE.sessionId;
-}
-function getParentSessionId() {
- return STATE.parentSessionId;
-}
-function switchSession(sessionId, projectDir = null) {
- STATE.planSlugCache.delete(STATE.sessionId);
- STATE.sessionId = sessionId;
- STATE.sessionProjectDir = projectDir;
- sessionSwitched.emit(sessionId);
-}
-function getSessionProjectDir() {
- return STATE.sessionProjectDir;
-}
-function getOriginalCwd() {
- return STATE.originalCwd;
-}
-function getProjectRoot() {
- return STATE.projectRoot;
-}
-function setOriginalCwd(cwd2) {
- STATE.originalCwd = cwd2.normalize("NFC");
-}
-function setProjectRoot(cwd2) {
- STATE.projectRoot = cwd2.normalize("NFC");
-}
-function getCwdState() {
- return STATE.cwd;
-}
-function setCwdState(cwd2) {
- STATE.cwd = cwd2.normalize("NFC");
-}
-function getDirectConnectServerUrl() {
- return STATE.directConnectServerUrl;
-}
-function setDirectConnectServerUrl(url) {
- STATE.directConnectServerUrl = url;
-}
-function addToTotalDurationState(duration, durationWithoutRetries) {
- STATE.totalAPIDuration += duration;
- STATE.totalAPIDurationWithoutRetries += durationWithoutRetries;
-}
-function resetTotalDurationStateAndCost_FOR_TESTS_ONLY() {
- STATE.totalAPIDuration = 0;
- STATE.totalAPIDurationWithoutRetries = 0;
- STATE.totalCostUSD = 0;
-}
-function addToTotalCostState(cost, modelUsage, model) {
- STATE.modelUsage[model] = modelUsage;
- STATE.totalCostUSD += cost;
-}
-function getTotalCostUSD() {
- return STATE.totalCostUSD;
-}
-function getTotalAPIDuration() {
- return STATE.totalAPIDuration;
-}
-function getTotalDuration() {
- return Date.now() - STATE.startTime;
-}
-function getTotalAPIDurationWithoutRetries() {
- return STATE.totalAPIDurationWithoutRetries;
-}
-function getTotalToolDuration() {
- return STATE.totalToolDuration;
-}
-function addToToolDuration(duration) {
- STATE.totalToolDuration += duration;
- STATE.turnToolDurationMs += duration;
- STATE.turnToolCount++;
-}
-function getTurnHookDurationMs() {
- return STATE.turnHookDurationMs;
-}
-function addToTurnHookDuration(duration) {
- STATE.turnHookDurationMs += duration;
- STATE.turnHookCount++;
-}
-function resetTurnHookDuration() {
- STATE.turnHookDurationMs = 0;
- STATE.turnHookCount = 0;
-}
-function getTurnHookCount() {
- return STATE.turnHookCount;
-}
-function getTurnToolDurationMs() {
- return STATE.turnToolDurationMs;
-}
-function resetTurnToolDuration() {
- STATE.turnToolDurationMs = 0;
- STATE.turnToolCount = 0;
-}
-function getTurnToolCount() {
- return STATE.turnToolCount;
-}
-function getTurnClassifierDurationMs() {
- return STATE.turnClassifierDurationMs;
-}
-function addToTurnClassifierDuration(duration) {
- STATE.turnClassifierDurationMs += duration;
- STATE.turnClassifierCount++;
-}
-function resetTurnClassifierDuration() {
- STATE.turnClassifierDurationMs = 0;
- STATE.turnClassifierCount = 0;
-}
-function getTurnClassifierCount() {
- return STATE.turnClassifierCount;
-}
-function getStatsStore() {
- return STATE.statsStore;
-}
-function setStatsStore(store) {
- STATE.statsStore = store;
-}
-function updateLastInteractionTime(immediate) {
- if (immediate) {
- flushInteractionTime_inner();
- } else {
- interactionTimeDirty = true;
- }
-}
-function flushInteractionTime() {
- if (interactionTimeDirty) {
- flushInteractionTime_inner();
- }
-}
-function flushInteractionTime_inner() {
- STATE.lastInteractionTime = Date.now();
- interactionTimeDirty = false;
-}
-function addToTotalLinesChanged(added, removed) {
- STATE.totalLinesAdded += added;
- STATE.totalLinesRemoved += removed;
-}
-function getTotalLinesAdded() {
- return STATE.totalLinesAdded;
-}
-function getTotalLinesRemoved() {
- return STATE.totalLinesRemoved;
-}
-function getTotalInputTokens() {
- return sumBy_default(Object.values(STATE.modelUsage), "inputTokens");
-}
-function getTotalOutputTokens() {
- return sumBy_default(Object.values(STATE.modelUsage), "outputTokens");
-}
-function getTotalCacheReadInputTokens() {
- return sumBy_default(Object.values(STATE.modelUsage), "cacheReadInputTokens");
-}
-function getTotalCacheCreationInputTokens() {
- return sumBy_default(Object.values(STATE.modelUsage), "cacheCreationInputTokens");
-}
-function getTotalWebSearchRequests() {
- return sumBy_default(Object.values(STATE.modelUsage), "webSearchRequests");
-}
-function getTurnOutputTokens() {
- return getTotalOutputTokens() - outputTokensAtTurnStart;
-}
-function getCurrentTurnTokenBudget() {
- return currentTurnTokenBudget;
-}
-function snapshotOutputTokensForTurn(budget) {
- outputTokensAtTurnStart = getTotalOutputTokens();
- currentTurnTokenBudget = budget;
- budgetContinuationCount = 0;
-}
-function getBudgetContinuationCount() {
- return budgetContinuationCount;
-}
-function incrementBudgetContinuationCount() {
- budgetContinuationCount++;
-}
-function setHasUnknownModelCost() {
- STATE.hasUnknownModelCost = true;
-}
-function hasUnknownModelCost() {
- return STATE.hasUnknownModelCost;
-}
-function getLastMainRequestId() {
- return STATE.lastMainRequestId;
-}
-function setLastMainRequestId(requestId) {
- STATE.lastMainRequestId = requestId;
-}
-function getLastApiCompletionTimestamp() {
- return STATE.lastApiCompletionTimestamp;
-}
-function setLastApiCompletionTimestamp(timestamp) {
- STATE.lastApiCompletionTimestamp = timestamp;
-}
-function markPostCompaction() {
- STATE.pendingPostCompaction = true;
-}
-function consumePostCompaction() {
- const was = STATE.pendingPostCompaction;
- STATE.pendingPostCompaction = false;
- return was;
-}
-function getLastInteractionTime() {
- return STATE.lastInteractionTime;
-}
-function markScrollActivity() {
- scrollDraining = true;
- if (scrollDrainTimer)
- clearTimeout(scrollDrainTimer);
- scrollDrainTimer = setTimeout(() => {
- scrollDraining = false;
- scrollDrainTimer = undefined;
- }, SCROLL_DRAIN_IDLE_MS);
- scrollDrainTimer.unref?.();
-}
-function getIsScrollDraining() {
- return scrollDraining;
-}
-async function waitForScrollIdle() {
- while (scrollDraining) {
- await new Promise((r) => setTimeout(r, SCROLL_DRAIN_IDLE_MS).unref?.());
- }
-}
-function getModelUsage() {
- return STATE.modelUsage;
-}
-function getUsageForModel(model) {
- return STATE.modelUsage[model];
-}
-function getMainLoopModelOverride() {
- return STATE.mainLoopModelOverride;
-}
-function getInitialMainLoopModel() {
- return STATE.initialMainLoopModel;
-}
-function setMainLoopModelOverride(model) {
- STATE.mainLoopModelOverride = model;
-}
-function setInitialMainLoopModel(model) {
- STATE.initialMainLoopModel = model;
-}
-function getSdkBetas() {
- return STATE.sdkBetas;
-}
-function setSdkBetas(betas) {
- STATE.sdkBetas = betas;
-}
-function resetCostState() {
- STATE.totalCostUSD = 0;
- STATE.totalAPIDuration = 0;
- STATE.totalAPIDurationWithoutRetries = 0;
- STATE.totalToolDuration = 0;
- STATE.startTime = Date.now();
- STATE.totalLinesAdded = 0;
- STATE.totalLinesRemoved = 0;
- STATE.hasUnknownModelCost = false;
- STATE.modelUsage = {};
- STATE.promptId = null;
-}
-function setCostStateForRestore({
- totalCostUSD,
- totalAPIDuration,
- totalAPIDurationWithoutRetries,
- totalToolDuration,
- totalLinesAdded,
- totalLinesRemoved,
- lastDuration,
- modelUsage
-}) {
- STATE.totalCostUSD = totalCostUSD;
- STATE.totalAPIDuration = totalAPIDuration;
- STATE.totalAPIDurationWithoutRetries = totalAPIDurationWithoutRetries;
- STATE.totalToolDuration = totalToolDuration;
- STATE.totalLinesAdded = totalLinesAdded;
- STATE.totalLinesRemoved = totalLinesRemoved;
- if (modelUsage) {
- STATE.modelUsage = modelUsage;
- }
- if (lastDuration) {
- STATE.startTime = Date.now() - lastDuration;
- }
-}
-function resetStateForTests() {
- if (true) {
- throw new Error("resetStateForTests can only be called in tests");
- }
- Object.entries(getInitialState()).forEach(([key, value]) => {
- STATE[key] = value;
- });
- outputTokensAtTurnStart = 0;
- currentTurnTokenBudget = null;
- budgetContinuationCount = 0;
- sessionSwitched.clear();
-}
-function getModelStrings() {
- return STATE.modelStrings;
-}
-function setModelStrings(modelStrings) {
- STATE.modelStrings = modelStrings;
-}
-function resetModelStringsForTestingOnly() {
- STATE.modelStrings = null;
-}
-function setMeter(meter, createCounter) {
- STATE.meter = meter;
- STATE.sessionCounter = createCounter("claude_code.session.count", {
- description: "Count of CLI sessions started"
- });
- STATE.locCounter = createCounter("claude_code.lines_of_code.count", {
- description: "Count of lines of code modified, with the 'type' attribute indicating whether lines were added or removed"
- });
- STATE.prCounter = createCounter("claude_code.pull_request.count", {
- description: "Number of pull requests created"
- });
- STATE.commitCounter = createCounter("claude_code.commit.count", {
- description: "Number of git commits created"
- });
- STATE.costCounter = createCounter("claude_code.cost.usage", {
- description: "Cost of the Claude Code session",
- unit: "USD"
- });
- STATE.tokenCounter = createCounter("claude_code.token.usage", {
- description: "Number of tokens used",
- unit: "tokens"
- });
- STATE.codeEditToolDecisionCounter = createCounter("claude_code.code_edit_tool.decision", {
- description: "Count of code editing tool permission decisions (accept/reject) for Edit, Write, and NotebookEdit tools"
- });
- STATE.activeTimeCounter = createCounter("claude_code.active_time.total", {
- description: "Total active time in seconds",
- unit: "s"
- });
-}
-function getMeter() {
- return STATE.meter;
-}
-function getSessionCounter() {
- return STATE.sessionCounter;
-}
-function getLocCounter() {
- return STATE.locCounter;
-}
-function getPrCounter() {
- return STATE.prCounter;
-}
-function getCommitCounter() {
- return STATE.commitCounter;
-}
-function getCostCounter() {
- return STATE.costCounter;
-}
-function getTokenCounter() {
- return STATE.tokenCounter;
-}
-function getCodeEditToolDecisionCounter() {
- return STATE.codeEditToolDecisionCounter;
-}
-function getActiveTimeCounter() {
- return STATE.activeTimeCounter;
-}
-function getLoggerProvider() {
- return STATE.loggerProvider;
-}
-function setLoggerProvider(provider) {
- STATE.loggerProvider = provider;
-}
-function getEventLogger() {
- return STATE.eventLogger;
-}
-function setEventLogger(logger) {
- STATE.eventLogger = logger;
-}
-function getMeterProvider() {
- return STATE.meterProvider;
-}
-function setMeterProvider(provider) {
- STATE.meterProvider = provider;
-}
-function getTracerProvider() {
- return STATE.tracerProvider;
-}
-function setTracerProvider(provider) {
- STATE.tracerProvider = provider;
-}
-function getIsNonInteractiveSession() {
- return !STATE.isInteractive;
-}
-function getIsInteractive() {
- return STATE.isInteractive;
-}
-function setIsInteractive(value) {
- STATE.isInteractive = value;
-}
-function getClientType() {
- return STATE.clientType;
-}
-function setClientType(type) {
- STATE.clientType = type;
-}
-function getSdkAgentProgressSummariesEnabled() {
- return STATE.sdkAgentProgressSummariesEnabled;
-}
-function setSdkAgentProgressSummariesEnabled(value) {
- STATE.sdkAgentProgressSummariesEnabled = value;
-}
-function getKairosActive() {
- return STATE.kairosActive;
-}
-function setKairosActive(value) {
- STATE.kairosActive = value;
-}
-function getStrictToolResultPairing() {
- return STATE.strictToolResultPairing;
-}
-function setStrictToolResultPairing(value) {
- STATE.strictToolResultPairing = value;
-}
-function getUserMsgOptIn() {
- return STATE.userMsgOptIn;
-}
-function setUserMsgOptIn(value) {
- STATE.userMsgOptIn = value;
-}
-function getSessionSource() {
- return STATE.sessionSource;
-}
-function setSessionSource(source) {
- STATE.sessionSource = source;
-}
-function getQuestionPreviewFormat() {
- return STATE.questionPreviewFormat;
-}
-function setQuestionPreviewFormat(format) {
- STATE.questionPreviewFormat = format;
-}
-function getAgentColorMap() {
- return STATE.agentColorMap;
-}
-function getFlagSettingsPath() {
- return STATE.flagSettingsPath;
-}
-function setFlagSettingsPath(path) {
- STATE.flagSettingsPath = path;
-}
-function getFlagSettingsInline() {
- return STATE.flagSettingsInline;
-}
-function setFlagSettingsInline(settings) {
- STATE.flagSettingsInline = settings;
-}
-function getSessionIngressToken() {
- return STATE.sessionIngressToken;
-}
-function setSessionIngressToken(token) {
- STATE.sessionIngressToken = token;
-}
-function getOauthTokenFromFd() {
- return STATE.oauthTokenFromFd;
-}
-function setOauthTokenFromFd(token) {
- STATE.oauthTokenFromFd = token;
-}
-function getApiKeyFromFd() {
- return STATE.apiKeyFromFd;
-}
-function setApiKeyFromFd(key) {
- STATE.apiKeyFromFd = key;
-}
-function setLastAPIRequest(params) {
- STATE.lastAPIRequest = params;
-}
-function getLastAPIRequest() {
- return STATE.lastAPIRequest;
-}
-function setLastAPIRequestMessages(messages) {
- STATE.lastAPIRequestMessages = messages;
-}
-function getLastAPIRequestMessages() {
- return STATE.lastAPIRequestMessages;
-}
-function setLastClassifierRequests(requests) {
- STATE.lastClassifierRequests = requests;
-}
-function getLastClassifierRequests() {
- return STATE.lastClassifierRequests;
-}
-function setCachedClaudeMdContent(content) {
- STATE.cachedClaudeMdContent = content;
-}
-function getCachedClaudeMdContent() {
- return STATE.cachedClaudeMdContent;
-}
-function addToInMemoryErrorLog(errorInfo) {
- const MAX_IN_MEMORY_ERRORS = 100;
- if (STATE.inMemoryErrorLog.length >= MAX_IN_MEMORY_ERRORS) {
- STATE.inMemoryErrorLog.shift();
- }
- STATE.inMemoryErrorLog.push(errorInfo);
-}
-function getAllowedSettingSources() {
- return STATE.allowedSettingSources;
-}
-function setAllowedSettingSources(sources) {
- STATE.allowedSettingSources = sources;
-}
-function preferThirdPartyAuthentication() {
- return getIsNonInteractiveSession() && STATE.clientType !== "claude-vscode";
-}
-function setInlinePlugins(plugins) {
- STATE.inlinePlugins = plugins;
-}
-function getInlinePlugins() {
- return STATE.inlinePlugins;
-}
-function setChromeFlagOverride(value) {
- STATE.chromeFlagOverride = value;
-}
-function getChromeFlagOverride() {
- return STATE.chromeFlagOverride;
-}
-function setUseCoworkPlugins(value) {
- STATE.useCoworkPlugins = value;
- resetSettingsCache();
-}
-function getUseCoworkPlugins() {
- return STATE.useCoworkPlugins;
-}
-function setSessionBypassPermissionsMode(enabled) {
- STATE.sessionBypassPermissionsMode = enabled;
-}
-function getSessionBypassPermissionsMode() {
- return STATE.sessionBypassPermissionsMode;
-}
-function setScheduledTasksEnabled(enabled) {
- STATE.scheduledTasksEnabled = enabled;
-}
-function getScheduledTasksEnabled() {
- return STATE.scheduledTasksEnabled;
-}
-function getSessionCronTasks() {
- return STATE.sessionCronTasks;
-}
-function addSessionCronTask(task) {
- STATE.sessionCronTasks.push(task);
-}
-function removeSessionCronTasks(ids) {
- if (ids.length === 0)
- return 0;
- const idSet = new Set(ids);
- const remaining = STATE.sessionCronTasks.filter((t) => !idSet.has(t.id));
- const removed = STATE.sessionCronTasks.length - remaining.length;
- if (removed === 0)
- return 0;
- STATE.sessionCronTasks = remaining;
- return removed;
-}
-function setSessionTrustAccepted(accepted) {
- STATE.sessionTrustAccepted = accepted;
-}
-function getSessionTrustAccepted() {
- return STATE.sessionTrustAccepted;
-}
-function setSessionPersistenceDisabled(disabled) {
- STATE.sessionPersistenceDisabled = disabled;
-}
-function isSessionPersistenceDisabled() {
- return STATE.sessionPersistenceDisabled;
-}
-function hasExitedPlanModeInSession() {
- return STATE.hasExitedPlanMode;
-}
-function setHasExitedPlanMode(value) {
- STATE.hasExitedPlanMode = value;
-}
-function needsPlanModeExitAttachment() {
- return STATE.needsPlanModeExitAttachment;
-}
-function setNeedsPlanModeExitAttachment(value) {
- STATE.needsPlanModeExitAttachment = value;
-}
-function handlePlanModeTransition(fromMode, toMode) {
- if (toMode === "plan" && fromMode !== "plan") {
- STATE.needsPlanModeExitAttachment = false;
- }
- if (fromMode === "plan" && toMode !== "plan") {
- STATE.needsPlanModeExitAttachment = true;
- }
-}
-function needsAutoModeExitAttachment() {
- return STATE.needsAutoModeExitAttachment;
-}
-function setNeedsAutoModeExitAttachment(value) {
- STATE.needsAutoModeExitAttachment = value;
-}
-function handleAutoModeTransition(fromMode, toMode) {
- if (fromMode === "auto" && toMode === "plan" || fromMode === "plan" && toMode === "auto") {
- return;
- }
- const fromIsAuto = fromMode === "auto";
- const toIsAuto = toMode === "auto";
- if (toIsAuto && !fromIsAuto) {
- STATE.needsAutoModeExitAttachment = false;
- }
- if (fromIsAuto && !toIsAuto) {
- STATE.needsAutoModeExitAttachment = true;
- }
-}
-function hasShownLspRecommendationThisSession() {
- return STATE.lspRecommendationShownThisSession;
-}
-function setLspRecommendationShownThisSession(value) {
- STATE.lspRecommendationShownThisSession = value;
-}
-function setInitJsonSchema(schema) {
- STATE.initJsonSchema = schema;
-}
-function getInitJsonSchema() {
- return STATE.initJsonSchema;
-}
-function registerHookCallbacks(hooks) {
- if (!STATE.registeredHooks) {
- STATE.registeredHooks = {};
- }
- for (const [event, matchers] of Object.entries(hooks)) {
- const eventKey = event;
- if (!STATE.registeredHooks[eventKey]) {
- STATE.registeredHooks[eventKey] = [];
- }
- STATE.registeredHooks[eventKey].push(...matchers);
- }
-}
-function getRegisteredHooks() {
- return STATE.registeredHooks;
-}
-function clearRegisteredHooks() {
- STATE.registeredHooks = null;
-}
-function clearRegisteredPluginHooks() {
- if (!STATE.registeredHooks) {
- return;
- }
- const filtered = {};
- for (const [event, matchers] of Object.entries(STATE.registeredHooks)) {
- const callbackHooks = matchers.filter((m) => !("pluginRoot" in m));
- if (callbackHooks.length > 0) {
- filtered[event] = callbackHooks;
- }
- }
- STATE.registeredHooks = Object.keys(filtered).length > 0 ? filtered : null;
-}
-function resetSdkInitState() {
- STATE.initJsonSchema = null;
- STATE.registeredHooks = null;
-}
-function getPlanSlugCache() {
- return STATE.planSlugCache;
-}
-function getSessionCreatedTeams() {
- return STATE.sessionCreatedTeams;
-}
-function setTeleportedSessionInfo(info) {
- STATE.teleportedSessionInfo = {
- isTeleported: true,
- hasLoggedFirstMessage: false,
- sessionId: info.sessionId
- };
-}
-function getTeleportedSessionInfo() {
- return STATE.teleportedSessionInfo;
-}
-function markFirstTeleportMessageLogged() {
- if (STATE.teleportedSessionInfo) {
- STATE.teleportedSessionInfo.hasLoggedFirstMessage = true;
- }
-}
-function addInvokedSkill(skillName, skillPath, content, agentId = null) {
- const key = `${agentId ?? ""}:${skillName}`;
- STATE.invokedSkills.set(key, {
- skillName,
- skillPath,
- content,
- invokedAt: Date.now(),
- agentId
- });
-}
-function getInvokedSkills() {
- return STATE.invokedSkills;
-}
-function getInvokedSkillsForAgent(agentId) {
- const normalizedId = agentId ?? null;
- const filtered = new Map;
- for (const [key, skill] of STATE.invokedSkills) {
- if (skill.agentId === normalizedId) {
- filtered.set(key, skill);
- }
- }
- return filtered;
-}
-function clearInvokedSkills(preservedAgentIds) {
- if (!preservedAgentIds || preservedAgentIds.size === 0) {
- STATE.invokedSkills.clear();
- return;
- }
- for (const [key, skill] of STATE.invokedSkills) {
- if (skill.agentId === null || !preservedAgentIds.has(skill.agentId)) {
- STATE.invokedSkills.delete(key);
- }
- }
-}
-function clearInvokedSkillsForAgent(agentId) {
- for (const [key, skill] of STATE.invokedSkills) {
- if (skill.agentId === agentId) {
- STATE.invokedSkills.delete(key);
- }
- }
-}
-function addSlowOperation(operation, durationMs) {
- if (process.env.USER_TYPE !== "ant")
- return;
- if (operation.includes("exec") && operation.includes("claude-prompt-")) {
- return;
- }
- const now = Date.now();
- STATE.slowOperations = STATE.slowOperations.filter((op) => now - op.timestamp < SLOW_OPERATION_TTL_MS);
- STATE.slowOperations.push({ operation, durationMs, timestamp: now });
- if (STATE.slowOperations.length > MAX_SLOW_OPERATIONS) {
- STATE.slowOperations = STATE.slowOperations.slice(-MAX_SLOW_OPERATIONS);
- }
-}
-function getSlowOperations() {
- if (STATE.slowOperations.length === 0) {
- return EMPTY_SLOW_OPERATIONS;
- }
- const now = Date.now();
- if (STATE.slowOperations.some((op) => now - op.timestamp >= SLOW_OPERATION_TTL_MS)) {
- STATE.slowOperations = STATE.slowOperations.filter((op) => now - op.timestamp < SLOW_OPERATION_TTL_MS);
- if (STATE.slowOperations.length === 0) {
- return EMPTY_SLOW_OPERATIONS;
- }
- }
- return STATE.slowOperations;
-}
-function getMainThreadAgentType() {
- return STATE.mainThreadAgentType;
-}
-function setMainThreadAgentType(agentType) {
- STATE.mainThreadAgentType = agentType;
-}
-function getIsRemoteMode() {
- return STATE.isRemoteMode;
-}
-function setIsRemoteMode(value) {
- STATE.isRemoteMode = value;
-}
-function getSystemPromptSectionCache() {
- return STATE.systemPromptSectionCache;
-}
-function setSystemPromptSectionCacheEntry(name, value) {
- STATE.systemPromptSectionCache.set(name, value);
-}
-function clearSystemPromptSectionState() {
- STATE.systemPromptSectionCache.clear();
-}
-function getLastEmittedDate() {
- return STATE.lastEmittedDate;
-}
-function setLastEmittedDate(date) {
- STATE.lastEmittedDate = date;
-}
-function getAdditionalDirectoriesForClaudeMd() {
- return STATE.additionalDirectoriesForClaudeMd;
-}
-function setAdditionalDirectoriesForClaudeMd(directories) {
- STATE.additionalDirectoriesForClaudeMd = directories;
-}
-function getAllowedChannels() {
- return STATE.allowedChannels;
-}
-function setAllowedChannels(entries) {
- STATE.allowedChannels = entries;
-}
-function getHasDevChannels() {
- return STATE.hasDevChannels;
-}
-function setHasDevChannels(value) {
- STATE.hasDevChannels = value;
-}
-function getPromptCache1hAllowlist() {
- return STATE.promptCache1hAllowlist;
-}
-function setPromptCache1hAllowlist(allowlist) {
- STATE.promptCache1hAllowlist = allowlist;
-}
-function getPromptCache1hEligible() {
- return STATE.promptCache1hEligible;
-}
-function setPromptCache1hEligible(eligible) {
- STATE.promptCache1hEligible = eligible;
-}
-function getAfkModeHeaderLatched() {
- return STATE.afkModeHeaderLatched;
-}
-function setAfkModeHeaderLatched(v) {
- STATE.afkModeHeaderLatched = v;
-}
-function getFastModeHeaderLatched() {
- return STATE.fastModeHeaderLatched;
-}
-function setFastModeHeaderLatched(v) {
- STATE.fastModeHeaderLatched = v;
-}
-function getCacheEditingHeaderLatched() {
- return STATE.cacheEditingHeaderLatched;
-}
-function setCacheEditingHeaderLatched(v) {
- STATE.cacheEditingHeaderLatched = v;
-}
-function getThinkingClearLatched() {
- return STATE.thinkingClearLatched;
-}
-function setThinkingClearLatched(v) {
- STATE.thinkingClearLatched = v;
-}
-function clearBetaHeaderLatches() {
- STATE.afkModeHeaderLatched = null;
- STATE.fastModeHeaderLatched = null;
- STATE.cacheEditingHeaderLatched = null;
- STATE.thinkingClearLatched = null;
-}
-function getPromptId() {
- return STATE.promptId;
-}
-function setPromptId(id) {
- STATE.promptId = id;
-}
-var STATE, sessionSwitched, onSessionSwitch, interactionTimeDirty = false, outputTokensAtTurnStart = 0, currentTurnTokenBudget = null, budgetContinuationCount = 0, scrollDraining = false, scrollDrainTimer, SCROLL_DRAIN_IDLE_MS = 150, MAX_SLOW_OPERATIONS = 10, SLOW_OPERATION_TTL_MS = 1e4, EMPTY_SLOW_OPERATIONS;
-var init_state = __esm(() => {
- init_sumBy();
- init_crypto();
- init_settingsCache();
- STATE = getInitialState();
- sessionSwitched = createSignal();
- onSessionSwitch = sessionSwitched.subscribe;
- EMPTY_SLOW_OPERATIONS = [];
-});
-
-// src/services/analytics/index.ts
-function stripProtoFields(metadata) {
- let result;
- for (const key in metadata) {
- if (key.startsWith("_PROTO_")) {
- if (result === undefined) {
- result = { ...metadata };
- }
- delete result[key];
- }
- }
- return result ?? metadata;
-}
-function attachAnalyticsSink(newSink) {
- if (sink !== null) {
- return;
- }
- sink = newSink;
- if (eventQueue.length > 0) {
- const queuedEvents = [...eventQueue];
- eventQueue.length = 0;
- if (process.env.USER_TYPE === "ant") {
- sink.logEvent("analytics_sink_attached", {
- queued_event_count: queuedEvents.length
- });
- }
- queueMicrotask(() => {
- for (const event of queuedEvents) {
- if (event.async) {
- sink.logEventAsync(event.eventName, event.metadata);
- } else {
- sink.logEvent(event.eventName, event.metadata);
- }
- }
- });
- }
-}
-function logEvent(eventName, metadata) {
- if (sink === null) {
- eventQueue.push({ eventName, metadata, async: false });
- return;
- }
- sink.logEvent(eventName, metadata);
-}
-var eventQueue, sink = null;
-var init_analytics = __esm(() => {
- eventQueue = [];
-});
-
-// src/utils/bufferedWriter.ts
-function createBufferedWriter({
- writeFn,
- flushIntervalMs = 1000,
- maxBufferSize = 100,
- maxBufferBytes = Infinity,
- immediateMode = false
-}) {
- let buffer = [];
- let bufferBytes = 0;
- let flushTimer = null;
- let pendingOverflow = null;
- function clearTimer() {
- if (flushTimer) {
- clearTimeout(flushTimer);
- flushTimer = null;
- }
- }
- function flush() {
- if (pendingOverflow) {
- writeFn(pendingOverflow.join(""));
- pendingOverflow = null;
- }
- if (buffer.length === 0)
- return;
- writeFn(buffer.join(""));
- buffer = [];
- bufferBytes = 0;
- clearTimer();
- }
- function scheduleFlush() {
- if (!flushTimer) {
- flushTimer = setTimeout(flush, flushIntervalMs);
- }
- }
- function flushDeferred() {
- if (pendingOverflow) {
- pendingOverflow.push(...buffer);
- buffer = [];
- bufferBytes = 0;
- clearTimer();
- return;
- }
- const detached = buffer;
- buffer = [];
- bufferBytes = 0;
- clearTimer();
- pendingOverflow = detached;
- setImmediate(() => {
- const toWrite = pendingOverflow;
- pendingOverflow = null;
- if (toWrite)
- writeFn(toWrite.join(""));
- });
- }
- return {
- write(content) {
- if (immediateMode) {
- writeFn(content);
- return;
- }
- buffer.push(content);
- bufferBytes += content.length;
- scheduleFlush();
- if (buffer.length >= maxBufferSize || bufferBytes >= maxBufferBytes) {
- flushDeferred();
- }
- },
- flush,
- dispose() {
- flush();
- }
- };
-}
-
-// src/utils/cleanupRegistry.ts
-function registerCleanup(cleanupFn) {
- cleanupFunctions.add(cleanupFn);
- return () => cleanupFunctions.delete(cleanupFn);
-}
-async function runCleanupFunctions() {
- await Promise.all(Array.from(cleanupFunctions).map((fn) => fn()));
-}
-var cleanupFunctions;
-var init_cleanupRegistry = __esm(() => {
- cleanupFunctions = new Set;
-});
-
-// src/utils/debugFilter.ts
-function extractDebugCategories(message) {
- const categories = [];
- const mcpMatch = message.match(/^MCP server ["']([^"']+)["']/);
- if (mcpMatch && mcpMatch[1]) {
- categories.push("mcp");
- categories.push(mcpMatch[1].toLowerCase());
- } else {
- const prefixMatch = message.match(/^([^:[]+):/);
- if (prefixMatch && prefixMatch[1]) {
- categories.push(prefixMatch[1].trim().toLowerCase());
- }
- }
- const bracketMatch = message.match(/^\[([^\]]+)]/);
- if (bracketMatch && bracketMatch[1]) {
- categories.push(bracketMatch[1].trim().toLowerCase());
- }
- if (message.toLowerCase().includes("1p event:")) {
- categories.push("1p");
- }
- const secondaryMatch = message.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);
- if (secondaryMatch && secondaryMatch[1]) {
- const secondary = secondaryMatch[1].trim().toLowerCase();
- if (secondary.length < 30 && !secondary.includes(" ")) {
- categories.push(secondary);
- }
- }
- return Array.from(new Set(categories));
-}
-function shouldShowDebugCategories(categories, filter) {
- if (!filter) {
- return true;
- }
- if (categories.length === 0) {
- return false;
- }
- if (filter.isExclusive) {
- return !categories.some((cat) => filter.exclude.includes(cat));
- } else {
- return categories.some((cat) => filter.include.includes(cat));
- }
-}
-function shouldShowDebugMessage(message, filter) {
- if (!filter) {
- return true;
- }
- const categories = extractDebugCategories(message);
- return shouldShowDebugCategories(categories, filter);
-}
-var parseDebugFilter;
-var init_debugFilter = __esm(() => {
- init_memoize();
- parseDebugFilter = memoize_default((filterString) => {
- if (!filterString || filterString.trim() === "") {
- return null;
- }
- const filters = filterString.split(",").map((f) => f.trim()).filter(Boolean);
- if (filters.length === 0) {
- return null;
- }
- const hasExclusive = filters.some((f) => f.startsWith("!"));
- const hasInclusive = filters.some((f) => !f.startsWith("!"));
- if (hasExclusive && hasInclusive) {
- return null;
- }
- const cleanFilters = filters.map((f) => f.replace(/^!/, "").toLowerCase());
- return {
- include: hasExclusive ? [] : cleanFilters,
- exclude: hasExclusive ? cleanFilters : [],
- isExclusive: hasExclusive
- };
- });
-});
-
-// src/utils/protectedNamespace.ts
-var exports_protectedNamespace = {};
-__export(exports_protectedNamespace, {
- isInProtectedNamespace: () => isInProtectedNamespace
-});
-function isInProtectedNamespace(_name) {
- return false;
-}
-
-// src/utils/envUtils.ts
-import { homedir } from "os";
-import { join } from "path";
-function getTeamsDir() {
- return join(getClaudeConfigHomeDir(), "teams");
-}
-function hasNodeOption(flag) {
- const nodeOptions = process.env.NODE_OPTIONS;
- if (!nodeOptions) {
- return false;
- }
- return nodeOptions.split(/\s+/).includes(flag);
-}
-function isEnvTruthy(envVar) {
- if (!envVar)
- return false;
- if (typeof envVar === "boolean")
- return envVar;
- const normalizedValue = envVar.toLowerCase().trim();
- return ["1", "true", "yes", "on"].includes(normalizedValue);
-}
-function isEnvDefinedFalsy(envVar) {
- if (envVar === undefined)
- return false;
- if (typeof envVar === "boolean")
- return !envVar;
- if (!envVar)
- return false;
- const normalizedValue = envVar.toLowerCase().trim();
- return ["0", "false", "no", "off"].includes(normalizedValue);
-}
-function isBareMode() {
- return isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE) || process.argv.includes("--bare");
-}
-function parseEnvVars(rawEnvArgs) {
- const parsedEnv = {};
- if (rawEnvArgs) {
- for (const envStr of rawEnvArgs) {
- const [key, ...valueParts] = envStr.split("=");
- if (!key || valueParts.length === 0) {
- throw new Error(`Invalid environment variable format: ${envStr}, environment variables should be added as: -e KEY1=value1 -e KEY2=value2`);
- }
- parsedEnv[key] = valueParts.join("=");
- }
- }
- return parsedEnv;
-}
-function getAWSRegion() {
- return process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || "us-east-1";
-}
-function getDefaultVertexRegion() {
- return process.env.CLOUD_ML_REGION || "us-east5";
-}
-function shouldMaintainProjectWorkingDir() {
- return isEnvTruthy(process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR);
-}
-function isRunningOnHomespace() {
- return process.env.USER_TYPE === "ant" && isEnvTruthy(process.env.COO_RUNNING_ON_HOMESPACE);
-}
-function isInProtectedNamespace2() {
- if (process.env.USER_TYPE === "ant") {
- return __toCommonJS(exports_protectedNamespace).checkProtectedNamespace();
- }
- return false;
-}
-function getVertexRegionForModel(model) {
- if (model) {
- const match = VERTEX_REGION_OVERRIDES.find(([prefix]) => model.startsWith(prefix));
- if (match) {
- return process.env[match[1]] || getDefaultVertexRegion();
- }
- }
- return getDefaultVertexRegion();
-}
-var getClaudeConfigHomeDir, VERTEX_REGION_OVERRIDES;
-var init_envUtils = __esm(() => {
- init_memoize();
- getClaudeConfigHomeDir = memoize_default(() => {
- return (process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude")).normalize("NFC");
- }, () => process.env.CLAUDE_CONFIG_DIR);
- VERTEX_REGION_OVERRIDES = [
- ["claude-haiku-4-5", "VERTEX_REGION_CLAUDE_HAIKU_4_5"],
- ["claude-3-5-haiku", "VERTEX_REGION_CLAUDE_3_5_HAIKU"],
- ["claude-3-5-sonnet", "VERTEX_REGION_CLAUDE_3_5_SONNET"],
- ["claude-3-7-sonnet", "VERTEX_REGION_CLAUDE_3_7_SONNET"],
- ["claude-opus-4-1", "VERTEX_REGION_CLAUDE_4_1_OPUS"],
- ["claude-opus-4", "VERTEX_REGION_CLAUDE_4_0_OPUS"],
- ["claude-sonnet-4-6", "VERTEX_REGION_CLAUDE_4_6_SONNET"],
- ["claude-sonnet-4-5", "VERTEX_REGION_CLAUDE_4_5_SONNET"],
- ["claude-sonnet-4", "VERTEX_REGION_CLAUDE_4_0_SONNET"]
- ];
-});
-
-// node_modules/@anthropic-ai/sdk/version.mjs
-var VERSION = "0.39.0";
-
-// node_modules/@anthropic-ai/sdk/_shims/registry.mjs
-function setShims(shims, options = { auto: false }) {
- if (auto) {
- throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${shims.kind}'\` before importing anything else from @anthropic-ai/sdk`);
- }
- if (kind) {
- throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${shims.kind}'\` after \`import '@anthropic-ai/sdk/shims/${kind}'\``);
- }
- auto = options.auto;
- kind = shims.kind;
- fetch2 = shims.fetch;
- Request2 = shims.Request;
- Response2 = shims.Response;
- Headers2 = shims.Headers;
- FormData2 = shims.FormData;
- Blob2 = shims.Blob;
- File2 = shims.File;
- ReadableStream2 = shims.ReadableStream;
- getMultipartRequestOptions = shims.getMultipartRequestOptions;
- getDefaultAgent = shims.getDefaultAgent;
- fileFromPath = shims.fileFromPath;
- isFsReadStream = shims.isFsReadStream;
-}
-var auto = false, kind = undefined, fetch2 = undefined, Request2 = undefined, Response2 = undefined, Headers2 = undefined, FormData2 = undefined, Blob2 = undefined, File2 = undefined, ReadableStream2 = undefined, getMultipartRequestOptions = undefined, getDefaultAgent = undefined, fileFromPath = undefined, isFsReadStream = undefined;
-
-// node_modules/@anthropic-ai/sdk/_shims/MultipartBody.mjs
-var MultipartBody;
-var init_MultipartBody = __esm(() => {
- MultipartBody = class MultipartBody {
- constructor(body) {
- this.body = body;
- }
- get [Symbol.toStringTag]() {
- return "MultipartBody";
- }
- };
-});
-
-// node_modules/@anthropic-ai/sdk/_shims/web-runtime.mjs
-function getRuntime({ manuallyImported } = {}) {
- const recommendation = manuallyImported ? `You may need to use polyfills` : `Add one of these imports before your first \`import \u2026 from '@anthropic-ai/sdk'\`:
-- \`import '@anthropic-ai/sdk/shims/node'\` (if you're running on Node)
-- \`import '@anthropic-ai/sdk/shims/web'\` (otherwise)
-`;
- let _fetch, _Request, _Response, _Headers;
- try {
- _fetch = fetch;
- _Request = Request;
- _Response = Response;
- _Headers = Headers;
- } catch (error) {
- throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`);
- }
- return {
- kind: "web",
- fetch: _fetch,
- Request: _Request,
- Response: _Response,
- Headers: _Headers,
- FormData: typeof FormData !== "undefined" ? FormData : class FormData3 {
- constructor() {
- throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`);
- }
- },
- Blob: typeof Blob !== "undefined" ? Blob : class Blob3 {
- constructor() {
- throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`);
- }
- },
- File: typeof File !== "undefined" ? File : class File3 {
- constructor() {
- throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`);
- }
- },
- ReadableStream: typeof ReadableStream !== "undefined" ? ReadableStream : class ReadableStream3 {
- constructor() {
- throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`);
- }
- },
- getMultipartRequestOptions: async (form, opts) => ({
- ...opts,
- body: new MultipartBody(form)
- }),
- getDefaultAgent: (url) => {
- return;
- },
- fileFromPath: () => {
- throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads");
- },
- isFsReadStream: (value) => false
- };
-}
-var init_web_runtime = __esm(() => {
- init_MultipartBody();
-});
-
-// node_modules/@anthropic-ai/sdk/_shims/bun-runtime.mjs
-import { ReadStream as FsReadStream } from "fs";
-function getRuntime2() {
- const runtime = getRuntime();
- function isFsReadStream2(value) {
- return value instanceof FsReadStream;
- }
- return { ...runtime, isFsReadStream: isFsReadStream2 };
-}
-var init_bun_runtime = __esm(() => {
- init_web_runtime();
-});
-
-// node_modules/@anthropic-ai/sdk/_shims/auto/runtime-bun.mjs
-var init_runtime_bun = __esm(() => {
- init_bun_runtime();
-});
-
-// node_modules/@anthropic-ai/sdk/_shims/index.mjs
-var init__shims = __esm(() => {
- init_runtime_bun();
- if (!kind)
- setShims(getRuntime2(), { auto: true });
-});
-
-// node_modules/@anthropic-ai/sdk/error.mjs
-var AnthropicError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError;
-var init_error = __esm(() => {
- init_core();
- AnthropicError = class AnthropicError extends Error {
- };
- APIError = class APIError extends AnthropicError {
- constructor(status, error, message, headers) {
- super(`${APIError.makeMessage(status, error, message)}`);
- this.status = status;
- this.headers = headers;
- this.request_id = headers?.["request-id"];
- this.error = error;
- }
- static makeMessage(status, error, message) {
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
- if (status && msg) {
- return `${status} ${msg}`;
- }
- if (status) {
- return `${status} status code (no body)`;
- }
- if (msg) {
- return msg;
- }
- return "(no status code or body)";
- }
- static generate(status, errorResponse, message, headers) {
- if (!status || !headers) {
- return new APIConnectionError({ message, cause: castToError(errorResponse) });
- }
- const error = errorResponse;
- if (status === 400) {
- return new BadRequestError(status, error, message, headers);
- }
- if (status === 401) {
- return new AuthenticationError(status, error, message, headers);
- }
- if (status === 403) {
- return new PermissionDeniedError(status, error, message, headers);
- }
- if (status === 404) {
- return new NotFoundError(status, error, message, headers);
- }
- if (status === 409) {
- return new ConflictError(status, error, message, headers);
- }
- if (status === 422) {
- return new UnprocessableEntityError(status, error, message, headers);
- }
- if (status === 429) {
- return new RateLimitError(status, error, message, headers);
- }
- if (status >= 500) {
- return new InternalServerError(status, error, message, headers);
- }
- return new APIError(status, error, message, headers);
- }
- };
- APIUserAbortError = class APIUserAbortError extends APIError {
- constructor({ message } = {}) {
- super(undefined, undefined, message || "Request was aborted.", undefined);
- }
- };
- APIConnectionError = class APIConnectionError extends APIError {
- constructor({ message, cause }) {
- super(undefined, undefined, message || "Connection error.", undefined);
- if (cause)
- this.cause = cause;
- }
- };
- APIConnectionTimeoutError = class APIConnectionTimeoutError extends APIConnectionError {
- constructor({ message } = {}) {
- super({ message: message ?? "Request timed out." });
- }
- };
- BadRequestError = class BadRequestError extends APIError {
- };
- AuthenticationError = class AuthenticationError extends APIError {
- };
- PermissionDeniedError = class PermissionDeniedError extends APIError {
- };
- NotFoundError = class NotFoundError extends APIError {
- };
- ConflictError = class ConflictError extends APIError {
- };
- UnprocessableEntityError = class UnprocessableEntityError extends APIError {
- };
- RateLimitError = class RateLimitError extends APIError {
- };
- InternalServerError = class InternalServerError extends APIError {
- };
-});
-
-// node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs
-class LineDecoder {
- constructor() {
- _LineDecoder_carriageReturnIndex.set(this, undefined);
- this.buffer = new Uint8Array;
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
- }
- decode(chunk) {
- if (chunk == null) {
- return [];
- }
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
- let newData = new Uint8Array(this.buffer.length + binaryChunk.length);
- newData.set(this.buffer);
- newData.set(binaryChunk, this.buffer.length);
- this.buffer = newData;
- const lines = [];
- let patternIndex;
- while ((patternIndex = findNewlineIndex(this.buffer, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
- if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) {
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
- continue;
- }
- if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
- lines.push(this.decodeText(this.buffer.slice(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
- this.buffer = this.buffer.slice(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"));
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
- continue;
- }
- const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
- const line = this.decodeText(this.buffer.slice(0, endIndex));
- lines.push(line);
- this.buffer = this.buffer.slice(patternIndex.index);
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
- }
- return lines;
- }
- decodeText(bytes) {
- if (bytes == null)
- return "";
- if (typeof bytes === "string")
- return bytes;
- if (typeof Buffer !== "undefined") {
- if (bytes instanceof Buffer) {
- return bytes.toString();
- }
- if (bytes instanceof Uint8Array) {
- return Buffer.from(bytes).toString();
- }
- throw new AnthropicError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`);
- }
- if (typeof TextDecoder !== "undefined") {
- if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
- this.textDecoder ?? (this.textDecoder = new TextDecoder("utf8"));
- return this.textDecoder.decode(bytes);
- }
- throw new AnthropicError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
- }
- throw new AnthropicError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`);
- }
- flush() {
- if (!this.buffer.length) {
- return [];
- }
- return this.decode(`
-`);
- }
-}
-function findNewlineIndex(buffer, startIndex) {
- const newline = 10;
- const carriage = 13;
- for (let i = startIndex ?? 0;i < buffer.length; i++) {
- if (buffer[i] === newline) {
- return { preceding: i, index: i + 1, carriage: false };
- }
- if (buffer[i] === carriage) {
- return { preceding: i, index: i + 1, carriage: true };
- }
- }
- return null;
-}
-function findDoubleNewlineIndex(buffer) {
- const newline = 10;
- const carriage = 13;
- for (let i = 0;i < buffer.length - 1; i++) {
- if (buffer[i] === newline && buffer[i + 1] === newline) {
- return i + 2;
- }
- if (buffer[i] === carriage && buffer[i + 1] === carriage) {
- return i + 2;
- }
- if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
- return i + 4;
- }
- }
- return -1;
-}
-var __classPrivateFieldSet = function(receiver, state, value, kind2, f) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "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 kind2 === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
-}, __classPrivateFieldGet = function(receiver, state, kind2, f) {
- if (kind2 === "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 kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
-}, _LineDecoder_carriageReturnIndex;
-var init_line = __esm(() => {
- init_error();
- _LineDecoder_carriageReturnIndex = new WeakMap;
- LineDecoder.NEWLINE_CHARS = new Set([`
-`, "\r"]);
- LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
-});
-
-// node_modules/@anthropic-ai/sdk/internal/stream-utils.mjs
-function ReadableStreamToAsyncIterable(stream) {
- if (stream[Symbol.asyncIterator])
- return stream;
- const reader = stream.getReader();
- return {
- async next() {
- try {
- const result = await reader.read();
- if (result?.done)
- reader.releaseLock();
- return result;
- } catch (e) {
- reader.releaseLock();
- throw e;
- }
- },
- async return() {
- const cancelPromise = reader.cancel();
- reader.releaseLock();
- await cancelPromise;
- return { done: true, value: undefined };
- },
- [Symbol.asyncIterator]() {
- return this;
- }
- };
-}
-
-// node_modules/@anthropic-ai/sdk/streaming.mjs
-async function* _iterSSEMessages(response, controller) {
- if (!response.body) {
- controller.abort();
- throw new AnthropicError(`Attempted to iterate over a response with no body`);
- }
- const sseDecoder = new SSEDecoder;
- const lineDecoder = new LineDecoder;
- const iter = ReadableStreamToAsyncIterable(response.body);
- for await (const sseChunk of iterSSEChunks(iter)) {
- for (const line of lineDecoder.decode(sseChunk)) {
- const sse = sseDecoder.decode(line);
- if (sse)
- yield sse;
- }
- }
- for (const line of lineDecoder.flush()) {
- const sse = sseDecoder.decode(line);
- if (sse)
- yield sse;
- }
-}
-async function* iterSSEChunks(iterator) {
- let data = new Uint8Array;
- for await (const chunk of iterator) {
- if (chunk == null) {
- continue;
- }
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
- let newData = new Uint8Array(data.length + binaryChunk.length);
- newData.set(data);
- newData.set(binaryChunk, data.length);
- data = newData;
- let patternIndex;
- while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
- yield data.slice(0, patternIndex);
- data = data.slice(patternIndex);
- }
- }
- if (data.length > 0) {
- yield data;
- }
-}
-
-class SSEDecoder {
- constructor() {
- this.event = null;
- this.data = [];
- this.chunks = [];
- }
- decode(line) {
- if (line.endsWith("\r")) {
- line = line.substring(0, line.length - 1);
- }
- if (!line) {
- if (!this.event && !this.data.length)
- return null;
- const sse = {
- event: this.event,
- data: this.data.join(`
-`),
- raw: this.chunks
- };
- this.event = null;
- this.data = [];
- this.chunks = [];
- return sse;
- }
- this.chunks.push(line);
- if (line.startsWith(":")) {
- return null;
- }
- let [fieldname, _, value] = partition(line, ":");
- if (value.startsWith(" ")) {
- value = value.substring(1);
- }
- if (fieldname === "event") {
- this.event = value;
- } else if (fieldname === "data") {
- this.data.push(value);
- }
- return null;
- }
-}
-function partition(str, delimiter) {
- const index = str.indexOf(delimiter);
- if (index !== -1) {
- return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
- }
- return [str, "", ""];
-}
-var Stream;
-var init_streaming = __esm(() => {
- init__shims();
- init_error();
- init_line();
- init_core();
- init_error();
- Stream = class Stream {
- constructor(iterator, controller) {
- this.iterator = iterator;
- this.controller = controller;
- }
- static fromSSEResponse(response, controller) {
- let consumed = false;
- async function* iterator() {
- if (consumed) {
- throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
- }
- consumed = true;
- let done = false;
- try {
- for await (const sse of _iterSSEMessages(response, controller)) {
- if (sse.event === "completion") {
- try {
- yield JSON.parse(sse.data);
- } catch (e) {
- console.error(`Could not parse message into JSON:`, sse.data);
- console.error(`From chunk:`, sse.raw);
- throw e;
- }
- }
- if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
- try {
- yield JSON.parse(sse.data);
- } catch (e) {
- console.error(`Could not parse message into JSON:`, sse.data);
- console.error(`From chunk:`, sse.raw);
- throw e;
- }
- }
- if (sse.event === "ping") {
- continue;
- }
- if (sse.event === "error") {
- throw APIError.generate(undefined, `SSE Error: ${sse.data}`, sse.data, createResponseHeaders(response.headers));
- }
- }
- done = true;
- } catch (e) {
- if (e instanceof Error && e.name === "AbortError")
- return;
- throw e;
- } finally {
- if (!done)
- controller.abort();
- }
- }
- return new Stream(iterator, controller);
- }
- static fromReadableStream(readableStream, controller) {
- let consumed = false;
- async function* iterLines() {
- const lineDecoder = new LineDecoder;
- const iter = ReadableStreamToAsyncIterable(readableStream);
- for await (const chunk of iter) {
- for (const line of lineDecoder.decode(chunk)) {
- yield line;
- }
- }
- for (const line of lineDecoder.flush()) {
- yield line;
- }
- }
- async function* iterator() {
- if (consumed) {
- throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
- }
- consumed = true;
- let done = false;
- try {
- for await (const line of iterLines()) {
- if (done)
- continue;
- if (line)
- yield JSON.parse(line);
- }
- done = true;
- } catch (e) {
- if (e instanceof Error && e.name === "AbortError")
- return;
- throw e;
- } finally {
- if (!done)
- controller.abort();
- }
- }
- return new Stream(iterator, controller);
- }
- [Symbol.asyncIterator]() {
- return this.iterator();
- }
- tee() {
- const left = [];
- const right = [];
- const iterator = this.iterator();
- const teeIterator = (queue) => {
- return {
- next: () => {
- if (queue.length === 0) {
- const result = iterator.next();
- left.push(result);
- right.push(result);
- }
- return queue.shift();
- }
- };
- };
- return [
- new Stream(() => teeIterator(left), this.controller),
- new Stream(() => teeIterator(right), this.controller)
- ];
- }
- toReadableStream() {
- const self2 = this;
- let iter;
- const encoder = new TextEncoder;
- return new ReadableStream2({
- async start() {
- iter = self2[Symbol.asyncIterator]();
- },
- async pull(ctrl) {
- try {
- const { value, done } = await iter.next();
- if (done)
- return ctrl.close();
- const bytes = encoder.encode(JSON.stringify(value) + `
-`);
- ctrl.enqueue(bytes);
- } catch (err) {
- ctrl.error(err);
- }
- },
- async cancel() {
- await iter.return?.();
- }
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/sdk/uploads.mjs
-async function toFile(value, name, options) {
- value = await value;
- if (isFileLike(value)) {
- return value;
- }
- if (isResponseLike(value)) {
- const blob = await value.blob();
- name || (name = new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file");
- const data = isBlobLike(blob) ? [await blob.arrayBuffer()] : [blob];
- return new File2(data, name, options);
- }
- const bits = await getBytes(value);
- name || (name = getName(value) ?? "unknown_file");
- if (!options?.type) {
- const type = bits[0]?.type;
- if (typeof type === "string") {
- options = { ...options, type };
- }
- }
- return new File2(bits, name, options);
-}
-async function getBytes(value) {
- let parts = [];
- if (typeof value === "string" || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
- parts.push(value);
- } else if (isBlobLike(value)) {
- parts.push(await value.arrayBuffer());
- } else if (isAsyncIterableIterator(value)) {
- for await (const chunk of value) {
- parts.push(chunk);
- }
- } else {
- throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);
- }
- return parts;
-}
-function propsForError(value) {
- const props = Object.getOwnPropertyNames(value);
- return `[${props.map((p) => `"${p}"`).join(", ")}]`;
-}
-function getName(value) {
- return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop();
-}
-var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", getStringFromMaybeBuffer = (x) => {
- if (typeof x === "string")
- return x;
- if (typeof Buffer !== "undefined" && x instanceof Buffer)
- return String(x);
- return;
-}, isAsyncIterableIterator = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", isMultipartBody = (body) => body && typeof body === "object" && body.body && body[Symbol.toStringTag] === "MultipartBody";
-var init_uploads = __esm(() => {
- init__shims();
- init__shims();
-});
-
-// node_modules/@anthropic-ai/sdk/core.mjs
-async function defaultParseResponse(props) {
- const { response } = props;
- if (props.options.stream) {
- debug("response", response.status, response.url, response.headers, response.body);
- if (props.options.__streamClass) {
- return props.options.__streamClass.fromSSEResponse(response, props.controller);
- }
- return Stream.fromSSEResponse(response, props.controller);
- }
- if (response.status === 204) {
- return null;
- }
- if (props.options.__binaryResponse) {
- return response;
- }
- const contentType = response.headers.get("content-type");
- const isJSON = contentType?.includes("application/json") || contentType?.includes("application/vnd.api+json");
- if (isJSON) {
- const json = await response.json();
- debug("response", response.status, response.url, response.headers, json);
- return _addRequestID(json, response);
- }
- const text = await response.text();
- debug("response", response.status, response.url, response.headers, text);
- return text;
-}
-function _addRequestID(value, response) {
- if (!value || typeof value !== "object" || Array.isArray(value)) {
- return value;
- }
- return Object.defineProperty(value, "_request_id", {
- value: response.headers.get("request-id"),
- enumerable: false
- });
-}
-
-class APIClient {
- constructor({
- baseURL,
- maxRetries = 2,
- timeout = 600000,
- httpAgent,
- fetch: overriddenFetch
- }) {
- this.baseURL = baseURL;
- this.maxRetries = validatePositiveInteger("maxRetries", maxRetries);
- this.timeout = validatePositiveInteger("timeout", timeout);
- this.httpAgent = httpAgent;
- this.fetch = overriddenFetch ?? fetch2;
- }
- authHeaders(opts) {
- return {};
- }
- defaultHeaders(opts) {
- return {
- Accept: "application/json",
- "Content-Type": "application/json",
- "User-Agent": this.getUserAgent(),
- ...getPlatformHeaders(),
- ...this.authHeaders(opts)
- };
- }
- validateHeaders(headers, customHeaders) {}
- defaultIdempotencyKey() {
- return `stainless-node-retry-${uuid4()}`;
- }
- get(path, opts) {
- return this.methodRequest("get", path, opts);
- }
- post(path, opts) {
- return this.methodRequest("post", path, opts);
- }
- patch(path, opts) {
- return this.methodRequest("patch", path, opts);
- }
- put(path, opts) {
- return this.methodRequest("put", path, opts);
- }
- delete(path, opts) {
- return this.methodRequest("delete", path, opts);
- }
- methodRequest(method, path, opts) {
- return this.request(Promise.resolve(opts).then(async (opts2) => {
- const body = opts2 && isBlobLike(opts2?.body) ? new DataView(await opts2.body.arrayBuffer()) : opts2?.body instanceof DataView ? opts2.body : opts2?.body instanceof ArrayBuffer ? new DataView(opts2.body) : opts2 && ArrayBuffer.isView(opts2?.body) ? new DataView(opts2.body.buffer) : opts2?.body;
- return { method, path, ...opts2, body };
- }));
- }
- getAPIList(path, Page, opts) {
- return this.requestAPIList(Page, { method: "get", path, ...opts });
- }
- calculateContentLength(body) {
- if (typeof body === "string") {
- if (typeof Buffer !== "undefined") {
- return Buffer.byteLength(body, "utf8").toString();
- }
- if (typeof TextEncoder !== "undefined") {
- const encoder = new TextEncoder;
- const encoded = encoder.encode(body);
- return encoded.length.toString();
- }
- } else if (ArrayBuffer.isView(body)) {
- return body.byteLength.toString();
- }
- return null;
- }
- buildRequest(options, { retryCount = 0 } = {}) {
- options = { ...options };
- const { method, path, query, headers = {} } = options;
- const body = ArrayBuffer.isView(options.body) || options.__binaryRequest && typeof options.body === "string" ? options.body : isMultipartBody(options.body) ? options.body.body : options.body ? JSON.stringify(options.body, null, 2) : null;
- const contentLength = this.calculateContentLength(body);
- const url = this.buildURL(path, query);
- if ("timeout" in options)
- validatePositiveInteger("timeout", options.timeout);
- options.timeout = options.timeout ?? this.timeout;
- const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
- const minAgentTimeout = options.timeout + 1000;
- if (typeof httpAgent?.options?.timeout === "number" && minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
- httpAgent.options.timeout = minAgentTimeout;
- }
- if (this.idempotencyHeader && method !== "get") {
- if (!options.idempotencyKey)
- options.idempotencyKey = this.defaultIdempotencyKey();
- headers[this.idempotencyHeader] = options.idempotencyKey;
- }
- const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });
- const req = {
- method,
- ...body && { body },
- headers: reqHeaders,
- ...httpAgent && { agent: httpAgent },
- signal: options.signal ?? null
- };
- return { req, url, timeout: options.timeout };
- }
- buildHeaders({ options, headers, contentLength, retryCount }) {
- const reqHeaders = {};
- if (contentLength) {
- reqHeaders["content-length"] = contentLength;
- }
- const defaultHeaders = this.defaultHeaders(options);
- applyHeadersMut(reqHeaders, defaultHeaders);
- applyHeadersMut(reqHeaders, headers);
- if (isMultipartBody(options.body) && kind !== "node") {
- delete reqHeaders["content-type"];
- }
- if (getHeader(defaultHeaders, "x-stainless-retry-count") === undefined && getHeader(headers, "x-stainless-retry-count") === undefined) {
- reqHeaders["x-stainless-retry-count"] = String(retryCount);
- }
- if (getHeader(defaultHeaders, "x-stainless-timeout") === undefined && getHeader(headers, "x-stainless-timeout") === undefined && options.timeout) {
- reqHeaders["x-stainless-timeout"] = String(options.timeout);
- }
- this.validateHeaders(reqHeaders, headers);
- return reqHeaders;
- }
- _calculateNonstreamingTimeout(maxTokens) {
- const defaultTimeout = 10 * 60;
- const expectedTimeout = 60 * 60 * maxTokens / 128000;
- if (expectedTimeout > defaultTimeout) {
- throw new AnthropicError("Streaming is strongly recommended for operations that may take longer than 10 minutes. " + "See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");
- }
- return defaultTimeout * 1000;
- }
- async prepareOptions(options) {}
- async prepareRequest(request, { url, options }) {}
- parseHeaders(headers) {
- return !headers ? {} : (Symbol.iterator in headers) ? Object.fromEntries(Array.from(headers).map((header) => [...header])) : { ...headers };
- }
- makeStatusError(status, error, message, headers) {
- return APIError.generate(status, error, message, headers);
- }
- request(options, remainingRetries = null) {
- return new APIPromise(this.makeRequest(options, remainingRetries));
- }
- async makeRequest(optionsInput, retriesRemaining) {
- const options = await optionsInput;
- const maxRetries = options.maxRetries ?? this.maxRetries;
- if (retriesRemaining == null) {
- retriesRemaining = maxRetries;
- }
- await this.prepareOptions(options);
- const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
- await this.prepareRequest(req, { url, options });
- debug("request", url, options, req.headers);
- if (options.signal?.aborted) {
- throw new APIUserAbortError;
- }
- const controller = new AbortController;
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
- if (response instanceof Error) {
- if (options.signal?.aborted) {
- throw new APIUserAbortError;
- }
- if (retriesRemaining) {
- return this.retryRequest(options, retriesRemaining);
- }
- if (response.name === "AbortError") {
- throw new APIConnectionTimeoutError;
- }
- throw new APIConnectionError({ cause: response });
- }
- const responseHeaders = createResponseHeaders(response.headers);
- if (!response.ok) {
- if (retriesRemaining && this.shouldRetry(response)) {
- const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
- debug(`response (error; ${retryMessage2})`, response.status, url, responseHeaders);
- return this.retryRequest(options, retriesRemaining, responseHeaders);
- }
- const errText = await response.text().catch((e) => castToError(e).message);
- const errJSON = safeJSON(errText);
- const errMessage = errJSON ? undefined : errText;
- const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
- debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);
- const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
- throw err;
- }
- return { response, options, controller };
- }
- requestAPIList(Page, options) {
- const request = this.makeRequest(options, null);
- return new PagePromise(this, request, Page);
- }
- buildURL(path, query) {
- const url = isAbsoluteURL(path) ? new URL(path) : new URL(this.baseURL + (this.baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path));
- const defaultQuery = this.defaultQuery();
- if (!isEmptyObj(defaultQuery)) {
- query = { ...defaultQuery, ...query };
- }
- if (typeof query === "object" && query && !Array.isArray(query)) {
- url.search = this.stringifyQuery(query);
- }
- return url.toString();
- }
- stringifyQuery(query) {
- return Object.entries(query).filter(([_, value]) => typeof value !== "undefined").map(([key, value]) => {
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
- }
- if (value === null) {
- return `${encodeURIComponent(key)}=`;
- }
- throw new AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
- }).join("&");
- }
- async fetchWithTimeout(url, init, ms, controller) {
- const { signal, ...options } = init || {};
- if (signal)
- signal.addEventListener("abort", () => controller.abort());
- const timeout = setTimeout(() => controller.abort(), ms);
- const fetchOptions = {
- signal: controller.signal,
- ...options
- };
- if (fetchOptions.method) {
- fetchOptions.method = fetchOptions.method.toUpperCase();
- }
- const socketKeepAliveInterval = 60 * 1000;
- const keepAliveTimeout = setTimeout(() => {
- if (fetchOptions && fetchOptions?.agent?.sockets) {
- for (const socket of Object.values(fetchOptions?.agent?.sockets).flat()) {
- if (socket?.setKeepAlive) {
- socket.setKeepAlive(true, socketKeepAliveInterval);
- }
- }
- }
- }, socketKeepAliveInterval);
- return this.fetch.call(undefined, url, fetchOptions).finally(() => {
- clearTimeout(timeout);
- clearTimeout(keepAliveTimeout);
- });
- }
- shouldRetry(response) {
- const shouldRetryHeader = response.headers.get("x-should-retry");
- if (shouldRetryHeader === "true")
- return true;
- if (shouldRetryHeader === "false")
- return false;
- if (response.status === 408)
- return true;
- if (response.status === 409)
- return true;
- if (response.status === 429)
- return true;
- if (response.status >= 500)
- return true;
- return false;
- }
- async retryRequest(options, retriesRemaining, responseHeaders) {
- let timeoutMillis;
- const retryAfterMillisHeader = responseHeaders?.["retry-after-ms"];
- if (retryAfterMillisHeader) {
- const timeoutMs = parseFloat(retryAfterMillisHeader);
- if (!Number.isNaN(timeoutMs)) {
- timeoutMillis = timeoutMs;
- }
- }
- const retryAfterHeader = responseHeaders?.["retry-after"];
- if (retryAfterHeader && !timeoutMillis) {
- const timeoutSeconds = parseFloat(retryAfterHeader);
- if (!Number.isNaN(timeoutSeconds)) {
- timeoutMillis = timeoutSeconds * 1000;
- } else {
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
- }
- }
- if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
- const maxRetries = options.maxRetries ?? this.maxRetries;
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
- }
- await sleep(timeoutMillis);
- return this.makeRequest(options, retriesRemaining - 1);
- }
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
- const initialRetryDelay = 0.5;
- const maxRetryDelay = 8;
- const numRetries = maxRetries - retriesRemaining;
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
- const jitter = 1 - Math.random() * 0.25;
- return sleepSeconds * jitter * 1000;
- }
- getUserAgent() {
- return `${this.constructor.name}/JS ${VERSION}`;
- }
-}
-function getBrowserInfo() {
- if (typeof navigator === "undefined" || !navigator) {
- return null;
- }
- const browserPatterns = [
- { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
- ];
- for (const { key, pattern } of browserPatterns) {
- const match = pattern.exec(navigator.userAgent);
- if (match) {
- const major = match[1] || 0;
- const minor = match[2] || 0;
- const patch = match[3] || 0;
- return { browser: key, version: `${major}.${minor}.${patch}` };
- }
- }
- return null;
-}
-function isEmptyObj(obj) {
- if (!obj)
- return true;
- for (const _k in obj)
- return false;
- return true;
-}
-function hasOwn(obj, key) {
- return Object.prototype.hasOwnProperty.call(obj, key);
-}
-function applyHeadersMut(targetHeaders, newHeaders) {
- for (const k in newHeaders) {
- if (!hasOwn(newHeaders, k))
- continue;
- const lowerKey = k.toLowerCase();
- if (!lowerKey)
- continue;
- const val = newHeaders[k];
- if (val === null) {
- delete targetHeaders[lowerKey];
- } else if (val !== undefined) {
- targetHeaders[lowerKey] = val;
- }
- }
-}
-function debug(action, ...args) {
- if (typeof process !== "undefined" && process?.env?.["DEBUG"] === "true") {
- console.log(`Anthropic:DEBUG:${action}`, ...args);
- }
-}
-var __classPrivateFieldSet2 = function(receiver, state, value, kind2, f) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "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 kind2 === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
-}, __classPrivateFieldGet2 = function(receiver, state, kind2, f) {
- if (kind2 === "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 kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
-}, _AbstractPage_client, APIPromise, AbstractPage, PagePromise, createResponseHeaders = (headers) => {
- return new Proxy(Object.fromEntries(headers.entries()), {
- get(target, name) {
- const key = name.toString();
- return target[key.toLowerCase()] || target[key];
- }
- });
-}, requestOptionsKeys, isRequestOptions = (obj) => {
- return typeof obj === "object" && obj !== null && !isEmptyObj(obj) && Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k));
-}, getPlatformProperties = () => {
- if (typeof Deno !== "undefined" && Deno.build != null) {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION,
- "X-Stainless-OS": normalizePlatform(Deno.build.os),
- "X-Stainless-Arch": normalizeArch(Deno.build.arch),
- "X-Stainless-Runtime": "deno",
- "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
- };
- }
- if (typeof EdgeRuntime !== "undefined") {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": `other:${EdgeRuntime}`,
- "X-Stainless-Runtime": "edge",
- "X-Stainless-Runtime-Version": process.version
- };
- }
- if (Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]") {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION,
- "X-Stainless-OS": normalizePlatform(process.platform),
- "X-Stainless-Arch": normalizeArch(process.arch),
- "X-Stainless-Runtime": "node",
- "X-Stainless-Runtime-Version": process.version
- };
- }
- const browserInfo = getBrowserInfo();
- if (browserInfo) {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": "unknown",
- "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
- "X-Stainless-Runtime-Version": browserInfo.version
- };
- }
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": "unknown",
- "X-Stainless-Runtime": "unknown",
- "X-Stainless-Runtime-Version": "unknown"
- };
-}, normalizeArch = (arch) => {
- if (arch === "x32")
- return "x32";
- if (arch === "x86_64" || arch === "x64")
- return "x64";
- if (arch === "arm")
- return "arm";
- if (arch === "aarch64" || arch === "arm64")
- return "arm64";
- if (arch)
- return `other:${arch}`;
- return "unknown";
-}, normalizePlatform = (platform) => {
- platform = platform.toLowerCase();
- if (platform.includes("ios"))
- return "iOS";
- if (platform === "android")
- return "Android";
- if (platform === "darwin")
- return "MacOS";
- if (platform === "win32")
- return "Windows";
- if (platform === "freebsd")
- return "FreeBSD";
- if (platform === "openbsd")
- return "OpenBSD";
- if (platform === "linux")
- return "Linux";
- if (platform)
- return `Other:${platform}`;
- return "Unknown";
-}, _platformHeaders, getPlatformHeaders = () => {
- return _platformHeaders ?? (_platformHeaders = getPlatformProperties());
-}, safeJSON = (text) => {
- try {
- return JSON.parse(text);
- } catch (err) {
- return;
- }
-}, startsWithSchemeRegexp, isAbsoluteURL = (url) => {
- return startsWithSchemeRegexp.test(url);
-}, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), validatePositiveInteger = (name, n) => {
- if (typeof n !== "number" || !Number.isInteger(n)) {
- throw new AnthropicError(`${name} must be an integer`);
- }
- if (n < 0) {
- throw new AnthropicError(`${name} must be a positive integer`);
- }
- return n;
-}, castToError = (err) => {
- if (err instanceof Error)
- return err;
- if (typeof err === "object" && err !== null) {
- try {
- return new Error(JSON.stringify(err));
- } catch {}
- }
- return new Error(String(err));
-}, readEnv = (env) => {
- if (typeof process !== "undefined") {
- return process.env?.[env]?.trim() ?? undefined;
- }
- if (typeof Deno !== "undefined") {
- return Deno.env?.get?.(env)?.trim();
- }
- return;
-}, uuid4 = () => {
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
- const r = Math.random() * 16 | 0;
- const v = c === "x" ? r : r & 3 | 8;
- return v.toString(16);
- });
-}, isRunningInBrowser = () => {
- return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined";
-}, isHeadersProtocol = (headers) => {
- return typeof headers?.get === "function";
-}, getHeader = (headers, header) => {
- const lowerCasedHeader = header.toLowerCase();
- if (isHeadersProtocol(headers)) {
- const intercapsHeader = header[0]?.toUpperCase() + header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());
- for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {
- const value = headers.get(key);
- if (value) {
- return value;
- }
- }
- }
- for (const [key, value] of Object.entries(headers)) {
- if (key.toLowerCase() === lowerCasedHeader) {
- if (Array.isArray(value)) {
- if (value.length <= 1)
- return value[0];
- console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);
- return value[0];
- }
- return value;
- }
- }
- return;
-};
-var init_core = __esm(() => {
- init_streaming();
- init_error();
- init__shims();
- init_uploads();
- APIPromise = class APIPromise extends Promise {
- constructor(responsePromise, parseResponse = defaultParseResponse) {
- super((resolve) => {
- resolve(null);
- });
- this.responsePromise = responsePromise;
- this.parseResponse = parseResponse;
- }
- _thenUnwrap(transform) {
- return new APIPromise(this.responsePromise, async (props) => _addRequestID(transform(await this.parseResponse(props), props), props.response));
- }
- asResponse() {
- return this.responsePromise.then((p) => p.response);
- }
- async withResponse() {
- const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
- return { data, response, request_id: response.headers.get("request-id") };
- }
- parse() {
- if (!this.parsedPromise) {
- this.parsedPromise = this.responsePromise.then(this.parseResponse);
- }
- return this.parsedPromise;
- }
- then(onfulfilled, onrejected) {
- return this.parse().then(onfulfilled, onrejected);
- }
- catch(onrejected) {
- return this.parse().catch(onrejected);
- }
- finally(onfinally) {
- return this.parse().finally(onfinally);
- }
- };
- AbstractPage = class AbstractPage {
- constructor(client, response, body, options) {
- _AbstractPage_client.set(this, undefined);
- __classPrivateFieldSet2(this, _AbstractPage_client, client, "f");
- this.options = options;
- this.response = response;
- this.body = body;
- }
- hasNextPage() {
- const items = this.getPaginatedItems();
- if (!items.length)
- return false;
- return this.nextPageInfo() != null;
- }
- async getNextPage() {
- const nextInfo = this.nextPageInfo();
- if (!nextInfo) {
- throw new AnthropicError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
- }
- const nextOptions = { ...this.options };
- if ("params" in nextInfo && typeof nextOptions.query === "object") {
- nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
- } else if ("url" in nextInfo) {
- const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
- for (const [key, value] of params) {
- nextInfo.url.searchParams.set(key, value);
- }
- nextOptions.query = undefined;
- nextOptions.path = nextInfo.url.toString();
- }
- return await __classPrivateFieldGet2(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
- }
- async* iterPages() {
- let page = this;
- yield page;
- while (page.hasNextPage()) {
- page = await page.getNextPage();
- yield page;
- }
- }
- async* [(_AbstractPage_client = new WeakMap, Symbol.asyncIterator)]() {
- for await (const page of this.iterPages()) {
- for (const item of page.getPaginatedItems()) {
- yield item;
- }
- }
- }
- };
- PagePromise = class PagePromise extends APIPromise {
- constructor(client, request, Page) {
- super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options));
- }
- async* [Symbol.asyncIterator]() {
- const page = await this;
- for await (const item of page) {
- yield item;
- }
- }
- };
- requestOptionsKeys = {
- method: true,
- path: true,
- query: true,
- body: true,
- headers: true,
- maxRetries: true,
- stream: true,
- timeout: true,
- httpAgent: true,
- signal: true,
- idempotencyKey: true,
- __binaryRequest: true,
- __binaryResponse: true,
- __streamClass: true
- };
- startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
-});
-
-// node_modules/@anthropic-ai/sdk/pagination.mjs
-var Page;
-var init_pagination = __esm(() => {
- init_core();
- Page = class Page extends AbstractPage {
- constructor(client, response, body, options) {
- super(client, response, body, options);
- this.data = body.data || [];
- this.has_more = body.has_more || false;
- this.first_id = body.first_id || null;
- this.last_id = body.last_id || null;
- }
- getPaginatedItems() {
- return this.data ?? [];
- }
- hasNextPage() {
- if (this.has_more === false) {
- return false;
- }
- return super.hasNextPage();
- }
- nextPageParams() {
- const info = this.nextPageInfo();
- if (!info)
- return null;
- if ("params" in info)
- return info.params;
- const params = Object.fromEntries(info.url.searchParams);
- if (!Object.keys(params).length)
- return null;
- return params;
- }
- nextPageInfo() {
- if (this.options.query?.["before_id"]) {
- const firstId = this.first_id;
- if (!firstId) {
- return null;
- }
- return {
- params: {
- before_id: firstId
- }
- };
- }
- const cursor = this.last_id;
- if (!cursor) {
- return null;
- }
- return {
- params: {
- after_id: cursor
- }
- };
- }
- };
-});
-
-// node_modules/@anthropic-ai/sdk/resources/shared.mjs
-var init_shared = () => {};
-
-// node_modules/@anthropic-ai/sdk/resource.mjs
-class APIResource {
- constructor(client) {
- this._client = client;
- }
-}
-
-// node_modules/@anthropic-ai/sdk/resources/beta/models.mjs
-var Models, BetaModelInfosPage;
-var init_models = __esm(() => {
- init_core();
- init_pagination();
- Models = class Models extends APIResource {
- retrieve(modelId, options) {
- return this._client.get(`/v1/models/${modelId}?beta=true`, options);
- }
- list(query = {}, options) {
- if (isRequestOptions(query)) {
- return this.list({}, query);
- }
- return this._client.getAPIList("/v1/models?beta=true", BetaModelInfosPage, { query, ...options });
- }
- };
- BetaModelInfosPage = class BetaModelInfosPage extends Page {
- };
- Models.BetaModelInfosPage = BetaModelInfosPage;
-});
-
-// node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs
-var JSONLDecoder;
-var init_jsonl = __esm(() => {
- init_error();
- init_line();
- JSONLDecoder = class JSONLDecoder {
- constructor(iterator, controller) {
- this.iterator = iterator;
- this.controller = controller;
- }
- async* decoder() {
- const lineDecoder = new LineDecoder;
- for await (const chunk of this.iterator) {
- for (const line of lineDecoder.decode(chunk)) {
- yield JSON.parse(line);
- }
- }
- for (const line of lineDecoder.flush()) {
- yield JSON.parse(line);
- }
- }
- [Symbol.asyncIterator]() {
- return this.decoder();
- }
- static fromResponse(response, controller) {
- if (!response.body) {
- controller.abort();
- throw new AnthropicError(`Attempted to iterate over a response with no body`);
- }
- return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller);
- }
- };
-});
-
-// node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs
-var Batches, BetaMessageBatchesPage;
-var init_batches = __esm(() => {
- init_core();
- init_pagination();
- init_jsonl();
- init_error();
- Batches = class Batches extends APIResource {
- create(params, options) {
- const { betas, ...body } = params;
- return this._client.post("/v1/messages/batches?beta=true", {
- body,
- ...options,
- headers: {
- "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
- ...options?.headers
- }
- });
- }
- retrieve(messageBatchId, params = {}, options) {
- if (isRequestOptions(params)) {
- return this.retrieve(messageBatchId, {}, params);
- }
- const { betas } = params;
- return this._client.get(`/v1/messages/batches/${messageBatchId}?beta=true`, {
- ...options,
- headers: {
- "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
- ...options?.headers
- }
- });
- }
- list(params = {}, options) {
- if (isRequestOptions(params)) {
- return this.list({}, params);
- }
- const { betas, ...query } = params;
- return this._client.getAPIList("/v1/messages/batches?beta=true", BetaMessageBatchesPage, {
- query,
- ...options,
- headers: {
- "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
- ...options?.headers
- }
- });
- }
- delete(messageBatchId, params = {}, options) {
- if (isRequestOptions(params)) {
- return this.delete(messageBatchId, {}, params);
- }
- const { betas } = params;
- return this._client.delete(`/v1/messages/batches/${messageBatchId}?beta=true`, {
- ...options,
- headers: {
- "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
- ...options?.headers
- }
- });
- }
- cancel(messageBatchId, params = {}, options) {
- if (isRequestOptions(params)) {
- return this.cancel(messageBatchId, {}, params);
- }
- const { betas } = params;
- return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel?beta=true`, {
- ...options,
- headers: {
- "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
- ...options?.headers
- }
- });
- }
- async results(messageBatchId, params = {}, options) {
- if (isRequestOptions(params)) {
- return this.results(messageBatchId, {}, params);
- }
- const batch = await this.retrieve(messageBatchId);
- if (!batch.results_url) {
- throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
- }
- const { betas } = params;
- return this._client.get(batch.results_url, {
- ...options,
- headers: {
- "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
- Accept: "application/binary",
- ...options?.headers
- },
- __binaryResponse: true
- })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));
- }
- };
- BetaMessageBatchesPage = class BetaMessageBatchesPage extends Page {
- };
- Batches.BetaMessageBatchesPage = BetaMessageBatchesPage;
-});
-
-// node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs
-var tokenize = (input) => {
- let current = 0;
- let tokens = [];
- while (current < input.length) {
- let char = input[current];
- if (char === "\\") {
- current++;
- continue;
- }
- if (char === "{") {
- tokens.push({
- type: "brace",
- value: "{"
- });
- current++;
- continue;
- }
- if (char === "}") {
- tokens.push({
- type: "brace",
- value: "}"
- });
- current++;
- continue;
- }
- if (char === "[") {
- tokens.push({
- type: "paren",
- value: "["
- });
- current++;
- continue;
- }
- if (char === "]") {
- tokens.push({
- type: "paren",
- value: "]"
- });
- current++;
- continue;
- }
- if (char === ":") {
- tokens.push({
- type: "separator",
- value: ":"
- });
- current++;
- continue;
- }
- if (char === ",") {
- tokens.push({
- type: "delimiter",
- value: ","
- });
- current++;
- continue;
- }
- if (char === '"') {
- let value = "";
- let danglingQuote = false;
- char = input[++current];
- while (char !== '"') {
- if (current === input.length) {
- danglingQuote = true;
- break;
- }
- if (char === "\\") {
- current++;
- if (current === input.length) {
- danglingQuote = true;
- break;
- }
- value += char + input[current];
- char = input[++current];
- } else {
- value += char;
- char = input[++current];
- }
- }
- char = input[++current];
- if (!danglingQuote) {
- tokens.push({
- type: "string",
- value
- });
- }
- continue;
- }
- let WHITESPACE = /\s/;
- if (char && WHITESPACE.test(char)) {
- current++;
- continue;
- }
- let NUMBERS = /[0-9]/;
- if (char && NUMBERS.test(char) || char === "-" || char === ".") {
- let value = "";
- if (char === "-") {
- value += char;
- char = input[++current];
- }
- while (char && NUMBERS.test(char) || char === ".") {
- value += char;
- char = input[++current];
- }
- tokens.push({
- type: "number",
- value
- });
- continue;
- }
- let LETTERS = /[a-z]/i;
- if (char && LETTERS.test(char)) {
- let value = "";
- while (char && LETTERS.test(char)) {
- if (current === input.length) {
- break;
- }
- value += char;
- char = input[++current];
- }
- if (value == "true" || value == "false" || value === "null") {
- tokens.push({
- type: "name",
- value
- });
- } else {
- current++;
- continue;
- }
- continue;
- }
- current++;
- }
- return tokens;
-}, strip = (tokens) => {
- if (tokens.length === 0) {
- return tokens;
- }
- let lastToken = tokens[tokens.length - 1];
- switch (lastToken.type) {
- case "separator":
- tokens = tokens.slice(0, tokens.length - 1);
- return strip(tokens);
- break;
- case "number":
- let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
- if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip(tokens);
- }
- case "string":
- let tokenBeforeTheLastToken = tokens[tokens.length - 2];
- if (tokenBeforeTheLastToken?.type === "delimiter") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip(tokens);
- } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip(tokens);
- }
- break;
- case "delimiter":
- tokens = tokens.slice(0, tokens.length - 1);
- return strip(tokens);
- break;
- }
- return tokens;
-}, unstrip = (tokens) => {
- let tail = [];
- tokens.map((token) => {
- if (token.type === "brace") {
- if (token.value === "{") {
- tail.push("}");
- } else {
- tail.splice(tail.lastIndexOf("}"), 1);
- }
- }
- if (token.type === "paren") {
- if (token.value === "[") {
- tail.push("]");
- } else {
- tail.splice(tail.lastIndexOf("]"), 1);
- }
- }
- });
- if (tail.length > 0) {
- tail.reverse().map((item) => {
- if (item === "}") {
- tokens.push({
- type: "brace",
- value: "}"
- });
- } else if (item === "]") {
- tokens.push({
- type: "paren",
- value: "]"
- });
- }
- });
- }
- return tokens;
-}, generate = (tokens) => {
- let output = "";
- tokens.map((token) => {
- switch (token.type) {
- case "string":
- output += '"' + token.value + '"';
- break;
- default:
- output += token.value;
- break;
- }
- });
- return output;
-}, partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
-var init_parser = () => {};
-
-// node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs
-function checkNever(x) {}
-var __classPrivateFieldSet3 = function(receiver, state, value, kind2, f) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "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 kind2 === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
-}, __classPrivateFieldGet3 = function(receiver, state, kind2, f) {
- if (kind2 === "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 kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
-}, _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage, JSON_BUF_PROPERTY = "__json_buf", BetaMessageStream;
-var init_BetaMessageStream = __esm(() => {
- init_error();
- init_streaming();
- init_parser();
- BetaMessageStream = class BetaMessageStream {
- constructor() {
- _BetaMessageStream_instances.add(this);
- this.messages = [];
- this.receivedMessages = [];
- _BetaMessageStream_currentMessageSnapshot.set(this, undefined);
- this.controller = new AbortController;
- _BetaMessageStream_connectedPromise.set(this, undefined);
- _BetaMessageStream_resolveConnectedPromise.set(this, () => {});
- _BetaMessageStream_rejectConnectedPromise.set(this, () => {});
- _BetaMessageStream_endPromise.set(this, undefined);
- _BetaMessageStream_resolveEndPromise.set(this, () => {});
- _BetaMessageStream_rejectEndPromise.set(this, () => {});
- _BetaMessageStream_listeners.set(this, {});
- _BetaMessageStream_ended.set(this, false);
- _BetaMessageStream_errored.set(this, false);
- _BetaMessageStream_aborted.set(this, false);
- _BetaMessageStream_catchingPromiseCreated.set(this, false);
- _BetaMessageStream_response.set(this, undefined);
- _BetaMessageStream_request_id.set(this, undefined);
- _BetaMessageStream_handleError.set(this, (error) => {
- __classPrivateFieldSet3(this, _BetaMessageStream_errored, true, "f");
- if (error instanceof Error && error.name === "AbortError") {
- error = new APIUserAbortError;
- }
- if (error instanceof APIUserAbortError) {
- __classPrivateFieldSet3(this, _BetaMessageStream_aborted, true, "f");
- return this._emit("abort", error);
- }
- if (error instanceof AnthropicError) {
- return this._emit("error", error);
- }
- if (error instanceof Error) {
- const anthropicError = new AnthropicError(error.message);
- anthropicError.cause = error;
- return this._emit("error", anthropicError);
- }
- return this._emit("error", new AnthropicError(String(error)));
- });
- __classPrivateFieldSet3(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => {
- __classPrivateFieldSet3(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f");
- __classPrivateFieldSet3(this, _BetaMessageStream_rejectConnectedPromise, reject, "f");
- }), "f");
- __classPrivateFieldSet3(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => {
- __classPrivateFieldSet3(this, _BetaMessageStream_resolveEndPromise, resolve, "f");
- __classPrivateFieldSet3(this, _BetaMessageStream_rejectEndPromise, reject, "f");
- }), "f");
- __classPrivateFieldGet3(this, _BetaMessageStream_connectedPromise, "f").catch(() => {});
- __classPrivateFieldGet3(this, _BetaMessageStream_endPromise, "f").catch(() => {});
- }
- get response() {
- return __classPrivateFieldGet3(this, _BetaMessageStream_response, "f");
- }
- get request_id() {
- return __classPrivateFieldGet3(this, _BetaMessageStream_request_id, "f");
- }
- async withResponse() {
- const response = await __classPrivateFieldGet3(this, _BetaMessageStream_connectedPromise, "f");
- if (!response) {
- throw new Error("Could not resolve a `Response` object");
- }
- return {
- data: this,
- response,
- request_id: response.headers.get("request-id")
- };
- }
- static fromReadableStream(stream) {
- const runner = new BetaMessageStream;
- runner._run(() => runner._fromReadableStream(stream));
- return runner;
- }
- static createMessage(messages, params, options) {
- const runner = new BetaMessageStream;
- for (const message of params.messages) {
- runner._addMessageParam(message);
- }
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
- return runner;
- }
- _run(executor) {
- executor().then(() => {
- this._emitFinal();
- this._emit("end");
- }, __classPrivateFieldGet3(this, _BetaMessageStream_handleError, "f"));
- }
- _addMessageParam(message) {
- this.messages.push(message);
- }
- _addMessage(message, emit = true) {
- this.receivedMessages.push(message);
- if (emit) {
- this._emit("message", message);
- }
- }
- async _createMessage(messages, params, options) {
- const signal = options?.signal;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- signal.addEventListener("abort", () => this.controller.abort());
- }
- __classPrivateFieldGet3(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
- const { response, data: stream } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse();
- this._connected(response);
- for await (const event of stream) {
- __classPrivateFieldGet3(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
- }
- if (stream.controller.signal?.aborted) {
- throw new APIUserAbortError;
- }
- __classPrivateFieldGet3(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
- }
- _connected(response) {
- if (this.ended)
- return;
- __classPrivateFieldSet3(this, _BetaMessageStream_response, response, "f");
- __classPrivateFieldSet3(this, _BetaMessageStream_request_id, response?.headers.get("request-id"), "f");
- __classPrivateFieldGet3(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response);
- this._emit("connect");
- }
- get ended() {
- return __classPrivateFieldGet3(this, _BetaMessageStream_ended, "f");
- }
- get errored() {
- return __classPrivateFieldGet3(this, _BetaMessageStream_errored, "f");
- }
- get aborted() {
- return __classPrivateFieldGet3(this, _BetaMessageStream_aborted, "f");
- }
- abort() {
- this.controller.abort();
- }
- on(event, listener) {
- const listeners = __classPrivateFieldGet3(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet3(this, _BetaMessageStream_listeners, "f")[event] = []);
- listeners.push({ listener });
- return this;
- }
- off(event, listener) {
- const listeners = __classPrivateFieldGet3(this, _BetaMessageStream_listeners, "f")[event];
- if (!listeners)
- return this;
- const index = listeners.findIndex((l) => l.listener === listener);
- if (index >= 0)
- listeners.splice(index, 1);
- return this;
- }
- once(event, listener) {
- const listeners = __classPrivateFieldGet3(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet3(this, _BetaMessageStream_listeners, "f")[event] = []);
- listeners.push({ listener, once: true });
- return this;
- }
- emitted(event) {
- return new Promise((resolve, reject) => {
- __classPrivateFieldSet3(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
- if (event !== "error")
- this.once("error", reject);
- this.once(event, resolve);
- });
- }
- async done() {
- __classPrivateFieldSet3(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
- await __classPrivateFieldGet3(this, _BetaMessageStream_endPromise, "f");
- }
- get currentMessage() {
- return __classPrivateFieldGet3(this, _BetaMessageStream_currentMessageSnapshot, "f");
- }
- async finalMessage() {
- await this.done();
- return __classPrivateFieldGet3(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this);
- }
- async finalText() {
- await this.done();
- return __classPrivateFieldGet3(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this);
- }
- _emit(event, ...args) {
- if (__classPrivateFieldGet3(this, _BetaMessageStream_ended, "f"))
- return;
- if (event === "end") {
- __classPrivateFieldSet3(this, _BetaMessageStream_ended, true, "f");
- __classPrivateFieldGet3(this, _BetaMessageStream_resolveEndPromise, "f").call(this);
- }
- const listeners = __classPrivateFieldGet3(this, _BetaMessageStream_listeners, "f")[event];
- if (listeners) {
- __classPrivateFieldGet3(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
- listeners.forEach(({ listener }) => listener(...args));
- }
- if (event === "abort") {
- const error = args[0];
- if (!__classPrivateFieldGet3(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
- Promise.reject(error);
- }
- __classPrivateFieldGet3(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
- __classPrivateFieldGet3(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
- this._emit("end");
- return;
- }
- if (event === "error") {
- const error = args[0];
- if (!__classPrivateFieldGet3(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
- Promise.reject(error);
- }
- __classPrivateFieldGet3(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
- __classPrivateFieldGet3(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
- this._emit("end");
- }
- }
- _emitFinal() {
- const finalMessage = this.receivedMessages.at(-1);
- if (finalMessage) {
- this._emit("finalMessage", __classPrivateFieldGet3(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this));
- }
- }
- async _fromReadableStream(readableStream, options) {
- const signal = options?.signal;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- signal.addEventListener("abort", () => this.controller.abort());
- }
- __classPrivateFieldGet3(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
- this._connected(null);
- const stream = Stream.fromReadableStream(readableStream, this.controller);
- for await (const event of stream) {
- __classPrivateFieldGet3(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
- }
- if (stream.controller.signal?.aborted) {
- throw new APIUserAbortError;
- }
- __classPrivateFieldGet3(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
- }
- [(_BetaMessageStream_currentMessageSnapshot = new WeakMap, _BetaMessageStream_connectedPromise = new WeakMap, _BetaMessageStream_resolveConnectedPromise = new WeakMap, _BetaMessageStream_rejectConnectedPromise = new WeakMap, _BetaMessageStream_endPromise = new WeakMap, _BetaMessageStream_resolveEndPromise = new WeakMap, _BetaMessageStream_rejectEndPromise = new WeakMap, _BetaMessageStream_listeners = new WeakMap, _BetaMessageStream_ended = new WeakMap, _BetaMessageStream_errored = new WeakMap, _BetaMessageStream_aborted = new WeakMap, _BetaMessageStream_catchingPromiseCreated = new WeakMap, _BetaMessageStream_response = new WeakMap, _BetaMessageStream_request_id = new WeakMap, _BetaMessageStream_handleError = new WeakMap, _BetaMessageStream_instances = new WeakSet, _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage2() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError("stream ended without producing a Message with role=assistant");
- }
- return this.receivedMessages.at(-1);
- }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText2() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError("stream ended without producing a Message with role=assistant");
- }
- const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text);
- if (textBlocks.length === 0) {
- throw new AnthropicError("stream ended without producing a content block with type=text");
- }
- return textBlocks.join(" ");
- }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest2() {
- if (this.ended)
- return;
- __classPrivateFieldSet3(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f");
- }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent2(event) {
- if (this.ended)
- return;
- const messageSnapshot = __classPrivateFieldGet3(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event);
- this._emit("streamEvent", event, messageSnapshot);
- switch (event.type) {
- case "content_block_delta": {
- const content = messageSnapshot.content.at(-1);
- switch (event.delta.type) {
- case "text_delta": {
- if (content.type === "text") {
- this._emit("text", event.delta.text, content.text || "");
- }
- break;
- }
- case "citations_delta": {
- if (content.type === "text") {
- this._emit("citation", event.delta.citation, content.citations ?? []);
- }
- break;
- }
- case "input_json_delta": {
- if (content.type === "tool_use" && content.input) {
- this._emit("inputJson", event.delta.partial_json, content.input);
- }
- break;
- }
- case "thinking_delta": {
- if (content.type === "thinking") {
- this._emit("thinking", event.delta.thinking, content.thinking);
- }
- break;
- }
- case "signature_delta": {
- if (content.type === "thinking") {
- this._emit("signature", content.signature);
- }
- break;
- }
- default:
- checkNever(event.delta);
- }
- break;
- }
- case "message_stop": {
- this._addMessageParam(messageSnapshot);
- this._addMessage(messageSnapshot, true);
- break;
- }
- case "content_block_stop": {
- this._emit("contentBlock", messageSnapshot.content.at(-1));
- break;
- }
- case "message_start": {
- __classPrivateFieldSet3(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f");
- break;
- }
- case "content_block_start":
- case "message_delta":
- break;
- }
- }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest2() {
- if (this.ended) {
- throw new AnthropicError(`stream has ended, this shouldn't happen`);
- }
- const snapshot = __classPrivateFieldGet3(this, _BetaMessageStream_currentMessageSnapshot, "f");
- if (!snapshot) {
- throw new AnthropicError(`request ended without sending any chunks`);
- }
- __classPrivateFieldSet3(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f");
- return snapshot;
- }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage2(event) {
- let snapshot = __classPrivateFieldGet3(this, _BetaMessageStream_currentMessageSnapshot, "f");
- if (event.type === "message_start") {
- if (snapshot) {
- throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
- }
- return event.message;
- }
- if (!snapshot) {
- throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
- }
- switch (event.type) {
- case "message_stop":
- return snapshot;
- case "message_delta":
- snapshot.stop_reason = event.delta.stop_reason;
- snapshot.stop_sequence = event.delta.stop_sequence;
- snapshot.usage.output_tokens = event.usage.output_tokens;
- return snapshot;
- case "content_block_start":
- snapshot.content.push(event.content_block);
- return snapshot;
- case "content_block_delta": {
- const snapshotContent = snapshot.content.at(event.index);
- switch (event.delta.type) {
- case "text_delta": {
- if (snapshotContent?.type === "text") {
- snapshotContent.text += event.delta.text;
- }
- break;
- }
- case "citations_delta": {
- if (snapshotContent?.type === "text") {
- snapshotContent.citations ?? (snapshotContent.citations = []);
- snapshotContent.citations.push(event.delta.citation);
- }
- break;
- }
- case "input_json_delta": {
- if (snapshotContent?.type === "tool_use") {
- let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || "";
- jsonBuf += event.delta.partial_json;
- Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY, {
- value: jsonBuf,
- enumerable: false,
- writable: true
- });
- if (jsonBuf) {
- snapshotContent.input = partialParse(jsonBuf);
- }
- }
- break;
- }
- case "thinking_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshotContent.thinking += event.delta.thinking;
- }
- break;
- }
- case "signature_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshotContent.signature = event.delta.signature;
- }
- break;
- }
- default:
- checkNever(event.delta);
- }
- return snapshot;
- }
- case "content_block_stop":
- return snapshot;
- }
- }, Symbol.asyncIterator)]() {
- const pushQueue = [];
- const readQueue = [];
- let done = false;
- this.on("streamEvent", (event) => {
- const reader = readQueue.shift();
- if (reader) {
- reader.resolve(event);
- } else {
- pushQueue.push(event);
- }
- });
- this.on("end", () => {
- done = true;
- for (const reader of readQueue) {
- reader.resolve(undefined);
- }
- readQueue.length = 0;
- });
- this.on("abort", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- this.on("error", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- return {
- next: async () => {
- if (!pushQueue.length) {
- if (done) {
- return { value: undefined, done: true };
- }
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
- }
- const chunk = pushQueue.shift();
- return { value: chunk, done: false };
- },
- return: async () => {
- this.abort();
- return { value: undefined, done: true };
- }
- };
- }
- toReadableStream() {
- const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
- return stream.toReadableStream();
- }
- };
-});
-
-// node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs
-var DEPRECATED_MODELS, Messages;
-var init_messages = __esm(() => {
- init_batches();
- init_batches();
- init_BetaMessageStream();
- DEPRECATED_MODELS = {
- "claude-1.3": "November 6th, 2024",
- "claude-1.3-100k": "November 6th, 2024",
- "claude-instant-1.1": "November 6th, 2024",
- "claude-instant-1.1-100k": "November 6th, 2024",
- "claude-instant-1.2": "November 6th, 2024",
- "claude-3-sonnet-20240229": "July 21st, 2025",
- "claude-2.1": "July 21st, 2025",
- "claude-2.0": "July 21st, 2025"
- };
- Messages = class Messages extends APIResource {
- constructor() {
- super(...arguments);
- this.batches = new Batches(this._client);
- }
- create(params, options) {
- const { betas, ...body } = params;
- if (body.model in DEPRECATED_MODELS) {
- console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}
-Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
- }
- return this._client.post("/v1/messages?beta=true", {
- body,
- timeout: this._client._options.timeout ?? (body.stream ? 600000 : this._client._calculateNonstreamingTimeout(body.max_tokens)),
- ...options,
- headers: {
- ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined,
- ...options?.headers
- },
- stream: params.stream ?? false
- });
- }
- stream(body, options) {
- return BetaMessageStream.createMessage(this, body, options);
- }
- countTokens(params, options) {
- const { betas, ...body } = params;
- return this._client.post("/v1/messages/count_tokens?beta=true", {
- body,
- ...options,
- headers: {
- "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString(),
- ...options?.headers
- }
- });
- }
- };
- Messages.Batches = Batches;
- Messages.BetaMessageBatchesPage = BetaMessageBatchesPage;
-});
-
-// node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs
-var Beta;
-var init_beta = __esm(() => {
- init_models();
- init_models();
- init_messages();
- init_messages();
- Beta = class Beta extends APIResource {
- constructor() {
- super(...arguments);
- this.models = new Models(this._client);
- this.messages = new Messages(this._client);
- }
- };
- Beta.Models = Models;
- Beta.BetaModelInfosPage = BetaModelInfosPage;
- Beta.Messages = Messages;
-});
-
-// node_modules/@anthropic-ai/sdk/resources/completions.mjs
-var Completions;
-var init_completions = __esm(() => {
- Completions = class Completions extends APIResource {
- create(body, options) {
- return this._client.post("/v1/complete", {
- body,
- timeout: this._client._options.timeout ?? 600000,
- ...options,
- stream: body.stream ?? false
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs
-var Batches2, MessageBatchesPage;
-var init_batches2 = __esm(() => {
- init_core();
- init_pagination();
- init_jsonl();
- init_error();
- Batches2 = class Batches2 extends APIResource {
- create(body, options) {
- return this._client.post("/v1/messages/batches", { body, ...options });
- }
- retrieve(messageBatchId, options) {
- return this._client.get(`/v1/messages/batches/${messageBatchId}`, options);
- }
- list(query = {}, options) {
- if (isRequestOptions(query)) {
- return this.list({}, query);
- }
- return this._client.getAPIList("/v1/messages/batches", MessageBatchesPage, { query, ...options });
- }
- delete(messageBatchId, options) {
- return this._client.delete(`/v1/messages/batches/${messageBatchId}`, options);
- }
- cancel(messageBatchId, options) {
- return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel`, options);
- }
- async results(messageBatchId, options) {
- const batch = await this.retrieve(messageBatchId);
- if (!batch.results_url) {
- throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
- }
- return this._client.get(batch.results_url, {
- ...options,
- headers: {
- Accept: "application/binary",
- ...options?.headers
- },
- __binaryResponse: true
- })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));
- }
- };
- MessageBatchesPage = class MessageBatchesPage extends Page {
- };
- Batches2.MessageBatchesPage = MessageBatchesPage;
-});
-
-// node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs
-function checkNever2(x) {}
-var __classPrivateFieldSet4 = function(receiver, state, value, kind2, f) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "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 kind2 === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
-}, __classPrivateFieldGet4 = function(receiver, state, kind2, f) {
- if (kind2 === "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 kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
-}, _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage, JSON_BUF_PROPERTY2 = "__json_buf", MessageStream;
-var init_MessageStream = __esm(() => {
- init_error();
- init_streaming();
- init_parser();
- MessageStream = class MessageStream {
- constructor() {
- _MessageStream_instances.add(this);
- this.messages = [];
- this.receivedMessages = [];
- _MessageStream_currentMessageSnapshot.set(this, undefined);
- this.controller = new AbortController;
- _MessageStream_connectedPromise.set(this, undefined);
- _MessageStream_resolveConnectedPromise.set(this, () => {});
- _MessageStream_rejectConnectedPromise.set(this, () => {});
- _MessageStream_endPromise.set(this, undefined);
- _MessageStream_resolveEndPromise.set(this, () => {});
- _MessageStream_rejectEndPromise.set(this, () => {});
- _MessageStream_listeners.set(this, {});
- _MessageStream_ended.set(this, false);
- _MessageStream_errored.set(this, false);
- _MessageStream_aborted.set(this, false);
- _MessageStream_catchingPromiseCreated.set(this, false);
- _MessageStream_response.set(this, undefined);
- _MessageStream_request_id.set(this, undefined);
- _MessageStream_handleError.set(this, (error) => {
- __classPrivateFieldSet4(this, _MessageStream_errored, true, "f");
- if (error instanceof Error && error.name === "AbortError") {
- error = new APIUserAbortError;
- }
- if (error instanceof APIUserAbortError) {
- __classPrivateFieldSet4(this, _MessageStream_aborted, true, "f");
- return this._emit("abort", error);
- }
- if (error instanceof AnthropicError) {
- return this._emit("error", error);
- }
- if (error instanceof Error) {
- const anthropicError = new AnthropicError(error.message);
- anthropicError.cause = error;
- return this._emit("error", anthropicError);
- }
- return this._emit("error", new AnthropicError(String(error)));
- });
- __classPrivateFieldSet4(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
- __classPrivateFieldSet4(this, _MessageStream_resolveConnectedPromise, resolve, "f");
- __classPrivateFieldSet4(this, _MessageStream_rejectConnectedPromise, reject, "f");
- }), "f");
- __classPrivateFieldSet4(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
- __classPrivateFieldSet4(this, _MessageStream_resolveEndPromise, resolve, "f");
- __classPrivateFieldSet4(this, _MessageStream_rejectEndPromise, reject, "f");
- }), "f");
- __classPrivateFieldGet4(this, _MessageStream_connectedPromise, "f").catch(() => {});
- __classPrivateFieldGet4(this, _MessageStream_endPromise, "f").catch(() => {});
- }
- get response() {
- return __classPrivateFieldGet4(this, _MessageStream_response, "f");
- }
- get request_id() {
- return __classPrivateFieldGet4(this, _MessageStream_request_id, "f");
- }
- async withResponse() {
- const response = await __classPrivateFieldGet4(this, _MessageStream_connectedPromise, "f");
- if (!response) {
- throw new Error("Could not resolve a `Response` object");
- }
- return {
- data: this,
- response,
- request_id: response.headers.get("request-id")
- };
- }
- static fromReadableStream(stream) {
- const runner = new MessageStream;
- runner._run(() => runner._fromReadableStream(stream));
- return runner;
- }
- static createMessage(messages, params, options) {
- const runner = new MessageStream;
- for (const message of params.messages) {
- runner._addMessageParam(message);
- }
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
- return runner;
- }
- _run(executor) {
- executor().then(() => {
- this._emitFinal();
- this._emit("end");
- }, __classPrivateFieldGet4(this, _MessageStream_handleError, "f"));
- }
- _addMessageParam(message) {
- this.messages.push(message);
- }
- _addMessage(message, emit = true) {
- this.receivedMessages.push(message);
- if (emit) {
- this._emit("message", message);
- }
- }
- async _createMessage(messages, params, options) {
- const signal = options?.signal;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- signal.addEventListener("abort", () => this.controller.abort());
- }
- __classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
- const { response, data: stream } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse();
- this._connected(response);
- for await (const event of stream) {
- __classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
- }
- if (stream.controller.signal?.aborted) {
- throw new APIUserAbortError;
- }
- __classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
- }
- _connected(response) {
- if (this.ended)
- return;
- __classPrivateFieldSet4(this, _MessageStream_response, response, "f");
- __classPrivateFieldSet4(this, _MessageStream_request_id, response?.headers.get("request-id"), "f");
- __classPrivateFieldGet4(this, _MessageStream_resolveConnectedPromise, "f").call(this, response);
- this._emit("connect");
- }
- get ended() {
- return __classPrivateFieldGet4(this, _MessageStream_ended, "f");
- }
- get errored() {
- return __classPrivateFieldGet4(this, _MessageStream_errored, "f");
- }
- get aborted() {
- return __classPrivateFieldGet4(this, _MessageStream_aborted, "f");
- }
- abort() {
- this.controller.abort();
- }
- on(event, listener) {
- const listeners = __classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event] = []);
- listeners.push({ listener });
- return this;
- }
- off(event, listener) {
- const listeners = __classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event];
- if (!listeners)
- return this;
- const index = listeners.findIndex((l) => l.listener === listener);
- if (index >= 0)
- listeners.splice(index, 1);
- return this;
- }
- once(event, listener) {
- const listeners = __classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event] = []);
- listeners.push({ listener, once: true });
- return this;
- }
- emitted(event) {
- return new Promise((resolve, reject) => {
- __classPrivateFieldSet4(this, _MessageStream_catchingPromiseCreated, true, "f");
- if (event !== "error")
- this.once("error", reject);
- this.once(event, resolve);
- });
- }
- async done() {
- __classPrivateFieldSet4(this, _MessageStream_catchingPromiseCreated, true, "f");
- await __classPrivateFieldGet4(this, _MessageStream_endPromise, "f");
- }
- get currentMessage() {
- return __classPrivateFieldGet4(this, _MessageStream_currentMessageSnapshot, "f");
- }
- async finalMessage() {
- await this.done();
- return __classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
- }
- async finalText() {
- await this.done();
- return __classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
- }
- _emit(event, ...args) {
- if (__classPrivateFieldGet4(this, _MessageStream_ended, "f"))
- return;
- if (event === "end") {
- __classPrivateFieldSet4(this, _MessageStream_ended, true, "f");
- __classPrivateFieldGet4(this, _MessageStream_resolveEndPromise, "f").call(this);
- }
- const listeners = __classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event];
- if (listeners) {
- __classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
- listeners.forEach(({ listener }) => listener(...args));
- }
- if (event === "abort") {
- const error = args[0];
- if (!__classPrivateFieldGet4(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
- Promise.reject(error);
- }
- __classPrivateFieldGet4(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
- __classPrivateFieldGet4(this, _MessageStream_rejectEndPromise, "f").call(this, error);
- this._emit("end");
- return;
- }
- if (event === "error") {
- const error = args[0];
- if (!__classPrivateFieldGet4(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
- Promise.reject(error);
- }
- __classPrivateFieldGet4(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
- __classPrivateFieldGet4(this, _MessageStream_rejectEndPromise, "f").call(this, error);
- this._emit("end");
- }
- }
- _emitFinal() {
- const finalMessage = this.receivedMessages.at(-1);
- if (finalMessage) {
- this._emit("finalMessage", __classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
- }
- }
- async _fromReadableStream(readableStream, options) {
- const signal = options?.signal;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- signal.addEventListener("abort", () => this.controller.abort());
- }
- __classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
- this._connected(null);
- const stream = Stream.fromReadableStream(readableStream, this.controller);
- for await (const event of stream) {
- __classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
- }
- if (stream.controller.signal?.aborted) {
- throw new APIUserAbortError;
- }
- __classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
- }
- [(_MessageStream_currentMessageSnapshot = new WeakMap, _MessageStream_connectedPromise = new WeakMap, _MessageStream_resolveConnectedPromise = new WeakMap, _MessageStream_rejectConnectedPromise = new WeakMap, _MessageStream_endPromise = new WeakMap, _MessageStream_resolveEndPromise = new WeakMap, _MessageStream_rejectEndPromise = new WeakMap, _MessageStream_listeners = new WeakMap, _MessageStream_ended = new WeakMap, _MessageStream_errored = new WeakMap, _MessageStream_aborted = new WeakMap, _MessageStream_catchingPromiseCreated = new WeakMap, _MessageStream_response = new WeakMap, _MessageStream_request_id = new WeakMap, _MessageStream_handleError = new WeakMap, _MessageStream_instances = new WeakSet, _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage2() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError("stream ended without producing a Message with role=assistant");
- }
- return this.receivedMessages.at(-1);
- }, _MessageStream_getFinalText = function _MessageStream_getFinalText2() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError("stream ended without producing a Message with role=assistant");
- }
- const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text);
- if (textBlocks.length === 0) {
- throw new AnthropicError("stream ended without producing a content block with type=text");
- }
- return textBlocks.join(" ");
- }, _MessageStream_beginRequest = function _MessageStream_beginRequest2() {
- if (this.ended)
- return;
- __classPrivateFieldSet4(this, _MessageStream_currentMessageSnapshot, undefined, "f");
- }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent2(event) {
- if (this.ended)
- return;
- const messageSnapshot = __classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
- this._emit("streamEvent", event, messageSnapshot);
- switch (event.type) {
- case "content_block_delta": {
- const content = messageSnapshot.content.at(-1);
- switch (event.delta.type) {
- case "text_delta": {
- if (content.type === "text") {
- this._emit("text", event.delta.text, content.text || "");
- }
- break;
- }
- case "citations_delta": {
- if (content.type === "text") {
- this._emit("citation", event.delta.citation, content.citations ?? []);
- }
- break;
- }
- case "input_json_delta": {
- if (content.type === "tool_use" && content.input) {
- this._emit("inputJson", event.delta.partial_json, content.input);
- }
- break;
- }
- case "thinking_delta": {
- if (content.type === "thinking") {
- this._emit("thinking", event.delta.thinking, content.thinking);
- }
- break;
- }
- case "signature_delta": {
- if (content.type === "thinking") {
- this._emit("signature", content.signature);
- }
- break;
- }
- default:
- checkNever2(event.delta);
- }
- break;
- }
- case "message_stop": {
- this._addMessageParam(messageSnapshot);
- this._addMessage(messageSnapshot, true);
- break;
- }
- case "content_block_stop": {
- this._emit("contentBlock", messageSnapshot.content.at(-1));
- break;
- }
- case "message_start": {
- __classPrivateFieldSet4(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
- break;
- }
- case "content_block_start":
- case "message_delta":
- break;
- }
- }, _MessageStream_endRequest = function _MessageStream_endRequest2() {
- if (this.ended) {
- throw new AnthropicError(`stream has ended, this shouldn't happen`);
- }
- const snapshot = __classPrivateFieldGet4(this, _MessageStream_currentMessageSnapshot, "f");
- if (!snapshot) {
- throw new AnthropicError(`request ended without sending any chunks`);
- }
- __classPrivateFieldSet4(this, _MessageStream_currentMessageSnapshot, undefined, "f");
- return snapshot;
- }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage2(event) {
- let snapshot = __classPrivateFieldGet4(this, _MessageStream_currentMessageSnapshot, "f");
- if (event.type === "message_start") {
- if (snapshot) {
- throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
- }
- return event.message;
- }
- if (!snapshot) {
- throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
- }
- switch (event.type) {
- case "message_stop":
- return snapshot;
- case "message_delta":
- snapshot.stop_reason = event.delta.stop_reason;
- snapshot.stop_sequence = event.delta.stop_sequence;
- snapshot.usage.output_tokens = event.usage.output_tokens;
- return snapshot;
- case "content_block_start":
- snapshot.content.push(event.content_block);
- return snapshot;
- case "content_block_delta": {
- const snapshotContent = snapshot.content.at(event.index);
- switch (event.delta.type) {
- case "text_delta": {
- if (snapshotContent?.type === "text") {
- snapshotContent.text += event.delta.text;
- }
- break;
- }
- case "citations_delta": {
- if (snapshotContent?.type === "text") {
- snapshotContent.citations ?? (snapshotContent.citations = []);
- snapshotContent.citations.push(event.delta.citation);
- }
- break;
- }
- case "input_json_delta": {
- if (snapshotContent?.type === "tool_use") {
- let jsonBuf = snapshotContent[JSON_BUF_PROPERTY2] || "";
- jsonBuf += event.delta.partial_json;
- Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY2, {
- value: jsonBuf,
- enumerable: false,
- writable: true
- });
- if (jsonBuf) {
- snapshotContent.input = partialParse(jsonBuf);
- }
- }
- break;
- }
- case "thinking_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshotContent.thinking += event.delta.thinking;
- }
- break;
- }
- case "signature_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshotContent.signature = event.delta.signature;
- }
- break;
- }
- default:
- checkNever2(event.delta);
- }
- return snapshot;
- }
- case "content_block_stop":
- return snapshot;
- }
- }, Symbol.asyncIterator)]() {
- const pushQueue = [];
- const readQueue = [];
- let done = false;
- this.on("streamEvent", (event) => {
- const reader = readQueue.shift();
- if (reader) {
- reader.resolve(event);
- } else {
- pushQueue.push(event);
- }
- });
- this.on("end", () => {
- done = true;
- for (const reader of readQueue) {
- reader.resolve(undefined);
- }
- readQueue.length = 0;
- });
- this.on("abort", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- this.on("error", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- return {
- next: async () => {
- if (!pushQueue.length) {
- if (done) {
- return { value: undefined, done: true };
- }
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
- }
- const chunk = pushQueue.shift();
- return { value: chunk, done: false };
- },
- return: async () => {
- this.abort();
- return { value: undefined, done: true };
- }
- };
- }
- toReadableStream() {
- const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
- return stream.toReadableStream();
- }
- };
-});
-
-// node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs
-var Messages2, DEPRECATED_MODELS2;
-var init_messages2 = __esm(() => {
- init_batches2();
- init_batches2();
- init_MessageStream();
- Messages2 = class Messages2 extends APIResource {
- constructor() {
- super(...arguments);
- this.batches = new Batches2(this._client);
- }
- create(body, options) {
- if (body.model in DEPRECATED_MODELS2) {
- console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS2[body.model]}
-Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
- }
- return this._client.post("/v1/messages", {
- body,
- timeout: this._client._options.timeout ?? (body.stream ? 600000 : this._client._calculateNonstreamingTimeout(body.max_tokens)),
- ...options,
- stream: body.stream ?? false
- });
- }
- stream(body, options) {
- return MessageStream.createMessage(this, body, options);
- }
- countTokens(body, options) {
- return this._client.post("/v1/messages/count_tokens", { body, ...options });
- }
- };
- DEPRECATED_MODELS2 = {
- "claude-1.3": "November 6th, 2024",
- "claude-1.3-100k": "November 6th, 2024",
- "claude-instant-1.1": "November 6th, 2024",
- "claude-instant-1.1-100k": "November 6th, 2024",
- "claude-instant-1.2": "November 6th, 2024",
- "claude-3-sonnet-20240229": "July 21st, 2025",
- "claude-2.1": "July 21st, 2025",
- "claude-2.0": "July 21st, 2025"
- };
- Messages2.Batches = Batches2;
- Messages2.MessageBatchesPage = MessageBatchesPage;
-});
-
-// node_modules/@anthropic-ai/sdk/resources/models.mjs
-var Models2, ModelInfosPage;
-var init_models2 = __esm(() => {
- init_core();
- init_pagination();
- Models2 = class Models2 extends APIResource {
- retrieve(modelId, options) {
- return this._client.get(`/v1/models/${modelId}`, options);
- }
- list(query = {}, options) {
- if (isRequestOptions(query)) {
- return this.list({}, query);
- }
- return this._client.getAPIList("/v1/models", ModelInfosPage, { query, ...options });
- }
- };
- ModelInfosPage = class ModelInfosPage extends Page {
- };
- Models2.ModelInfosPage = ModelInfosPage;
-});
-
-// node_modules/@anthropic-ai/sdk/resources/index.mjs
-var init_resources = __esm(() => {
- init_beta();
- init_completions();
- init_messages2();
- init_models2();
- init_shared();
-});
-
-// node_modules/@anthropic-ai/sdk/index.mjs
-var _a, Anthropic, sdk_default;
-var init_sdk = __esm(() => {
- init_core();
- init_error();
- init_uploads();
- init_resources();
- init_completions();
- init_models2();
- init_beta();
- init_messages2();
- init_error();
- Anthropic = class Anthropic extends APIClient {
- constructor({ baseURL = readEnv("ANTHROPIC_BASE_URL"), apiKey = readEnv("ANTHROPIC_API_KEY") ?? null, authToken = readEnv("ANTHROPIC_AUTH_TOKEN") ?? null, ...opts } = {}) {
- const options = {
- apiKey,
- authToken,
- ...opts,
- baseURL: baseURL || `https://api.anthropic.com`
- };
- if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
- throw new AnthropicError(`It looks like you're running in a browser-like environment.
-
-This is disabled by default, as it risks exposing your secret API credentials to attackers.
-If you understand the risks and have appropriate mitigations in place,
-you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
-
-new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
-`);
- }
- super({
- baseURL: options.baseURL,
- timeout: options.timeout ?? 600000,
- httpAgent: options.httpAgent,
- maxRetries: options.maxRetries,
- fetch: options.fetch
- });
- this.completions = new Completions(this);
- this.messages = new Messages2(this);
- this.models = new Models2(this);
- this.beta = new Beta(this);
- this._options = options;
- this.apiKey = apiKey;
- this.authToken = authToken;
- }
- defaultQuery() {
- return this._options.defaultQuery;
- }
- defaultHeaders(opts) {
- return {
- ...super.defaultHeaders(opts),
- ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : undefined,
- "anthropic-version": "2023-06-01",
- ...this._options.defaultHeaders
- };
- }
- validateHeaders(headers, customHeaders) {
- if (this.apiKey && headers["x-api-key"]) {
- return;
- }
- if (customHeaders["x-api-key"] === null) {
- return;
- }
- if (this.authToken && headers["authorization"]) {
- return;
- }
- if (customHeaders["authorization"] === null) {
- return;
- }
- throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
- }
- authHeaders(opts) {
- const apiKeyAuth = this.apiKeyAuth(opts);
- const bearerAuth = this.bearerAuth(opts);
- if (apiKeyAuth != null && !isEmptyObj(apiKeyAuth)) {
- return apiKeyAuth;
- }
- if (bearerAuth != null && !isEmptyObj(bearerAuth)) {
- return bearerAuth;
- }
- return {};
- }
- apiKeyAuth(opts) {
- if (this.apiKey == null) {
- return {};
- }
- return { "X-Api-Key": this.apiKey };
- }
- bearerAuth(opts) {
- if (this.authToken == null) {
- return {};
- }
- return { Authorization: `Bearer ${this.authToken}` };
- }
- };
- _a = Anthropic;
- Anthropic.Anthropic = _a;
- Anthropic.HUMAN_PROMPT = `
-
-Human:`;
- Anthropic.AI_PROMPT = `
-
-Assistant:`;
- Anthropic.DEFAULT_TIMEOUT = 600000;
- Anthropic.AnthropicError = AnthropicError;
- Anthropic.APIError = APIError;
- Anthropic.APIConnectionError = APIConnectionError;
- Anthropic.APIConnectionTimeoutError = APIConnectionTimeoutError;
- Anthropic.APIUserAbortError = APIUserAbortError;
- Anthropic.NotFoundError = NotFoundError;
- Anthropic.ConflictError = ConflictError;
- Anthropic.RateLimitError = RateLimitError;
- Anthropic.BadRequestError = BadRequestError;
- Anthropic.AuthenticationError = AuthenticationError;
- Anthropic.InternalServerError = InternalServerError;
- Anthropic.PermissionDeniedError = PermissionDeniedError;
- Anthropic.UnprocessableEntityError = UnprocessableEntityError;
- Anthropic.toFile = toFile;
- Anthropic.fileFromPath = fileFromPath;
- Anthropic.Completions = Completions;
- Anthropic.Messages = Messages2;
- Anthropic.Models = Models2;
- Anthropic.ModelInfosPage = ModelInfosPage;
- Anthropic.Beta = Beta;
- sdk_default = Anthropic;
-});
-
-// src/utils/errors.ts
-function isAbortError(e) {
- return e instanceof AbortError || e instanceof APIUserAbortError || e instanceof Error && e.name === "AbortError";
-}
-function hasExactErrorMessage(error, message) {
- return error instanceof Error && error.message === message;
-}
-function toError(e) {
- return e instanceof Error ? e : new Error(String(e));
-}
-function errorMessage(e) {
- return e instanceof Error ? e.message : String(e);
-}
-function getErrnoCode(e) {
- if (e && typeof e === "object" && "code" in e && typeof e.code === "string") {
- return e.code;
- }
- return;
-}
-function isENOENT(e) {
- return getErrnoCode(e) === "ENOENT";
-}
-function getErrnoPath(e) {
- if (e && typeof e === "object" && "path" in e && typeof e.path === "string") {
- return e.path;
- }
- return;
-}
-function isFsInaccessible(e) {
- const code = getErrnoCode(e);
- return code === "ENOENT" || code === "EACCES" || code === "EPERM" || code === "ENOTDIR" || code === "ELOOP";
-}
-function classifyAxiosError(e) {
- const message = errorMessage(e);
- if (!e || typeof e !== "object" || !("isAxiosError" in e) || !e.isAxiosError) {
- return { kind: "other", message };
- }
- const err = e;
- const status = err.response?.status;
- if (status === 401 || status === 403)
- return { kind: "auth", status, message };
- if (err.code === "ECONNABORTED")
- return { kind: "timeout", status, message };
- if (err.code === "ECONNREFUSED" || err.code === "ENOTFOUND") {
- return { kind: "network", status, message };
- }
- return { kind: "http", status, message };
-}
-var ClaudeError, MalformedCommandError, AbortError, ConfigParseError, ShellError, TeleportOperationError, TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS;
-var init_errors = __esm(() => {
- init_sdk();
- ClaudeError = class ClaudeError extends Error {
- constructor(message) {
- super(message);
- this.name = this.constructor.name;
- }
- };
- MalformedCommandError = class MalformedCommandError extends Error {
- };
- AbortError = class AbortError extends Error {
- constructor(message) {
- super(message);
- this.name = "AbortError";
- }
- };
- ConfigParseError = class ConfigParseError extends Error {
- filePath;
- defaultConfig;
- constructor(message, filePath, defaultConfig) {
- super(message);
- this.name = "ConfigParseError";
- this.filePath = filePath;
- this.defaultConfig = defaultConfig;
- }
- };
- ShellError = class ShellError extends Error {
- stdout;
- stderr;
- code;
- interrupted;
- constructor(stdout, stderr, code, interrupted) {
- super("Shell command failed");
- this.stdout = stdout;
- this.stderr = stderr;
- this.code = code;
- this.interrupted = interrupted;
- this.name = "ShellError";
- }
- };
- TeleportOperationError = class TeleportOperationError extends Error {
- formattedMessage;
- constructor(message, formattedMessage) {
- super(message);
- this.formattedMessage = formattedMessage;
- this.name = "TeleportOperationError";
- }
- };
- TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS = class TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS extends Error {
- telemetryMessage;
- constructor(message, telemetryMessage) {
- super(message);
- this.name = "TelemetrySafeError";
- this.telemetryMessage = telemetryMessage ?? message;
- }
- };
-});
-
-// node_modules/lodash-es/_arrayEach.js
-function arrayEach(array, iteratee) {
- var index = -1, length = array == null ? 0 : array.length;
- while (++index < length) {
- if (iteratee(array[index], index, array) === false) {
- break;
- }
- }
- return array;
-}
-var _arrayEach_default;
-var init__arrayEach = __esm(() => {
- _arrayEach_default = arrayEach;
-});
-
-// node_modules/lodash-es/_defineProperty.js
-var defineProperty, _defineProperty_default;
-var init__defineProperty = __esm(() => {
- init__getNative();
- defineProperty = function() {
- try {
- var func = _getNative_default(Object, "defineProperty");
- func({}, "", {});
- return func;
- } catch (e) {}
- }();
- _defineProperty_default = defineProperty;
-});
-
-// node_modules/lodash-es/_baseAssignValue.js
-function baseAssignValue(object, key, value) {
- if (key == "__proto__" && _defineProperty_default) {
- _defineProperty_default(object, key, {
- configurable: true,
- enumerable: true,
- value,
- writable: true
- });
- } else {
- object[key] = value;
- }
-}
-var _baseAssignValue_default;
-var init__baseAssignValue = __esm(() => {
- init__defineProperty();
- _baseAssignValue_default = baseAssignValue;
-});
-
-// node_modules/lodash-es/_assignValue.js
-function assignValue(object, key, value) {
- var objValue = object[key];
- if (!(hasOwnProperty10.call(object, key) && eq_default(objValue, value)) || value === undefined && !(key in object)) {
- _baseAssignValue_default(object, key, value);
- }
-}
-var objectProto13, hasOwnProperty10, _assignValue_default;
-var init__assignValue = __esm(() => {
- init__baseAssignValue();
- init_eq();
- objectProto13 = Object.prototype;
- hasOwnProperty10 = objectProto13.hasOwnProperty;
- _assignValue_default = assignValue;
-});
-
-// node_modules/lodash-es/_copyObject.js
-function copyObject(source, props, object, customizer) {
- var isNew = !object;
- object || (object = {});
- var index = -1, length = props.length;
- while (++index < length) {
- var key = props[index];
- var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined;
- if (newValue === undefined) {
- newValue = source[key];
- }
- if (isNew) {
- _baseAssignValue_default(object, key, newValue);
- } else {
- _assignValue_default(object, key, newValue);
- }
- }
- return object;
-}
-var _copyObject_default;
-var init__copyObject = __esm(() => {
- init__assignValue();
- init__baseAssignValue();
- _copyObject_default = copyObject;
-});
-
-// node_modules/lodash-es/_baseAssign.js
-function baseAssign(object, source) {
- return object && _copyObject_default(source, keys_default(source), object);
-}
-var _baseAssign_default;
-var init__baseAssign = __esm(() => {
- init__copyObject();
- init_keys();
- _baseAssign_default = baseAssign;
-});
-
-// node_modules/lodash-es/_nativeKeysIn.js
-function nativeKeysIn(object) {
- var result = [];
- if (object != null) {
- for (var key in Object(object)) {
- result.push(key);
- }
- }
- return result;
-}
-var _nativeKeysIn_default;
-var init__nativeKeysIn = __esm(() => {
- _nativeKeysIn_default = nativeKeysIn;
-});
-
-// node_modules/lodash-es/_baseKeysIn.js
-function baseKeysIn(object) {
- if (!isObject_default(object)) {
- return _nativeKeysIn_default(object);
- }
- var isProto = _isPrototype_default(object), result = [];
- for (var key in object) {
- if (!(key == "constructor" && (isProto || !hasOwnProperty11.call(object, key)))) {
- result.push(key);
- }
- }
- return result;
-}
-var objectProto14, hasOwnProperty11, _baseKeysIn_default;
-var init__baseKeysIn = __esm(() => {
- init_isObject();
- init__isPrototype();
- init__nativeKeysIn();
- objectProto14 = Object.prototype;
- hasOwnProperty11 = objectProto14.hasOwnProperty;
- _baseKeysIn_default = baseKeysIn;
-});
-
-// node_modules/lodash-es/keysIn.js
-function keysIn(object) {
- return isArrayLike_default(object) ? _arrayLikeKeys_default(object, true) : _baseKeysIn_default(object);
-}
-var keysIn_default;
-var init_keysIn = __esm(() => {
- init__arrayLikeKeys();
- init__baseKeysIn();
- init_isArrayLike();
- keysIn_default = keysIn;
-});
-
-// node_modules/lodash-es/_baseAssignIn.js
-function baseAssignIn(object, source) {
- return object && _copyObject_default(source, keysIn_default(source), object);
-}
-var _baseAssignIn_default;
-var init__baseAssignIn = __esm(() => {
- init__copyObject();
- init_keysIn();
- _baseAssignIn_default = baseAssignIn;
-});
-
-// node_modules/lodash-es/_cloneBuffer.js
-var exports__cloneBuffer = {};
-__export(exports__cloneBuffer, {
- default: () => _cloneBuffer_default
-});
-function cloneBuffer(buffer, isDeep) {
- if (isDeep) {
- return buffer.slice();
- }
- var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
- buffer.copy(result);
- return result;
-}
-var freeExports3, freeModule3, moduleExports3, Buffer3, allocUnsafe, _cloneBuffer_default;
-var init__cloneBuffer = __esm(() => {
- init__root();
- freeExports3 = typeof exports__cloneBuffer == "object" && exports__cloneBuffer && !exports__cloneBuffer.nodeType && exports__cloneBuffer;
- freeModule3 = freeExports3 && typeof module__cloneBuffer == "object" && module__cloneBuffer && !module__cloneBuffer.nodeType && module__cloneBuffer;
- moduleExports3 = freeModule3 && freeModule3.exports === freeExports3;
- Buffer3 = moduleExports3 ? _root_default.Buffer : undefined;
- allocUnsafe = Buffer3 ? Buffer3.allocUnsafe : undefined;
- _cloneBuffer_default = cloneBuffer;
-});
-
-// node_modules/lodash-es/_copyArray.js
-function copyArray(source, array) {
- var index = -1, length = source.length;
- array || (array = Array(length));
- while (++index < length) {
- array[index] = source[index];
- }
- return array;
-}
-var _copyArray_default;
-var init__copyArray = __esm(() => {
- _copyArray_default = copyArray;
-});
-
-// node_modules/lodash-es/_copySymbols.js
-function copySymbols(source, object) {
- return _copyObject_default(source, _getSymbols_default(source), object);
-}
-var _copySymbols_default;
-var init__copySymbols = __esm(() => {
- init__copyObject();
- init__getSymbols();
- _copySymbols_default = copySymbols;
-});
-
-// node_modules/lodash-es/_getPrototype.js
-var getPrototype, _getPrototype_default;
-var init__getPrototype = __esm(() => {
- init__overArg();
- getPrototype = _overArg_default(Object.getPrototypeOf, Object);
- _getPrototype_default = getPrototype;
-});
-
-// node_modules/lodash-es/_getSymbolsIn.js
-var nativeGetSymbols2, getSymbolsIn, _getSymbolsIn_default;
-var init__getSymbolsIn = __esm(() => {
- init__arrayPush();
- init__getPrototype();
- init__getSymbols();
- init_stubArray();
- nativeGetSymbols2 = Object.getOwnPropertySymbols;
- getSymbolsIn = !nativeGetSymbols2 ? stubArray_default : function(object) {
- var result = [];
- while (object) {
- _arrayPush_default(result, _getSymbols_default(object));
- object = _getPrototype_default(object);
- }
- return result;
- };
- _getSymbolsIn_default = getSymbolsIn;
-});
-
-// node_modules/lodash-es/_copySymbolsIn.js
-function copySymbolsIn(source, object) {
- return _copyObject_default(source, _getSymbolsIn_default(source), object);
-}
-var _copySymbolsIn_default;
-var init__copySymbolsIn = __esm(() => {
- init__copyObject();
- init__getSymbolsIn();
- _copySymbolsIn_default = copySymbolsIn;
-});
-
-// node_modules/lodash-es/_getAllKeysIn.js
-function getAllKeysIn(object) {
- return _baseGetAllKeys_default(object, keysIn_default, _getSymbolsIn_default);
-}
-var _getAllKeysIn_default;
-var init__getAllKeysIn = __esm(() => {
- init__baseGetAllKeys();
- init__getSymbolsIn();
- init_keysIn();
- _getAllKeysIn_default = getAllKeysIn;
-});
-
-// node_modules/lodash-es/_initCloneArray.js
-function initCloneArray(array) {
- var length = array.length, result = new array.constructor(length);
- if (length && typeof array[0] == "string" && hasOwnProperty12.call(array, "index")) {
- result.index = array.index;
- result.input = array.input;
- }
- return result;
-}
-var objectProto15, hasOwnProperty12, _initCloneArray_default;
-var init__initCloneArray = __esm(() => {
- objectProto15 = Object.prototype;
- hasOwnProperty12 = objectProto15.hasOwnProperty;
- _initCloneArray_default = initCloneArray;
-});
-
-// node_modules/lodash-es/_cloneArrayBuffer.js
-function cloneArrayBuffer(arrayBuffer) {
- var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
- new _Uint8Array_default(result).set(new _Uint8Array_default(arrayBuffer));
- return result;
-}
-var _cloneArrayBuffer_default;
-var init__cloneArrayBuffer = __esm(() => {
- init__Uint8Array();
- _cloneArrayBuffer_default = cloneArrayBuffer;
-});
-
-// node_modules/lodash-es/_cloneDataView.js
-function cloneDataView(dataView, isDeep) {
- var buffer = isDeep ? _cloneArrayBuffer_default(dataView.buffer) : dataView.buffer;
- return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
-}
-var _cloneDataView_default;
-var init__cloneDataView = __esm(() => {
- init__cloneArrayBuffer();
- _cloneDataView_default = cloneDataView;
-});
-
-// node_modules/lodash-es/_cloneRegExp.js
-function cloneRegExp(regexp) {
- var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
- result.lastIndex = regexp.lastIndex;
- return result;
-}
-var reFlags, _cloneRegExp_default;
-var init__cloneRegExp = __esm(() => {
- reFlags = /\w*$/;
- _cloneRegExp_default = cloneRegExp;
-});
-
-// node_modules/lodash-es/_cloneSymbol.js
-function cloneSymbol(symbol) {
- return symbolValueOf2 ? Object(symbolValueOf2.call(symbol)) : {};
-}
-var symbolProto3, symbolValueOf2, _cloneSymbol_default;
-var init__cloneSymbol = __esm(() => {
- init__Symbol();
- symbolProto3 = _Symbol_default ? _Symbol_default.prototype : undefined;
- symbolValueOf2 = symbolProto3 ? symbolProto3.valueOf : undefined;
- _cloneSymbol_default = cloneSymbol;
-});
-
-// node_modules/lodash-es/_cloneTypedArray.js
-function cloneTypedArray(typedArray, isDeep) {
- var buffer = isDeep ? _cloneArrayBuffer_default(typedArray.buffer) : typedArray.buffer;
- return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
-}
-var _cloneTypedArray_default;
-var init__cloneTypedArray = __esm(() => {
- init__cloneArrayBuffer();
- _cloneTypedArray_default = cloneTypedArray;
-});
-
-// node_modules/lodash-es/_initCloneByTag.js
-function initCloneByTag(object, tag, isDeep) {
- var Ctor = object.constructor;
- switch (tag) {
- case arrayBufferTag3:
- return _cloneArrayBuffer_default(object);
- case boolTag3:
- case dateTag3:
- return new Ctor(+object);
- case dataViewTag4:
- return _cloneDataView_default(object, isDeep);
- case float32Tag2:
- case float64Tag2:
- case int8Tag2:
- case int16Tag2:
- case int32Tag2:
- case uint8Tag2:
- case uint8ClampedTag2:
- case uint16Tag2:
- case uint32Tag2:
- return _cloneTypedArray_default(object, isDeep);
- case mapTag4:
- return new Ctor;
- case numberTag3:
- case stringTag3:
- return new Ctor(object);
- case regexpTag3:
- return _cloneRegExp_default(object);
- case setTag4:
- return new Ctor;
- case symbolTag3:
- return _cloneSymbol_default(object);
- }
-}
-var boolTag3 = "[object Boolean]", dateTag3 = "[object Date]", mapTag4 = "[object Map]", numberTag3 = "[object Number]", regexpTag3 = "[object RegExp]", setTag4 = "[object Set]", stringTag3 = "[object String]", symbolTag3 = "[object Symbol]", arrayBufferTag3 = "[object ArrayBuffer]", dataViewTag4 = "[object DataView]", float32Tag2 = "[object Float32Array]", float64Tag2 = "[object Float64Array]", int8Tag2 = "[object Int8Array]", int16Tag2 = "[object Int16Array]", int32Tag2 = "[object Int32Array]", uint8Tag2 = "[object Uint8Array]", uint8ClampedTag2 = "[object Uint8ClampedArray]", uint16Tag2 = "[object Uint16Array]", uint32Tag2 = "[object Uint32Array]", _initCloneByTag_default;
-var init__initCloneByTag = __esm(() => {
- init__cloneArrayBuffer();
- init__cloneDataView();
- init__cloneRegExp();
- init__cloneSymbol();
- init__cloneTypedArray();
- _initCloneByTag_default = initCloneByTag;
-});
-
-// node_modules/lodash-es/_baseCreate.js
-var objectCreate, baseCreate, _baseCreate_default;
-var init__baseCreate = __esm(() => {
- init_isObject();
- objectCreate = Object.create;
- baseCreate = function() {
- function object() {}
- return function(proto) {
- if (!isObject_default(proto)) {
- return {};
- }
- if (objectCreate) {
- return objectCreate(proto);
- }
- object.prototype = proto;
- var result = new object;
- object.prototype = undefined;
- return result;
- };
- }();
- _baseCreate_default = baseCreate;
-});
-
-// node_modules/lodash-es/_initCloneObject.js
-function initCloneObject(object) {
- return typeof object.constructor == "function" && !_isPrototype_default(object) ? _baseCreate_default(_getPrototype_default(object)) : {};
-}
-var _initCloneObject_default;
-var init__initCloneObject = __esm(() => {
- init__baseCreate();
- init__getPrototype();
- init__isPrototype();
- _initCloneObject_default = initCloneObject;
-});
-
-// node_modules/lodash-es/_baseIsMap.js
-function baseIsMap(value) {
- return isObjectLike_default(value) && _getTag_default(value) == mapTag5;
-}
-var mapTag5 = "[object Map]", _baseIsMap_default;
-var init__baseIsMap = __esm(() => {
- init__getTag();
- init_isObjectLike();
- _baseIsMap_default = baseIsMap;
-});
-
-// node_modules/lodash-es/isMap.js
-var nodeIsMap, isMap, isMap_default;
-var init_isMap = __esm(() => {
- init__baseIsMap();
- init__baseUnary();
- init__nodeUtil();
- nodeIsMap = _nodeUtil_default && _nodeUtil_default.isMap;
- isMap = nodeIsMap ? _baseUnary_default(nodeIsMap) : _baseIsMap_default;
- isMap_default = isMap;
-});
-
-// node_modules/lodash-es/_baseIsSet.js
-function baseIsSet(value) {
- return isObjectLike_default(value) && _getTag_default(value) == setTag5;
-}
-var setTag5 = "[object Set]", _baseIsSet_default;
-var init__baseIsSet = __esm(() => {
- init__getTag();
- init_isObjectLike();
- _baseIsSet_default = baseIsSet;
-});
-
-// node_modules/lodash-es/isSet.js
-var nodeIsSet, isSet, isSet_default;
-var init_isSet = __esm(() => {
- init__baseIsSet();
- init__baseUnary();
- init__nodeUtil();
- nodeIsSet = _nodeUtil_default && _nodeUtil_default.isSet;
- isSet = nodeIsSet ? _baseUnary_default(nodeIsSet) : _baseIsSet_default;
- isSet_default = isSet;
-});
-
-// node_modules/lodash-es/_baseClone.js
-function baseClone(value, bitmask, customizer, key, object, stack) {
- var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
- if (customizer) {
- result = object ? customizer(value, key, object, stack) : customizer(value);
- }
- if (result !== undefined) {
- return result;
- }
- if (!isObject_default(value)) {
- return value;
- }
- var isArr = isArray_default(value);
- if (isArr) {
- result = _initCloneArray_default(value);
- if (!isDeep) {
- return _copyArray_default(value, result);
- }
- } else {
- var tag = _getTag_default(value), isFunc = tag == funcTag3 || tag == genTag2;
- if (isBuffer_default(value)) {
- return _cloneBuffer_default(value, isDeep);
- }
- if (tag == objectTag4 || tag == argsTag4 || isFunc && !object) {
- result = isFlat || isFunc ? {} : _initCloneObject_default(value);
- if (!isDeep) {
- return isFlat ? _copySymbolsIn_default(value, _baseAssignIn_default(result, value)) : _copySymbols_default(value, _baseAssign_default(result, value));
- }
- } else {
- if (!cloneableTags[tag]) {
- return object ? value : {};
- }
- result = _initCloneByTag_default(value, tag, isDeep);
- }
- }
- stack || (stack = new _Stack_default);
- var stacked = stack.get(value);
- if (stacked) {
- return stacked;
- }
- stack.set(value, result);
- if (isSet_default(value)) {
- value.forEach(function(subValue) {
- result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
- });
- } else if (isMap_default(value)) {
- value.forEach(function(subValue, key2) {
- result.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
- });
- }
- var keysFunc = isFull ? isFlat ? _getAllKeysIn_default : _getAllKeys_default : isFlat ? keysIn_default : keys_default;
- var props = isArr ? undefined : keysFunc(value);
- _arrayEach_default(props || value, function(subValue, key2) {
- if (props) {
- key2 = subValue;
- subValue = value[key2];
- }
- _assignValue_default(result, key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
- });
- return result;
-}
-var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4, argsTag4 = "[object Arguments]", arrayTag3 = "[object Array]", boolTag4 = "[object Boolean]", dateTag4 = "[object Date]", errorTag3 = "[object Error]", funcTag3 = "[object Function]", genTag2 = "[object GeneratorFunction]", mapTag6 = "[object Map]", numberTag4 = "[object Number]", objectTag4 = "[object Object]", regexpTag4 = "[object RegExp]", setTag6 = "[object Set]", stringTag4 = "[object String]", symbolTag4 = "[object Symbol]", weakMapTag3 = "[object WeakMap]", arrayBufferTag4 = "[object ArrayBuffer]", dataViewTag5 = "[object DataView]", float32Tag3 = "[object Float32Array]", float64Tag3 = "[object Float64Array]", int8Tag3 = "[object Int8Array]", int16Tag3 = "[object Int16Array]", int32Tag3 = "[object Int32Array]", uint8Tag3 = "[object Uint8Array]", uint8ClampedTag3 = "[object Uint8ClampedArray]", uint16Tag3 = "[object Uint16Array]", uint32Tag3 = "[object Uint32Array]", cloneableTags, _baseClone_default;
-var init__baseClone = __esm(() => {
- init__Stack();
- init__arrayEach();
- init__assignValue();
- init__baseAssign();
- init__baseAssignIn();
- init__cloneBuffer();
- init__copyArray();
- init__copySymbols();
- init__copySymbolsIn();
- init__getAllKeys();
- init__getAllKeysIn();
- init__getTag();
- init__initCloneArray();
- init__initCloneByTag();
- init__initCloneObject();
- init_isArray();
- init_isBuffer();
- init_isMap();
- init_isObject();
- init_isSet();
- init_keys();
- init_keysIn();
- cloneableTags = {};
- cloneableTags[argsTag4] = cloneableTags[arrayTag3] = cloneableTags[arrayBufferTag4] = cloneableTags[dataViewTag5] = cloneableTags[boolTag4] = cloneableTags[dateTag4] = cloneableTags[float32Tag3] = cloneableTags[float64Tag3] = cloneableTags[int8Tag3] = cloneableTags[int16Tag3] = cloneableTags[int32Tag3] = cloneableTags[mapTag6] = cloneableTags[numberTag4] = cloneableTags[objectTag4] = cloneableTags[regexpTag4] = cloneableTags[setTag6] = cloneableTags[stringTag4] = cloneableTags[symbolTag4] = cloneableTags[uint8Tag3] = cloneableTags[uint8ClampedTag3] = cloneableTags[uint16Tag3] = cloneableTags[uint32Tag3] = true;
- cloneableTags[errorTag3] = cloneableTags[funcTag3] = cloneableTags[weakMapTag3] = false;
- _baseClone_default = baseClone;
-});
-
-// src/utils/slowOperations.ts
-import {
- closeSync,
- writeFileSync as fsWriteFileSync,
- fsyncSync,
- openSync
-} from "fs";
-function slowLoggingExternal() {
- return NOOP_LOGGER;
-}
-function jsonStringify(value, replacer, space) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`JSON.stringify(${value})`, 0);
- return JSON.stringify(value, replacer, space);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
-}
-function clone(value, options) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`structuredClone(${value})`, 0);
- return structuredClone(value, options);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
-}
-function writeFileSync_DEPRECATED(filePath, data, options) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.writeFileSync(${filePath}, ${data})`, 0);
- const needsFlush = options !== null && typeof options === "object" && "flush" in options && options.flush === true;
- if (needsFlush) {
- const encoding = typeof options === "object" && "encoding" in options ? options.encoding : undefined;
- const mode = typeof options === "object" && "mode" in options ? options.mode : undefined;
- let fd;
- try {
- fd = openSync(filePath, "w", mode);
- fsWriteFileSync(fd, data, { encoding: encoding ?? undefined });
- fsyncSync(fd);
- } finally {
- if (fd !== undefined) {
- closeSync(fd);
- }
- }
- } else {
- fsWriteFileSync(filePath, data, options);
- }
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
-}
-var SLOW_OPERATION_THRESHOLD_MS, NOOP_LOGGER, slowLogging, jsonParse = (text, reviver) => {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`JSON.parse(${text})`, 0);
- return typeof reviver === "undefined" ? JSON.parse(text) : JSON.parse(text, reviver);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
-};
-var init_slowOperations = __esm(() => {
- init_state();
- init_debug();
- SLOW_OPERATION_THRESHOLD_MS = (() => {
- const envValue = process.env.CLAUDE_CODE_SLOW_OPERATION_THRESHOLD_MS;
- if (envValue !== undefined) {
- const parsed = Number(envValue);
- if (!Number.isNaN(parsed) && parsed >= 0) {
- return parsed;
- }
- }
- if (true) {
- return 20;
- }
- if (process.env.USER_TYPE === "ant") {
- return 300;
- }
- return Infinity;
- })();
- NOOP_LOGGER = { [Symbol.dispose]() {} };
- slowLogging = slowLoggingExternal;
-});
-
-// src/utils/fsOperations.ts
-import * as fs from "fs";
-import {
- mkdir as mkdirPromise,
- open,
- readdir as readdirPromise,
- readFile as readFilePromise,
- rename as renamePromise,
- rmdir as rmdirPromise,
- rm as rmPromise,
- stat as statPromise,
- unlink as unlinkPromise
-} from "fs/promises";
-import { homedir as homedir2 } from "os";
-import * as nodePath from "path";
-function safeResolvePath(fs2, filePath) {
- if (filePath.startsWith("//") || filePath.startsWith("\\\\")) {
- return { resolvedPath: filePath, isSymlink: false, isCanonical: false };
- }
- try {
- const stats = fs2.lstatSync(filePath);
- if (stats.isFIFO() || stats.isSocket() || stats.isCharacterDevice() || stats.isBlockDevice()) {
- return { resolvedPath: filePath, isSymlink: false, isCanonical: false };
- }
- const resolvedPath = fs2.realpathSync(filePath);
- return {
- resolvedPath,
- isSymlink: resolvedPath !== filePath,
- isCanonical: true
- };
- } catch (_error) {
- return { resolvedPath: filePath, isSymlink: false, isCanonical: false };
- }
-}
-function isDuplicatePath(fs2, filePath, loadedPaths) {
- const { resolvedPath } = safeResolvePath(fs2, filePath);
- if (loadedPaths.has(resolvedPath)) {
- return true;
- }
- loadedPaths.add(resolvedPath);
- return false;
-}
-function resolveDeepestExistingAncestorSync(fs2, absolutePath) {
- let dir = absolutePath;
- const segments = [];
- while (dir !== nodePath.dirname(dir)) {
- let st;
- try {
- st = fs2.lstatSync(dir);
- } catch {
- segments.unshift(nodePath.basename(dir));
- dir = nodePath.dirname(dir);
- continue;
- }
- if (st.isSymbolicLink()) {
- try {
- const resolved = fs2.realpathSync(dir);
- return segments.length === 0 ? resolved : nodePath.join(resolved, ...segments);
- } catch {
- const target = fs2.readlinkSync(dir);
- const absTarget = nodePath.isAbsolute(target) ? target : nodePath.resolve(nodePath.dirname(dir), target);
- return segments.length === 0 ? absTarget : nodePath.join(absTarget, ...segments);
- }
- }
- try {
- const resolved = fs2.realpathSync(dir);
- if (resolved !== dir) {
- return segments.length === 0 ? resolved : nodePath.join(resolved, ...segments);
- }
- } catch {}
- return;
- }
- return;
-}
-function getPathsForPermissionCheck(inputPath) {
- let path = inputPath;
- if (path === "~") {
- path = homedir2().normalize("NFC");
- } else if (path.startsWith("~/")) {
- path = nodePath.join(homedir2().normalize("NFC"), path.slice(2));
- }
- const pathSet = new Set;
- const fsImpl = getFsImplementation();
- pathSet.add(path);
- if (path.startsWith("//") || path.startsWith("\\\\")) {
- return Array.from(pathSet);
- }
- try {
- let currentPath = path;
- const visited = new Set;
- const maxDepth = 40;
- for (let depth = 0;depth < maxDepth; depth++) {
- if (visited.has(currentPath)) {
- break;
- }
- visited.add(currentPath);
- if (!fsImpl.existsSync(currentPath)) {
- if (currentPath === path) {
- const resolved = resolveDeepestExistingAncestorSync(fsImpl, path);
- if (resolved !== undefined) {
- pathSet.add(resolved);
- }
- }
- break;
- }
- const stats = fsImpl.lstatSync(currentPath);
- if (stats.isFIFO() || stats.isSocket() || stats.isCharacterDevice() || stats.isBlockDevice()) {
- break;
- }
- if (!stats.isSymbolicLink()) {
- break;
- }
- const target = fsImpl.readlinkSync(currentPath);
- const absoluteTarget = nodePath.isAbsolute(target) ? target : nodePath.resolve(nodePath.dirname(currentPath), target);
- pathSet.add(absoluteTarget);
- currentPath = absoluteTarget;
- }
- } catch {}
- const { resolvedPath, isSymlink } = safeResolvePath(fsImpl, path);
- if (isSymlink && resolvedPath !== path) {
- pathSet.add(resolvedPath);
- }
- return Array.from(pathSet);
-}
-function getFsImplementation() {
- return activeFs;
-}
-async function readFileRange(path, offset, maxBytes) {
- let __stack = [];
- try {
- const fh = __using(__stack, await open(path, "r"), 1);
- const size = (await fh.stat()).size;
- if (size <= offset) {
- return null;
- }
- const bytesToRead = Math.min(size - offset, maxBytes);
- const buffer = Buffer.allocUnsafe(bytesToRead);
- let totalRead = 0;
- while (totalRead < bytesToRead) {
- const { bytesRead } = await fh.read(buffer, totalRead, bytesToRead - totalRead, offset + totalRead);
- if (bytesRead === 0) {
- break;
- }
- totalRead += bytesRead;
- }
- return {
- content: buffer.toString("utf8", 0, totalRead),
- bytesRead: totalRead,
- bytesTotal: size
- };
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- var _promise = __callDispose(__stack, _err, _hasErr);
- _promise && await _promise;
- }
-}
-async function tailFile(path, maxBytes) {
- let __stack = [];
- try {
- const fh = __using(__stack, await open(path, "r"), 1);
- const size = (await fh.stat()).size;
- if (size === 0) {
- return { content: "", bytesRead: 0, bytesTotal: 0 };
- }
- const offset = Math.max(0, size - maxBytes);
- const bytesToRead = size - offset;
- const buffer = Buffer.allocUnsafe(bytesToRead);
- let totalRead = 0;
- while (totalRead < bytesToRead) {
- const { bytesRead } = await fh.read(buffer, totalRead, bytesToRead - totalRead, offset + totalRead);
- if (bytesRead === 0) {
- break;
- }
- totalRead += bytesRead;
- }
- return {
- content: buffer.toString("utf8", 0, totalRead),
- bytesRead: totalRead,
- bytesTotal: size
- };
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- var _promise = __callDispose(__stack, _err, _hasErr);
- _promise && await _promise;
- }
-}
-async function* readLinesReverse(path) {
- const CHUNK_SIZE = 1024 * 4;
- const fileHandle = await open(path, "r");
- try {
- const stats = await fileHandle.stat();
- let position = stats.size;
- let remainder = Buffer.alloc(0);
- const buffer = Buffer.alloc(CHUNK_SIZE);
- while (position > 0) {
- const currentChunkSize = Math.min(CHUNK_SIZE, position);
- position -= currentChunkSize;
- await fileHandle.read(buffer, 0, currentChunkSize, position);
- const combined = Buffer.concat([
- buffer.subarray(0, currentChunkSize),
- remainder
- ]);
- const firstNewline = combined.indexOf(10);
- if (firstNewline === -1) {
- remainder = combined;
- continue;
- }
- remainder = Buffer.from(combined.subarray(0, firstNewline));
- const lines = combined.toString("utf8", firstNewline + 1).split(`
-`);
- for (let i = lines.length - 1;i >= 0; i--) {
- const line = lines[i];
- if (line) {
- yield line;
- }
- }
- }
- if (remainder.length > 0) {
- yield remainder.toString("utf8");
- }
- } finally {
- await fileHandle.close();
- }
-}
-var NodeFsOperations, activeFs;
-var init_fsOperations = __esm(() => {
- init_errors();
- init_slowOperations();
- NodeFsOperations = {
- cwd() {
- return process.cwd();
- },
- existsSync(fsPath) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.existsSync(${fsPath})`, 0);
- return fs.existsSync(fsPath);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- async stat(fsPath) {
- return statPromise(fsPath);
- },
- async readdir(fsPath) {
- return readdirPromise(fsPath, { withFileTypes: true });
- },
- async unlink(fsPath) {
- return unlinkPromise(fsPath);
- },
- async rmdir(fsPath) {
- return rmdirPromise(fsPath);
- },
- async rm(fsPath, options) {
- return rmPromise(fsPath, options);
- },
- async mkdir(dirPath, options) {
- try {
- await mkdirPromise(dirPath, { recursive: true, ...options });
- } catch (e) {
- if (getErrnoCode(e) !== "EEXIST")
- throw e;
- }
- },
- async readFile(fsPath, options) {
- return readFilePromise(fsPath, { encoding: options.encoding });
- },
- async rename(oldPath, newPath) {
- return renamePromise(oldPath, newPath);
- },
- statSync(fsPath) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.statSync(${fsPath})`, 0);
- return fs.statSync(fsPath);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- lstatSync(fsPath) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.lstatSync(${fsPath})`, 0);
- return fs.lstatSync(fsPath);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- readFileSync(fsPath, options) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.readFileSync(${fsPath})`, 0);
- return fs.readFileSync(fsPath, { encoding: options.encoding });
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- readFileBytesSync(fsPath) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.readFileBytesSync(${fsPath})`, 0);
- return fs.readFileSync(fsPath);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- readSync(fsPath, options) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.readSync(${fsPath}, ${options.length} bytes)`, 0);
- let fd = undefined;
- try {
- fd = fs.openSync(fsPath, "r");
- const buffer = Buffer.alloc(options.length);
- const bytesRead = fs.readSync(fd, buffer, 0, options.length, 0);
- return { buffer, bytesRead };
- } finally {
- if (fd)
- fs.closeSync(fd);
- }
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- appendFileSync(path, data, options) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.appendFileSync(${path}, ${data.length} chars)`, 0);
- if (options?.mode !== undefined) {
- try {
- const fd = fs.openSync(path, "ax", options.mode);
- try {
- fs.appendFileSync(fd, data);
- } finally {
- fs.closeSync(fd);
- }
- return;
- } catch (e) {
- if (getErrnoCode(e) !== "EEXIST")
- throw e;
- }
- }
- fs.appendFileSync(path, data);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- copyFileSync(src, dest) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.copyFileSync(${src} \u2192 ${dest})`, 0);
- fs.copyFileSync(src, dest);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- unlinkSync(path) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.unlinkSync(${path})`, 0);
- fs.unlinkSync(path);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- renameSync(oldPath, newPath) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.renameSync(${oldPath} \u2192 ${newPath})`, 0);
- fs.renameSync(oldPath, newPath);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- linkSync(target, path) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.linkSync(${target} \u2192 ${path})`, 0);
- fs.linkSync(target, path);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- symlinkSync(target, path, type) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.symlinkSync(${target} \u2192 ${path})`, 0);
- fs.symlinkSync(target, path, type);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- readlinkSync(path) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.readlinkSync(${path})`, 0);
- return fs.readlinkSync(path);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- realpathSync(path) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.realpathSync(${path})`, 0);
- return fs.realpathSync(path).normalize("NFC");
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- mkdirSync(dirPath, options) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.mkdirSync(${dirPath})`, 0);
- const mkdirOptions = {
- recursive: true
- };
- if (options?.mode !== undefined) {
- mkdirOptions.mode = options.mode;
- }
- try {
- fs.mkdirSync(dirPath, mkdirOptions);
- } catch (e) {
- if (getErrnoCode(e) !== "EEXIST")
- throw e;
- }
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- readdirSync(dirPath) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.readdirSync(${dirPath})`, 0);
- return fs.readdirSync(dirPath, { withFileTypes: true });
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- readdirStringSync(dirPath) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.readdirStringSync(${dirPath})`, 0);
- return fs.readdirSync(dirPath);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- isDirEmptySync(dirPath) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.isDirEmptySync(${dirPath})`, 0);
- const files = this.readdirSync(dirPath);
- return files.length === 0;
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- rmdirSync(dirPath) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.rmdirSync(${dirPath})`, 0);
- fs.rmdirSync(dirPath);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- rmSync(path, options) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`fs.rmSync(${path})`, 0);
- fs.rmSync(path, options);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
- },
- createWriteStream(path) {
- return fs.createWriteStream(path);
- },
- async readFileBytes(fsPath, maxBytes) {
- if (maxBytes === undefined) {
- return readFilePromise(fsPath);
- }
- const handle = await open(fsPath, "r");
- try {
- const { size } = await handle.stat();
- const readSize = Math.min(size, maxBytes);
- const buffer = Buffer.allocUnsafe(readSize);
- let offset = 0;
- while (offset < readSize) {
- const { bytesRead } = await handle.read(buffer, offset, readSize - offset, offset);
- if (bytesRead === 0)
- break;
- offset += bytesRead;
- }
- return offset < readSize ? buffer.subarray(0, offset) : buffer;
- } finally {
- await handle.close();
- }
- }
- };
- activeFs = NodeFsOperations;
-});
-
-// src/utils/process.ts
-function handleEPIPE(stream) {
- return (err) => {
- if (err.code === "EPIPE") {
- stream.destroy();
- }
- };
-}
-function registerProcessOutputErrorHandlers() {
- process.stdout.on("error", handleEPIPE(process.stdout));
- process.stderr.on("error", handleEPIPE(process.stderr));
-}
-function writeOut(stream, data) {
- if (stream.destroyed) {
- return;
- }
- stream.write(data);
-}
-function writeToStdout(data) {
- writeOut(process.stdout, data);
-}
-function writeToStderr(data) {
- writeOut(process.stderr, data);
-}
-function peekForStdinData(stream, ms) {
- return new Promise((resolve2) => {
- const done = (timedOut) => {
- clearTimeout(peek);
- stream.off("end", onEnd);
- stream.off("data", onFirstData);
- resolve2(timedOut);
- };
- const onEnd = () => done(false);
- const onFirstData = () => clearTimeout(peek);
- const peek = setTimeout(done, ms, true);
- stream.once("end", onEnd);
- stream.once("data", onFirstData);
- });
-}
-
-// src/utils/debug.ts
-import { appendFile, mkdir, symlink, unlink } from "fs/promises";
-import { dirname as dirname2, join as join3 } from "path";
-function enableDebugLogging() {
- const wasActive = isDebugMode() || process.env.USER_TYPE === "ant";
- runtimeDebugEnabled = true;
- isDebugMode.cache.clear?.();
- return wasActive;
-}
-function shouldLogDebugMessage(message) {
- if (false) {}
- if (process.env.USER_TYPE !== "ant" && !isDebugMode()) {
- return false;
- }
- if (typeof process === "undefined" || typeof process.versions === "undefined" || typeof process.versions.node === "undefined") {
- return false;
- }
- const filter = getDebugFilter();
- return shouldShowDebugMessage(message, filter);
-}
-function setHasFormattedOutput(value) {
- hasFormattedOutput = value;
-}
-function getHasFormattedOutput() {
- return hasFormattedOutput;
-}
-async function appendAsync(needMkdir, dir, path, content) {
- if (needMkdir) {
- await mkdir(dir, { recursive: true }).catch(() => {});
- }
- await appendFile(path, content);
- updateLatestDebugLogSymlink();
-}
-function noop() {}
-function getDebugWriter() {
- if (!debugWriter) {
- let ensuredDir = null;
- debugWriter = createBufferedWriter({
- writeFn: (content) => {
- const path = getDebugLogPath();
- const dir = dirname2(path);
- const needMkdir = ensuredDir !== dir;
- ensuredDir = dir;
- if (isDebugMode()) {
- if (needMkdir) {
- try {
- getFsImplementation().mkdirSync(dir);
- } catch {}
- }
- getFsImplementation().appendFileSync(path, content);
- updateLatestDebugLogSymlink();
- return;
- }
- pendingWrite = pendingWrite.then(appendAsync.bind(null, needMkdir, dir, path, content)).catch(noop);
- },
- flushIntervalMs: 1000,
- maxBufferSize: 100,
- immediateMode: isDebugMode()
- });
- registerCleanup(async () => {
- debugWriter?.dispose();
- await pendingWrite;
- });
- }
- return debugWriter;
-}
-function logForDebugging(message, { level } = {
- level: "debug"
-}) {
- if (LEVEL_ORDER[level] < LEVEL_ORDER[getMinDebugLogLevel()]) {
- return;
- }
- if (!shouldLogDebugMessage(message)) {
- return;
- }
- if (hasFormattedOutput && message.includes(`
-`)) {
- message = jsonStringify(message);
- }
- const timestamp = new Date().toISOString();
- const output = `${timestamp} [${level.toUpperCase()}] ${message.trim()}
-`;
- if (isDebugToStdErr()) {
- writeToStderr(output);
- return;
- }
- getDebugWriter().write(output);
-}
-function getDebugLogPath() {
- return getDebugFilePath() ?? process.env.CLAUDE_CODE_DEBUG_LOGS_DIR ?? join3(getClaudeConfigHomeDir(), "debug", `${getSessionId()}.txt`);
-}
-function logAntError(context, error) {
- if (process.env.USER_TYPE !== "ant") {
- return;
- }
- if (error instanceof Error && error.stack) {
- logForDebugging(`[ANT-ONLY] ${context} stack trace:
-${error.stack}`, {
- level: "error"
- });
- }
-}
-var LEVEL_ORDER, getMinDebugLogLevel, runtimeDebugEnabled = false, isDebugMode, getDebugFilter, isDebugToStdErr, getDebugFilePath, hasFormattedOutput = false, debugWriter = null, pendingWrite, updateLatestDebugLogSymlink;
-var init_debug = __esm(() => {
- init_memoize();
- init_state();
- init_cleanupRegistry();
- init_debugFilter();
- init_envUtils();
- init_fsOperations();
- init_slowOperations();
- LEVEL_ORDER = {
- verbose: 0,
- debug: 1,
- info: 2,
- warn: 3,
- error: 4
- };
- getMinDebugLogLevel = memoize_default(() => {
- const raw = process.env.CLAUDE_CODE_DEBUG_LOG_LEVEL?.toLowerCase().trim();
- if (raw && Object.hasOwn(LEVEL_ORDER, raw)) {
- return raw;
- }
- return "debug";
- });
- isDebugMode = memoize_default(() => {
- return runtimeDebugEnabled || isEnvTruthy(process.env.DEBUG) || isEnvTruthy(process.env.DEBUG_SDK) || process.argv.includes("--debug") || process.argv.includes("-d") || isDebugToStdErr() || process.argv.some((arg) => arg.startsWith("--debug=")) || getDebugFilePath() !== null;
- });
- getDebugFilter = memoize_default(() => {
- const debugArg = process.argv.find((arg) => arg.startsWith("--debug="));
- if (!debugArg) {
- return null;
- }
- const filterPattern = debugArg.substring("--debug=".length);
- return parseDebugFilter(filterPattern);
- });
- isDebugToStdErr = memoize_default(() => {
- return process.argv.includes("--debug-to-stderr") || process.argv.includes("-d2e");
- });
- getDebugFilePath = memoize_default(() => {
- for (let i = 0;i < process.argv.length; i++) {
- const arg = process.argv[i];
- if (arg.startsWith("--debug-file=")) {
- return arg.substring("--debug-file=".length);
- }
- if (arg === "--debug-file" && i + 1 < process.argv.length) {
- return process.argv[i + 1];
- }
- }
- return null;
- });
- pendingWrite = Promise.resolve();
- updateLatestDebugLogSymlink = memoize_default(async () => {
- try {
- const debugLogPath = getDebugLogPath();
- const debugLogsDir = dirname2(debugLogPath);
- const latestSymlinkPath = join3(debugLogsDir, "latest");
- await unlink(latestSymlinkPath).catch(() => {});
- await symlink(debugLogPath, latestSymlinkPath);
- } catch {}
- });
-});
-
-// src/utils/intl.ts
-function getGraphemeSegmenter() {
- if (!graphemeSegmenter) {
- graphemeSegmenter = new Intl.Segmenter(undefined, {
- granularity: "grapheme"
- });
- }
- return graphemeSegmenter;
-}
-function firstGrapheme(text) {
- if (!text)
- return "";
- const segments = getGraphemeSegmenter().segment(text);
- const first = segments[Symbol.iterator]().next().value;
- return first?.segment ?? "";
-}
-function lastGrapheme(text) {
- if (!text)
- return "";
- let last = "";
- for (const { segment } of getGraphemeSegmenter().segment(text)) {
- last = segment;
- }
- return last;
-}
-function getWordSegmenter() {
- if (!wordSegmenter) {
- wordSegmenter = new Intl.Segmenter(undefined, { granularity: "word" });
- }
- return wordSegmenter;
-}
-function getRelativeTimeFormat(style, numeric) {
- const key = `${style}:${numeric}`;
- let rtf = rtfCache.get(key);
- if (!rtf) {
- rtf = new Intl.RelativeTimeFormat("en", { style, numeric });
- rtfCache.set(key, rtf);
- }
- return rtf;
-}
-function getTimeZone() {
- if (!cachedTimeZone) {
- cachedTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
- }
- return cachedTimeZone;
-}
-var graphemeSegmenter = null, wordSegmenter = null, rtfCache, cachedTimeZone = null;
-var init_intl = __esm(() => {
- rtfCache = new Map;
-});
-
-// node_modules/emoji-regex/index.mjs
-var emoji_regex_default = () => {
- return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
-};
-
-// node_modules/get-east-asian-width/lookup-data.js
-var ambiguousRanges, fullwidthRanges, halfwidthRanges, narrowRanges, wideRanges;
-var init_lookup_data = __esm(() => {
- ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109];
- fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510];
- halfwidthRanges = [8361, 8361, 65377, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65512, 65518];
- narrowRanges = [32, 126, 162, 163, 165, 166, 172, 172, 175, 175, 10214, 10221, 10629, 10630];
- wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101589, 101631, 101662, 101760, 101874, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128728, 128732, 128735, 128747, 128748, 128756, 128764, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129674, 129678, 129734, 129736, 129736, 129741, 129756, 129759, 129770, 129775, 129784, 131072, 196605, 196608, 262141];
-});
-
-// node_modules/get-east-asian-width/utilities.js
-var isInRange = (ranges, codePoint) => {
- let low = 0;
- let high = Math.floor(ranges.length / 2) - 1;
- while (low <= high) {
- const mid = Math.floor((low + high) / 2);
- const i = mid * 2;
- if (codePoint < ranges[i]) {
- high = mid - 1;
- } else if (codePoint > ranges[i + 1]) {
- low = mid + 1;
- } else {
- return true;
- }
- }
- return false;
-};
-
-// node_modules/get-east-asian-width/lookup.js
-function findWideFastPathRange(ranges) {
- let fastPathStart = ranges[0];
- let fastPathEnd = ranges[1];
- for (let index = 0;index < ranges.length; index += 2) {
- const start = ranges[index];
- const end = ranges[index + 1];
- if (commonCjkCodePoint >= start && commonCjkCodePoint <= end) {
- return [start, end];
- }
- if (end - start > fastPathEnd - fastPathStart) {
- fastPathStart = start;
- fastPathEnd = end;
- }
- }
- return [fastPathStart, fastPathEnd];
-}
-var minimumAmbiguousCodePoint, maximumAmbiguousCodePoint, minimumFullWidthCodePoint, maximumFullWidthCodePoint, minimumHalfWidthCodePoint, maximumHalfWidthCodePoint, minimumNarrowCodePoint, maximumNarrowCodePoint, minimumWideCodePoint, maximumWideCodePoint, commonCjkCodePoint = 19968, wideFastPathStart, wideFastPathEnd, isAmbiguous = (codePoint) => {
- if (codePoint < minimumAmbiguousCodePoint || codePoint > maximumAmbiguousCodePoint) {
- return false;
- }
- return isInRange(ambiguousRanges, codePoint);
-}, isFullWidth = (codePoint) => {
- if (codePoint < minimumFullWidthCodePoint || codePoint > maximumFullWidthCodePoint) {
- return false;
- }
- return isInRange(fullwidthRanges, codePoint);
-}, isWide = (codePoint) => {
- if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) {
- return true;
- }
- if (codePoint < minimumWideCodePoint || codePoint > maximumWideCodePoint) {
- return false;
- }
- return isInRange(wideRanges, codePoint);
-};
-var init_lookup = __esm(() => {
- init_lookup_data();
- minimumAmbiguousCodePoint = ambiguousRanges[0];
- maximumAmbiguousCodePoint = ambiguousRanges.at(-1);
- minimumFullWidthCodePoint = fullwidthRanges[0];
- maximumFullWidthCodePoint = fullwidthRanges.at(-1);
- minimumHalfWidthCodePoint = halfwidthRanges[0];
- maximumHalfWidthCodePoint = halfwidthRanges.at(-1);
- minimumNarrowCodePoint = narrowRanges[0];
- maximumNarrowCodePoint = narrowRanges.at(-1);
- minimumWideCodePoint = wideRanges[0];
- maximumWideCodePoint = wideRanges.at(-1);
- [wideFastPathStart, wideFastPathEnd] = findWideFastPathRange(wideRanges);
-});
-
-// node_modules/get-east-asian-width/index.js
-function validate(codePoint) {
- if (!Number.isSafeInteger(codePoint)) {
- throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
- }
-}
-function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
- validate(codePoint);
- if (isFullWidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) {
- return 2;
- }
- return 1;
-}
-var init_get_east_asian_width = __esm(() => {
- init_lookup();
-});
-
-// node_modules/ansi-regex/index.js
-function ansiRegex({ onlyFirst = false } = {}) {
- const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
- const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`;
- const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
- const pattern = `${osc}|${csi}`;
- return new RegExp(pattern, onlyFirst ? undefined : "g");
-}
-
-// node_modules/strip-ansi/index.js
-function stripAnsi(string) {
- if (typeof string !== "string") {
- throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
- }
- if (!string.includes("\x1B") && !string.includes("\x9B")) {
- return string;
- }
- return string.replace(regex, "");
-}
-var regex;
-var init_strip_ansi = __esm(() => {
- regex = ansiRegex();
-});
-
-// src/ink/stringWidth.ts
-function stringWidthJavaScript(str) {
- if (typeof str !== "string" || str.length === 0) {
- return 0;
- }
- let isPureAscii = true;
- for (let i = 0;i < str.length; i++) {
- const code = str.charCodeAt(i);
- if (code >= 127 || code === 27) {
- isPureAscii = false;
- break;
- }
- }
- if (isPureAscii) {
- let width2 = 0;
- for (let i = 0;i < str.length; i++) {
- const code = str.charCodeAt(i);
- if (code > 31) {
- width2++;
- }
- }
- return width2;
- }
- if (str.includes("\x1B")) {
- str = stripAnsi(str);
- if (str.length === 0) {
- return 0;
- }
- }
- if (!needsSegmentation(str)) {
- let width2 = 0;
- for (const char of str) {
- const codePoint = char.codePointAt(0);
- if (!isZeroWidth(codePoint)) {
- width2 += eastAsianWidth(codePoint, { ambiguousAsWide: false });
- }
- }
- return width2;
- }
- let width = 0;
- for (const { segment: grapheme } of getGraphemeSegmenter().segment(str)) {
- EMOJI_REGEX.lastIndex = 0;
- if (EMOJI_REGEX.test(grapheme)) {
- width += getEmojiWidth(grapheme);
- continue;
- }
- for (const char of grapheme) {
- const codePoint = char.codePointAt(0);
- if (!isZeroWidth(codePoint)) {
- width += eastAsianWidth(codePoint, { ambiguousAsWide: false });
- break;
- }
- }
- }
- return width;
-}
-function needsSegmentation(str) {
- for (const char of str) {
- const cp = char.codePointAt(0);
- if (cp >= 127744 && cp <= 129791)
- return true;
- if (cp >= 9728 && cp <= 10175)
- return true;
- if (cp >= 127462 && cp <= 127487)
- return true;
- if (cp >= 65024 && cp <= 65039)
- return true;
- if (cp === 8205)
- return true;
- }
- return false;
-}
-function getEmojiWidth(grapheme) {
- const first = grapheme.codePointAt(0);
- if (first >= 127462 && first <= 127487) {
- let count = 0;
- for (const _ of grapheme)
- count++;
- return count === 1 ? 1 : 2;
- }
- if (grapheme.length === 2) {
- const second = grapheme.codePointAt(1);
- if (second === 65039 && (first >= 48 && first <= 57 || first === 35 || first === 42)) {
- return 1;
- }
- }
- return 2;
-}
-function isZeroWidth(codePoint) {
- if (codePoint >= 32 && codePoint < 127)
- return false;
- if (codePoint >= 160 && codePoint < 768)
- return codePoint === 173;
- if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159)
- return true;
- if (codePoint >= 8203 && codePoint <= 8205 || codePoint === 65279 || codePoint >= 8288 && codePoint <= 8292) {
- return true;
- }
- if (codePoint >= 65024 && codePoint <= 65039 || codePoint >= 917760 && codePoint <= 917999) {
- return true;
- }
- if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
- return true;
- }
- if (codePoint >= 2304 && codePoint <= 3407) {
- const offset = codePoint & 127;
- if (offset <= 3)
- return true;
- if (offset >= 58 && offset <= 79)
- return true;
- if (offset >= 81 && offset <= 87)
- return true;
- if (offset >= 98 && offset <= 99)
- return true;
- }
- if (codePoint === 3633 || codePoint >= 3636 && codePoint <= 3642 || codePoint >= 3655 && codePoint <= 3662 || codePoint === 3761 || codePoint >= 3764 && codePoint <= 3772 || codePoint >= 3784 && codePoint <= 3789) {
- return true;
- }
- if (codePoint >= 1536 && codePoint <= 1541 || codePoint === 1757 || codePoint === 1807 || codePoint === 2274) {
- return true;
- }
- if (codePoint >= 55296 && codePoint <= 57343)
- return true;
- if (codePoint >= 917504 && codePoint <= 917631)
- return true;
- return false;
-}
-var EMOJI_REGEX, bunStringWidth, BUN_STRING_WIDTH_OPTS, stringWidth;
-var init_stringWidth = __esm(() => {
- init_get_east_asian_width();
- init_strip_ansi();
- init_intl();
- EMOJI_REGEX = emoji_regex_default();
- bunStringWidth = typeof Bun !== "undefined" && typeof Bun.stringWidth === "function" ? Bun.stringWidth : null;
- BUN_STRING_WIDTH_OPTS = { ambiguousIsNarrow: true };
- stringWidth = bunStringWidth ? (str) => bunStringWidth(str, BUN_STRING_WIDTH_OPTS) : stringWidthJavaScript;
-});
-
-// src/utils/truncate.ts
-function truncatePathMiddle(path, maxLength) {
- if (stringWidth(path) <= maxLength) {
- return path;
- }
- if (maxLength <= 0) {
- return "\u2026";
- }
- if (maxLength < 5) {
- return truncateToWidth(path, maxLength);
- }
- const lastSlash = path.lastIndexOf("/");
- const filename = lastSlash >= 0 ? path.slice(lastSlash) : path;
- const directory = lastSlash >= 0 ? path.slice(0, lastSlash) : "";
- const filenameWidth = stringWidth(filename);
- if (filenameWidth >= maxLength - 1) {
- return truncateStartToWidth(path, maxLength);
- }
- const availableForDir = maxLength - 1 - filenameWidth;
- if (availableForDir <= 0) {
- return truncateStartToWidth(filename, maxLength);
- }
- const truncatedDir = truncateToWidthNoEllipsis(directory, availableForDir);
- return truncatedDir + "\u2026" + filename;
-}
-function truncateToWidth(text, maxWidth) {
- if (stringWidth(text) <= maxWidth)
- return text;
- if (maxWidth <= 1)
- return "\u2026";
- let width = 0;
- let result = "";
- for (const { segment } of getGraphemeSegmenter().segment(text)) {
- const segWidth = stringWidth(segment);
- if (width + segWidth > maxWidth - 1)
- break;
- result += segment;
- width += segWidth;
- }
- return result + "\u2026";
-}
-function truncateStartToWidth(text, maxWidth) {
- if (stringWidth(text) <= maxWidth)
- return text;
- if (maxWidth <= 1)
- return "\u2026";
- const segments = [...getGraphemeSegmenter().segment(text)];
- let width = 0;
- let startIdx = segments.length;
- for (let i = segments.length - 1;i >= 0; i--) {
- const segWidth = stringWidth(segments[i].segment);
- if (width + segWidth > maxWidth - 1)
- break;
- width += segWidth;
- startIdx = i;
- }
- return "\u2026" + segments.slice(startIdx).map((s) => s.segment).join("");
-}
-function truncateToWidthNoEllipsis(text, maxWidth) {
- if (stringWidth(text) <= maxWidth)
- return text;
- if (maxWidth <= 0)
- return "";
- let width = 0;
- let result = "";
- for (const { segment } of getGraphemeSegmenter().segment(text)) {
- const segWidth = stringWidth(segment);
- if (width + segWidth > maxWidth)
- break;
- result += segment;
- width += segWidth;
- }
- return result;
-}
-function truncate(str, maxWidth, singleLine = false) {
- let result = str;
- if (singleLine) {
- const firstNewline = str.indexOf(`
-`);
- if (firstNewline !== -1) {
- result = str.substring(0, firstNewline);
- if (stringWidth(result) + 1 > maxWidth) {
- return truncateToWidth(result, maxWidth);
- }
- return `${result}\u2026`;
- }
- }
- if (stringWidth(result) <= maxWidth) {
- return result;
- }
- return truncateToWidth(result, maxWidth);
-}
-var init_truncate = __esm(() => {
- init_stringWidth();
- init_intl();
-});
-
-// src/utils/format.ts
-function formatFileSize(sizeInBytes) {
- const kb = sizeInBytes / 1024;
- if (kb < 1) {
- return `${sizeInBytes} bytes`;
- }
- if (kb < 1024) {
- return `${kb.toFixed(1).replace(/\.0$/, "")}KB`;
- }
- const mb = kb / 1024;
- if (mb < 1024) {
- return `${mb.toFixed(1).replace(/\.0$/, "")}MB`;
- }
- const gb = mb / 1024;
- return `${gb.toFixed(1).replace(/\.0$/, "")}GB`;
-}
-function formatSecondsShort(ms) {
- return `${(ms / 1000).toFixed(1)}s`;
-}
-function formatDuration(ms, options) {
- if (ms < 60000) {
- if (ms === 0) {
- return "0s";
- }
- if (ms < 1) {
- const s2 = (ms / 1000).toFixed(1);
- return `${s2}s`;
- }
- const s = Math.floor(ms / 1000).toString();
- return `${s}s`;
- }
- let days = Math.floor(ms / 86400000);
- let hours = Math.floor(ms % 86400000 / 3600000);
- let minutes = Math.floor(ms % 3600000 / 60000);
- let seconds = Math.round(ms % 60000 / 1000);
- if (seconds === 60) {
- seconds = 0;
- minutes++;
- }
- if (minutes === 60) {
- minutes = 0;
- hours++;
- }
- if (hours === 24) {
- hours = 0;
- days++;
- }
- const hide = options?.hideTrailingZeros;
- if (options?.mostSignificantOnly) {
- if (days > 0)
- return `${days}d`;
- if (hours > 0)
- return `${hours}h`;
- if (minutes > 0)
- return `${minutes}m`;
- return `${seconds}s`;
- }
- if (days > 0) {
- if (hide && hours === 0 && minutes === 0)
- return `${days}d`;
- if (hide && minutes === 0)
- return `${days}d ${hours}h`;
- return `${days}d ${hours}h ${minutes}m`;
- }
- if (hours > 0) {
- if (hide && minutes === 0 && seconds === 0)
- return `${hours}h`;
- if (hide && seconds === 0)
- return `${hours}h ${minutes}m`;
- return `${hours}h ${minutes}m ${seconds}s`;
- }
- if (minutes > 0) {
- if (hide && seconds === 0)
- return `${minutes}m`;
- return `${minutes}m ${seconds}s`;
- }
- return `${seconds}s`;
-}
-function formatNumber(number) {
- const shouldUseConsistentDecimals = number >= 1000;
- return getNumberFormatter(shouldUseConsistentDecimals).format(number).toLowerCase();
-}
-function formatTokens(count) {
- return formatNumber(count).replace(".0", "");
-}
-function formatRelativeTime(date, options = {}) {
- const { style = "narrow", numeric = "always", now = new Date } = options;
- const diffInMs = date.getTime() - now.getTime();
- const diffInSeconds = Math.trunc(diffInMs / 1000);
- const intervals = [
- { unit: "year", seconds: 31536000, shortUnit: "y" },
- { unit: "month", seconds: 2592000, shortUnit: "mo" },
- { unit: "week", seconds: 604800, shortUnit: "w" },
- { unit: "day", seconds: 86400, shortUnit: "d" },
- { unit: "hour", seconds: 3600, shortUnit: "h" },
- { unit: "minute", seconds: 60, shortUnit: "m" },
- { unit: "second", seconds: 1, shortUnit: "s" }
- ];
- for (const { unit, seconds: intervalSeconds, shortUnit } of intervals) {
- if (Math.abs(diffInSeconds) >= intervalSeconds) {
- const value = Math.trunc(diffInSeconds / intervalSeconds);
- if (style === "narrow") {
- return diffInSeconds < 0 ? `${Math.abs(value)}${shortUnit} ago` : `in ${value}${shortUnit}`;
- }
- return getRelativeTimeFormat("long", numeric).format(value, unit);
- }
- }
- if (style === "narrow") {
- return diffInSeconds <= 0 ? "0s ago" : "in 0s";
- }
- return getRelativeTimeFormat(style, numeric).format(0, "second");
-}
-function formatRelativeTimeAgo(date, options = {}) {
- const { now = new Date, ...restOptions } = options;
- if (date > now) {
- return formatRelativeTime(date, { ...restOptions, now });
- }
- return formatRelativeTime(date, { ...restOptions, numeric: "always", now });
-}
-function formatLogMetadata(log) {
- const sizeOrCount = log.fileSize !== undefined ? formatFileSize(log.fileSize) : `${log.messageCount} messages`;
- const parts = [
- formatRelativeTimeAgo(log.modified, { style: "short" }),
- ...log.gitBranch ? [log.gitBranch] : [],
- sizeOrCount
- ];
- if (log.tag) {
- parts.push(`#${log.tag}`);
- }
- if (log.agentSetting) {
- parts.push(`@${log.agentSetting}`);
- }
- if (log.prNumber) {
- parts.push(log.prRepository ? `${log.prRepository}#${log.prNumber}` : `#${log.prNumber}`);
- }
- return parts.join(" \xB7 ");
-}
-function formatResetTime(timestampInSeconds, showTimezone = false, showTime = true) {
- if (!timestampInSeconds)
- return;
- const date = new Date(timestampInSeconds * 1000);
- const now = new Date;
- const minutes = date.getMinutes();
- const hoursUntilReset = (date.getTime() - now.getTime()) / (1000 * 60 * 60);
- if (hoursUntilReset > 24) {
- const dateOptions = {
- month: "short",
- day: "numeric",
- hour: showTime ? "numeric" : undefined,
- minute: !showTime || minutes === 0 ? undefined : "2-digit",
- hour12: showTime ? true : undefined
- };
- if (date.getFullYear() !== now.getFullYear()) {
- dateOptions.year = "numeric";
- }
- const dateString = date.toLocaleString("en-US", dateOptions);
- return dateString.replace(/ ([AP]M)/i, (_match, ampm) => ampm.toLowerCase()) + (showTimezone ? ` (${getTimeZone()})` : "");
- }
- const timeString = date.toLocaleTimeString("en-US", {
- hour: "numeric",
- minute: minutes === 0 ? undefined : "2-digit",
- hour12: true
- });
- return timeString.replace(/ ([AP]M)/i, (_match, ampm) => ampm.toLowerCase()) + (showTimezone ? ` (${getTimeZone()})` : "");
-}
-function formatResetText(resetsAt, showTimezone = false, showTime = true) {
- const dt = new Date(resetsAt);
- return `${formatResetTime(Math.floor(dt.getTime() / 1000), showTimezone, showTime)}`;
-}
-var numberFormatterForConsistentDecimals = null, numberFormatterForInconsistentDecimals = null, getNumberFormatter = (useConsistentDecimals) => {
- if (useConsistentDecimals) {
- if (!numberFormatterForConsistentDecimals) {
- numberFormatterForConsistentDecimals = new Intl.NumberFormat("en-US", {
- notation: "compact",
- maximumFractionDigits: 1,
- minimumFractionDigits: 1
- });
- }
- return numberFormatterForConsistentDecimals;
- } else {
- if (!numberFormatterForInconsistentDecimals) {
- numberFormatterForInconsistentDecimals = new Intl.NumberFormat("en-US", {
- notation: "compact",
- maximumFractionDigits: 1,
- minimumFractionDigits: 0
- });
- }
- return numberFormatterForInconsistentDecimals;
- }
-};
-var init_format = __esm(() => {
- init_intl();
- init_truncate();
-});
-
-// src/utils/profilerBase.ts
-function getPerformance() {
- if (!performance2) {
- performance2 = __require("perf_hooks").performance;
- }
- return performance2;
-}
-function formatMs(ms) {
- return ms.toFixed(3);
-}
-function formatTimelineLine(totalMs, deltaMs, name, memory, totalPad, deltaPad, extra = "") {
- const memInfo = memory ? ` | RSS: ${formatFileSize(memory.rss)}, Heap: ${formatFileSize(memory.heapUsed)}` : "";
- return `[+${formatMs(totalMs).padStart(totalPad)}ms] (+${formatMs(deltaMs).padStart(deltaPad)}ms) ${name}${extra}${memInfo}`;
-}
-var performance2 = null;
-var init_profilerBase = __esm(() => {
- init_format();
-});
-
-// src/utils/startupProfiler.ts
-import { dirname as dirname3, join as join4 } from "path";
-function profileCheckpoint(name) {
- if (!SHOULD_PROFILE)
- return;
- const perf = getPerformance();
- perf.mark(name);
- if (DETAILED_PROFILING) {
- memorySnapshots.push(process.memoryUsage());
- }
-}
-function getReport() {
- if (!DETAILED_PROFILING) {
- return "Startup profiling not enabled";
- }
- const perf = getPerformance();
- const marks = perf.getEntriesByType("mark");
- if (marks.length === 0) {
- return "No profiling checkpoints recorded";
- }
- const lines = [];
- lines.push("=".repeat(80));
- lines.push("STARTUP PROFILING REPORT");
- lines.push("=".repeat(80));
- lines.push("");
- let prevTime = 0;
- for (const [i, mark] of marks.entries()) {
- lines.push(formatTimelineLine(mark.startTime, mark.startTime - prevTime, mark.name, memorySnapshots[i], 8, 7));
- prevTime = mark.startTime;
- }
- const lastMark = marks[marks.length - 1];
- lines.push("");
- lines.push(`Total startup time: ${formatMs(lastMark?.startTime ?? 0)}ms`);
- lines.push("=".repeat(80));
- return lines.join(`
-`);
-}
-function profileReport() {
- if (reported)
- return;
- reported = true;
- logStartupPerf();
- if (DETAILED_PROFILING) {
- const path = getStartupPerfLogPath();
- const dir = dirname3(path);
- const fs2 = getFsImplementation();
- fs2.mkdirSync(dir);
- writeFileSync_DEPRECATED(path, getReport(), {
- encoding: "utf8",
- flush: true
- });
- logForDebugging("Startup profiling report:");
- logForDebugging(getReport());
- }
-}
-function getStartupPerfLogPath() {
- return join4(getClaudeConfigHomeDir(), "startup-perf", `${getSessionId()}.txt`);
-}
-function logStartupPerf() {
- if (!STATSIG_LOGGING_SAMPLED)
- return;
- const perf = getPerformance();
- const marks = perf.getEntriesByType("mark");
- if (marks.length === 0)
- return;
- const checkpointTimes = new Map;
- for (const mark of marks) {
- checkpointTimes.set(mark.name, mark.startTime);
- }
- const metadata = {};
- for (const [phaseName, [startCheckpoint, endCheckpoint]] of Object.entries(PHASE_DEFINITIONS)) {
- const startTime = checkpointTimes.get(startCheckpoint);
- const endTime = checkpointTimes.get(endCheckpoint);
- if (startTime !== undefined && endTime !== undefined) {
- metadata[`${phaseName}_ms`] = Math.round(endTime - startTime);
- }
- }
- metadata.checkpoint_count = marks.length;
- logEvent("tengu_startup_perf", metadata);
-}
-var DETAILED_PROFILING, STATSIG_SAMPLE_RATE = 0.005, STATSIG_LOGGING_SAMPLED, SHOULD_PROFILE, memorySnapshots, PHASE_DEFINITIONS, reported = false;
-var init_startupProfiler = __esm(() => {
- init_state();
- init_analytics();
- init_debug();
- init_envUtils();
- init_fsOperations();
- init_profilerBase();
- init_slowOperations();
- DETAILED_PROFILING = isEnvTruthy(process.env.CLAUDE_CODE_PROFILE_STARTUP);
- STATSIG_LOGGING_SAMPLED = process.env.USER_TYPE === "ant" || Math.random() < STATSIG_SAMPLE_RATE;
- SHOULD_PROFILE = DETAILED_PROFILING || STATSIG_LOGGING_SAMPLED;
- memorySnapshots = [];
- PHASE_DEFINITIONS = {
- import_time: ["cli_entry", "main_tsx_imports_loaded"],
- init_time: ["init_function_start", "init_function_end"],
- settings_time: ["eagerLoadSettings_start", "eagerLoadSettings_end"],
- total_time: ["cli_entry", "main_after_run"]
- };
- if (SHOULD_PROFILE) {
- profileCheckpoint("profiler_initialized");
- }
-});
-
-// src/utils/settings/mdm/constants.ts
-import { homedir as homedir3, userInfo } from "os";
-import { join as join5 } from "path";
-function getMacOSPlistPaths() {
- let username = "";
- try {
- username = userInfo().username;
- } catch {}
- const paths = [];
- if (username) {
- paths.push({
- path: `/Library/Managed Preferences/${username}/${MACOS_PREFERENCE_DOMAIN}.plist`,
- label: "per-user managed preferences"
- });
- }
- paths.push({
- path: `/Library/Managed Preferences/${MACOS_PREFERENCE_DOMAIN}.plist`,
- label: "device-level managed preferences"
- });
- if (process.env.USER_TYPE === "ant") {
- paths.push({
- path: join5(homedir3(), "Library", "Preferences", `${MACOS_PREFERENCE_DOMAIN}.plist`),
- label: "user preferences (ant-only)"
- });
- }
- return paths;
-}
-var MACOS_PREFERENCE_DOMAIN = "com.anthropic.claudecode", WINDOWS_REGISTRY_KEY_PATH_HKLM = "HKLM\\SOFTWARE\\Policies\\ClaudeCode", WINDOWS_REGISTRY_KEY_PATH_HKCU = "HKCU\\SOFTWARE\\Policies\\ClaudeCode", WINDOWS_REGISTRY_VALUE_NAME = "Settings", PLUTIL_PATH = "/usr/bin/plutil", PLUTIL_ARGS_PREFIX, MDM_SUBPROCESS_TIMEOUT_MS = 5000;
-var init_constants = __esm(() => {
- PLUTIL_ARGS_PREFIX = ["-convert", "json", "-o", "-", "--"];
-});
-
-// src/utils/settings/mdm/rawRead.ts
-import { execFile } from "child_process";
-import { existsSync as existsSync2 } from "fs";
-function execFilePromise(cmd, args) {
- return new Promise((resolve2) => {
- execFile(cmd, args, { encoding: "utf-8", timeout: MDM_SUBPROCESS_TIMEOUT_MS }, (err, stdout) => {
- resolve2({ stdout: stdout ?? "", code: err ? 1 : 0 });
- });
- });
-}
-function fireRawRead() {
- return (async () => {
- if (process.platform === "darwin") {
- const plistPaths = getMacOSPlistPaths();
- const allResults = await Promise.all(plistPaths.map(async ({ path, label }) => {
- if (!existsSync2(path)) {
- return { stdout: "", label, ok: false };
- }
- const { stdout, code } = await execFilePromise(PLUTIL_PATH, [
- ...PLUTIL_ARGS_PREFIX,
- path
- ]);
- return { stdout, label, ok: code === 0 && !!stdout };
- }));
- const winner = allResults.find((r) => r.ok);
- return {
- plistStdouts: winner ? [{ stdout: winner.stdout, label: winner.label }] : [],
- hklmStdout: null,
- hkcuStdout: null
- };
- }
- if (process.platform === "win32") {
- const [hklm, hkcu] = await Promise.all([
- execFilePromise("reg", [
- "query",
- WINDOWS_REGISTRY_KEY_PATH_HKLM,
- "/v",
- WINDOWS_REGISTRY_VALUE_NAME
- ]),
- execFilePromise("reg", [
- "query",
- WINDOWS_REGISTRY_KEY_PATH_HKCU,
- "/v",
- WINDOWS_REGISTRY_VALUE_NAME
- ])
- ]);
- return {
- plistStdouts: null,
- hklmStdout: hklm.code === 0 ? hklm.stdout : null,
- hkcuStdout: hkcu.code === 0 ? hkcu.stdout : null
- };
- }
- return { plistStdouts: null, hklmStdout: null, hkcuStdout: null };
- })();
-}
-function startMdmRawRead() {
- if (rawReadPromise)
- return;
- rawReadPromise = fireRawRead();
-}
-function getMdmRawReadPromise() {
- return rawReadPromise;
-}
-var rawReadPromise = null;
-var init_rawRead = __esm(() => {
- init_constants();
-});
-
-// src/constants/oauth.ts
-var exports_oauth = {};
-__export(exports_oauth, {
- getOauthConfig: () => getOauthConfig,
- fileSuffixForOauthConfig: () => fileSuffixForOauthConfig,
- OAUTH_BETA_HEADER: () => OAUTH_BETA_HEADER,
- MCP_CLIENT_METADATA_URL: () => MCP_CLIENT_METADATA_URL,
- CONSOLE_OAUTH_SCOPES: () => CONSOLE_OAUTH_SCOPES,
- CLAUDE_AI_PROFILE_SCOPE: () => CLAUDE_AI_PROFILE_SCOPE,
- CLAUDE_AI_OAUTH_SCOPES: () => CLAUDE_AI_OAUTH_SCOPES,
- CLAUDE_AI_INFERENCE_SCOPE: () => CLAUDE_AI_INFERENCE_SCOPE,
- ALL_OAUTH_SCOPES: () => ALL_OAUTH_SCOPES
-});
-function getOauthConfigType() {
- if (process.env.USER_TYPE === "ant") {
- if (isEnvTruthy(process.env.USE_LOCAL_OAUTH)) {
- return "local";
- }
- if (isEnvTruthy(process.env.USE_STAGING_OAUTH)) {
- return "staging";
- }
- }
- return "prod";
-}
-function fileSuffixForOauthConfig() {
- if (process.env.CLAUDE_CODE_CUSTOM_OAUTH_URL) {
- return "-custom-oauth";
- }
- switch (getOauthConfigType()) {
- case "local":
- return "-local-oauth";
- case "staging":
- return "-staging-oauth";
- case "prod":
- return "";
- }
-}
-function getLocalOauthConfig() {
- const api = process.env.CLAUDE_LOCAL_OAUTH_API_BASE?.replace(/\/$/, "") ?? "http://localhost:8000";
- const apps = process.env.CLAUDE_LOCAL_OAUTH_APPS_BASE?.replace(/\/$/, "") ?? "http://localhost:4000";
- const consoleBase = process.env.CLAUDE_LOCAL_OAUTH_CONSOLE_BASE?.replace(/\/$/, "") ?? "http://localhost:3000";
- return {
- BASE_API_URL: api,
- CONSOLE_AUTHORIZE_URL: `${consoleBase}/oauth/authorize`,
- CLAUDE_AI_AUTHORIZE_URL: `${apps}/oauth/authorize`,
- CLAUDE_AI_ORIGIN: apps,
- TOKEN_URL: `${api}/v1/oauth/token`,
- API_KEY_URL: `${api}/api/oauth/claude_cli/create_api_key`,
- ROLES_URL: `${api}/api/oauth/claude_cli/roles`,
- CONSOLE_SUCCESS_URL: `${consoleBase}/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code`,
- CLAUDEAI_SUCCESS_URL: `${consoleBase}/oauth/code/success?app=claude-code`,
- MANUAL_REDIRECT_URL: `${consoleBase}/oauth/code/callback`,
- CLIENT_ID: "22422756-60c9-4084-8eb7-27705fd5cf9a",
- OAUTH_FILE_SUFFIX: "-local-oauth",
- MCP_PROXY_URL: "http://localhost:8205",
- MCP_PROXY_PATH: "/v1/toolbox/shttp/mcp/{server_id}"
- };
-}
-function getOauthConfig() {
- let config = (() => {
- switch (getOauthConfigType()) {
- case "local":
- return getLocalOauthConfig();
- case "staging":
- return STAGING_OAUTH_CONFIG ?? PROD_OAUTH_CONFIG;
- case "prod":
- return PROD_OAUTH_CONFIG;
- }
- })();
- const oauthBaseUrl = process.env.CLAUDE_CODE_CUSTOM_OAUTH_URL;
- if (oauthBaseUrl) {
- const base = oauthBaseUrl.replace(/\/$/, "");
- if (!ALLOWED_OAUTH_BASE_URLS.includes(base)) {
- throw new Error("CLAUDE_CODE_CUSTOM_OAUTH_URL is not an approved endpoint.");
- }
- config = {
- ...config,
- BASE_API_URL: base,
- CONSOLE_AUTHORIZE_URL: `${base}/oauth/authorize`,
- CLAUDE_AI_AUTHORIZE_URL: `${base}/oauth/authorize`,
- CLAUDE_AI_ORIGIN: base,
- TOKEN_URL: `${base}/v1/oauth/token`,
- API_KEY_URL: `${base}/api/oauth/claude_cli/create_api_key`,
- ROLES_URL: `${base}/api/oauth/claude_cli/roles`,
- CONSOLE_SUCCESS_URL: `${base}/oauth/code/success?app=claude-code`,
- CLAUDEAI_SUCCESS_URL: `${base}/oauth/code/success?app=claude-code`,
- MANUAL_REDIRECT_URL: `${base}/oauth/code/callback`,
- OAUTH_FILE_SUFFIX: "-custom-oauth"
- };
- }
- const clientIdOverride = process.env.CLAUDE_CODE_OAUTH_CLIENT_ID;
- if (clientIdOverride) {
- config = {
- ...config,
- CLIENT_ID: clientIdOverride
- };
- }
- return config;
-}
-var CLAUDE_AI_INFERENCE_SCOPE = "user:inference", CLAUDE_AI_PROFILE_SCOPE = "user:profile", CONSOLE_SCOPE = "org:create_api_key", OAUTH_BETA_HEADER = "oauth-2025-04-20", CONSOLE_OAUTH_SCOPES, CLAUDE_AI_OAUTH_SCOPES, ALL_OAUTH_SCOPES, PROD_OAUTH_CONFIG, MCP_CLIENT_METADATA_URL = "https://claude.ai/oauth/claude-code-client-metadata", STAGING_OAUTH_CONFIG, ALLOWED_OAUTH_BASE_URLS;
-var init_oauth = __esm(() => {
- init_envUtils();
- CONSOLE_OAUTH_SCOPES = [
- CONSOLE_SCOPE,
- CLAUDE_AI_PROFILE_SCOPE
- ];
- CLAUDE_AI_OAUTH_SCOPES = [
- CLAUDE_AI_PROFILE_SCOPE,
- CLAUDE_AI_INFERENCE_SCOPE,
- "user:sessions:claude_code",
- "user:mcp_servers",
- "user:file_upload"
- ];
- ALL_OAUTH_SCOPES = Array.from(new Set([...CONSOLE_OAUTH_SCOPES, ...CLAUDE_AI_OAUTH_SCOPES]));
- PROD_OAUTH_CONFIG = {
- BASE_API_URL: "https://api.anthropic.com",
- CONSOLE_AUTHORIZE_URL: "https://platform.claude.com/oauth/authorize",
- CLAUDE_AI_AUTHORIZE_URL: "https://claude.com/cai/oauth/authorize",
- CLAUDE_AI_ORIGIN: "https://claude.ai",
- TOKEN_URL: "https://platform.claude.com/v1/oauth/token",
- API_KEY_URL: "https://api.anthropic.com/api/oauth/claude_cli/create_api_key",
- ROLES_URL: "https://api.anthropic.com/api/oauth/claude_cli/roles",
- CONSOLE_SUCCESS_URL: "https://platform.claude.com/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code",
- CLAUDEAI_SUCCESS_URL: "https://platform.claude.com/oauth/code/success?app=claude-code",
- MANUAL_REDIRECT_URL: "https://platform.claude.com/oauth/code/callback",
- CLIENT_ID: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
- OAUTH_FILE_SUFFIX: "",
- MCP_PROXY_URL: "https://mcp-proxy.anthropic.com",
- MCP_PROXY_PATH: "/v1/mcp/{server_id}"
- };
- STAGING_OAUTH_CONFIG = process.env.USER_TYPE === "ant" ? {
- BASE_API_URL: "https://api-staging.anthropic.com",
- CONSOLE_AUTHORIZE_URL: "https://platform.staging.ant.dev/oauth/authorize",
- CLAUDE_AI_AUTHORIZE_URL: "https://claude-ai.staging.ant.dev/oauth/authorize",
- CLAUDE_AI_ORIGIN: "https://claude-ai.staging.ant.dev",
- TOKEN_URL: "https://platform.staging.ant.dev/v1/oauth/token",
- API_KEY_URL: "https://api-staging.anthropic.com/api/oauth/claude_cli/create_api_key",
- ROLES_URL: "https://api-staging.anthropic.com/api/oauth/claude_cli/roles",
- CONSOLE_SUCCESS_URL: "https://platform.staging.ant.dev/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code",
- CLAUDEAI_SUCCESS_URL: "https://platform.staging.ant.dev/oauth/code/success?app=claude-code",
- MANUAL_REDIRECT_URL: "https://platform.staging.ant.dev/oauth/code/callback",
- CLIENT_ID: "22422756-60c9-4084-8eb7-27705fd5cf9a",
- OAUTH_FILE_SUFFIX: "-staging-oauth",
- MCP_PROXY_URL: "https://mcp-proxy-staging.anthropic.com",
- MCP_PROXY_PATH: "/v1/mcp/{server_id}"
- } : undefined;
- ALLOWED_OAUTH_BASE_URLS = [
- "https://beacon.claude-ai.staging.ant.dev",
- "https://claude.fedstart.com",
- "https://claude-staging.fedstart.com"
- ];
-});
-
-// src/utils/secureStorage/macOsKeychainHelpers.ts
-import { createHash } from "crypto";
-import { userInfo as userInfo2 } from "os";
-function getMacOsKeychainStorageServiceName(serviceSuffix = "") {
- const configDir = getClaudeConfigHomeDir();
- const isDefaultDir = !process.env.CLAUDE_CONFIG_DIR;
- const dirHash = isDefaultDir ? "" : `-${createHash("sha256").update(configDir).digest("hex").substring(0, 8)}`;
- return `Claude Code${getOauthConfig().OAUTH_FILE_SUFFIX}${serviceSuffix}${dirHash}`;
-}
-function getUsername() {
- try {
- return process.env.USER || userInfo2().username;
- } catch {
- return "claude-code-user";
- }
-}
-function clearKeychainCache() {
- keychainCacheState.cache = { data: null, cachedAt: 0 };
- keychainCacheState.generation++;
- keychainCacheState.readInFlight = null;
-}
-function primeKeychainCacheFromPrefetch(stdout) {
- if (keychainCacheState.cache.cachedAt !== 0)
- return;
- let data = null;
- if (stdout) {
- try {
- data = JSON.parse(stdout);
- } catch {
- return;
- }
- }
- keychainCacheState.cache = { data, cachedAt: Date.now() };
-}
-var CREDENTIALS_SERVICE_SUFFIX = "-credentials", KEYCHAIN_CACHE_TTL_MS = 30000, keychainCacheState;
-var init_macOsKeychainHelpers = __esm(() => {
- init_oauth();
- init_envUtils();
- keychainCacheState = {
- cache: { data: null, cachedAt: 0 },
- generation: 0,
- readInFlight: null
- };
-});
-
-// src/utils/secureStorage/keychainPrefetch.ts
-import { execFile as execFile2 } from "child_process";
-function spawnSecurity(serviceName) {
- return new Promise((resolve2) => {
- execFile2("security", ["find-generic-password", "-a", getUsername(), "-w", "-s", serviceName], { encoding: "utf-8", timeout: KEYCHAIN_PREFETCH_TIMEOUT_MS }, (err, stdout) => {
- resolve2({
- stdout: err ? null : stdout?.trim() || null,
- timedOut: Boolean(err && "killed" in err && err.killed)
- });
- });
- });
-}
-function startKeychainPrefetch() {
- if (process.platform !== "darwin" || prefetchPromise || isBareMode())
- return;
- const oauthSpawn = spawnSecurity(getMacOsKeychainStorageServiceName(CREDENTIALS_SERVICE_SUFFIX));
- const legacySpawn = spawnSecurity(getMacOsKeychainStorageServiceName());
- prefetchPromise = Promise.all([oauthSpawn, legacySpawn]).then(([oauth, legacy]) => {
- if (!oauth.timedOut)
- primeKeychainCacheFromPrefetch(oauth.stdout);
- if (!legacy.timedOut)
- legacyApiKeyPrefetch = { stdout: legacy.stdout };
- });
-}
-async function ensureKeychainPrefetchCompleted() {
- if (prefetchPromise)
- await prefetchPromise;
-}
-function getLegacyApiKeyPrefetchResult() {
- return legacyApiKeyPrefetch;
-}
-function clearLegacyApiKeyPrefetch() {
- legacyApiKeyPrefetch = null;
-}
-var KEYCHAIN_PREFETCH_TIMEOUT_MS = 1e4, legacyApiKeyPrefetch = null, prefetchPromise = null;
-var init_keychainPrefetch = __esm(() => {
- init_envUtils();
- init_macOsKeychainHelpers();
-});
-
-// node_modules/commander/lib/error.js
-var require_error = __commonJS((exports) => {
- class CommanderError extends Error {
- constructor(exitCode, code, message) {
- super(message);
- Error.captureStackTrace(this, this.constructor);
- this.name = this.constructor.name;
- this.code = code;
- this.exitCode = exitCode;
- this.nestedError = undefined;
- }
- }
-
- class InvalidArgumentError extends CommanderError {
- constructor(message) {
- super(1, "commander.invalidArgument", message);
- Error.captureStackTrace(this, this.constructor);
- this.name = this.constructor.name;
- }
- }
- exports.CommanderError = CommanderError;
- exports.InvalidArgumentError = InvalidArgumentError;
-});
-
-// node_modules/commander/lib/argument.js
-var require_argument = __commonJS((exports) => {
- var { InvalidArgumentError } = require_error();
-
- class Argument {
- constructor(name, description) {
- this.description = description || "";
- this.variadic = false;
- this.parseArg = undefined;
- this.defaultValue = undefined;
- this.defaultValueDescription = undefined;
- this.argChoices = undefined;
- switch (name[0]) {
- case "<":
- this.required = true;
- this._name = name.slice(1, -1);
- break;
- case "[":
- this.required = false;
- this._name = name.slice(1, -1);
- break;
- default:
- this.required = true;
- this._name = name;
- break;
- }
- if (this._name.length > 3 && this._name.slice(-3) === "...") {
- this.variadic = true;
- this._name = this._name.slice(0, -3);
- }
- }
- name() {
- return this._name;
- }
- _concatValue(value, previous) {
- if (previous === this.defaultValue || !Array.isArray(previous)) {
- return [value];
- }
- return previous.concat(value);
- }
- default(value, description) {
- this.defaultValue = value;
- this.defaultValueDescription = description;
- return this;
- }
- argParser(fn) {
- this.parseArg = fn;
- return this;
- }
- choices(values) {
- this.argChoices = values.slice();
- this.parseArg = (arg, previous) => {
- if (!this.argChoices.includes(arg)) {
- throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
- }
- if (this.variadic) {
- return this._concatValue(arg, previous);
- }
- return arg;
- };
- return this;
- }
- argRequired() {
- this.required = true;
- return this;
- }
- argOptional() {
- this.required = false;
- return this;
- }
- }
- function humanReadableArgName(arg) {
- const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
- return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
- }
- exports.Argument = Argument;
- exports.humanReadableArgName = humanReadableArgName;
-});
-
-// node_modules/commander/lib/help.js
-var require_help = __commonJS((exports) => {
- var { humanReadableArgName } = require_argument();
-
- class Help {
- constructor() {
- this.helpWidth = undefined;
- this.minWidthToWrap = 40;
- this.sortSubcommands = false;
- this.sortOptions = false;
- this.showGlobalOptions = false;
- }
- prepareContext(contextOptions) {
- this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
- }
- visibleCommands(cmd) {
- const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
- const helpCommand = cmd._getHelpCommand();
- if (helpCommand && !helpCommand._hidden) {
- visibleCommands.push(helpCommand);
- }
- if (this.sortSubcommands) {
- visibleCommands.sort((a, b) => {
- return a.name().localeCompare(b.name());
- });
- }
- return visibleCommands;
- }
- compareOptions(a, b) {
- const getSortKey = (option) => {
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
- };
- return getSortKey(a).localeCompare(getSortKey(b));
- }
- visibleOptions(cmd) {
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
- const helpOption = cmd._getHelpOption();
- if (helpOption && !helpOption.hidden) {
- const removeShort = helpOption.short && cmd._findOption(helpOption.short);
- const removeLong = helpOption.long && cmd._findOption(helpOption.long);
- if (!removeShort && !removeLong) {
- visibleOptions.push(helpOption);
- } else if (helpOption.long && !removeLong) {
- visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
- } else if (helpOption.short && !removeShort) {
- visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
- }
- }
- if (this.sortOptions) {
- visibleOptions.sort(this.compareOptions);
- }
- return visibleOptions;
- }
- visibleGlobalOptions(cmd) {
- if (!this.showGlobalOptions)
- return [];
- const globalOptions = [];
- for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
- const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
- globalOptions.push(...visibleOptions);
- }
- if (this.sortOptions) {
- globalOptions.sort(this.compareOptions);
- }
- return globalOptions;
- }
- visibleArguments(cmd) {
- if (cmd._argsDescription) {
- cmd.registeredArguments.forEach((argument) => {
- argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
- });
- }
- if (cmd.registeredArguments.find((argument) => argument.description)) {
- return cmd.registeredArguments;
- }
- return [];
- }
- subcommandTerm(cmd) {
- const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
- return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
- }
- optionTerm(option) {
- return option.flags;
- }
- argumentTerm(argument) {
- return argument.name();
- }
- longestSubcommandTermLength(cmd, helper) {
- return helper.visibleCommands(cmd).reduce((max, command) => {
- return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
- }, 0);
- }
- longestOptionTermLength(cmd, helper) {
- return helper.visibleOptions(cmd).reduce((max, option) => {
- return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
- }, 0);
- }
- longestGlobalOptionTermLength(cmd, helper) {
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
- return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
- }, 0);
- }
- longestArgumentTermLength(cmd, helper) {
- return helper.visibleArguments(cmd).reduce((max, argument) => {
- return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
- }, 0);
- }
- commandUsage(cmd) {
- let cmdName = cmd._name;
- if (cmd._aliases[0]) {
- cmdName = cmdName + "|" + cmd._aliases[0];
- }
- let ancestorCmdNames = "";
- for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
- ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
- }
- return ancestorCmdNames + cmdName + " " + cmd.usage();
- }
- commandDescription(cmd) {
- return cmd.description();
- }
- subcommandDescription(cmd) {
- return cmd.summary() || cmd.description();
- }
- optionDescription(option) {
- const extraInfo = [];
- if (option.argChoices) {
- extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
- }
- if (option.defaultValue !== undefined) {
- const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
- if (showDefault) {
- extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
- }
- }
- if (option.presetArg !== undefined && option.optional) {
- extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
- }
- if (option.envVar !== undefined) {
- extraInfo.push(`env: ${option.envVar}`);
- }
- if (extraInfo.length > 0) {
- return `${option.description} (${extraInfo.join(", ")})`;
- }
- return option.description;
- }
- argumentDescription(argument) {
- const extraInfo = [];
- if (argument.argChoices) {
- extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
- }
- if (argument.defaultValue !== undefined) {
- extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
- }
- if (extraInfo.length > 0) {
- const extraDescription = `(${extraInfo.join(", ")})`;
- if (argument.description) {
- return `${argument.description} ${extraDescription}`;
- }
- return extraDescription;
- }
- return argument.description;
- }
- formatHelp(cmd, helper) {
- const termWidth = helper.padWidth(cmd, helper);
- const helpWidth = helper.helpWidth ?? 80;
- function callFormatItem(term, description) {
- return helper.formatItem(term, termWidth, description, helper);
- }
- let output = [
- `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
- ""
- ];
- const commandDescription = helper.commandDescription(cmd);
- if (commandDescription.length > 0) {
- output = output.concat([
- helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
- ""
- ]);
- }
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
- return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
- });
- if (argumentList.length > 0) {
- output = output.concat([
- helper.styleTitle("Arguments:"),
- ...argumentList,
- ""
- ]);
- }
- const optionList = helper.visibleOptions(cmd).map((option) => {
- return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
- });
- if (optionList.length > 0) {
- output = output.concat([
- helper.styleTitle("Options:"),
- ...optionList,
- ""
- ]);
- }
- if (helper.showGlobalOptions) {
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
- return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
- });
- if (globalOptionList.length > 0) {
- output = output.concat([
- helper.styleTitle("Global Options:"),
- ...globalOptionList,
- ""
- ]);
- }
- }
- const commandList = helper.visibleCommands(cmd).map((cmd2) => {
- return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)), helper.styleSubcommandDescription(helper.subcommandDescription(cmd2)));
- });
- if (commandList.length > 0) {
- output = output.concat([
- helper.styleTitle("Commands:"),
- ...commandList,
- ""
- ]);
- }
- return output.join(`
-`);
- }
- displayWidth(str) {
- return stripColor(str).length;
- }
- styleTitle(str) {
- return str;
- }
- styleUsage(str) {
- return str.split(" ").map((word) => {
- if (word === "[options]")
- return this.styleOptionText(word);
- if (word === "[command]")
- return this.styleSubcommandText(word);
- if (word[0] === "[" || word[0] === "<")
- return this.styleArgumentText(word);
- return this.styleCommandText(word);
- }).join(" ");
- }
- styleCommandDescription(str) {
- return this.styleDescriptionText(str);
- }
- styleOptionDescription(str) {
- return this.styleDescriptionText(str);
- }
- styleSubcommandDescription(str) {
- return this.styleDescriptionText(str);
- }
- styleArgumentDescription(str) {
- return this.styleDescriptionText(str);
- }
- styleDescriptionText(str) {
- return str;
- }
- styleOptionTerm(str) {
- return this.styleOptionText(str);
- }
- styleSubcommandTerm(str) {
- return str.split(" ").map((word) => {
- if (word === "[options]")
- return this.styleOptionText(word);
- if (word[0] === "[" || word[0] === "<")
- return this.styleArgumentText(word);
- return this.styleSubcommandText(word);
- }).join(" ");
- }
- styleArgumentTerm(str) {
- return this.styleArgumentText(str);
- }
- styleOptionText(str) {
- return str;
- }
- styleArgumentText(str) {
- return str;
- }
- styleSubcommandText(str) {
- return str;
- }
- styleCommandText(str) {
- return str;
- }
- padWidth(cmd, helper) {
- return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
- }
- preformatted(str) {
- return /\n[^\S\r\n]/.test(str);
- }
- formatItem(term, termWidth, description, helper) {
- const itemIndent = 2;
- const itemIndentStr = " ".repeat(itemIndent);
- if (!description)
- return itemIndentStr + term;
- const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
- const spacerWidth = 2;
- const helpWidth = this.helpWidth ?? 80;
- const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
- let formattedDescription;
- if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
- formattedDescription = description;
- } else {
- const wrappedDescription = helper.boxWrap(description, remainingWidth);
- formattedDescription = wrappedDescription.replace(/\n/g, `
-` + " ".repeat(termWidth + spacerWidth));
- }
- return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
-${itemIndentStr}`);
- }
- boxWrap(str, width) {
- if (width < this.minWidthToWrap)
- return str;
- const rawLines = str.split(/\r\n|\n/);
- const chunkPattern = /[\s]*[^\s]+/g;
- const wrappedLines = [];
- rawLines.forEach((line) => {
- const chunks = line.match(chunkPattern);
- if (chunks === null) {
- wrappedLines.push("");
- return;
- }
- let sumChunks = [chunks.shift()];
- let sumWidth = this.displayWidth(sumChunks[0]);
- chunks.forEach((chunk) => {
- const visibleWidth = this.displayWidth(chunk);
- if (sumWidth + visibleWidth <= width) {
- sumChunks.push(chunk);
- sumWidth += visibleWidth;
- return;
- }
- wrappedLines.push(sumChunks.join(""));
- const nextChunk = chunk.trimStart();
- sumChunks = [nextChunk];
- sumWidth = this.displayWidth(nextChunk);
- });
- wrappedLines.push(sumChunks.join(""));
- });
- return wrappedLines.join(`
-`);
- }
- }
- function stripColor(str) {
- const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
- return str.replace(sgrPattern, "");
- }
- exports.Help = Help;
- exports.stripColor = stripColor;
-});
-
-// node_modules/commander/lib/option.js
-var require_option = __commonJS((exports) => {
- var { InvalidArgumentError } = require_error();
-
- class Option {
- constructor(flags, description) {
- this.flags = flags;
- this.description = description || "";
- this.required = flags.includes("<");
- this.optional = flags.includes("[");
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
- this.mandatory = false;
- const optionFlags = splitOptionFlags(flags);
- this.short = optionFlags.shortFlag;
- this.long = optionFlags.longFlag;
- this.negate = false;
- if (this.long) {
- this.negate = this.long.startsWith("--no-");
- }
- this.defaultValue = undefined;
- this.defaultValueDescription = undefined;
- this.presetArg = undefined;
- this.envVar = undefined;
- this.parseArg = undefined;
- this.hidden = false;
- this.argChoices = undefined;
- this.conflictsWith = [];
- this.implied = undefined;
- }
- default(value, description) {
- this.defaultValue = value;
- this.defaultValueDescription = description;
- return this;
- }
- preset(arg) {
- this.presetArg = arg;
- return this;
- }
- conflicts(names) {
- this.conflictsWith = this.conflictsWith.concat(names);
- return this;
- }
- implies(impliedOptionValues) {
- let newImplied = impliedOptionValues;
- if (typeof impliedOptionValues === "string") {
- newImplied = { [impliedOptionValues]: true };
- }
- this.implied = Object.assign(this.implied || {}, newImplied);
- return this;
- }
- env(name) {
- this.envVar = name;
- return this;
- }
- argParser(fn) {
- this.parseArg = fn;
- return this;
- }
- makeOptionMandatory(mandatory = true) {
- this.mandatory = !!mandatory;
- return this;
- }
- hideHelp(hide = true) {
- this.hidden = !!hide;
- return this;
- }
- _concatValue(value, previous) {
- if (previous === this.defaultValue || !Array.isArray(previous)) {
- return [value];
- }
- return previous.concat(value);
- }
- choices(values) {
- this.argChoices = values.slice();
- this.parseArg = (arg, previous) => {
- if (!this.argChoices.includes(arg)) {
- throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
- }
- if (this.variadic) {
- return this._concatValue(arg, previous);
- }
- return arg;
- };
- return this;
- }
- name() {
- if (this.long) {
- return this.long.replace(/^--/, "");
- }
- return this.short.replace(/^-/, "");
- }
- attributeName() {
- if (this.negate) {
- return camelcase(this.name().replace(/^no-/, ""));
- }
- return camelcase(this.name());
- }
- is(arg) {
- return this.short === arg || this.long === arg;
- }
- isBoolean() {
- return !this.required && !this.optional && !this.negate;
- }
- }
-
- class DualOptions {
- constructor(options) {
- this.positiveOptions = new Map;
- this.negativeOptions = new Map;
- this.dualOptions = new Set;
- options.forEach((option) => {
- if (option.negate) {
- this.negativeOptions.set(option.attributeName(), option);
- } else {
- this.positiveOptions.set(option.attributeName(), option);
- }
- });
- this.negativeOptions.forEach((value, key) => {
- if (this.positiveOptions.has(key)) {
- this.dualOptions.add(key);
- }
- });
- }
- valueFromOption(value, option) {
- const optionKey = option.attributeName();
- if (!this.dualOptions.has(optionKey))
- return true;
- const preset = this.negativeOptions.get(optionKey).presetArg;
- const negativeValue = preset !== undefined ? preset : false;
- return option.negate === (negativeValue === value);
- }
- }
- function camelcase(str) {
- return str.split("-").reduce((str2, word) => {
- return str2 + word[0].toUpperCase() + word.slice(1);
- });
- }
- function splitOptionFlags(flags) {
- let shortFlag;
- let longFlag;
- const shortFlagExp = /^-[^-]$/;
- const longFlagExp = /^--[^-]/;
- const flagParts = flags.split(/[ |,]+/).concat("guard");
- if (shortFlagExp.test(flagParts[0]))
- shortFlag = flagParts.shift();
- if (longFlagExp.test(flagParts[0]))
- longFlag = flagParts.shift();
- if (!shortFlag && shortFlagExp.test(flagParts[0]))
- shortFlag = flagParts.shift();
- if (!shortFlag && longFlagExp.test(flagParts[0])) {
- shortFlag = longFlag;
- longFlag = flagParts.shift();
- }
- if (flagParts[0].startsWith("-")) {
- const unsupportedFlag = flagParts[0];
- const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
- if (/^-[^-][^-]/.test(unsupportedFlag))
- throw new Error(`${baseError}
-- a short flag is a single dash and a single character
- - either use a single dash and a single character (for a short flag)
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
- if (shortFlagExp.test(unsupportedFlag))
- throw new Error(`${baseError}
-- too many short flags`);
- if (longFlagExp.test(unsupportedFlag))
- throw new Error(`${baseError}
-- too many long flags`);
- throw new Error(`${baseError}
-- unrecognised flag format`);
- }
- if (shortFlag === undefined && longFlag === undefined)
- throw new Error(`option creation failed due to no flags found in '${flags}'.`);
- return { shortFlag, longFlag };
- }
- exports.Option = Option;
- exports.DualOptions = DualOptions;
-});
-
-// node_modules/commander/lib/suggestSimilar.js
-var require_suggestSimilar = __commonJS((exports) => {
- var maxDistance = 3;
- function editDistance(a, b) {
- if (Math.abs(a.length - b.length) > maxDistance)
- return Math.max(a.length, b.length);
- const d = [];
- for (let i = 0;i <= a.length; i++) {
- d[i] = [i];
- }
- for (let j = 0;j <= b.length; j++) {
- d[0][j] = j;
- }
- for (let j = 1;j <= b.length; j++) {
- for (let i = 1;i <= a.length; i++) {
- let cost = 1;
- if (a[i - 1] === b[j - 1]) {
- cost = 0;
- } else {
- cost = 1;
- }
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
- }
- }
- }
- return d[a.length][b.length];
- }
- function suggestSimilar(word, candidates) {
- if (!candidates || candidates.length === 0)
- return "";
- candidates = Array.from(new Set(candidates));
- const searchingOptions = word.startsWith("--");
- if (searchingOptions) {
- word = word.slice(2);
- candidates = candidates.map((candidate) => candidate.slice(2));
- }
- let similar = [];
- let bestDistance = maxDistance;
- const minSimilarity = 0.4;
- candidates.forEach((candidate) => {
- if (candidate.length <= 1)
- return;
- const distance = editDistance(word, candidate);
- const length = Math.max(word.length, candidate.length);
- const similarity = (length - distance) / length;
- if (similarity > minSimilarity) {
- if (distance < bestDistance) {
- bestDistance = distance;
- similar = [candidate];
- } else if (distance === bestDistance) {
- similar.push(candidate);
- }
- }
- });
- similar.sort((a, b) => a.localeCompare(b));
- if (searchingOptions) {
- similar = similar.map((candidate) => `--${candidate}`);
- }
- if (similar.length > 1) {
- return `
-(Did you mean one of ${similar.join(", ")}?)`;
- }
- if (similar.length === 1) {
- return `
-(Did you mean ${similar[0]}?)`;
- }
- return "";
- }
- exports.suggestSimilar = suggestSimilar;
-});
-
-// node_modules/commander/lib/command.js
-var require_command = __commonJS((exports) => {
- var EventEmitter = __require("events").EventEmitter;
- var childProcess = __require("child_process");
- var path = __require("path");
- var fs2 = __require("fs");
- var process2 = __require("process");
- var { Argument, humanReadableArgName } = require_argument();
- var { CommanderError } = require_error();
- var { Help, stripColor } = require_help();
- var { Option, DualOptions } = require_option();
- var { suggestSimilar } = require_suggestSimilar();
-
- class Command extends EventEmitter {
- constructor(name) {
- super();
- this.commands = [];
- this.options = [];
- this.parent = null;
- this._allowUnknownOption = false;
- this._allowExcessArguments = false;
- this.registeredArguments = [];
- this._args = this.registeredArguments;
- this.args = [];
- this.rawArgs = [];
- this.processedArgs = [];
- this._scriptPath = null;
- this._name = name || "";
- this._optionValues = {};
- this._optionValueSources = {};
- this._storeOptionsAsProperties = false;
- this._actionHandler = null;
- this._executableHandler = false;
- this._executableFile = null;
- this._executableDir = null;
- this._defaultCommandName = null;
- this._exitCallback = null;
- this._aliases = [];
- this._combineFlagAndOptionalValue = true;
- this._description = "";
- this._summary = "";
- this._argsDescription = undefined;
- this._enablePositionalOptions = false;
- this._passThroughOptions = false;
- this._lifeCycleHooks = {};
- this._showHelpAfterError = false;
- this._showSuggestionAfterError = true;
- this._savedState = null;
- this._outputConfiguration = {
- writeOut: (str) => process2.stdout.write(str),
- writeErr: (str) => process2.stderr.write(str),
- outputError: (str, write) => write(str),
- getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
- getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
- getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
- getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
- stripColor: (str) => stripColor(str)
- };
- this._hidden = false;
- this._helpOption = undefined;
- this._addImplicitHelpCommand = undefined;
- this._helpCommand = undefined;
- this._helpConfiguration = {};
- }
- copyInheritedSettings(sourceCommand) {
- this._outputConfiguration = sourceCommand._outputConfiguration;
- this._helpOption = sourceCommand._helpOption;
- this._helpCommand = sourceCommand._helpCommand;
- this._helpConfiguration = sourceCommand._helpConfiguration;
- this._exitCallback = sourceCommand._exitCallback;
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
- return this;
- }
- _getCommandAndAncestors() {
- const result = [];
- for (let command = this;command; command = command.parent) {
- result.push(command);
- }
- return result;
- }
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
- let desc = actionOptsOrExecDesc;
- let opts = execOpts;
- if (typeof desc === "object" && desc !== null) {
- opts = desc;
- desc = null;
- }
- opts = opts || {};
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
- const cmd = this.createCommand(name);
- if (desc) {
- cmd.description(desc);
- cmd._executableHandler = true;
- }
- if (opts.isDefault)
- this._defaultCommandName = cmd._name;
- cmd._hidden = !!(opts.noHelp || opts.hidden);
- cmd._executableFile = opts.executableFile || null;
- if (args)
- cmd.arguments(args);
- this._registerCommand(cmd);
- cmd.parent = this;
- cmd.copyInheritedSettings(this);
- if (desc)
- return this;
- return cmd;
- }
- createCommand(name) {
- return new Command(name);
- }
- createHelp() {
- return Object.assign(new Help, this.configureHelp());
- }
- configureHelp(configuration) {
- if (configuration === undefined)
- return this._helpConfiguration;
- this._helpConfiguration = configuration;
- return this;
- }
- configureOutput(configuration) {
- if (configuration === undefined)
- return this._outputConfiguration;
- Object.assign(this._outputConfiguration, configuration);
- return this;
- }
- showHelpAfterError(displayHelp = true) {
- if (typeof displayHelp !== "string")
- displayHelp = !!displayHelp;
- this._showHelpAfterError = displayHelp;
- return this;
- }
- showSuggestionAfterError(displaySuggestion = true) {
- this._showSuggestionAfterError = !!displaySuggestion;
- return this;
- }
- addCommand(cmd, opts) {
- if (!cmd._name) {
- throw new Error(`Command passed to .addCommand() must have a name
-- specify the name in Command constructor or using .name()`);
- }
- opts = opts || {};
- if (opts.isDefault)
- this._defaultCommandName = cmd._name;
- if (opts.noHelp || opts.hidden)
- cmd._hidden = true;
- this._registerCommand(cmd);
- cmd.parent = this;
- cmd._checkForBrokenPassThrough();
- return this;
- }
- createArgument(name, description) {
- return new Argument(name, description);
- }
- argument(name, description, fn, defaultValue) {
- const argument = this.createArgument(name, description);
- if (typeof fn === "function") {
- argument.default(defaultValue).argParser(fn);
- } else {
- argument.default(fn);
- }
- this.addArgument(argument);
- return this;
- }
- arguments(names) {
- names.trim().split(/ +/).forEach((detail) => {
- this.argument(detail);
- });
- return this;
- }
- addArgument(argument) {
- const previousArgument = this.registeredArguments.slice(-1)[0];
- if (previousArgument && previousArgument.variadic) {
- throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
- }
- if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
- throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
- }
- this.registeredArguments.push(argument);
- return this;
- }
- helpCommand(enableOrNameAndArgs, description) {
- if (typeof enableOrNameAndArgs === "boolean") {
- this._addImplicitHelpCommand = enableOrNameAndArgs;
- return this;
- }
- enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
- const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
- const helpDescription = description ?? "display help for command";
- const helpCommand = this.createCommand(helpName);
- helpCommand.helpOption(false);
- if (helpArgs)
- helpCommand.arguments(helpArgs);
- if (helpDescription)
- helpCommand.description(helpDescription);
- this._addImplicitHelpCommand = true;
- this._helpCommand = helpCommand;
- return this;
- }
- addHelpCommand(helpCommand, deprecatedDescription) {
- if (typeof helpCommand !== "object") {
- this.helpCommand(helpCommand, deprecatedDescription);
- return this;
- }
- this._addImplicitHelpCommand = true;
- this._helpCommand = helpCommand;
- return this;
- }
- _getHelpCommand() {
- const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
- if (hasImplicitHelpCommand) {
- if (this._helpCommand === undefined) {
- this.helpCommand(undefined, undefined);
- }
- return this._helpCommand;
- }
- return null;
- }
- hook(event, listener) {
- const allowedValues = ["preSubcommand", "preAction", "postAction"];
- if (!allowedValues.includes(event)) {
- throw new Error(`Unexpected value for event passed to hook : '${event}'.
-Expecting one of '${allowedValues.join("', '")}'`);
- }
- if (this._lifeCycleHooks[event]) {
- this._lifeCycleHooks[event].push(listener);
- } else {
- this._lifeCycleHooks[event] = [listener];
- }
- return this;
- }
- exitOverride(fn) {
- if (fn) {
- this._exitCallback = fn;
- } else {
- this._exitCallback = (err) => {
- if (err.code !== "commander.executeSubCommandAsync") {
- throw err;
- } else {}
- };
- }
- return this;
- }
- _exit(exitCode, code, message) {
- if (this._exitCallback) {
- this._exitCallback(new CommanderError(exitCode, code, message));
- }
- process2.exit(exitCode);
- }
- action(fn) {
- const listener = (args) => {
- const expectedArgsCount = this.registeredArguments.length;
- const actionArgs = args.slice(0, expectedArgsCount);
- if (this._storeOptionsAsProperties) {
- actionArgs[expectedArgsCount] = this;
- } else {
- actionArgs[expectedArgsCount] = this.opts();
- }
- actionArgs.push(this);
- return fn.apply(this, actionArgs);
- };
- this._actionHandler = listener;
- return this;
- }
- createOption(flags, description) {
- return new Option(flags, description);
- }
- _callParseArg(target, value, previous, invalidArgumentMessage) {
- try {
- return target.parseArg(value, previous);
- } catch (err) {
- if (err.code === "commander.invalidArgument") {
- const message = `${invalidArgumentMessage} ${err.message}`;
- this.error(message, { exitCode: err.exitCode, code: err.code });
- }
- throw err;
- }
- }
- _registerOption(option) {
- const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
- if (matchingOption) {
- const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
- throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
-- already used by option '${matchingOption.flags}'`);
- }
- this.options.push(option);
- }
- _registerCommand(command) {
- const knownBy = (cmd) => {
- return [cmd.name()].concat(cmd.aliases());
- };
- const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
- if (alreadyUsed) {
- const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
- const newCmd = knownBy(command).join("|");
- throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
- }
- this.commands.push(command);
- }
- addOption(option) {
- this._registerOption(option);
- const oname = option.name();
- const name = option.attributeName();
- if (option.negate) {
- const positiveLongFlag = option.long.replace(/^--no-/, "--");
- if (!this._findOption(positiveLongFlag)) {
- this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
- }
- } else if (option.defaultValue !== undefined) {
- this.setOptionValueWithSource(name, option.defaultValue, "default");
- }
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
- if (val == null && option.presetArg !== undefined) {
- val = option.presetArg;
- }
- const oldValue = this.getOptionValue(name);
- if (val !== null && option.parseArg) {
- val = this._callParseArg(option, val, oldValue, invalidValueMessage);
- } else if (val !== null && option.variadic) {
- val = option._concatValue(val, oldValue);
- }
- if (val == null) {
- if (option.negate) {
- val = false;
- } else if (option.isBoolean() || option.optional) {
- val = true;
- } else {
- val = "";
- }
- }
- this.setOptionValueWithSource(name, val, valueSource);
- };
- this.on("option:" + oname, (val) => {
- const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
- handleOptionValue(val, invalidValueMessage, "cli");
- });
- if (option.envVar) {
- this.on("optionEnv:" + oname, (val) => {
- const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
- handleOptionValue(val, invalidValueMessage, "env");
- });
- }
- return this;
- }
- _optionEx(config, flags, description, fn, defaultValue) {
- if (typeof flags === "object" && flags instanceof Option) {
- throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
- }
- const option = this.createOption(flags, description);
- option.makeOptionMandatory(!!config.mandatory);
- if (typeof fn === "function") {
- option.default(defaultValue).argParser(fn);
- } else if (fn instanceof RegExp) {
- const regex2 = fn;
- fn = (val, def) => {
- const m = regex2.exec(val);
- return m ? m[0] : def;
- };
- option.default(defaultValue).argParser(fn);
- } else {
- option.default(fn);
- }
- return this.addOption(option);
- }
- option(flags, description, parseArg, defaultValue) {
- return this._optionEx({}, flags, description, parseArg, defaultValue);
- }
- requiredOption(flags, description, parseArg, defaultValue) {
- return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
- }
- combineFlagAndOptionalValue(combine = true) {
- this._combineFlagAndOptionalValue = !!combine;
- return this;
- }
- allowUnknownOption(allowUnknown = true) {
- this._allowUnknownOption = !!allowUnknown;
- return this;
- }
- allowExcessArguments(allowExcess = true) {
- this._allowExcessArguments = !!allowExcess;
- return this;
- }
- enablePositionalOptions(positional = true) {
- this._enablePositionalOptions = !!positional;
- return this;
- }
- passThroughOptions(passThrough = true) {
- this._passThroughOptions = !!passThrough;
- this._checkForBrokenPassThrough();
- return this;
- }
- _checkForBrokenPassThrough() {
- if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
- throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
- }
- }
- storeOptionsAsProperties(storeAsProperties = true) {
- if (this.options.length) {
- throw new Error("call .storeOptionsAsProperties() before adding options");
- }
- if (Object.keys(this._optionValues).length) {
- throw new Error("call .storeOptionsAsProperties() before setting option values");
- }
- this._storeOptionsAsProperties = !!storeAsProperties;
- return this;
- }
- getOptionValue(key) {
- if (this._storeOptionsAsProperties) {
- return this[key];
- }
- return this._optionValues[key];
- }
- setOptionValue(key, value) {
- return this.setOptionValueWithSource(key, value, undefined);
- }
- setOptionValueWithSource(key, value, source) {
- if (this._storeOptionsAsProperties) {
- this[key] = value;
- } else {
- this._optionValues[key] = value;
- }
- this._optionValueSources[key] = source;
- return this;
- }
- getOptionValueSource(key) {
- return this._optionValueSources[key];
- }
- getOptionValueSourceWithGlobals(key) {
- let source;
- this._getCommandAndAncestors().forEach((cmd) => {
- if (cmd.getOptionValueSource(key) !== undefined) {
- source = cmd.getOptionValueSource(key);
- }
- });
- return source;
- }
- _prepareUserArgs(argv, parseOptions) {
- if (argv !== undefined && !Array.isArray(argv)) {
- throw new Error("first parameter to parse must be array or undefined");
- }
- parseOptions = parseOptions || {};
- if (argv === undefined && parseOptions.from === undefined) {
- if (process2.versions?.electron) {
- parseOptions.from = "electron";
- }
- const execArgv = process2.execArgv ?? [];
- if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
- parseOptions.from = "eval";
- }
- }
- if (argv === undefined) {
- argv = process2.argv;
- }
- this.rawArgs = argv.slice();
- let userArgs;
- switch (parseOptions.from) {
- case undefined:
- case "node":
- this._scriptPath = argv[1];
- userArgs = argv.slice(2);
- break;
- case "electron":
- if (process2.defaultApp) {
- this._scriptPath = argv[1];
- userArgs = argv.slice(2);
- } else {
- userArgs = argv.slice(1);
- }
- break;
- case "user":
- userArgs = argv.slice(0);
- break;
- case "eval":
- userArgs = argv.slice(1);
- break;
- default:
- throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
- }
- if (!this._name && this._scriptPath)
- this.nameFromFilename(this._scriptPath);
- this._name = this._name || "program";
- return userArgs;
- }
- parse(argv, parseOptions) {
- this._prepareForParse();
- const userArgs = this._prepareUserArgs(argv, parseOptions);
- this._parseCommand([], userArgs);
- return this;
- }
- async parseAsync(argv, parseOptions) {
- this._prepareForParse();
- const userArgs = this._prepareUserArgs(argv, parseOptions);
- await this._parseCommand([], userArgs);
- return this;
- }
- _prepareForParse() {
- if (this._savedState === null) {
- this.saveStateBeforeParse();
- } else {
- this.restoreStateBeforeParse();
- }
- }
- saveStateBeforeParse() {
- this._savedState = {
- _name: this._name,
- _optionValues: { ...this._optionValues },
- _optionValueSources: { ...this._optionValueSources }
- };
- }
- restoreStateBeforeParse() {
- if (this._storeOptionsAsProperties)
- throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
-- either make a new Command for each call to parse, or stop storing options as properties`);
- this._name = this._savedState._name;
- this._scriptPath = null;
- this.rawArgs = [];
- this._optionValues = { ...this._savedState._optionValues };
- this._optionValueSources = { ...this._savedState._optionValueSources };
- this.args = [];
- this.processedArgs = [];
- }
- _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
- if (fs2.existsSync(executableFile))
- return;
- const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
- const executableMissing = `'${executableFile}' does not exist
- - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
- - ${executableDirMessage}`;
- throw new Error(executableMissing);
- }
- _executeSubCommand(subcommand, args) {
- args = args.slice();
- let launchWithNode = false;
- const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
- function findFile(baseDir, baseName) {
- const localBin = path.resolve(baseDir, baseName);
- if (fs2.existsSync(localBin))
- return localBin;
- if (sourceExt.includes(path.extname(baseName)))
- return;
- const foundExt = sourceExt.find((ext) => fs2.existsSync(`${localBin}${ext}`));
- if (foundExt)
- return `${localBin}${foundExt}`;
- return;
- }
- this._checkForMissingMandatoryOptions();
- this._checkForConflictingOptions();
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
- let executableDir = this._executableDir || "";
- if (this._scriptPath) {
- let resolvedScriptPath;
- try {
- resolvedScriptPath = fs2.realpathSync(this._scriptPath);
- } catch {
- resolvedScriptPath = this._scriptPath;
- }
- executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
- }
- if (executableDir) {
- let localFile = findFile(executableDir, executableFile);
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
- const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
- if (legacyName !== this._name) {
- localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
- }
- }
- executableFile = localFile || executableFile;
- }
- launchWithNode = sourceExt.includes(path.extname(executableFile));
- let proc;
- if (process2.platform !== "win32") {
- if (launchWithNode) {
- args.unshift(executableFile);
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
- proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
- } else {
- proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
- }
- } else {
- this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
- args.unshift(executableFile);
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
- proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
- }
- if (!proc.killed) {
- const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
- signals.forEach((signal) => {
- process2.on(signal, () => {
- if (proc.killed === false && proc.exitCode === null) {
- proc.kill(signal);
- }
- });
- });
- }
- const exitCallback = this._exitCallback;
- proc.on("close", (code) => {
- code = code ?? 1;
- if (!exitCallback) {
- process2.exit(code);
- } else {
- exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
- }
- });
- proc.on("error", (err) => {
- if (err.code === "ENOENT") {
- this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
- } else if (err.code === "EACCES") {
- throw new Error(`'${executableFile}' not executable`);
- }
- if (!exitCallback) {
- process2.exit(1);
- } else {
- const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
- wrappedError.nestedError = err;
- exitCallback(wrappedError);
- }
- });
- this.runningCommand = proc;
- }
- _dispatchSubcommand(commandName, operands, unknown) {
- const subCommand = this._findCommand(commandName);
- if (!subCommand)
- this.help({ error: true });
- subCommand._prepareForParse();
- let promiseChain;
- promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
- promiseChain = this._chainOrCall(promiseChain, () => {
- if (subCommand._executableHandler) {
- this._executeSubCommand(subCommand, operands.concat(unknown));
- } else {
- return subCommand._parseCommand(operands, unknown);
- }
- });
- return promiseChain;
- }
- _dispatchHelpCommand(subcommandName) {
- if (!subcommandName) {
- this.help();
- }
- const subCommand = this._findCommand(subcommandName);
- if (subCommand && !subCommand._executableHandler) {
- subCommand.help();
- }
- return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
- }
- _checkNumberOfArguments() {
- this.registeredArguments.forEach((arg, i) => {
- if (arg.required && this.args[i] == null) {
- this.missingArgument(arg.name());
- }
- });
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
- return;
- }
- if (this.args.length > this.registeredArguments.length) {
- this._excessArguments(this.args);
- }
- }
- _processArguments() {
- const myParseArg = (argument, value, previous) => {
- let parsedValue = value;
- if (value !== null && argument.parseArg) {
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
- parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
- }
- return parsedValue;
- };
- this._checkNumberOfArguments();
- const processedArgs = [];
- this.registeredArguments.forEach((declaredArg, index) => {
- let value = declaredArg.defaultValue;
- if (declaredArg.variadic) {
- if (index < this.args.length) {
- value = this.args.slice(index);
- if (declaredArg.parseArg) {
- value = value.reduce((processed, v) => {
- return myParseArg(declaredArg, v, processed);
- }, declaredArg.defaultValue);
- }
- } else if (value === undefined) {
- value = [];
- }
- } else if (index < this.args.length) {
- value = this.args[index];
- if (declaredArg.parseArg) {
- value = myParseArg(declaredArg, value, declaredArg.defaultValue);
- }
- }
- processedArgs[index] = value;
- });
- this.processedArgs = processedArgs;
- }
- _chainOrCall(promise, fn) {
- if (promise && promise.then && typeof promise.then === "function") {
- return promise.then(() => fn());
- }
- return fn();
- }
- _chainOrCallHooks(promise, event) {
- let result = promise;
- const hooks = [];
- this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
- hooks.push({ hookedCommand, callback });
- });
- });
- if (event === "postAction") {
- hooks.reverse();
- }
- hooks.forEach((hookDetail) => {
- result = this._chainOrCall(result, () => {
- return hookDetail.callback(hookDetail.hookedCommand, this);
- });
- });
- return result;
- }
- _chainOrCallSubCommandHook(promise, subCommand, event) {
- let result = promise;
- if (this._lifeCycleHooks[event] !== undefined) {
- this._lifeCycleHooks[event].forEach((hook) => {
- result = this._chainOrCall(result, () => {
- return hook(this, subCommand);
- });
- });
- }
- return result;
- }
- _parseCommand(operands, unknown) {
- const parsed = this.parseOptions(unknown);
- this._parseOptionsEnv();
- this._parseOptionsImplied();
- operands = operands.concat(parsed.operands);
- unknown = parsed.unknown;
- this.args = operands.concat(unknown);
- if (operands && this._findCommand(operands[0])) {
- return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
- }
- if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
- return this._dispatchHelpCommand(operands[1]);
- }
- if (this._defaultCommandName) {
- this._outputHelpIfRequested(unknown);
- return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
- }
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
- this.help({ error: true });
- }
- this._outputHelpIfRequested(parsed.unknown);
- this._checkForMissingMandatoryOptions();
- this._checkForConflictingOptions();
- const checkForUnknownOptions = () => {
- if (parsed.unknown.length > 0) {
- this.unknownOption(parsed.unknown[0]);
- }
- };
- const commandEvent = `command:${this.name()}`;
- if (this._actionHandler) {
- checkForUnknownOptions();
- this._processArguments();
- let promiseChain;
- promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
- promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
- if (this.parent) {
- promiseChain = this._chainOrCall(promiseChain, () => {
- this.parent.emit(commandEvent, operands, unknown);
- });
- }
- promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
- return promiseChain;
- }
- if (this.parent && this.parent.listenerCount(commandEvent)) {
- checkForUnknownOptions();
- this._processArguments();
- this.parent.emit(commandEvent, operands, unknown);
- } else if (operands.length) {
- if (this._findCommand("*")) {
- return this._dispatchSubcommand("*", operands, unknown);
- }
- if (this.listenerCount("command:*")) {
- this.emit("command:*", operands, unknown);
- } else if (this.commands.length) {
- this.unknownCommand();
- } else {
- checkForUnknownOptions();
- this._processArguments();
- }
- } else if (this.commands.length) {
- checkForUnknownOptions();
- this.help({ error: true });
- } else {
- checkForUnknownOptions();
- this._processArguments();
- }
- }
- _findCommand(name) {
- if (!name)
- return;
- return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
- }
- _findOption(arg) {
- return this.options.find((option) => option.is(arg));
- }
- _checkForMissingMandatoryOptions() {
- this._getCommandAndAncestors().forEach((cmd) => {
- cmd.options.forEach((anOption) => {
- if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
- cmd.missingMandatoryOptionValue(anOption);
- }
- });
- });
- }
- _checkForConflictingLocalOptions() {
- const definedNonDefaultOptions = this.options.filter((option) => {
- const optionKey = option.attributeName();
- if (this.getOptionValue(optionKey) === undefined) {
- return false;
- }
- return this.getOptionValueSource(optionKey) !== "default";
- });
- const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
- optionsWithConflicting.forEach((option) => {
- const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
- if (conflictingAndDefined) {
- this._conflictingOption(option, conflictingAndDefined);
- }
- });
- }
- _checkForConflictingOptions() {
- this._getCommandAndAncestors().forEach((cmd) => {
- cmd._checkForConflictingLocalOptions();
- });
- }
- parseOptions(argv) {
- const operands = [];
- const unknown = [];
- let dest = operands;
- const args = argv.slice();
- function maybeOption(arg) {
- return arg.length > 1 && arg[0] === "-";
- }
- let activeVariadicOption = null;
- while (args.length) {
- const arg = args.shift();
- if (arg === "--") {
- if (dest === unknown)
- dest.push(arg);
- dest.push(...args);
- break;
- }
- if (activeVariadicOption && !maybeOption(arg)) {
- this.emit(`option:${activeVariadicOption.name()}`, arg);
- continue;
- }
- activeVariadicOption = null;
- if (maybeOption(arg)) {
- const option = this._findOption(arg);
- if (option) {
- if (option.required) {
- const value = args.shift();
- if (value === undefined)
- this.optionMissingArgument(option);
- this.emit(`option:${option.name()}`, value);
- } else if (option.optional) {
- let value = null;
- if (args.length > 0 && !maybeOption(args[0])) {
- value = args.shift();
- }
- this.emit(`option:${option.name()}`, value);
- } else {
- this.emit(`option:${option.name()}`);
- }
- activeVariadicOption = option.variadic ? option : null;
- continue;
- }
- }
- if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
- const option = this._findOption(`-${arg[1]}`);
- if (option) {
- if (option.required || option.optional && this._combineFlagAndOptionalValue) {
- this.emit(`option:${option.name()}`, arg.slice(2));
- } else {
- this.emit(`option:${option.name()}`);
- args.unshift(`-${arg.slice(2)}`);
- }
- continue;
- }
- }
- if (/^--[^=]+=/.test(arg)) {
- const index = arg.indexOf("=");
- const option = this._findOption(arg.slice(0, index));
- if (option && (option.required || option.optional)) {
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
- continue;
- }
- }
- if (maybeOption(arg)) {
- dest = unknown;
- }
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
- if (this._findCommand(arg)) {
- operands.push(arg);
- if (args.length > 0)
- unknown.push(...args);
- break;
- } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
- operands.push(arg);
- if (args.length > 0)
- operands.push(...args);
- break;
- } else if (this._defaultCommandName) {
- unknown.push(arg);
- if (args.length > 0)
- unknown.push(...args);
- break;
- }
- }
- if (this._passThroughOptions) {
- dest.push(arg);
- if (args.length > 0)
- dest.push(...args);
- break;
- }
- dest.push(arg);
- }
- return { operands, unknown };
- }
- opts() {
- if (this._storeOptionsAsProperties) {
- const result = {};
- const len = this.options.length;
- for (let i = 0;i < len; i++) {
- const key = this.options[i].attributeName();
- result[key] = key === this._versionOptionName ? this._version : this[key];
- }
- return result;
- }
- return this._optionValues;
- }
- optsWithGlobals() {
- return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
- }
- error(message, errorOptions) {
- this._outputConfiguration.outputError(`${message}
-`, this._outputConfiguration.writeErr);
- if (typeof this._showHelpAfterError === "string") {
- this._outputConfiguration.writeErr(`${this._showHelpAfterError}
-`);
- } else if (this._showHelpAfterError) {
- this._outputConfiguration.writeErr(`
-`);
- this.outputHelp({ error: true });
- }
- const config = errorOptions || {};
- const exitCode = config.exitCode || 1;
- const code = config.code || "commander.error";
- this._exit(exitCode, code, message);
- }
- _parseOptionsEnv() {
- this.options.forEach((option) => {
- if (option.envVar && option.envVar in process2.env) {
- const optionKey = option.attributeName();
- if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
- if (option.required || option.optional) {
- this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
- } else {
- this.emit(`optionEnv:${option.name()}`);
- }
- }
- }
- });
- }
- _parseOptionsImplied() {
- const dualHelper = new DualOptions(this.options);
- const hasCustomOptionValue = (optionKey) => {
- return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
- };
- this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
- Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
- this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
- });
- });
- }
- missingArgument(name) {
- const message = `error: missing required argument '${name}'`;
- this.error(message, { code: "commander.missingArgument" });
- }
- optionMissingArgument(option) {
- const message = `error: option '${option.flags}' argument missing`;
- this.error(message, { code: "commander.optionMissingArgument" });
- }
- missingMandatoryOptionValue(option) {
- const message = `error: required option '${option.flags}' not specified`;
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
- }
- _conflictingOption(option, conflictingOption) {
- const findBestOptionFromValue = (option2) => {
- const optionKey = option2.attributeName();
- const optionValue = this.getOptionValue(optionKey);
- const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
- const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
- if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
- return negativeOption;
- }
- return positiveOption || option2;
- };
- const getErrorMessage = (option2) => {
- const bestOption = findBestOptionFromValue(option2);
- const optionKey = bestOption.attributeName();
- const source = this.getOptionValueSource(optionKey);
- if (source === "env") {
- return `environment variable '${bestOption.envVar}'`;
- }
- return `option '${bestOption.flags}'`;
- };
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
- this.error(message, { code: "commander.conflictingOption" });
- }
- unknownOption(flag) {
- if (this._allowUnknownOption)
- return;
- let suggestion = "";
- if (flag.startsWith("--") && this._showSuggestionAfterError) {
- let candidateFlags = [];
- let command = this;
- do {
- const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
- candidateFlags = candidateFlags.concat(moreFlags);
- command = command.parent;
- } while (command && !command._enablePositionalOptions);
- suggestion = suggestSimilar(flag, candidateFlags);
- }
- const message = `error: unknown option '${flag}'${suggestion}`;
- this.error(message, { code: "commander.unknownOption" });
- }
- _excessArguments(receivedArgs) {
- if (this._allowExcessArguments)
- return;
- const expected = this.registeredArguments.length;
- const s = expected === 1 ? "" : "s";
- const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
- this.error(message, { code: "commander.excessArguments" });
- }
- unknownCommand() {
- const unknownName = this.args[0];
- let suggestion = "";
- if (this._showSuggestionAfterError) {
- const candidateNames = [];
- this.createHelp().visibleCommands(this).forEach((command) => {
- candidateNames.push(command.name());
- if (command.alias())
- candidateNames.push(command.alias());
- });
- suggestion = suggestSimilar(unknownName, candidateNames);
- }
- const message = `error: unknown command '${unknownName}'${suggestion}`;
- this.error(message, { code: "commander.unknownCommand" });
- }
- version(str, flags, description) {
- if (str === undefined)
- return this._version;
- this._version = str;
- flags = flags || "-V, --version";
- description = description || "output the version number";
- const versionOption = this.createOption(flags, description);
- this._versionOptionName = versionOption.attributeName();
- this._registerOption(versionOption);
- this.on("option:" + versionOption.name(), () => {
- this._outputConfiguration.writeOut(`${str}
-`);
- this._exit(0, "commander.version", str);
- });
- return this;
- }
- description(str, argsDescription) {
- if (str === undefined && argsDescription === undefined)
- return this._description;
- this._description = str;
- if (argsDescription) {
- this._argsDescription = argsDescription;
- }
- return this;
- }
- summary(str) {
- if (str === undefined)
- return this._summary;
- this._summary = str;
- return this;
- }
- alias(alias) {
- if (alias === undefined)
- return this._aliases[0];
- let command = this;
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
- command = this.commands[this.commands.length - 1];
- }
- if (alias === command._name)
- throw new Error("Command alias can't be the same as its name");
- const matchingCommand = this.parent?._findCommand(alias);
- if (matchingCommand) {
- const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
- throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
- }
- command._aliases.push(alias);
- return this;
- }
- aliases(aliases) {
- if (aliases === undefined)
- return this._aliases;
- aliases.forEach((alias) => this.alias(alias));
- return this;
- }
- usage(str) {
- if (str === undefined) {
- if (this._usage)
- return this._usage;
- const args = this.registeredArguments.map((arg) => {
- return humanReadableArgName(arg);
- });
- return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
- }
- this._usage = str;
- return this;
- }
- name(str) {
- if (str === undefined)
- return this._name;
- this._name = str;
- return this;
- }
- nameFromFilename(filename) {
- this._name = path.basename(filename, path.extname(filename));
- return this;
- }
- executableDir(path2) {
- if (path2 === undefined)
- return this._executableDir;
- this._executableDir = path2;
- return this;
- }
- helpInformation(contextOptions) {
- const helper = this.createHelp();
- const context = this._getOutputContext(contextOptions);
- helper.prepareContext({
- error: context.error,
- helpWidth: context.helpWidth,
- outputHasColors: context.hasColors
- });
- const text = helper.formatHelp(this, helper);
- if (context.hasColors)
- return text;
- return this._outputConfiguration.stripColor(text);
- }
- _getOutputContext(contextOptions) {
- contextOptions = contextOptions || {};
- const error = !!contextOptions.error;
- let baseWrite;
- let hasColors;
- let helpWidth;
- if (error) {
- baseWrite = (str) => this._outputConfiguration.writeErr(str);
- hasColors = this._outputConfiguration.getErrHasColors();
- helpWidth = this._outputConfiguration.getErrHelpWidth();
- } else {
- baseWrite = (str) => this._outputConfiguration.writeOut(str);
- hasColors = this._outputConfiguration.getOutHasColors();
- helpWidth = this._outputConfiguration.getOutHelpWidth();
- }
- const write = (str) => {
- if (!hasColors)
- str = this._outputConfiguration.stripColor(str);
- return baseWrite(str);
- };
- return { error, write, hasColors, helpWidth };
- }
- outputHelp(contextOptions) {
- let deprecatedCallback;
- if (typeof contextOptions === "function") {
- deprecatedCallback = contextOptions;
- contextOptions = undefined;
- }
- const outputContext = this._getOutputContext(contextOptions);
- const eventContext = {
- error: outputContext.error,
- write: outputContext.write,
- command: this
- };
- this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
- this.emit("beforeHelp", eventContext);
- let helpInformation = this.helpInformation({ error: outputContext.error });
- if (deprecatedCallback) {
- helpInformation = deprecatedCallback(helpInformation);
- if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
- throw new Error("outputHelp callback must return a string or a Buffer");
- }
- }
- outputContext.write(helpInformation);
- if (this._getHelpOption()?.long) {
- this.emit(this._getHelpOption().long);
- }
- this.emit("afterHelp", eventContext);
- this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
- }
- helpOption(flags, description) {
- if (typeof flags === "boolean") {
- if (flags) {
- this._helpOption = this._helpOption ?? undefined;
- } else {
- this._helpOption = null;
- }
- return this;
- }
- flags = flags ?? "-h, --help";
- description = description ?? "display help for command";
- this._helpOption = this.createOption(flags, description);
- return this;
- }
- _getHelpOption() {
- if (this._helpOption === undefined) {
- this.helpOption(undefined, undefined);
- }
- return this._helpOption;
- }
- addHelpOption(option) {
- this._helpOption = option;
- return this;
- }
- help(contextOptions) {
- this.outputHelp(contextOptions);
- let exitCode = Number(process2.exitCode ?? 0);
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
- exitCode = 1;
- }
- this._exit(exitCode, "commander.help", "(outputHelp)");
- }
- addHelpText(position, text) {
- const allowedValues = ["beforeAll", "before", "after", "afterAll"];
- if (!allowedValues.includes(position)) {
- throw new Error(`Unexpected value for position to addHelpText.
-Expecting one of '${allowedValues.join("', '")}'`);
- }
- const helpEvent = `${position}Help`;
- this.on(helpEvent, (context) => {
- let helpStr;
- if (typeof text === "function") {
- helpStr = text({ error: context.error, command: context.command });
- } else {
- helpStr = text;
- }
- if (helpStr) {
- context.write(`${helpStr}
-`);
- }
- });
- return this;
- }
- _outputHelpIfRequested(args) {
- const helpOption = this._getHelpOption();
- const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
- if (helpRequested) {
- this.outputHelp();
- this._exit(0, "commander.helpDisplayed", "(outputHelp)");
- }
- }
- }
- function incrementNodeInspectorPort(args) {
- return args.map((arg) => {
- if (!arg.startsWith("--inspect")) {
- return arg;
- }
- let debugOption;
- let debugHost = "127.0.0.1";
- let debugPort = "9229";
- let match;
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
- debugOption = match[1];
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
- debugOption = match[1];
- if (/^\d+$/.test(match[3])) {
- debugPort = match[3];
- } else {
- debugHost = match[3];
- }
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
- debugOption = match[1];
- debugHost = match[3];
- debugPort = match[4];
- }
- if (debugOption && debugPort !== "0") {
- return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
- }
- return arg;
- });
- }
- function useColor() {
- if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
- return false;
- if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
- return true;
- return;
- }
- exports.Command = Command;
- exports.useColor = useColor;
-});
-
-// node_modules/commander/index.js
-var require_commander = __commonJS((exports) => {
- var { Argument } = require_argument();
- var { Command } = require_command();
- var { CommanderError, InvalidArgumentError } = require_error();
- var { Help } = require_help();
- var { Option } = require_option();
- exports.program = new Command;
- exports.createCommand = (name) => new Command(name);
- exports.createOption = (flags, description) => new Option(flags, description);
- exports.createArgument = (name, description) => new Argument(name, description);
- exports.Command = Command;
- exports.Option = Option;
- exports.Argument = Argument;
- exports.Help = Help;
- exports.CommanderError = CommanderError;
- exports.InvalidArgumentError = InvalidArgumentError;
- exports.InvalidOptionArgumentError = InvalidArgumentError;
-});
-
-// node_modules/@commander-js/extra-typings/index.js
-var require_extra_typings = __commonJS((exports, module) => {
- var commander = require_commander();
- exports = module.exports = {};
- exports.program = new commander.Command;
- exports.Argument = commander.Argument;
- exports.Command = commander.Command;
- exports.CommanderError = commander.CommanderError;
- exports.Help = commander.Help;
- exports.InvalidArgumentError = commander.InvalidArgumentError;
- exports.InvalidOptionArgumentError = commander.InvalidArgumentError;
- exports.Option = commander.Option;
- exports.createCommand = (name) => new commander.Command(name);
- exports.createOption = (flags, description) => new commander.Option(flags, description);
- exports.createArgument = (name, description) => new commander.Argument(name, description);
-});
-
-// node_modules/chalk/source/vendor/ansi-styles/index.js
-function assembleStyles() {
- const codes = new Map;
- for (const [groupName, group] of Object.entries(styles)) {
- for (const [styleName, style] of Object.entries(group)) {
- styles[styleName] = {
- open: `\x1B[${style[0]}m`,
- close: `\x1B[${style[1]}m`
- };
- group[styleName] = styles[styleName];
- codes.set(style[0], style[1]);
- }
- Object.defineProperty(styles, groupName, {
- value: group,
- enumerable: false
- });
- }
- Object.defineProperty(styles, "codes", {
- value: codes,
- enumerable: false
- });
- styles.color.close = "\x1B[39m";
- styles.bgColor.close = "\x1B[49m";
- styles.color.ansi = wrapAnsi16();
- styles.color.ansi256 = wrapAnsi256();
- styles.color.ansi16m = wrapAnsi16m();
- styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
- styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
- styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
- Object.defineProperties(styles, {
- rgbToAnsi256: {
- value(red, green, blue) {
- if (red === green && green === blue) {
- if (red < 8) {
- return 16;
- }
- if (red > 248) {
- return 231;
- }
- return Math.round((red - 8) / 247 * 24) + 232;
- }
- return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
- },
- enumerable: false
- },
- hexToRgb: {
- value(hex) {
- const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
- if (!matches) {
- return [0, 0, 0];
- }
- let [colorString] = matches;
- if (colorString.length === 3) {
- colorString = [...colorString].map((character) => character + character).join("");
- }
- const integer = Number.parseInt(colorString, 16);
- return [
- integer >> 16 & 255,
- integer >> 8 & 255,
- integer & 255
- ];
- },
- enumerable: false
- },
- hexToAnsi256: {
- value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
- enumerable: false
- },
- ansi256ToAnsi: {
- value(code) {
- if (code < 8) {
- return 30 + code;
- }
- if (code < 16) {
- return 90 + (code - 8);
- }
- let red;
- let green;
- let blue;
- if (code >= 232) {
- red = ((code - 232) * 10 + 8) / 255;
- green = red;
- blue = red;
- } else {
- code -= 16;
- const remainder = code % 36;
- red = Math.floor(code / 36) / 5;
- green = Math.floor(remainder / 6) / 5;
- blue = remainder % 6 / 5;
- }
- const value = Math.max(red, green, blue) * 2;
- if (value === 0) {
- return 30;
- }
- let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
- if (value === 2) {
- result += 60;
- }
- return result;
- },
- enumerable: false
- },
- rgbToAnsi: {
- value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
- enumerable: false
- },
- hexToAnsi: {
- value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
- enumerable: false
- }
- });
- return styles;
-}
-var ANSI_BACKGROUND_OFFSET = 10, wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`, wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default;
-var init_ansi_styles = __esm(() => {
- styles = {
- modifier: {
- reset: [0, 0],
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- overline: [53, 55],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29]
- },
- color: {
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
- blackBright: [90, 39],
- gray: [90, 39],
- grey: [90, 39],
- redBright: [91, 39],
- greenBright: [92, 39],
- yellowBright: [93, 39],
- blueBright: [94, 39],
- magentaBright: [95, 39],
- cyanBright: [96, 39],
- whiteBright: [97, 39]
- },
- bgColor: {
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
- bgBlackBright: [100, 49],
- bgGray: [100, 49],
- bgGrey: [100, 49],
- bgRedBright: [101, 49],
- bgGreenBright: [102, 49],
- bgYellowBright: [103, 49],
- bgBlueBright: [104, 49],
- bgMagentaBright: [105, 49],
- bgCyanBright: [106, 49],
- bgWhiteBright: [107, 49]
- }
- };
- modifierNames = Object.keys(styles.modifier);
- foregroundColorNames = Object.keys(styles.color);
- backgroundColorNames = Object.keys(styles.bgColor);
- colorNames = [...foregroundColorNames, ...backgroundColorNames];
- ansiStyles = assembleStyles();
- ansi_styles_default = ansiStyles;
-});
-
-// node_modules/chalk/source/vendor/supports-color/index.js
-import process2 from "process";
-import os from "os";
-import tty from "tty";
-function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
- const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
- const position = argv.indexOf(prefix + flag);
- const terminatorPosition = argv.indexOf("--");
- return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
-}
-function envForceColor() {
- if ("FORCE_COLOR" in env) {
- if (env.FORCE_COLOR === "true") {
- return 1;
- }
- if (env.FORCE_COLOR === "false") {
- return 0;
- }
- return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
- }
-}
-function translateLevel(level) {
- if (level === 0) {
- return false;
- }
- return {
- level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3
- };
-}
-function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
- const noFlagForceColor = envForceColor();
- if (noFlagForceColor !== undefined) {
- flagForceColor = noFlagForceColor;
- }
- const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
- if (forceColor === 0) {
- return 0;
- }
- if (sniffFlags) {
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
- return 3;
- }
- if (hasFlag("color=256")) {
- return 2;
- }
- }
- if ("TF_BUILD" in env && "AGENT_NAME" in env) {
- return 1;
- }
- if (haveStream && !streamIsTTY && forceColor === undefined) {
- return 0;
- }
- const min = forceColor || 0;
- if (env.TERM === "dumb") {
- return min;
- }
- if (process2.platform === "win32") {
- const osRelease = os.release().split(".");
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
- }
- return 1;
- }
- if ("CI" in env) {
- if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => (key in env))) {
- return 3;
- }
- if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => (sign in env)) || env.CI_NAME === "codeship") {
- return 1;
- }
- return min;
- }
- if ("TEAMCITY_VERSION" in env) {
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
- }
- if (env.COLORTERM === "truecolor") {
- return 3;
- }
- if (env.TERM === "xterm-kitty") {
- return 3;
- }
- if (env.TERM === "xterm-ghostty") {
- return 3;
- }
- if (env.TERM === "wezterm") {
- return 3;
- }
- if ("TERM_PROGRAM" in env) {
- const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
- switch (env.TERM_PROGRAM) {
- case "iTerm.app": {
- return version >= 3 ? 3 : 2;
- }
- case "Apple_Terminal": {
- return 2;
- }
- }
- }
- if (/-256(color)?$/i.test(env.TERM)) {
- return 2;
- }
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
- return 1;
- }
- if ("COLORTERM" in env) {
- return 1;
- }
- return min;
-}
-function createSupportsColor(stream, options = {}) {
- const level = _supportsColor(stream, {
- streamIsTTY: stream && stream.isTTY,
- ...options
- });
- return translateLevel(level);
-}
-var env, flagForceColor, supportsColor, supports_color_default;
-var init_supports_color = __esm(() => {
- ({ env } = process2);
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
- flagForceColor = 0;
- } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
- flagForceColor = 1;
- }
- supportsColor = {
- stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
- stderr: createSupportsColor({ isTTY: tty.isatty(2) })
- };
- supports_color_default = supportsColor;
-});
-
-// node_modules/chalk/source/utilities.js
-function stringReplaceAll(string, substring, replacer) {
- let index = string.indexOf(substring);
- if (index === -1) {
- return string;
- }
- const substringLength = substring.length;
- let endIndex = 0;
- let returnValue = "";
- do {
- returnValue += string.slice(endIndex, index) + substring + replacer;
- endIndex = index + substringLength;
- index = string.indexOf(substring, endIndex);
- } while (index !== -1);
- returnValue += string.slice(endIndex);
- return returnValue;
-}
-function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
- let endIndex = 0;
- let returnValue = "";
- do {
- const gotCR = string[index - 1] === "\r";
- returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? `\r
-` : `
-`) + postfix;
- endIndex = index + 1;
- index = string.indexOf(`
-`, endIndex);
- } while (index !== -1);
- returnValue += string.slice(endIndex);
- return returnValue;
-}
-
-// node_modules/chalk/source/index.js
-class Chalk {
- constructor(options) {
- return chalkFactory(options);
- }
-}
-function createChalk(options) {
- return chalkFactory(options);
-}
-var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions = (object, options = {}) => {
- if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
- throw new Error("The `level` option should be an integer from 0 to 3");
- }
- const colorLevel = stdoutColor ? stdoutColor.level : 0;
- object.level = options.level === undefined ? colorLevel : options.level;
-}, chalkFactory = (options) => {
- const chalk = (...strings) => strings.join(" ");
- applyOptions(chalk, options);
- Object.setPrototypeOf(chalk, createChalk.prototype);
- return chalk;
-}, getModelAnsi = (model, level, type, ...arguments_) => {
- if (model === "rgb") {
- if (level === "ansi16m") {
- return ansi_styles_default[type].ansi16m(...arguments_);
- }
- if (level === "ansi256") {
- return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
- }
- return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
- }
- if (model === "hex") {
- return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
- }
- return ansi_styles_default[type][model](...arguments_);
-}, usedModels, proto, createStyler = (open2, close, parent) => {
- let openAll;
- let closeAll;
- if (parent === undefined) {
- openAll = open2;
- closeAll = close;
- } else {
- openAll = parent.openAll + open2;
- closeAll = close + parent.closeAll;
- }
- return {
- open: open2,
- close,
- openAll,
- closeAll,
- parent
- };
-}, createBuilder = (self2, _styler, _isEmpty) => {
- const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
- Object.setPrototypeOf(builder, proto);
- builder[GENERATOR] = self2;
- builder[STYLER] = _styler;
- builder[IS_EMPTY] = _isEmpty;
- return builder;
-}, applyStyle = (self2, string) => {
- if (self2.level <= 0 || !string) {
- return self2[IS_EMPTY] ? "" : string;
- }
- let styler = self2[STYLER];
- if (styler === undefined) {
- return string;
- }
- const { openAll, closeAll } = styler;
- if (string.includes("\x1B")) {
- while (styler !== undefined) {
- string = stringReplaceAll(string, styler.close, styler.open);
- styler = styler.parent;
- }
- }
- const lfIndex = string.indexOf(`
-`);
- if (lfIndex !== -1) {
- string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
- }
- return openAll + string + closeAll;
-}, chalk, chalkStderr, source_default;
-var init_source = __esm(() => {
- init_ansi_styles();
- init_supports_color();
- ({ stdout: stdoutColor, stderr: stderrColor } = supports_color_default);
- GENERATOR = Symbol("GENERATOR");
- STYLER = Symbol("STYLER");
- IS_EMPTY = Symbol("IS_EMPTY");
- levelMapping = [
- "ansi",
- "ansi",
- "ansi256",
- "ansi16m"
- ];
- styles2 = Object.create(null);
- Object.setPrototypeOf(createChalk.prototype, Function.prototype);
- for (const [styleName, style] of Object.entries(ansi_styles_default)) {
- styles2[styleName] = {
- get() {
- const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
- Object.defineProperty(this, styleName, { value: builder });
- return builder;
- }
- };
- }
- styles2.visible = {
- get() {
- const builder = createBuilder(this, this[STYLER], true);
- Object.defineProperty(this, "visible", { value: builder });
- return builder;
- }
- };
- usedModels = ["rgb", "hex", "ansi256"];
- for (const model of usedModels) {
- styles2[model] = {
- get() {
- const { level } = this;
- return function(...arguments_) {
- const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
- return createBuilder(this, styler, this[IS_EMPTY]);
- };
- }
- };
- const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
- styles2[bgModel] = {
- get() {
- const { level } = this;
- return function(...arguments_) {
- const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
- return createBuilder(this, styler, this[IS_EMPTY]);
- };
- }
- };
- }
- proto = Object.defineProperties(() => {}, {
- ...styles2,
- level: {
- enumerable: true,
- get() {
- return this[GENERATOR].level;
- },
- set(level) {
- this[GENERATOR].level = level;
- }
- }
- });
- Object.defineProperties(createChalk.prototype, styles2);
- chalk = createChalk();
- chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
- source_default = chalk;
-});
-
-// node_modules/lodash-es/_createBaseFor.js
-function createBaseFor(fromRight) {
- return function(object, iteratee, keysFunc) {
- var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length;
- while (length--) {
- var key = props[fromRight ? length : ++index];
- if (iteratee(iterable[key], key, iterable) === false) {
- break;
- }
- }
- return object;
- };
-}
-var _createBaseFor_default;
-var init__createBaseFor = __esm(() => {
- _createBaseFor_default = createBaseFor;
-});
-
-// node_modules/lodash-es/_baseFor.js
-var baseFor, _baseFor_default;
-var init__baseFor = __esm(() => {
- init__createBaseFor();
- baseFor = _createBaseFor_default();
- _baseFor_default = baseFor;
-});
-
-// node_modules/lodash-es/_baseForOwn.js
-function baseForOwn(object, iteratee) {
- return object && _baseFor_default(object, iteratee, keys_default);
-}
-var _baseForOwn_default;
-var init__baseForOwn = __esm(() => {
- init__baseFor();
- init_keys();
- _baseForOwn_default = baseForOwn;
-});
-
-// node_modules/lodash-es/mapValues.js
-function mapValues(object, iteratee) {
- var result = {};
- iteratee = _baseIteratee_default(iteratee, 3);
- _baseForOwn_default(object, function(value, key, object2) {
- _baseAssignValue_default(result, key, iteratee(value, key, object2));
- });
- return result;
-}
-var mapValues_default;
-var init_mapValues = __esm(() => {
- init__baseAssignValue();
- init__baseForOwn();
- init__baseIteratee();
- mapValues_default = mapValues;
-});
-
-// node_modules/lodash-es/_baseSet.js
-function baseSet(object, path, value, customizer) {
- if (!isObject_default(object)) {
- return object;
- }
- path = _castPath_default(path, object);
- var index = -1, length = path.length, lastIndex = length - 1, nested = object;
- while (nested != null && ++index < length) {
- var key = _toKey_default(path[index]), newValue = value;
- if (key === "__proto__" || key === "constructor" || key === "prototype") {
- return object;
- }
- if (index != lastIndex) {
- var objValue = nested[key];
- newValue = customizer ? customizer(objValue, key, nested) : undefined;
- if (newValue === undefined) {
- newValue = isObject_default(objValue) ? objValue : _isIndex_default(path[index + 1]) ? [] : {};
- }
- }
- _assignValue_default(nested, key, newValue);
- nested = nested[key];
- }
- return object;
-}
-var _baseSet_default;
-var init__baseSet = __esm(() => {
- init__assignValue();
- init__castPath();
- init__isIndex();
- init_isObject();
- init__toKey();
- _baseSet_default = baseSet;
-});
-
-// node_modules/lodash-es/_basePickBy.js
-function basePickBy(object, paths, predicate) {
- var index = -1, length = paths.length, result = {};
- while (++index < length) {
- var path = paths[index], value = _baseGet_default(object, path);
- if (predicate(value, path)) {
- _baseSet_default(result, _castPath_default(path, object), value);
- }
- }
- return result;
-}
-var _basePickBy_default;
-var init__basePickBy = __esm(() => {
- init__baseGet();
- init__baseSet();
- init__castPath();
- _basePickBy_default = basePickBy;
-});
-
-// node_modules/lodash-es/pickBy.js
-function pickBy(object, predicate) {
- if (object == null) {
- return {};
- }
- var props = _arrayMap_default(_getAllKeysIn_default(object), function(prop) {
- return [prop];
- });
- predicate = _baseIteratee_default(predicate);
- return _basePickBy_default(object, props, function(value, path) {
- return predicate(value, path[0]);
- });
-}
-var pickBy_default;
-var init_pickBy = __esm(() => {
- init__arrayMap();
- init__baseIteratee();
- init__basePickBy();
- init__getAllKeysIn();
- pickBy_default = pickBy;
-});
-
-// node_modules/lodash-es/_baseFindIndex.js
-function baseFindIndex(array, predicate, fromIndex, fromRight) {
- var length = array.length, index = fromIndex + (fromRight ? 1 : -1);
- while (fromRight ? index-- : ++index < length) {
- if (predicate(array[index], index, array)) {
- return index;
- }
- }
- return -1;
-}
-var _baseFindIndex_default;
-var init__baseFindIndex = __esm(() => {
- _baseFindIndex_default = baseFindIndex;
-});
-
-// node_modules/lodash-es/_baseIsNaN.js
-function baseIsNaN(value) {
- return value !== value;
-}
-var _baseIsNaN_default;
-var init__baseIsNaN = __esm(() => {
- _baseIsNaN_default = baseIsNaN;
-});
-
-// node_modules/lodash-es/_strictIndexOf.js
-function strictIndexOf(array, value, fromIndex) {
- var index = fromIndex - 1, length = array.length;
- while (++index < length) {
- if (array[index] === value) {
- return index;
- }
- }
- return -1;
-}
-var _strictIndexOf_default;
-var init__strictIndexOf = __esm(() => {
- _strictIndexOf_default = strictIndexOf;
-});
-
-// node_modules/lodash-es/_baseIndexOf.js
-function baseIndexOf(array, value, fromIndex) {
- return value === value ? _strictIndexOf_default(array, value, fromIndex) : _baseFindIndex_default(array, _baseIsNaN_default, fromIndex);
-}
-var _baseIndexOf_default;
-var init__baseIndexOf = __esm(() => {
- init__baseFindIndex();
- init__baseIsNaN();
- init__strictIndexOf();
- _baseIndexOf_default = baseIndexOf;
-});
-
-// node_modules/lodash-es/_arrayIncludes.js
-function arrayIncludes(array, value) {
- var length = array == null ? 0 : array.length;
- return !!length && _baseIndexOf_default(array, value, 0) > -1;
-}
-var _arrayIncludes_default;
-var init__arrayIncludes = __esm(() => {
- init__baseIndexOf();
- _arrayIncludes_default = arrayIncludes;
-});
-
-// node_modules/lodash-es/_arrayIncludesWith.js
-function arrayIncludesWith(array, value, comparator) {
- var index = -1, length = array == null ? 0 : array.length;
- while (++index < length) {
- if (comparator(value, array[index])) {
- return true;
- }
- }
- return false;
-}
-var _arrayIncludesWith_default;
-var init__arrayIncludesWith = __esm(() => {
- _arrayIncludesWith_default = arrayIncludesWith;
-});
-
-// node_modules/lodash-es/noop.js
-function noop2() {}
-var noop_default;
-var init_noop = __esm(() => {
- noop_default = noop2;
-});
-
-// node_modules/lodash-es/_createSet.js
-var INFINITY3, createSet, _createSet_default;
-var init__createSet = __esm(() => {
- init__Set();
- init_noop();
- init__setToArray();
- INFINITY3 = 1 / 0;
- createSet = !(_Set_default && 1 / _setToArray_default(new _Set_default([, -0]))[1] == INFINITY3) ? noop_default : function(values) {
- return new _Set_default(values);
- };
- _createSet_default = createSet;
-});
-
-// node_modules/lodash-es/_baseUniq.js
-function baseUniq(array, iteratee, comparator) {
- var index = -1, includes = _arrayIncludes_default, length = array.length, isCommon = true, result = [], seen = result;
- if (comparator) {
- isCommon = false;
- includes = _arrayIncludesWith_default;
- } else if (length >= LARGE_ARRAY_SIZE2) {
- var set = iteratee ? null : _createSet_default(array);
- if (set) {
- return _setToArray_default(set);
- }
- isCommon = false;
- includes = _cacheHas_default;
- seen = new _SetCache_default;
- } else {
- seen = iteratee ? [] : result;
- }
- outer:
- while (++index < length) {
- var value = array[index], computed = iteratee ? iteratee(value) : value;
- value = comparator || value !== 0 ? value : 0;
- if (isCommon && computed === computed) {
- var seenIndex = seen.length;
- while (seenIndex--) {
- if (seen[seenIndex] === computed) {
- continue outer;
- }
- }
- if (iteratee) {
- seen.push(computed);
- }
- result.push(value);
- } else if (!includes(seen, computed, comparator)) {
- if (seen !== result) {
- seen.push(computed);
- }
- result.push(value);
- }
- }
- return result;
-}
-var LARGE_ARRAY_SIZE2 = 200, _baseUniq_default;
-var init__baseUniq = __esm(() => {
- init__SetCache();
- init__arrayIncludes();
- init__arrayIncludesWith();
- init__cacheHas();
- init__createSet();
- init__setToArray();
- _baseUniq_default = baseUniq;
-});
-
-// node_modules/lodash-es/uniqBy.js
-function uniqBy(array, iteratee) {
- return array && array.length ? _baseUniq_default(array, _baseIteratee_default(iteratee, 2)) : [];
-}
-var uniqBy_default;
-var init_uniqBy = __esm(() => {
- init__baseIteratee();
- init__baseUniq();
- uniqBy_default = uniqBy;
-});
-
-// src/bridge/sessionIdCompat.ts
-var exports_sessionIdCompat = {};
-__export(exports_sessionIdCompat, {
- toInfraSessionId: () => toInfraSessionId,
- toCompatSessionId: () => toCompatSessionId,
- setCseShimGate: () => setCseShimGate
-});
-function setCseShimGate(gate) {
- _isCseShimEnabled = gate;
-}
-function toCompatSessionId(id) {
- if (!id.startsWith("cse_"))
- return id;
- if (_isCseShimEnabled && !_isCseShimEnabled())
- return id;
- return "session_" + id.slice("cse_".length);
-}
-function toInfraSessionId(id) {
- if (!id.startsWith("session_"))
- return id;
- return "cse_" + id.slice("session_".length);
-}
-var _isCseShimEnabled;
-
-// src/constants/product.ts
-function isRemoteSessionStaging(sessionId, ingressUrl) {
- return sessionId?.includes("_staging_") === true || ingressUrl?.includes("staging") === true;
-}
-function isRemoteSessionLocal(sessionId, ingressUrl) {
- return sessionId?.includes("_local_") === true || ingressUrl?.includes("localhost") === true;
-}
-function getClaudeAiBaseUrl(sessionId, ingressUrl) {
- if (isRemoteSessionLocal(sessionId, ingressUrl)) {
- return CLAUDE_AI_LOCAL_BASE_URL;
- }
- if (isRemoteSessionStaging(sessionId, ingressUrl)) {
- return CLAUDE_AI_STAGING_BASE_URL;
- }
- return CLAUDE_AI_BASE_URL;
-}
-function getRemoteSessionUrl(sessionId, ingressUrl) {
- const { toCompatSessionId: toCompatSessionId2 } = __toCommonJS(exports_sessionIdCompat);
- const compatId = toCompatSessionId2(sessionId);
- const baseUrl = getClaudeAiBaseUrl(compatId, ingressUrl);
- return `${baseUrl}/code/${compatId}`;
-}
-var PRODUCT_URL = "https://claude.com/claude-code", CLAUDE_AI_BASE_URL = "https://claude.ai", CLAUDE_AI_STAGING_BASE_URL = "https://claude-ai.staging.ant.dev", CLAUDE_AI_LOCAL_BASE_URL = "http://localhost:4000";
-
-// src/constants/common.ts
-function getLocalISODate() {
- if (process.env.CLAUDE_CODE_OVERRIDE_DATE) {
- return process.env.CLAUDE_CODE_OVERRIDE_DATE;
- }
- const now = new Date;
- const year = now.getFullYear();
- const month = String(now.getMonth() + 1).padStart(2, "0");
- const day = String(now.getDate()).padStart(2, "0");
- return `${year}-${month}-${day}`;
-}
-function getLocalMonthYear() {
- const date = process.env.CLAUDE_CODE_OVERRIDE_DATE ? new Date(process.env.CLAUDE_CODE_OVERRIDE_DATE) : new Date;
- return date.toLocaleString("en-US", { month: "long", year: "numeric" });
-}
-var getSessionStartDate;
-var init_common = __esm(() => {
- init_memoize();
- getSessionStartDate = memoize_default(getLocalISODate);
-});
-
-// node_modules/ignore/index.js
-var require_ignore = __commonJS((exports, module) => {
- function makeArray(subject) {
- return Array.isArray(subject) ? subject : [subject];
- }
- var EMPTY = "";
- var SPACE = " ";
- var ESCAPE = "\\";
- var REGEX_TEST_BLANK_LINE = /^\s+$/;
- var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
- var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
- var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
- var REGEX_SPLITALL_CRLF = /\r?\n/g;
- var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
- var SLASH = "/";
- var TMP_KEY_IGNORE = "node-ignore";
- if (typeof Symbol !== "undefined") {
- TMP_KEY_IGNORE = Symbol.for("node-ignore");
- }
- var KEY_IGNORE = TMP_KEY_IGNORE;
- var define2 = (object, key, value) => Object.defineProperty(object, key, { value });
- var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
- var RETURN_FALSE = () => false;
- var sanitizeRange = (range) => range.replace(REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY);
- var cleanRangeBackSlash = (slashes) => {
- const { length } = slashes;
- return slashes.slice(0, length - length % 2);
- };
- var REPLACERS = [
- [
- /^\uFEFF/,
- () => EMPTY
- ],
- [
- /((?:\\\\)*?)(\\?\s+)$/,
- (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
- ],
- [
- /(\\+?)\s/g,
- (_, m1) => {
- const { length } = m1;
- return m1.slice(0, length - length % 2) + SPACE;
- }
- ],
- [
- /[\\$.|*+(){^]/g,
- (match) => `\\${match}`
- ],
- [
- /(?!\\)\?/g,
- () => "[^/]"
- ],
- [
- /^\//,
- () => "^"
- ],
- [
- /\//g,
- () => "\\/"
- ],
- [
- /^\^*\\\*\\\*\\\//,
- () => "^(?:.*\\/)?"
- ],
- [
- /^(?=[^^])/,
- function startingReplacer() {
- return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
- }
- ],
- [
- /\\\/\\\*\\\*(?=\\\/|$)/g,
- (_, index, str) => index + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
- ],
- [
- /(^|[^\\]+)(\\\*)+(?=.+)/g,
- (_, p1, p2) => {
- const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
- return p1 + unescaped;
- }
- ],
- [
- /\\\\\\(?=[$.|*+(){^])/g,
- () => ESCAPE
- ],
- [
- /\\\\/g,
- () => ESCAPE
- ],
- [
- /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
- (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
- ],
- [
- /(?:[^*])$/,
- (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`
- ],
- [
- /(\^|\\\/)?\\\*$/,
- (_, p1) => {
- const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
- return `${prefix}(?=$|\\/$)`;
- }
- ]
- ];
- var regexCache = Object.create(null);
- var makeRegex = (pattern, ignoreCase) => {
- let source = regexCache[pattern];
- if (!source) {
- source = REPLACERS.reduce((prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)), pattern);
- regexCache[pattern] = source;
- }
- return ignoreCase ? new RegExp(source, "i") : new RegExp(source);
- };
- var isString = (subject) => typeof subject === "string";
- var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
- var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF);
-
- class IgnoreRule {
- constructor(origin, pattern, negative, regex2) {
- this.origin = origin;
- this.pattern = pattern;
- this.negative = negative;
- this.regex = regex2;
- }
- }
- var createRule = (pattern, ignoreCase) => {
- const origin = pattern;
- let negative = false;
- if (pattern.indexOf("!") === 0) {
- negative = true;
- pattern = pattern.substr(1);
- }
- pattern = pattern.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
- const regex2 = makeRegex(pattern, ignoreCase);
- return new IgnoreRule(origin, pattern, negative, regex2);
- };
- var throwError = (message, Ctor) => {
- throw new Ctor(message);
- };
- var checkPath = (path, originalPath, doThrow) => {
- if (!isString(path)) {
- return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
- }
- if (!path) {
- return doThrow(`path must not be empty`, TypeError);
- }
- if (checkPath.isNotRelative(path)) {
- const r = "`path.relative()`d";
- return doThrow(`path should be a ${r} string, but got "${originalPath}"`, RangeError);
- }
- return true;
- };
- var isNotRelative = (path) => REGEX_TEST_INVALID_PATH.test(path);
- checkPath.isNotRelative = isNotRelative;
- checkPath.convert = (p) => p;
-
- class Ignore {
- constructor({
- ignorecase = true,
- ignoreCase = ignorecase,
- allowRelativePaths = false
- } = {}) {
- define2(this, KEY_IGNORE, true);
- this._rules = [];
- this._ignoreCase = ignoreCase;
- this._allowRelativePaths = allowRelativePaths;
- this._initCache();
- }
- _initCache() {
- this._ignoreCache = Object.create(null);
- this._testCache = Object.create(null);
- }
- _addPattern(pattern) {
- if (pattern && pattern[KEY_IGNORE]) {
- this._rules = this._rules.concat(pattern._rules);
- this._added = true;
- return;
- }
- if (checkPattern(pattern)) {
- const rule = createRule(pattern, this._ignoreCase);
- this._added = true;
- this._rules.push(rule);
- }
- }
- add(pattern) {
- this._added = false;
- makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this);
- if (this._added) {
- this._initCache();
- }
- return this;
- }
- addPattern(pattern) {
- return this.add(pattern);
- }
- _testOne(path, checkUnignored) {
- let ignored = false;
- let unignored = false;
- this._rules.forEach((rule) => {
- const { negative } = rule;
- if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
- return;
- }
- const matched = rule.regex.test(path);
- if (matched) {
- ignored = !negative;
- unignored = negative;
- }
- });
- return {
- ignored,
- unignored
- };
- }
- _test(originalPath, cache, checkUnignored, slices) {
- const path = originalPath && checkPath.convert(originalPath);
- checkPath(path, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
- return this._t(path, cache, checkUnignored, slices);
- }
- _t(path, cache, checkUnignored, slices) {
- if (path in cache) {
- return cache[path];
- }
- if (!slices) {
- slices = path.split(SLASH);
- }
- slices.pop();
- if (!slices.length) {
- return cache[path] = this._testOne(path, checkUnignored);
- }
- const parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices);
- return cache[path] = parent.ignored ? parent : this._testOne(path, checkUnignored);
- }
- ignores(path) {
- return this._test(path, this._ignoreCache, false).ignored;
- }
- createFilter() {
- return (path) => !this.ignores(path);
- }
- filter(paths) {
- return makeArray(paths).filter(this.createFilter());
- }
- test(path) {
- return this._test(path, this._testCache, true);
- }
- }
- var factory = (options) => new Ignore(options);
- var isPathValid = (path) => checkPath(path && checkPath.convert(path), path, RETURN_FALSE);
- factory.isPathValid = isPathValid;
- factory.default = factory;
- module.exports = factory;
- if (typeof process !== "undefined" && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === "win32")) {
- const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
- checkPath.convert = makePosix;
- const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
- checkPath.isNotRelative = (path) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
- }
-});
-
-// node_modules/marked/lib/marked.esm.js
-function _getDefaults() {
- return {
- async: false,
- breaks: false,
- extensions: null,
- gfm: true,
- hooks: null,
- pedantic: false,
- renderer: null,
- silent: false,
- tokenizer: null,
- walkTokens: null
- };
-}
-function changeDefaults(newDefaults) {
- _defaults = newDefaults;
-}
-function edit(regex2, opt = "") {
- let source = typeof regex2 === "string" ? regex2 : regex2.source;
- const obj = {
- replace: (name, val) => {
- let valSource = typeof val === "string" ? val : val.source;
- valSource = valSource.replace(other.caret, "$1");
- source = source.replace(name, valSource);
- return obj;
- },
- getRegex: () => {
- return new RegExp(source, opt);
- }
- };
- return obj;
-}
-function escape22(html2, encode) {
- if (encode) {
- if (other.escapeTest.test(html2)) {
- return html2.replace(other.escapeReplace, getEscapeReplacement);
- }
- } else {
- if (other.escapeTestNoEncode.test(html2)) {
- return html2.replace(other.escapeReplaceNoEncode, getEscapeReplacement);
- }
- }
- return html2;
-}
-function cleanUrl(href) {
- try {
- href = encodeURI(href).replace(other.percentDecode, "%");
- } catch {
- return null;
- }
- return href;
-}
-function splitCells(tableRow, count) {
- const row = tableRow.replace(other.findPipe, (match, offset, str) => {
- let escaped = false;
- let curr = offset;
- while (--curr >= 0 && str[curr] === "\\")
- escaped = !escaped;
- if (escaped) {
- return "|";
- } else {
- return " |";
- }
- }), cells = row.split(other.splitPipe);
- let i = 0;
- if (!cells[0].trim()) {
- cells.shift();
- }
- if (cells.length > 0 && !cells.at(-1)?.trim()) {
- cells.pop();
- }
- if (count) {
- if (cells.length > count) {
- cells.splice(count);
- } else {
- while (cells.length < count)
- cells.push("");
- }
- }
- for (;i < cells.length; i++) {
- cells[i] = cells[i].trim().replace(other.slashPipe, "|");
- }
- return cells;
-}
-function rtrim(str, c, invert) {
- const l = str.length;
- if (l === 0) {
- return "";
- }
- let suffLen = 0;
- while (suffLen < l) {
- const currChar = str.charAt(l - suffLen - 1);
- if (currChar === c && !invert) {
- suffLen++;
- } else if (currChar !== c && invert) {
- suffLen++;
- } else {
- break;
- }
- }
- return str.slice(0, l - suffLen);
-}
-function findClosingBracket(str, b) {
- if (str.indexOf(b[1]) === -1) {
- return -1;
- }
- let level = 0;
- for (let i = 0;i < str.length; i++) {
- if (str[i] === "\\") {
- i++;
- } else if (str[i] === b[0]) {
- level++;
- } else if (str[i] === b[1]) {
- level--;
- if (level < 0) {
- return i;
- }
- }
- }
- if (level > 0) {
- return -2;
- }
- return -1;
-}
-function outputLink(cap, link2, raw, lexer2, rules) {
- const href = link2.href;
- const title = link2.title || null;
- const text = cap[1].replace(rules.other.outputLinkReplace, "$1");
- lexer2.state.inLink = true;
- const token = {
- type: cap[0].charAt(0) === "!" ? "image" : "link",
- raw,
- href,
- title,
- text,
- tokens: lexer2.inlineTokens(text)
- };
- lexer2.state.inLink = false;
- return token;
-}
-function indentCodeCompensation(raw, text, rules) {
- const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);
- if (matchIndentToCode === null) {
- return text;
- }
- const indentToCode = matchIndentToCode[1];
- return text.split(`
-`).map((node) => {
- const matchIndentInNode = node.match(rules.other.beginningSpace);
- if (matchIndentInNode === null) {
- return node;
- }
- const [indentInNode] = matchIndentInNode;
- if (indentInNode.length >= indentToCode.length) {
- return node.slice(indentToCode.length);
- }
- return node;
- }).join(`
-`);
-}
-function marked(src, opt) {
- return markedInstance.parse(src, opt);
-}
-var _defaults, noopTest, other, newline, blockCode, fences, hr, heading, bullet, lheadingCore, lheading, lheadingGfm, _paragraph, blockText, _blockLabel, def, list, _tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul", _comment, html, paragraph, blockquote, blockNormal, gfmTable, blockGfm, blockPedantic, escape2, inlineCode, br, inlineText, _punctuation, _punctuationOrSpace, _notPunctuationOrSpace, punctuation, _punctuationGfmStrongEm, _punctuationOrSpaceGfmStrongEm, _notPunctuationOrSpaceGfmStrongEm, blockSkip, emStrongLDelimCore, emStrongLDelim, emStrongLDelimGfm, emStrongRDelimAstCore = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)", emStrongRDelimAst, emStrongRDelimAstGfm, emStrongRDelimUnd, anyPunctuation, autolink, _inlineComment, tag, _inlineLabel, link, reflink, nolink, reflinkSearch, inlineNormal, inlinePedantic, inlineGfm, inlineBreaks, block, inline, escapeReplacements, getEscapeReplacement = (ch) => escapeReplacements[ch], _Tokenizer = class {
- options;
- rules;
- lexer;
- constructor(options2) {
- this.options = options2 || _defaults;
- }
- space(src) {
- const cap = this.rules.block.newline.exec(src);
- if (cap && cap[0].length > 0) {
- return {
- type: "space",
- raw: cap[0]
- };
- }
- }
- code(src) {
- const cap = this.rules.block.code.exec(src);
- if (cap) {
- const text = cap[0].replace(this.rules.other.codeRemoveIndent, "");
- return {
- type: "code",
- raw: cap[0],
- codeBlockStyle: "indented",
- text: !this.options.pedantic ? rtrim(text, `
-`) : text
- };
- }
- }
- fences(src) {
- const cap = this.rules.block.fences.exec(src);
- if (cap) {
- const raw = cap[0];
- const text = indentCodeCompensation(raw, cap[3] || "", this.rules);
- return {
- type: "code",
- raw,
- lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : cap[2],
- text
- };
- }
- }
- heading(src) {
- const cap = this.rules.block.heading.exec(src);
- if (cap) {
- let text = cap[2].trim();
- if (this.rules.other.endingHash.test(text)) {
- const trimmed = rtrim(text, "#");
- if (this.options.pedantic) {
- text = trimmed.trim();
- } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {
- text = trimmed.trim();
- }
- }
- return {
- type: "heading",
- raw: cap[0],
- depth: cap[1].length,
- text,
- tokens: this.lexer.inline(text)
- };
- }
- }
- hr(src) {
- const cap = this.rules.block.hr.exec(src);
- if (cap) {
- return {
- type: "hr",
- raw: rtrim(cap[0], `
-`)
- };
- }
- }
- blockquote(src) {
- const cap = this.rules.block.blockquote.exec(src);
- if (cap) {
- let lines = rtrim(cap[0], `
-`).split(`
-`);
- let raw = "";
- let text = "";
- const tokens = [];
- while (lines.length > 0) {
- let inBlockquote = false;
- const currentLines = [];
- let i;
- for (i = 0;i < lines.length; i++) {
- if (this.rules.other.blockquoteStart.test(lines[i])) {
- currentLines.push(lines[i]);
- inBlockquote = true;
- } else if (!inBlockquote) {
- currentLines.push(lines[i]);
- } else {
- break;
- }
- }
- lines = lines.slice(i);
- const currentRaw = currentLines.join(`
-`);
- const currentText = currentRaw.replace(this.rules.other.blockquoteSetextReplace, `
- $1`).replace(this.rules.other.blockquoteSetextReplace2, "");
- raw = raw ? `${raw}
-${currentRaw}` : currentRaw;
- text = text ? `${text}
-${currentText}` : currentText;
- const top = this.lexer.state.top;
- this.lexer.state.top = true;
- this.lexer.blockTokens(currentText, tokens, true);
- this.lexer.state.top = top;
- if (lines.length === 0) {
- break;
- }
- const lastToken = tokens.at(-1);
- if (lastToken?.type === "code") {
- break;
- } else if (lastToken?.type === "blockquote") {
- const oldToken = lastToken;
- const newText = oldToken.raw + `
-` + lines.join(`
-`);
- const newToken = this.blockquote(newText);
- tokens[tokens.length - 1] = newToken;
- raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;
- text = text.substring(0, text.length - oldToken.text.length) + newToken.text;
- break;
- } else if (lastToken?.type === "list") {
- const oldToken = lastToken;
- const newText = oldToken.raw + `
-` + lines.join(`
-`);
- const newToken = this.list(newText);
- tokens[tokens.length - 1] = newToken;
- raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;
- text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;
- lines = newText.substring(tokens.at(-1).raw.length).split(`
-`);
- continue;
- }
- }
- return {
- type: "blockquote",
- raw,
- tokens,
- text
- };
- }
- }
- list(src) {
- let cap = this.rules.block.list.exec(src);
- if (cap) {
- let bull = cap[1].trim();
- const isordered = bull.length > 1;
- const list2 = {
- type: "list",
- raw: "",
- ordered: isordered,
- start: isordered ? +bull.slice(0, -1) : "",
- loose: false,
- items: []
- };
- bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
- if (this.options.pedantic) {
- bull = isordered ? bull : "[*+-]";
- }
- const itemRegex = this.rules.other.listItemRegex(bull);
- let endsWithBlankLine = false;
- while (src) {
- let endEarly = false;
- let raw = "";
- let itemContents = "";
- if (!(cap = itemRegex.exec(src))) {
- break;
- }
- if (this.rules.block.hr.test(src)) {
- break;
- }
- raw = cap[0];
- src = src.substring(raw.length);
- let line = cap[2].split(`
-`, 1)[0].replace(this.rules.other.listReplaceTabs, (t) => " ".repeat(3 * t.length));
- let nextLine = src.split(`
-`, 1)[0];
- let blankLine = !line.trim();
- let indent = 0;
- if (this.options.pedantic) {
- indent = 2;
- itemContents = line.trimStart();
- } else if (blankLine) {
- indent = cap[1].length + 1;
- } else {
- indent = cap[2].search(this.rules.other.nonSpaceChar);
- indent = indent > 4 ? 1 : indent;
- itemContents = line.slice(indent);
- indent += cap[1].length;
- }
- if (blankLine && this.rules.other.blankLine.test(nextLine)) {
- raw += nextLine + `
-`;
- src = src.substring(nextLine.length + 1);
- endEarly = true;
- }
- if (!endEarly) {
- const nextBulletRegex = this.rules.other.nextBulletRegex(indent);
- const hrRegex = this.rules.other.hrRegex(indent);
- const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);
- const headingBeginRegex = this.rules.other.headingBeginRegex(indent);
- const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);
- while (src) {
- const rawLine = src.split(`
-`, 1)[0];
- let nextLineWithoutTabs;
- nextLine = rawLine;
- if (this.options.pedantic) {
- nextLine = nextLine.replace(this.rules.other.listReplaceNesting, " ");
- nextLineWithoutTabs = nextLine;
- } else {
- nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, " ");
- }
- if (fencesBeginRegex.test(nextLine)) {
- break;
- }
- if (headingBeginRegex.test(nextLine)) {
- break;
- }
- if (htmlBeginRegex.test(nextLine)) {
- break;
- }
- if (nextBulletRegex.test(nextLine)) {
- break;
- }
- if (hrRegex.test(nextLine)) {
- break;
- }
- if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) {
- itemContents += `
-` + nextLineWithoutTabs.slice(indent);
- } else {
- if (blankLine) {
- break;
- }
- if (line.replace(this.rules.other.tabCharGlobal, " ").search(this.rules.other.nonSpaceChar) >= 4) {
- break;
- }
- if (fencesBeginRegex.test(line)) {
- break;
- }
- if (headingBeginRegex.test(line)) {
- break;
- }
- if (hrRegex.test(line)) {
- break;
- }
- itemContents += `
-` + nextLine;
- }
- if (!blankLine && !nextLine.trim()) {
- blankLine = true;
- }
- raw += rawLine + `
-`;
- src = src.substring(rawLine.length + 1);
- line = nextLineWithoutTabs.slice(indent);
- }
- }
- if (!list2.loose) {
- if (endsWithBlankLine) {
- list2.loose = true;
- } else if (this.rules.other.doubleBlankLine.test(raw)) {
- endsWithBlankLine = true;
- }
- }
- let istask = null;
- let ischecked;
- if (this.options.gfm) {
- istask = this.rules.other.listIsTask.exec(itemContents);
- if (istask) {
- ischecked = istask[0] !== "[ ] ";
- itemContents = itemContents.replace(this.rules.other.listReplaceTask, "");
- }
- }
- list2.items.push({
- type: "list_item",
- raw,
- task: !!istask,
- checked: ischecked,
- loose: false,
- text: itemContents,
- tokens: []
- });
- list2.raw += raw;
- }
- const lastItem = list2.items.at(-1);
- if (lastItem) {
- lastItem.raw = lastItem.raw.trimEnd();
- lastItem.text = lastItem.text.trimEnd();
- } else {
- return;
- }
- list2.raw = list2.raw.trimEnd();
- for (let i = 0;i < list2.items.length; i++) {
- this.lexer.state.top = false;
- list2.items[i].tokens = this.lexer.blockTokens(list2.items[i].text, []);
- if (!list2.loose) {
- const spacers = list2.items[i].tokens.filter((t) => t.type === "space");
- const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t) => this.rules.other.anyLine.test(t.raw));
- list2.loose = hasMultipleLineBreaks;
- }
- }
- if (list2.loose) {
- for (let i = 0;i < list2.items.length; i++) {
- list2.items[i].loose = true;
- }
- }
- return list2;
- }
- }
- html(src) {
- const cap = this.rules.block.html.exec(src);
- if (cap) {
- const token = {
- type: "html",
- block: true,
- raw: cap[0],
- pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style",
- text: cap[0]
- };
- return token;
- }
- }
- def(src) {
- const cap = this.rules.block.def.exec(src);
- if (cap) {
- const tag2 = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " ");
- const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "";
- const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : cap[3];
- return {
- type: "def",
- tag: tag2,
- raw: cap[0],
- href,
- title
- };
- }
- }
- table(src) {
- const cap = this.rules.block.table.exec(src);
- if (!cap) {
- return;
- }
- if (!this.rules.other.tableDelimiter.test(cap[2])) {
- return;
- }
- const headers = splitCells(cap[1]);
- const aligns = cap[2].replace(this.rules.other.tableAlignChars, "").split("|");
- const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, "").split(`
-`) : [];
- const item = {
- type: "table",
- raw: cap[0],
- header: [],
- align: [],
- rows: []
- };
- if (headers.length !== aligns.length) {
- return;
- }
- for (const align of aligns) {
- if (this.rules.other.tableAlignRight.test(align)) {
- item.align.push("right");
- } else if (this.rules.other.tableAlignCenter.test(align)) {
- item.align.push("center");
- } else if (this.rules.other.tableAlignLeft.test(align)) {
- item.align.push("left");
- } else {
- item.align.push(null);
- }
- }
- for (let i = 0;i < headers.length; i++) {
- item.header.push({
- text: headers[i],
- tokens: this.lexer.inline(headers[i]),
- header: true,
- align: item.align[i]
- });
- }
- for (const row of rows) {
- item.rows.push(splitCells(row, item.header.length).map((cell, i) => {
- return {
- text: cell,
- tokens: this.lexer.inline(cell),
- header: false,
- align: item.align[i]
- };
- }));
- }
- return item;
- }
- lheading(src) {
- const cap = this.rules.block.lheading.exec(src);
- if (cap) {
- return {
- type: "heading",
- raw: cap[0],
- depth: cap[2].charAt(0) === "=" ? 1 : 2,
- text: cap[1],
- tokens: this.lexer.inline(cap[1])
- };
- }
- }
- paragraph(src) {
- const cap = this.rules.block.paragraph.exec(src);
- if (cap) {
- const text = cap[1].charAt(cap[1].length - 1) === `
-` ? cap[1].slice(0, -1) : cap[1];
- return {
- type: "paragraph",
- raw: cap[0],
- text,
- tokens: this.lexer.inline(text)
- };
- }
- }
- text(src) {
- const cap = this.rules.block.text.exec(src);
- if (cap) {
- return {
- type: "text",
- raw: cap[0],
- text: cap[0],
- tokens: this.lexer.inline(cap[0])
- };
- }
- }
- escape(src) {
- const cap = this.rules.inline.escape.exec(src);
- if (cap) {
- return {
- type: "escape",
- raw: cap[0],
- text: cap[1]
- };
- }
- }
- tag(src) {
- const cap = this.rules.inline.tag.exec(src);
- if (cap) {
- if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {
- this.lexer.state.inLink = true;
- } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {
- this.lexer.state.inLink = false;
- }
- if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {
- this.lexer.state.inRawBlock = true;
- } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {
- this.lexer.state.inRawBlock = false;
- }
- return {
- type: "html",
- raw: cap[0],
- inLink: this.lexer.state.inLink,
- inRawBlock: this.lexer.state.inRawBlock,
- block: false,
- text: cap[0]
- };
- }
- }
- link(src) {
- const cap = this.rules.inline.link.exec(src);
- if (cap) {
- const trimmedUrl = cap[2].trim();
- if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {
- if (!this.rules.other.endAngleBracket.test(trimmedUrl)) {
- return;
- }
- const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), "\\");
- if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
- return;
- }
- } else {
- const lastParenIndex = findClosingBracket(cap[2], "()");
- if (lastParenIndex === -2) {
- return;
- }
- if (lastParenIndex > -1) {
- const start = cap[0].indexOf("!") === 0 ? 5 : 4;
- const linkLen = start + cap[1].length + lastParenIndex;
- cap[2] = cap[2].substring(0, lastParenIndex);
- cap[0] = cap[0].substring(0, linkLen).trim();
- cap[3] = "";
- }
- }
- let href = cap[2];
- let title = "";
- if (this.options.pedantic) {
- const link2 = this.rules.other.pedanticHrefTitle.exec(href);
- if (link2) {
- href = link2[1];
- title = link2[3];
- }
- } else {
- title = cap[3] ? cap[3].slice(1, -1) : "";
- }
- href = href.trim();
- if (this.rules.other.startAngleBracket.test(href)) {
- if (this.options.pedantic && !this.rules.other.endAngleBracket.test(trimmedUrl)) {
- href = href.slice(1);
- } else {
- href = href.slice(1, -1);
- }
- }
- return outputLink(cap, {
- href: href ? href.replace(this.rules.inline.anyPunctuation, "$1") : href,
- title: title ? title.replace(this.rules.inline.anyPunctuation, "$1") : title
- }, cap[0], this.lexer, this.rules);
- }
- }
- reflink(src, links) {
- let cap;
- if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
- const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, " ");
- const link2 = links[linkString.toLowerCase()];
- if (!link2) {
- const text = cap[0].charAt(0);
- return {
- type: "text",
- raw: text,
- text
- };
- }
- return outputLink(cap, link2, cap[0], this.lexer, this.rules);
- }
- }
- emStrong(src, maskedSrc, prevChar = "") {
- let match = this.rules.inline.emStrongLDelim.exec(src);
- if (!match)
- return;
- if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric))
- return;
- const nextChar = match[1] || match[2] || "";
- if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
- const lLength = [...match[0]].length - 1;
- let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
- const endReg = match[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
- endReg.lastIndex = 0;
- maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
- while ((match = endReg.exec(maskedSrc)) != null) {
- rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
- if (!rDelim)
- continue;
- rLength = [...rDelim].length;
- if (match[3] || match[4]) {
- delimTotal += rLength;
- continue;
- } else if (match[5] || match[6]) {
- if (lLength % 3 && !((lLength + rLength) % 3)) {
- midDelimTotal += rLength;
- continue;
- }
- }
- delimTotal -= rLength;
- if (delimTotal > 0)
- continue;
- rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
- const lastCharLength = [...match[0]][0].length;
- const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);
- if (Math.min(lLength, rLength) % 2) {
- const text2 = raw.slice(1, -1);
- return {
- type: "em",
- raw,
- text: text2,
- tokens: this.lexer.inlineTokens(text2)
- };
- }
- const text = raw.slice(2, -2);
- return {
- type: "strong",
- raw,
- text,
- tokens: this.lexer.inlineTokens(text)
- };
- }
- }
- }
- codespan(src) {
- const cap = this.rules.inline.code.exec(src);
- if (cap) {
- let text = cap[2].replace(this.rules.other.newLineCharGlobal, " ");
- const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);
- const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);
- if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
- text = text.substring(1, text.length - 1);
- }
- return {
- type: "codespan",
- raw: cap[0],
- text
- };
- }
- }
- br(src) {
- const cap = this.rules.inline.br.exec(src);
- if (cap) {
- return {
- type: "br",
- raw: cap[0]
- };
- }
- }
- del(src) {
- const cap = this.rules.inline.del.exec(src);
- if (cap) {
- return {
- type: "del",
- raw: cap[0],
- text: cap[2],
- tokens: this.lexer.inlineTokens(cap[2])
- };
- }
- }
- autolink(src) {
- const cap = this.rules.inline.autolink.exec(src);
- if (cap) {
- let text, href;
- if (cap[2] === "@") {
- text = cap[1];
- href = "mailto:" + text;
- } else {
- text = cap[1];
- href = text;
- }
- return {
- type: "link",
- raw: cap[0],
- text,
- href,
- tokens: [
- {
- type: "text",
- raw: text,
- text
- }
- ]
- };
- }
- }
- url(src) {
- let cap;
- if (cap = this.rules.inline.url.exec(src)) {
- let text, href;
- if (cap[2] === "@") {
- text = cap[0];
- href = "mailto:" + text;
- } else {
- let prevCapZero;
- do {
- prevCapZero = cap[0];
- cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? "";
- } while (prevCapZero !== cap[0]);
- text = cap[0];
- if (cap[1] === "www.") {
- href = "http://" + cap[0];
- } else {
- href = cap[0];
- }
- }
- return {
- type: "link",
- raw: cap[0],
- text,
- href,
- tokens: [
- {
- type: "text",
- raw: text,
- text
- }
- ]
- };
- }
- }
- inlineText(src) {
- const cap = this.rules.inline.text.exec(src);
- if (cap) {
- const escaped = this.lexer.state.inRawBlock;
- return {
- type: "text",
- raw: cap[0],
- text: cap[0],
- escaped
- };
- }
- }
-}, _Lexer = class __Lexer {
- tokens;
- options;
- state;
- tokenizer;
- inlineQueue;
- constructor(options2) {
- this.tokens = [];
- this.tokens.links = /* @__PURE__ */ Object.create(null);
- this.options = options2 || _defaults;
- this.options.tokenizer = this.options.tokenizer || new _Tokenizer;
- this.tokenizer = this.options.tokenizer;
- this.tokenizer.options = this.options;
- this.tokenizer.lexer = this;
- this.inlineQueue = [];
- this.state = {
- inLink: false,
- inRawBlock: false,
- top: true
- };
- const rules = {
- other,
- block: block.normal,
- inline: inline.normal
- };
- if (this.options.pedantic) {
- rules.block = block.pedantic;
- rules.inline = inline.pedantic;
- } else if (this.options.gfm) {
- rules.block = block.gfm;
- if (this.options.breaks) {
- rules.inline = inline.breaks;
- } else {
- rules.inline = inline.gfm;
- }
- }
- this.tokenizer.rules = rules;
- }
- static get rules() {
- return {
- block,
- inline
- };
- }
- static lex(src, options2) {
- const lexer2 = new __Lexer(options2);
- return lexer2.lex(src);
- }
- static lexInline(src, options2) {
- const lexer2 = new __Lexer(options2);
- return lexer2.inlineTokens(src);
- }
- lex(src) {
- src = src.replace(other.carriageReturn, `
-`);
- this.blockTokens(src, this.tokens);
- for (let i = 0;i < this.inlineQueue.length; i++) {
- const next = this.inlineQueue[i];
- this.inlineTokens(next.src, next.tokens);
- }
- this.inlineQueue = [];
- return this.tokens;
- }
- blockTokens(src, tokens = [], lastParagraphClipped = false) {
- if (this.options.pedantic) {
- src = src.replace(other.tabCharGlobal, " ").replace(other.spaceLine, "");
- }
- while (src) {
- let token;
- if (this.options.extensions?.block?.some((extTokenizer) => {
- if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- return true;
- }
- return false;
- })) {
- continue;
- }
- if (token = this.tokenizer.space(src)) {
- src = src.substring(token.raw.length);
- const lastToken = tokens.at(-1);
- if (token.raw.length === 1 && lastToken !== undefined) {
- lastToken.raw += `
-`;
- } else {
- tokens.push(token);
- }
- continue;
- }
- if (token = this.tokenizer.code(src)) {
- src = src.substring(token.raw.length);
- const lastToken = tokens.at(-1);
- if (lastToken?.type === "paragraph" || lastToken?.type === "text") {
- lastToken.raw += `
-` + token.raw;
- lastToken.text += `
-` + token.text;
- this.inlineQueue.at(-1).src = lastToken.text;
- } else {
- tokens.push(token);
- }
- continue;
- }
- if (token = this.tokenizer.fences(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.heading(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.hr(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.blockquote(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.list(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.html(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.def(src)) {
- src = src.substring(token.raw.length);
- const lastToken = tokens.at(-1);
- if (lastToken?.type === "paragraph" || lastToken?.type === "text") {
- lastToken.raw += `
-` + token.raw;
- lastToken.text += `
-` + token.raw;
- this.inlineQueue.at(-1).src = lastToken.text;
- } else if (!this.tokens.links[token.tag]) {
- this.tokens.links[token.tag] = {
- href: token.href,
- title: token.title
- };
- }
- continue;
- }
- if (token = this.tokenizer.table(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.lheading(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- let cutSrc = src;
- if (this.options.extensions?.startBlock) {
- let startIndex = Infinity;
- const tempSrc = src.slice(1);
- let tempStart;
- this.options.extensions.startBlock.forEach((getStartIndex) => {
- tempStart = getStartIndex.call({ lexer: this }, tempSrc);
- if (typeof tempStart === "number" && tempStart >= 0) {
- startIndex = Math.min(startIndex, tempStart);
- }
- });
- if (startIndex < Infinity && startIndex >= 0) {
- cutSrc = src.substring(0, startIndex + 1);
- }
- }
- if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
- const lastToken = tokens.at(-1);
- if (lastParagraphClipped && lastToken?.type === "paragraph") {
- lastToken.raw += `
-` + token.raw;
- lastToken.text += `
-` + token.text;
- this.inlineQueue.pop();
- this.inlineQueue.at(-1).src = lastToken.text;
- } else {
- tokens.push(token);
- }
- lastParagraphClipped = cutSrc.length !== src.length;
- src = src.substring(token.raw.length);
- continue;
- }
- if (token = this.tokenizer.text(src)) {
- src = src.substring(token.raw.length);
- const lastToken = tokens.at(-1);
- if (lastToken?.type === "text") {
- lastToken.raw += `
-` + token.raw;
- lastToken.text += `
-` + token.text;
- this.inlineQueue.pop();
- this.inlineQueue.at(-1).src = lastToken.text;
- } else {
- tokens.push(token);
- }
- continue;
- }
- if (src) {
- const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
- if (this.options.silent) {
- console.error(errMsg);
- break;
- } else {
- throw new Error(errMsg);
- }
- }
- }
- this.state.top = true;
- return tokens;
- }
- inline(src, tokens = []) {
- this.inlineQueue.push({ src, tokens });
- return tokens;
- }
- inlineTokens(src, tokens = []) {
- let maskedSrc = src;
- let match = null;
- if (this.tokens.links) {
- const links = Object.keys(this.tokens.links);
- if (links.length > 0) {
- while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
- if (links.includes(match[0].slice(match[0].lastIndexOf("[") + 1, -1))) {
- maskedSrc = maskedSrc.slice(0, match.index) + "[" + "a".repeat(match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
- }
- }
- }
- }
- while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
- maskedSrc = maskedSrc.slice(0, match.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
- }
- while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
- maskedSrc = maskedSrc.slice(0, match.index) + "[" + "a".repeat(match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
- }
- let keepPrevChar = false;
- let prevChar = "";
- while (src) {
- if (!keepPrevChar) {
- prevChar = "";
- }
- keepPrevChar = false;
- let token;
- if (this.options.extensions?.inline?.some((extTokenizer) => {
- if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- return true;
- }
- return false;
- })) {
- continue;
- }
- if (token = this.tokenizer.escape(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.tag(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.link(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.reflink(src, this.tokens.links)) {
- src = src.substring(token.raw.length);
- const lastToken = tokens.at(-1);
- if (token.type === "text" && lastToken?.type === "text") {
- lastToken.raw += token.raw;
- lastToken.text += token.text;
- } else {
- tokens.push(token);
- }
- continue;
- }
- if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.codespan(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.br(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.del(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (token = this.tokenizer.autolink(src)) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- if (!this.state.inLink && (token = this.tokenizer.url(src))) {
- src = src.substring(token.raw.length);
- tokens.push(token);
- continue;
- }
- let cutSrc = src;
- if (this.options.extensions?.startInline) {
- let startIndex = Infinity;
- const tempSrc = src.slice(1);
- let tempStart;
- this.options.extensions.startInline.forEach((getStartIndex) => {
- tempStart = getStartIndex.call({ lexer: this }, tempSrc);
- if (typeof tempStart === "number" && tempStart >= 0) {
- startIndex = Math.min(startIndex, tempStart);
- }
- });
- if (startIndex < Infinity && startIndex >= 0) {
- cutSrc = src.substring(0, startIndex + 1);
- }
- }
- if (token = this.tokenizer.inlineText(cutSrc)) {
- src = src.substring(token.raw.length);
- if (token.raw.slice(-1) !== "_") {
- prevChar = token.raw.slice(-1);
- }
- keepPrevChar = true;
- const lastToken = tokens.at(-1);
- if (lastToken?.type === "text") {
- lastToken.raw += token.raw;
- lastToken.text += token.text;
- } else {
- tokens.push(token);
- }
- continue;
- }
- if (src) {
- const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
- if (this.options.silent) {
- console.error(errMsg);
- break;
- } else {
- throw new Error(errMsg);
- }
- }
- }
- return tokens;
- }
-}, _Renderer = class {
- options;
- parser;
- constructor(options2) {
- this.options = options2 || _defaults;
- }
- space(token) {
- return "";
- }
- code({ text, lang, escaped }) {
- const langString = (lang || "").match(other.notSpaceStart)?.[0];
- const code = text.replace(other.endingNewline, "") + `
-`;
- if (!langString) {
- return "
" + (escaped ? code : escape22(code, true)) + `
-`;
- }
- return '' + (escaped ? code : escape22(code, true)) + `
-`;
- }
- blockquote({ tokens }) {
- const body = this.parser.parse(tokens);
- return `
-${body}
-`;
- }
- html({ text }) {
- return text;
- }
- heading({ tokens, depth }) {
- return `${this.parser.parseInline(tokens)}
-`;
- }
- hr(token) {
- return `
-`;
- }
- list(token) {
- const ordered = token.ordered;
- const start = token.start;
- let body = "";
- for (let j = 0;j < token.items.length; j++) {
- const item = token.items[j];
- body += this.listitem(item);
- }
- const type = ordered ? "ol" : "ul";
- const startAttr = ordered && start !== 1 ? ' start="' + start + '"' : "";
- return "<" + type + startAttr + `>
-` + body + "" + type + `>
-`;
- }
- listitem(item) {
- let itemBody = "";
- if (item.task) {
- const checkbox = this.checkbox({ checked: !!item.checked });
- if (item.loose) {
- if (item.tokens[0]?.type === "paragraph") {
- item.tokens[0].text = checkbox + " " + item.tokens[0].text;
- if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") {
- item.tokens[0].tokens[0].text = checkbox + " " + escape22(item.tokens[0].tokens[0].text);
- item.tokens[0].tokens[0].escaped = true;
- }
- } else {
- item.tokens.unshift({
- type: "text",
- raw: checkbox + " ",
- text: checkbox + " ",
- escaped: true
- });
- }
- } else {
- itemBody += checkbox + " ";
- }
- }
- itemBody += this.parser.parse(item.tokens, !!item.loose);
- return `${itemBody}
-`;
- }
- checkbox({ checked }) {
- return "';
- }
- paragraph({ tokens }) {
- return `${this.parser.parseInline(tokens)}
-`;
- }
- table(token) {
- let header = "";
- let cell = "";
- for (let j = 0;j < token.header.length; j++) {
- cell += this.tablecell(token.header[j]);
- }
- header += this.tablerow({ text: cell });
- let body = "";
- for (let j = 0;j < token.rows.length; j++) {
- const row = token.rows[j];
- cell = "";
- for (let k = 0;k < row.length; k++) {
- cell += this.tablecell(row[k]);
- }
- body += this.tablerow({ text: cell });
- }
- if (body)
- body = `${body}`;
- return `
-
-` + header + `
-` + body + `
-`;
- }
- tablerow({ text }) {
- return `
-${text}
-`;
- }
- tablecell(token) {
- const content = this.parser.parseInline(token.tokens);
- const type = token.header ? "th" : "td";
- const tag2 = token.align ? `<${type} align="${token.align}">` : `<${type}>`;
- return tag2 + content + `${type}>
-`;
- }
- strong({ tokens }) {
- return `${this.parser.parseInline(tokens)}`;
- }
- em({ tokens }) {
- return `${this.parser.parseInline(tokens)}`;
- }
- codespan({ text }) {
- return `${escape22(text, true)}`;
- }
- br(token) {
- return "
";
- }
- del({ tokens }) {
- return `${this.parser.parseInline(tokens)}`;
- }
- link({ href, title, tokens }) {
- const text = this.parser.parseInline(tokens);
- const cleanHref = cleanUrl(href);
- if (cleanHref === null) {
- return text;
- }
- href = cleanHref;
- let out = '" + text + "";
- return out;
- }
- image({ href, title, text, tokens }) {
- if (tokens) {
- text = this.parser.parseInline(tokens, this.parser.textRenderer);
- }
- const cleanHref = cleanUrl(href);
- if (cleanHref === null) {
- return escape22(text);
- }
- href = cleanHref;
- let out = `
";
- return out;
- }
- text(token) {
- return "tokens" in token && token.tokens ? this.parser.parseInline(token.tokens) : ("escaped" in token) && token.escaped ? token.text : escape22(token.text);
- }
-}, _TextRenderer = class {
- strong({ text }) {
- return text;
- }
- em({ text }) {
- return text;
- }
- codespan({ text }) {
- return text;
- }
- del({ text }) {
- return text;
- }
- html({ text }) {
- return text;
- }
- text({ text }) {
- return text;
- }
- link({ text }) {
- return "" + text;
- }
- image({ text }) {
- return "" + text;
- }
- br() {
- return "";
- }
-}, _Parser = class __Parser {
- options;
- renderer;
- textRenderer;
- constructor(options2) {
- this.options = options2 || _defaults;
- this.options.renderer = this.options.renderer || new _Renderer;
- this.renderer = this.options.renderer;
- this.renderer.options = this.options;
- this.renderer.parser = this;
- this.textRenderer = new _TextRenderer;
- }
- static parse(tokens, options2) {
- const parser2 = new __Parser(options2);
- return parser2.parse(tokens);
- }
- static parseInline(tokens, options2) {
- const parser2 = new __Parser(options2);
- return parser2.parseInline(tokens);
- }
- parse(tokens, top = true) {
- let out = "";
- for (let i = 0;i < tokens.length; i++) {
- const anyToken = tokens[i];
- if (this.options.extensions?.renderers?.[anyToken.type]) {
- const genericToken = anyToken;
- const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
- if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(genericToken.type)) {
- out += ret || "";
- continue;
- }
- }
- const token = anyToken;
- switch (token.type) {
- case "space": {
- out += this.renderer.space(token);
- continue;
- }
- case "hr": {
- out += this.renderer.hr(token);
- continue;
- }
- case "heading": {
- out += this.renderer.heading(token);
- continue;
- }
- case "code": {
- out += this.renderer.code(token);
- continue;
- }
- case "table": {
- out += this.renderer.table(token);
- continue;
- }
- case "blockquote": {
- out += this.renderer.blockquote(token);
- continue;
- }
- case "list": {
- out += this.renderer.list(token);
- continue;
- }
- case "html": {
- out += this.renderer.html(token);
- continue;
- }
- case "paragraph": {
- out += this.renderer.paragraph(token);
- continue;
- }
- case "text": {
- let textToken = token;
- let body = this.renderer.text(textToken);
- while (i + 1 < tokens.length && tokens[i + 1].type === "text") {
- textToken = tokens[++i];
- body += `
-` + this.renderer.text(textToken);
- }
- if (top) {
- out += this.renderer.paragraph({
- type: "paragraph",
- raw: body,
- text: body,
- tokens: [{ type: "text", raw: body, text: body, escaped: true }]
- });
- } else {
- out += body;
- }
- continue;
- }
- default: {
- const errMsg = 'Token with "' + token.type + '" type was not found.';
- if (this.options.silent) {
- console.error(errMsg);
- return "";
- } else {
- throw new Error(errMsg);
- }
- }
- }
- }
- return out;
- }
- parseInline(tokens, renderer = this.renderer) {
- let out = "";
- for (let i = 0;i < tokens.length; i++) {
- const anyToken = tokens[i];
- if (this.options.extensions?.renderers?.[anyToken.type]) {
- const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
- if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(anyToken.type)) {
- out += ret || "";
- continue;
- }
- }
- const token = anyToken;
- switch (token.type) {
- case "escape": {
- out += renderer.text(token);
- break;
- }
- case "html": {
- out += renderer.html(token);
- break;
- }
- case "link": {
- out += renderer.link(token);
- break;
- }
- case "image": {
- out += renderer.image(token);
- break;
- }
- case "strong": {
- out += renderer.strong(token);
- break;
- }
- case "em": {
- out += renderer.em(token);
- break;
- }
- case "codespan": {
- out += renderer.codespan(token);
- break;
- }
- case "br": {
- out += renderer.br(token);
- break;
- }
- case "del": {
- out += renderer.del(token);
- break;
- }
- case "text": {
- out += renderer.text(token);
- break;
- }
- default: {
- const errMsg = 'Token with "' + token.type + '" type was not found.';
- if (this.options.silent) {
- console.error(errMsg);
- return "";
- } else {
- throw new Error(errMsg);
- }
- }
- }
- }
- return out;
- }
-}, _Hooks, Marked = class {
- defaults = _getDefaults();
- options = this.setOptions;
- parse = this.parseMarkdown(true);
- parseInline = this.parseMarkdown(false);
- Parser = _Parser;
- Renderer = _Renderer;
- TextRenderer = _TextRenderer;
- Lexer = _Lexer;
- Tokenizer = _Tokenizer;
- Hooks = _Hooks;
- constructor(...args) {
- this.use(...args);
- }
- walkTokens(tokens, callback) {
- let values = [];
- for (const token of tokens) {
- values = values.concat(callback.call(this, token));
- switch (token.type) {
- case "table": {
- const tableToken = token;
- for (const cell of tableToken.header) {
- values = values.concat(this.walkTokens(cell.tokens, callback));
- }
- for (const row of tableToken.rows) {
- for (const cell of row) {
- values = values.concat(this.walkTokens(cell.tokens, callback));
- }
- }
- break;
- }
- case "list": {
- const listToken = token;
- values = values.concat(this.walkTokens(listToken.items, callback));
- break;
- }
- default: {
- const genericToken = token;
- if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
- this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
- const tokens2 = genericToken[childTokens].flat(Infinity);
- values = values.concat(this.walkTokens(tokens2, callback));
- });
- } else if (genericToken.tokens) {
- values = values.concat(this.walkTokens(genericToken.tokens, callback));
- }
- }
- }
- }
- return values;
- }
- use(...args) {
- const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
- args.forEach((pack) => {
- const opts = { ...pack };
- opts.async = this.defaults.async || opts.async || false;
- if (pack.extensions) {
- pack.extensions.forEach((ext) => {
- if (!ext.name) {
- throw new Error("extension name required");
- }
- if ("renderer" in ext) {
- const prevRenderer = extensions.renderers[ext.name];
- if (prevRenderer) {
- extensions.renderers[ext.name] = function(...args2) {
- let ret = ext.renderer.apply(this, args2);
- if (ret === false) {
- ret = prevRenderer.apply(this, args2);
- }
- return ret;
- };
- } else {
- extensions.renderers[ext.name] = ext.renderer;
- }
- }
- if ("tokenizer" in ext) {
- if (!ext.level || ext.level !== "block" && ext.level !== "inline") {
- throw new Error("extension level must be 'block' or 'inline'");
- }
- const extLevel = extensions[ext.level];
- if (extLevel) {
- extLevel.unshift(ext.tokenizer);
- } else {
- extensions[ext.level] = [ext.tokenizer];
- }
- if (ext.start) {
- if (ext.level === "block") {
- if (extensions.startBlock) {
- extensions.startBlock.push(ext.start);
- } else {
- extensions.startBlock = [ext.start];
- }
- } else if (ext.level === "inline") {
- if (extensions.startInline) {
- extensions.startInline.push(ext.start);
- } else {
- extensions.startInline = [ext.start];
- }
- }
- }
- }
- if ("childTokens" in ext && ext.childTokens) {
- extensions.childTokens[ext.name] = ext.childTokens;
- }
- });
- opts.extensions = extensions;
- }
- if (pack.renderer) {
- const renderer = this.defaults.renderer || new _Renderer(this.defaults);
- for (const prop in pack.renderer) {
- if (!(prop in renderer)) {
- throw new Error(`renderer '${prop}' does not exist`);
- }
- if (["options", "parser"].includes(prop)) {
- continue;
- }
- const rendererProp = prop;
- const rendererFunc = pack.renderer[rendererProp];
- const prevRenderer = renderer[rendererProp];
- renderer[rendererProp] = (...args2) => {
- let ret = rendererFunc.apply(renderer, args2);
- if (ret === false) {
- ret = prevRenderer.apply(renderer, args2);
- }
- return ret || "";
- };
- }
- opts.renderer = renderer;
- }
- if (pack.tokenizer) {
- const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
- for (const prop in pack.tokenizer) {
- if (!(prop in tokenizer)) {
- throw new Error(`tokenizer '${prop}' does not exist`);
- }
- if (["options", "rules", "lexer"].includes(prop)) {
- continue;
- }
- const tokenizerProp = prop;
- const tokenizerFunc = pack.tokenizer[tokenizerProp];
- const prevTokenizer = tokenizer[tokenizerProp];
- tokenizer[tokenizerProp] = (...args2) => {
- let ret = tokenizerFunc.apply(tokenizer, args2);
- if (ret === false) {
- ret = prevTokenizer.apply(tokenizer, args2);
- }
- return ret;
- };
- }
- opts.tokenizer = tokenizer;
- }
- if (pack.hooks) {
- const hooks = this.defaults.hooks || new _Hooks;
- for (const prop in pack.hooks) {
- if (!(prop in hooks)) {
- throw new Error(`hook '${prop}' does not exist`);
- }
- if (["options", "block"].includes(prop)) {
- continue;
- }
- const hooksProp = prop;
- const hooksFunc = pack.hooks[hooksProp];
- const prevHook = hooks[hooksProp];
- if (_Hooks.passThroughHooks.has(prop)) {
- hooks[hooksProp] = (arg) => {
- if (this.defaults.async) {
- return Promise.resolve(hooksFunc.call(hooks, arg)).then((ret2) => {
- return prevHook.call(hooks, ret2);
- });
- }
- const ret = hooksFunc.call(hooks, arg);
- return prevHook.call(hooks, ret);
- };
- } else {
- hooks[hooksProp] = (...args2) => {
- let ret = hooksFunc.apply(hooks, args2);
- if (ret === false) {
- ret = prevHook.apply(hooks, args2);
- }
- return ret;
- };
- }
- }
- opts.hooks = hooks;
- }
- if (pack.walkTokens) {
- const walkTokens2 = this.defaults.walkTokens;
- const packWalktokens = pack.walkTokens;
- opts.walkTokens = function(token) {
- let values = [];
- values.push(packWalktokens.call(this, token));
- if (walkTokens2) {
- values = values.concat(walkTokens2.call(this, token));
- }
- return values;
- };
- }
- this.defaults = { ...this.defaults, ...opts };
- });
- return this;
- }
- setOptions(opt) {
- this.defaults = { ...this.defaults, ...opt };
- return this;
- }
- lexer(src, options2) {
- return _Lexer.lex(src, options2 ?? this.defaults);
- }
- parser(tokens, options2) {
- return _Parser.parse(tokens, options2 ?? this.defaults);
- }
- parseMarkdown(blockType) {
- const parse2 = (src, options2) => {
- const origOpt = { ...options2 };
- const opt = { ...this.defaults, ...origOpt };
- const throwError = this.onError(!!opt.silent, !!opt.async);
- if (this.defaults.async === true && origOpt.async === false) {
- return throwError(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
- }
- if (typeof src === "undefined" || src === null) {
- return throwError(new Error("marked(): input parameter is undefined or null"));
- }
- if (typeof src !== "string") {
- return throwError(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected"));
- }
- if (opt.hooks) {
- opt.hooks.options = opt;
- opt.hooks.block = blockType;
- }
- const lexer2 = opt.hooks ? opt.hooks.provideLexer() : blockType ? _Lexer.lex : _Lexer.lexInline;
- const parser2 = opt.hooks ? opt.hooks.provideParser() : blockType ? _Parser.parse : _Parser.parseInline;
- if (opt.async) {
- return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer2(src2, opt)).then((tokens) => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser2(tokens, opt)).then((html2) => opt.hooks ? opt.hooks.postprocess(html2) : html2).catch(throwError);
- }
- try {
- if (opt.hooks) {
- src = opt.hooks.preprocess(src);
- }
- let tokens = lexer2(src, opt);
- if (opt.hooks) {
- tokens = opt.hooks.processAllTokens(tokens);
- }
- if (opt.walkTokens) {
- this.walkTokens(tokens, opt.walkTokens);
- }
- let html2 = parser2(tokens, opt);
- if (opt.hooks) {
- html2 = opt.hooks.postprocess(html2);
- }
- return html2;
- } catch (e) {
- return throwError(e);
- }
- };
- return parse2;
- }
- onError(silent, async) {
- return (e) => {
- e.message += `
-Please report this to https://github.com/markedjs/marked.`;
- if (silent) {
- const msg = "An error occurred:
" + escape22(e.message + "", true) + "
";
- if (async) {
- return Promise.resolve(msg);
- }
- return msg;
- }
- if (async) {
- return Promise.reject(e);
- }
- throw e;
- };
- }
-}, markedInstance, options, setOptions, use, walkTokens, parseInline, parser, lexer;
-var init_marked_esm = __esm(() => {
- _defaults = _getDefaults();
- noopTest = { exec: () => null };
- other = {
- codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm,
- outputLinkReplace: /\\([\[\]])/g,
- indentCodeCompensation: /^(\s+)(?:```)/,
- beginningSpace: /^\s+/,
- endingHash: /#$/,
- startingSpaceChar: /^ /,
- endingSpaceChar: / $/,
- nonSpaceChar: /[^ ]/,
- newLineCharGlobal: /\n/g,
- tabCharGlobal: /\t/g,
- multipleSpaceGlobal: /\s+/g,
- blankLine: /^[ \t]*$/,
- doubleBlankLine: /\n[ \t]*\n[ \t]*$/,
- blockquoteStart: /^ {0,3}>/,
- blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g,
- blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm,
- listReplaceTabs: /^\t+/,
- listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,
- listIsTask: /^\[[ xX]\] /,
- listReplaceTask: /^\[[ xX]\] +/,
- anyLine: /\n.*\n/,
- hrefBrackets: /^<(.*)>$/,
- tableDelimiter: /[:|]/,
- tableAlignChars: /^\||\| *$/g,
- tableRowBlankLine: /\n[ \t]*$/,
- tableAlignRight: /^ *-+: *$/,
- tableAlignCenter: /^ *:-+: *$/,
- tableAlignLeft: /^ *:-+ *$/,
- startATag: /^/i,
- startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i,
- endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i,
- startAngleBracket: /^,
- endAngleBracket: />$/,
- pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/,
- unicodeAlphaNumeric: /[\p{L}\p{N}]/u,
- escapeTest: /[&<>"']/,
- escapeReplace: /[&<>"']/g,
- escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,
- escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,
- unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,
- caret: /(^|[^\[])\^/g,
- percentDecode: /%25/g,
- findPipe: /\|/g,
- splitPipe: / \|/,
- slashPipe: /\\\|/g,
- carriageReturn: /\r\n|\r/g,
- spaceLine: /^ +$/gm,
- notSpaceStart: /^\S*/,
- endingNewline: /\n$/,
- listItemRegex: (bull) => new RegExp(`^( {0,3}${bull})((?:[ ][^\\n]*)?(?:\\n|$))`),
- nextBulletRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),
- hrRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),
- fencesBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`),
- headingBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),
- htmlBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, "i")
- };
- newline = /^(?:[ \t]*(?:\n|$))+/;
- blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
- fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
- hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
- heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
- bullet = /(?:[*+-]|\d{1,9}[.)])/;
- lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/;
- lheading = edit(lheadingCore).replace(/bull/g, bullet).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex();
- lheadingGfm = edit(lheadingCore).replace(/bull/g, bullet).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex();
- _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
- blockText = /^[^\n]+/;
- _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
- def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", _blockLabel).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
- list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, bullet).getRegex();
- _comment = /|$))/;
- html = edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))", "i").replace("comment", _comment).replace("tag", _tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
- paragraph = edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
- blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", paragraph).getRegex();
- blockNormal = {
- blockquote,
- code: blockCode,
- def,
- fences,
- heading,
- hr,
- html,
- lheading,
- list,
- newline,
- paragraph,
- table: noopTest,
- text: blockText
- };
- gfmTable = edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3}\t)[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
- blockGfm = {
- ...blockNormal,
- lheading: lheadingGfm,
- table: gfmTable,
- paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", gfmTable).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex()
- };
- blockPedantic = {
- ...blockNormal,
- html: edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?\\1> *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", _comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),
- def: /^ *\[([^\]]+)\]: *([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
- heading: /^(#{1,6})(.*)(?:\n+|$)/,
- fences: noopTest,
- lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
- paragraph: edit(_paragraph).replace("hr", hr).replace("heading", ` *#{1,6} *[^
-]`).replace("lheading", lheading).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
- };
- escape2 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
- inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
- br = /^( {2,}|\\)\n(?!\s*$)/;
- inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g;
- emStrongLDelimCore = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/;
- emStrongLDelim = edit(emStrongLDelimCore, "u").replace(/punct/g, _punctuation).getRegex();
- emStrongLDelimGfm = edit(emStrongLDelimCore, "u").replace(/punct/g, _punctuationGfmStrongEm).getRegex();
- emStrongRDelimAst = edit(emStrongRDelimAstCore, "gu").replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();
- emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, "gu").replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm).replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm).replace(/punct/g, _punctuationGfmStrongEm).getRegex();
- emStrongRDelimUnd = edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();
- anyPunctuation = edit(/\\(punct)/, "gu").replace(/punct/g, _punctuation).getRegex();
- autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();
- _inlineComment = edit(_comment).replace("(?:-->|$)", "-->").getRegex();
- tag = edit("^comment|^[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment", _inlineComment).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
- _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
- link = edit(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label", _inlineLabel).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
- reflink = edit(/^!?\[(label)\]\[(ref)\]/).replace("label", _inlineLabel).replace("ref", _blockLabel).getRegex();
- nolink = edit(/^!?\[(ref)\](?:\[\])?/).replace("ref", _blockLabel).getRegex();
- reflinkSearch = edit("reflink|nolink(?!\\()", "g").replace("reflink", reflink).replace("nolink", nolink).getRegex();
- inlineNormal = {
- _backpedal: noopTest,
- anyPunctuation,
- autolink,
- blockSkip,
- br,
- code: inlineCode,
- del: noopTest,
- emStrongLDelim,
- emStrongRDelimAst,
- emStrongRDelimUnd,
- escape: escape2,
- link,
- nolink,
- punctuation,
- reflink,
- reflinkSearch,
- tag,
- text: inlineText,
- url: noopTest
- };
- inlinePedantic = {
- ...inlineNormal,
- link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", _inlineLabel).getRegex(),
- reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", _inlineLabel).getRegex()
- };
- inlineGfm = {
- ...inlineNormal,
- emStrongRDelimAst: emStrongRDelimAstGfm,
- emStrongLDelim: emStrongLDelimGfm,
- url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),
- _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
- del: /^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,
- text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\": ">",
- '"': """,
- "'": "'"
- };
- _Hooks = class {
- options;
- block;
- constructor(options2) {
- this.options = options2 || _defaults;
- }
- static passThroughHooks = /* @__PURE__ */ new Set([
- "preprocess",
- "postprocess",
- "processAllTokens"
- ]);
- preprocess(markdown) {
- return markdown;
- }
- postprocess(html2) {
- return html2;
- }
- processAllTokens(tokens) {
- return tokens;
- }
- provideLexer() {
- return this.block ? _Lexer.lex : _Lexer.lexInline;
- }
- provideParser() {
- return this.block ? _Parser.parse : _Parser.parseInline;
- }
- };
- markedInstance = new Marked;
- marked.options = marked.setOptions = function(options2) {
- markedInstance.setOptions(options2);
- marked.defaults = markedInstance.defaults;
- changeDefaults(marked.defaults);
- return marked;
- };
- marked.getDefaults = _getDefaults;
- marked.defaults = _defaults;
- marked.use = function(...args) {
- markedInstance.use(...args);
- marked.defaults = markedInstance.defaults;
- changeDefaults(marked.defaults);
- return marked;
- };
- marked.walkTokens = function(tokens, callback) {
- return markedInstance.walkTokens(tokens, callback);
- };
- marked.parseInline = markedInstance.parseInline;
- marked.Parser = _Parser;
- marked.parser = _Parser.parse;
- marked.Renderer = _Renderer;
- marked.TextRenderer = _TextRenderer;
- marked.Lexer = _Lexer;
- marked.lexer = _Lexer.lex;
- marked.Tokenizer = _Tokenizer;
- marked.Hooks = _Hooks;
- marked.parse = marked;
- options = marked.options;
- setOptions = marked.setOptions;
- use = marked.use;
- walkTokens = marked.walkTokens;
- parseInline = marked.parseInline;
- parser = _Parser.parse;
- lexer = _Lexer.lex;
-});
-
-// node_modules/picomatch/lib/constants.js
-var require_constants = __commonJS((exports, module) => {
- var WIN_SLASH = "\\\\/";
- var WIN_NO_SLASH = `[^${WIN_SLASH}]`;
- var DEFAULT_MAX_EXTGLOB_RECURSION = 0;
- var DOT_LITERAL = "\\.";
- var PLUS_LITERAL = "\\+";
- var QMARK_LITERAL = "\\?";
- var SLASH_LITERAL = "\\/";
- var ONE_CHAR = "(?=.)";
- var QMARK = "[^/]";
- var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
- var START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
- var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
- var NO_DOT = `(?!${DOT_LITERAL})`;
- var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
- var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
- var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
- var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
- var STAR = `${QMARK}*?`;
- var SEP = "/";
- var POSIX_CHARS = {
- DOT_LITERAL,
- PLUS_LITERAL,
- QMARK_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- QMARK,
- END_ANCHOR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOTS,
- NO_DOT_SLASH,
- NO_DOTS_SLASH,
- QMARK_NO_DOT,
- STAR,
- START_ANCHOR,
- SEP
- };
- var WINDOWS_CHARS = {
- ...POSIX_CHARS,
- SLASH_LITERAL: `[${WIN_SLASH}]`,
- QMARK: WIN_NO_SLASH,
- STAR: `${WIN_NO_SLASH}*?`,
- DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
- NO_DOT: `(?!${DOT_LITERAL})`,
- NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
- NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
- NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
- QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
- START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
- END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
- SEP: "\\"
- };
- var POSIX_REGEX_SOURCE = {
- __proto__: null,
- alnum: "a-zA-Z0-9",
- alpha: "a-zA-Z",
- ascii: "\\x00-\\x7F",
- blank: " \\t",
- cntrl: "\\x00-\\x1F\\x7F",
- digit: "0-9",
- graph: "\\x21-\\x7E",
- lower: "a-z",
- print: "\\x20-\\x7E ",
- punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
- space: " \\t\\r\\n\\v\\f",
- upper: "A-Z",
- word: "A-Za-z0-9_",
- xdigit: "A-Fa-f0-9"
- };
- module.exports = {
- DEFAULT_MAX_EXTGLOB_RECURSION,
- MAX_LENGTH: 1024 * 64,
- POSIX_REGEX_SOURCE,
- REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
- REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
- REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
- REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
- REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
- REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
- REPLACEMENTS: {
- __proto__: null,
- "***": "*",
- "**/**": "**",
- "**/**/**": "**"
- },
- CHAR_0: 48,
- CHAR_9: 57,
- CHAR_UPPERCASE_A: 65,
- CHAR_LOWERCASE_A: 97,
- CHAR_UPPERCASE_Z: 90,
- CHAR_LOWERCASE_Z: 122,
- CHAR_LEFT_PARENTHESES: 40,
- CHAR_RIGHT_PARENTHESES: 41,
- CHAR_ASTERISK: 42,
- CHAR_AMPERSAND: 38,
- CHAR_AT: 64,
- CHAR_BACKWARD_SLASH: 92,
- CHAR_CARRIAGE_RETURN: 13,
- CHAR_CIRCUMFLEX_ACCENT: 94,
- CHAR_COLON: 58,
- CHAR_COMMA: 44,
- CHAR_DOT: 46,
- CHAR_DOUBLE_QUOTE: 34,
- CHAR_EQUAL: 61,
- CHAR_EXCLAMATION_MARK: 33,
- CHAR_FORM_FEED: 12,
- CHAR_FORWARD_SLASH: 47,
- CHAR_GRAVE_ACCENT: 96,
- CHAR_HASH: 35,
- CHAR_HYPHEN_MINUS: 45,
- CHAR_LEFT_ANGLE_BRACKET: 60,
- CHAR_LEFT_CURLY_BRACE: 123,
- CHAR_LEFT_SQUARE_BRACKET: 91,
- CHAR_LINE_FEED: 10,
- CHAR_NO_BREAK_SPACE: 160,
- CHAR_PERCENT: 37,
- CHAR_PLUS: 43,
- CHAR_QUESTION_MARK: 63,
- CHAR_RIGHT_ANGLE_BRACKET: 62,
- CHAR_RIGHT_CURLY_BRACE: 125,
- CHAR_RIGHT_SQUARE_BRACKET: 93,
- CHAR_SEMICOLON: 59,
- CHAR_SINGLE_QUOTE: 39,
- CHAR_SPACE: 32,
- CHAR_TAB: 9,
- CHAR_UNDERSCORE: 95,
- CHAR_VERTICAL_LINE: 124,
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
- extglobChars(chars) {
- return {
- "!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` },
- "?": { type: "qmark", open: "(?:", close: ")?" },
- "+": { type: "plus", open: "(?:", close: ")+" },
- "*": { type: "star", open: "(?:", close: ")*" },
- "@": { type: "at", open: "(?:", close: ")" }
- };
- },
- globChars(win32) {
- return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
- }
- };
-});
-
-// node_modules/picomatch/lib/utils.js
-var require_utils = __commonJS((exports) => {
- var {
- REGEX_BACKSLASH,
- REGEX_REMOVE_BACKSLASH,
- REGEX_SPECIAL_CHARS,
- REGEX_SPECIAL_CHARS_GLOBAL
- } = require_constants();
- exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
- exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
- exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
- exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
- exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
- exports.isWindows = () => {
- if (typeof navigator !== "undefined" && navigator.platform) {
- const platform = navigator.platform.toLowerCase();
- return platform === "win32" || platform === "windows";
- }
- if (typeof process !== "undefined" && process.platform) {
- return process.platform === "win32";
- }
- return false;
- };
- exports.removeBackslashes = (str) => {
- return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
- return match === "\\" ? "" : match;
- });
- };
- exports.escapeLast = (input, char, lastIdx) => {
- const idx = input.lastIndexOf(char, lastIdx);
- if (idx === -1)
- return input;
- if (input[idx - 1] === "\\")
- return exports.escapeLast(input, char, idx - 1);
- return `${input.slice(0, idx)}\\${input.slice(idx)}`;
- };
- exports.removePrefix = (input, state = {}) => {
- let output = input;
- if (output.startsWith("./")) {
- output = output.slice(2);
- state.prefix = "./";
- }
- return output;
- };
- exports.wrapOutput = (input, state = {}, options2 = {}) => {
- const prepend = options2.contains ? "" : "^";
- const append = options2.contains ? "" : "$";
- let output = `${prepend}(?:${input})${append}`;
- if (state.negated === true) {
- output = `(?:^(?!${output}).*$)`;
- }
- return output;
- };
- exports.basename = (path, { windows } = {}) => {
- const segs = path.split(windows ? /[\\/]/ : "/");
- const last = segs[segs.length - 1];
- if (last === "") {
- return segs[segs.length - 2];
- }
- return last;
- };
-});
-
-// node_modules/picomatch/lib/scan.js
-var require_scan = __commonJS((exports, module) => {
- var utils = require_utils();
- var {
- CHAR_ASTERISK,
- CHAR_AT,
- CHAR_BACKWARD_SLASH,
- CHAR_COMMA,
- CHAR_DOT,
- CHAR_EXCLAMATION_MARK,
- CHAR_FORWARD_SLASH,
- CHAR_LEFT_CURLY_BRACE,
- CHAR_LEFT_PARENTHESES,
- CHAR_LEFT_SQUARE_BRACKET,
- CHAR_PLUS,
- CHAR_QUESTION_MARK,
- CHAR_RIGHT_CURLY_BRACE,
- CHAR_RIGHT_PARENTHESES,
- CHAR_RIGHT_SQUARE_BRACKET
- } = require_constants();
- var isPathSeparator = (code) => {
- return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
- };
- var depth = (token) => {
- if (token.isPrefix !== true) {
- token.depth = token.isGlobstar ? Infinity : 1;
- }
- };
- var scan = (input, options2) => {
- const opts = options2 || {};
- const length = input.length - 1;
- const scanToEnd = opts.parts === true || opts.scanToEnd === true;
- const slashes = [];
- const tokens = [];
- const parts = [];
- let str = input;
- let index = -1;
- let start = 0;
- let lastIndex = 0;
- let isBrace = false;
- let isBracket = false;
- let isGlob = false;
- let isExtglob = false;
- let isGlobstar = false;
- let braceEscaped = false;
- let backslashes = false;
- let negated = false;
- let negatedExtglob = false;
- let finished = false;
- let braces = 0;
- let prev;
- let code;
- let token = { value: "", depth: 0, isGlob: false };
- const eos = () => index >= length;
- const peek = () => str.charCodeAt(index + 1);
- const advance = () => {
- prev = code;
- return str.charCodeAt(++index);
- };
- while (index < length) {
- code = advance();
- let next;
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- code = advance();
- if (code === CHAR_LEFT_CURLY_BRACE) {
- braceEscaped = true;
- }
- continue;
- }
- if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
- braces++;
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- advance();
- continue;
- }
- if (code === CHAR_LEFT_CURLY_BRACE) {
- braces++;
- continue;
- }
- if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
- isBrace = token.isBrace = true;
- isGlob = token.isGlob = true;
- finished = true;
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- if (braceEscaped !== true && code === CHAR_COMMA) {
- isBrace = token.isBrace = true;
- isGlob = token.isGlob = true;
- finished = true;
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- if (code === CHAR_RIGHT_CURLY_BRACE) {
- braces--;
- if (braces === 0) {
- braceEscaped = false;
- isBrace = token.isBrace = true;
- finished = true;
- break;
- }
- }
- }
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- if (code === CHAR_FORWARD_SLASH) {
- slashes.push(index);
- tokens.push(token);
- token = { value: "", depth: 0, isGlob: false };
- if (finished === true)
- continue;
- if (prev === CHAR_DOT && index === start + 1) {
- start += 2;
- continue;
- }
- lastIndex = index + 1;
- continue;
- }
- if (opts.noext !== true) {
- const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
- if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
- isGlob = token.isGlob = true;
- isExtglob = token.isExtglob = true;
- finished = true;
- if (code === CHAR_EXCLAMATION_MARK && index === start) {
- negatedExtglob = true;
- }
- if (scanToEnd === true) {
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- code = advance();
- continue;
- }
- if (code === CHAR_RIGHT_PARENTHESES) {
- isGlob = token.isGlob = true;
- finished = true;
- break;
- }
- }
- continue;
- }
- break;
- }
- }
- if (code === CHAR_ASTERISK) {
- if (prev === CHAR_ASTERISK)
- isGlobstar = token.isGlobstar = true;
- isGlob = token.isGlob = true;
- finished = true;
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- if (code === CHAR_QUESTION_MARK) {
- isGlob = token.isGlob = true;
- finished = true;
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- if (code === CHAR_LEFT_SQUARE_BRACKET) {
- while (eos() !== true && (next = advance())) {
- if (next === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- advance();
- continue;
- }
- if (next === CHAR_RIGHT_SQUARE_BRACKET) {
- isBracket = token.isBracket = true;
- isGlob = token.isGlob = true;
- finished = true;
- break;
- }
- }
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
- negated = token.negated = true;
- start++;
- continue;
- }
- if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
- isGlob = token.isGlob = true;
- if (scanToEnd === true) {
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_LEFT_PARENTHESES) {
- backslashes = token.backslashes = true;
- code = advance();
- continue;
- }
- if (code === CHAR_RIGHT_PARENTHESES) {
- finished = true;
- break;
- }
- }
- continue;
- }
- break;
- }
- if (isGlob === true) {
- finished = true;
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- }
- if (opts.noext === true) {
- isExtglob = false;
- isGlob = false;
- }
- let base = str;
- let prefix = "";
- let glob = "";
- if (start > 0) {
- prefix = str.slice(0, start);
- str = str.slice(start);
- lastIndex -= start;
- }
- if (base && isGlob === true && lastIndex > 0) {
- base = str.slice(0, lastIndex);
- glob = str.slice(lastIndex);
- } else if (isGlob === true) {
- base = "";
- glob = str;
- } else {
- base = str;
- }
- if (base && base !== "" && base !== "/" && base !== str) {
- if (isPathSeparator(base.charCodeAt(base.length - 1))) {
- base = base.slice(0, -1);
- }
- }
- if (opts.unescape === true) {
- if (glob)
- glob = utils.removeBackslashes(glob);
- if (base && backslashes === true) {
- base = utils.removeBackslashes(base);
- }
- }
- const state = {
- prefix,
- input,
- start,
- base,
- glob,
- isBrace,
- isBracket,
- isGlob,
- isExtglob,
- isGlobstar,
- negated,
- negatedExtglob
- };
- if (opts.tokens === true) {
- state.maxDepth = 0;
- if (!isPathSeparator(code)) {
- tokens.push(token);
- }
- state.tokens = tokens;
- }
- if (opts.parts === true || opts.tokens === true) {
- let prevIndex;
- for (let idx = 0;idx < slashes.length; idx++) {
- const n = prevIndex ? prevIndex + 1 : start;
- const i = slashes[idx];
- const value = input.slice(n, i);
- if (opts.tokens) {
- if (idx === 0 && start !== 0) {
- tokens[idx].isPrefix = true;
- tokens[idx].value = prefix;
- } else {
- tokens[idx].value = value;
- }
- depth(tokens[idx]);
- state.maxDepth += tokens[idx].depth;
- }
- if (idx !== 0 || value !== "") {
- parts.push(value);
- }
- prevIndex = i;
- }
- if (prevIndex && prevIndex + 1 < input.length) {
- const value = input.slice(prevIndex + 1);
- parts.push(value);
- if (opts.tokens) {
- tokens[tokens.length - 1].value = value;
- depth(tokens[tokens.length - 1]);
- state.maxDepth += tokens[tokens.length - 1].depth;
- }
- }
- state.slashes = slashes;
- state.parts = parts;
- }
- return state;
- };
- module.exports = scan;
-});
-
-// node_modules/picomatch/lib/parse.js
-var require_parse = __commonJS((exports, module) => {
- var constants = require_constants();
- var utils = require_utils();
- var {
- MAX_LENGTH,
- POSIX_REGEX_SOURCE,
- REGEX_NON_SPECIAL_CHARS,
- REGEX_SPECIAL_CHARS_BACKREF,
- REPLACEMENTS
- } = constants;
- var expandRange = (args, options2) => {
- if (typeof options2.expandRange === "function") {
- return options2.expandRange(...args, options2);
- }
- args.sort();
- const value = `[${args.join("-")}]`;
- try {
- new RegExp(value);
- } catch (ex) {
- return args.map((v) => utils.escapeRegex(v)).join("..");
- }
- return value;
- };
- var syntaxError = (type, char) => {
- return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
- };
- var splitTopLevel = (input) => {
- const parts = [];
- let bracket = 0;
- let paren = 0;
- let quote = 0;
- let value = "";
- let escaped = false;
- for (const ch of input) {
- if (escaped === true) {
- value += ch;
- escaped = false;
- continue;
- }
- if (ch === "\\") {
- value += ch;
- escaped = true;
- continue;
- }
- if (ch === '"') {
- quote = quote === 1 ? 0 : 1;
- value += ch;
- continue;
- }
- if (quote === 0) {
- if (ch === "[") {
- bracket++;
- } else if (ch === "]" && bracket > 0) {
- bracket--;
- } else if (bracket === 0) {
- if (ch === "(") {
- paren++;
- } else if (ch === ")" && paren > 0) {
- paren--;
- } else if (ch === "|" && paren === 0) {
- parts.push(value);
- value = "";
- continue;
- }
- }
- }
- value += ch;
- }
- parts.push(value);
- return parts;
- };
- var isPlainBranch = (branch) => {
- let escaped = false;
- for (const ch of branch) {
- if (escaped === true) {
- escaped = false;
- continue;
- }
- if (ch === "\\") {
- escaped = true;
- continue;
- }
- if (/[?*+@!()[\]{}]/.test(ch)) {
- return false;
- }
- }
- return true;
- };
- var normalizeSimpleBranch = (branch) => {
- let value = branch.trim();
- let changed = true;
- while (changed === true) {
- changed = false;
- if (/^@\([^\\()[\]{}|]+\)$/.test(value)) {
- value = value.slice(2, -1);
- changed = true;
- }
- }
- if (!isPlainBranch(value)) {
- return;
- }
- return value.replace(/\\(.)/g, "$1");
- };
- var hasRepeatedCharPrefixOverlap = (branches) => {
- const values = branches.map(normalizeSimpleBranch).filter(Boolean);
- for (let i = 0;i < values.length; i++) {
- for (let j = i + 1;j < values.length; j++) {
- const a = values[i];
- const b = values[j];
- const char = a[0];
- if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) {
- continue;
- }
- if (a === b || a.startsWith(b) || b.startsWith(a)) {
- return true;
- }
- }
- }
- return false;
- };
- var parseRepeatedExtglob = (pattern, requireEnd = true) => {
- if (pattern[0] !== "+" && pattern[0] !== "*" || pattern[1] !== "(") {
- return;
- }
- let bracket = 0;
- let paren = 0;
- let quote = 0;
- let escaped = false;
- for (let i = 1;i < pattern.length; i++) {
- const ch = pattern[i];
- if (escaped === true) {
- escaped = false;
- continue;
- }
- if (ch === "\\") {
- escaped = true;
- continue;
- }
- if (ch === '"') {
- quote = quote === 1 ? 0 : 1;
- continue;
- }
- if (quote === 1) {
- continue;
- }
- if (ch === "[") {
- bracket++;
- continue;
- }
- if (ch === "]" && bracket > 0) {
- bracket--;
- continue;
- }
- if (bracket > 0) {
- continue;
- }
- if (ch === "(") {
- paren++;
- continue;
- }
- if (ch === ")") {
- paren--;
- if (paren === 0) {
- if (requireEnd === true && i !== pattern.length - 1) {
- return;
- }
- return {
- type: pattern[0],
- body: pattern.slice(2, i),
- end: i
- };
- }
- }
- }
- };
- var getStarExtglobSequenceOutput = (pattern) => {
- let index = 0;
- const chars = [];
- while (index < pattern.length) {
- const match = parseRepeatedExtglob(pattern.slice(index), false);
- if (!match || match.type !== "*") {
- return;
- }
- const branches = splitTopLevel(match.body).map((branch2) => branch2.trim());
- if (branches.length !== 1) {
- return;
- }
- const branch = normalizeSimpleBranch(branches[0]);
- if (!branch || branch.length !== 1) {
- return;
- }
- chars.push(branch);
- index += match.end + 1;
- }
- if (chars.length < 1) {
- return;
- }
- const source = chars.length === 1 ? utils.escapeRegex(chars[0]) : `[${chars.map((ch) => utils.escapeRegex(ch)).join("")}]`;
- return `${source}*`;
- };
- var repeatedExtglobRecursion = (pattern) => {
- let depth = 0;
- let value = pattern.trim();
- let match = parseRepeatedExtglob(value);
- while (match) {
- depth++;
- value = match.body.trim();
- match = parseRepeatedExtglob(value);
- }
- return depth;
- };
- var analyzeRepeatedExtglob = (body, options2) => {
- if (options2.maxExtglobRecursion === false) {
- return { risky: false };
- }
- const max = typeof options2.maxExtglobRecursion === "number" ? options2.maxExtglobRecursion : constants.DEFAULT_MAX_EXTGLOB_RECURSION;
- const branches = splitTopLevel(body).map((branch) => branch.trim());
- if (branches.length > 1) {
- if (branches.some((branch) => branch === "") || branches.some((branch) => /^[*?]+$/.test(branch)) || hasRepeatedCharPrefixOverlap(branches)) {
- return { risky: true };
- }
- }
- for (const branch of branches) {
- const safeOutput = getStarExtglobSequenceOutput(branch);
- if (safeOutput) {
- return { risky: true, safeOutput };
- }
- if (repeatedExtglobRecursion(branch) > max) {
- return { risky: true };
- }
- }
- return { risky: false };
- };
- var parse = (input, options2) => {
- if (typeof input !== "string") {
- throw new TypeError("Expected a string");
- }
- input = REPLACEMENTS[input] || input;
- const opts = { ...options2 };
- const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
- let len = input.length;
- if (len > max) {
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
- }
- const bos = { type: "bos", value: "", output: opts.prepend || "" };
- const tokens = [bos];
- const capture = opts.capture ? "" : "?:";
- const PLATFORM_CHARS = constants.globChars(opts.windows);
- const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
- const {
- DOT_LITERAL,
- PLUS_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOT_SLASH,
- NO_DOTS_SLASH,
- QMARK,
- QMARK_NO_DOT,
- STAR,
- START_ANCHOR
- } = PLATFORM_CHARS;
- const globstar = (opts2) => {
- return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
- };
- const nodot = opts.dot ? "" : NO_DOT;
- const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
- let star = opts.bash === true ? globstar(opts) : STAR;
- if (opts.capture) {
- star = `(${star})`;
- }
- if (typeof opts.noext === "boolean") {
- opts.noextglob = opts.noext;
- }
- const state = {
- input,
- index: -1,
- start: 0,
- dot: opts.dot === true,
- consumed: "",
- output: "",
- prefix: "",
- backtrack: false,
- negated: false,
- brackets: 0,
- braces: 0,
- parens: 0,
- quotes: 0,
- globstar: false,
- tokens
- };
- input = utils.removePrefix(input, state);
- len = input.length;
- const extglobs = [];
- const braces = [];
- const stack = [];
- let prev = bos;
- let value;
- const eos = () => state.index === len - 1;
- const peek = state.peek = (n = 1) => input[state.index + n];
- const advance = state.advance = () => input[++state.index] || "";
- const remaining = () => input.slice(state.index + 1);
- const consume = (value2 = "", num = 0) => {
- state.consumed += value2;
- state.index += num;
- };
- const append = (token) => {
- state.output += token.output != null ? token.output : token.value;
- consume(token.value);
- };
- const negate = () => {
- let count = 1;
- while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
- advance();
- state.start++;
- count++;
- }
- if (count % 2 === 0) {
- return false;
- }
- state.negated = true;
- state.start++;
- return true;
- };
- const increment = (type) => {
- state[type]++;
- stack.push(type);
- };
- const decrement = (type) => {
- state[type]--;
- stack.pop();
- };
- const push = (tok) => {
- if (prev.type === "globstar") {
- const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
- const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
- if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
- state.output = state.output.slice(0, -prev.output.length);
- prev.type = "star";
- prev.value = "*";
- prev.output = star;
- state.output += prev.output;
- }
- }
- if (extglobs.length && tok.type !== "paren") {
- extglobs[extglobs.length - 1].inner += tok.value;
- }
- if (tok.value || tok.output)
- append(tok);
- if (prev && prev.type === "text" && tok.type === "text") {
- prev.output = (prev.output || prev.value) + tok.value;
- prev.value += tok.value;
- return;
- }
- tok.prev = prev;
- tokens.push(tok);
- prev = tok;
- };
- const extglobOpen = (type, value2) => {
- const token = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" };
- token.prev = prev;
- token.parens = state.parens;
- token.output = state.output;
- token.startIndex = state.index;
- token.tokensIndex = tokens.length;
- const output = (opts.capture ? "(" : "") + token.open;
- increment("parens");
- push({ type, value: value2, output: state.output ? "" : ONE_CHAR });
- push({ type: "paren", extglob: true, value: advance(), output });
- extglobs.push(token);
- };
- const extglobClose = (token) => {
- const literal = input.slice(token.startIndex, state.index + 1);
- const body = input.slice(token.startIndex + 2, state.index);
- const analysis = analyzeRepeatedExtglob(body, opts);
- if ((token.type === "plus" || token.type === "star") && analysis.risky) {
- const safeOutput = analysis.safeOutput ? (token.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : undefined;
- const open2 = tokens[token.tokensIndex];
- open2.type = "text";
- open2.value = literal;
- open2.output = safeOutput || utils.escapeRegex(literal);
- for (let i = token.tokensIndex + 1;i < tokens.length; i++) {
- tokens[i].value = "";
- tokens[i].output = "";
- delete tokens[i].suffix;
- }
- state.output = token.output + open2.output;
- state.backtrack = true;
- push({ type: "paren", extglob: true, value, output: "" });
- decrement("parens");
- return;
- }
- let output = token.close + (opts.capture ? ")" : "");
- let rest;
- if (token.type === "negate") {
- let extglobStar = star;
- if (token.inner && token.inner.length > 1 && token.inner.includes("/")) {
- extglobStar = globstar(opts);
- }
- if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
- output = token.close = `)$))${extglobStar}`;
- }
- if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
- const expression = parse(rest, { ...options2, fastpaths: false }).output;
- output = token.close = `)${expression})${extglobStar})`;
- }
- if (token.prev.type === "bos") {
- state.negatedExtglob = true;
- }
- }
- push({ type: "paren", extglob: true, value, output });
- decrement("parens");
- };
- if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
- let backslashes = false;
- let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
- if (first === "\\") {
- backslashes = true;
- return m;
- }
- if (first === "?") {
- if (esc) {
- return esc + first + (rest ? QMARK.repeat(rest.length) : "");
- }
- if (index === 0) {
- return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : "");
- }
- return QMARK.repeat(chars.length);
- }
- if (first === ".") {
- return DOT_LITERAL.repeat(chars.length);
- }
- if (first === "*") {
- if (esc) {
- return esc + first + (rest ? star : "");
- }
- return star;
- }
- return esc ? m : `\\${m}`;
- });
- if (backslashes === true) {
- if (opts.unescape === true) {
- output = output.replace(/\\/g, "");
- } else {
- output = output.replace(/\\+/g, (m) => {
- return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
- });
- }
- }
- if (output === input && opts.contains === true) {
- state.output = input;
- return state;
- }
- state.output = utils.wrapOutput(output, state, options2);
- return state;
- }
- while (!eos()) {
- value = advance();
- if (value === "\x00") {
- continue;
- }
- if (value === "\\") {
- const next = peek();
- if (next === "/" && opts.bash !== true) {
- continue;
- }
- if (next === "." || next === ";") {
- continue;
- }
- if (!next) {
- value += "\\";
- push({ type: "text", value });
- continue;
- }
- const match = /^\\+/.exec(remaining());
- let slashes = 0;
- if (match && match[0].length > 2) {
- slashes = match[0].length;
- state.index += slashes;
- if (slashes % 2 !== 0) {
- value += "\\";
- }
- }
- if (opts.unescape === true) {
- value = advance();
- } else {
- value += advance();
- }
- if (state.brackets === 0) {
- push({ type: "text", value });
- continue;
- }
- }
- if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
- if (opts.posix !== false && value === ":") {
- const inner = prev.value.slice(1);
- if (inner.includes("[")) {
- prev.posix = true;
- if (inner.includes(":")) {
- const idx = prev.value.lastIndexOf("[");
- const pre = prev.value.slice(0, idx);
- const rest2 = prev.value.slice(idx + 2);
- const posix = POSIX_REGEX_SOURCE[rest2];
- if (posix) {
- prev.value = pre + posix;
- state.backtrack = true;
- advance();
- if (!bos.output && tokens.indexOf(prev) === 1) {
- bos.output = ONE_CHAR;
- }
- continue;
- }
- }
- }
- }
- if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") {
- value = `\\${value}`;
- }
- if (value === "]" && (prev.value === "[" || prev.value === "[^")) {
- value = `\\${value}`;
- }
- if (opts.posix === true && value === "!" && prev.value === "[") {
- value = "^";
- }
- prev.value += value;
- append({ value });
- continue;
- }
- if (state.quotes === 1 && value !== '"') {
- value = utils.escapeRegex(value);
- prev.value += value;
- append({ value });
- continue;
- }
- if (value === '"') {
- state.quotes = state.quotes === 1 ? 0 : 1;
- if (opts.keepQuotes === true) {
- push({ type: "text", value });
- }
- continue;
- }
- if (value === "(") {
- increment("parens");
- push({ type: "paren", value });
- continue;
- }
- if (value === ")") {
- if (state.parens === 0 && opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError("opening", "("));
- }
- const extglob = extglobs[extglobs.length - 1];
- if (extglob && state.parens === extglob.parens + 1) {
- extglobClose(extglobs.pop());
- continue;
- }
- push({ type: "paren", value, output: state.parens ? ")" : "\\)" });
- decrement("parens");
- continue;
- }
- if (value === "[") {
- if (opts.nobracket === true || !remaining().includes("]")) {
- if (opts.nobracket !== true && opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError("closing", "]"));
- }
- value = `\\${value}`;
- } else {
- increment("brackets");
- }
- push({ type: "bracket", value });
- continue;
- }
- if (value === "]") {
- if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
- push({ type: "text", value, output: `\\${value}` });
- continue;
- }
- if (state.brackets === 0) {
- if (opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError("opening", "["));
- }
- push({ type: "text", value, output: `\\${value}` });
- continue;
- }
- decrement("brackets");
- const prevValue = prev.value.slice(1);
- if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) {
- value = `/${value}`;
- }
- prev.value += value;
- append({ value });
- if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
- continue;
- }
- const escaped = utils.escapeRegex(prev.value);
- state.output = state.output.slice(0, -prev.value.length);
- if (opts.literalBrackets === true) {
- state.output += escaped;
- prev.value = escaped;
- continue;
- }
- prev.value = `(${capture}${escaped}|${prev.value})`;
- state.output += prev.value;
- continue;
- }
- if (value === "{" && opts.nobrace !== true) {
- increment("braces");
- const open2 = {
- type: "brace",
- value,
- output: "(",
- outputIndex: state.output.length,
- tokensIndex: state.tokens.length
- };
- braces.push(open2);
- push(open2);
- continue;
- }
- if (value === "}") {
- const brace = braces[braces.length - 1];
- if (opts.nobrace === true || !brace) {
- push({ type: "text", value, output: value });
- continue;
- }
- let output = ")";
- if (brace.dots === true) {
- const arr = tokens.slice();
- const range = [];
- for (let i = arr.length - 1;i >= 0; i--) {
- tokens.pop();
- if (arr[i].type === "brace") {
- break;
- }
- if (arr[i].type !== "dots") {
- range.unshift(arr[i].value);
- }
- }
- output = expandRange(range, opts);
- state.backtrack = true;
- }
- if (brace.comma !== true && brace.dots !== true) {
- const out = state.output.slice(0, brace.outputIndex);
- const toks = state.tokens.slice(brace.tokensIndex);
- brace.value = brace.output = "\\{";
- value = output = "\\}";
- state.output = out;
- for (const t of toks) {
- state.output += t.output || t.value;
- }
- }
- push({ type: "brace", value, output });
- decrement("braces");
- braces.pop();
- continue;
- }
- if (value === "|") {
- if (extglobs.length > 0) {
- extglobs[extglobs.length - 1].conditions++;
- }
- push({ type: "text", value });
- continue;
- }
- if (value === ",") {
- let output = value;
- const brace = braces[braces.length - 1];
- if (brace && stack[stack.length - 1] === "braces") {
- brace.comma = true;
- output = "|";
- }
- push({ type: "comma", value, output });
- continue;
- }
- if (value === "/") {
- if (prev.type === "dot" && state.index === state.start + 1) {
- state.start = state.index + 1;
- state.consumed = "";
- state.output = "";
- tokens.pop();
- prev = bos;
- continue;
- }
- push({ type: "slash", value, output: SLASH_LITERAL });
- continue;
- }
- if (value === ".") {
- if (state.braces > 0 && prev.type === "dot") {
- if (prev.value === ".")
- prev.output = DOT_LITERAL;
- const brace = braces[braces.length - 1];
- prev.type = "dots";
- prev.output += value;
- prev.value += value;
- brace.dots = true;
- continue;
- }
- if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
- push({ type: "text", value, output: DOT_LITERAL });
- continue;
- }
- push({ type: "dot", value, output: DOT_LITERAL });
- continue;
- }
- if (value === "?") {
- const isGroup = prev && prev.value === "(";
- if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
- extglobOpen("qmark", value);
- continue;
- }
- if (prev && prev.type === "paren") {
- const next = peek();
- let output = value;
- if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) {
- output = `\\${value}`;
- }
- push({ type: "text", value, output });
- continue;
- }
- if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
- push({ type: "qmark", value, output: QMARK_NO_DOT });
- continue;
- }
- push({ type: "qmark", value, output: QMARK });
- continue;
- }
- if (value === "!") {
- if (opts.noextglob !== true && peek() === "(") {
- if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
- extglobOpen("negate", value);
- continue;
- }
- }
- if (opts.nonegate !== true && state.index === 0) {
- negate();
- continue;
- }
- }
- if (value === "+") {
- if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
- extglobOpen("plus", value);
- continue;
- }
- if (prev && prev.value === "(" || opts.regex === false) {
- push({ type: "plus", value, output: PLUS_LITERAL });
- continue;
- }
- if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
- push({ type: "plus", value });
- continue;
- }
- push({ type: "plus", value: PLUS_LITERAL });
- continue;
- }
- if (value === "@") {
- if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
- push({ type: "at", extglob: true, value, output: "" });
- continue;
- }
- push({ type: "text", value });
- continue;
- }
- if (value !== "*") {
- if (value === "$" || value === "^") {
- value = `\\${value}`;
- }
- const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
- if (match) {
- value += match[0];
- state.index += match[0].length;
- }
- push({ type: "text", value });
- continue;
- }
- if (prev && (prev.type === "globstar" || prev.star === true)) {
- prev.type = "star";
- prev.star = true;
- prev.value += value;
- prev.output = star;
- state.backtrack = true;
- state.globstar = true;
- consume(value);
- continue;
- }
- let rest = remaining();
- if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
- extglobOpen("star", value);
- continue;
- }
- if (prev.type === "star") {
- if (opts.noglobstar === true) {
- consume(value);
- continue;
- }
- const prior = prev.prev;
- const before = prior.prev;
- const isStart = prior.type === "slash" || prior.type === "bos";
- const afterStar = before && (before.type === "star" || before.type === "globstar");
- if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
- push({ type: "star", value, output: "" });
- continue;
- }
- const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
- const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
- if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
- push({ type: "star", value, output: "" });
- continue;
- }
- while (rest.slice(0, 3) === "/**") {
- const after = input[state.index + 4];
- if (after && after !== "/") {
- break;
- }
- rest = rest.slice(3);
- consume("/**", 3);
- }
- if (prior.type === "bos" && eos()) {
- prev.type = "globstar";
- prev.value += value;
- prev.output = globstar(opts);
- state.output = prev.output;
- state.globstar = true;
- consume(value);
- continue;
- }
- if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
- prior.output = `(?:${prior.output}`;
- prev.type = "globstar";
- prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
- prev.value += value;
- state.globstar = true;
- state.output += prior.output + prev.output;
- consume(value);
- continue;
- }
- if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
- const end = rest[1] !== undefined ? "|$" : "";
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
- prior.output = `(?:${prior.output}`;
- prev.type = "globstar";
- prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
- prev.value += value;
- state.output += prior.output + prev.output;
- state.globstar = true;
- consume(value + advance());
- push({ type: "slash", value: "/", output: "" });
- continue;
- }
- if (prior.type === "bos" && rest[0] === "/") {
- prev.type = "globstar";
- prev.value += value;
- prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
- state.output = prev.output;
- state.globstar = true;
- consume(value + advance());
- push({ type: "slash", value: "/", output: "" });
- continue;
- }
- state.output = state.output.slice(0, -prev.output.length);
- prev.type = "globstar";
- prev.output = globstar(opts);
- prev.value += value;
- state.output += prev.output;
- state.globstar = true;
- consume(value);
- continue;
- }
- const token = { type: "star", value, output: star };
- if (opts.bash === true) {
- token.output = ".*?";
- if (prev.type === "bos" || prev.type === "slash") {
- token.output = nodot + token.output;
- }
- push(token);
- continue;
- }
- if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
- token.output = value;
- push(token);
- continue;
- }
- if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
- if (prev.type === "dot") {
- state.output += NO_DOT_SLASH;
- prev.output += NO_DOT_SLASH;
- } else if (opts.dot === true) {
- state.output += NO_DOTS_SLASH;
- prev.output += NO_DOTS_SLASH;
- } else {
- state.output += nodot;
- prev.output += nodot;
- }
- if (peek() !== "*") {
- state.output += ONE_CHAR;
- prev.output += ONE_CHAR;
- }
- }
- push(token);
- }
- while (state.brackets > 0) {
- if (opts.strictBrackets === true)
- throw new SyntaxError(syntaxError("closing", "]"));
- state.output = utils.escapeLast(state.output, "[");
- decrement("brackets");
- }
- while (state.parens > 0) {
- if (opts.strictBrackets === true)
- throw new SyntaxError(syntaxError("closing", ")"));
- state.output = utils.escapeLast(state.output, "(");
- decrement("parens");
- }
- while (state.braces > 0) {
- if (opts.strictBrackets === true)
- throw new SyntaxError(syntaxError("closing", "}"));
- state.output = utils.escapeLast(state.output, "{");
- decrement("braces");
- }
- if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) {
- push({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` });
- }
- if (state.backtrack === true) {
- state.output = "";
- for (const token of state.tokens) {
- state.output += token.output != null ? token.output : token.value;
- if (token.suffix) {
- state.output += token.suffix;
- }
- }
- }
- return state;
- };
- parse.fastpaths = (input, options2) => {
- const opts = { ...options2 };
- const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
- const len = input.length;
- if (len > max) {
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
- }
- input = REPLACEMENTS[input] || input;
- const {
- DOT_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOTS,
- NO_DOTS_SLASH,
- STAR,
- START_ANCHOR
- } = constants.globChars(opts.windows);
- const nodot = opts.dot ? NO_DOTS : NO_DOT;
- const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
- const capture = opts.capture ? "" : "?:";
- const state = { negated: false, prefix: "" };
- let star = opts.bash === true ? ".*?" : STAR;
- if (opts.capture) {
- star = `(${star})`;
- }
- const globstar = (opts2) => {
- if (opts2.noglobstar === true)
- return star;
- return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
- };
- const create = (str) => {
- switch (str) {
- case "*":
- return `${nodot}${ONE_CHAR}${star}`;
- case ".*":
- return `${DOT_LITERAL}${ONE_CHAR}${star}`;
- case "*.*":
- return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
- case "*/*":
- return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
- case "**":
- return nodot + globstar(opts);
- case "**/*":
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
- case "**/*.*":
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
- case "**/.*":
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
- default: {
- const match = /^(.*?)\.(\w+)$/.exec(str);
- if (!match)
- return;
- const source2 = create(match[1]);
- if (!source2)
- return;
- return source2 + DOT_LITERAL + match[2];
- }
- }
- };
- const output = utils.removePrefix(input, state);
- let source = create(output);
- if (source && opts.strictSlashes !== true) {
- source += `${SLASH_LITERAL}?`;
- }
- return source;
- };
- module.exports = parse;
-});
-
-// node_modules/picomatch/lib/picomatch.js
-var require_picomatch = __commonJS((exports, module) => {
- var scan = require_scan();
- var parse = require_parse();
- var utils = require_utils();
- var constants = require_constants();
- var isObject2 = (val) => val && typeof val === "object" && !Array.isArray(val);
- var picomatch = (glob, options2, returnState = false) => {
- if (Array.isArray(glob)) {
- const fns = glob.map((input) => picomatch(input, options2, returnState));
- const arrayMatcher = (str) => {
- for (const isMatch of fns) {
- const state2 = isMatch(str);
- if (state2)
- return state2;
- }
- return false;
- };
- return arrayMatcher;
- }
- const isState = isObject2(glob) && glob.tokens && glob.input;
- if (glob === "" || typeof glob !== "string" && !isState) {
- throw new TypeError("Expected pattern to be a non-empty string");
- }
- const opts = options2 || {};
- const posix = opts.windows;
- const regex2 = isState ? picomatch.compileRe(glob, options2) : picomatch.makeRe(glob, options2, false, true);
- const state = regex2.state;
- delete regex2.state;
- let isIgnored = () => false;
- if (opts.ignore) {
- const ignoreOpts = { ...options2, ignore: null, onMatch: null, onResult: null };
- isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
- }
- const matcher = (input, returnObject = false) => {
- const { isMatch, match, output } = picomatch.test(input, regex2, options2, { glob, posix });
- const result = { glob, state, regex: regex2, posix, input, output, match, isMatch };
- if (typeof opts.onResult === "function") {
- opts.onResult(result);
- }
- if (isMatch === false) {
- result.isMatch = false;
- return returnObject ? result : false;
- }
- if (isIgnored(input)) {
- if (typeof opts.onIgnore === "function") {
- opts.onIgnore(result);
- }
- result.isMatch = false;
- return returnObject ? result : false;
- }
- if (typeof opts.onMatch === "function") {
- opts.onMatch(result);
- }
- return returnObject ? result : true;
- };
- if (returnState) {
- matcher.state = state;
- }
- return matcher;
- };
- picomatch.test = (input, regex2, options2, { glob, posix } = {}) => {
- if (typeof input !== "string") {
- throw new TypeError("Expected input to be a string");
- }
- if (input === "") {
- return { isMatch: false, output: "" };
- }
- const opts = options2 || {};
- const format = opts.format || (posix ? utils.toPosixSlashes : null);
- let match = input === glob;
- let output = match && format ? format(input) : input;
- if (match === false) {
- output = format ? format(input) : input;
- match = output === glob;
- }
- if (match === false || opts.capture === true) {
- if (opts.matchBase === true || opts.basename === true) {
- match = picomatch.matchBase(input, regex2, options2, posix);
- } else {
- match = regex2.exec(output);
- }
- }
- return { isMatch: Boolean(match), match, output };
- };
- picomatch.matchBase = (input, glob, options2) => {
- const regex2 = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options2);
- return regex2.test(utils.basename(input));
- };
- picomatch.isMatch = (str, patterns, options2) => picomatch(patterns, options2)(str);
- picomatch.parse = (pattern, options2) => {
- if (Array.isArray(pattern))
- return pattern.map((p) => picomatch.parse(p, options2));
- return parse(pattern, { ...options2, fastpaths: false });
- };
- picomatch.scan = (input, options2) => scan(input, options2);
- picomatch.compileRe = (state, options2, returnOutput = false, returnState = false) => {
- if (returnOutput === true) {
- return state.output;
- }
- const opts = options2 || {};
- const prepend = opts.contains ? "" : "^";
- const append = opts.contains ? "" : "$";
- let source = `${prepend}(?:${state.output})${append}`;
- if (state && state.negated === true) {
- source = `^(?!${source}).*$`;
- }
- const regex2 = picomatch.toRegex(source, options2);
- if (returnState === true) {
- regex2.state = state;
- }
- return regex2;
- };
- picomatch.makeRe = (input, options2 = {}, returnOutput = false, returnState = false) => {
- if (!input || typeof input !== "string") {
- throw new TypeError("Expected a non-empty string");
- }
- let parsed = { negated: false, fastpaths: true };
- if (options2.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
- parsed.output = parse.fastpaths(input, options2);
- }
- if (!parsed.output) {
- parsed = parse(input, options2);
- }
- return picomatch.compileRe(parsed, options2, returnOutput, returnState);
- };
- picomatch.toRegex = (source, options2) => {
- try {
- const opts = options2 || {};
- return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
- } catch (err) {
- if (options2 && options2.debug === true)
- throw err;
- return /$^/;
- }
- };
- picomatch.constants = constants;
- module.exports = picomatch;
-});
-
-// node_modules/picomatch/index.js
-var require_picomatch2 = __commonJS((exports, module) => {
- var pico = require_picomatch();
- var utils = require_utils();
- function picomatch(glob, options2, returnState = false) {
- if (options2 && (options2.windows === null || options2.windows === undefined)) {
- options2 = { ...options2, windows: utils.isWindows() };
- }
- return pico(glob, options2, returnState);
- }
- Object.assign(picomatch, pico);
- module.exports = picomatch;
-});
-
-// node_modules/dom-mutator/dist/dom-mutator.esm.js
-function getObserverInit(attr) {
- return attr === "html" ? {
- childList: true,
- subtree: true,
- attributes: true,
- characterData: true
- } : {
- childList: false,
- subtree: false,
- attributes: true,
- attributeFilter: [attr]
- };
-}
-function getElementRecord(element) {
- var record = elements.get(element);
- if (!record) {
- record = {
- element,
- attributes: {}
- };
- elements.set(element, record);
- }
- return record;
-}
-function createElementPropertyRecord(el, attr, getCurrentValue, setValue, mutationRunner) {
- var currentValue = getCurrentValue(el);
- var record = {
- isDirty: false,
- originalValue: currentValue,
- virtualValue: currentValue,
- mutations: [],
- el,
- _positionTimeout: null,
- observer: new MutationObserver(function() {
- if (attr === "position" && record._positionTimeout)
- return;
- else if (attr === "position")
- record._positionTimeout = setTimeout(function() {
- record._positionTimeout = null;
- }, 1000);
- var currentValue2 = getCurrentValue(el);
- if (attr === "position" && currentValue2.parentNode === record.virtualValue.parentNode && currentValue2.insertBeforeNode === record.virtualValue.insertBeforeNode)
- return;
- if (currentValue2 === record.virtualValue)
- return;
- record.originalValue = currentValue2;
- mutationRunner(record);
- }),
- mutationRunner,
- setValue,
- getCurrentValue
- };
- if (attr === "position" && el.parentNode) {
- record.observer.observe(el.parentNode, {
- childList: true,
- subtree: true,
- attributes: false,
- characterData: false
- });
- } else {
- record.observer.observe(el, getObserverInit(attr));
- }
- return record;
-}
-function queueIfNeeded(val, record) {
- var currentVal = record.getCurrentValue(record.el);
- record.virtualValue = val;
- if (val && typeof val !== "string") {
- if (!currentVal || val.parentNode !== currentVal.parentNode || val.insertBeforeNode !== currentVal.insertBeforeNode) {
- record.isDirty = true;
- runDOMUpdates();
- }
- } else if (val !== currentVal) {
- record.isDirty = true;
- runDOMUpdates();
- }
-}
-function htmlMutationRunner(record) {
- var val = record.originalValue;
- record.mutations.forEach(function(m) {
- return val = m.mutate(val);
- });
- queueIfNeeded(getTransformedHTML(val), record);
-}
-function classMutationRunner(record) {
- var val = new Set(record.originalValue.split(/\s+/).filter(Boolean));
- record.mutations.forEach(function(m) {
- return m.mutate(val);
- });
- queueIfNeeded(Array.from(val).filter(Boolean).join(" "), record);
-}
-function attrMutationRunner(record) {
- var val = record.originalValue;
- record.mutations.forEach(function(m) {
- return val = m.mutate(val);
- });
- queueIfNeeded(val, record);
-}
-function _loadDOMNodes(_ref) {
- var { parentSelector, insertBeforeSelector } = _ref;
- var parentNode = document.querySelector(parentSelector);
- if (!parentNode)
- return null;
- var insertBeforeNode = insertBeforeSelector ? document.querySelector(insertBeforeSelector) : null;
- if (insertBeforeSelector && !insertBeforeNode)
- return null;
- return {
- parentNode,
- insertBeforeNode
- };
-}
-function positionMutationRunner(record) {
- var val = record.originalValue;
- record.mutations.forEach(function(m) {
- var selectors = m.mutate();
- var newNodes = _loadDOMNodes(selectors);
- val = newNodes || val;
- });
- queueIfNeeded(val, record);
-}
-function getElementHTMLRecord(element) {
- var elementRecord = getElementRecord(element);
- if (!elementRecord.html) {
- elementRecord.html = createElementPropertyRecord(element, "html", getHTMLValue, setHTMLValue, htmlMutationRunner);
- }
- return elementRecord.html;
-}
-function getElementPositionRecord(element) {
- var elementRecord = getElementRecord(element);
- if (!elementRecord.position) {
- elementRecord.position = createElementPropertyRecord(element, "position", getElementPosition, setElementPosition, positionMutationRunner);
- }
- return elementRecord.position;
-}
-function getElementClassRecord(el) {
- var elementRecord = getElementRecord(el);
- if (!elementRecord.classes) {
- elementRecord.classes = createElementPropertyRecord(el, "class", getClassValue, setClassValue, classMutationRunner);
- }
- return elementRecord.classes;
-}
-function getElementAttributeRecord(el, attr) {
- var elementRecord = getElementRecord(el);
- if (!elementRecord.attributes[attr]) {
- elementRecord.attributes[attr] = createElementPropertyRecord(el, attr, getAttrValue(attr), setAttrValue(attr), attrMutationRunner);
- }
- return elementRecord.attributes[attr];
-}
-function deleteElementPropertyRecord(el, attr) {
- var element = elements.get(el);
- if (!element)
- return;
- if (attr === "html") {
- var _element$html, _element$html$observe;
- (_element$html = element.html) == null || (_element$html$observe = _element$html.observer) == null || _element$html$observe.disconnect();
- delete element.html;
- } else if (attr === "class") {
- var _element$classes, _element$classes$obse;
- (_element$classes = element.classes) == null || (_element$classes$obse = _element$classes.observer) == null || _element$classes$obse.disconnect();
- delete element.classes;
- } else if (attr === "position") {
- var _element$position, _element$position$obs;
- (_element$position = element.position) == null || (_element$position$obs = _element$position.observer) == null || _element$position$obs.disconnect();
- delete element.position;
- } else {
- var _element$attributes, _element$attributes$a, _element$attributes$a2;
- (_element$attributes = element.attributes) == null || (_element$attributes$a = _element$attributes[attr]) == null || (_element$attributes$a2 = _element$attributes$a.observer) == null || _element$attributes$a2.disconnect();
- delete element.attributes[attr];
- }
-}
-function getTransformedHTML(html2) {
- if (!transformContainer) {
- transformContainer = document.createElement("div");
- }
- transformContainer.innerHTML = html2;
- return transformContainer.innerHTML;
-}
-function setPropertyValue(el, attr, m) {
- if (!m.isDirty)
- return;
- m.isDirty = false;
- var val = m.virtualValue;
- if (!m.mutations.length) {
- deleteElementPropertyRecord(el, attr);
- }
- m.setValue(el, val);
-}
-function setValue(m, el) {
- m.html && setPropertyValue(el, "html", m.html);
- m.classes && setPropertyValue(el, "class", m.classes);
- m.position && setPropertyValue(el, "position", m.position);
- Object.keys(m.attributes).forEach(function(attr) {
- setPropertyValue(el, attr, m.attributes[attr]);
- });
-}
-function runDOMUpdates() {
- elements.forEach(setValue);
-}
-function startMutating(mutation, element) {
- var record = null;
- if (mutation.kind === "html") {
- record = getElementHTMLRecord(element);
- } else if (mutation.kind === "class") {
- record = getElementClassRecord(element);
- } else if (mutation.kind === "attribute") {
- record = getElementAttributeRecord(element, mutation.attribute);
- } else if (mutation.kind === "position") {
- record = getElementPositionRecord(element);
- }
- if (!record)
- return;
- record.mutations.push(mutation);
- record.mutationRunner(record);
-}
-function stopMutating(mutation, el) {
- var record = null;
- if (mutation.kind === "html") {
- record = getElementHTMLRecord(el);
- } else if (mutation.kind === "class") {
- record = getElementClassRecord(el);
- } else if (mutation.kind === "attribute") {
- record = getElementAttributeRecord(el, mutation.attribute);
- } else if (mutation.kind === "position") {
- record = getElementPositionRecord(el);
- }
- if (!record)
- return;
- var index = record.mutations.indexOf(mutation);
- if (index !== -1)
- record.mutations.splice(index, 1);
- record.mutationRunner(record);
-}
-function refreshElementsSet(mutation) {
- if (mutation.kind === "position" && mutation.elements.size === 1)
- return;
- var existingElements = new Set(mutation.elements);
- var matchingElements = document.querySelectorAll(mutation.selector);
- matchingElements.forEach(function(el) {
- if (!existingElements.has(el)) {
- mutation.elements.add(el);
- startMutating(mutation, el);
- }
- });
-}
-function revertMutation(mutation) {
- mutation.elements.forEach(function(el) {
- return stopMutating(mutation, el);
- });
- mutation.elements.clear();
- mutations["delete"](mutation);
-}
-function refreshAllElementSets() {
- mutations.forEach(refreshElementsSet);
-}
-function connectGlobalObserver() {
- if (typeof document === "undefined")
- return;
- if (!observer) {
- observer = new MutationObserver(function() {
- refreshAllElementSets();
- });
- }
- refreshAllElementSets();
- observer.observe(document.documentElement, {
- childList: true,
- subtree: true,
- attributes: false,
- characterData: false
- });
-}
-function newMutation(m) {
- if (typeof document === "undefined")
- return nullController;
- mutations.add(m);
- refreshElementsSet(m);
- return {
- revert: function revert2() {
- revertMutation(m);
- }
- };
-}
-function html2(selector, mutate) {
- return newMutation({
- kind: "html",
- elements: new Set,
- mutate,
- selector
- });
-}
-function position(selector, mutate) {
- return newMutation({
- kind: "position",
- elements: new Set,
- mutate,
- selector
- });
-}
-function classes(selector, mutate) {
- return newMutation({
- kind: "class",
- elements: new Set,
- mutate,
- selector
- });
-}
-function attribute(selector, attribute2, mutate) {
- if (!validAttributeName.test(attribute2))
- return nullController;
- if (attribute2 === "class" || attribute2 === "className") {
- return classes(selector, function(classnames) {
- var mutatedClassnames = mutate(Array.from(classnames).join(" "));
- classnames.clear();
- if (!mutatedClassnames)
- return;
- mutatedClassnames.split(/\s+/g).filter(Boolean).forEach(function(c) {
- return classnames.add(c);
- });
- });
- }
- return newMutation({
- kind: "attribute",
- attribute: attribute2,
- elements: new Set,
- mutate,
- selector
- });
-}
-function declarative(_ref2) {
- var { selector, action, value, attribute: attr, parentSelector, insertBeforeSelector } = _ref2;
- if (attr === "html") {
- if (action === "append") {
- return html2(selector, function(val) {
- return val + (value != null ? value : "");
- });
- } else if (action === "set") {
- return html2(selector, function() {
- return value != null ? value : "";
- });
- }
- } else if (attr === "class") {
- if (action === "append") {
- return classes(selector, function(val) {
- if (value)
- val.add(value);
- });
- } else if (action === "remove") {
- return classes(selector, function(val) {
- if (value)
- val["delete"](value);
- });
- } else if (action === "set") {
- return classes(selector, function(val) {
- val.clear();
- if (value)
- val.add(value);
- });
- }
- } else if (attr === "position") {
- if (action === "set" && parentSelector) {
- return position(selector, function() {
- return {
- insertBeforeSelector,
- parentSelector
- };
- });
- }
- } else {
- if (action === "append") {
- return attribute(selector, attr, function(val) {
- return val !== null ? val + (value != null ? value : "") : value != null ? value : "";
- });
- } else if (action === "set") {
- return attribute(selector, attr, function() {
- return value != null ? value : "";
- });
- } else if (action === "remove") {
- return attribute(selector, attr, function() {
- return null;
- });
- }
- }
- return nullController;
-}
-var validAttributeName, nullController, elements, mutations, getHTMLValue = function getHTMLValue2(el) {
- return el.innerHTML;
-}, setHTMLValue = function setHTMLValue2(el, value) {
- return el.innerHTML = value;
-}, getElementPosition = function getElementPosition2(el) {
- return {
- parentNode: el.parentElement,
- insertBeforeNode: el.nextElementSibling
- };
-}, setElementPosition = function setElementPosition2(el, value) {
- if (value.insertBeforeNode && !value.parentNode.contains(value.insertBeforeNode)) {
- return;
- }
- value.parentNode.insertBefore(el, value.insertBeforeNode);
-}, setClassValue = function setClassValue2(el, val) {
- return val ? el.className = val : el.removeAttribute("class");
-}, getClassValue = function getClassValue2(el) {
- return el.className;
-}, getAttrValue = function getAttrValue2(attrName) {
- return function(el) {
- var _el$getAttribute;
- return (_el$getAttribute = el.getAttribute(attrName)) != null ? _el$getAttribute : null;
- };
-}, setAttrValue = function setAttrValue2(attrName) {
- return function(el, val) {
- return val !== null ? el.setAttribute(attrName, val) : el.removeAttribute(attrName);
- };
-}, transformContainer, observer, index, dom_mutator_esm_default;
-var init_dom_mutator_esm = __esm(() => {
- validAttributeName = /^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/;
- nullController = {
- revert: function revert() {}
- };
- elements = /* @__PURE__ */ new Map;
- mutations = /* @__PURE__ */ new Set;
- connectGlobalObserver();
- index = {
- html: html2,
- classes,
- attribute,
- position,
- declarative
- };
- dom_mutator_esm_default = index;
-});
-
-// node_modules/@growthbook/growthbook/dist/esm/util.mjs
-function getPolyfills() {
- return polyfills;
-}
-function hashFnv32a(str) {
- let hval = 2166136261;
- const l = str.length;
- for (let i = 0;i < l; i++) {
- hval ^= str.charCodeAt(i);
- hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
- }
- return hval >>> 0;
-}
-function hash(seed, value, version) {
- if (version === 2) {
- return hashFnv32a(hashFnv32a(seed + value) + "") % 1e4 / 1e4;
- }
- if (version === 1) {
- return hashFnv32a(value + seed) % 1000 / 1000;
- }
- return null;
-}
-function getEqualWeights(n) {
- if (n <= 0)
- return [];
- return new Array(n).fill(1 / n);
-}
-function inRange(n, range) {
- return n >= range[0] && n < range[1];
-}
-function inNamespace(hashValue, namespace) {
- const n = hash("__" + namespace[0], hashValue, 1);
- if (n === null)
- return false;
- return n >= namespace[1] && n < namespace[2];
-}
-function chooseVariation(n, ranges) {
- for (let i = 0;i < ranges.length; i++) {
- if (inRange(n, ranges[i])) {
- return i;
- }
- }
- return -1;
-}
-function getUrlRegExp(regexString) {
- try {
- const escaped = regexString.replace(/([^\\])\//g, "$1\\/");
- return new RegExp(escaped);
- } catch (e) {
- console.error(e);
- return;
- }
-}
-function isURLTargeted(url, targets) {
- if (!targets.length)
- return false;
- let hasIncludeRules = false;
- let isIncluded = false;
- for (let i = 0;i < targets.length; i++) {
- const match = _evalURLTarget(url, targets[i].type, targets[i].pattern);
- if (targets[i].include === false) {
- if (match)
- return false;
- } else {
- hasIncludeRules = true;
- if (match)
- isIncluded = true;
- }
- }
- return isIncluded || !hasIncludeRules;
-}
-function _evalSimpleUrlPart(actual, pattern, isPath) {
- try {
- let escaped = pattern.replace(/[*.+?^${}()|[\]\\]/g, "\\$&").replace(/_____/g, ".*");
- if (isPath) {
- escaped = "\\/?" + escaped.replace(/(^\/|\/$)/g, "") + "\\/?";
- }
- const regex2 = new RegExp("^" + escaped + "$", "i");
- return regex2.test(actual);
- } catch (e) {
- return false;
- }
-}
-function _evalSimpleUrlTarget(actual, pattern) {
- try {
- const expected = new URL(pattern.replace(/^([^:/?]*)\./i, "https://$1.").replace(/\*/g, "_____"), "https://_____");
- const comps = [[actual.host, expected.host, false], [actual.pathname, expected.pathname, true]];
- if (expected.hash) {
- comps.push([actual.hash, expected.hash, false]);
- }
- expected.searchParams.forEach((v, k) => {
- comps.push([actual.searchParams.get(k) || "", v, false]);
- });
- return !comps.some((data) => !_evalSimpleUrlPart(data[0], data[1], data[2]));
- } catch (e) {
- return false;
- }
-}
-function _evalURLTarget(url, type, pattern) {
- try {
- const parsed = new URL(url, "https://_");
- if (type === "regex") {
- const regex2 = getUrlRegExp(pattern);
- if (!regex2)
- return false;
- return regex2.test(parsed.href) || regex2.test(parsed.href.substring(parsed.origin.length));
- } else if (type === "simple") {
- return _evalSimpleUrlTarget(parsed, pattern);
- }
- return false;
- } catch (e) {
- return false;
- }
-}
-function getBucketRanges(numVariations, coverage, weights) {
- coverage = coverage === undefined ? 1 : coverage;
- if (coverage < 0) {
- if (true) {
- console.error("Experiment.coverage must be greater than or equal to 0");
- }
- coverage = 0;
- } else if (coverage > 1) {
- if (true) {
- console.error("Experiment.coverage must be less than or equal to 1");
- }
- coverage = 1;
- }
- const equal = getEqualWeights(numVariations);
- weights = weights || equal;
- if (weights.length !== numVariations) {
- if (true) {
- console.error("Experiment.weights array must be the same length as Experiment.variations");
- }
- weights = equal;
- }
- const totalWeight = weights.reduce((w, sum) => sum + w, 0);
- if (totalWeight < 0.99 || totalWeight > 1.01) {
- if (true) {
- console.error("Experiment.weights must add up to 1");
- }
- weights = equal;
- }
- let cumulative = 0;
- return weights.map((w) => {
- const start = cumulative;
- cumulative += w;
- return [start, start + coverage * w];
- });
-}
-function getQueryStringOverride(id, url, numVariations) {
- if (!url) {
- return null;
- }
- const search = url.split("?")[1];
- if (!search) {
- return null;
- }
- const match = search.replace(/#.*/, "").split("&").map((kv) => kv.split("=", 2)).filter(([k]) => k === id).map(([, v]) => parseInt(v));
- if (match.length > 0 && match[0] >= 0 && match[0] < numVariations)
- return match[0];
- return null;
-}
-function isIncluded(include) {
- try {
- return include();
- } catch (e) {
- console.error(e);
- return false;
- }
-}
-async function decrypt(encryptedString, decryptionKey, subtle) {
- decryptionKey = decryptionKey || "";
- subtle = subtle || globalThis.crypto && globalThis.crypto.subtle || polyfills.SubtleCrypto;
- if (!subtle) {
- throw new Error("No SubtleCrypto implementation found");
- }
- try {
- const key = await subtle.importKey("raw", base64ToBuf(decryptionKey), {
- name: "AES-CBC",
- length: 128
- }, true, ["encrypt", "decrypt"]);
- const [iv, cipherText] = encryptedString.split(".");
- const plainTextBuffer = await subtle.decrypt({
- name: "AES-CBC",
- iv: base64ToBuf(iv)
- }, key, base64ToBuf(cipherText));
- return new TextDecoder().decode(plainTextBuffer);
- } catch (e) {
- throw new Error("Failed to decrypt");
- }
-}
-function toString2(input) {
- if (typeof input === "string")
- return input;
- return JSON.stringify(input);
-}
-function paddedVersionString(input) {
- if (typeof input === "number") {
- input = input + "";
- }
- if (!input || typeof input !== "string") {
- input = "0";
- }
- const parts = input.replace(/(^v|\+.*$)/g, "").split(/[-.]/);
- if (parts.length === 3) {
- parts.push("~");
- }
- return parts.map((v) => v.match(/^[0-9]+$/) ? v.padStart(5, " ") : v).join("-");
-}
-function loadSDKVersion() {
- let version;
- try {
- version = "1.6.5";
- } catch (e) {
- version = "";
- }
- return version;
-}
-function mergeQueryStrings(oldUrl, newUrl) {
- let currUrl;
- let redirectUrl;
- try {
- currUrl = new URL(oldUrl);
- redirectUrl = new URL(newUrl);
- } catch (e) {
- console.error(`Unable to merge query strings: ${e}`);
- return newUrl;
- }
- currUrl.searchParams.forEach((value, key) => {
- if (redirectUrl.searchParams.has(key)) {
- return;
- }
- redirectUrl.searchParams.set(key, value);
- });
- return redirectUrl.toString();
-}
-function isObj(x) {
- return typeof x === "object" && x !== null;
-}
-function getAutoExperimentChangeType(exp) {
- if (exp.urlPatterns && exp.variations.some((variation) => isObj(variation) && ("urlRedirect" in variation))) {
- return "redirect";
- } else if (exp.variations.some((variation) => isObj(variation) && (variation.domMutations || ("js" in variation) || ("css" in variation)))) {
- return "visual";
- }
- return "unknown";
-}
-async function promiseTimeout(promise, timeout) {
- return new Promise((resolve2) => {
- let resolved = false;
- let timer;
- const finish = (data) => {
- if (resolved)
- return;
- resolved = true;
- timer && clearTimeout(timer);
- resolve2(data || null);
- };
- if (timeout) {
- timer = setTimeout(() => finish(), timeout);
- }
- promise.then((data) => finish(data)).catch(() => finish());
- });
-}
-var polyfills, base64ToBuf = (b) => Uint8Array.from(atob(b), (c) => c.charCodeAt(0));
-var init_util = __esm(() => {
- polyfills = {
- fetch: globalThis.fetch ? globalThis.fetch.bind(globalThis) : undefined,
- SubtleCrypto: globalThis.crypto ? globalThis.crypto.subtle : undefined,
- EventSource: globalThis.EventSource
- };
-});
-
-// node_modules/@growthbook/growthbook/dist/esm/feature-repository.mjs
-function configureCache(overrides) {
- Object.assign(cacheSettings, overrides);
- if (!cacheSettings.backgroundSync) {
- clearAutoRefresh();
- }
-}
-async function refreshFeatures({
- instance,
- timeout,
- skipCache,
- allowStale,
- backgroundSync
-}) {
- if (!backgroundSync) {
- cacheSettings.backgroundSync = false;
- }
- return fetchFeaturesWithCache({
- instance,
- allowStale,
- timeout,
- skipCache
- });
-}
-function subscribe(instance) {
- const key = getKey(instance);
- const subs = subscribedInstances.get(key) || new Set;
- subs.add(instance);
- subscribedInstances.set(key, subs);
-}
-function unsubscribe(instance) {
- subscribedInstances.forEach((s) => s.delete(instance));
-}
-function onHidden() {
- streams.forEach((channel) => {
- if (!channel)
- return;
- channel.state = "idle";
- disableChannel(channel);
- });
-}
-function onVisible() {
- streams.forEach((channel) => {
- if (!channel)
- return;
- if (channel.state !== "idle")
- return;
- enableChannel(channel);
- });
-}
-async function updatePersistentCache() {
- try {
- if (!polyfills2.localStorage)
- return;
- await polyfills2.localStorage.setItem(cacheSettings.cacheKey, JSON.stringify(Array.from(cache.entries())));
- } catch (e) {}
-}
-async function fetchFeaturesWithCache({
- instance,
- allowStale,
- timeout,
- skipCache
-}) {
- const key = getKey(instance);
- const cacheKey = getCacheKey(instance);
- const now = new Date;
- const minStaleAt = new Date(now.getTime() - cacheSettings.maxAge + cacheSettings.staleTTL);
- await initializeCache();
- const existing = !cacheSettings.disableCache && !skipCache ? cache.get(cacheKey) : undefined;
- if (existing && (allowStale || existing.staleAt > now) && existing.staleAt > minStaleAt) {
- if (existing.sse)
- supportsSSE.add(key);
- if (existing.staleAt < now) {
- fetchFeatures(instance);
- } else {
- startAutoRefresh(instance);
- }
- return {
- data: existing.data,
- success: true,
- source: "cache"
- };
- } else {
- const res = await promiseTimeout(fetchFeatures(instance), timeout);
- return res || {
- data: null,
- success: false,
- source: "timeout",
- error: new Error("Timeout")
- };
- }
-}
-function getKey(instance) {
- const [apiHost, clientKey] = instance.getApiInfo();
- return `${apiHost}||${clientKey}`;
-}
-function getCacheKey(instance) {
- const baseKey = getKey(instance);
- if (!("isRemoteEval" in instance) || !instance.isRemoteEval())
- return baseKey;
- const attributes = instance.getAttributes();
- const cacheKeyAttributes = instance.getCacheKeyAttributes() || Object.keys(instance.getAttributes());
- const ca = {};
- cacheKeyAttributes.forEach((key) => {
- ca[key] = attributes[key];
- });
- const fv = instance.getForcedVariations();
- const url = instance.getUrl();
- return `${baseKey}||${JSON.stringify({
- ca,
- fv,
- url
- })}`;
-}
-async function initializeCache() {
- if (cacheInitialized)
- return;
- cacheInitialized = true;
- try {
- if (polyfills2.localStorage) {
- const value = await polyfills2.localStorage.getItem(cacheSettings.cacheKey);
- if (!cacheSettings.disableCache && value) {
- const parsed = JSON.parse(value);
- if (parsed && Array.isArray(parsed)) {
- parsed.forEach(([key, data]) => {
- cache.set(key, {
- ...data,
- staleAt: new Date(data.staleAt)
- });
- });
- }
- cleanupCache();
- }
- }
- } catch (e) {}
- if (!cacheSettings.disableIdleStreams) {
- const cleanupFn = helpers.startIdleListener();
- if (cleanupFn) {
- helpers.stopIdleListener = cleanupFn;
- }
- }
-}
-function cleanupCache() {
- const entriesWithTimestamps = Array.from(cache.entries()).map(([key, value]) => ({
- key,
- staleAt: value.staleAt.getTime()
- })).sort((a, b) => a.staleAt - b.staleAt);
- const entriesToRemoveCount = Math.min(Math.max(0, cache.size - cacheSettings.maxEntries), cache.size);
- for (let i = 0;i < entriesToRemoveCount; i++) {
- cache.delete(entriesWithTimestamps[i].key);
- }
-}
-function onNewFeatureData(key, cacheKey, data) {
- const version = data.dateUpdated || "";
- const staleAt = new Date(Date.now() + cacheSettings.staleTTL);
- const existing = !cacheSettings.disableCache ? cache.get(cacheKey) : undefined;
- if (existing && version && existing.version === version) {
- existing.staleAt = staleAt;
- updatePersistentCache();
- return;
- }
- if (!cacheSettings.disableCache) {
- cache.set(cacheKey, {
- data,
- version,
- staleAt,
- sse: supportsSSE.has(key)
- });
- cleanupCache();
- }
- updatePersistentCache();
- const instances = subscribedInstances.get(key);
- instances && instances.forEach((instance) => refreshInstance(instance, data));
-}
-async function refreshInstance(instance, data) {
- await instance.setPayload(data || instance.getPayload());
-}
-async function fetchFeatures(instance) {
- const {
- apiHost,
- apiRequestHeaders
- } = instance.getApiHosts();
- const clientKey = instance.getClientKey();
- const remoteEval = "isRemoteEval" in instance && instance.isRemoteEval();
- const key = getKey(instance);
- const cacheKey = getCacheKey(instance);
- let promise = activeFetches.get(cacheKey);
- if (!promise) {
- const fetcher = remoteEval ? helpers.fetchRemoteEvalCall({
- host: apiHost,
- clientKey,
- payload: {
- attributes: instance.getAttributes(),
- forcedVariations: instance.getForcedVariations(),
- forcedFeatures: Array.from(instance.getForcedFeatures().entries()),
- url: instance.getUrl()
- },
- headers: apiRequestHeaders
- }) : helpers.fetchFeaturesCall({
- host: apiHost,
- clientKey,
- headers: apiRequestHeaders
- });
- promise = fetcher.then((res) => {
- if (!res.ok) {
- throw new Error(`HTTP error: ${res.status}`);
- }
- if (res.headers.get("x-sse-support") === "enabled") {
- supportsSSE.add(key);
- }
- return res.json();
- }).then((data) => {
- onNewFeatureData(key, cacheKey, data);
- startAutoRefresh(instance);
- activeFetches.delete(cacheKey);
- return {
- data,
- success: true,
- source: "network"
- };
- }).catch((e) => {
- instance.log("Error fetching features", {
- apiHost,
- clientKey,
- error: e ? e.message : null
- });
- activeFetches.delete(cacheKey);
- return {
- data: null,
- source: "error",
- success: false,
- error: e
- };
- });
- activeFetches.set(cacheKey, promise);
- }
- return promise;
-}
-function startAutoRefresh(instance, forceSSE = false) {
- const key = getKey(instance);
- const cacheKey = getCacheKey(instance);
- const {
- streamingHost,
- streamingHostRequestHeaders
- } = instance.getApiHosts();
- const clientKey = instance.getClientKey();
- if (forceSSE) {
- supportsSSE.add(key);
- }
- if (cacheSettings.backgroundSync && supportsSSE.has(key) && polyfills2.EventSource) {
- if (streams.has(key))
- return;
- const channel = {
- src: null,
- host: streamingHost,
- clientKey,
- headers: streamingHostRequestHeaders,
- cb: (event) => {
- try {
- if (event.type === "features-updated") {
- const instances = subscribedInstances.get(key);
- instances && instances.forEach((instance2) => {
- fetchFeatures(instance2);
- });
- } else if (event.type === "features") {
- const json = JSON.parse(event.data);
- onNewFeatureData(key, cacheKey, json);
- }
- channel.errors = 0;
- } catch (e) {
- instance.log("SSE Error", {
- streamingHost,
- clientKey,
- error: e ? e.message : null
- });
- onSSEError(channel);
- }
- },
- errors: 0,
- state: "active"
- };
- streams.set(key, channel);
- enableChannel(channel);
- }
-}
-function onSSEError(channel) {
- if (channel.state === "idle")
- return;
- channel.errors++;
- if (channel.errors > 3 || channel.src && channel.src.readyState === 2) {
- const delay = Math.pow(3, channel.errors - 3) * (1000 + Math.random() * 1000);
- disableChannel(channel);
- setTimeout(() => {
- if (["idle", "active"].includes(channel.state))
- return;
- enableChannel(channel);
- }, Math.min(delay, 300000));
- }
-}
-function disableChannel(channel) {
- if (!channel.src)
- return;
- channel.src.onopen = null;
- channel.src.onerror = null;
- channel.src.close();
- channel.src = null;
- if (channel.state === "active") {
- channel.state = "disabled";
- }
-}
-function enableChannel(channel) {
- channel.src = helpers.eventSourceCall({
- host: channel.host,
- clientKey: channel.clientKey,
- headers: channel.headers
- });
- channel.state = "active";
- channel.src.addEventListener("features", channel.cb);
- channel.src.addEventListener("features-updated", channel.cb);
- channel.src.onerror = () => onSSEError(channel);
- channel.src.onopen = () => {
- channel.errors = 0;
- };
-}
-function destroyChannel(channel, key) {
- disableChannel(channel);
- streams.delete(key);
-}
-function clearAutoRefresh() {
- supportsSSE.clear();
- streams.forEach(destroyChannel);
- subscribedInstances.clear();
- helpers.stopIdleListener();
-}
-function startStreaming(instance, options2) {
- if (options2.streaming) {
- if (!instance.getClientKey()) {
- throw new Error("Must specify clientKey to enable streaming");
- }
- if (options2.payload) {
- startAutoRefresh(instance, true);
- }
- subscribe(instance);
- }
-}
-var cacheSettings, polyfills2, helpers, subscribedInstances, cacheInitialized = false, cache, activeFetches, streams, supportsSSE;
-var init_feature_repository = __esm(() => {
- init_util();
- cacheSettings = {
- staleTTL: 1000 * 60,
- maxAge: 1000 * 60 * 60 * 4,
- cacheKey: "gbFeaturesCache",
- backgroundSync: true,
- maxEntries: 10,
- disableIdleStreams: false,
- idleStreamInterval: 20000,
- disableCache: false
- };
- polyfills2 = getPolyfills();
- helpers = {
- fetchFeaturesCall: ({
- host,
- clientKey,
- headers
- }) => {
- return polyfills2.fetch(`${host}/api/features/${clientKey}`, {
- headers
- });
- },
- fetchRemoteEvalCall: ({
- host,
- clientKey,
- payload,
- headers
- }) => {
- const options2 = {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...headers
- },
- body: JSON.stringify(payload)
- };
- return polyfills2.fetch(`${host}/api/eval/${clientKey}`, options2);
- },
- eventSourceCall: ({
- host,
- clientKey,
- headers
- }) => {
- if (headers) {
- return new polyfills2.EventSource(`${host}/sub/${clientKey}`, {
- headers
- });
- }
- return new polyfills2.EventSource(`${host}/sub/${clientKey}`);
- },
- startIdleListener: () => {
- let idleTimeout;
- const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
- if (!isBrowser)
- return;
- const onVisibilityChange = () => {
- if (document.visibilityState === "visible") {
- window.clearTimeout(idleTimeout);
- onVisible();
- } else if (document.visibilityState === "hidden") {
- idleTimeout = window.setTimeout(onHidden, cacheSettings.idleStreamInterval);
- }
- };
- document.addEventListener("visibilitychange", onVisibilityChange);
- return () => document.removeEventListener("visibilitychange", onVisibilityChange);
- },
- stopIdleListener: () => {}
- };
- try {
- if (globalThis.localStorage) {
- polyfills2.localStorage = globalThis.localStorage;
- }
- } catch (e) {}
- subscribedInstances = new Map;
- cache = new Map;
- activeFetches = new Map;
- streams = new Map;
- supportsSSE = new Set;
-});
-
-// node_modules/@growthbook/growthbook/dist/esm/mongrule.mjs
-function evalCondition(obj, condition, savedGroups) {
- savedGroups = savedGroups || {};
- for (const [k, v] of Object.entries(condition)) {
- switch (k) {
- case "$or":
- if (!evalOr(obj, v, savedGroups))
- return false;
- break;
- case "$nor":
- if (evalOr(obj, v, savedGroups))
- return false;
- break;
- case "$and":
- if (!evalAnd(obj, v, savedGroups))
- return false;
- break;
- case "$not":
- if (evalCondition(obj, v, savedGroups))
- return false;
- break;
- default:
- if (!evalConditionValue(v, getPath(obj, k), savedGroups))
- return false;
- }
- }
- return true;
-}
-function getPath(obj, path) {
- const parts = path.split(".");
- let current = obj;
- for (let i = 0;i < parts.length; i++) {
- if (current && typeof current === "object" && parts[i] in current) {
- current = current[parts[i]];
- } else {
- return null;
- }
- }
- return current;
-}
-function getRegex(regex2, insensitive = false) {
- const cacheKey = `${regex2}${insensitive ? "/i" : ""}`;
- if (!_regexCache[cacheKey]) {
- _regexCache[cacheKey] = new RegExp(regex2.replace(/([^\\])\//g, "$1\\/"), insensitive ? "i" : undefined);
- }
- return _regexCache[cacheKey];
-}
-function evalConditionValue(condition, value, savedGroups, insensitive = false) {
- if (typeof condition === "string") {
- if (insensitive) {
- return String(value).toLowerCase() === condition.toLowerCase();
- }
- return value + "" === condition;
- }
- if (typeof condition === "number") {
- return value * 1 === condition;
- }
- if (typeof condition === "boolean") {
- return value !== null && !!value === condition;
- }
- if (condition === null) {
- return value === null;
- }
- if (Array.isArray(condition) || !isOperatorObject(condition)) {
- return JSON.stringify(value) === JSON.stringify(condition);
- }
- for (const op in condition) {
- if (!evalOperatorCondition(op, value, condition[op], savedGroups)) {
- return false;
- }
- }
- return true;
-}
-function isOperatorObject(obj) {
- const keys2 = Object.keys(obj);
- return keys2.length > 0 && keys2.filter((k) => k[0] === "$").length === keys2.length;
-}
-function getType(v) {
- if (v === null)
- return "null";
- if (Array.isArray(v))
- return "array";
- const t = typeof v;
- if (["string", "number", "boolean", "object", "undefined"].includes(t)) {
- return t;
- }
- return "unknown";
-}
-function elemMatch(actual, expected, savedGroups) {
- if (!Array.isArray(actual))
- return false;
- const check = isOperatorObject(expected) ? (v) => evalConditionValue(expected, v, savedGroups) : (v) => evalCondition(v, expected, savedGroups);
- for (let i = 0;i < actual.length; i++) {
- if (actual[i] && check(actual[i])) {
- return true;
- }
- }
- return false;
-}
-function isIn(actual, expected, insensitive = false) {
- if (insensitive) {
- const caseFold = (val) => typeof val === "string" ? val.toLowerCase() : val;
- if (Array.isArray(actual)) {
- return actual.some((el) => expected.some((exp) => caseFold(el) === caseFold(exp)));
- }
- return expected.some((exp) => caseFold(actual) === caseFold(exp));
- }
- if (Array.isArray(actual)) {
- return actual.some((el) => expected.includes(el));
- }
- return expected.includes(actual);
-}
-function isInAll(actual, expected, savedGroups, insensitive = false) {
- if (!Array.isArray(actual))
- return false;
- for (let i = 0;i < expected.length; i++) {
- let passed = false;
- for (let j = 0;j < actual.length; j++) {
- if (evalConditionValue(expected[i], actual[j], savedGroups, insensitive)) {
- passed = true;
- break;
- }
- }
- if (!passed)
- return false;
- }
- return true;
-}
-function evalOperatorCondition(operator, actual, expected, savedGroups) {
- switch (operator) {
- case "$veq":
- return paddedVersionString(actual) === paddedVersionString(expected);
- case "$vne":
- return paddedVersionString(actual) !== paddedVersionString(expected);
- case "$vgt":
- return paddedVersionString(actual) > paddedVersionString(expected);
- case "$vgte":
- return paddedVersionString(actual) >= paddedVersionString(expected);
- case "$vlt":
- return paddedVersionString(actual) < paddedVersionString(expected);
- case "$vlte":
- return paddedVersionString(actual) <= paddedVersionString(expected);
- case "$eq":
- return actual === expected;
- case "$ne":
- return actual !== expected;
- case "$lt":
- return actual < expected;
- case "$lte":
- return actual <= expected;
- case "$gt":
- return actual > expected;
- case "$gte":
- return actual >= expected;
- case "$exists":
- return expected ? actual != null : actual == null;
- case "$in":
- if (!Array.isArray(expected))
- return false;
- return isIn(actual, expected);
- case "$ini":
- if (!Array.isArray(expected))
- return false;
- return isIn(actual, expected, true);
- case "$inGroup":
- return isIn(actual, savedGroups[expected] || []);
- case "$notInGroup":
- return !isIn(actual, savedGroups[expected] || []);
- case "$nin":
- if (!Array.isArray(expected))
- return false;
- return !isIn(actual, expected);
- case "$nini":
- if (!Array.isArray(expected))
- return false;
- return !isIn(actual, expected, true);
- case "$not":
- return !evalConditionValue(expected, actual, savedGroups);
- case "$size":
- if (!Array.isArray(actual))
- return false;
- return evalConditionValue(expected, actual.length, savedGroups);
- case "$elemMatch":
- return elemMatch(actual, expected, savedGroups);
- case "$all":
- if (!Array.isArray(expected))
- return false;
- return isInAll(actual, expected, savedGroups);
- case "$alli":
- if (!Array.isArray(expected))
- return false;
- return isInAll(actual, expected, savedGroups, true);
- case "$regex":
- try {
- return getRegex(expected).test(actual);
- } catch (e) {
- return false;
- }
- case "$regexi":
- try {
- return getRegex(expected, true).test(actual);
- } catch (e) {
- return false;
- }
- case "$type":
- return getType(actual) === expected;
- default:
- console.error("Unknown operator: " + operator);
- return false;
- }
-}
-function evalOr(obj, conditions, savedGroups) {
- if (!conditions.length)
- return true;
- for (let i = 0;i < conditions.length; i++) {
- if (evalCondition(obj, conditions[i], savedGroups)) {
- return true;
- }
- }
- return false;
-}
-function evalAnd(obj, conditions, savedGroups) {
- for (let i = 0;i < conditions.length; i++) {
- if (!evalCondition(obj, conditions[i], savedGroups)) {
- return false;
- }
- }
- return true;
-}
-var _regexCache;
-var init_mongrule = __esm(() => {
- init_util();
- _regexCache = {};
-});
-
-// node_modules/@growthbook/growthbook/dist/esm/core.mjs
-function getForcedFeatureValues(ctx) {
- const ret = new Map;
- if (ctx.global.forcedFeatureValues) {
- ctx.global.forcedFeatureValues.forEach((v, k) => ret.set(k, v));
- }
- if (ctx.user.forcedFeatureValues) {
- ctx.user.forcedFeatureValues.forEach((v, k) => ret.set(k, v));
- }
- return ret;
-}
-function getForcedVariations(ctx) {
- if (ctx.global.forcedVariations && ctx.user.forcedVariations) {
- return {
- ...ctx.global.forcedVariations,
- ...ctx.user.forcedVariations
- };
- } else if (ctx.global.forcedVariations) {
- return ctx.global.forcedVariations;
- } else if (ctx.user.forcedVariations) {
- return ctx.user.forcedVariations;
- } else {
- return {};
- }
-}
-async function safeCall(fn) {
- try {
- await fn();
- } catch (e) {}
-}
-function onExperimentViewed(ctx, experiment, result) {
- if (ctx.user.trackedExperiments) {
- const k = getExperimentDedupeKey(experiment, result);
- if (ctx.user.trackedExperiments.has(k)) {
- return [];
- }
- ctx.user.trackedExperiments.add(k);
- }
- if (ctx.user.enableDevMode && ctx.user.devLogs) {
- ctx.user.devLogs.push({
- experiment,
- result,
- timestamp: Date.now().toString(),
- logType: "experiment"
- });
- }
- const calls = [];
- if (ctx.global.trackingCallback) {
- const cb = ctx.global.trackingCallback;
- calls.push(safeCall(() => cb(experiment, result, ctx.user)));
- }
- if (ctx.user.trackingCallback) {
- const cb = ctx.user.trackingCallback;
- calls.push(safeCall(() => cb(experiment, result)));
- }
- if (ctx.global.eventLogger) {
- const cb = ctx.global.eventLogger;
- calls.push(safeCall(() => cb(EVENT_EXPERIMENT_VIEWED, {
- experimentId: experiment.key,
- variationId: result.key,
- hashAttribute: result.hashAttribute,
- hashValue: result.hashValue
- }, ctx.user)));
- }
- return calls;
-}
-function onFeatureUsage(ctx, key, ret) {
- if (ctx.user.trackedFeatureUsage) {
- const stringifiedValue = JSON.stringify(ret.value);
- if (ctx.user.trackedFeatureUsage[key] === stringifiedValue)
- return;
- ctx.user.trackedFeatureUsage[key] = stringifiedValue;
- if (ctx.user.enableDevMode && ctx.user.devLogs) {
- ctx.user.devLogs.push({
- featureKey: key,
- result: ret,
- timestamp: Date.now().toString(),
- logType: "feature"
- });
- }
- }
- if (ctx.global.onFeatureUsage) {
- const cb = ctx.global.onFeatureUsage;
- safeCall(() => cb(key, ret, ctx.user));
- }
- if (ctx.user.onFeatureUsage) {
- const cb = ctx.user.onFeatureUsage;
- safeCall(() => cb(key, ret));
- }
- if (ctx.global.eventLogger) {
- const cb = ctx.global.eventLogger;
- safeCall(() => cb(EVENT_FEATURE_EVALUATED, {
- feature: key,
- source: ret.source,
- value: ret.value,
- ruleId: ret.source === "defaultValue" ? "$default" : ret.ruleId || "",
- variationId: ret.experimentResult ? ret.experimentResult.key : ""
- }, ctx.user));
- }
-}
-function evalFeature(id, ctx) {
- if (ctx.stack.evaluatedFeatures.has(id)) {
- ctx.global.log(`evalFeature: circular dependency detected: ${ctx.stack.id} -> ${id}`, {
- from: ctx.stack.id,
- to: id
- });
- return getFeatureResult(ctx, id, null, "cyclicPrerequisite");
- }
- ctx.stack.evaluatedFeatures.add(id);
- ctx.stack.id = id;
- const forcedValues = getForcedFeatureValues(ctx);
- if (forcedValues.has(id)) {
- ctx.global.log("Global override", {
- id,
- value: forcedValues.get(id)
- });
- return getFeatureResult(ctx, id, forcedValues.get(id), "override");
- }
- if (!ctx.global.features || !ctx.global.features[id]) {
- ctx.global.log("Unknown feature", {
- id
- });
- return getFeatureResult(ctx, id, null, "unknownFeature");
- }
- const feature = ctx.global.features[id];
- if (feature.rules) {
- const evaluatedFeatures = new Set(ctx.stack.evaluatedFeatures);
- rules:
- for (const rule of feature.rules) {
- if (rule.parentConditions) {
- for (const parentCondition of rule.parentConditions) {
- ctx.stack.evaluatedFeatures = new Set(evaluatedFeatures);
- const parentResult = evalFeature(parentCondition.id, ctx);
- if (parentResult.source === "cyclicPrerequisite") {
- return getFeatureResult(ctx, id, null, "cyclicPrerequisite");
- }
- const evalObj = {
- value: parentResult.value
- };
- const evaled = evalCondition(evalObj, parentCondition.condition || {});
- if (!evaled) {
- if (parentCondition.gate) {
- ctx.global.log("Feature blocked by prerequisite", {
- id,
- rule
- });
- return getFeatureResult(ctx, id, null, "prerequisite");
- }
- ctx.global.log("Skip rule because prerequisite evaluation fails", {
- id,
- rule
- });
- continue rules;
- }
- }
- }
- if (rule.filters && isFilteredOut(rule.filters, ctx)) {
- ctx.global.log("Skip rule because of filters", {
- id,
- rule
- });
- continue;
- }
- if ("force" in rule) {
- if (rule.condition && !conditionPasses(rule.condition, ctx)) {
- ctx.global.log("Skip rule because of condition ff", {
- id,
- rule
- });
- continue;
- }
- if (!isIncludedInRollout(ctx, rule.seed || id, rule.hashAttribute, ctx.user.saveStickyBucketAssignmentDoc && !rule.disableStickyBucketing ? rule.fallbackAttribute : undefined, rule.range, rule.coverage, rule.hashVersion)) {
- ctx.global.log("Skip rule because user not included in rollout", {
- id,
- rule
- });
- continue;
- }
- ctx.global.log("Force value from rule", {
- id,
- rule
- });
- if (rule.tracks) {
- rule.tracks.forEach((t) => {
- const calls = onExperimentViewed(ctx, t.experiment, t.result);
- if (!calls.length && ctx.global.saveDeferredTrack) {
- ctx.global.saveDeferredTrack({
- experiment: t.experiment,
- result: t.result
- });
- }
- });
- }
- return getFeatureResult(ctx, id, rule.force, "force", rule.id);
- }
- if (!rule.variations) {
- ctx.global.log("Skip invalid rule", {
- id,
- rule
- });
- continue;
- }
- const exp = {
- variations: rule.variations,
- key: rule.key || id
- };
- if ("coverage" in rule)
- exp.coverage = rule.coverage;
- if (rule.weights)
- exp.weights = rule.weights;
- if (rule.hashAttribute)
- exp.hashAttribute = rule.hashAttribute;
- if (rule.fallbackAttribute)
- exp.fallbackAttribute = rule.fallbackAttribute;
- if (rule.disableStickyBucketing)
- exp.disableStickyBucketing = rule.disableStickyBucketing;
- if (rule.bucketVersion !== undefined)
- exp.bucketVersion = rule.bucketVersion;
- if (rule.minBucketVersion !== undefined)
- exp.minBucketVersion = rule.minBucketVersion;
- if (rule.namespace)
- exp.namespace = rule.namespace;
- if (rule.meta)
- exp.meta = rule.meta;
- if (rule.ranges)
- exp.ranges = rule.ranges;
- if (rule.name)
- exp.name = rule.name;
- if (rule.phase)
- exp.phase = rule.phase;
- if (rule.seed)
- exp.seed = rule.seed;
- if (rule.hashVersion)
- exp.hashVersion = rule.hashVersion;
- if (rule.filters)
- exp.filters = rule.filters;
- if (rule.condition)
- exp.condition = rule.condition;
- const {
- result
- } = runExperiment(exp, id, ctx);
- ctx.global.onExperimentEval && ctx.global.onExperimentEval(exp, result);
- if (result.inExperiment && !result.passthrough) {
- return getFeatureResult(ctx, id, result.value, "experiment", rule.id, exp, result);
- }
- }
- }
- ctx.global.log("Use default value", {
- id,
- value: feature.defaultValue
- });
- return getFeatureResult(ctx, id, feature.defaultValue === undefined ? null : feature.defaultValue, "defaultValue");
-}
-function runExperiment(experiment, featureId, ctx) {
- const key = experiment.key;
- const numVariations = experiment.variations.length;
- if (numVariations < 2) {
- ctx.global.log("Invalid experiment", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- if (ctx.global.enabled === false || ctx.user.enabled === false) {
- ctx.global.log("Context disabled", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- experiment = mergeOverrides(experiment, ctx);
- if (experiment.urlPatterns && !isURLTargeted(ctx.user.url || "", experiment.urlPatterns)) {
- ctx.global.log("Skip because of url targeting", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- const qsOverride = getQueryStringOverride(key, ctx.user.url || "", numVariations);
- if (qsOverride !== null) {
- ctx.global.log("Force via querystring", {
- id: key,
- variation: qsOverride
- });
- return {
- result: getExperimentResult(ctx, experiment, qsOverride, false, featureId)
- };
- }
- const forcedVariations = getForcedVariations(ctx);
- if (key in forcedVariations) {
- const variation = forcedVariations[key];
- ctx.global.log("Force via dev tools", {
- id: key,
- variation
- });
- return {
- result: getExperimentResult(ctx, experiment, variation, false, featureId)
- };
- }
- if (experiment.status === "draft" || experiment.active === false) {
- ctx.global.log("Skip because inactive", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- const {
- hashAttribute,
- hashValue
- } = getHashAttribute(ctx, experiment.hashAttribute, ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing ? experiment.fallbackAttribute : undefined);
- if (!hashValue) {
- ctx.global.log("Skip because missing hashAttribute", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- let assigned = -1;
- let foundStickyBucket = false;
- let stickyBucketVersionIsBlocked = false;
- if (ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing) {
- const {
- variation,
- versionIsBlocked
- } = getStickyBucketVariation({
- ctx,
- expKey: experiment.key,
- expBucketVersion: experiment.bucketVersion,
- expHashAttribute: experiment.hashAttribute,
- expFallbackAttribute: experiment.fallbackAttribute,
- expMinBucketVersion: experiment.minBucketVersion,
- expMeta: experiment.meta
- });
- foundStickyBucket = variation >= 0;
- assigned = variation;
- stickyBucketVersionIsBlocked = !!versionIsBlocked;
- }
- if (!foundStickyBucket) {
- if (experiment.filters) {
- if (isFilteredOut(experiment.filters, ctx)) {
- ctx.global.log("Skip because of filters", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- } else if (experiment.namespace && !inNamespace(hashValue, experiment.namespace)) {
- ctx.global.log("Skip because of namespace", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- if (experiment.include && !isIncluded(experiment.include)) {
- ctx.global.log("Skip because of include function", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- if (experiment.condition && !conditionPasses(experiment.condition, ctx)) {
- ctx.global.log("Skip because of condition exp", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- if (experiment.parentConditions) {
- const evaluatedFeatures = new Set(ctx.stack.evaluatedFeatures);
- for (const parentCondition of experiment.parentConditions) {
- ctx.stack.evaluatedFeatures = new Set(evaluatedFeatures);
- const parentResult = evalFeature(parentCondition.id, ctx);
- if (parentResult.source === "cyclicPrerequisite") {
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- const evalObj = {
- value: parentResult.value
- };
- if (!evalCondition(evalObj, parentCondition.condition || {})) {
- ctx.global.log("Skip because prerequisite evaluation fails", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- }
- }
- if (experiment.groups && !hasGroupOverlap(experiment.groups, ctx)) {
- ctx.global.log("Skip because of groups", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- }
- if (experiment.url && !urlIsValid(experiment.url, ctx)) {
- ctx.global.log("Skip because of url", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- const n = hash(experiment.seed || key, hashValue, experiment.hashVersion || 1);
- if (n === null) {
- ctx.global.log("Skip because of invalid hash version", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- if (!foundStickyBucket) {
- const ranges = experiment.ranges || getBucketRanges(numVariations, experiment.coverage === undefined ? 1 : experiment.coverage, experiment.weights);
- assigned = chooseVariation(n, ranges);
- }
- if (stickyBucketVersionIsBlocked) {
- ctx.global.log("Skip because sticky bucket version is blocked", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId, undefined, true)
- };
- }
- if (assigned < 0) {
- ctx.global.log("Skip because of coverage", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- if ("force" in experiment) {
- ctx.global.log("Force variation", {
- id: key,
- variation: experiment.force
- });
- return {
- result: getExperimentResult(ctx, experiment, experiment.force === undefined ? -1 : experiment.force, false, featureId)
- };
- }
- if (ctx.global.qaMode || ctx.user.qaMode) {
- ctx.global.log("Skip because QA mode", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- if (experiment.status === "stopped") {
- ctx.global.log("Skip because stopped", {
- id: key
- });
- return {
- result: getExperimentResult(ctx, experiment, -1, false, featureId)
- };
- }
- const result = getExperimentResult(ctx, experiment, assigned, true, featureId, n, foundStickyBucket);
- if (ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing) {
- const {
- changed,
- key: attrKey,
- doc
- } = generateStickyBucketAssignmentDoc(ctx, hashAttribute, toString2(hashValue), {
- [getStickyBucketExperimentKey(experiment.key, experiment.bucketVersion)]: result.key
- });
- if (changed) {
- ctx.user.stickyBucketAssignmentDocs = ctx.user.stickyBucketAssignmentDocs || {};
- ctx.user.stickyBucketAssignmentDocs[attrKey] = doc;
- ctx.user.saveStickyBucketAssignmentDoc(doc);
- }
- }
- const trackingCalls = onExperimentViewed(ctx, experiment, result);
- if (trackingCalls.length === 0 && ctx.global.saveDeferredTrack) {
- ctx.global.saveDeferredTrack({
- experiment,
- result
- });
- }
- const trackingCall = !trackingCalls.length ? undefined : trackingCalls.length === 1 ? trackingCalls[0] : Promise.all(trackingCalls).then(() => {});
- "changeId" in experiment && experiment.changeId && ctx.global.recordChangeId && ctx.global.recordChangeId(experiment.changeId);
- ctx.global.log("In experiment", {
- id: key,
- variation: result.variationId
- });
- return {
- result,
- trackingCall
- };
-}
-function getFeatureResult(ctx, key, value, source, ruleId, experiment, result) {
- const ret = {
- value,
- on: !!value,
- off: !value,
- source,
- ruleId: ruleId || ""
- };
- if (experiment)
- ret.experiment = experiment;
- if (result)
- ret.experimentResult = result;
- if (source !== "override") {
- onFeatureUsage(ctx, key, ret);
- }
- return ret;
-}
-function getAttributes(ctx) {
- return {
- ...ctx.user.attributes,
- ...ctx.user.attributeOverrides
- };
-}
-function conditionPasses(condition, ctx) {
- return evalCondition(getAttributes(ctx), condition, ctx.global.savedGroups || {});
-}
-function isFilteredOut(filters, ctx) {
- return filters.some((filter) => {
- const {
- hashValue
- } = getHashAttribute(ctx, filter.attribute);
- if (!hashValue)
- return true;
- const n = hash(filter.seed, hashValue, filter.hashVersion || 2);
- if (n === null)
- return true;
- return !filter.ranges.some((r) => inRange(n, r));
- });
-}
-function isIncludedInRollout(ctx, seed, hashAttribute, fallbackAttribute, range, coverage, hashVersion) {
- if (!range && coverage === undefined)
- return true;
- if (!range && coverage === 0)
- return false;
- const {
- hashValue
- } = getHashAttribute(ctx, hashAttribute, fallbackAttribute);
- if (!hashValue) {
- return false;
- }
- const n = hash(seed, hashValue, hashVersion || 1);
- if (n === null)
- return false;
- return range ? inRange(n, range) : coverage !== undefined ? n <= coverage : true;
-}
-function getExperimentResult(ctx, experiment, variationIndex, hashUsed, featureId, bucket, stickyBucketUsed) {
- let inExperiment = true;
- if (variationIndex < 0 || variationIndex >= experiment.variations.length) {
- variationIndex = 0;
- inExperiment = false;
- }
- const {
- hashAttribute,
- hashValue
- } = getHashAttribute(ctx, experiment.hashAttribute, ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing ? experiment.fallbackAttribute : undefined);
- const meta = experiment.meta ? experiment.meta[variationIndex] : {};
- const res = {
- key: meta.key || "" + variationIndex,
- featureId,
- inExperiment,
- hashUsed,
- variationId: variationIndex,
- value: experiment.variations[variationIndex],
- hashAttribute,
- hashValue,
- stickyBucketUsed: !!stickyBucketUsed
- };
- if (meta.name)
- res.name = meta.name;
- if (bucket !== undefined)
- res.bucket = bucket;
- if (meta.passthrough)
- res.passthrough = meta.passthrough;
- return res;
-}
-function mergeOverrides(experiment, ctx) {
- const key = experiment.key;
- const o = ctx.global.overrides;
- if (o && o[key]) {
- experiment = Object.assign({}, experiment, o[key]);
- if (typeof experiment.url === "string") {
- experiment.url = getUrlRegExp(experiment.url);
- }
- }
- return experiment;
-}
-function getHashAttribute(ctx, attr, fallback) {
- let hashAttribute = attr || "id";
- let hashValue = "";
- const attributes = getAttributes(ctx);
- if (attributes[hashAttribute]) {
- hashValue = attributes[hashAttribute];
- }
- if (!hashValue && fallback) {
- if (attributes[fallback]) {
- hashValue = attributes[fallback];
- }
- if (hashValue) {
- hashAttribute = fallback;
- }
- }
- return {
- hashAttribute,
- hashValue
- };
-}
-function urlIsValid(urlRegex, ctx) {
- const url = ctx.user.url;
- if (!url)
- return false;
- const pathOnly = url.replace(/^https?:\/\//, "").replace(/^[^/]*\//, "/");
- if (urlRegex.test(url))
- return true;
- if (urlRegex.test(pathOnly))
- return true;
- return false;
-}
-function hasGroupOverlap(expGroups, ctx) {
- const groups = ctx.global.groups || {};
- for (let i = 0;i < expGroups.length; i++) {
- if (groups[expGroups[i]])
- return true;
- }
- return false;
-}
-function getStickyBucketVariation({
- ctx,
- expKey,
- expBucketVersion,
- expHashAttribute,
- expFallbackAttribute,
- expMinBucketVersion,
- expMeta
-}) {
- expBucketVersion = expBucketVersion || 0;
- expMinBucketVersion = expMinBucketVersion || 0;
- expHashAttribute = expHashAttribute || "id";
- expMeta = expMeta || [];
- const id = getStickyBucketExperimentKey(expKey, expBucketVersion);
- const assignments = getStickyBucketAssignments(ctx, expHashAttribute, expFallbackAttribute);
- if (expMinBucketVersion > 0) {
- for (let i = 0;i < expMinBucketVersion; i++) {
- const blockedKey = getStickyBucketExperimentKey(expKey, i);
- if (assignments[blockedKey] !== undefined) {
- return {
- variation: -1,
- versionIsBlocked: true
- };
- }
- }
- }
- const variationKey = assignments[id];
- if (variationKey === undefined)
- return {
- variation: -1
- };
- const variation = expMeta.findIndex((m) => m.key === variationKey);
- if (variation < 0)
- return {
- variation: -1
- };
- return {
- variation
- };
-}
-function getStickyBucketExperimentKey(experimentKey, experimentBucketVersion) {
- experimentBucketVersion = experimentBucketVersion || 0;
- return `${experimentKey}__${experimentBucketVersion}`;
-}
-function getStickyBucketAttributeKey(attributeName, attributeValue) {
- return `${attributeName}||${attributeValue}`;
-}
-function getStickyBucketAssignments(ctx, expHashAttribute, expFallbackAttribute) {
- if (!ctx.user.stickyBucketAssignmentDocs)
- return {};
- const {
- hashAttribute,
- hashValue
- } = getHashAttribute(ctx, expHashAttribute);
- const hashKey = getStickyBucketAttributeKey(hashAttribute, toString2(hashValue));
- const {
- hashAttribute: fallbackAttribute,
- hashValue: fallbackValue
- } = getHashAttribute(ctx, expFallbackAttribute);
- const fallbackKey = fallbackValue ? getStickyBucketAttributeKey(fallbackAttribute, toString2(fallbackValue)) : null;
- const assignments = {};
- if (fallbackKey && ctx.user.stickyBucketAssignmentDocs[fallbackKey]) {
- Object.assign(assignments, ctx.user.stickyBucketAssignmentDocs[fallbackKey].assignments || {});
- }
- if (ctx.user.stickyBucketAssignmentDocs[hashKey]) {
- Object.assign(assignments, ctx.user.stickyBucketAssignmentDocs[hashKey].assignments || {});
- }
- return assignments;
-}
-function generateStickyBucketAssignmentDoc(ctx, attributeName, attributeValue, assignments) {
- const key = getStickyBucketAttributeKey(attributeName, attributeValue);
- const existingAssignments = ctx.user.stickyBucketAssignmentDocs && ctx.user.stickyBucketAssignmentDocs[key] ? ctx.user.stickyBucketAssignmentDocs[key].assignments || {} : {};
- const newAssignments = {
- ...existingAssignments,
- ...assignments
- };
- const changed = JSON.stringify(existingAssignments) !== JSON.stringify(newAssignments);
- return {
- key,
- doc: {
- attributeName,
- attributeValue,
- assignments: newAssignments
- },
- changed
- };
-}
-function deriveStickyBucketIdentifierAttributes(ctx, data) {
- const attributes = new Set;
- const features = data && data.features ? data.features : ctx.global.features || {};
- const experiments = data && data.experiments ? data.experiments : ctx.global.experiments || [];
- Object.keys(features).forEach((id) => {
- const feature = features[id];
- if (feature.rules) {
- for (const rule of feature.rules) {
- if (rule.variations) {
- attributes.add(rule.hashAttribute || "id");
- if (rule.fallbackAttribute) {
- attributes.add(rule.fallbackAttribute);
- }
- }
- }
- }
- });
- experiments.map((experiment) => {
- attributes.add(experiment.hashAttribute || "id");
- if (experiment.fallbackAttribute) {
- attributes.add(experiment.fallbackAttribute);
- }
- });
- return Array.from(attributes);
-}
-async function getAllStickyBucketAssignmentDocs(ctx, stickyBucketService, data) {
- const attributes = getStickyBucketAttributes(ctx, data);
- return stickyBucketService.getAllAssignments(attributes);
-}
-function getStickyBucketAttributes(ctx, data) {
- const attributes = {};
- const stickyBucketIdentifierAttributes = deriveStickyBucketIdentifierAttributes(ctx, data);
- stickyBucketIdentifierAttributes.forEach((attr) => {
- const {
- hashValue
- } = getHashAttribute(ctx, attr);
- attributes[attr] = toString2(hashValue);
- });
- return attributes;
-}
-async function decryptPayload(data, decryptionKey, subtle) {
- data = {
- ...data
- };
- if (data.encryptedFeatures) {
- try {
- data.features = JSON.parse(await decrypt(data.encryptedFeatures, decryptionKey, subtle));
- } catch (e) {
- console.error(e);
- }
- delete data.encryptedFeatures;
- }
- if (data.encryptedExperiments) {
- try {
- data.experiments = JSON.parse(await decrypt(data.encryptedExperiments, decryptionKey, subtle));
- } catch (e) {
- console.error(e);
- }
- delete data.encryptedExperiments;
- }
- if (data.encryptedSavedGroups) {
- try {
- data.savedGroups = JSON.parse(await decrypt(data.encryptedSavedGroups, decryptionKey, subtle));
- } catch (e) {
- console.error(e);
- }
- delete data.encryptedSavedGroups;
- }
- return data;
-}
-function getApiHosts(options2) {
- const defaultHost = options2.apiHost || "https://cdn.growthbook.io";
- return {
- apiHost: defaultHost.replace(/\/*$/, ""),
- streamingHost: (options2.streamingHost || defaultHost).replace(/\/*$/, ""),
- apiRequestHeaders: options2.apiHostRequestHeaders,
- streamingHostRequestHeaders: options2.streamingHostRequestHeaders
- };
-}
-function getExperimentDedupeKey(experiment, result) {
- return result.hashAttribute + result.hashValue + experiment.key + result.variationId;
-}
-var EVENT_FEATURE_EVALUATED = "Feature Evaluated", EVENT_EXPERIMENT_VIEWED = "Experiment Viewed";
-var init_core2 = __esm(() => {
- init_mongrule();
- init_util();
-});
-
-// node_modules/@growthbook/growthbook/dist/esm/GrowthBook.mjs
-class GrowthBook {
- constructor(options2) {
- options2 = options2 || {};
- this.version = SDK_VERSION;
- this._options = this.context = options2;
- this._renderer = options2.renderer || null;
- this._trackedExperiments = new Set;
- this._completedChangeIds = new Set;
- this._trackedFeatures = {};
- this.debug = !!options2.debug;
- this._subscriptions = new Set;
- this.ready = false;
- this._assigned = new Map;
- this._activeAutoExperiments = new Map;
- this._triggeredExpKeys = new Set;
- this._initialized = false;
- this._redirectedUrl = "";
- this._deferredTrackingCalls = new Map;
- this._autoExperimentsAllowed = !options2.disableExperimentsOnLoad;
- this._destroyCallbacks = [];
- this.logs = [];
- this.log = this.log.bind(this);
- this._saveDeferredTrack = this._saveDeferredTrack.bind(this);
- this._onExperimentEval = this._onExperimentEval.bind(this);
- this._fireSubscriptions = this._fireSubscriptions.bind(this);
- this._recordChangedId = this._recordChangedId.bind(this);
- if (options2.remoteEval) {
- if (options2.decryptionKey) {
- throw new Error("Encryption is not available for remoteEval");
- }
- if (!options2.clientKey) {
- throw new Error("Missing clientKey");
- }
- let isGbHost = false;
- try {
- isGbHost = !!new URL(options2.apiHost || "").hostname.match(/growthbook\.io$/i);
- } catch (e) {}
- if (isGbHost) {
- throw new Error("Cannot use remoteEval on GrowthBook Cloud");
- }
- } else {
- if (options2.cacheKeyAttributes) {
- throw new Error("cacheKeyAttributes are only used for remoteEval");
- }
- }
- if (options2.stickyBucketService) {
- const s = options2.stickyBucketService;
- this._saveStickyBucketAssignmentDoc = (doc) => {
- return s.saveAssignments(doc);
- };
- }
- if (options2.plugins) {
- for (const plugin of options2.plugins) {
- plugin(this);
- }
- }
- if (options2.features) {
- this.ready = true;
- }
- if (isBrowser && options2.enableDevMode) {
- window._growthbook = this;
- document.dispatchEvent(new Event("gbloaded"));
- }
- if (options2.experiments) {
- this.ready = true;
- this._updateAllAutoExperiments();
- }
- if (this._options.stickyBucketService && this._options.stickyBucketAssignmentDocs) {
- for (const key in this._options.stickyBucketAssignmentDocs) {
- const doc = this._options.stickyBucketAssignmentDocs[key];
- if (doc) {
- this._options.stickyBucketService.saveAssignments(doc).catch(() => {});
- }
- }
- }
- if (this.ready) {
- this.refreshStickyBuckets(this.getPayload());
- }
- }
- async setPayload(payload) {
- this._payload = payload;
- const data = await decryptPayload(payload, this._options.decryptionKey);
- this._decryptedPayload = data;
- await this.refreshStickyBuckets(data);
- if (data.features) {
- this._options.features = data.features;
- }
- if (data.savedGroups) {
- this._options.savedGroups = data.savedGroups;
- }
- if (data.experiments) {
- this._options.experiments = data.experiments;
- this._updateAllAutoExperiments();
- }
- this.ready = true;
- this._render();
- }
- initSync(options2) {
- this._initialized = true;
- const payload = options2.payload;
- if (payload.encryptedExperiments || payload.encryptedFeatures) {
- throw new Error("initSync does not support encrypted payloads");
- }
- if (this._options.stickyBucketService && !this._options.stickyBucketAssignmentDocs) {
- this._options.stickyBucketAssignmentDocs = this.generateStickyBucketAssignmentDocsSync(this._options.stickyBucketService, payload);
- }
- this._payload = payload;
- this._decryptedPayload = payload;
- if (payload.features) {
- this._options.features = payload.features;
- }
- if (payload.experiments) {
- this._options.experiments = payload.experiments;
- this._updateAllAutoExperiments();
- }
- this.ready = true;
- startStreaming(this, options2);
- return this;
- }
- async init(options2) {
- this._initialized = true;
- options2 = options2 || {};
- if (options2.cacheSettings) {
- configureCache(options2.cacheSettings);
- }
- if (options2.payload) {
- await this.setPayload(options2.payload);
- startStreaming(this, options2);
- return {
- success: true,
- source: "init"
- };
- } else {
- const {
- data,
- ...res
- } = await this._refresh({
- ...options2,
- allowStale: true
- });
- startStreaming(this, options2);
- await this.setPayload(data || {});
- return res;
- }
- }
- async loadFeatures(options2) {
- options2 = options2 || {};
- await this.init({
- skipCache: options2.skipCache,
- timeout: options2.timeout,
- streaming: (this._options.backgroundSync ?? true) && (options2.autoRefresh || this._options.subscribeToChanges)
- });
- }
- async refreshFeatures(options2) {
- const res = await this._refresh({
- ...options2 || {},
- allowStale: false
- });
- if (res.data) {
- await this.setPayload(res.data);
- }
- }
- getApiInfo() {
- return [this.getApiHosts().apiHost, this.getClientKey()];
- }
- getApiHosts() {
- return getApiHosts(this._options);
- }
- getClientKey() {
- return this._options.clientKey || "";
- }
- getPayload() {
- return this._payload || {
- features: this.getFeatures(),
- experiments: this.getExperiments()
- };
- }
- getDecryptedPayload() {
- return this._decryptedPayload || this.getPayload();
- }
- isRemoteEval() {
- return this._options.remoteEval || false;
- }
- getCacheKeyAttributes() {
- return this._options.cacheKeyAttributes;
- }
- async _refresh({
- timeout,
- skipCache,
- allowStale,
- streaming
- }) {
- if (!this._options.clientKey) {
- throw new Error("Missing clientKey");
- }
- return refreshFeatures({
- instance: this,
- timeout,
- skipCache: skipCache || this._options.disableCache,
- allowStale,
- backgroundSync: streaming ?? this._options.backgroundSync ?? true
- });
- }
- _render() {
- if (this._renderer) {
- try {
- this._renderer();
- } catch (e) {
- console.error("Failed to render", e);
- }
- }
- }
- setFeatures(features) {
- this._options.features = features;
- this.ready = true;
- this._render();
- }
- async setEncryptedFeatures(encryptedString, decryptionKey, subtle) {
- const featuresJSON = await decrypt(encryptedString, decryptionKey || this._options.decryptionKey, subtle);
- this.setFeatures(JSON.parse(featuresJSON));
- }
- setExperiments(experiments) {
- this._options.experiments = experiments;
- this.ready = true;
- this._updateAllAutoExperiments();
- }
- async setEncryptedExperiments(encryptedString, decryptionKey, subtle) {
- const experimentsJSON = await decrypt(encryptedString, decryptionKey || this._options.decryptionKey, subtle);
- this.setExperiments(JSON.parse(experimentsJSON));
- }
- async setAttributes(attributes) {
- this._options.attributes = attributes;
- if (this._options.stickyBucketService) {
- await this.refreshStickyBuckets();
- }
- if (this._options.remoteEval) {
- await this._refreshForRemoteEval();
- return;
- }
- this._render();
- this._updateAllAutoExperiments();
- }
- async updateAttributes(attributes) {
- return this.setAttributes({
- ...this._options.attributes,
- ...attributes
- });
- }
- async setAttributeOverrides(overrides) {
- this._options.attributeOverrides = overrides;
- if (this._options.stickyBucketService) {
- await this.refreshStickyBuckets();
- }
- if (this._options.remoteEval) {
- await this._refreshForRemoteEval();
- return;
- }
- this._render();
- this._updateAllAutoExperiments();
- }
- async setForcedVariations(vars) {
- this._options.forcedVariations = vars || {};
- if (this._options.remoteEval) {
- await this._refreshForRemoteEval();
- return;
- }
- this._render();
- this._updateAllAutoExperiments();
- }
- setForcedFeatures(map) {
- this._options.forcedFeatureValues = map;
- this._render();
- }
- async setURL(url) {
- if (url === this._options.url)
- return;
- this._options.url = url;
- this._redirectedUrl = "";
- if (this._options.remoteEval) {
- await this._refreshForRemoteEval();
- this._updateAllAutoExperiments(true);
- return;
- }
- this._updateAllAutoExperiments(true);
- }
- getAttributes() {
- return {
- ...this._options.attributes,
- ...this._options.attributeOverrides
- };
- }
- getForcedVariations() {
- return this._options.forcedVariations || {};
- }
- getForcedFeatures() {
- return this._options.forcedFeatureValues || new Map;
- }
- getStickyBucketAssignmentDocs() {
- return this._options.stickyBucketAssignmentDocs || {};
- }
- getUrl() {
- return this._options.url || "";
- }
- getFeatures() {
- return this._options.features || {};
- }
- getExperiments() {
- return this._options.experiments || [];
- }
- getCompletedChangeIds() {
- return Array.from(this._completedChangeIds);
- }
- subscribe(cb) {
- this._subscriptions.add(cb);
- return () => {
- this._subscriptions.delete(cb);
- };
- }
- async _refreshForRemoteEval() {
- if (!this._options.remoteEval)
- return;
- if (!this._initialized)
- return;
- const res = await this._refresh({
- allowStale: false
- });
- if (res.data) {
- await this.setPayload(res.data);
- }
- }
- getAllResults() {
- return new Map(this._assigned);
- }
- onDestroy(cb) {
- this._destroyCallbacks.push(cb);
- }
- isDestroyed() {
- return !!this._destroyed;
- }
- destroy(options2) {
- options2 = options2 || {};
- this._destroyed = true;
- this._destroyCallbacks.forEach((cb) => {
- try {
- cb();
- } catch (e) {
- console.error(e);
- }
- });
- this._subscriptions.clear();
- this._assigned.clear();
- this._trackedExperiments.clear();
- this._completedChangeIds.clear();
- this._deferredTrackingCalls.clear();
- this._trackedFeatures = {};
- this._destroyCallbacks = [];
- this._payload = undefined;
- this._saveStickyBucketAssignmentDoc = undefined;
- unsubscribe(this);
- if (options2.destroyAllStreams) {
- clearAutoRefresh();
- }
- this.logs = [];
- if (isBrowser && window._growthbook === this) {
- delete window._growthbook;
- }
- this._activeAutoExperiments.forEach((exp) => {
- exp.undo();
- });
- this._activeAutoExperiments.clear();
- this._triggeredExpKeys.clear();
- }
- setRenderer(renderer) {
- this._renderer = renderer;
- }
- forceVariation(key, variation) {
- this._options.forcedVariations = this._options.forcedVariations || {};
- this._options.forcedVariations[key] = variation;
- if (this._options.remoteEval) {
- this._refreshForRemoteEval();
- return;
- }
- this._updateAllAutoExperiments();
- this._render();
- }
- run(experiment) {
- const {
- result
- } = runExperiment(experiment, null, this._getEvalContext());
- this._onExperimentEval(experiment, result);
- return result;
- }
- triggerExperiment(key) {
- this._triggeredExpKeys.add(key);
- if (!this._options.experiments)
- return null;
- const experiments = this._options.experiments.filter((exp) => exp.key === key);
- return experiments.map((exp) => {
- return this._runAutoExperiment(exp);
- }).filter((res) => res !== null);
- }
- triggerAutoExperiments() {
- this._autoExperimentsAllowed = true;
- this._updateAllAutoExperiments(true);
- }
- _getEvalContext() {
- return {
- user: this._getUserContext(),
- global: this._getGlobalContext(),
- stack: {
- evaluatedFeatures: new Set
- }
- };
- }
- _getUserContext() {
- return {
- attributes: this._options.user ? {
- ...this._options.user,
- ...this._options.attributes
- } : this._options.attributes,
- enableDevMode: this._options.enableDevMode,
- blockedChangeIds: this._options.blockedChangeIds,
- stickyBucketAssignmentDocs: this._options.stickyBucketAssignmentDocs,
- url: this._getContextUrl(),
- forcedVariations: this._options.forcedVariations,
- forcedFeatureValues: this._options.forcedFeatureValues,
- attributeOverrides: this._options.attributeOverrides,
- saveStickyBucketAssignmentDoc: this._saveStickyBucketAssignmentDoc,
- trackingCallback: this._options.trackingCallback,
- onFeatureUsage: this._options.onFeatureUsage,
- devLogs: this.logs,
- trackedExperiments: this._trackedExperiments,
- trackedFeatureUsage: this._trackedFeatures
- };
- }
- _getGlobalContext() {
- return {
- features: this._options.features,
- experiments: this._options.experiments,
- log: this.log,
- enabled: this._options.enabled,
- qaMode: this._options.qaMode,
- savedGroups: this._options.savedGroups,
- groups: this._options.groups,
- overrides: this._options.overrides,
- onExperimentEval: this._onExperimentEval,
- recordChangeId: this._recordChangedId,
- saveDeferredTrack: this._saveDeferredTrack,
- eventLogger: this._options.eventLogger
- };
- }
- _runAutoExperiment(experiment, forceRerun) {
- const existing = this._activeAutoExperiments.get(experiment);
- if (experiment.manual && !this._triggeredExpKeys.has(experiment.key) && !existing)
- return null;
- const isBlocked = this._isAutoExperimentBlockedByContext(experiment);
- if (isBlocked) {
- this.log("Auto experiment blocked", {
- id: experiment.key
- });
- }
- let result;
- let trackingCall;
- if (isBlocked) {
- result = getExperimentResult(this._getEvalContext(), experiment, -1, false, "");
- } else {
- ({
- result,
- trackingCall
- } = runExperiment(experiment, null, this._getEvalContext()));
- this._onExperimentEval(experiment, result);
- }
- const valueHash = JSON.stringify(result.value);
- if (!forceRerun && result.inExperiment && existing && existing.valueHash === valueHash) {
- return result;
- }
- if (existing)
- this._undoActiveAutoExperiment(experiment);
- if (result.inExperiment) {
- const changeType = getAutoExperimentChangeType(experiment);
- if (changeType === "redirect" && result.value.urlRedirect && experiment.urlPatterns) {
- const url = experiment.persistQueryString ? mergeQueryStrings(this._getContextUrl(), result.value.urlRedirect) : result.value.urlRedirect;
- if (isURLTargeted(url, experiment.urlPatterns)) {
- this.log("Skipping redirect because original URL matches redirect URL", {
- id: experiment.key
- });
- return result;
- }
- this._redirectedUrl = url;
- const {
- navigate,
- delay
- } = this._getNavigateFunction();
- if (navigate) {
- if (isBrowser) {
- Promise.all([...trackingCall ? [promiseTimeout(trackingCall, this._options.maxNavigateDelay ?? 1000)] : [], new Promise((resolve2) => window.setTimeout(resolve2, this._options.navigateDelay ?? delay))]).then(() => {
- try {
- navigate(url);
- } catch (e) {
- console.error(e);
- }
- });
- } else {
- try {
- navigate(url);
- } catch (e) {
- console.error(e);
- }
- }
- }
- } else if (changeType === "visual") {
- const undo = this._options.applyDomChangesCallback ? this._options.applyDomChangesCallback(result.value) : this._applyDOMChanges(result.value);
- if (undo) {
- this._activeAutoExperiments.set(experiment, {
- undo,
- valueHash
- });
- }
- }
- }
- return result;
- }
- _undoActiveAutoExperiment(exp) {
- const data = this._activeAutoExperiments.get(exp);
- if (data) {
- data.undo();
- this._activeAutoExperiments.delete(exp);
- }
- }
- _updateAllAutoExperiments(forceRerun) {
- if (!this._autoExperimentsAllowed)
- return;
- const experiments = this._options.experiments || [];
- const keys2 = new Set(experiments);
- this._activeAutoExperiments.forEach((v, k) => {
- if (!keys2.has(k)) {
- v.undo();
- this._activeAutoExperiments.delete(k);
- }
- });
- for (const exp of experiments) {
- const result = this._runAutoExperiment(exp, forceRerun);
- if (result && result.inExperiment && getAutoExperimentChangeType(exp) === "redirect") {
- break;
- }
- }
- }
- _onExperimentEval(experiment, result) {
- const prev = this._assigned.get(experiment.key);
- this._assigned.set(experiment.key, {
- experiment,
- result
- });
- if (this._subscriptions.size > 0) {
- this._fireSubscriptions(experiment, result, prev);
- }
- }
- _fireSubscriptions(experiment, result, prev) {
- if (!prev || prev.result.inExperiment !== result.inExperiment || prev.result.variationId !== result.variationId) {
- this._subscriptions.forEach((cb) => {
- try {
- cb(experiment, result);
- } catch (e) {
- console.error(e);
- }
- });
- }
- }
- _recordChangedId(id) {
- this._completedChangeIds.add(id);
- }
- isOn(key) {
- return this.evalFeature(key).on;
- }
- isOff(key) {
- return this.evalFeature(key).off;
- }
- getFeatureValue(key, defaultValue) {
- const value = this.evalFeature(key).value;
- return value === null ? defaultValue : value;
- }
- feature(id) {
- return this.evalFeature(id);
- }
- evalFeature(id) {
- return evalFeature(id, this._getEvalContext());
- }
- log(msg, ctx) {
- if (!this.debug)
- return;
- if (this._options.log)
- this._options.log(msg, ctx);
- else
- console.log(msg, ctx);
- }
- getDeferredTrackingCalls() {
- return Array.from(this._deferredTrackingCalls.values());
- }
- setDeferredTrackingCalls(calls) {
- this._deferredTrackingCalls = new Map(calls.filter((c) => c && c.experiment && c.result).map((c) => {
- return [getExperimentDedupeKey(c.experiment, c.result), c];
- }));
- }
- async fireDeferredTrackingCalls() {
- if (!this._options.trackingCallback)
- return;
- const promises = [];
- this._deferredTrackingCalls.forEach((call) => {
- if (!call || !call.experiment || !call.result) {
- console.error("Invalid deferred tracking call", {
- call
- });
- } else {
- promises.push(this._options.trackingCallback(call.experiment, call.result));
- }
- });
- this._deferredTrackingCalls.clear();
- await Promise.all(promises);
- }
- setTrackingCallback(callback) {
- this._options.trackingCallback = callback;
- this.fireDeferredTrackingCalls();
- }
- setFeatureUsageCallback(callback) {
- this._options.onFeatureUsage = callback;
- }
- setEventLogger(logger) {
- this._options.eventLogger = logger;
- }
- async logEvent(eventName, properties) {
- if (this._destroyed) {
- console.error("Cannot log event to destroyed GrowthBook instance");
- return;
- }
- if (this._options.enableDevMode) {
- this.logs.push({
- eventName,
- properties,
- timestamp: Date.now().toString(),
- logType: "event"
- });
- }
- if (this._options.eventLogger) {
- try {
- await this._options.eventLogger(eventName, properties || {}, this._getUserContext());
- } catch (e) {
- console.error(e);
- }
- } else {
- console.error("No event logger configured");
- }
- }
- _saveDeferredTrack(data) {
- this._deferredTrackingCalls.set(getExperimentDedupeKey(data.experiment, data.result), data);
- }
- _getContextUrl() {
- return this._options.url || (isBrowser ? window.location.href : "");
- }
- _isAutoExperimentBlockedByContext(experiment) {
- const changeType = getAutoExperimentChangeType(experiment);
- if (changeType === "visual") {
- if (this._options.disableVisualExperiments)
- return true;
- if (this._options.disableJsInjection) {
- if (experiment.variations.some((v) => v.js)) {
- return true;
- }
- }
- } else if (changeType === "redirect") {
- if (this._options.disableUrlRedirectExperiments)
- return true;
- try {
- const current = new URL(this._getContextUrl());
- for (const v of experiment.variations) {
- if (!v || !v.urlRedirect)
- continue;
- const url = new URL(v.urlRedirect);
- if (this._options.disableCrossOriginUrlRedirectExperiments) {
- if (url.protocol !== current.protocol)
- return true;
- if (url.host !== current.host)
- return true;
- }
- }
- } catch (e) {
- this.log("Error parsing current or redirect URL", {
- id: experiment.key,
- error: e
- });
- return true;
- }
- } else {
- return true;
- }
- if (experiment.changeId && (this._options.blockedChangeIds || []).includes(experiment.changeId)) {
- return true;
- }
- return false;
- }
- getRedirectUrl() {
- return this._redirectedUrl;
- }
- _getNavigateFunction() {
- if (this._options.navigate) {
- return {
- navigate: this._options.navigate,
- delay: 0
- };
- } else if (isBrowser) {
- return {
- navigate: (url) => {
- window.location.replace(url);
- },
- delay: 100
- };
- }
- return {
- navigate: null,
- delay: 0
- };
- }
- _applyDOMChanges(changes) {
- if (!isBrowser)
- return;
- const undo = [];
- if (changes.css) {
- const s = document.createElement("style");
- s.innerHTML = changes.css;
- document.head.appendChild(s);
- undo.push(() => s.remove());
- }
- if (changes.js) {
- const script = document.createElement("script");
- script.innerHTML = changes.js;
- if (this._options.jsInjectionNonce) {
- script.nonce = this._options.jsInjectionNonce;
- }
- document.head.appendChild(script);
- undo.push(() => script.remove());
- }
- if (changes.domMutations) {
- changes.domMutations.forEach((mutation) => {
- undo.push(dom_mutator_esm_default.declarative(mutation).revert);
- });
- }
- return () => {
- undo.forEach((fn) => fn());
- };
- }
- async refreshStickyBuckets(data) {
- if (this._options.stickyBucketService) {
- const ctx = this._getEvalContext();
- const docs = await getAllStickyBucketAssignmentDocs(ctx, this._options.stickyBucketService, data);
- this._options.stickyBucketAssignmentDocs = docs;
- }
- }
- generateStickyBucketAssignmentDocsSync(stickyBucketService, payload) {
- if (!("getAllAssignmentsSync" in stickyBucketService)) {
- console.error("generating StickyBucketAssignmentDocs docs requires StickyBucketServiceSync");
- return;
- }
- const ctx = this._getEvalContext();
- const attributes = getStickyBucketAttributes(ctx, payload);
- return stickyBucketService.getAllAssignmentsSync(attributes);
- }
- inDevMode() {
- return !!this._options.enableDevMode;
- }
-}
-var isBrowser, SDK_VERSION;
-var init_GrowthBook = __esm(() => {
- init_dom_mutator_esm();
- init_util();
- init_feature_repository();
- init_core2();
- isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
- SDK_VERSION = loadSDKVersion();
-});
-
-// node_modules/@growthbook/growthbook/dist/esm/index.mjs
-var init_esm = __esm(() => {
- init_GrowthBook();
-});
-
-// node_modules/lodash-es/isEqual.js
-function isEqual(value, other2) {
- return _baseIsEqual_default(value, other2);
-}
-var isEqual_default;
-var init_isEqual = __esm(() => {
- init__baseIsEqual();
- isEqual_default = isEqual;
-});
-
-// node_modules/lodash-es/lodash.js
-var init_lodash = __esm(() => {
- init_isEqual();
- init_memoize();
-});
-
-// src/constants/keys.ts
-function getGrowthBookClientKey() {
- return process.env.USER_TYPE === "ant" ? isEnvTruthy(process.env.ENABLE_GROWTHBOOK_DEV) ? "sdk-yZQvlplybuXjYh6L" : "sdk-xRVcrliHIlrg4og4" : "sdk-zAZezfDKGoZuXXKe";
-}
-var init_keys2 = __esm(() => {
- init_envUtils();
-});
-
-// src/utils/cwd.ts
-import { AsyncLocalStorage } from "async_hooks";
-function runWithCwdOverride(cwd2, fn) {
- return cwdOverrideStorage.run(cwd2, fn);
-}
-function pwd() {
- return cwdOverrideStorage.getStore() ?? getCwdState();
-}
-function getCwd() {
- try {
- return pwd();
- } catch {
- return getOriginalCwd();
- }
-}
-var cwdOverrideStorage;
-var init_cwd = __esm(() => {
- init_state();
- cwdOverrideStorage = new AsyncLocalStorage;
-});
-
-// src/utils/diagLogs.ts
-import { dirname as dirname4 } from "path";
-function logForDiagnosticsNoPII(level, event, data) {
- const logFile = getDiagnosticLogFile();
- if (!logFile) {
- return;
- }
- const entry = {
- timestamp: new Date().toISOString(),
- level,
- event,
- data: data ?? {}
- };
- const fs2 = getFsImplementation();
- const line = jsonStringify(entry) + `
-`;
- try {
- fs2.appendFileSync(logFile, line);
- } catch {
- try {
- fs2.mkdirSync(dirname4(logFile));
- fs2.appendFileSync(logFile, line);
- } catch {}
- }
-}
-function getDiagnosticLogFile() {
- return process.env.CLAUDE_CODE_DIAGNOSTICS_FILE;
-}
-async function withDiagnosticsTiming(event, fn, getData) {
- const startTime = Date.now();
- logForDiagnosticsNoPII("info", `${event}_started`);
- try {
- const result = await fn();
- const additionalData = getData ? getData(result) : {};
- logForDiagnosticsNoPII("info", `${event}_completed`, {
- duration_ms: Date.now() - startTime,
- ...additionalData
- });
- return result;
- } catch (error) {
- logForDiagnosticsNoPII("error", `${event}_failed`, {
- duration_ms: Date.now() - startTime
- });
- throw error;
- }
-}
-var init_diagLogs = __esm(() => {
- init_fsOperations();
- init_slowOperations();
-});
-
-// src/utils/bundledMode.ts
-function isRunningWithBun() {
- return process.versions.bun !== undefined;
-}
-function isInBundledMode() {
- return typeof Bun !== "undefined" && Array.isArray(Bun.embeddedFiles) && Bun.embeddedFiles.length > 0;
-}
-
-// node_modules/is-plain-obj/index.js
-function isPlainObject(value) {
- if (typeof value !== "object" || value === null) {
- return false;
- }
- const prototype = Object.getPrototypeOf(value);
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
-}
-
-// node_modules/execa/lib/arguments/file-url.js
-import { fileURLToPath } from "url";
-var safeNormalizeFileUrl = (file, name) => {
- const fileString = normalizeFileUrl(normalizeDenoExecPath(file));
- if (typeof fileString !== "string") {
- throw new TypeError(`${name} must be a string or a file URL: ${fileString}.`);
- }
- return fileString;
-}, normalizeDenoExecPath = (file) => isDenoExecPath(file) ? file.toString() : file, isDenoExecPath = (file) => typeof file !== "string" && file && Object.getPrototypeOf(file) === String.prototype, normalizeFileUrl = (file) => file instanceof URL ? fileURLToPath(file) : file;
-var init_file_url = () => {};
-
-// node_modules/execa/lib/methods/parameters.js
-var normalizeParameters = (rawFile, rawArguments = [], rawOptions = {}) => {
- const filePath = safeNormalizeFileUrl(rawFile, "First argument");
- const [commandArguments, options2] = isPlainObject(rawArguments) ? [[], rawArguments] : [rawArguments, rawOptions];
- if (!Array.isArray(commandArguments)) {
- throw new TypeError(`Second argument must be either an array of arguments or an options object: ${commandArguments}`);
- }
- if (commandArguments.some((commandArgument) => typeof commandArgument === "object" && commandArgument !== null)) {
- throw new TypeError(`Second argument must be an array of strings: ${commandArguments}`);
- }
- const normalizedArguments = commandArguments.map(String);
- const nullByteArgument = normalizedArguments.find((normalizedArgument) => normalizedArgument.includes("\x00"));
- if (nullByteArgument !== undefined) {
- throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${nullByteArgument}`);
- }
- if (!isPlainObject(options2)) {
- throw new TypeError(`Last argument must be an options object: ${options2}`);
- }
- return [filePath, normalizedArguments, options2];
-};
-var init_parameters = __esm(() => {
- init_file_url();
-});
-
-// node_modules/execa/lib/utils/uint-array.js
-import { StringDecoder } from "string_decoder";
-var objectToString2, isArrayBuffer = (value) => objectToString2.call(value) === "[object ArrayBuffer]", isUint8Array = (value) => objectToString2.call(value) === "[object Uint8Array]", bufferToUint8Array = (buffer) => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength), textEncoder, stringToUint8Array = (string) => textEncoder.encode(string), textDecoder, uint8ArrayToString = (uint8Array) => textDecoder.decode(uint8Array), joinToString = (uint8ArraysOrStrings, encoding) => {
- const strings = uint8ArraysToStrings(uint8ArraysOrStrings, encoding);
- return strings.join("");
-}, uint8ArraysToStrings = (uint8ArraysOrStrings, encoding) => {
- if (encoding === "utf8" && uint8ArraysOrStrings.every((uint8ArrayOrString) => typeof uint8ArrayOrString === "string")) {
- return uint8ArraysOrStrings;
- }
- const decoder = new StringDecoder(encoding);
- const strings = uint8ArraysOrStrings.map((uint8ArrayOrString) => typeof uint8ArrayOrString === "string" ? stringToUint8Array(uint8ArrayOrString) : uint8ArrayOrString).map((uint8Array) => decoder.write(uint8Array));
- const finalString = decoder.end();
- return finalString === "" ? strings : [...strings, finalString];
-}, joinToUint8Array = (uint8ArraysOrStrings) => {
- if (uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0])) {
- return uint8ArraysOrStrings[0];
- }
- return concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));
-}, stringsToUint8Arrays = (uint8ArraysOrStrings) => uint8ArraysOrStrings.map((uint8ArrayOrString) => typeof uint8ArrayOrString === "string" ? stringToUint8Array(uint8ArrayOrString) : uint8ArrayOrString), concatUint8Arrays = (uint8Arrays) => {
- const result = new Uint8Array(getJoinLength(uint8Arrays));
- let index2 = 0;
- for (const uint8Array of uint8Arrays) {
- result.set(uint8Array, index2);
- index2 += uint8Array.length;
- }
- return result;
-}, getJoinLength = (uint8Arrays) => {
- let joinLength = 0;
- for (const uint8Array of uint8Arrays) {
- joinLength += uint8Array.length;
- }
- return joinLength;
-};
-var init_uint_array = __esm(() => {
- ({ toString: objectToString2 } = Object.prototype);
- textEncoder = new TextEncoder;
- textDecoder = new TextDecoder;
-});
-
-// node_modules/execa/lib/methods/template.js
-import { ChildProcess } from "child_process";
-var isTemplateString = (templates) => Array.isArray(templates) && Array.isArray(templates.raw), parseTemplates = (templates, expressions) => {
- let tokens = [];
- for (const [index2, template] of templates.entries()) {
- tokens = parseTemplate({
- templates,
- expressions,
- tokens,
- index: index2,
- template
- });
- }
- if (tokens.length === 0) {
- throw new TypeError("Template script must not be empty");
- }
- const [file, ...commandArguments] = tokens;
- return [file, commandArguments, {}];
-}, parseTemplate = ({ templates, expressions, tokens, index: index2, template }) => {
- if (template === undefined) {
- throw new TypeError(`Invalid backslash sequence: ${templates.raw[index2]}`);
- }
- const { nextTokens, leadingWhitespaces, trailingWhitespaces } = splitByWhitespaces(template, templates.raw[index2]);
- const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);
- if (index2 === expressions.length) {
- return newTokens;
- }
- const expression = expressions[index2];
- const expressionTokens = Array.isArray(expression) ? expression.map((expression2) => parseExpression(expression2)) : [parseExpression(expression)];
- return concatTokens(newTokens, expressionTokens, trailingWhitespaces);
-}, splitByWhitespaces = (template, rawTemplate) => {
- if (rawTemplate.length === 0) {
- return { nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false };
- }
- const nextTokens = [];
- let templateStart = 0;
- const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);
- for (let templateIndex = 0, rawIndex = 0;templateIndex < template.length; templateIndex += 1, rawIndex += 1) {
- const rawCharacter = rawTemplate[rawIndex];
- if (DELIMITERS.has(rawCharacter)) {
- if (templateStart !== templateIndex) {
- nextTokens.push(template.slice(templateStart, templateIndex));
- }
- templateStart = templateIndex + 1;
- } else if (rawCharacter === "\\") {
- const nextRawCharacter = rawTemplate[rawIndex + 1];
- if (nextRawCharacter === `
-`) {
- templateIndex -= 1;
- rawIndex += 1;
- } else if (nextRawCharacter === "u" && rawTemplate[rawIndex + 2] === "{") {
- rawIndex = rawTemplate.indexOf("}", rawIndex + 3);
- } else {
- rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;
- }
- }
- }
- const trailingWhitespaces = templateStart === template.length;
- if (!trailingWhitespaces) {
- nextTokens.push(template.slice(templateStart));
- }
- return { nextTokens, leadingWhitespaces, trailingWhitespaces };
-}, DELIMITERS, ESCAPE_LENGTH, concatTokens = (tokens, nextTokens, isSeparated) => isSeparated || tokens.length === 0 || nextTokens.length === 0 ? [...tokens, ...nextTokens] : [
- ...tokens.slice(0, -1),
- `${tokens.at(-1)}${nextTokens[0]}`,
- ...nextTokens.slice(1)
-], parseExpression = (expression) => {
- const typeOfExpression = typeof expression;
- if (typeOfExpression === "string") {
- return expression;
- }
- if (typeOfExpression === "number") {
- return String(expression);
- }
- if (isPlainObject(expression) && (("stdout" in expression) || ("isMaxBuffer" in expression))) {
- return getSubprocessResult(expression);
- }
- if (expression instanceof ChildProcess || Object.prototype.toString.call(expression) === "[object Promise]") {
- throw new TypeError("Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}.");
- }
- throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);
-}, getSubprocessResult = ({ stdout }) => {
- if (typeof stdout === "string") {
- return stdout;
- }
- if (isUint8Array(stdout)) {
- return uint8ArrayToString(stdout);
- }
- if (stdout === undefined) {
- throw new TypeError(`Missing result.stdout in template expression. This is probably due to the previous subprocess' "stdout" option.`);
- }
- throw new TypeError(`Unexpected "${typeof stdout}" stdout in template expression`);
-};
-var init_template = __esm(() => {
- init_uint_array();
- DELIMITERS = new Set([" ", "\t", "\r", `
-`]);
- ESCAPE_LENGTH = { x: 3, u: 5 };
-});
-
-// node_modules/execa/lib/utils/standard-stream.js
-import process3 from "process";
-var isStandardStream = (stream) => STANDARD_STREAMS.includes(stream), STANDARD_STREAMS, STANDARD_STREAMS_ALIASES, getStreamName = (fdNumber) => STANDARD_STREAMS_ALIASES[fdNumber] ?? `stdio[${fdNumber}]`;
-var init_standard_stream = __esm(() => {
- STANDARD_STREAMS = [process3.stdin, process3.stdout, process3.stderr];
- STANDARD_STREAMS_ALIASES = ["stdin", "stdout", "stderr"];
-});
-
-// node_modules/execa/lib/arguments/specific.js
-import { debuglog } from "util";
-var normalizeFdSpecificOptions = (options2) => {
- const optionsCopy = { ...options2 };
- for (const optionName of FD_SPECIFIC_OPTIONS) {
- optionsCopy[optionName] = normalizeFdSpecificOption(options2, optionName);
- }
- return optionsCopy;
-}, normalizeFdSpecificOption = (options2, optionName) => {
- const optionBaseArray = Array.from({ length: getStdioLength(options2) + 1 });
- const optionArray = normalizeFdSpecificValue(options2[optionName], optionBaseArray, optionName);
- return addDefaultValue(optionArray, optionName);
-}, getStdioLength = ({ stdio }) => Array.isArray(stdio) ? Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length) : STANDARD_STREAMS_ALIASES.length, normalizeFdSpecificValue = (optionValue, optionArray, optionName) => isPlainObject(optionValue) ? normalizeOptionObject(optionValue, optionArray, optionName) : optionArray.fill(optionValue), normalizeOptionObject = (optionValue, optionArray, optionName) => {
- for (const fdName of Object.keys(optionValue).sort(compareFdName)) {
- for (const fdNumber of parseFdName(fdName, optionName, optionArray)) {
- optionArray[fdNumber] = optionValue[fdName];
- }
- }
- return optionArray;
-}, compareFdName = (fdNameA, fdNameB) => getFdNameOrder(fdNameA) < getFdNameOrder(fdNameB) ? 1 : -1, getFdNameOrder = (fdName) => {
- if (fdName === "stdout" || fdName === "stderr") {
- return 0;
- }
- return fdName === "all" ? 2 : 1;
-}, parseFdName = (fdName, optionName, optionArray) => {
- if (fdName === "ipc") {
- return [optionArray.length - 1];
- }
- const fdNumber = parseFd(fdName);
- if (fdNumber === undefined || fdNumber === 0) {
- throw new TypeError(`"${optionName}.${fdName}" is invalid.
-It must be "${optionName}.stdout", "${optionName}.stderr", "${optionName}.all", "${optionName}.ipc", or "${optionName}.fd3", "${optionName}.fd4" (and so on).`);
- }
- if (fdNumber >= optionArray.length) {
- throw new TypeError(`"${optionName}.${fdName}" is invalid: that file descriptor does not exist.
-Please set the "stdio" option to ensure that file descriptor exists.`);
- }
- return fdNumber === "all" ? [1, 2] : [fdNumber];
-}, parseFd = (fdName) => {
- if (fdName === "all") {
- return fdName;
- }
- if (STANDARD_STREAMS_ALIASES.includes(fdName)) {
- return STANDARD_STREAMS_ALIASES.indexOf(fdName);
- }
- const regexpResult = FD_REGEXP.exec(fdName);
- if (regexpResult !== null) {
- return Number(regexpResult[1]);
- }
-}, FD_REGEXP, addDefaultValue = (optionArray, optionName) => optionArray.map((optionValue) => optionValue === undefined ? DEFAULT_OPTIONS[optionName] : optionValue), verboseDefault, DEFAULT_OPTIONS, FD_SPECIFIC_OPTIONS, getFdSpecificValue = (optionArray, fdNumber) => fdNumber === "ipc" ? optionArray.at(-1) : optionArray[fdNumber];
-var init_specific = __esm(() => {
- init_standard_stream();
- FD_REGEXP = /^fd(\d+)$/;
- verboseDefault = debuglog("execa").enabled ? "full" : "none";
- DEFAULT_OPTIONS = {
- lines: false,
- buffer: true,
- maxBuffer: 1000 * 1000 * 100,
- verbose: verboseDefault,
- stripFinalNewline: true
- };
- FD_SPECIFIC_OPTIONS = ["lines", "buffer", "maxBuffer", "verbose", "stripFinalNewline"];
-});
-
-// node_modules/execa/lib/verbose/values.js
-var isVerbose = ({ verbose }, fdNumber) => getFdVerbose(verbose, fdNumber) !== "none", isFullVerbose = ({ verbose }, fdNumber) => !["none", "short"].includes(getFdVerbose(verbose, fdNumber)), getVerboseFunction = ({ verbose }, fdNumber) => {
- const fdVerbose = getFdVerbose(verbose, fdNumber);
- return isVerboseFunction(fdVerbose) ? fdVerbose : undefined;
-}, getFdVerbose = (verbose, fdNumber) => fdNumber === undefined ? getFdGenericVerbose(verbose) : getFdSpecificValue(verbose, fdNumber), getFdGenericVerbose = (verbose) => verbose.find((fdVerbose) => isVerboseFunction(fdVerbose)) ?? VERBOSE_VALUES.findLast((fdVerbose) => verbose.includes(fdVerbose)), isVerboseFunction = (fdVerbose) => typeof fdVerbose === "function", VERBOSE_VALUES;
-var init_values = __esm(() => {
- init_specific();
- VERBOSE_VALUES = ["none", "short", "full"];
-});
-
-// node_modules/execa/lib/arguments/escape.js
-import { platform } from "process";
-import { stripVTControlCharacters } from "util";
-var joinCommand = (filePath, rawArguments) => {
- const fileAndArguments = [filePath, ...rawArguments];
- const command = fileAndArguments.join(" ");
- const escapedCommand = fileAndArguments.map((fileAndArgument) => quoteString(escapeControlCharacters(fileAndArgument))).join(" ");
- return { command, escapedCommand };
-}, escapeLines = (lines) => stripVTControlCharacters(lines).split(`
-`).map((line) => escapeControlCharacters(line)).join(`
-`), escapeControlCharacters = (line) => line.replaceAll(SPECIAL_CHAR_REGEXP, (character) => escapeControlCharacter(character)), escapeControlCharacter = (character) => {
- const commonEscape = COMMON_ESCAPES[character];
- if (commonEscape !== undefined) {
- return commonEscape;
- }
- const codepoint = character.codePointAt(0);
- const codepointHex = codepoint.toString(16);
- return codepoint <= ASTRAL_START ? `\\u${codepointHex.padStart(4, "0")}` : `\\U${codepointHex}`;
-}, getSpecialCharRegExp = () => {
- try {
- return new RegExp("\\p{Separator}|\\p{Other}", "gu");
- } catch {
- return /[\s\u0000-\u001F\u007F-\u009F\u00AD]/g;
- }
-}, SPECIAL_CHAR_REGEXP, COMMON_ESCAPES, ASTRAL_START = 65535, quoteString = (escapedArgument) => {
- if (NO_ESCAPE_REGEXP.test(escapedArgument)) {
- return escapedArgument;
- }
- return platform === "win32" ? `"${escapedArgument.replaceAll('"', '""')}"` : `'${escapedArgument.replaceAll("'", "'\\''")}'`;
-}, NO_ESCAPE_REGEXP;
-var init_escape = __esm(() => {
- SPECIAL_CHAR_REGEXP = getSpecialCharRegExp();
- COMMON_ESCAPES = {
- " ": " ",
- "\b": "\\b",
- "\f": "\\f",
- "\n": "\\n",
- "\r": "\\r",
- "\t": "\\t"
- };
- NO_ESCAPE_REGEXP = /^[\w./-]+$/;
-});
-
-// node_modules/is-unicode-supported/index.js
-import process4 from "process";
-function isUnicodeSupported() {
- const { env: env2 } = process4;
- const { TERM, TERM_PROGRAM } = env2;
- if (process4.platform !== "win32") {
- return TERM !== "linux";
- }
- return Boolean(env2.WT_SESSION) || Boolean(env2.TERMINUS_SUBLIME) || env2.ConEmuTask === "{cmd::Cmder}" || TERM_PROGRAM === "Terminus-Sublime" || TERM_PROGRAM === "vscode" || TERM === "xterm-256color" || TERM === "alacritty" || TERM === "rxvt-unicode" || TERM === "rxvt-unicode-256color" || env2.TERMINAL_EMULATOR === "JetBrains-JediTerm";
-}
-var init_is_unicode_supported = () => {};
-
-// node_modules/figures/index.js
-var common, specialMainSymbols, specialFallbackSymbols, mainSymbols, fallbackSymbols, shouldUseMain, figures, figures_default, replacements;
-var init_figures = __esm(() => {
- init_is_unicode_supported();
- common = {
- circleQuestionMark: "(?)",
- questionMarkPrefix: "(?)",
- square: "\u2588",
- squareDarkShade: "\u2593",
- squareMediumShade: "\u2592",
- squareLightShade: "\u2591",
- squareTop: "\u2580",
- squareBottom: "\u2584",
- squareLeft: "\u258C",
- squareRight: "\u2590",
- squareCenter: "\u25A0",
- bullet: "\u25CF",
- dot: "\u2024",
- ellipsis: "\u2026",
- pointerSmall: "\u203A",
- triangleUp: "\u25B2",
- triangleUpSmall: "\u25B4",
- triangleDown: "\u25BC",
- triangleDownSmall: "\u25BE",
- triangleLeftSmall: "\u25C2",
- triangleRightSmall: "\u25B8",
- home: "\u2302",
- heart: "\u2665",
- musicNote: "\u266A",
- musicNoteBeamed: "\u266B",
- arrowUp: "\u2191",
- arrowDown: "\u2193",
- arrowLeft: "\u2190",
- arrowRight: "\u2192",
- arrowLeftRight: "\u2194",
- arrowUpDown: "\u2195",
- almostEqual: "\u2248",
- notEqual: "\u2260",
- lessOrEqual: "\u2264",
- greaterOrEqual: "\u2265",
- identical: "\u2261",
- infinity: "\u221E",
- subscriptZero: "\u2080",
- subscriptOne: "\u2081",
- subscriptTwo: "\u2082",
- subscriptThree: "\u2083",
- subscriptFour: "\u2084",
- subscriptFive: "\u2085",
- subscriptSix: "\u2086",
- subscriptSeven: "\u2087",
- subscriptEight: "\u2088",
- subscriptNine: "\u2089",
- oneHalf: "\xBD",
- oneThird: "\u2153",
- oneQuarter: "\xBC",
- oneFifth: "\u2155",
- oneSixth: "\u2159",
- oneEighth: "\u215B",
- twoThirds: "\u2154",
- twoFifths: "\u2156",
- threeQuarters: "\xBE",
- threeFifths: "\u2157",
- threeEighths: "\u215C",
- fourFifths: "\u2158",
- fiveSixths: "\u215A",
- fiveEighths: "\u215D",
- sevenEighths: "\u215E",
- line: "\u2500",
- lineBold: "\u2501",
- lineDouble: "\u2550",
- lineDashed0: "\u2504",
- lineDashed1: "\u2505",
- lineDashed2: "\u2508",
- lineDashed3: "\u2509",
- lineDashed4: "\u254C",
- lineDashed5: "\u254D",
- lineDashed6: "\u2574",
- lineDashed7: "\u2576",
- lineDashed8: "\u2578",
- lineDashed9: "\u257A",
- lineDashed10: "\u257C",
- lineDashed11: "\u257E",
- lineDashed12: "\u2212",
- lineDashed13: "\u2013",
- lineDashed14: "\u2010",
- lineDashed15: "\u2043",
- lineVertical: "\u2502",
- lineVerticalBold: "\u2503",
- lineVerticalDouble: "\u2551",
- lineVerticalDashed0: "\u2506",
- lineVerticalDashed1: "\u2507",
- lineVerticalDashed2: "\u250A",
- lineVerticalDashed3: "\u250B",
- lineVerticalDashed4: "\u254E",
- lineVerticalDashed5: "\u254F",
- lineVerticalDashed6: "\u2575",
- lineVerticalDashed7: "\u2577",
- lineVerticalDashed8: "\u2579",
- lineVerticalDashed9: "\u257B",
- lineVerticalDashed10: "\u257D",
- lineVerticalDashed11: "\u257F",
- lineDownLeft: "\u2510",
- lineDownLeftArc: "\u256E",
- lineDownBoldLeftBold: "\u2513",
- lineDownBoldLeft: "\u2512",
- lineDownLeftBold: "\u2511",
- lineDownDoubleLeftDouble: "\u2557",
- lineDownDoubleLeft: "\u2556",
- lineDownLeftDouble: "\u2555",
- lineDownRight: "\u250C",
- lineDownRightArc: "\u256D",
- lineDownBoldRightBold: "\u250F",
- lineDownBoldRight: "\u250E",
- lineDownRightBold: "\u250D",
- lineDownDoubleRightDouble: "\u2554",
- lineDownDoubleRight: "\u2553",
- lineDownRightDouble: "\u2552",
- lineUpLeft: "\u2518",
- lineUpLeftArc: "\u256F",
- lineUpBoldLeftBold: "\u251B",
- lineUpBoldLeft: "\u251A",
- lineUpLeftBold: "\u2519",
- lineUpDoubleLeftDouble: "\u255D",
- lineUpDoubleLeft: "\u255C",
- lineUpLeftDouble: "\u255B",
- lineUpRight: "\u2514",
- lineUpRightArc: "\u2570",
- lineUpBoldRightBold: "\u2517",
- lineUpBoldRight: "\u2516",
- lineUpRightBold: "\u2515",
- lineUpDoubleRightDouble: "\u255A",
- lineUpDoubleRight: "\u2559",
- lineUpRightDouble: "\u2558",
- lineUpDownLeft: "\u2524",
- lineUpBoldDownBoldLeftBold: "\u252B",
- lineUpBoldDownBoldLeft: "\u2528",
- lineUpDownLeftBold: "\u2525",
- lineUpBoldDownLeftBold: "\u2529",
- lineUpDownBoldLeftBold: "\u252A",
- lineUpDownBoldLeft: "\u2527",
- lineUpBoldDownLeft: "\u2526",
- lineUpDoubleDownDoubleLeftDouble: "\u2563",
- lineUpDoubleDownDoubleLeft: "\u2562",
- lineUpDownLeftDouble: "\u2561",
- lineUpDownRight: "\u251C",
- lineUpBoldDownBoldRightBold: "\u2523",
- lineUpBoldDownBoldRight: "\u2520",
- lineUpDownRightBold: "\u251D",
- lineUpBoldDownRightBold: "\u2521",
- lineUpDownBoldRightBold: "\u2522",
- lineUpDownBoldRight: "\u251F",
- lineUpBoldDownRight: "\u251E",
- lineUpDoubleDownDoubleRightDouble: "\u2560",
- lineUpDoubleDownDoubleRight: "\u255F",
- lineUpDownRightDouble: "\u255E",
- lineDownLeftRight: "\u252C",
- lineDownBoldLeftBoldRightBold: "\u2533",
- lineDownLeftBoldRightBold: "\u252F",
- lineDownBoldLeftRight: "\u2530",
- lineDownBoldLeftBoldRight: "\u2531",
- lineDownBoldLeftRightBold: "\u2532",
- lineDownLeftRightBold: "\u252E",
- lineDownLeftBoldRight: "\u252D",
- lineDownDoubleLeftDoubleRightDouble: "\u2566",
- lineDownDoubleLeftRight: "\u2565",
- lineDownLeftDoubleRightDouble: "\u2564",
- lineUpLeftRight: "\u2534",
- lineUpBoldLeftBoldRightBold: "\u253B",
- lineUpLeftBoldRightBold: "\u2537",
- lineUpBoldLeftRight: "\u2538",
- lineUpBoldLeftBoldRight: "\u2539",
- lineUpBoldLeftRightBold: "\u253A",
- lineUpLeftRightBold: "\u2536",
- lineUpLeftBoldRight: "\u2535",
- lineUpDoubleLeftDoubleRightDouble: "\u2569",
- lineUpDoubleLeftRight: "\u2568",
- lineUpLeftDoubleRightDouble: "\u2567",
- lineUpDownLeftRight: "\u253C",
- lineUpBoldDownBoldLeftBoldRightBold: "\u254B",
- lineUpDownBoldLeftBoldRightBold: "\u2548",
- lineUpBoldDownLeftBoldRightBold: "\u2547",
- lineUpBoldDownBoldLeftRightBold: "\u254A",
- lineUpBoldDownBoldLeftBoldRight: "\u2549",
- lineUpBoldDownLeftRight: "\u2540",
- lineUpDownBoldLeftRight: "\u2541",
- lineUpDownLeftBoldRight: "\u253D",
- lineUpDownLeftRightBold: "\u253E",
- lineUpBoldDownBoldLeftRight: "\u2542",
- lineUpDownLeftBoldRightBold: "\u253F",
- lineUpBoldDownLeftBoldRight: "\u2543",
- lineUpBoldDownLeftRightBold: "\u2544",
- lineUpDownBoldLeftBoldRight: "\u2545",
- lineUpDownBoldLeftRightBold: "\u2546",
- lineUpDoubleDownDoubleLeftDoubleRightDouble: "\u256C",
- lineUpDoubleDownDoubleLeftRight: "\u256B",
- lineUpDownLeftDoubleRightDouble: "\u256A",
- lineCross: "\u2573",
- lineBackslash: "\u2572",
- lineSlash: "\u2571"
- };
- specialMainSymbols = {
- tick: "\u2714",
- info: "\u2139",
- warning: "\u26A0",
- cross: "\u2718",
- squareSmall: "\u25FB",
- squareSmallFilled: "\u25FC",
- circle: "\u25EF",
- circleFilled: "\u25C9",
- circleDotted: "\u25CC",
- circleDouble: "\u25CE",
- circleCircle: "\u24DE",
- circleCross: "\u24E7",
- circlePipe: "\u24BE",
- radioOn: "\u25C9",
- radioOff: "\u25EF",
- checkboxOn: "\u2612",
- checkboxOff: "\u2610",
- checkboxCircleOn: "\u24E7",
- checkboxCircleOff: "\u24BE",
- pointer: "\u276F",
- triangleUpOutline: "\u25B3",
- triangleLeft: "\u25C0",
- triangleRight: "\u25B6",
- lozenge: "\u25C6",
- lozengeOutline: "\u25C7",
- hamburger: "\u2630",
- smiley: "\u32E1",
- mustache: "\u0DF4",
- star: "\u2605",
- play: "\u25B6",
- nodejs: "\u2B22",
- oneSeventh: "\u2150",
- oneNinth: "\u2151",
- oneTenth: "\u2152"
- };
- specialFallbackSymbols = {
- tick: "\u221A",
- info: "i",
- warning: "\u203C",
- cross: "\xD7",
- squareSmall: "\u25A1",
- squareSmallFilled: "\u25A0",
- circle: "( )",
- circleFilled: "(*)",
- circleDotted: "( )",
- circleDouble: "( )",
- circleCircle: "(\u25CB)",
- circleCross: "(\xD7)",
- circlePipe: "(\u2502)",
- radioOn: "(*)",
- radioOff: "( )",
- checkboxOn: "[\xD7]",
- checkboxOff: "[ ]",
- checkboxCircleOn: "(\xD7)",
- checkboxCircleOff: "( )",
- pointer: ">",
- triangleUpOutline: "\u2206",
- triangleLeft: "\u25C4",
- triangleRight: "\u25BA",
- lozenge: "\u2666",
- lozengeOutline: "\u25CA",
- hamburger: "\u2261",
- smiley: "\u263A",
- mustache: "\u250C\u2500\u2510",
- star: "\u2736",
- play: "\u25BA",
- nodejs: "\u2666",
- oneSeventh: "1/7",
- oneNinth: "1/9",
- oneTenth: "1/10"
- };
- mainSymbols = { ...common, ...specialMainSymbols };
- fallbackSymbols = { ...common, ...specialFallbackSymbols };
- shouldUseMain = isUnicodeSupported();
- figures = shouldUseMain ? mainSymbols : fallbackSymbols;
- figures_default = figures;
- replacements = Object.entries(specialMainSymbols);
-});
-
-// node_modules/yoctocolors/base.js
-import tty2 from "tty";
-var hasColors, format = (open2, close) => {
- if (!hasColors) {
- return (input) => input;
- }
- const openCode = `\x1B[${open2}m`;
- const closeCode = `\x1B[${close}m`;
- return (input) => {
- const string = input + "";
- let index2 = string.indexOf(closeCode);
- if (index2 === -1) {
- return openCode + string + closeCode;
- }
- let result = openCode;
- let lastIndex = 0;
- const reopenOnNestedClose = close === 22;
- const replaceCode = (reopenOnNestedClose ? closeCode : "") + openCode;
- while (index2 !== -1) {
- result += string.slice(lastIndex, index2) + replaceCode;
- lastIndex = index2 + closeCode.length;
- index2 = string.indexOf(closeCode, lastIndex);
- }
- result += string.slice(lastIndex) + closeCode;
- return result;
- };
-}, reset, bold, dim, italic, underline, overline, inverse, hidden, strikethrough, black, red, green, yellow, blue, magenta, cyan, white, gray, bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite, bgGray, redBright, greenBright, yellowBright, blueBright, magentaBright, cyanBright, whiteBright, bgRedBright, bgGreenBright, bgYellowBright, bgBlueBright, bgMagentaBright, bgCyanBright, bgWhiteBright;
-var init_base = __esm(() => {
- hasColors = tty2?.WriteStream?.prototype?.hasColors?.() ?? false;
- reset = format(0, 0);
- bold = format(1, 22);
- dim = format(2, 22);
- italic = format(3, 23);
- underline = format(4, 24);
- overline = format(53, 55);
- inverse = format(7, 27);
- hidden = format(8, 28);
- strikethrough = format(9, 29);
- black = format(30, 39);
- red = format(31, 39);
- green = format(32, 39);
- yellow = format(33, 39);
- blue = format(34, 39);
- magenta = format(35, 39);
- cyan = format(36, 39);
- white = format(37, 39);
- gray = format(90, 39);
- bgBlack = format(40, 49);
- bgRed = format(41, 49);
- bgGreen = format(42, 49);
- bgYellow = format(43, 49);
- bgBlue = format(44, 49);
- bgMagenta = format(45, 49);
- bgCyan = format(46, 49);
- bgWhite = format(47, 49);
- bgGray = format(100, 49);
- redBright = format(91, 39);
- greenBright = format(92, 39);
- yellowBright = format(93, 39);
- blueBright = format(94, 39);
- magentaBright = format(95, 39);
- cyanBright = format(96, 39);
- whiteBright = format(97, 39);
- bgRedBright = format(101, 49);
- bgGreenBright = format(102, 49);
- bgYellowBright = format(103, 49);
- bgBlueBright = format(104, 49);
- bgMagentaBright = format(105, 49);
- bgCyanBright = format(106, 49);
- bgWhiteBright = format(107, 49);
-});
-
-// node_modules/yoctocolors/index.js
-var init_yoctocolors = __esm(() => {
- init_base();
-});
-
-// node_modules/execa/lib/verbose/default.js
-var defaultVerboseFunction = ({
- type,
- message,
- timestamp,
- piped,
- commandId,
- result: { failed = false } = {},
- options: { reject = true }
-}) => {
- const timestampString = serializeTimestamp(timestamp);
- const icon = ICONS[type]({ failed, reject, piped });
- const color = COLORS[type]({ reject });
- return `${gray(`[${timestampString}]`)} ${gray(`[${commandId}]`)} ${color(icon)} ${color(message)}`;
-}, serializeTimestamp = (timestamp) => `${padField(timestamp.getHours(), 2)}:${padField(timestamp.getMinutes(), 2)}:${padField(timestamp.getSeconds(), 2)}.${padField(timestamp.getMilliseconds(), 3)}`, padField = (field, padding) => String(field).padStart(padding, "0"), getFinalIcon = ({ failed, reject }) => {
- if (!failed) {
- return figures_default.tick;
- }
- return reject ? figures_default.cross : figures_default.warning;
-}, ICONS, identity2 = (string) => string, COLORS;
-var init_default = __esm(() => {
- init_figures();
- init_yoctocolors();
- ICONS = {
- command: ({ piped }) => piped ? "|" : "$",
- output: () => " ",
- ipc: () => "*",
- error: getFinalIcon,
- duration: getFinalIcon
- };
- COLORS = {
- command: () => bold,
- output: () => identity2,
- ipc: () => identity2,
- error: ({ reject }) => reject ? redBright : yellowBright,
- duration: () => gray
- };
-});
-
-// node_modules/execa/lib/verbose/custom.js
-var applyVerboseOnLines = (printedLines, verboseInfo, fdNumber) => {
- const verboseFunction = getVerboseFunction(verboseInfo, fdNumber);
- return printedLines.map(({ verboseLine, verboseObject }) => applyVerboseFunction(verboseLine, verboseObject, verboseFunction)).filter((printedLine) => printedLine !== undefined).map((printedLine) => appendNewline(printedLine)).join("");
-}, applyVerboseFunction = (verboseLine, verboseObject, verboseFunction) => {
- if (verboseFunction === undefined) {
- return verboseLine;
- }
- const printedLine = verboseFunction(verboseLine, verboseObject);
- if (typeof printedLine === "string") {
- return printedLine;
- }
-}, appendNewline = (printedLine) => printedLine.endsWith(`
-`) ? printedLine : `${printedLine}
-`;
-var init_custom = __esm(() => {
- init_values();
-});
-
-// node_modules/execa/lib/verbose/log.js
-import { inspect } from "util";
-var verboseLog = ({ type, verboseMessage, fdNumber, verboseInfo, result }) => {
- const verboseObject = getVerboseObject({ type, result, verboseInfo });
- const printedLines = getPrintedLines(verboseMessage, verboseObject);
- const finalLines = applyVerboseOnLines(printedLines, verboseInfo, fdNumber);
- if (finalLines !== "") {
- console.warn(finalLines.slice(0, -1));
- }
-}, getVerboseObject = ({
- type,
- result,
- verboseInfo: { escapedCommand, commandId, rawOptions: { piped = false, ...options2 } }
-}) => ({
- type,
- escapedCommand,
- commandId: `${commandId}`,
- timestamp: new Date,
- piped,
- result,
- options: options2
-}), getPrintedLines = (verboseMessage, verboseObject) => verboseMessage.split(`
-`).map((message) => getPrintedLine({ ...verboseObject, message })), getPrintedLine = (verboseObject) => {
- const verboseLine = defaultVerboseFunction(verboseObject);
- return { verboseLine, verboseObject };
-}, serializeVerboseMessage = (message) => {
- const messageString = typeof message === "string" ? message : inspect(message);
- const escapedMessage = escapeLines(messageString);
- return escapedMessage.replaceAll("\t", " ".repeat(TAB_SIZE));
-}, TAB_SIZE = 2;
-var init_log = __esm(() => {
- init_escape();
- init_default();
- init_custom();
-});
-
-// node_modules/execa/lib/verbose/start.js
-var logCommand = (escapedCommand, verboseInfo) => {
- if (!isVerbose(verboseInfo)) {
- return;
- }
- verboseLog({
- type: "command",
- verboseMessage: escapedCommand,
- verboseInfo
- });
-};
-var init_start = __esm(() => {
- init_values();
- init_log();
-});
-
-// node_modules/execa/lib/verbose/info.js
-var getVerboseInfo = (verbose, escapedCommand, rawOptions) => {
- validateVerbose(verbose);
- const commandId = getCommandId(verbose);
- return {
- verbose,
- escapedCommand,
- commandId,
- rawOptions
- };
-}, getCommandId = (verbose) => isVerbose({ verbose }) ? COMMAND_ID++ : undefined, COMMAND_ID = 0n, validateVerbose = (verbose) => {
- for (const fdVerbose of verbose) {
- if (fdVerbose === false) {
- throw new TypeError(`The "verbose: false" option was renamed to "verbose: 'none'".`);
- }
- if (fdVerbose === true) {
- throw new TypeError(`The "verbose: true" option was renamed to "verbose: 'short'".`);
- }
- if (!VERBOSE_VALUES.includes(fdVerbose) && !isVerboseFunction(fdVerbose)) {
- const allowedValues = VERBOSE_VALUES.map((allowedValue) => `'${allowedValue}'`).join(", ");
- throw new TypeError(`The "verbose" option must not be ${fdVerbose}. Allowed values are: ${allowedValues} or a function.`);
- }
- }
-};
-var init_info = __esm(() => {
- init_values();
-});
-
-// node_modules/execa/lib/return/duration.js
-import { hrtime } from "process";
-var getStartTime = () => hrtime.bigint(), getDurationMs = (startTime) => Number(hrtime.bigint() - startTime) / 1e6;
-var init_duration = () => {};
-
-// node_modules/execa/lib/arguments/command.js
-var handleCommand = (filePath, rawArguments, rawOptions) => {
- const startTime = getStartTime();
- const { command, escapedCommand } = joinCommand(filePath, rawArguments);
- const verbose = normalizeFdSpecificOption(rawOptions, "verbose");
- const verboseInfo = getVerboseInfo(verbose, escapedCommand, { ...rawOptions });
- logCommand(escapedCommand, verboseInfo);
- return {
- command,
- escapedCommand,
- startTime,
- verboseInfo
- };
-};
-var init_command = __esm(() => {
- init_start();
- init_info();
- init_duration();
- init_escape();
- init_specific();
-});
-
-// node_modules/isexe/windows.js
-var require_windows = __commonJS((exports, module) => {
- module.exports = isexe;
- isexe.sync = sync;
- var fs2 = __require("fs");
- function checkPathExt(path, options2) {
- var pathext = options2.pathExt !== undefined ? options2.pathExt : process.env.PATHEXT;
- if (!pathext) {
- return true;
- }
- pathext = pathext.split(";");
- if (pathext.indexOf("") !== -1) {
- return true;
- }
- for (var i = 0;i < pathext.length; i++) {
- var p = pathext[i].toLowerCase();
- if (p && path.substr(-p.length).toLowerCase() === p) {
- return true;
- }
- }
- return false;
- }
- function checkStat(stat, path, options2) {
- if (!stat.isSymbolicLink() && !stat.isFile()) {
- return false;
- }
- return checkPathExt(path, options2);
- }
- function isexe(path, options2, cb) {
- fs2.stat(path, function(er, stat) {
- cb(er, er ? false : checkStat(stat, path, options2));
- });
- }
- function sync(path, options2) {
- return checkStat(fs2.statSync(path), path, options2);
- }
-});
-
-// node_modules/isexe/mode.js
-var require_mode = __commonJS((exports, module) => {
- module.exports = isexe;
- isexe.sync = sync;
- var fs2 = __require("fs");
- function isexe(path, options2, cb) {
- fs2.stat(path, function(er, stat) {
- cb(er, er ? false : checkStat(stat, options2));
- });
- }
- function sync(path, options2) {
- return checkStat(fs2.statSync(path), options2);
- }
- function checkStat(stat, options2) {
- return stat.isFile() && checkMode(stat, options2);
- }
- function checkMode(stat, options2) {
- var mod2 = stat.mode;
- var uid = stat.uid;
- var gid = stat.gid;
- var myUid = options2.uid !== undefined ? options2.uid : process.getuid && process.getuid();
- var myGid = options2.gid !== undefined ? options2.gid : process.getgid && process.getgid();
- var u = parseInt("100", 8);
- var g = parseInt("010", 8);
- var o = parseInt("001", 8);
- var ug = u | g;
- var ret = mod2 & o || mod2 & g && gid === myGid || mod2 & u && uid === myUid || mod2 & ug && myUid === 0;
- return ret;
- }
-});
-
-// node_modules/isexe/index.js
-var require_isexe = __commonJS((exports, module) => {
- var fs2 = __require("fs");
- var core;
- if (process.platform === "win32" || global.TESTING_WINDOWS) {
- core = require_windows();
- } else {
- core = require_mode();
- }
- module.exports = isexe;
- isexe.sync = sync;
- function isexe(path, options2, cb) {
- if (typeof options2 === "function") {
- cb = options2;
- options2 = {};
- }
- if (!cb) {
- if (typeof Promise !== "function") {
- throw new TypeError("callback not provided");
- }
- return new Promise(function(resolve2, reject) {
- isexe(path, options2 || {}, function(er, is) {
- if (er) {
- reject(er);
- } else {
- resolve2(is);
- }
- });
- });
- }
- core(path, options2 || {}, function(er, is) {
- if (er) {
- if (er.code === "EACCES" || options2 && options2.ignoreErrors) {
- er = null;
- is = false;
- }
- }
- cb(er, is);
- });
- }
- function sync(path, options2) {
- try {
- return core.sync(path, options2 || {});
- } catch (er) {
- if (options2 && options2.ignoreErrors || er.code === "EACCES") {
- return false;
- } else {
- throw er;
- }
- }
- }
-});
-
-// node_modules/which/which.js
-var require_which = __commonJS((exports, module) => {
- var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
- var path = __require("path");
- var COLON = isWindows ? ";" : ":";
- var isexe = require_isexe();
- var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
- var getPathInfo = (cmd, opt) => {
- const colon = opt.colon || COLON;
- const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
- ...isWindows ? [process.cwd()] : [],
- ...(opt.path || process.env.PATH || "").split(colon)
- ];
- const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
- const pathExt = isWindows ? pathExtExe.split(colon) : [""];
- if (isWindows) {
- if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
- pathExt.unshift("");
- }
- return {
- pathEnv,
- pathExt,
- pathExtExe
- };
- };
- var which = (cmd, opt, cb) => {
- if (typeof opt === "function") {
- cb = opt;
- opt = {};
- }
- if (!opt)
- opt = {};
- const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
- const found = [];
- const step = (i) => new Promise((resolve2, reject) => {
- if (i === pathEnv.length)
- return opt.all && found.length ? resolve2(found) : reject(getNotFoundError(cmd));
- const ppRaw = pathEnv[i];
- const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
- const pCmd = path.join(pathPart, cmd);
- const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
- resolve2(subStep(p, i, 0));
- });
- const subStep = (p, i, ii) => new Promise((resolve2, reject) => {
- if (ii === pathExt.length)
- return resolve2(step(i + 1));
- const ext = pathExt[ii];
- isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
- if (!er && is) {
- if (opt.all)
- found.push(p + ext);
- else
- return resolve2(p + ext);
- }
- return resolve2(subStep(p, i, ii + 1));
- });
- });
- return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
- };
- var whichSync = (cmd, opt) => {
- opt = opt || {};
- const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
- const found = [];
- for (let i = 0;i < pathEnv.length; i++) {
- const ppRaw = pathEnv[i];
- const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
- const pCmd = path.join(pathPart, cmd);
- const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
- for (let j = 0;j < pathExt.length; j++) {
- const cur = p + pathExt[j];
- try {
- const is = isexe.sync(cur, { pathExt: pathExtExe });
- if (is) {
- if (opt.all)
- found.push(cur);
- else
- return cur;
- }
- } catch (ex) {}
- }
- }
- if (opt.all && found.length)
- return found;
- if (opt.nothrow)
- return null;
- throw getNotFoundError(cmd);
- };
- module.exports = which;
- which.sync = whichSync;
-});
-
-// node_modules/path-key/index.js
-var require_path_key = __commonJS((exports, module) => {
- var pathKey = (options2 = {}) => {
- const environment = options2.env || process.env;
- const platform2 = options2.platform || process.platform;
- if (platform2 !== "win32") {
- return "PATH";
- }
- return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
- };
- module.exports = pathKey;
- module.exports.default = pathKey;
-});
-
-// node_modules/cross-spawn/lib/util/resolveCommand.js
-var require_resolveCommand = __commonJS((exports, module) => {
- var path = __require("path");
- var which = require_which();
- var getPathKey = require_path_key();
- function resolveCommandAttempt(parsed, withoutPathExt) {
- const env2 = parsed.options.env || process.env;
- const cwd2 = process.cwd();
- const hasCustomCwd = parsed.options.cwd != null;
- const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
- if (shouldSwitchCwd) {
- try {
- process.chdir(parsed.options.cwd);
- } catch (err) {}
- }
- let resolved;
- try {
- resolved = which.sync(parsed.command, {
- path: env2[getPathKey({ env: env2 })],
- pathExt: withoutPathExt ? path.delimiter : undefined
- });
- } catch (e) {} finally {
- if (shouldSwitchCwd) {
- process.chdir(cwd2);
- }
- }
- if (resolved) {
- resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
- }
- return resolved;
- }
- function resolveCommand(parsed) {
- return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
- }
- module.exports = resolveCommand;
-});
-
-// node_modules/cross-spawn/lib/util/escape.js
-var require_escape = __commonJS((exports, module) => {
- var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
- function escapeCommand(arg) {
- arg = arg.replace(metaCharsRegExp, "^$1");
- return arg;
- }
- function escapeArgument(arg, doubleEscapeMetaChars) {
- arg = `${arg}`;
- arg = arg.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\"");
- arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
- arg = `"${arg}"`;
- arg = arg.replace(metaCharsRegExp, "^$1");
- if (doubleEscapeMetaChars) {
- arg = arg.replace(metaCharsRegExp, "^$1");
- }
- return arg;
- }
- exports.command = escapeCommand;
- exports.argument = escapeArgument;
-});
-
-// node_modules/shebang-regex/index.js
-var require_shebang_regex = __commonJS((exports, module) => {
- module.exports = /^#!(.*)/;
-});
-
-// node_modules/shebang-command/index.js
-var require_shebang_command = __commonJS((exports, module) => {
- var shebangRegex = require_shebang_regex();
- module.exports = (string = "") => {
- const match = string.match(shebangRegex);
- if (!match) {
- return null;
- }
- const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
- const binary = path.split("/").pop();
- if (binary === "env") {
- return argument;
- }
- return argument ? `${binary} ${argument}` : binary;
- };
-});
-
-// node_modules/cross-spawn/lib/util/readShebang.js
-var require_readShebang = __commonJS((exports, module) => {
- var fs2 = __require("fs");
- var shebangCommand = require_shebang_command();
- function readShebang(command) {
- const size = 150;
- const buffer = Buffer.alloc(size);
- let fd;
- try {
- fd = fs2.openSync(command, "r");
- fs2.readSync(fd, buffer, 0, size, 0);
- fs2.closeSync(fd);
- } catch (e) {}
- return shebangCommand(buffer.toString());
- }
- module.exports = readShebang;
-});
-
-// node_modules/cross-spawn/lib/parse.js
-var require_parse2 = __commonJS((exports, module) => {
- var path = __require("path");
- var resolveCommand = require_resolveCommand();
- var escape3 = require_escape();
- var readShebang = require_readShebang();
- var isWin = process.platform === "win32";
- var isExecutableRegExp = /\.(?:com|exe)$/i;
- var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
- function detectShebang(parsed) {
- parsed.file = resolveCommand(parsed);
- const shebang = parsed.file && readShebang(parsed.file);
- if (shebang) {
- parsed.args.unshift(parsed.file);
- parsed.command = shebang;
- return resolveCommand(parsed);
- }
- return parsed.file;
- }
- function parseNonShell(parsed) {
- if (!isWin) {
- return parsed;
- }
- const commandFile = detectShebang(parsed);
- const needsShell = !isExecutableRegExp.test(commandFile);
- if (parsed.options.forceShell || needsShell) {
- const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
- parsed.command = path.normalize(parsed.command);
- parsed.command = escape3.command(parsed.command);
- parsed.args = parsed.args.map((arg) => escape3.argument(arg, needsDoubleEscapeMetaChars));
- const shellCommand = [parsed.command].concat(parsed.args).join(" ");
- parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
- parsed.command = process.env.comspec || "cmd.exe";
- parsed.options.windowsVerbatimArguments = true;
- }
- return parsed;
- }
- function parse(command, args, options2) {
- if (args && !Array.isArray(args)) {
- options2 = args;
- args = null;
- }
- args = args ? args.slice(0) : [];
- options2 = Object.assign({}, options2);
- const parsed = {
- command,
- args,
- options: options2,
- file: undefined,
- original: {
- command,
- args
- }
- };
- return options2.shell ? parsed : parseNonShell(parsed);
- }
- module.exports = parse;
-});
-
-// node_modules/cross-spawn/lib/enoent.js
-var require_enoent = __commonJS((exports, module) => {
- var isWin = process.platform === "win32";
- function notFoundError(original, syscall) {
- return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
- code: "ENOENT",
- errno: "ENOENT",
- syscall: `${syscall} ${original.command}`,
- path: original.command,
- spawnargs: original.args
- });
- }
- function hookChildProcess(cp, parsed) {
- if (!isWin) {
- return;
- }
- const originalEmit = cp.emit;
- cp.emit = function(name, arg1) {
- if (name === "exit") {
- const err = verifyENOENT(arg1, parsed);
- if (err) {
- return originalEmit.call(cp, "error", err);
- }
- }
- return originalEmit.apply(cp, arguments);
- };
- }
- function verifyENOENT(status, parsed) {
- if (isWin && status === 1 && !parsed.file) {
- return notFoundError(parsed.original, "spawn");
- }
- return null;
- }
- function verifyENOENTSync(status, parsed) {
- if (isWin && status === 1 && !parsed.file) {
- return notFoundError(parsed.original, "spawnSync");
- }
- return null;
- }
- module.exports = {
- hookChildProcess,
- verifyENOENT,
- verifyENOENTSync,
- notFoundError
- };
-});
-
-// node_modules/cross-spawn/index.js
-var require_cross_spawn = __commonJS((exports, module) => {
- var cp = __require("child_process");
- var parse = require_parse2();
- var enoent = require_enoent();
- function spawn(command, args, options2) {
- const parsed = parse(command, args, options2);
- const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
- enoent.hookChildProcess(spawned, parsed);
- return spawned;
- }
- function spawnSync(command, args, options2) {
- const parsed = parse(command, args, options2);
- const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
- result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
- return result;
- }
- module.exports = spawn;
- module.exports.spawn = spawn;
- module.exports.sync = spawnSync;
- module.exports._parse = parse;
- module.exports._enoent = enoent;
-});
-
-// node_modules/npm-run-path/node_modules/path-key/index.js
-function pathKey(options2 = {}) {
- const {
- env: env2 = process.env,
- platform: platform2 = process.platform
- } = options2;
- if (platform2 !== "win32") {
- return "PATH";
- }
- return Object.keys(env2).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
-}
-
-// node_modules/unicorn-magic/node.js
-import { promisify } from "util";
-import { execFile as execFileCallback, execFileSync as execFileSyncOriginal } from "child_process";
-import path from "path";
-import { fileURLToPath as fileURLToPath2 } from "url";
-function toPath(urlOrPath) {
- return urlOrPath instanceof URL ? fileURLToPath2(urlOrPath) : urlOrPath;
-}
-function traversePathUp(startPath) {
- return {
- *[Symbol.iterator]() {
- let currentPath = path.resolve(toPath(startPath));
- let previousPath;
- while (previousPath !== currentPath) {
- yield currentPath;
- previousPath = currentPath;
- currentPath = path.resolve(currentPath, "..");
- }
- }
- };
-}
-var execFileOriginal, TEN_MEGABYTES_IN_BYTES;
-var init_node = __esm(() => {
- execFileOriginal = promisify(execFileCallback);
- TEN_MEGABYTES_IN_BYTES = 10 * 1024 * 1024;
-});
-
-// node_modules/npm-run-path/index.js
-import process5 from "process";
-import path2 from "path";
-var npmRunPath = ({
- cwd: cwd2 = process5.cwd(),
- path: pathOption = process5.env[pathKey()],
- preferLocal = true,
- execPath = process5.execPath,
- addExecPath = true
-} = {}) => {
- const cwdPath = path2.resolve(toPath(cwd2));
- const result = [];
- const pathParts = pathOption.split(path2.delimiter);
- if (preferLocal) {
- applyPreferLocal(result, pathParts, cwdPath);
- }
- if (addExecPath) {
- applyExecPath(result, pathParts, execPath, cwdPath);
- }
- return pathOption === "" || pathOption === path2.delimiter ? `${result.join(path2.delimiter)}${pathOption}` : [...result, pathOption].join(path2.delimiter);
-}, applyPreferLocal = (result, pathParts, cwdPath) => {
- for (const directory of traversePathUp(cwdPath)) {
- const pathPart = path2.join(directory, "node_modules/.bin");
- if (!pathParts.includes(pathPart)) {
- result.push(pathPart);
- }
- }
-}, applyExecPath = (result, pathParts, execPath, cwdPath) => {
- const pathPart = path2.resolve(cwdPath, toPath(execPath), "..");
- if (!pathParts.includes(pathPart)) {
- result.push(pathPart);
- }
-}, npmRunPathEnv = ({ env: env2 = process5.env, ...options2 } = {}) => {
- env2 = { ...env2 };
- const pathName = pathKey({ env: env2 });
- options2.path = env2[pathName];
- env2[pathName] = npmRunPath(options2);
- return env2;
-};
-var init_npm_run_path = __esm(() => {
- init_node();
-});
-
-// node_modules/execa/lib/return/final-error.js
-var getFinalError = (originalError, message, isSync) => {
- const ErrorClass = isSync ? ExecaSyncError : ExecaError;
- const options2 = originalError instanceof DiscardedError ? {} : { cause: originalError };
- return new ErrorClass(message, options2);
-}, DiscardedError, setErrorName = (ErrorClass, value) => {
- Object.defineProperty(ErrorClass.prototype, "name", {
- value,
- writable: true,
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(ErrorClass.prototype, execaErrorSymbol, {
- value: true,
- writable: false,
- enumerable: false,
- configurable: false
- });
-}, isExecaError = (error) => isErrorInstance(error) && (execaErrorSymbol in error), execaErrorSymbol, isErrorInstance = (value) => Object.prototype.toString.call(value) === "[object Error]", ExecaError, ExecaSyncError;
-var init_final_error = __esm(() => {
- DiscardedError = class DiscardedError extends Error {
- };
- execaErrorSymbol = Symbol("isExecaError");
- ExecaError = class ExecaError extends Error {
- };
- setErrorName(ExecaError, ExecaError.name);
- ExecaSyncError = class ExecaSyncError extends Error {
- };
- setErrorName(ExecaSyncError, ExecaSyncError.name);
-});
-
-// node_modules/human-signals/build/src/realtime.js
-var getRealtimeSignals = () => {
- const length = SIGRTMAX - SIGRTMIN + 1;
- return Array.from({ length }, getRealtimeSignal);
-}, getRealtimeSignal = (value, index2) => ({
- name: `SIGRT${index2 + 1}`,
- number: SIGRTMIN + index2,
- action: "terminate",
- description: "Application-specific signal (realtime)",
- standard: "posix"
-}), SIGRTMIN = 34, SIGRTMAX = 64;
-
-// node_modules/human-signals/build/src/core.js
-var SIGNALS;
-var init_core3 = __esm(() => {
- SIGNALS = [
- {
- name: "SIGHUP",
- number: 1,
- action: "terminate",
- description: "Terminal closed",
- standard: "posix"
- },
- {
- name: "SIGINT",
- number: 2,
- action: "terminate",
- description: "User interruption with CTRL-C",
- standard: "ansi"
- },
- {
- name: "SIGQUIT",
- number: 3,
- action: "core",
- description: "User interruption with CTRL-\\",
- standard: "posix"
- },
- {
- name: "SIGILL",
- number: 4,
- action: "core",
- description: "Invalid machine instruction",
- standard: "ansi"
- },
- {
- name: "SIGTRAP",
- number: 5,
- action: "core",
- description: "Debugger breakpoint",
- standard: "posix"
- },
- {
- name: "SIGABRT",
- number: 6,
- action: "core",
- description: "Aborted",
- standard: "ansi"
- },
- {
- name: "SIGIOT",
- number: 6,
- action: "core",
- description: "Aborted",
- standard: "bsd"
- },
- {
- name: "SIGBUS",
- number: 7,
- action: "core",
- description: "Bus error due to misaligned, non-existing address or paging error",
- standard: "bsd"
- },
- {
- name: "SIGEMT",
- number: 7,
- action: "terminate",
- description: "Command should be emulated but is not implemented",
- standard: "other"
- },
- {
- name: "SIGFPE",
- number: 8,
- action: "core",
- description: "Floating point arithmetic error",
- standard: "ansi"
- },
- {
- name: "SIGKILL",
- number: 9,
- action: "terminate",
- description: "Forced termination",
- standard: "posix",
- forced: true
- },
- {
- name: "SIGUSR1",
- number: 10,
- action: "terminate",
- description: "Application-specific signal",
- standard: "posix"
- },
- {
- name: "SIGSEGV",
- number: 11,
- action: "core",
- description: "Segmentation fault",
- standard: "ansi"
- },
- {
- name: "SIGUSR2",
- number: 12,
- action: "terminate",
- description: "Application-specific signal",
- standard: "posix"
- },
- {
- name: "SIGPIPE",
- number: 13,
- action: "terminate",
- description: "Broken pipe or socket",
- standard: "posix"
- },
- {
- name: "SIGALRM",
- number: 14,
- action: "terminate",
- description: "Timeout or timer",
- standard: "posix"
- },
- {
- name: "SIGTERM",
- number: 15,
- action: "terminate",
- description: "Termination",
- standard: "ansi"
- },
- {
- name: "SIGSTKFLT",
- number: 16,
- action: "terminate",
- description: "Stack is empty or overflowed",
- standard: "other"
- },
- {
- name: "SIGCHLD",
- number: 17,
- action: "ignore",
- description: "Child process terminated, paused or unpaused",
- standard: "posix"
- },
- {
- name: "SIGCLD",
- number: 17,
- action: "ignore",
- description: "Child process terminated, paused or unpaused",
- standard: "other"
- },
- {
- name: "SIGCONT",
- number: 18,
- action: "unpause",
- description: "Unpaused",
- standard: "posix",
- forced: true
- },
- {
- name: "SIGSTOP",
- number: 19,
- action: "pause",
- description: "Paused",
- standard: "posix",
- forced: true
- },
- {
- name: "SIGTSTP",
- number: 20,
- action: "pause",
- description: 'Paused using CTRL-Z or "suspend"',
- standard: "posix"
- },
- {
- name: "SIGTTIN",
- number: 21,
- action: "pause",
- description: "Background process cannot read terminal input",
- standard: "posix"
- },
- {
- name: "SIGBREAK",
- number: 21,
- action: "terminate",
- description: "User interruption with CTRL-BREAK",
- standard: "other"
- },
- {
- name: "SIGTTOU",
- number: 22,
- action: "pause",
- description: "Background process cannot write to terminal output",
- standard: "posix"
- },
- {
- name: "SIGURG",
- number: 23,
- action: "ignore",
- description: "Socket received out-of-band data",
- standard: "bsd"
- },
- {
- name: "SIGXCPU",
- number: 24,
- action: "core",
- description: "Process timed out",
- standard: "bsd"
- },
- {
- name: "SIGXFSZ",
- number: 25,
- action: "core",
- description: "File too big",
- standard: "bsd"
- },
- {
- name: "SIGVTALRM",
- number: 26,
- action: "terminate",
- description: "Timeout or timer",
- standard: "bsd"
- },
- {
- name: "SIGPROF",
- number: 27,
- action: "terminate",
- description: "Timeout or timer",
- standard: "bsd"
- },
- {
- name: "SIGWINCH",
- number: 28,
- action: "ignore",
- description: "Terminal window size changed",
- standard: "bsd"
- },
- {
- name: "SIGIO",
- number: 29,
- action: "terminate",
- description: "I/O is available",
- standard: "other"
- },
- {
- name: "SIGPOLL",
- number: 29,
- action: "terminate",
- description: "Watched event",
- standard: "other"
- },
- {
- name: "SIGINFO",
- number: 29,
- action: "ignore",
- description: "Request for process information",
- standard: "other"
- },
- {
- name: "SIGPWR",
- number: 30,
- action: "terminate",
- description: "Device running out of power",
- standard: "systemv"
- },
- {
- name: "SIGSYS",
- number: 31,
- action: "core",
- description: "Invalid system call",
- standard: "other"
- },
- {
- name: "SIGUNUSED",
- number: 31,
- action: "terminate",
- description: "Invalid system call",
- standard: "other"
- }
- ];
-});
-
-// node_modules/human-signals/build/src/signals.js
-import { constants } from "os";
-var getSignals = () => {
- const realtimeSignals = getRealtimeSignals();
- const signals = [...SIGNALS, ...realtimeSignals].map(normalizeSignal);
- return signals;
-}, normalizeSignal = ({
- name,
- number: defaultNumber,
- description,
- action,
- forced = false,
- standard
-}) => {
- const {
- signals: { [name]: constantSignal }
- } = constants;
- const supported = constantSignal !== undefined;
- const number = supported ? constantSignal : defaultNumber;
- return { name, number, description, supported, action, forced, standard };
-};
-var init_signals = __esm(() => {
- init_core3();
-});
-
-// node_modules/human-signals/build/src/main.js
-import { constants as constants2 } from "os";
-var getSignalsByName = () => {
- const signals = getSignals();
- return Object.fromEntries(signals.map(getSignalByName));
-}, getSignalByName = ({
- name,
- number,
- description,
- supported,
- action,
- forced,
- standard
-}) => [name, { name, number, description, supported, action, forced, standard }], signalsByName, getSignalsByNumber = () => {
- const signals = getSignals();
- const length = SIGRTMAX + 1;
- const signalsA = Array.from({ length }, (value, number) => getSignalByNumber(number, signals));
- return Object.assign({}, ...signalsA);
-}, getSignalByNumber = (number, signals) => {
- const signal = findSignalByNumber(number, signals);
- if (signal === undefined) {
- return {};
- }
- const { name, description, supported, action, forced, standard } = signal;
- return {
- [number]: {
- name,
- number,
- description,
- supported,
- action,
- forced,
- standard
- }
- };
-}, findSignalByNumber = (number, signals) => {
- const signal = signals.find(({ name }) => constants2.signals[name] === number);
- if (signal !== undefined) {
- return signal;
- }
- return signals.find((signalA) => signalA.number === number);
-}, signalsByNumber;
-var init_main = __esm(() => {
- init_signals();
- signalsByName = getSignalsByName();
- signalsByNumber = getSignalsByNumber();
-});
-
-// node_modules/execa/lib/terminate/signal.js
-import { constants as constants3 } from "os";
-var normalizeKillSignal = (killSignal) => {
- const optionName = "option `killSignal`";
- if (killSignal === 0) {
- throw new TypeError(`Invalid ${optionName}: 0 cannot be used.`);
- }
- return normalizeSignal2(killSignal, optionName);
-}, normalizeSignalArgument = (signal) => signal === 0 ? signal : normalizeSignal2(signal, "`subprocess.kill()`'s argument"), normalizeSignal2 = (signalNameOrInteger, optionName) => {
- if (Number.isInteger(signalNameOrInteger)) {
- return normalizeSignalInteger(signalNameOrInteger, optionName);
- }
- if (typeof signalNameOrInteger === "string") {
- return normalizeSignalName(signalNameOrInteger, optionName);
- }
- throw new TypeError(`Invalid ${optionName} ${String(signalNameOrInteger)}: it must be a string or an integer.
-${getAvailableSignals()}`);
-}, normalizeSignalInteger = (signalInteger, optionName) => {
- if (signalsIntegerToName.has(signalInteger)) {
- return signalsIntegerToName.get(signalInteger);
- }
- throw new TypeError(`Invalid ${optionName} ${signalInteger}: this signal integer does not exist.
-${getAvailableSignals()}`);
-}, getSignalsIntegerToName = () => new Map(Object.entries(constants3.signals).reverse().map(([signalName, signalInteger]) => [signalInteger, signalName])), signalsIntegerToName, normalizeSignalName = (signalName, optionName) => {
- if (signalName in constants3.signals) {
- return signalName;
- }
- if (signalName.toUpperCase() in constants3.signals) {
- throw new TypeError(`Invalid ${optionName} '${signalName}': please rename it to '${signalName.toUpperCase()}'.`);
- }
- throw new TypeError(`Invalid ${optionName} '${signalName}': this signal name does not exist.
-${getAvailableSignals()}`);
-}, getAvailableSignals = () => `Available signal names: ${getAvailableSignalNames()}.
-Available signal numbers: ${getAvailableSignalIntegers()}.`, getAvailableSignalNames = () => Object.keys(constants3.signals).sort().map((signalName) => `'${signalName}'`).join(", "), getAvailableSignalIntegers = () => [...new Set(Object.values(constants3.signals).sort((signalInteger, signalIntegerTwo) => signalInteger - signalIntegerTwo))].join(", "), getSignalDescription = (signal) => signalsByName[signal].description;
-var init_signal = __esm(() => {
- init_main();
- signalsIntegerToName = getSignalsIntegerToName();
-});
-
-// node_modules/execa/lib/terminate/kill.js
-import { setTimeout as setTimeout2 } from "timers/promises";
-var normalizeForceKillAfterDelay = (forceKillAfterDelay) => {
- if (forceKillAfterDelay === false) {
- return forceKillAfterDelay;
- }
- if (forceKillAfterDelay === true) {
- return DEFAULT_FORCE_KILL_TIMEOUT;
- }
- if (!Number.isFinite(forceKillAfterDelay) || forceKillAfterDelay < 0) {
- throw new TypeError(`Expected the \`forceKillAfterDelay\` option to be a non-negative integer, got \`${forceKillAfterDelay}\` (${typeof forceKillAfterDelay})`);
- }
- return forceKillAfterDelay;
-}, DEFAULT_FORCE_KILL_TIMEOUT, subprocessKill = ({ kill, options: { forceKillAfterDelay, killSignal }, onInternalError, context, controller }, signalOrError, errorArgument) => {
- const { signal, error } = parseKillArguments(signalOrError, errorArgument, killSignal);
- emitKillError(error, onInternalError);
- const killResult = kill(signal);
- setKillTimeout({
- kill,
- signal,
- forceKillAfterDelay,
- killSignal,
- killResult,
- context,
- controller
- });
- return killResult;
-}, parseKillArguments = (signalOrError, errorArgument, killSignal) => {
- const [signal = killSignal, error] = isErrorInstance(signalOrError) ? [undefined, signalOrError] : [signalOrError, errorArgument];
- if (typeof signal !== "string" && !Number.isInteger(signal)) {
- throw new TypeError(`The first argument must be an error instance or a signal name string/integer: ${String(signal)}`);
- }
- if (error !== undefined && !isErrorInstance(error)) {
- throw new TypeError(`The second argument is optional. If specified, it must be an error instance: ${error}`);
- }
- return { signal: normalizeSignalArgument(signal), error };
-}, emitKillError = (error, onInternalError) => {
- if (error !== undefined) {
- onInternalError.reject(error);
- }
-}, setKillTimeout = async ({ kill, signal, forceKillAfterDelay, killSignal, killResult, context, controller }) => {
- if (signal === killSignal && killResult) {
- killOnTimeout({
- kill,
- forceKillAfterDelay,
- context,
- controllerSignal: controller.signal
- });
- }
-}, killOnTimeout = async ({ kill, forceKillAfterDelay, context, controllerSignal }) => {
- if (forceKillAfterDelay === false) {
- return;
- }
- try {
- await setTimeout2(forceKillAfterDelay, undefined, { signal: controllerSignal });
- if (kill("SIGKILL")) {
- context.isForcefullyTerminated ??= true;
- }
- } catch {}
-};
-var init_kill = __esm(() => {
- init_final_error();
- init_signal();
- DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
-});
-
-// node_modules/execa/lib/utils/abort-signal.js
-import { once } from "events";
-var onAbortedSignal = async (mainSignal, stopSignal) => {
- if (!mainSignal.aborted) {
- await once(mainSignal, "abort", { signal: stopSignal });
- }
-};
-var init_abort_signal = () => {};
-
-// node_modules/execa/lib/terminate/cancel.js
-var validateCancelSignal = ({ cancelSignal }) => {
- if (cancelSignal !== undefined && Object.prototype.toString.call(cancelSignal) !== "[object AbortSignal]") {
- throw new Error(`The \`cancelSignal\` option must be an AbortSignal: ${String(cancelSignal)}`);
- }
-}, throwOnCancel = ({ subprocess, cancelSignal, gracefulCancel, context, controller }) => cancelSignal === undefined || gracefulCancel ? [] : [terminateOnCancel(subprocess, cancelSignal, context, controller)], terminateOnCancel = async (subprocess, cancelSignal, context, { signal }) => {
- await onAbortedSignal(cancelSignal, signal);
- context.terminationReason ??= "cancel";
- subprocess.kill();
- throw cancelSignal.reason;
-};
-var init_cancel = __esm(() => {
- init_abort_signal();
-});
-
-// node_modules/execa/lib/ipc/validation.js
-var validateIpcMethod = ({ methodName, isSubprocess, ipc, isConnected }) => {
- validateIpcOption(methodName, isSubprocess, ipc);
- validateConnection(methodName, isSubprocess, isConnected);
-}, validateIpcOption = (methodName, isSubprocess, ipc) => {
- if (!ipc) {
- throw new Error(`${getMethodName(methodName, isSubprocess)} can only be used if the \`ipc\` option is \`true\`.`);
- }
-}, validateConnection = (methodName, isSubprocess, isConnected) => {
- if (!isConnected) {
- throw new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);
- }
-}, throwOnEarlyDisconnect = (isSubprocess) => {
- throw new Error(`${getMethodName("getOneMessage", isSubprocess)} could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);
-}, throwOnStrictDeadlockError = (isSubprocess) => {
- throw new Error(`${getMethodName("sendMessage", isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is sending a message too, instead of listening to incoming messages.
-This can be fixed by both sending a message and listening to incoming messages at the same time:
-
-const [receivedMessage] = await Promise.all([
- ${getMethodName("getOneMessage", isSubprocess)},
- ${getMethodName("sendMessage", isSubprocess, "message, {strict: true}")},
-]);`);
-}, getStrictResponseError = (error, isSubprocess) => new Error(`${getMethodName("sendMessage", isSubprocess)} failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, { cause: error }), throwOnMissingStrict = (isSubprocess) => {
- throw new Error(`${getMethodName("sendMessage", isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is not listening to incoming messages.`);
-}, throwOnStrictDisconnect = (isSubprocess) => {
- throw new Error(`${getMethodName("sendMessage", isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} exited without listening to incoming messages.`);
-}, getAbortDisconnectError = () => new Error(`\`cancelSignal\` aborted: the ${getOtherProcessName(true)} disconnected.`), throwOnMissingParent = () => {
- throw new Error("`getCancelSignal()` cannot be used without setting the `cancelSignal` subprocess option.");
-}, handleEpipeError = ({ error, methodName, isSubprocess }) => {
- if (error.code === "EPIPE") {
- throw new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} is disconnecting.`, { cause: error });
- }
-}, handleSerializationError = ({ error, methodName, isSubprocess, message }) => {
- if (isSerializationError(error)) {
- throw new Error(`${getMethodName(methodName, isSubprocess)}'s argument type is invalid: the message cannot be serialized: ${String(message)}.`, { cause: error });
- }
-}, isSerializationError = ({ code, message }) => SERIALIZATION_ERROR_CODES.has(code) || SERIALIZATION_ERROR_MESSAGES.some((serializationErrorMessage) => message.includes(serializationErrorMessage)), SERIALIZATION_ERROR_CODES, SERIALIZATION_ERROR_MESSAGES, getMethodName = (methodName, isSubprocess, parameters = "") => methodName === "cancelSignal" ? "`cancelSignal`'s `controller.abort()`" : `${getNamespaceName(isSubprocess)}${methodName}(${parameters})`, getNamespaceName = (isSubprocess) => isSubprocess ? "" : "subprocess.", getOtherProcessName = (isSubprocess) => isSubprocess ? "parent process" : "subprocess", disconnect = (anyProcess) => {
- if (anyProcess.connected) {
- anyProcess.disconnect();
- }
-};
-var init_validation = __esm(() => {
- SERIALIZATION_ERROR_CODES = new Set([
- "ERR_MISSING_ARGS",
- "ERR_INVALID_ARG_TYPE"
- ]);
- SERIALIZATION_ERROR_MESSAGES = [
- "could not be cloned",
- "circular structure",
- "call stack size exceeded"
- ];
-});
-
-// node_modules/execa/lib/utils/deferred.js
-var createDeferred = () => {
- const methods = {};
- const promise = new Promise((resolve2, reject) => {
- Object.assign(methods, { resolve: resolve2, reject });
- });
- return Object.assign(promise, methods);
-};
-
-// node_modules/execa/lib/arguments/fd-options.js
-var getToStream = (destination, to = "stdin") => {
- const isWritable = true;
- const { options: options2, fileDescriptors } = SUBPROCESS_OPTIONS.get(destination);
- const fdNumber = getFdNumber(fileDescriptors, to, isWritable);
- const destinationStream = destination.stdio[fdNumber];
- if (destinationStream === null) {
- throw new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options2, isWritable));
- }
- return destinationStream;
-}, getFromStream = (source, from = "stdout") => {
- const isWritable = false;
- const { options: options2, fileDescriptors } = SUBPROCESS_OPTIONS.get(source);
- const fdNumber = getFdNumber(fileDescriptors, from, isWritable);
- const sourceStream = fdNumber === "all" ? source.all : source.stdio[fdNumber];
- if (sourceStream === null || sourceStream === undefined) {
- throw new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options2, isWritable));
- }
- return sourceStream;
-}, SUBPROCESS_OPTIONS, getFdNumber = (fileDescriptors, fdName, isWritable) => {
- const fdNumber = parseFdNumber(fdName, isWritable);
- validateFdNumber(fdNumber, fdName, isWritable, fileDescriptors);
- return fdNumber;
-}, parseFdNumber = (fdName, isWritable) => {
- const fdNumber = parseFd(fdName);
- if (fdNumber !== undefined) {
- return fdNumber;
- }
- const { validOptions, defaultValue } = isWritable ? { validOptions: '"stdin"', defaultValue: "stdin" } : { validOptions: '"stdout", "stderr", "all"', defaultValue: "stdout" };
- throw new TypeError(`"${getOptionName(isWritable)}" must not be "${fdName}".
-It must be ${validOptions} or "fd3", "fd4" (and so on).
-It is optional and defaults to "${defaultValue}".`);
-}, validateFdNumber = (fdNumber, fdName, isWritable, fileDescriptors) => {
- const fileDescriptor = fileDescriptors[getUsedDescriptor(fdNumber)];
- if (fileDescriptor === undefined) {
- throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. That file descriptor does not exist.
-Please set the "stdio" option to ensure that file descriptor exists.`);
- }
- if (fileDescriptor.direction === "input" && !isWritable) {
- throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a readable stream, not writable.`);
- }
- if (fileDescriptor.direction !== "input" && isWritable) {
- throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a writable stream, not readable.`);
- }
-}, getInvalidStdioOptionMessage = (fdNumber, fdName, options2, isWritable) => {
- if (fdNumber === "all" && !options2.all) {
- return `The "all" option must be true to use "from: 'all'".`;
- }
- const { optionName, optionValue } = getInvalidStdioOption(fdNumber, options2);
- return `The "${optionName}: ${serializeOptionValue(optionValue)}" option is incompatible with using "${getOptionName(isWritable)}: ${serializeOptionValue(fdName)}".
-Please set this option with "pipe" instead.`;
-}, getInvalidStdioOption = (fdNumber, { stdin, stdout, stderr, stdio }) => {
- const usedDescriptor = getUsedDescriptor(fdNumber);
- if (usedDescriptor === 0 && stdin !== undefined) {
- return { optionName: "stdin", optionValue: stdin };
- }
- if (usedDescriptor === 1 && stdout !== undefined) {
- return { optionName: "stdout", optionValue: stdout };
- }
- if (usedDescriptor === 2 && stderr !== undefined) {
- return { optionName: "stderr", optionValue: stderr };
- }
- return { optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor] };
-}, getUsedDescriptor = (fdNumber) => fdNumber === "all" ? 1 : fdNumber, getOptionName = (isWritable) => isWritable ? "to" : "from", serializeOptionValue = (value) => {
- if (typeof value === "string") {
- return `'${value}'`;
- }
- return typeof value === "number" ? `${value}` : "Stream";
-};
-var init_fd_options = __esm(() => {
- init_specific();
- SUBPROCESS_OPTIONS = new WeakMap;
-});
-
-// node_modules/execa/lib/utils/max-listeners.js
-import { addAbortListener } from "events";
-var incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {
- const maxListeners = eventEmitter.getMaxListeners();
- if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {
- return;
- }
- eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement);
- addAbortListener(signal, () => {
- eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);
- });
-};
-var init_max_listeners = () => {};
-
-// node_modules/execa/lib/ipc/reference.js
-var addReference = (channel, reference) => {
- if (reference) {
- addReferenceCount(channel);
- }
-}, addReferenceCount = (channel) => {
- channel.refCounted();
-}, removeReference = (channel, reference) => {
- if (reference) {
- removeReferenceCount(channel);
- }
-}, removeReferenceCount = (channel) => {
- channel.unrefCounted();
-}, undoAddedReferences = (channel, isSubprocess) => {
- if (isSubprocess) {
- removeReferenceCount(channel);
- removeReferenceCount(channel);
- }
-}, redoAddedReferences = (channel, isSubprocess) => {
- if (isSubprocess) {
- addReferenceCount(channel);
- addReferenceCount(channel);
- }
-};
-
-// node_modules/execa/lib/ipc/incoming.js
-import { once as once2 } from "events";
-import { scheduler } from "timers/promises";
-var onMessage = async ({ anyProcess, channel, isSubprocess, ipcEmitter }, wrappedMessage) => {
- if (handleStrictResponse(wrappedMessage) || handleAbort(wrappedMessage)) {
- return;
- }
- if (!INCOMING_MESSAGES.has(anyProcess)) {
- INCOMING_MESSAGES.set(anyProcess, []);
- }
- const incomingMessages = INCOMING_MESSAGES.get(anyProcess);
- incomingMessages.push(wrappedMessage);
- if (incomingMessages.length > 1) {
- return;
- }
- while (incomingMessages.length > 0) {
- await waitForOutgoingMessages(anyProcess, ipcEmitter, wrappedMessage);
- await scheduler.yield();
- const message = await handleStrictRequest({
- wrappedMessage: incomingMessages[0],
- anyProcess,
- channel,
- isSubprocess,
- ipcEmitter
- });
- incomingMessages.shift();
- ipcEmitter.emit("message", message);
- ipcEmitter.emit("message:done");
- }
-}, onDisconnect = async ({ anyProcess, channel, isSubprocess, ipcEmitter, boundOnMessage }) => {
- abortOnDisconnect();
- const incomingMessages = INCOMING_MESSAGES.get(anyProcess);
- while (incomingMessages?.length > 0) {
- await once2(ipcEmitter, "message:done");
- }
- anyProcess.removeListener("message", boundOnMessage);
- redoAddedReferences(channel, isSubprocess);
- ipcEmitter.connected = false;
- ipcEmitter.emit("disconnect");
-}, INCOMING_MESSAGES;
-var init_incoming = __esm(() => {
- init_outgoing();
- init_strict();
- init_graceful();
- INCOMING_MESSAGES = new WeakMap;
-});
-
-// node_modules/execa/lib/ipc/forward.js
-import { EventEmitter } from "events";
-var getIpcEmitter = (anyProcess, channel, isSubprocess) => {
- if (IPC_EMITTERS.has(anyProcess)) {
- return IPC_EMITTERS.get(anyProcess);
- }
- const ipcEmitter = new EventEmitter;
- ipcEmitter.connected = true;
- IPC_EMITTERS.set(anyProcess, ipcEmitter);
- forwardEvents({
- ipcEmitter,
- anyProcess,
- channel,
- isSubprocess
- });
- return ipcEmitter;
-}, IPC_EMITTERS, forwardEvents = ({ ipcEmitter, anyProcess, channel, isSubprocess }) => {
- const boundOnMessage = onMessage.bind(undefined, {
- anyProcess,
- channel,
- isSubprocess,
- ipcEmitter
- });
- anyProcess.on("message", boundOnMessage);
- anyProcess.once("disconnect", onDisconnect.bind(undefined, {
- anyProcess,
- channel,
- isSubprocess,
- ipcEmitter,
- boundOnMessage
- }));
- undoAddedReferences(channel, isSubprocess);
-}, isConnected = (anyProcess) => {
- const ipcEmitter = IPC_EMITTERS.get(anyProcess);
- return ipcEmitter === undefined ? anyProcess.channel !== null : ipcEmitter.connected;
-};
-var init_forward = __esm(() => {
- init_incoming();
- IPC_EMITTERS = new WeakMap;
-});
-
-// node_modules/execa/lib/ipc/strict.js
-import { once as once3 } from "events";
-var handleSendStrict = ({ anyProcess, channel, isSubprocess, message, strict }) => {
- if (!strict) {
- return message;
- }
- const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);
- const hasListeners = hasMessageListeners(anyProcess, ipcEmitter);
- return {
- id: count++,
- type: REQUEST_TYPE,
- message,
- hasListeners
- };
-}, count = 0n, validateStrictDeadlock = (outgoingMessages, wrappedMessage) => {
- if (wrappedMessage?.type !== REQUEST_TYPE || wrappedMessage.hasListeners) {
- return;
- }
- for (const { id } of outgoingMessages) {
- if (id !== undefined) {
- STRICT_RESPONSES[id].resolve({ isDeadlock: true, hasListeners: false });
- }
- }
-}, handleStrictRequest = async ({ wrappedMessage, anyProcess, channel, isSubprocess, ipcEmitter }) => {
- if (wrappedMessage?.type !== REQUEST_TYPE || !anyProcess.connected) {
- return wrappedMessage;
- }
- const { id, message } = wrappedMessage;
- const response = { id, type: RESPONSE_TYPE, message: hasMessageListeners(anyProcess, ipcEmitter) };
- try {
- await sendMessage({
- anyProcess,
- channel,
- isSubprocess,
- ipc: true
- }, response);
- } catch (error) {
- ipcEmitter.emit("strict:error", error);
- }
- return message;
-}, handleStrictResponse = (wrappedMessage) => {
- if (wrappedMessage?.type !== RESPONSE_TYPE) {
- return false;
- }
- const { id, message: hasListeners } = wrappedMessage;
- STRICT_RESPONSES[id]?.resolve({ isDeadlock: false, hasListeners });
- return true;
-}, waitForStrictResponse = async (wrappedMessage, anyProcess, isSubprocess) => {
- if (wrappedMessage?.type !== REQUEST_TYPE) {
- return;
- }
- const deferred = createDeferred();
- STRICT_RESPONSES[wrappedMessage.id] = deferred;
- const controller = new AbortController;
- try {
- const { isDeadlock, hasListeners } = await Promise.race([
- deferred,
- throwOnDisconnect(anyProcess, isSubprocess, controller)
- ]);
- if (isDeadlock) {
- throwOnStrictDeadlockError(isSubprocess);
- }
- if (!hasListeners) {
- throwOnMissingStrict(isSubprocess);
- }
- } finally {
- controller.abort();
- delete STRICT_RESPONSES[wrappedMessage.id];
- }
-}, STRICT_RESPONSES, throwOnDisconnect = async (anyProcess, isSubprocess, { signal }) => {
- incrementMaxListeners(anyProcess, 1, signal);
- await once3(anyProcess, "disconnect", { signal });
- throwOnStrictDisconnect(isSubprocess);
-}, REQUEST_TYPE = "execa:ipc:request", RESPONSE_TYPE = "execa:ipc:response";
-var init_strict = __esm(() => {
- init_max_listeners();
- init_send();
- init_validation();
- init_forward();
- init_outgoing();
- STRICT_RESPONSES = {};
-});
-
-// node_modules/execa/lib/ipc/outgoing.js
-var startSendMessage = (anyProcess, wrappedMessage, strict) => {
- if (!OUTGOING_MESSAGES.has(anyProcess)) {
- OUTGOING_MESSAGES.set(anyProcess, new Set);
- }
- const outgoingMessages = OUTGOING_MESSAGES.get(anyProcess);
- const onMessageSent = createDeferred();
- const id = strict ? wrappedMessage.id : undefined;
- const outgoingMessage = { onMessageSent, id };
- outgoingMessages.add(outgoingMessage);
- return { outgoingMessages, outgoingMessage };
-}, endSendMessage = ({ outgoingMessages, outgoingMessage }) => {
- outgoingMessages.delete(outgoingMessage);
- outgoingMessage.onMessageSent.resolve();
-}, waitForOutgoingMessages = async (anyProcess, ipcEmitter, wrappedMessage) => {
- while (!hasMessageListeners(anyProcess, ipcEmitter) && OUTGOING_MESSAGES.get(anyProcess)?.size > 0) {
- const outgoingMessages = [...OUTGOING_MESSAGES.get(anyProcess)];
- validateStrictDeadlock(outgoingMessages, wrappedMessage);
- await Promise.all(outgoingMessages.map(({ onMessageSent }) => onMessageSent));
- }
-}, OUTGOING_MESSAGES, hasMessageListeners = (anyProcess, ipcEmitter) => ipcEmitter.listenerCount("message") > getMinListenerCount(anyProcess), getMinListenerCount = (anyProcess) => SUBPROCESS_OPTIONS.has(anyProcess) && !getFdSpecificValue(SUBPROCESS_OPTIONS.get(anyProcess).options.buffer, "ipc") ? 1 : 0;
-var init_outgoing = __esm(() => {
- init_specific();
- init_fd_options();
- init_strict();
- OUTGOING_MESSAGES = new WeakMap;
-});
-
-// node_modules/execa/lib/ipc/send.js
-import { promisify as promisify2 } from "util";
-var sendMessage = ({ anyProcess, channel, isSubprocess, ipc }, message, { strict = false } = {}) => {
- const methodName = "sendMessage";
- validateIpcMethod({
- methodName,
- isSubprocess,
- ipc,
- isConnected: anyProcess.connected
- });
- return sendMessageAsync({
- anyProcess,
- channel,
- methodName,
- isSubprocess,
- message,
- strict
- });
-}, sendMessageAsync = async ({ anyProcess, channel, methodName, isSubprocess, message, strict }) => {
- const wrappedMessage = handleSendStrict({
- anyProcess,
- channel,
- isSubprocess,
- message,
- strict
- });
- const outgoingMessagesState = startSendMessage(anyProcess, wrappedMessage, strict);
- try {
- await sendOneMessage({
- anyProcess,
- methodName,
- isSubprocess,
- wrappedMessage,
- message
- });
- } catch (error) {
- disconnect(anyProcess);
- throw error;
- } finally {
- endSendMessage(outgoingMessagesState);
- }
-}, sendOneMessage = async ({ anyProcess, methodName, isSubprocess, wrappedMessage, message }) => {
- const sendMethod = getSendMethod(anyProcess);
- try {
- await Promise.all([
- waitForStrictResponse(wrappedMessage, anyProcess, isSubprocess),
- sendMethod(wrappedMessage)
- ]);
- } catch (error) {
- handleEpipeError({ error, methodName, isSubprocess });
- handleSerializationError({
- error,
- methodName,
- isSubprocess,
- message
- });
- throw error;
- }
-}, getSendMethod = (anyProcess) => {
- if (PROCESS_SEND_METHODS.has(anyProcess)) {
- return PROCESS_SEND_METHODS.get(anyProcess);
- }
- const sendMethod = promisify2(anyProcess.send.bind(anyProcess));
- PROCESS_SEND_METHODS.set(anyProcess, sendMethod);
- return sendMethod;
-}, PROCESS_SEND_METHODS;
-var init_send = __esm(() => {
- init_validation();
- init_outgoing();
- init_strict();
- PROCESS_SEND_METHODS = new WeakMap;
-});
-
-// node_modules/execa/lib/ipc/graceful.js
-import { scheduler as scheduler2 } from "timers/promises";
-var sendAbort = (subprocess, message) => {
- const methodName = "cancelSignal";
- validateConnection(methodName, false, subprocess.connected);
- return sendOneMessage({
- anyProcess: subprocess,
- methodName,
- isSubprocess: false,
- wrappedMessage: { type: GRACEFUL_CANCEL_TYPE, message },
- message
- });
-}, getCancelSignal = async ({ anyProcess, channel, isSubprocess, ipc }) => {
- await startIpc({
- anyProcess,
- channel,
- isSubprocess,
- ipc
- });
- return cancelController.signal;
-}, startIpc = async ({ anyProcess, channel, isSubprocess, ipc }) => {
- if (cancelListening) {
- return;
- }
- cancelListening = true;
- if (!ipc) {
- throwOnMissingParent();
- return;
- }
- if (channel === null) {
- abortOnDisconnect();
- return;
- }
- getIpcEmitter(anyProcess, channel, isSubprocess);
- await scheduler2.yield();
-}, cancelListening = false, handleAbort = (wrappedMessage) => {
- if (wrappedMessage?.type !== GRACEFUL_CANCEL_TYPE) {
- return false;
- }
- cancelController.abort(wrappedMessage.message);
- return true;
-}, GRACEFUL_CANCEL_TYPE = "execa:ipc:cancel", abortOnDisconnect = () => {
- cancelController.abort(getAbortDisconnectError());
-}, cancelController;
-var init_graceful = __esm(() => {
- init_send();
- init_forward();
- init_validation();
- cancelController = new AbortController;
-});
-
-// node_modules/execa/lib/terminate/graceful.js
-var validateGracefulCancel = ({ gracefulCancel, cancelSignal, ipc, serialization }) => {
- if (!gracefulCancel) {
- return;
- }
- if (cancelSignal === undefined) {
- throw new Error("The `cancelSignal` option must be defined when setting the `gracefulCancel` option.");
- }
- if (!ipc) {
- throw new Error("The `ipc` option cannot be false when setting the `gracefulCancel` option.");
- }
- if (serialization === "json") {
- throw new Error("The `serialization` option cannot be 'json' when setting the `gracefulCancel` option.");
- }
-}, throwOnGracefulCancel = ({
- subprocess,
- cancelSignal,
- gracefulCancel,
- forceKillAfterDelay,
- context,
- controller
-}) => gracefulCancel ? [sendOnAbort({
- subprocess,
- cancelSignal,
- forceKillAfterDelay,
- context,
- controller
-})] : [], sendOnAbort = async ({ subprocess, cancelSignal, forceKillAfterDelay, context, controller: { signal } }) => {
- await onAbortedSignal(cancelSignal, signal);
- const reason = getReason(cancelSignal);
- await sendAbort(subprocess, reason);
- killOnTimeout({
- kill: subprocess.kill,
- forceKillAfterDelay,
- context,
- controllerSignal: signal
- });
- context.terminationReason ??= "gracefulCancel";
- throw cancelSignal.reason;
-}, getReason = ({ reason }) => {
- if (!(reason instanceof DOMException)) {
- return reason;
- }
- const error = new Error(reason.message);
- Object.defineProperty(error, "stack", {
- value: reason.stack,
- enumerable: false,
- configurable: true,
- writable: true
- });
- return error;
-};
-var init_graceful2 = __esm(() => {
- init_abort_signal();
- init_graceful();
- init_kill();
-});
-
-// node_modules/execa/lib/terminate/timeout.js
-import { setTimeout as setTimeout3 } from "timers/promises";
-var validateTimeout = ({ timeout }) => {
- if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
- throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
- }
-}, throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === undefined ? [] : [killAfterTimeout(subprocess, timeout, context, controller)], killAfterTimeout = async (subprocess, timeout, context, { signal }) => {
- await setTimeout3(timeout, undefined, { signal });
- context.terminationReason ??= "timeout";
- subprocess.kill();
- throw new DiscardedError;
-};
-var init_timeout = __esm(() => {
- init_final_error();
-});
-
-// node_modules/execa/lib/methods/node.js
-import { execPath, execArgv } from "process";
-import path3 from "path";
-var mapNode = ({ options: options2 }) => {
- if (options2.node === false) {
- throw new TypeError('The "node" option cannot be false with `execaNode()`.');
- }
- return { options: { ...options2, node: true } };
-}, handleNodeOption = (file, commandArguments, {
- node: shouldHandleNode = false,
- nodePath: nodePath2 = execPath,
- nodeOptions = execArgv.filter((nodeOption) => !nodeOption.startsWith("--inspect")),
- cwd: cwd2,
- execPath: formerNodePath,
- ...options2
-}) => {
- if (formerNodePath !== undefined) {
- throw new TypeError('The "execPath" option has been removed. Please use the "nodePath" option instead.');
- }
- const normalizedNodePath = safeNormalizeFileUrl(nodePath2, 'The "nodePath" option');
- const resolvedNodePath = path3.resolve(cwd2, normalizedNodePath);
- const newOptions = {
- ...options2,
- nodePath: resolvedNodePath,
- node: shouldHandleNode,
- cwd: cwd2
- };
- if (!shouldHandleNode) {
- return [file, commandArguments, newOptions];
- }
- if (path3.basename(file, ".exe") === "node") {
- throw new TypeError('When the "node" option is true, the first argument does not need to be "node".');
- }
- return [
- resolvedNodePath,
- [...nodeOptions, file, ...commandArguments],
- { ipc: true, ...newOptions, shell: false }
- ];
-};
-var init_node2 = __esm(() => {
- init_file_url();
-});
-
-// node_modules/execa/lib/ipc/ipc-input.js
-import { serialize } from "v8";
-var validateIpcInputOption = ({ ipcInput, ipc, serialization }) => {
- if (ipcInput === undefined) {
- return;
- }
- if (!ipc) {
- throw new Error("The `ipcInput` option cannot be set unless the `ipc` option is `true`.");
- }
- validateIpcInput[serialization](ipcInput);
-}, validateAdvancedInput = (ipcInput) => {
- try {
- serialize(ipcInput);
- } catch (error) {
- throw new Error("The `ipcInput` option is not serializable with a structured clone.", { cause: error });
- }
-}, validateJsonInput = (ipcInput) => {
- try {
- JSON.stringify(ipcInput);
- } catch (error) {
- throw new Error("The `ipcInput` option is not serializable with JSON.", { cause: error });
- }
-}, validateIpcInput, sendIpcInput = async (subprocess, ipcInput) => {
- if (ipcInput === undefined) {
- return;
- }
- await subprocess.sendMessage(ipcInput);
-};
-var init_ipc_input = __esm(() => {
- validateIpcInput = {
- advanced: validateAdvancedInput,
- json: validateJsonInput
- };
-});
-
-// node_modules/execa/lib/arguments/encoding-option.js
-var validateEncoding = ({ encoding }) => {
- if (ENCODINGS.has(encoding)) {
- return;
- }
- const correctEncoding = getCorrectEncoding(encoding);
- if (correctEncoding !== undefined) {
- throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`.
-Please rename it to ${serializeEncoding(correctEncoding)}.`);
- }
- const correctEncodings = [...ENCODINGS].map((correctEncoding2) => serializeEncoding(correctEncoding2)).join(", ");
- throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`.
-Please rename it to one of: ${correctEncodings}.`);
-}, TEXT_ENCODINGS, BINARY_ENCODINGS, ENCODINGS, getCorrectEncoding = (encoding) => {
- if (encoding === null) {
- return "buffer";
- }
- if (typeof encoding !== "string") {
- return;
- }
- const lowerEncoding = encoding.toLowerCase();
- if (lowerEncoding in ENCODING_ALIASES) {
- return ENCODING_ALIASES[lowerEncoding];
- }
- if (ENCODINGS.has(lowerEncoding)) {
- return lowerEncoding;
- }
-}, ENCODING_ALIASES, serializeEncoding = (encoding) => typeof encoding === "string" ? `"${encoding}"` : String(encoding);
-var init_encoding_option = __esm(() => {
- TEXT_ENCODINGS = new Set(["utf8", "utf16le"]);
- BINARY_ENCODINGS = new Set(["buffer", "hex", "base64", "base64url", "latin1", "ascii"]);
- ENCODINGS = new Set([...TEXT_ENCODINGS, ...BINARY_ENCODINGS]);
- ENCODING_ALIASES = {
- "utf-8": "utf8",
- "utf-16le": "utf16le",
- "ucs-2": "utf16le",
- ucs2: "utf16le",
- binary: "latin1"
- };
-});
-
-// node_modules/execa/lib/arguments/cwd.js
-import { statSync as statSync2 } from "fs";
-import path4 from "path";
-import process6 from "process";
-var normalizeCwd = (cwd2 = getDefaultCwd()) => {
- const cwdString = safeNormalizeFileUrl(cwd2, 'The "cwd" option');
- return path4.resolve(cwdString);
-}, getDefaultCwd = () => {
- try {
- return process6.cwd();
- } catch (error) {
- error.message = `The current directory does not exist.
-${error.message}`;
- throw error;
- }
-}, fixCwdError = (originalMessage, cwd2) => {
- if (cwd2 === getDefaultCwd()) {
- return originalMessage;
- }
- let cwdStat;
- try {
- cwdStat = statSync2(cwd2);
- } catch (error) {
- return `The "cwd" option is invalid: ${cwd2}.
-${error.message}
-${originalMessage}`;
- }
- if (!cwdStat.isDirectory()) {
- return `The "cwd" option is not a directory: ${cwd2}.
-${originalMessage}`;
- }
- return originalMessage;
-};
-var init_cwd2 = __esm(() => {
- init_file_url();
-});
-
-// node_modules/execa/lib/arguments/options.js
-import path5 from "path";
-import process7 from "process";
-var import_cross_spawn, normalizeOptions = (filePath, rawArguments, rawOptions) => {
- rawOptions.cwd = normalizeCwd(rawOptions.cwd);
- const [processedFile, processedArguments, processedOptions] = handleNodeOption(filePath, rawArguments, rawOptions);
- const { command: file, args: commandArguments, options: initialOptions } = import_cross_spawn.default._parse(processedFile, processedArguments, processedOptions);
- const fdOptions = normalizeFdSpecificOptions(initialOptions);
- const options2 = addDefaultOptions(fdOptions);
- validateTimeout(options2);
- validateEncoding(options2);
- validateIpcInputOption(options2);
- validateCancelSignal(options2);
- validateGracefulCancel(options2);
- options2.shell = normalizeFileUrl(options2.shell);
- options2.env = getEnv(options2);
- options2.killSignal = normalizeKillSignal(options2.killSignal);
- options2.forceKillAfterDelay = normalizeForceKillAfterDelay(options2.forceKillAfterDelay);
- options2.lines = options2.lines.map((lines, fdNumber) => lines && !BINARY_ENCODINGS.has(options2.encoding) && options2.buffer[fdNumber]);
- if (process7.platform === "win32" && path5.basename(file, ".exe") === "cmd") {
- commandArguments.unshift("/q");
- }
- return { file, commandArguments, options: options2 };
-}, addDefaultOptions = ({
- extendEnv = true,
- preferLocal = false,
- cwd: cwd2,
- localDir: localDirectory = cwd2,
- encoding = "utf8",
- reject = true,
- cleanup = true,
- all = false,
- windowsHide = true,
- killSignal = "SIGTERM",
- forceKillAfterDelay = true,
- gracefulCancel = false,
- ipcInput,
- ipc = ipcInput !== undefined || gracefulCancel,
- serialization = "advanced",
- ...options2
-}) => ({
- ...options2,
- extendEnv,
- preferLocal,
- cwd: cwd2,
- localDirectory,
- encoding,
- reject,
- cleanup,
- all,
- windowsHide,
- killSignal,
- forceKillAfterDelay,
- gracefulCancel,
- ipcInput,
- ipc,
- serialization
-}), getEnv = ({ env: envOption, extendEnv, preferLocal, node, localDirectory, nodePath: nodePath2 }) => {
- const env2 = extendEnv ? { ...process7.env, ...envOption } : envOption;
- if (preferLocal || node) {
- return npmRunPathEnv({
- env: env2,
- cwd: localDirectory,
- execPath: nodePath2,
- preferLocal,
- addExecPath: node
- });
- }
- return env2;
-};
-var init_options = __esm(() => {
- init_npm_run_path();
- init_kill();
- init_signal();
- init_cancel();
- init_graceful2();
- init_timeout();
- init_node2();
- init_ipc_input();
- init_encoding_option();
- init_cwd2();
- init_file_url();
- init_specific();
- import_cross_spawn = __toESM(require_cross_spawn(), 1);
-});
-
-// node_modules/execa/lib/arguments/shell.js
-var concatenateShell = (file, commandArguments, options2) => options2.shell && commandArguments.length > 0 ? [[file, ...commandArguments].join(" "), [], options2] : [file, commandArguments, options2];
-
-// node_modules/strip-final-newline/index.js
-function stripFinalNewline(input) {
- if (typeof input === "string") {
- return stripFinalNewlineString(input);
- }
- if (!(ArrayBuffer.isView(input) && input.BYTES_PER_ELEMENT === 1)) {
- throw new Error("Input must be a string or a Uint8Array");
- }
- return stripFinalNewlineBinary(input);
-}
-var stripFinalNewlineString = (input) => input.at(-1) === LF ? input.slice(0, input.at(-2) === CR ? -2 : -1) : input, stripFinalNewlineBinary = (input) => input.at(-1) === LF_BINARY ? input.subarray(0, input.at(-2) === CR_BINARY ? -2 : -1) : input, LF = `
-`, LF_BINARY, CR = "\r", CR_BINARY;
-var init_strip_final_newline = __esm(() => {
- LF_BINARY = LF.codePointAt(0);
- CR_BINARY = CR.codePointAt(0);
-});
-
-// node_modules/is-stream/index.js
-function isStream(stream, { checkOpen = true } = {}) {
- return stream !== null && typeof stream === "object" && (stream.writable || stream.readable || !checkOpen || stream.writable === undefined && stream.readable === undefined) && typeof stream.pipe === "function";
-}
-function isWritableStream(stream, { checkOpen = true } = {}) {
- return isStream(stream, { checkOpen }) && (stream.writable || !checkOpen) && typeof stream.write === "function" && typeof stream.end === "function" && typeof stream.writable === "boolean" && typeof stream.writableObjectMode === "boolean" && typeof stream.destroy === "function" && typeof stream.destroyed === "boolean";
-}
-function isReadableStream(stream, { checkOpen = true } = {}) {
- return isStream(stream, { checkOpen }) && (stream.readable || !checkOpen) && typeof stream.read === "function" && typeof stream.readable === "boolean" && typeof stream.readableObjectMode === "boolean" && typeof stream.destroy === "function" && typeof stream.destroyed === "boolean";
-}
-function isDuplexStream(stream, options2) {
- return isWritableStream(stream, options2) && isReadableStream(stream, options2);
-}
-
-// node_modules/@sec-ant/readable-stream/dist/ponyfill/asyncIterator.js
-class c {
- #t;
- #n;
- #r = false;
- #e = undefined;
- constructor(e, t) {
- this.#t = e, this.#n = t;
- }
- next() {
- const e = () => this.#s();
- return this.#e = this.#e ? this.#e.then(e, e) : e(), this.#e;
- }
- return(e) {
- const t = () => this.#i(e);
- return this.#e ? this.#e.then(t, t) : t();
- }
- async#s() {
- if (this.#r)
- return {
- done: true,
- value: undefined
- };
- let e;
- try {
- e = await this.#t.read();
- } catch (t) {
- throw this.#e = undefined, this.#r = true, this.#t.releaseLock(), t;
- }
- return e.done && (this.#e = undefined, this.#r = true, this.#t.releaseLock()), e;
- }
- async#i(e) {
- if (this.#r)
- return {
- done: true,
- value: e
- };
- if (this.#r = true, !this.#n) {
- const t = this.#t.cancel(e);
- return this.#t.releaseLock(), await t, {
- done: true,
- value: e
- };
- }
- return this.#t.releaseLock(), {
- done: true,
- value: e
- };
- }
-}
-function i() {
- return this[n].next();
-}
-function o(r) {
- return this[n].return(r);
-}
-function h({ preventCancel: r = false } = {}) {
- const e = this.getReader(), t = new c(e, r), s = Object.create(u);
- return s[n] = t, s;
-}
-var a, n, u;
-var init_asyncIterator = __esm(() => {
- a = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype);
- n = Symbol();
- Object.defineProperty(i, "name", { value: "next" });
- Object.defineProperty(o, "name", { value: "return" });
- u = Object.create(a, {
- next: {
- enumerable: true,
- configurable: true,
- writable: true,
- value: i
- },
- return: {
- enumerable: true,
- configurable: true,
- writable: true,
- value: o
- }
- });
-});
-
-// node_modules/@sec-ant/readable-stream/dist/ponyfill/fromAnyIterable.js
-var init_fromAnyIterable = () => {};
-
-// node_modules/@sec-ant/readable-stream/dist/ponyfill/index.js
-var init_ponyfill = __esm(() => {
- init_asyncIterator();
- init_fromAnyIterable();
-});
-
-// node_modules/get-stream/source/stream.js
-var getAsyncIterable = (stream) => {
- if (isReadableStream(stream, { checkOpen: false }) && nodeImports.on !== undefined) {
- return getStreamIterable(stream);
- }
- if (typeof stream?.[Symbol.asyncIterator] === "function") {
- return stream;
- }
- if (toString3.call(stream) === "[object ReadableStream]") {
- return h.call(stream);
- }
- throw new TypeError("The first argument must be a Readable, a ReadableStream, or an async iterable.");
-}, toString3, getStreamIterable = async function* (stream) {
- const controller = new AbortController;
- const state = {};
- handleStreamEnd(stream, controller, state);
- try {
- for await (const [chunk] of nodeImports.on(stream, "data", { signal: controller.signal })) {
- yield chunk;
- }
- } catch (error) {
- if (state.error !== undefined) {
- throw state.error;
- } else if (!controller.signal.aborted) {
- throw error;
- }
- } finally {
- stream.destroy();
- }
-}, handleStreamEnd = async (stream, controller, state) => {
- try {
- await nodeImports.finished(stream, {
- cleanup: true,
- readable: true,
- writable: false,
- error: false
- });
- } catch (error) {
- state.error = error;
- } finally {
- controller.abort();
- }
-}, nodeImports;
-var init_stream = __esm(() => {
- init_ponyfill();
- ({ toString: toString3 } = Object.prototype);
- nodeImports = {};
-});
-
-// node_modules/get-stream/source/contents.js
-var getStreamContents = async (stream, { init, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, finalize }, { maxBuffer = Number.POSITIVE_INFINITY } = {}) => {
- const asyncIterable = getAsyncIterable(stream);
- const state = init();
- state.length = 0;
- try {
- for await (const chunk of asyncIterable) {
- const chunkType = getChunkType(chunk);
- const convertedChunk = convertChunk[chunkType](chunk, state);
- appendChunk({
- convertedChunk,
- state,
- getSize,
- truncateChunk,
- addChunk,
- maxBuffer
- });
- }
- appendFinalChunk({
- state,
- convertChunk,
- getSize,
- truncateChunk,
- addChunk,
- getFinalChunk,
- maxBuffer
- });
- return finalize(state);
- } catch (error) {
- const normalizedError = typeof error === "object" && error !== null ? error : new Error(error);
- normalizedError.bufferedData = finalize(state);
- throw normalizedError;
- }
-}, appendFinalChunk = ({ state, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer }) => {
- const convertedChunk = getFinalChunk(state);
- if (convertedChunk !== undefined) {
- appendChunk({
- convertedChunk,
- state,
- getSize,
- truncateChunk,
- addChunk,
- maxBuffer
- });
- }
-}, appendChunk = ({ convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer }) => {
- const chunkSize = getSize(convertedChunk);
- const newLength = state.length + chunkSize;
- if (newLength <= maxBuffer) {
- addNewChunk(convertedChunk, state, addChunk, newLength);
- return;
- }
- const truncatedChunk = truncateChunk(convertedChunk, maxBuffer - state.length);
- if (truncatedChunk !== undefined) {
- addNewChunk(truncatedChunk, state, addChunk, maxBuffer);
- }
- throw new MaxBufferError;
-}, addNewChunk = (convertedChunk, state, addChunk, newLength) => {
- state.contents = addChunk(convertedChunk, state, newLength);
- state.length = newLength;
-}, getChunkType = (chunk) => {
- const typeOfChunk = typeof chunk;
- if (typeOfChunk === "string") {
- return "string";
- }
- if (typeOfChunk !== "object" || chunk === null) {
- return "others";
- }
- if (globalThis.Buffer?.isBuffer(chunk)) {
- return "buffer";
- }
- const prototypeName = objectToString3.call(chunk);
- if (prototypeName === "[object ArrayBuffer]") {
- return "arrayBuffer";
- }
- if (prototypeName === "[object DataView]") {
- return "dataView";
- }
- if (Number.isInteger(chunk.byteLength) && Number.isInteger(chunk.byteOffset) && objectToString3.call(chunk.buffer) === "[object ArrayBuffer]") {
- return "typedArray";
- }
- return "others";
-}, objectToString3, MaxBufferError;
-var init_contents = __esm(() => {
- init_stream();
- ({ toString: objectToString3 } = Object.prototype);
- MaxBufferError = class MaxBufferError extends Error {
- name = "MaxBufferError";
- constructor() {
- super("maxBuffer exceeded");
- }
- };
-});
-
-// node_modules/get-stream/source/utils.js
-var identity3 = (value) => value, noop3 = () => {
- return;
-}, getContentsProperty = ({ contents }) => contents, throwObjectStream = (chunk) => {
- throw new Error(`Streams in object mode are not supported: ${String(chunk)}`);
-}, getLengthProperty = (convertedChunk) => convertedChunk.length;
-
-// node_modules/get-stream/source/array.js
-async function getStreamAsArray(stream, options2) {
- return getStreamContents(stream, arrayMethods, options2);
-}
-var initArray = () => ({ contents: [] }), increment = () => 1, addArrayChunk = (convertedChunk, { contents }) => {
- contents.push(convertedChunk);
- return contents;
-}, arrayMethods;
-var init_array = __esm(() => {
- init_contents();
- arrayMethods = {
- init: initArray,
- convertChunk: {
- string: identity3,
- buffer: identity3,
- arrayBuffer: identity3,
- dataView: identity3,
- typedArray: identity3,
- others: identity3
- },
- getSize: increment,
- truncateChunk: noop3,
- addChunk: addArrayChunk,
- getFinalChunk: noop3,
- finalize: getContentsProperty
- };
-});
-
-// node_modules/get-stream/source/array-buffer.js
-async function getStreamAsArrayBuffer(stream, options2) {
- return getStreamContents(stream, arrayBufferMethods, options2);
-}
-var initArrayBuffer = () => ({ contents: new ArrayBuffer(0) }), useTextEncoder = (chunk) => textEncoder2.encode(chunk), textEncoder2, useUint8Array = (chunk) => new Uint8Array(chunk), useUint8ArrayWithOffset = (chunk) => new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength), truncateArrayBufferChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize), addArrayBufferChunk = (convertedChunk, { contents, length: previousLength }, length) => {
- const newContents = hasArrayBufferResize() ? resizeArrayBuffer(contents, length) : resizeArrayBufferSlow(contents, length);
- new Uint8Array(newContents).set(convertedChunk, previousLength);
- return newContents;
-}, resizeArrayBufferSlow = (contents, length) => {
- if (length <= contents.byteLength) {
- return contents;
- }
- const arrayBuffer = new ArrayBuffer(getNewContentsLength(length));
- new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0);
- return arrayBuffer;
-}, resizeArrayBuffer = (contents, length) => {
- if (length <= contents.maxByteLength) {
- contents.resize(length);
- return contents;
- }
- const arrayBuffer = new ArrayBuffer(length, { maxByteLength: getNewContentsLength(length) });
- new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0);
- return arrayBuffer;
-}, getNewContentsLength = (length) => SCALE_FACTOR ** Math.ceil(Math.log(length) / Math.log(SCALE_FACTOR)), SCALE_FACTOR = 2, finalizeArrayBuffer = ({ contents, length }) => hasArrayBufferResize() ? contents : contents.slice(0, length), hasArrayBufferResize = () => ("resize" in ArrayBuffer.prototype), arrayBufferMethods;
-var init_array_buffer = __esm(() => {
- init_contents();
- textEncoder2 = new TextEncoder;
- arrayBufferMethods = {
- init: initArrayBuffer,
- convertChunk: {
- string: useTextEncoder,
- buffer: useUint8Array,
- arrayBuffer: useUint8Array,
- dataView: useUint8ArrayWithOffset,
- typedArray: useUint8ArrayWithOffset,
- others: throwObjectStream
- },
- getSize: getLengthProperty,
- truncateChunk: truncateArrayBufferChunk,
- addChunk: addArrayBufferChunk,
- getFinalChunk: noop3,
- finalize: finalizeArrayBuffer
- };
-});
-
-// node_modules/get-stream/source/string.js
-async function getStreamAsString(stream, options2) {
- return getStreamContents(stream, stringMethods, options2);
-}
-var initString = () => ({ contents: "", textDecoder: new TextDecoder }), useTextDecoder = (chunk, { textDecoder: textDecoder2 }) => textDecoder2.decode(chunk, { stream: true }), addStringChunk = (convertedChunk, { contents }) => contents + convertedChunk, truncateStringChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize), getFinalStringChunk = ({ textDecoder: textDecoder2 }) => {
- const finalChunk = textDecoder2.decode();
- return finalChunk === "" ? undefined : finalChunk;
-}, stringMethods;
-var init_string = __esm(() => {
- init_contents();
- stringMethods = {
- init: initString,
- convertChunk: {
- string: identity3,
- buffer: useTextDecoder,
- arrayBuffer: useTextDecoder,
- dataView: useTextDecoder,
- typedArray: useTextDecoder,
- others: throwObjectStream
- },
- getSize: getLengthProperty,
- truncateChunk: truncateStringChunk,
- addChunk: addStringChunk,
- getFinalChunk: getFinalStringChunk,
- finalize: getContentsProperty
- };
-});
-
-// node_modules/get-stream/source/exports.js
-var init_exports = __esm(() => {
- init_array();
- init_array_buffer();
- init_string();
- init_contents();
-});
-
-// node_modules/get-stream/source/index.js
-import { on } from "events";
-import { finished } from "stream/promises";
-var init_source2 = __esm(() => {
- init_stream();
- init_exports();
- Object.assign(nodeImports, { on, finished });
-});
-
-// node_modules/execa/lib/io/max-buffer.js
-var handleMaxBuffer = ({ error, stream, readableObjectMode, lines, encoding, fdNumber }) => {
- if (!(error instanceof MaxBufferError)) {
- throw error;
- }
- if (fdNumber === "all") {
- return error;
- }
- const unit = getMaxBufferUnit(readableObjectMode, lines, encoding);
- error.maxBufferInfo = { fdNumber, unit };
- stream.destroy();
- throw error;
-}, getMaxBufferUnit = (readableObjectMode, lines, encoding) => {
- if (readableObjectMode) {
- return "objects";
- }
- if (lines) {
- return "lines";
- }
- if (encoding === "buffer") {
- return "bytes";
- }
- return "characters";
-}, checkIpcMaxBuffer = (subprocess, ipcOutput, maxBuffer) => {
- if (ipcOutput.length !== maxBuffer) {
- return;
- }
- const error = new MaxBufferError;
- error.maxBufferInfo = { fdNumber: "ipc" };
- throw error;
-}, getMaxBufferMessage = (error, maxBuffer) => {
- const { streamName, threshold, unit } = getMaxBufferInfo(error, maxBuffer);
- return `Command's ${streamName} was larger than ${threshold} ${unit}`;
-}, getMaxBufferInfo = (error, maxBuffer) => {
- if (error?.maxBufferInfo === undefined) {
- return { streamName: "output", threshold: maxBuffer[1], unit: "bytes" };
- }
- const { maxBufferInfo: { fdNumber, unit } } = error;
- delete error.maxBufferInfo;
- const threshold = getFdSpecificValue(maxBuffer, fdNumber);
- if (fdNumber === "ipc") {
- return { streamName: "IPC output", threshold, unit: "messages" };
- }
- return { streamName: getStreamName(fdNumber), threshold, unit };
-}, isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === "ENOBUFS" && output !== null && output.some((result) => result !== null && result.length > getMaxBufferSync(maxBuffer)), truncateMaxBufferSync = (result, isMaxBuffer, maxBuffer) => {
- if (!isMaxBuffer) {
- return result;
- }
- const maxBufferValue = getMaxBufferSync(maxBuffer);
- return result.length > maxBufferValue ? result.slice(0, maxBufferValue) : result;
-}, getMaxBufferSync = ([, stdoutMaxBuffer]) => stdoutMaxBuffer;
-var init_max_buffer = __esm(() => {
- init_source2();
- init_standard_stream();
- init_specific();
-});
-
-// node_modules/execa/lib/return/message.js
-import { inspect as inspect2 } from "util";
-var createMessages = ({
- stdio,
- all,
- ipcOutput,
- originalError,
- signal,
- signalDescription,
- exitCode,
- escapedCommand,
- timedOut,
- isCanceled,
- isGracefullyCanceled,
- isMaxBuffer,
- isForcefullyTerminated,
- forceKillAfterDelay,
- killSignal,
- maxBuffer,
- timeout,
- cwd: cwd2
-}) => {
- const errorCode = originalError?.code;
- const prefix = getErrorPrefix({
- originalError,
- timedOut,
- timeout,
- isMaxBuffer,
- maxBuffer,
- errorCode,
- signal,
- signalDescription,
- exitCode,
- isCanceled,
- isGracefullyCanceled,
- isForcefullyTerminated,
- forceKillAfterDelay,
- killSignal
- });
- const originalMessage = getOriginalMessage(originalError, cwd2);
- const suffix = originalMessage === undefined ? "" : `
-${originalMessage}`;
- const shortMessage = `${prefix}: ${escapedCommand}${suffix}`;
- const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all];
- const message = [
- shortMessage,
- ...messageStdio,
- ...stdio.slice(3),
- ipcOutput.map((ipcMessage) => serializeIpcMessage(ipcMessage)).join(`
-`)
- ].map((messagePart) => escapeLines(stripFinalNewline(serializeMessagePart(messagePart)))).filter(Boolean).join(`
-
-`);
- return { originalMessage, shortMessage, message };
-}, getErrorPrefix = ({
- originalError,
- timedOut,
- timeout,
- isMaxBuffer,
- maxBuffer,
- errorCode,
- signal,
- signalDescription,
- exitCode,
- isCanceled,
- isGracefullyCanceled,
- isForcefullyTerminated,
- forceKillAfterDelay,
- killSignal
-}) => {
- const forcefulSuffix = getForcefulSuffix(isForcefullyTerminated, forceKillAfterDelay);
- if (timedOut) {
- return `Command timed out after ${timeout} milliseconds${forcefulSuffix}`;
- }
- if (isGracefullyCanceled) {
- if (signal === undefined) {
- return `Command was gracefully canceled with exit code ${exitCode}`;
- }
- return isForcefullyTerminated ? `Command was gracefully canceled${forcefulSuffix}` : `Command was gracefully canceled with ${signal} (${signalDescription})`;
- }
- if (isCanceled) {
- return `Command was canceled${forcefulSuffix}`;
- }
- if (isMaxBuffer) {
- return `${getMaxBufferMessage(originalError, maxBuffer)}${forcefulSuffix}`;
- }
- if (errorCode !== undefined) {
- return `Command failed with ${errorCode}${forcefulSuffix}`;
- }
- if (isForcefullyTerminated) {
- return `Command was killed with ${killSignal} (${getSignalDescription(killSignal)})${forcefulSuffix}`;
- }
- if (signal !== undefined) {
- return `Command was killed with ${signal} (${signalDescription})`;
- }
- if (exitCode !== undefined) {
- return `Command failed with exit code ${exitCode}`;
- }
- return "Command failed";
-}, getForcefulSuffix = (isForcefullyTerminated, forceKillAfterDelay) => isForcefullyTerminated ? ` and was forcefully terminated after ${forceKillAfterDelay} milliseconds` : "", getOriginalMessage = (originalError, cwd2) => {
- if (originalError instanceof DiscardedError) {
- return;
- }
- const originalMessage = isExecaError(originalError) ? originalError.originalMessage : String(originalError?.message ?? originalError);
- const escapedOriginalMessage = escapeLines(fixCwdError(originalMessage, cwd2));
- return escapedOriginalMessage === "" ? undefined : escapedOriginalMessage;
-}, serializeIpcMessage = (ipcMessage) => typeof ipcMessage === "string" ? ipcMessage : inspect2(ipcMessage), serializeMessagePart = (messagePart) => Array.isArray(messagePart) ? messagePart.map((messageItem) => stripFinalNewline(serializeMessageItem(messageItem))).filter(Boolean).join(`
-`) : serializeMessageItem(messagePart), serializeMessageItem = (messageItem) => {
- if (typeof messageItem === "string") {
- return messageItem;
- }
- if (isUint8Array(messageItem)) {
- return uint8ArrayToString(messageItem);
- }
- return "";
-};
-var init_message = __esm(() => {
- init_strip_final_newline();
- init_uint_array();
- init_cwd2();
- init_escape();
- init_max_buffer();
- init_signal();
- init_final_error();
-});
-
-// node_modules/execa/lib/return/result.js
-var makeSuccessResult = ({
- command,
- escapedCommand,
- stdio,
- all,
- ipcOutput,
- options: { cwd: cwd2 },
- startTime
-}) => omitUndefinedProperties({
- command,
- escapedCommand,
- cwd: cwd2,
- durationMs: getDurationMs(startTime),
- failed: false,
- timedOut: false,
- isCanceled: false,
- isGracefullyCanceled: false,
- isTerminated: false,
- isMaxBuffer: false,
- isForcefullyTerminated: false,
- exitCode: 0,
- stdout: stdio[1],
- stderr: stdio[2],
- all,
- stdio,
- ipcOutput,
- pipedFrom: []
-}), makeEarlyError = ({
- error,
- command,
- escapedCommand,
- fileDescriptors,
- options: options2,
- startTime,
- isSync
-}) => makeError({
- error,
- command,
- escapedCommand,
- startTime,
- timedOut: false,
- isCanceled: false,
- isGracefullyCanceled: false,
- isMaxBuffer: false,
- isForcefullyTerminated: false,
- stdio: Array.from({ length: fileDescriptors.length }),
- ipcOutput: [],
- options: options2,
- isSync
-}), makeError = ({
- error: originalError,
- command,
- escapedCommand,
- startTime,
- timedOut,
- isCanceled,
- isGracefullyCanceled,
- isMaxBuffer,
- isForcefullyTerminated,
- exitCode: rawExitCode,
- signal: rawSignal,
- stdio,
- all,
- ipcOutput,
- options: {
- timeoutDuration,
- timeout = timeoutDuration,
- forceKillAfterDelay,
- killSignal,
- cwd: cwd2,
- maxBuffer
- },
- isSync
-}) => {
- const { exitCode, signal, signalDescription } = normalizeExitPayload(rawExitCode, rawSignal);
- const { originalMessage, shortMessage, message } = createMessages({
- stdio,
- all,
- ipcOutput,
- originalError,
- signal,
- signalDescription,
- exitCode,
- escapedCommand,
- timedOut,
- isCanceled,
- isGracefullyCanceled,
- isMaxBuffer,
- isForcefullyTerminated,
- forceKillAfterDelay,
- killSignal,
- maxBuffer,
- timeout,
- cwd: cwd2
- });
- const error = getFinalError(originalError, message, isSync);
- Object.assign(error, getErrorProperties({
- error,
- command,
- escapedCommand,
- startTime,
- timedOut,
- isCanceled,
- isGracefullyCanceled,
- isMaxBuffer,
- isForcefullyTerminated,
- exitCode,
- signal,
- signalDescription,
- stdio,
- all,
- ipcOutput,
- cwd: cwd2,
- originalMessage,
- shortMessage
- }));
- return error;
-}, getErrorProperties = ({
- error,
- command,
- escapedCommand,
- startTime,
- timedOut,
- isCanceled,
- isGracefullyCanceled,
- isMaxBuffer,
- isForcefullyTerminated,
- exitCode,
- signal,
- signalDescription,
- stdio,
- all,
- ipcOutput,
- cwd: cwd2,
- originalMessage,
- shortMessage
-}) => omitUndefinedProperties({
- shortMessage,
- originalMessage,
- command,
- escapedCommand,
- cwd: cwd2,
- durationMs: getDurationMs(startTime),
- failed: true,
- timedOut,
- isCanceled,
- isGracefullyCanceled,
- isTerminated: signal !== undefined,
- isMaxBuffer,
- isForcefullyTerminated,
- exitCode,
- signal,
- signalDescription,
- code: error.cause?.code,
- stdout: stdio[1],
- stderr: stdio[2],
- all,
- stdio,
- ipcOutput,
- pipedFrom: []
-}), omitUndefinedProperties = (result) => Object.fromEntries(Object.entries(result).filter(([, value]) => value !== undefined)), normalizeExitPayload = (rawExitCode, rawSignal) => {
- const exitCode = rawExitCode === null ? undefined : rawExitCode;
- const signal = rawSignal === null ? undefined : rawSignal;
- const signalDescription = signal === undefined ? undefined : getSignalDescription(rawSignal);
- return { exitCode, signal, signalDescription };
-};
-var init_result = __esm(() => {
- init_signal();
- init_duration();
- init_final_error();
- init_message();
-});
-
-// node_modules/parse-ms/index.js
-function parseNumber(milliseconds) {
- return {
- days: Math.trunc(milliseconds / 86400000),
- hours: Math.trunc(milliseconds / 3600000 % 24),
- minutes: Math.trunc(milliseconds / 60000 % 60),
- seconds: Math.trunc(milliseconds / 1000 % 60),
- milliseconds: Math.trunc(milliseconds % 1000),
- microseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1000) % 1000),
- nanoseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e6) % 1000)
- };
-}
-function parseBigint(milliseconds) {
- return {
- days: milliseconds / 86400000n,
- hours: milliseconds / 3600000n % 24n,
- minutes: milliseconds / 60000n % 60n,
- seconds: milliseconds / 1000n % 60n,
- milliseconds: milliseconds % 1000n,
- microseconds: 0n,
- nanoseconds: 0n
- };
-}
-function parseMilliseconds(milliseconds) {
- switch (typeof milliseconds) {
- case "number": {
- if (Number.isFinite(milliseconds)) {
- return parseNumber(milliseconds);
- }
- break;
- }
- case "bigint": {
- return parseBigint(milliseconds);
- }
- }
- throw new TypeError("Expected a finite number or bigint");
-}
-var toZeroIfInfinity = (value) => Number.isFinite(value) ? value : 0;
-
-// node_modules/pretty-ms/index.js
-function prettyMilliseconds(milliseconds, options2) {
- const isBigInt = typeof milliseconds === "bigint";
- if (!isBigInt && !Number.isFinite(milliseconds)) {
- throw new TypeError("Expected a finite number or bigint");
- }
- options2 = { ...options2 };
- const sign = milliseconds < 0 ? "-" : "";
- milliseconds = milliseconds < 0 ? -milliseconds : milliseconds;
- if (options2.colonNotation) {
- options2.compact = false;
- options2.formatSubMilliseconds = false;
- options2.separateMilliseconds = false;
- options2.verbose = false;
- }
- if (options2.compact) {
- options2.unitCount = 1;
- options2.secondsDecimalDigits = 0;
- options2.millisecondsDecimalDigits = 0;
- }
- let result = [];
- const floorDecimals = (value, decimalDigits) => {
- const flooredInterimValue = Math.floor(value * 10 ** decimalDigits + SECOND_ROUNDING_EPSILON);
- const flooredValue = Math.round(flooredInterimValue) / 10 ** decimalDigits;
- return flooredValue.toFixed(decimalDigits);
- };
- const add = (value, long, short, valueString) => {
- if ((result.length === 0 || !options2.colonNotation) && isZero(value) && !(options2.colonNotation && short === "m")) {
- return;
- }
- valueString ??= String(value);
- if (options2.colonNotation) {
- const wholeDigits = valueString.includes(".") ? valueString.split(".")[0].length : valueString.length;
- const minLength = result.length > 0 ? 2 : 1;
- valueString = "0".repeat(Math.max(0, minLength - wholeDigits)) + valueString;
- } else {
- valueString += options2.verbose ? " " + pluralize(long, value) : short;
- }
- result.push(valueString);
- };
- const parsed = parseMilliseconds(milliseconds);
- const days = BigInt(parsed.days);
- if (options2.hideYearAndDays) {
- add(BigInt(days) * 24n + BigInt(parsed.hours), "hour", "h");
- } else {
- if (options2.hideYear) {
- add(days, "day", "d");
- } else {
- add(days / 365n, "year", "y");
- add(days % 365n, "day", "d");
- }
- add(Number(parsed.hours), "hour", "h");
- }
- add(Number(parsed.minutes), "minute", "m");
- if (!options2.hideSeconds) {
- if (options2.separateMilliseconds || options2.formatSubMilliseconds || !options2.colonNotation && milliseconds < 1000 && !options2.subSecondsAsDecimals) {
- const seconds = Number(parsed.seconds);
- const milliseconds2 = Number(parsed.milliseconds);
- const microseconds = Number(parsed.microseconds);
- const nanoseconds = Number(parsed.nanoseconds);
- add(seconds, "second", "s");
- if (options2.formatSubMilliseconds) {
- add(milliseconds2, "millisecond", "ms");
- add(microseconds, "microsecond", "\xB5s");
- add(nanoseconds, "nanosecond", "ns");
- } else {
- const millisecondsAndBelow = milliseconds2 + microseconds / 1000 + nanoseconds / 1e6;
- const millisecondsDecimalDigits = typeof options2.millisecondsDecimalDigits === "number" ? options2.millisecondsDecimalDigits : 0;
- const roundedMilliseconds = millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow);
- const millisecondsString = millisecondsDecimalDigits ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits) : roundedMilliseconds;
- add(Number.parseFloat(millisecondsString), "millisecond", "ms", millisecondsString);
- }
- } else {
- const seconds = (isBigInt ? Number(milliseconds % ONE_DAY_IN_MILLISECONDS) : milliseconds) / 1000 % 60;
- const secondsDecimalDigits = typeof options2.secondsDecimalDigits === "number" ? options2.secondsDecimalDigits : 1;
- const secondsFixed = floorDecimals(seconds, secondsDecimalDigits);
- const secondsString = options2.keepDecimalsOnWholeSeconds ? secondsFixed : secondsFixed.replace(/\.0+$/, "");
- add(Number.parseFloat(secondsString), "second", "s", secondsString);
- }
- }
- if (result.length === 0) {
- return sign + "0" + (options2.verbose ? " milliseconds" : "ms");
- }
- const separator = options2.colonNotation ? ":" : " ";
- if (typeof options2.unitCount === "number") {
- result = result.slice(0, Math.max(options2.unitCount, 1));
- }
- return sign + result.join(separator);
-}
-var isZero = (value) => value === 0 || value === 0n, pluralize = (word, count2) => count2 === 1 || count2 === 1n ? word : `${word}s`, SECOND_ROUNDING_EPSILON = 0.0000001, ONE_DAY_IN_MILLISECONDS;
-var init_pretty_ms = __esm(() => {
- ONE_DAY_IN_MILLISECONDS = 24n * 60n * 60n * 1000n;
-});
-
-// node_modules/execa/lib/verbose/error.js
-var logError = (result, verboseInfo) => {
- if (result.failed) {
- verboseLog({
- type: "error",
- verboseMessage: result.shortMessage,
- verboseInfo,
- result
- });
- }
-};
-var init_error2 = __esm(() => {
- init_log();
-});
-
-// node_modules/execa/lib/verbose/complete.js
-var logResult = (result, verboseInfo) => {
- if (!isVerbose(verboseInfo)) {
- return;
- }
- logError(result, verboseInfo);
- logDuration(result, verboseInfo);
-}, logDuration = (result, verboseInfo) => {
- const verboseMessage = `(done in ${prettyMilliseconds(result.durationMs)})`;
- verboseLog({
- type: "duration",
- verboseMessage,
- verboseInfo,
- result
- });
-};
-var init_complete = __esm(() => {
- init_pretty_ms();
- init_values();
- init_log();
- init_error2();
-});
-
-// node_modules/execa/lib/return/reject.js
-var handleResult = (result, verboseInfo, { reject }) => {
- logResult(result, verboseInfo);
- if (result.failed && reject) {
- throw result;
- }
- return result;
-};
-var init_reject = __esm(() => {
- init_complete();
-});
-
-// node_modules/execa/lib/stdio/type.js
-var getStdioItemType = (value, optionName) => {
- if (isAsyncGenerator(value)) {
- return "asyncGenerator";
- }
- if (isSyncGenerator(value)) {
- return "generator";
- }
- if (isUrl(value)) {
- return "fileUrl";
- }
- if (isFilePathObject(value)) {
- return "filePath";
- }
- if (isWebStream(value)) {
- return "webStream";
- }
- if (isStream(value, { checkOpen: false })) {
- return "native";
- }
- if (isUint8Array(value)) {
- return "uint8Array";
- }
- if (isAsyncIterableObject(value)) {
- return "asyncIterable";
- }
- if (isIterableObject(value)) {
- return "iterable";
- }
- if (isTransformStream(value)) {
- return getTransformStreamType({ transform: value }, optionName);
- }
- if (isTransformOptions(value)) {
- return getTransformObjectType(value, optionName);
- }
- return "native";
-}, getTransformObjectType = (value, optionName) => {
- if (isDuplexStream(value.transform, { checkOpen: false })) {
- return getDuplexType(value, optionName);
- }
- if (isTransformStream(value.transform)) {
- return getTransformStreamType(value, optionName);
- }
- return getGeneratorObjectType(value, optionName);
-}, getDuplexType = (value, optionName) => {
- validateNonGeneratorType(value, optionName, "Duplex stream");
- return "duplex";
-}, getTransformStreamType = (value, optionName) => {
- validateNonGeneratorType(value, optionName, "web TransformStream");
- return "webTransform";
-}, validateNonGeneratorType = ({ final, binary, objectMode }, optionName, typeName) => {
- checkUndefinedOption(final, `${optionName}.final`, typeName);
- checkUndefinedOption(binary, `${optionName}.binary`, typeName);
- checkBooleanOption(objectMode, `${optionName}.objectMode`);
-}, checkUndefinedOption = (value, optionName, typeName) => {
- if (value !== undefined) {
- throw new TypeError(`The \`${optionName}\` option can only be defined when using a generator, not a ${typeName}.`);
- }
-}, getGeneratorObjectType = ({ transform, final, binary, objectMode }, optionName) => {
- if (transform !== undefined && !isGenerator(transform)) {
- throw new TypeError(`The \`${optionName}.transform\` option must be a generator, a Duplex stream or a web TransformStream.`);
- }
- if (isDuplexStream(final, { checkOpen: false })) {
- throw new TypeError(`The \`${optionName}.final\` option must not be a Duplex stream.`);
- }
- if (isTransformStream(final)) {
- throw new TypeError(`The \`${optionName}.final\` option must not be a web TransformStream.`);
- }
- if (final !== undefined && !isGenerator(final)) {
- throw new TypeError(`The \`${optionName}.final\` option must be a generator.`);
- }
- checkBooleanOption(binary, `${optionName}.binary`);
- checkBooleanOption(objectMode, `${optionName}.objectMode`);
- return isAsyncGenerator(transform) || isAsyncGenerator(final) ? "asyncGenerator" : "generator";
-}, checkBooleanOption = (value, optionName) => {
- if (value !== undefined && typeof value !== "boolean") {
- throw new TypeError(`The \`${optionName}\` option must use a boolean.`);
- }
-}, isGenerator = (value) => isAsyncGenerator(value) || isSyncGenerator(value), isAsyncGenerator = (value) => Object.prototype.toString.call(value) === "[object AsyncGeneratorFunction]", isSyncGenerator = (value) => Object.prototype.toString.call(value) === "[object GeneratorFunction]", isTransformOptions = (value) => isPlainObject(value) && (value.transform !== undefined || value.final !== undefined), isUrl = (value) => Object.prototype.toString.call(value) === "[object URL]", isRegularUrl = (value) => isUrl(value) && value.protocol !== "file:", isFilePathObject = (value) => isPlainObject(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => FILE_PATH_KEYS.has(key)) && isFilePathString(value.file), FILE_PATH_KEYS, isFilePathString = (file) => typeof file === "string", isUnknownStdioString = (type, value) => type === "native" && typeof value === "string" && !KNOWN_STDIO_STRINGS.has(value), KNOWN_STDIO_STRINGS, isReadableStream2 = (value) => Object.prototype.toString.call(value) === "[object ReadableStream]", isWritableStream2 = (value) => Object.prototype.toString.call(value) === "[object WritableStream]", isWebStream = (value) => isReadableStream2(value) || isWritableStream2(value), isTransformStream = (value) => isReadableStream2(value?.readable) && isWritableStream2(value?.writable), isAsyncIterableObject = (value) => isObject2(value) && typeof value[Symbol.asyncIterator] === "function", isIterableObject = (value) => isObject2(value) && typeof value[Symbol.iterator] === "function", isObject2 = (value) => typeof value === "object" && value !== null, TRANSFORM_TYPES, FILE_TYPES, SPECIAL_DUPLICATE_TYPES_SYNC, SPECIAL_DUPLICATE_TYPES, FORBID_DUPLICATE_TYPES, TYPE_TO_MESSAGE;
-var init_type = __esm(() => {
- init_uint_array();
- FILE_PATH_KEYS = new Set(["file", "append"]);
- KNOWN_STDIO_STRINGS = new Set(["ipc", "ignore", "inherit", "overlapped", "pipe"]);
- TRANSFORM_TYPES = new Set(["generator", "asyncGenerator", "duplex", "webTransform"]);
- FILE_TYPES = new Set(["fileUrl", "filePath", "fileNumber"]);
- SPECIAL_DUPLICATE_TYPES_SYNC = new Set(["fileUrl", "filePath"]);
- SPECIAL_DUPLICATE_TYPES = new Set([...SPECIAL_DUPLICATE_TYPES_SYNC, "webStream", "nodeStream"]);
- FORBID_DUPLICATE_TYPES = new Set(["webTransform", "duplex"]);
- TYPE_TO_MESSAGE = {
- generator: "a generator",
- asyncGenerator: "an async generator",
- fileUrl: "a file URL",
- filePath: "a file path string",
- fileNumber: "a file descriptor number",
- webStream: "a web stream",
- nodeStream: "a Node.js stream",
- webTransform: "a web TransformStream",
- duplex: "a Duplex stream",
- native: "any value",
- iterable: "an iterable",
- asyncIterable: "an async iterable",
- string: "a string",
- uint8Array: "a Uint8Array"
- };
-});
-
-// node_modules/execa/lib/transform/object-mode.js
-var getTransformObjectModes = (objectMode, index2, newTransforms, direction) => direction === "output" ? getOutputObjectModes(objectMode, index2, newTransforms) : getInputObjectModes(objectMode, index2, newTransforms), getOutputObjectModes = (objectMode, index2, newTransforms) => {
- const writableObjectMode = index2 !== 0 && newTransforms[index2 - 1].value.readableObjectMode;
- const readableObjectMode = objectMode ?? writableObjectMode;
- return { writableObjectMode, readableObjectMode };
-}, getInputObjectModes = (objectMode, index2, newTransforms) => {
- const writableObjectMode = index2 === 0 ? objectMode === true : newTransforms[index2 - 1].value.readableObjectMode;
- const readableObjectMode = index2 !== newTransforms.length - 1 && (objectMode ?? writableObjectMode);
- return { writableObjectMode, readableObjectMode };
-}, getFdObjectMode = (stdioItems, direction) => {
- const lastTransform = stdioItems.findLast(({ type }) => TRANSFORM_TYPES.has(type));
- if (lastTransform === undefined) {
- return false;
- }
- return direction === "input" ? lastTransform.value.writableObjectMode : lastTransform.value.readableObjectMode;
-};
-var init_object_mode = __esm(() => {
- init_type();
-});
-
-// node_modules/execa/lib/transform/normalize.js
-var normalizeTransforms = (stdioItems, optionName, direction, options2) => [
- ...stdioItems.filter(({ type }) => !TRANSFORM_TYPES.has(type)),
- ...getTransforms(stdioItems, optionName, direction, options2)
-], getTransforms = (stdioItems, optionName, direction, { encoding }) => {
- const transforms = stdioItems.filter(({ type }) => TRANSFORM_TYPES.has(type));
- const newTransforms = Array.from({ length: transforms.length });
- for (const [index2, stdioItem] of Object.entries(transforms)) {
- newTransforms[index2] = normalizeTransform({
- stdioItem,
- index: Number(index2),
- newTransforms,
- optionName,
- direction,
- encoding
- });
- }
- return sortTransforms(newTransforms, direction);
-}, normalizeTransform = ({ stdioItem, stdioItem: { type }, index: index2, newTransforms, optionName, direction, encoding }) => {
- if (type === "duplex") {
- return normalizeDuplex({ stdioItem, optionName });
- }
- if (type === "webTransform") {
- return normalizeTransformStream({
- stdioItem,
- index: index2,
- newTransforms,
- direction
- });
- }
- return normalizeGenerator({
- stdioItem,
- index: index2,
- newTransforms,
- direction,
- encoding
- });
-}, normalizeDuplex = ({
- stdioItem,
- stdioItem: {
- value: {
- transform,
- transform: { writableObjectMode, readableObjectMode },
- objectMode = readableObjectMode
- }
- },
- optionName
-}) => {
- if (objectMode && !readableObjectMode) {
- throw new TypeError(`The \`${optionName}.objectMode\` option can only be \`true\` if \`new Duplex({objectMode: true})\` is used.`);
- }
- if (!objectMode && readableObjectMode) {
- throw new TypeError(`The \`${optionName}.objectMode\` option cannot be \`false\` if \`new Duplex({objectMode: true})\` is used.`);
- }
- return {
- ...stdioItem,
- value: { transform, writableObjectMode, readableObjectMode }
- };
-}, normalizeTransformStream = ({ stdioItem, stdioItem: { value }, index: index2, newTransforms, direction }) => {
- const { transform, objectMode } = isPlainObject(value) ? value : { transform: value };
- const { writableObjectMode, readableObjectMode } = getTransformObjectModes(objectMode, index2, newTransforms, direction);
- return {
- ...stdioItem,
- value: { transform, writableObjectMode, readableObjectMode }
- };
-}, normalizeGenerator = ({ stdioItem, stdioItem: { value }, index: index2, newTransforms, direction, encoding }) => {
- const {
- transform,
- final,
- binary: binaryOption = false,
- preserveNewlines = false,
- objectMode
- } = isPlainObject(value) ? value : { transform: value };
- const binary = binaryOption || BINARY_ENCODINGS.has(encoding);
- const { writableObjectMode, readableObjectMode } = getTransformObjectModes(objectMode, index2, newTransforms, direction);
- return {
- ...stdioItem,
- value: {
- transform,
- final,
- binary,
- preserveNewlines,
- writableObjectMode,
- readableObjectMode
- }
- };
-}, sortTransforms = (newTransforms, direction) => direction === "input" ? newTransforms.reverse() : newTransforms;
-var init_normalize = __esm(() => {
- init_encoding_option();
- init_type();
- init_object_mode();
-});
-
-// node_modules/execa/lib/stdio/direction.js
-import process8 from "process";
-var getStreamDirection = (stdioItems, fdNumber, optionName) => {
- const directions = stdioItems.map((stdioItem) => getStdioItemDirection(stdioItem, fdNumber));
- if (directions.includes("input") && directions.includes("output")) {
- throw new TypeError(`The \`${optionName}\` option must not be an array of both readable and writable values.`);
- }
- return directions.find(Boolean) ?? DEFAULT_DIRECTION;
-}, getStdioItemDirection = ({ type, value }, fdNumber) => KNOWN_DIRECTIONS[fdNumber] ?? guessStreamDirection[type](value), KNOWN_DIRECTIONS, anyDirection = () => {
- return;
-}, alwaysInput = () => "input", guessStreamDirection, getStandardStreamDirection = (value) => {
- if ([0, process8.stdin].includes(value)) {
- return "input";
- }
- if ([1, 2, process8.stdout, process8.stderr].includes(value)) {
- return "output";
- }
-}, DEFAULT_DIRECTION = "output";
-var init_direction = __esm(() => {
- init_type();
- KNOWN_DIRECTIONS = ["input", "output", "output"];
- guessStreamDirection = {
- generator: anyDirection,
- asyncGenerator: anyDirection,
- fileUrl: anyDirection,
- filePath: anyDirection,
- iterable: alwaysInput,
- asyncIterable: alwaysInput,
- uint8Array: alwaysInput,
- webStream: (value) => isWritableStream2(value) ? "output" : "input",
- nodeStream(value) {
- if (!isReadableStream(value, { checkOpen: false })) {
- return "output";
- }
- return isWritableStream(value, { checkOpen: false }) ? undefined : "input";
- },
- webTransform: anyDirection,
- duplex: anyDirection,
- native(value) {
- const standardStreamDirection = getStandardStreamDirection(value);
- if (standardStreamDirection !== undefined) {
- return standardStreamDirection;
- }
- if (isStream(value, { checkOpen: false })) {
- return guessStreamDirection.nodeStream(value);
- }
- }
- };
-});
-
-// node_modules/execa/lib/ipc/array.js
-var normalizeIpcStdioArray = (stdioArray, ipc) => ipc && !stdioArray.includes("ipc") ? [...stdioArray, "ipc"] : stdioArray;
-
-// node_modules/execa/lib/stdio/stdio-option.js
-var normalizeStdioOption = ({ stdio, ipc, buffer, ...options2 }, verboseInfo, isSync) => {
- const stdioArray = getStdioArray(stdio, options2).map((stdioOption, fdNumber) => addDefaultValue2(stdioOption, fdNumber));
- return isSync ? normalizeStdioSync(stdioArray, buffer, verboseInfo) : normalizeIpcStdioArray(stdioArray, ipc);
-}, getStdioArray = (stdio, options2) => {
- if (stdio === undefined) {
- return STANDARD_STREAMS_ALIASES.map((alias) => options2[alias]);
- }
- if (hasAlias(options2)) {
- throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${STANDARD_STREAMS_ALIASES.map((alias) => `\`${alias}\``).join(", ")}`);
- }
- if (typeof stdio === "string") {
- return [stdio, stdio, stdio];
- }
- if (!Array.isArray(stdio)) {
- throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
- }
- const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);
- return Array.from({ length }, (_, fdNumber) => stdio[fdNumber]);
-}, hasAlias = (options2) => STANDARD_STREAMS_ALIASES.some((alias) => options2[alias] !== undefined), addDefaultValue2 = (stdioOption, fdNumber) => {
- if (Array.isArray(stdioOption)) {
- return stdioOption.map((item) => addDefaultValue2(item, fdNumber));
- }
- if (stdioOption === null || stdioOption === undefined) {
- return fdNumber >= STANDARD_STREAMS_ALIASES.length ? "ignore" : "pipe";
- }
- return stdioOption;
-}, normalizeStdioSync = (stdioArray, buffer, verboseInfo) => stdioArray.map((stdioOption, fdNumber) => !buffer[fdNumber] && fdNumber !== 0 && !isFullVerbose(verboseInfo, fdNumber) && isOutputPipeOnly(stdioOption) ? "ignore" : stdioOption), isOutputPipeOnly = (stdioOption) => stdioOption === "pipe" || Array.isArray(stdioOption) && stdioOption.every((item) => item === "pipe");
-var init_stdio_option = __esm(() => {
- init_standard_stream();
- init_values();
-});
-
-// node_modules/execa/lib/stdio/native.js
-import { readFileSync as readFileSync2 } from "fs";
-import tty3 from "tty";
-var handleNativeStream = ({ stdioItem, stdioItem: { type }, isStdioArray, fdNumber, direction, isSync }) => {
- if (!isStdioArray || type !== "native") {
- return stdioItem;
- }
- return isSync ? handleNativeStreamSync({ stdioItem, fdNumber, direction }) : handleNativeStreamAsync({ stdioItem, fdNumber });
-}, handleNativeStreamSync = ({ stdioItem, stdioItem: { value, optionName }, fdNumber, direction }) => {
- const targetFd = getTargetFd({
- value,
- optionName,
- fdNumber,
- direction
- });
- if (targetFd !== undefined) {
- return targetFd;
- }
- if (isStream(value, { checkOpen: false })) {
- throw new TypeError(`The \`${optionName}: Stream\` option cannot both be an array and include a stream with synchronous methods.`);
- }
- return stdioItem;
-}, getTargetFd = ({ value, optionName, fdNumber, direction }) => {
- const targetFdNumber = getTargetFdNumber(value, fdNumber);
- if (targetFdNumber === undefined) {
- return;
- }
- if (direction === "output") {
- return { type: "fileNumber", value: targetFdNumber, optionName };
- }
- if (tty3.isatty(targetFdNumber)) {
- throw new TypeError(`The \`${optionName}: ${serializeOptionValue(value)}\` option is invalid: it cannot be a TTY with synchronous methods.`);
- }
- return { type: "uint8Array", value: bufferToUint8Array(readFileSync2(targetFdNumber)), optionName };
-}, getTargetFdNumber = (value, fdNumber) => {
- if (value === "inherit") {
- return fdNumber;
- }
- if (typeof value === "number") {
- return value;
- }
- const standardStreamIndex = STANDARD_STREAMS.indexOf(value);
- if (standardStreamIndex !== -1) {
- return standardStreamIndex;
- }
-}, handleNativeStreamAsync = ({ stdioItem, stdioItem: { value, optionName }, fdNumber }) => {
- if (value === "inherit") {
- return { type: "nodeStream", value: getStandardStream(fdNumber, value, optionName), optionName };
- }
- if (typeof value === "number") {
- return { type: "nodeStream", value: getStandardStream(value, value, optionName), optionName };
- }
- if (isStream(value, { checkOpen: false })) {
- return { type: "nodeStream", value, optionName };
- }
- return stdioItem;
-}, getStandardStream = (fdNumber, value, optionName) => {
- const standardStream = STANDARD_STREAMS[fdNumber];
- if (standardStream === undefined) {
- throw new TypeError(`The \`${optionName}: ${value}\` option is invalid: no such standard stream.`);
- }
- return standardStream;
-};
-var init_native = __esm(() => {
- init_standard_stream();
- init_uint_array();
- init_fd_options();
-});
-
-// node_modules/execa/lib/stdio/input-option.js
-var handleInputOptions = ({ input, inputFile }, fdNumber) => fdNumber === 0 ? [
- ...handleInputOption(input),
- ...handleInputFileOption(inputFile)
-] : [], handleInputOption = (input) => input === undefined ? [] : [{
- type: getInputType(input),
- value: input,
- optionName: "input"
-}], getInputType = (input) => {
- if (isReadableStream(input, { checkOpen: false })) {
- return "nodeStream";
- }
- if (typeof input === "string") {
- return "string";
- }
- if (isUint8Array(input)) {
- return "uint8Array";
- }
- throw new Error("The `input` option must be a string, a Uint8Array or a Node.js Readable stream.");
-}, handleInputFileOption = (inputFile) => inputFile === undefined ? [] : [{
- ...getInputFileType(inputFile),
- optionName: "inputFile"
-}], getInputFileType = (inputFile) => {
- if (isUrl(inputFile)) {
- return { type: "fileUrl", value: inputFile };
- }
- if (isFilePathString(inputFile)) {
- return { type: "filePath", value: { file: inputFile } };
- }
- throw new Error("The `inputFile` option must be a file path string or a file URL.");
-};
-var init_input_option = __esm(() => {
- init_uint_array();
- init_type();
-});
-
-// node_modules/execa/lib/stdio/duplicate.js
-var filterDuplicates = (stdioItems) => stdioItems.filter((stdioItemOne, indexOne) => stdioItems.every((stdioItemTwo, indexTwo) => stdioItemOne.value !== stdioItemTwo.value || indexOne >= indexTwo || stdioItemOne.type === "generator" || stdioItemOne.type === "asyncGenerator")), getDuplicateStream = ({ stdioItem: { type, value, optionName }, direction, fileDescriptors, isSync }) => {
- const otherStdioItems = getOtherStdioItems(fileDescriptors, type);
- if (otherStdioItems.length === 0) {
- return;
- }
- if (isSync) {
- validateDuplicateStreamSync({
- otherStdioItems,
- type,
- value,
- optionName,
- direction
- });
- return;
- }
- if (SPECIAL_DUPLICATE_TYPES.has(type)) {
- return getDuplicateStreamInstance({
- otherStdioItems,
- type,
- value,
- optionName,
- direction
- });
- }
- if (FORBID_DUPLICATE_TYPES.has(type)) {
- validateDuplicateTransform({
- otherStdioItems,
- type,
- value,
- optionName
- });
- }
-}, getOtherStdioItems = (fileDescriptors, type) => fileDescriptors.flatMap(({ direction, stdioItems }) => stdioItems.filter((stdioItem) => stdioItem.type === type).map((stdioItem) => ({ ...stdioItem, direction }))), validateDuplicateStreamSync = ({ otherStdioItems, type, value, optionName, direction }) => {
- if (SPECIAL_DUPLICATE_TYPES_SYNC.has(type)) {
- getDuplicateStreamInstance({
- otherStdioItems,
- type,
- value,
- optionName,
- direction
- });
- }
-}, getDuplicateStreamInstance = ({ otherStdioItems, type, value, optionName, direction }) => {
- const duplicateStdioItems = otherStdioItems.filter((stdioItem) => hasSameValue(stdioItem, value));
- if (duplicateStdioItems.length === 0) {
- return;
- }
- const differentStdioItem = duplicateStdioItems.find((stdioItem) => stdioItem.direction !== direction);
- throwOnDuplicateStream(differentStdioItem, optionName, type);
- return direction === "output" ? duplicateStdioItems[0].stream : undefined;
-}, hasSameValue = ({ type, value }, secondValue) => {
- if (type === "filePath") {
- return value.file === secondValue.file;
- }
- if (type === "fileUrl") {
- return value.href === secondValue.href;
- }
- return value === secondValue;
-}, validateDuplicateTransform = ({ otherStdioItems, type, value, optionName }) => {
- const duplicateStdioItem = otherStdioItems.find(({ value: { transform } }) => transform === value.transform);
- throwOnDuplicateStream(duplicateStdioItem, optionName, type);
-}, throwOnDuplicateStream = (stdioItem, optionName, type) => {
- if (stdioItem !== undefined) {
- throw new TypeError(`The \`${stdioItem.optionName}\` and \`${optionName}\` options must not target ${TYPE_TO_MESSAGE[type]} that is the same.`);
- }
-};
-var init_duplicate = __esm(() => {
- init_type();
-});
-
-// node_modules/execa/lib/stdio/handle.js
-var handleStdio = (addProperties, options2, verboseInfo, isSync) => {
- const stdio = normalizeStdioOption(options2, verboseInfo, isSync);
- const initialFileDescriptors = stdio.map((stdioOption, fdNumber) => getFileDescriptor({
- stdioOption,
- fdNumber,
- options: options2,
- isSync
- }));
- const fileDescriptors = getFinalFileDescriptors({
- initialFileDescriptors,
- addProperties,
- options: options2,
- isSync
- });
- options2.stdio = fileDescriptors.map(({ stdioItems }) => forwardStdio(stdioItems));
- return fileDescriptors;
-}, getFileDescriptor = ({ stdioOption, fdNumber, options: options2, isSync }) => {
- const optionName = getStreamName(fdNumber);
- const { stdioItems: initialStdioItems, isStdioArray } = initializeStdioItems({
- stdioOption,
- fdNumber,
- options: options2,
- optionName
- });
- const direction = getStreamDirection(initialStdioItems, fdNumber, optionName);
- const stdioItems = initialStdioItems.map((stdioItem) => handleNativeStream({
- stdioItem,
- isStdioArray,
- fdNumber,
- direction,
- isSync
- }));
- const normalizedStdioItems = normalizeTransforms(stdioItems, optionName, direction, options2);
- const objectMode = getFdObjectMode(normalizedStdioItems, direction);
- validateFileObjectMode(normalizedStdioItems, objectMode);
- return { direction, objectMode, stdioItems: normalizedStdioItems };
-}, initializeStdioItems = ({ stdioOption, fdNumber, options: options2, optionName }) => {
- const values = Array.isArray(stdioOption) ? stdioOption : [stdioOption];
- const initialStdioItems = [
- ...values.map((value) => initializeStdioItem(value, optionName)),
- ...handleInputOptions(options2, fdNumber)
- ];
- const stdioItems = filterDuplicates(initialStdioItems);
- const isStdioArray = stdioItems.length > 1;
- validateStdioArray(stdioItems, isStdioArray, optionName);
- validateStreams(stdioItems);
- return { stdioItems, isStdioArray };
-}, initializeStdioItem = (value, optionName) => ({
- type: getStdioItemType(value, optionName),
- value,
- optionName
-}), validateStdioArray = (stdioItems, isStdioArray, optionName) => {
- if (stdioItems.length === 0) {
- throw new TypeError(`The \`${optionName}\` option must not be an empty array.`);
- }
- if (!isStdioArray) {
- return;
- }
- for (const { value, optionName: optionName2 } of stdioItems) {
- if (INVALID_STDIO_ARRAY_OPTIONS.has(value)) {
- throw new Error(`The \`${optionName2}\` option must not include \`${value}\`.`);
- }
- }
-}, INVALID_STDIO_ARRAY_OPTIONS, validateStreams = (stdioItems) => {
- for (const stdioItem of stdioItems) {
- validateFileStdio(stdioItem);
- }
-}, validateFileStdio = ({ type, value, optionName }) => {
- if (isRegularUrl(value)) {
- throw new TypeError(`The \`${optionName}: URL\` option must use the \`file:\` scheme.
-For example, you can use the \`pathToFileURL()\` method of the \`url\` core module.`);
- }
- if (isUnknownStdioString(type, value)) {
- throw new TypeError(`The \`${optionName}: { file: '...' }\` option must be used instead of \`${optionName}: '...'\`.`);
- }
-}, validateFileObjectMode = (stdioItems, objectMode) => {
- if (!objectMode) {
- return;
- }
- const fileStdioItem = stdioItems.find(({ type }) => FILE_TYPES.has(type));
- if (fileStdioItem !== undefined) {
- throw new TypeError(`The \`${fileStdioItem.optionName}\` option cannot use both files and transforms in objectMode.`);
- }
-}, getFinalFileDescriptors = ({ initialFileDescriptors, addProperties, options: options2, isSync }) => {
- const fileDescriptors = [];
- try {
- for (const fileDescriptor of initialFileDescriptors) {
- fileDescriptors.push(getFinalFileDescriptor({
- fileDescriptor,
- fileDescriptors,
- addProperties,
- options: options2,
- isSync
- }));
- }
- return fileDescriptors;
- } catch (error) {
- cleanupCustomStreams(fileDescriptors);
- throw error;
- }
-}, getFinalFileDescriptor = ({
- fileDescriptor: { direction, objectMode, stdioItems },
- fileDescriptors,
- addProperties,
- options: options2,
- isSync
-}) => {
- const finalStdioItems = stdioItems.map((stdioItem) => addStreamProperties({
- stdioItem,
- addProperties,
- direction,
- options: options2,
- fileDescriptors,
- isSync
- }));
- return { direction, objectMode, stdioItems: finalStdioItems };
-}, addStreamProperties = ({ stdioItem, addProperties, direction, options: options2, fileDescriptors, isSync }) => {
- const duplicateStream = getDuplicateStream({
- stdioItem,
- direction,
- fileDescriptors,
- isSync
- });
- if (duplicateStream !== undefined) {
- return { ...stdioItem, stream: duplicateStream };
- }
- return {
- ...stdioItem,
- ...addProperties[direction][stdioItem.type](stdioItem, options2)
- };
-}, cleanupCustomStreams = (fileDescriptors) => {
- for (const { stdioItems } of fileDescriptors) {
- for (const { stream } of stdioItems) {
- if (stream !== undefined && !isStandardStream(stream)) {
- stream.destroy();
- }
- }
- }
-}, forwardStdio = (stdioItems) => {
- if (stdioItems.length > 1) {
- return stdioItems.some(({ value: value2 }) => value2 === "overlapped") ? "overlapped" : "pipe";
- }
- const [{ type, value }] = stdioItems;
- return type === "native" ? value : "pipe";
-};
-var init_handle = __esm(() => {
- init_standard_stream();
- init_normalize();
- init_object_mode();
- init_type();
- init_direction();
- init_stdio_option();
- init_native();
- init_input_option();
- init_duplicate();
- INVALID_STDIO_ARRAY_OPTIONS = new Set(["ignore", "ipc"]);
-});
-
-// node_modules/execa/lib/stdio/handle-sync.js
-import { readFileSync as readFileSync3 } from "fs";
-var handleStdioSync = (options2, verboseInfo) => handleStdio(addPropertiesSync, options2, verboseInfo, true), forbiddenIfSync = ({ type, optionName }) => {
- throwInvalidSyncValue(optionName, TYPE_TO_MESSAGE[type]);
-}, forbiddenNativeIfSync = ({ optionName, value }) => {
- if (value === "ipc" || value === "overlapped") {
- throwInvalidSyncValue(optionName, `"${value}"`);
- }
- return {};
-}, throwInvalidSyncValue = (optionName, value) => {
- throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`);
-}, addProperties, addPropertiesSync;
-var init_handle_sync = __esm(() => {
- init_uint_array();
- init_handle();
- init_type();
- addProperties = {
- generator() {},
- asyncGenerator: forbiddenIfSync,
- webStream: forbiddenIfSync,
- nodeStream: forbiddenIfSync,
- webTransform: forbiddenIfSync,
- duplex: forbiddenIfSync,
- asyncIterable: forbiddenIfSync,
- native: forbiddenNativeIfSync
- };
- addPropertiesSync = {
- input: {
- ...addProperties,
- fileUrl: ({ value }) => ({ contents: [bufferToUint8Array(readFileSync3(value))] }),
- filePath: ({ value: { file } }) => ({ contents: [bufferToUint8Array(readFileSync3(file))] }),
- fileNumber: forbiddenIfSync,
- iterable: ({ value }) => ({ contents: [...value] }),
- string: ({ value }) => ({ contents: [value] }),
- uint8Array: ({ value }) => ({ contents: [value] })
- },
- output: {
- ...addProperties,
- fileUrl: ({ value }) => ({ path: value }),
- filePath: ({ value: { file, append } }) => ({ path: file, append }),
- fileNumber: ({ value }) => ({ path: value }),
- iterable: forbiddenIfSync,
- string: forbiddenIfSync,
- uint8Array: forbiddenIfSync
- }
- };
-});
-
-// node_modules/execa/lib/io/strip-newline.js
-var stripNewline = (value, { stripFinalNewline: stripFinalNewline2 }, fdNumber) => getStripFinalNewline(stripFinalNewline2, fdNumber) && value !== undefined && !Array.isArray(value) ? stripFinalNewline(value) : value, getStripFinalNewline = (stripFinalNewline2, fdNumber) => fdNumber === "all" ? stripFinalNewline2[1] || stripFinalNewline2[2] : stripFinalNewline2[fdNumber];
-var init_strip_newline = __esm(() => {
- init_strip_final_newline();
-});
-
-// node_modules/execa/lib/transform/split.js
-var getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped ? undefined : initializeSplitLines(preserveNewlines, state), splitLinesSync = (chunk, preserveNewlines, objectMode) => objectMode ? chunk.flatMap((item) => splitLinesItemSync(item, preserveNewlines)) : splitLinesItemSync(chunk, preserveNewlines), splitLinesItemSync = (chunk, preserveNewlines) => {
- const { transform, final } = initializeSplitLines(preserveNewlines, {});
- return [...transform(chunk), ...final()];
-}, initializeSplitLines = (preserveNewlines, state) => {
- state.previousChunks = "";
- return {
- transform: splitGenerator.bind(undefined, state, preserveNewlines),
- final: linesFinal.bind(undefined, state)
- };
-}, splitGenerator = function* (state, preserveNewlines, chunk) {
- if (typeof chunk !== "string") {
- yield chunk;
- return;
- }
- let { previousChunks } = state;
- let start = -1;
- for (let end = 0;end < chunk.length; end += 1) {
- if (chunk[end] === `
-`) {
- const newlineLength = getNewlineLength(chunk, end, preserveNewlines, state);
- let line = chunk.slice(start + 1, end + 1 - newlineLength);
- if (previousChunks.length > 0) {
- line = concatString(previousChunks, line);
- previousChunks = "";
- }
- yield line;
- start = end;
- }
- }
- if (start !== chunk.length - 1) {
- previousChunks = concatString(previousChunks, chunk.slice(start + 1));
- }
- state.previousChunks = previousChunks;
-}, getNewlineLength = (chunk, end, preserveNewlines, state) => {
- if (preserveNewlines) {
- return 0;
- }
- state.isWindowsNewline = end !== 0 && chunk[end - 1] === "\r";
- return state.isWindowsNewline ? 2 : 1;
-}, linesFinal = function* ({ previousChunks }) {
- if (previousChunks.length > 0) {
- yield previousChunks;
- }
-}, getAppendNewlineGenerator = ({ binary, preserveNewlines, readableObjectMode, state }) => binary || preserveNewlines || readableObjectMode ? undefined : { transform: appendNewlineGenerator.bind(undefined, state) }, appendNewlineGenerator = function* ({ isWindowsNewline = false }, chunk) {
- const { unixNewline, windowsNewline, LF: LF2, concatBytes } = typeof chunk === "string" ? linesStringInfo : linesUint8ArrayInfo;
- if (chunk.at(-1) === LF2) {
- yield chunk;
- return;
- }
- const newline2 = isWindowsNewline ? windowsNewline : unixNewline;
- yield concatBytes(chunk, newline2);
-}, concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`, linesStringInfo, concatUint8Array = (firstChunk, secondChunk) => {
- const chunk = new Uint8Array(firstChunk.length + secondChunk.length);
- chunk.set(firstChunk, 0);
- chunk.set(secondChunk, firstChunk.length);
- return chunk;
-}, linesUint8ArrayInfo;
-var init_split = __esm(() => {
- linesStringInfo = {
- windowsNewline: `\r
-`,
- unixNewline: `
-`,
- LF: `
-`,
- concatBytes: concatString
- };
- linesUint8ArrayInfo = {
- windowsNewline: new Uint8Array([13, 10]),
- unixNewline: new Uint8Array([10]),
- LF: 10,
- concatBytes: concatUint8Array
- };
-});
-
-// node_modules/execa/lib/transform/validate.js
-import { Buffer as Buffer4 } from "buffer";
-var getValidateTransformInput = (writableObjectMode, optionName) => writableObjectMode ? undefined : validateStringTransformInput.bind(undefined, optionName), validateStringTransformInput = function* (optionName, chunk) {
- if (typeof chunk !== "string" && !isUint8Array(chunk) && !Buffer4.isBuffer(chunk)) {
- throw new TypeError(`The \`${optionName}\` option's transform must use "objectMode: true" to receive as input: ${typeof chunk}.`);
- }
- yield chunk;
-}, getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode ? validateObjectTransformReturn.bind(undefined, optionName) : validateStringTransformReturn.bind(undefined, optionName), validateObjectTransformReturn = function* (optionName, chunk) {
- validateEmptyReturn(optionName, chunk);
- yield chunk;
-}, validateStringTransformReturn = function* (optionName, chunk) {
- validateEmptyReturn(optionName, chunk);
- if (typeof chunk !== "string" && !isUint8Array(chunk)) {
- throw new TypeError(`The \`${optionName}\` option's function must yield a string or an Uint8Array, not ${typeof chunk}.`);
- }
- yield chunk;
-}, validateEmptyReturn = (optionName, chunk) => {
- if (chunk === null || chunk === undefined) {
- throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`.
-Instead, \`yield\` should either be called with a value, or not be called at all. For example:
- if (condition) { yield value; }`);
- }
-};
-var init_validate = __esm(() => {
- init_uint_array();
-});
-
-// node_modules/execa/lib/transform/encoding-transform.js
-import { Buffer as Buffer5 } from "buffer";
-import { StringDecoder as StringDecoder2 } from "string_decoder";
-var getEncodingTransformGenerator = (binary, encoding, skipped) => {
- if (skipped) {
- return;
- }
- if (binary) {
- return { transform: encodingUint8ArrayGenerator.bind(undefined, new TextEncoder) };
- }
- const stringDecoder = new StringDecoder2(encoding);
- return {
- transform: encodingStringGenerator.bind(undefined, stringDecoder),
- final: encodingStringFinal.bind(undefined, stringDecoder)
- };
-}, encodingUint8ArrayGenerator = function* (textEncoder3, chunk) {
- if (Buffer5.isBuffer(chunk)) {
- yield bufferToUint8Array(chunk);
- } else if (typeof chunk === "string") {
- yield textEncoder3.encode(chunk);
- } else {
- yield chunk;
- }
-}, encodingStringGenerator = function* (stringDecoder, chunk) {
- yield isUint8Array(chunk) ? stringDecoder.write(chunk) : chunk;
-}, encodingStringFinal = function* (stringDecoder) {
- const lastChunk = stringDecoder.end();
- if (lastChunk !== "") {
- yield lastChunk;
- }
-};
-var init_encoding_transform = __esm(() => {
- init_uint_array();
-});
-
-// node_modules/execa/lib/transform/run-async.js
-import { callbackify } from "util";
-var pushChunks, transformChunk = async function* (chunk, generators, index2) {
- if (index2 === generators.length) {
- yield chunk;
- return;
- }
- const { transform = identityGenerator } = generators[index2];
- for await (const transformedChunk of transform(chunk)) {
- yield* transformChunk(transformedChunk, generators, index2 + 1);
- }
-}, finalChunks = async function* (generators) {
- for (const [index2, { final }] of Object.entries(generators)) {
- yield* generatorFinalChunks(final, Number(index2), generators);
- }
-}, generatorFinalChunks = async function* (final, index2, generators) {
- if (final === undefined) {
- return;
- }
- for await (const finalChunk of final()) {
- yield* transformChunk(finalChunk, generators, index2 + 1);
- }
-}, destroyTransform, identityGenerator = function* (chunk) {
- yield chunk;
-};
-var init_run_async = __esm(() => {
- pushChunks = callbackify(async (getChunks, state, getChunksArguments, transformStream) => {
- state.currentIterable = getChunks(...getChunksArguments);
- try {
- for await (const chunk of state.currentIterable) {
- transformStream.push(chunk);
- }
- } finally {
- delete state.currentIterable;
- }
- });
- destroyTransform = callbackify(async ({ currentIterable }, error) => {
- if (currentIterable !== undefined) {
- await (error ? currentIterable.throw(error) : currentIterable.return());
- return;
- }
- if (error) {
- throw error;
- }
- });
-});
-
-// node_modules/execa/lib/transform/run-sync.js
-var pushChunksSync = (getChunksSync, getChunksArguments, transformStream, done) => {
- try {
- for (const chunk of getChunksSync(...getChunksArguments)) {
- transformStream.push(chunk);
- }
- done();
- } catch (error) {
- done(error);
- }
-}, runTransformSync = (generators, chunks) => [
- ...chunks.flatMap((chunk) => [...transformChunkSync(chunk, generators, 0)]),
- ...finalChunksSync(generators)
-], transformChunkSync = function* (chunk, generators, index2) {
- if (index2 === generators.length) {
- yield chunk;
- return;
- }
- const { transform = identityGenerator2 } = generators[index2];
- for (const transformedChunk of transform(chunk)) {
- yield* transformChunkSync(transformedChunk, generators, index2 + 1);
- }
-}, finalChunksSync = function* (generators) {
- for (const [index2, { final }] of Object.entries(generators)) {
- yield* generatorFinalChunksSync(final, Number(index2), generators);
- }
-}, generatorFinalChunksSync = function* (final, index2, generators) {
- if (final === undefined) {
- return;
- }
- for (const finalChunk of final()) {
- yield* transformChunkSync(finalChunk, generators, index2 + 1);
- }
-}, identityGenerator2 = function* (chunk) {
- yield chunk;
-};
-
-// node_modules/execa/lib/transform/generator.js
-import { Transform, getDefaultHighWaterMark } from "stream";
-var generatorToStream = ({
- value,
- value: { transform, final, writableObjectMode, readableObjectMode },
- optionName
-}, { encoding }) => {
- const state = {};
- const generators = addInternalGenerators(value, encoding, optionName);
- const transformAsync = isAsyncGenerator(transform);
- const finalAsync = isAsyncGenerator(final);
- const transformMethod = transformAsync ? pushChunks.bind(undefined, transformChunk, state) : pushChunksSync.bind(undefined, transformChunkSync);
- const finalMethod = transformAsync || finalAsync ? pushChunks.bind(undefined, finalChunks, state) : pushChunksSync.bind(undefined, finalChunksSync);
- const destroyMethod = transformAsync || finalAsync ? destroyTransform.bind(undefined, state) : undefined;
- const stream = new Transform({
- writableObjectMode,
- writableHighWaterMark: getDefaultHighWaterMark(writableObjectMode),
- readableObjectMode,
- readableHighWaterMark: getDefaultHighWaterMark(readableObjectMode),
- transform(chunk, encoding2, done) {
- transformMethod([chunk, generators, 0], this, done);
- },
- flush(done) {
- finalMethod([generators], this, done);
- },
- destroy: destroyMethod
- });
- return { stream };
-}, runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => {
- const generators = stdioItems.filter(({ type }) => type === "generator");
- const reversedGenerators = isInput ? generators.reverse() : generators;
- for (const { value, optionName } of reversedGenerators) {
- const generators2 = addInternalGenerators(value, encoding, optionName);
- chunks = runTransformSync(generators2, chunks);
- }
- return chunks;
-}, addInternalGenerators = ({ transform, final, binary, writableObjectMode, readableObjectMode, preserveNewlines }, encoding, optionName) => {
- const state = {};
- return [
- { transform: getValidateTransformInput(writableObjectMode, optionName) },
- getEncodingTransformGenerator(binary, encoding, writableObjectMode),
- getSplitLinesGenerator(binary, preserveNewlines, writableObjectMode, state),
- { transform, final },
- { transform: getValidateTransformReturn(readableObjectMode, optionName) },
- getAppendNewlineGenerator({
- binary,
- preserveNewlines,
- readableObjectMode,
- state
- })
- ].filter(Boolean);
-};
-var init_generator = __esm(() => {
- init_type();
- init_split();
- init_validate();
- init_encoding_transform();
- init_run_async();
-});
-
-// node_modules/execa/lib/io/input-sync.js
-var addInputOptionsSync = (fileDescriptors, options2) => {
- for (const fdNumber of getInputFdNumbers(fileDescriptors)) {
- addInputOptionSync(fileDescriptors, fdNumber, options2);
- }
-}, getInputFdNumbers = (fileDescriptors) => new Set(Object.entries(fileDescriptors).filter(([, { direction }]) => direction === "input").map(([fdNumber]) => Number(fdNumber))), addInputOptionSync = (fileDescriptors, fdNumber, options2) => {
- const { stdioItems } = fileDescriptors[fdNumber];
- const allStdioItems = stdioItems.filter(({ contents }) => contents !== undefined);
- if (allStdioItems.length === 0) {
- return;
- }
- if (fdNumber !== 0) {
- const [{ type, optionName }] = allStdioItems;
- throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`);
- }
- const allContents = allStdioItems.map(({ contents }) => contents);
- const transformedContents = allContents.map((contents) => applySingleInputGeneratorsSync(contents, stdioItems));
- options2.input = joinToUint8Array(transformedContents);
-}, applySingleInputGeneratorsSync = (contents, stdioItems) => {
- const newContents = runGeneratorsSync(contents, stdioItems, "utf8", true);
- validateSerializable(newContents);
- return joinToUint8Array(newContents);
-}, validateSerializable = (newContents) => {
- const invalidItem = newContents.find((item) => typeof item !== "string" && !isUint8Array(item));
- if (invalidItem !== undefined) {
- throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${invalidItem}.`);
- }
-};
-var init_input_sync = __esm(() => {
- init_generator();
- init_uint_array();
- init_type();
-});
-
-// node_modules/execa/lib/verbose/output.js
-var shouldLogOutput = ({ stdioItems, encoding, verboseInfo, fdNumber }) => fdNumber !== "all" && isFullVerbose(verboseInfo, fdNumber) && !BINARY_ENCODINGS.has(encoding) && fdUsesVerbose(fdNumber) && (stdioItems.some(({ type, value }) => type === "native" && PIPED_STDIO_VALUES.has(value)) || stdioItems.every(({ type }) => TRANSFORM_TYPES.has(type))), fdUsesVerbose = (fdNumber) => fdNumber === 1 || fdNumber === 2, PIPED_STDIO_VALUES, logLines = async (linesIterable, stream, fdNumber, verboseInfo) => {
- for await (const line of linesIterable) {
- if (!isPipingStream(stream)) {
- logLine(line, fdNumber, verboseInfo);
- }
- }
-}, logLinesSync = (linesArray, fdNumber, verboseInfo) => {
- for (const line of linesArray) {
- logLine(line, fdNumber, verboseInfo);
- }
-}, isPipingStream = (stream) => stream._readableState.pipes.length > 0, logLine = (line, fdNumber, verboseInfo) => {
- const verboseMessage = serializeVerboseMessage(line);
- verboseLog({
- type: "output",
- verboseMessage,
- fdNumber,
- verboseInfo
- });
-};
-var init_output = __esm(() => {
- init_encoding_option();
- init_type();
- init_log();
- init_values();
- PIPED_STDIO_VALUES = new Set(["pipe", "overlapped"]);
-});
-
-// node_modules/execa/lib/io/output-sync.js
-import { writeFileSync, appendFileSync as appendFileSync2 } from "fs";
-var transformOutputSync = ({ fileDescriptors, syncResult: { output }, options: options2, isMaxBuffer, verboseInfo }) => {
- if (output === null) {
- return { output: Array.from({ length: 3 }) };
- }
- const state = {};
- const outputFiles = new Set([]);
- const transformedOutput = output.map((result, fdNumber) => transformOutputResultSync({
- result,
- fileDescriptors,
- fdNumber,
- state,
- outputFiles,
- isMaxBuffer,
- verboseInfo
- }, options2));
- return { output: transformedOutput, ...state };
-}, transformOutputResultSync = ({ result, fileDescriptors, fdNumber, state, outputFiles, isMaxBuffer, verboseInfo }, { buffer, encoding, lines, stripFinalNewline: stripFinalNewline2, maxBuffer }) => {
- if (result === null) {
- return;
- }
- const truncatedResult = truncateMaxBufferSync(result, isMaxBuffer, maxBuffer);
- const uint8ArrayResult = bufferToUint8Array(truncatedResult);
- const { stdioItems, objectMode } = fileDescriptors[fdNumber];
- const chunks = runOutputGeneratorsSync([uint8ArrayResult], stdioItems, encoding, state);
- const { serializedResult, finalResult = serializedResult } = serializeChunks({
- chunks,
- objectMode,
- encoding,
- lines,
- stripFinalNewline: stripFinalNewline2,
- fdNumber
- });
- logOutputSync({
- serializedResult,
- fdNumber,
- state,
- verboseInfo,
- encoding,
- stdioItems,
- objectMode
- });
- const returnedResult = buffer[fdNumber] ? finalResult : undefined;
- try {
- if (state.error === undefined) {
- writeToFiles(serializedResult, stdioItems, outputFiles);
- }
- return returnedResult;
- } catch (error) {
- state.error = error;
- return returnedResult;
- }
-}, runOutputGeneratorsSync = (chunks, stdioItems, encoding, state) => {
- try {
- return runGeneratorsSync(chunks, stdioItems, encoding, false);
- } catch (error) {
- state.error = error;
- return chunks;
- }
-}, serializeChunks = ({ chunks, objectMode, encoding, lines, stripFinalNewline: stripFinalNewline2, fdNumber }) => {
- if (objectMode) {
- return { serializedResult: chunks };
- }
- if (encoding === "buffer") {
- return { serializedResult: joinToUint8Array(chunks) };
- }
- const serializedResult = joinToString(chunks, encoding);
- if (lines[fdNumber]) {
- return { serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline2[fdNumber], objectMode) };
- }
- return { serializedResult };
-}, logOutputSync = ({ serializedResult, fdNumber, state, verboseInfo, encoding, stdioItems, objectMode }) => {
- if (!shouldLogOutput({
- stdioItems,
- encoding,
- verboseInfo,
- fdNumber
- })) {
- return;
- }
- const linesArray = splitLinesSync(serializedResult, false, objectMode);
- try {
- logLinesSync(linesArray, fdNumber, verboseInfo);
- } catch (error) {
- state.error ??= error;
- }
-}, writeToFiles = (serializedResult, stdioItems, outputFiles) => {
- for (const { path: path6, append } of stdioItems.filter(({ type }) => FILE_TYPES.has(type))) {
- const pathString = typeof path6 === "string" ? path6 : path6.toString();
- if (append || outputFiles.has(pathString)) {
- appendFileSync2(path6, serializedResult);
- } else {
- outputFiles.add(pathString);
- writeFileSync(path6, serializedResult);
- }
- }
-};
-var init_output_sync = __esm(() => {
- init_output();
- init_generator();
- init_split();
- init_uint_array();
- init_type();
- init_max_buffer();
-});
-
-// node_modules/execa/lib/resolve/all-sync.js
-var getAllSync = ([, stdout, stderr], options2) => {
- if (!options2.all) {
- return;
- }
- if (stdout === undefined) {
- return stderr;
- }
- if (stderr === undefined) {
- return stdout;
- }
- if (Array.isArray(stdout)) {
- return Array.isArray(stderr) ? [...stdout, ...stderr] : [...stdout, stripNewline(stderr, options2, "all")];
- }
- if (Array.isArray(stderr)) {
- return [stripNewline(stdout, options2, "all"), ...stderr];
- }
- if (isUint8Array(stdout) && isUint8Array(stderr)) {
- return concatUint8Arrays([stdout, stderr]);
- }
- return `${stdout}${stderr}`;
-};
-var init_all_sync = __esm(() => {
- init_uint_array();
- init_strip_newline();
-});
-
-// node_modules/execa/lib/resolve/exit-async.js
-import { once as once4 } from "events";
-var waitForExit = async (subprocess, context) => {
- const [exitCode, signal] = await waitForExitOrError(subprocess);
- context.isForcefullyTerminated ??= false;
- return [exitCode, signal];
-}, waitForExitOrError = async (subprocess) => {
- const [spawnPayload, exitPayload] = await Promise.allSettled([
- once4(subprocess, "spawn"),
- once4(subprocess, "exit")
- ]);
- if (spawnPayload.status === "rejected") {
- return [];
- }
- return exitPayload.status === "rejected" ? waitForSubprocessExit(subprocess) : exitPayload.value;
-}, waitForSubprocessExit = async (subprocess) => {
- try {
- return await once4(subprocess, "exit");
- } catch {
- return waitForSubprocessExit(subprocess);
- }
-}, waitForSuccessfulExit = async (exitPromise) => {
- const [exitCode, signal] = await exitPromise;
- if (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {
- throw new DiscardedError;
- }
- return [exitCode, signal];
-}, isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined, isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;
-var init_exit_async = __esm(() => {
- init_final_error();
-});
-
-// node_modules/execa/lib/resolve/exit-sync.js
-var getExitResultSync = ({ error, status: exitCode, signal, output }, { maxBuffer }) => {
- const resultError = getResultError(error, exitCode, signal);
- const timedOut = resultError?.code === "ETIMEDOUT";
- const isMaxBuffer = isMaxBufferSync(resultError, output, maxBuffer);
- return {
- resultError,
- exitCode,
- signal,
- timedOut,
- isMaxBuffer
- };
-}, getResultError = (error, exitCode, signal) => {
- if (error !== undefined) {
- return error;
- }
- return isFailedExit(exitCode, signal) ? new DiscardedError : undefined;
-};
-var init_exit_sync = __esm(() => {
- init_final_error();
- init_max_buffer();
- init_exit_async();
-});
-
-// node_modules/execa/lib/methods/main-sync.js
-import { spawnSync } from "child_process";
-var execaCoreSync = (rawFile, rawArguments, rawOptions) => {
- const { file, commandArguments, command, escapedCommand, startTime, verboseInfo, options: options2, fileDescriptors } = handleSyncArguments(rawFile, rawArguments, rawOptions);
- const result = spawnSubprocessSync({
- file,
- commandArguments,
- options: options2,
- command,
- escapedCommand,
- verboseInfo,
- fileDescriptors,
- startTime
- });
- return handleResult(result, verboseInfo, options2);
-}, handleSyncArguments = (rawFile, rawArguments, rawOptions) => {
- const { command, escapedCommand, startTime, verboseInfo } = handleCommand(rawFile, rawArguments, rawOptions);
- const syncOptions = normalizeSyncOptions(rawOptions);
- const { file, commandArguments, options: options2 } = normalizeOptions(rawFile, rawArguments, syncOptions);
- validateSyncOptions(options2);
- const fileDescriptors = handleStdioSync(options2, verboseInfo);
- return {
- file,
- commandArguments,
- command,
- escapedCommand,
- startTime,
- verboseInfo,
- options: options2,
- fileDescriptors
- };
-}, normalizeSyncOptions = (options2) => options2.node && !options2.ipc ? { ...options2, ipc: false } : options2, validateSyncOptions = ({ ipc, ipcInput, detached, cancelSignal }) => {
- if (ipcInput) {
- throwInvalidSyncOption("ipcInput");
- }
- if (ipc) {
- throwInvalidSyncOption("ipc: true");
- }
- if (detached) {
- throwInvalidSyncOption("detached: true");
- }
- if (cancelSignal) {
- throwInvalidSyncOption("cancelSignal");
- }
-}, throwInvalidSyncOption = (value) => {
- throw new TypeError(`The "${value}" option cannot be used with synchronous methods.`);
-}, spawnSubprocessSync = ({ file, commandArguments, options: options2, command, escapedCommand, verboseInfo, fileDescriptors, startTime }) => {
- const syncResult = runSubprocessSync({
- file,
- commandArguments,
- options: options2,
- command,
- escapedCommand,
- fileDescriptors,
- startTime
- });
- if (syncResult.failed) {
- return syncResult;
- }
- const { resultError, exitCode, signal, timedOut, isMaxBuffer } = getExitResultSync(syncResult, options2);
- const { output, error = resultError } = transformOutputSync({
- fileDescriptors,
- syncResult,
- options: options2,
- isMaxBuffer,
- verboseInfo
- });
- const stdio = output.map((stdioOutput, fdNumber) => stripNewline(stdioOutput, options2, fdNumber));
- const all = stripNewline(getAllSync(output, options2), options2, "all");
- return getSyncResult({
- error,
- exitCode,
- signal,
- timedOut,
- isMaxBuffer,
- stdio,
- all,
- options: options2,
- command,
- escapedCommand,
- startTime
- });
-}, runSubprocessSync = ({ file, commandArguments, options: options2, command, escapedCommand, fileDescriptors, startTime }) => {
- try {
- addInputOptionsSync(fileDescriptors, options2);
- const normalizedOptions = normalizeSpawnSyncOptions(options2);
- return spawnSync(...concatenateShell(file, commandArguments, normalizedOptions));
- } catch (error) {
- return makeEarlyError({
- error,
- command,
- escapedCommand,
- fileDescriptors,
- options: options2,
- startTime,
- isSync: true
- });
- }
-}, normalizeSpawnSyncOptions = ({ encoding, maxBuffer, ...options2 }) => ({ ...options2, encoding: "buffer", maxBuffer: getMaxBufferSync(maxBuffer) }), getSyncResult = ({ error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options: options2, command, escapedCommand, startTime }) => error === undefined ? makeSuccessResult({
- command,
- escapedCommand,
- stdio,
- all,
- ipcOutput: [],
- options: options2,
- startTime
-}) : makeError({
- error,
- command,
- escapedCommand,
- timedOut,
- isCanceled: false,
- isGracefullyCanceled: false,
- isMaxBuffer,
- isForcefullyTerminated: false,
- exitCode,
- signal,
- stdio,
- all,
- ipcOutput: [],
- options: options2,
- startTime,
- isSync: true
-});
-var init_main_sync = __esm(() => {
- init_command();
- init_options();
- init_result();
- init_reject();
- init_handle_sync();
- init_strip_newline();
- init_input_sync();
- init_output_sync();
- init_max_buffer();
- init_all_sync();
- init_exit_sync();
-});
-
-// node_modules/execa/lib/ipc/get-one.js
-import { once as once5, on as on2 } from "events";
-var getOneMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = true, filter } = {}) => {
- validateIpcMethod({
- methodName: "getOneMessage",
- isSubprocess,
- ipc,
- isConnected: isConnected(anyProcess)
- });
- return getOneMessageAsync({
- anyProcess,
- channel,
- isSubprocess,
- filter,
- reference
- });
-}, getOneMessageAsync = async ({ anyProcess, channel, isSubprocess, filter, reference }) => {
- addReference(channel, reference);
- const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);
- const controller = new AbortController;
- try {
- return await Promise.race([
- getMessage(ipcEmitter, filter, controller),
- throwOnDisconnect2(ipcEmitter, isSubprocess, controller),
- throwOnStrictError(ipcEmitter, isSubprocess, controller)
- ]);
- } catch (error) {
- disconnect(anyProcess);
- throw error;
- } finally {
- controller.abort();
- removeReference(channel, reference);
- }
-}, getMessage = async (ipcEmitter, filter, { signal }) => {
- if (filter === undefined) {
- const [message] = await once5(ipcEmitter, "message", { signal });
- return message;
- }
- for await (const [message] of on2(ipcEmitter, "message", { signal })) {
- if (filter(message)) {
- return message;
- }
- }
-}, throwOnDisconnect2 = async (ipcEmitter, isSubprocess, { signal }) => {
- await once5(ipcEmitter, "disconnect", { signal });
- throwOnEarlyDisconnect(isSubprocess);
-}, throwOnStrictError = async (ipcEmitter, isSubprocess, { signal }) => {
- const [error] = await once5(ipcEmitter, "strict:error", { signal });
- throw getStrictResponseError(error, isSubprocess);
-};
-var init_get_one = __esm(() => {
- init_validation();
- init_forward();
-});
-
-// node_modules/execa/lib/ipc/get-each.js
-import { once as once6, on as on3 } from "events";
-var getEachMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = true } = {}) => loopOnMessages({
- anyProcess,
- channel,
- isSubprocess,
- ipc,
- shouldAwait: !isSubprocess,
- reference
-}), loopOnMessages = ({ anyProcess, channel, isSubprocess, ipc, shouldAwait, reference }) => {
- validateIpcMethod({
- methodName: "getEachMessage",
- isSubprocess,
- ipc,
- isConnected: isConnected(anyProcess)
- });
- addReference(channel, reference);
- const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);
- const controller = new AbortController;
- const state = {};
- stopOnDisconnect(anyProcess, ipcEmitter, controller);
- abortOnStrictError({
- ipcEmitter,
- isSubprocess,
- controller,
- state
- });
- return iterateOnMessages({
- anyProcess,
- channel,
- ipcEmitter,
- isSubprocess,
- shouldAwait,
- controller,
- state,
- reference
- });
-}, stopOnDisconnect = async (anyProcess, ipcEmitter, controller) => {
- try {
- await once6(ipcEmitter, "disconnect", { signal: controller.signal });
- controller.abort();
- } catch {}
-}, abortOnStrictError = async ({ ipcEmitter, isSubprocess, controller, state }) => {
- try {
- const [error] = await once6(ipcEmitter, "strict:error", { signal: controller.signal });
- state.error = getStrictResponseError(error, isSubprocess);
- controller.abort();
- } catch {}
-}, iterateOnMessages = async function* ({ anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state, reference }) {
- try {
- for await (const [message] of on3(ipcEmitter, "message", { signal: controller.signal })) {
- throwIfStrictError(state);
- yield message;
- }
- } catch {
- throwIfStrictError(state);
- } finally {
- controller.abort();
- removeReference(channel, reference);
- if (!isSubprocess) {
- disconnect(anyProcess);
- }
- if (shouldAwait) {
- await anyProcess;
- }
- }
-}, throwIfStrictError = ({ error }) => {
- if (error) {
- throw error;
- }
-};
-var init_get_each = __esm(() => {
- init_validation();
- init_forward();
-});
-
-// node_modules/execa/lib/ipc/methods.js
-import process9 from "process";
-var addIpcMethods = (subprocess, { ipc }) => {
- Object.assign(subprocess, getIpcMethods(subprocess, false, ipc));
-}, getIpcExport = () => {
- const anyProcess = process9;
- const isSubprocess = true;
- const ipc = process9.channel !== undefined;
- return {
- ...getIpcMethods(anyProcess, isSubprocess, ipc),
- getCancelSignal: getCancelSignal.bind(undefined, {
- anyProcess,
- channel: anyProcess.channel,
- isSubprocess,
- ipc
- })
- };
-}, getIpcMethods = (anyProcess, isSubprocess, ipc) => ({
- sendMessage: sendMessage.bind(undefined, {
- anyProcess,
- channel: anyProcess.channel,
- isSubprocess,
- ipc
- }),
- getOneMessage: getOneMessage.bind(undefined, {
- anyProcess,
- channel: anyProcess.channel,
- isSubprocess,
- ipc
- }),
- getEachMessage: getEachMessage.bind(undefined, {
- anyProcess,
- channel: anyProcess.channel,
- isSubprocess,
- ipc
- })
-});
-var init_methods = __esm(() => {
- init_send();
- init_get_one();
- init_get_each();
- init_graceful();
-});
-
-// node_modules/execa/lib/return/early-error.js
-import { ChildProcess as ChildProcess2 } from "child_process";
-import {
- PassThrough,
- Readable,
- Writable,
- Duplex
-} from "stream";
-var handleEarlyError = ({ error, command, escapedCommand, fileDescriptors, options: options2, startTime, verboseInfo }) => {
- cleanupCustomStreams(fileDescriptors);
- const subprocess = new ChildProcess2;
- createDummyStreams(subprocess, fileDescriptors);
- Object.assign(subprocess, { readable, writable, duplex });
- const earlyError = makeEarlyError({
- error,
- command,
- escapedCommand,
- fileDescriptors,
- options: options2,
- startTime,
- isSync: false
- });
- const promise = handleDummyPromise(earlyError, verboseInfo, options2);
- return { subprocess, promise };
-}, createDummyStreams = (subprocess, fileDescriptors) => {
- const stdin = createDummyStream();
- const stdout = createDummyStream();
- const stderr = createDummyStream();
- const extraStdio = Array.from({ length: fileDescriptors.length - 3 }, createDummyStream);
- const all = createDummyStream();
- const stdio = [stdin, stdout, stderr, ...extraStdio];
- Object.assign(subprocess, {
- stdin,
- stdout,
- stderr,
- all,
- stdio
- });
-}, createDummyStream = () => {
- const stream = new PassThrough;
- stream.end();
- return stream;
-}, readable = () => new Readable({ read() {} }), writable = () => new Writable({ write() {} }), duplex = () => new Duplex({ read() {}, write() {} }), handleDummyPromise = async (error, verboseInfo, options2) => handleResult(error, verboseInfo, options2);
-var init_early_error = __esm(() => {
- init_handle();
- init_result();
- init_reject();
-});
-
-// node_modules/execa/lib/stdio/handle-async.js
-import { createReadStream, createWriteStream as createWriteStream2 } from "fs";
-import { Buffer as Buffer6 } from "buffer";
-import { Readable as Readable2, Writable as Writable2, Duplex as Duplex2 } from "stream";
-var handleStdioAsync = (options2, verboseInfo) => handleStdio(addPropertiesAsync, options2, verboseInfo, false), forbiddenIfAsync = ({ type, optionName }) => {
- throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);
-}, addProperties2, addPropertiesAsync;
-var init_handle_async = __esm(() => {
- init_generator();
- init_handle();
- init_type();
- addProperties2 = {
- fileNumber: forbiddenIfAsync,
- generator: generatorToStream,
- asyncGenerator: generatorToStream,
- nodeStream: ({ value }) => ({ stream: value }),
- webTransform({ value: { transform, writableObjectMode, readableObjectMode } }) {
- const objectMode = writableObjectMode || readableObjectMode;
- const stream = Duplex2.fromWeb(transform, { objectMode });
- return { stream };
- },
- duplex: ({ value: { transform } }) => ({ stream: transform }),
- native() {}
- };
- addPropertiesAsync = {
- input: {
- ...addProperties2,
- fileUrl: ({ value }) => ({ stream: createReadStream(value) }),
- filePath: ({ value: { file } }) => ({ stream: createReadStream(file) }),
- webStream: ({ value }) => ({ stream: Readable2.fromWeb(value) }),
- iterable: ({ value }) => ({ stream: Readable2.from(value) }),
- asyncIterable: ({ value }) => ({ stream: Readable2.from(value) }),
- string: ({ value }) => ({ stream: Readable2.from(value) }),
- uint8Array: ({ value }) => ({ stream: Readable2.from(Buffer6.from(value)) })
- },
- output: {
- ...addProperties2,
- fileUrl: ({ value }) => ({ stream: createWriteStream2(value) }),
- filePath: ({ value: { file, append } }) => ({ stream: createWriteStream2(file, append ? { flags: "a" } : {}) }),
- webStream: ({ value }) => ({ stream: Writable2.fromWeb(value) }),
- iterable: forbiddenIfAsync,
- asyncIterable: forbiddenIfAsync,
- string: forbiddenIfAsync,
- uint8Array: forbiddenIfAsync
- }
- };
-});
-
-// node_modules/@sindresorhus/merge-streams/index.js
-import { on as on4, once as once7 } from "events";
-import { PassThrough as PassThroughStream, getDefaultHighWaterMark as getDefaultHighWaterMark2 } from "stream";
-import { finished as finished2 } from "stream/promises";
-function mergeStreams(streams2) {
- if (!Array.isArray(streams2)) {
- throw new TypeError(`Expected an array, got \`${typeof streams2}\`.`);
- }
- for (const stream of streams2) {
- validateStream(stream);
- }
- const objectMode = streams2.some(({ readableObjectMode }) => readableObjectMode);
- const highWaterMark = getHighWaterMark(streams2, objectMode);
- const passThroughStream = new MergedStream({
- objectMode,
- writableHighWaterMark: highWaterMark,
- readableHighWaterMark: highWaterMark
- });
- for (const stream of streams2) {
- passThroughStream.add(stream);
- }
- return passThroughStream;
-}
-var getHighWaterMark = (streams2, objectMode) => {
- if (streams2.length === 0) {
- return getDefaultHighWaterMark2(objectMode);
- }
- const highWaterMarks = streams2.filter(({ readableObjectMode }) => readableObjectMode === objectMode).map(({ readableHighWaterMark }) => readableHighWaterMark);
- return Math.max(...highWaterMarks);
-}, MergedStream, onMergedStreamFinished = async (passThroughStream, streams2, unpipeEvent) => {
- updateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_COUNT);
- const controller = new AbortController;
- try {
- await Promise.race([
- onMergedStreamEnd(passThroughStream, controller),
- onInputStreamsUnpipe(passThroughStream, streams2, unpipeEvent, controller)
- ]);
- } finally {
- controller.abort();
- updateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_COUNT);
- }
-}, onMergedStreamEnd = async (passThroughStream, { signal }) => {
- try {
- await finished2(passThroughStream, { signal, cleanup: true });
- } catch (error) {
- errorOrAbortStream(passThroughStream, error);
- throw error;
- }
-}, onInputStreamsUnpipe = async (passThroughStream, streams2, unpipeEvent, { signal }) => {
- for await (const [unpipedStream] of on4(passThroughStream, "unpipe", { signal })) {
- if (streams2.has(unpipedStream)) {
- unpipedStream.emit(unpipeEvent);
- }
- }
-}, validateStream = (stream) => {
- if (typeof stream?.pipe !== "function") {
- throw new TypeError(`Expected a readable stream, got: \`${typeof stream}\`.`);
- }
-}, endWhenStreamsDone = async ({ passThroughStream, stream, streams: streams2, ended, aborted, onFinished, unpipeEvent }) => {
- updateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_PER_STREAM);
- const controller = new AbortController;
- try {
- await Promise.race([
- afterMergedStreamFinished(onFinished, stream, controller),
- onInputStreamEnd({
- passThroughStream,
- stream,
- streams: streams2,
- ended,
- aborted,
- controller
- }),
- onInputStreamUnpipe({
- stream,
- streams: streams2,
- ended,
- aborted,
- unpipeEvent,
- controller
- })
- ]);
- } finally {
- controller.abort();
- updateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_PER_STREAM);
- }
- if (streams2.size > 0 && streams2.size === ended.size + aborted.size) {
- if (ended.size === 0 && aborted.size > 0) {
- abortStream(passThroughStream);
- } else {
- endStream(passThroughStream);
- }
- }
-}, afterMergedStreamFinished = async (onFinished, stream, { signal }) => {
- try {
- await onFinished;
- if (!signal.aborted) {
- abortStream(stream);
- }
- } catch (error) {
- if (!signal.aborted) {
- errorOrAbortStream(stream, error);
- }
- }
-}, onInputStreamEnd = async ({ passThroughStream, stream, streams: streams2, ended, aborted, controller: { signal } }) => {
- try {
- await finished2(stream, {
- signal,
- cleanup: true,
- readable: true,
- writable: false
- });
- if (streams2.has(stream)) {
- ended.add(stream);
- }
- } catch (error) {
- if (signal.aborted || !streams2.has(stream)) {
- return;
- }
- if (isAbortError2(error)) {
- aborted.add(stream);
- } else {
- errorStream(passThroughStream, error);
- }
- }
-}, onInputStreamUnpipe = async ({ stream, streams: streams2, ended, aborted, unpipeEvent, controller: { signal } }) => {
- await once7(stream, unpipeEvent, { signal });
- if (!stream.readable) {
- return once7(signal, "abort", { signal });
- }
- streams2.delete(stream);
- ended.delete(stream);
- aborted.delete(stream);
-}, endStream = (stream) => {
- if (stream.writable) {
- stream.end();
- }
-}, errorOrAbortStream = (stream, error) => {
- if (isAbortError2(error)) {
- abortStream(stream);
- } else {
- errorStream(stream, error);
- }
-}, isAbortError2 = (error) => error?.code === "ERR_STREAM_PREMATURE_CLOSE", abortStream = (stream) => {
- if (stream.readable || stream.writable) {
- stream.destroy();
- }
-}, errorStream = (stream, error) => {
- if (!stream.destroyed) {
- stream.once("error", noop4);
- stream.destroy(error);
- }
-}, noop4 = () => {}, updateMaxListeners = (passThroughStream, increment2) => {
- const maxListeners = passThroughStream.getMaxListeners();
- if (maxListeners !== 0 && maxListeners !== Number.POSITIVE_INFINITY) {
- passThroughStream.setMaxListeners(maxListeners + increment2);
- }
-}, PASSTHROUGH_LISTENERS_COUNT = 2, PASSTHROUGH_LISTENERS_PER_STREAM = 1;
-var init_merge_streams = __esm(() => {
- MergedStream = class MergedStream extends PassThroughStream {
- #streams = new Set([]);
- #ended = new Set([]);
- #aborted = new Set([]);
- #onFinished;
- #unpipeEvent = Symbol("unpipe");
- #streamPromises = new WeakMap;
- add(stream) {
- validateStream(stream);
- if (this.#streams.has(stream)) {
- return;
- }
- this.#streams.add(stream);
- this.#onFinished ??= onMergedStreamFinished(this, this.#streams, this.#unpipeEvent);
- const streamPromise = endWhenStreamsDone({
- passThroughStream: this,
- stream,
- streams: this.#streams,
- ended: this.#ended,
- aborted: this.#aborted,
- onFinished: this.#onFinished,
- unpipeEvent: this.#unpipeEvent
- });
- this.#streamPromises.set(stream, streamPromise);
- stream.pipe(this, { end: false });
- }
- async remove(stream) {
- validateStream(stream);
- if (!this.#streams.has(stream)) {
- return false;
- }
- const streamPromise = this.#streamPromises.get(stream);
- if (streamPromise === undefined) {
- return false;
- }
- this.#streamPromises.delete(stream);
- stream.unpipe(this);
- await streamPromise;
- return true;
- }
- };
-});
-
-// node_modules/execa/lib/io/pipeline.js
-import { finished as finished3 } from "stream/promises";
-var pipeStreams = (source, destination) => {
- source.pipe(destination);
- onSourceFinish(source, destination);
- onDestinationFinish(source, destination);
-}, onSourceFinish = async (source, destination) => {
- if (isStandardStream(source) || isStandardStream(destination)) {
- return;
- }
- try {
- await finished3(source, { cleanup: true, readable: true, writable: false });
- } catch {}
- endDestinationStream(destination);
-}, endDestinationStream = (destination) => {
- if (destination.writable) {
- destination.end();
- }
-}, onDestinationFinish = async (source, destination) => {
- if (isStandardStream(source) || isStandardStream(destination)) {
- return;
- }
- try {
- await finished3(destination, { cleanup: true, readable: false, writable: true });
- } catch {}
- abortSourceStream(source);
-}, abortSourceStream = (source) => {
- if (source.readable) {
- source.destroy();
- }
-};
-var init_pipeline = __esm(() => {
- init_standard_stream();
-});
-
-// node_modules/execa/lib/io/output-async.js
-var pipeOutputAsync = (subprocess, fileDescriptors, controller) => {
- const pipeGroups = new Map;
- for (const [fdNumber, { stdioItems, direction }] of Object.entries(fileDescriptors)) {
- for (const { stream } of stdioItems.filter(({ type }) => TRANSFORM_TYPES.has(type))) {
- pipeTransform(subprocess, stream, direction, fdNumber);
- }
- for (const { stream } of stdioItems.filter(({ type }) => !TRANSFORM_TYPES.has(type))) {
- pipeStdioItem({
- subprocess,
- stream,
- direction,
- fdNumber,
- pipeGroups,
- controller
- });
- }
- }
- for (const [outputStream, inputStreams] of pipeGroups.entries()) {
- const inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams);
- pipeStreams(inputStream, outputStream);
- }
-}, pipeTransform = (subprocess, stream, direction, fdNumber) => {
- if (direction === "output") {
- pipeStreams(subprocess.stdio[fdNumber], stream);
- } else {
- pipeStreams(stream, subprocess.stdio[fdNumber]);
- }
- const streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];
- if (streamProperty !== undefined) {
- subprocess[streamProperty] = stream;
- }
- subprocess.stdio[fdNumber] = stream;
-}, SUBPROCESS_STREAM_PROPERTIES, pipeStdioItem = ({ subprocess, stream, direction, fdNumber, pipeGroups, controller }) => {
- if (stream === undefined) {
- return;
- }
- setStandardStreamMaxListeners(stream, controller);
- const [inputStream, outputStream] = direction === "output" ? [stream, subprocess.stdio[fdNumber]] : [subprocess.stdio[fdNumber], stream];
- const outputStreams = pipeGroups.get(inputStream) ?? [];
- pipeGroups.set(inputStream, [...outputStreams, outputStream]);
-}, setStandardStreamMaxListeners = (stream, { signal }) => {
- if (isStandardStream(stream)) {
- incrementMaxListeners(stream, MAX_LISTENERS_INCREMENT, signal);
- }
-}, MAX_LISTENERS_INCREMENT = 2;
-var init_output_async = __esm(() => {
- init_merge_streams();
- init_standard_stream();
- init_max_listeners();
- init_type();
- init_pipeline();
- SUBPROCESS_STREAM_PROPERTIES = ["stdin", "stdout", "stderr"];
-});
-
-// node_modules/signal-exit/dist/mjs/signals.js
-var signals;
-var init_signals2 = __esm(() => {
- signals = [];
- signals.push("SIGHUP", "SIGINT", "SIGTERM");
- if (process.platform !== "win32") {
- signals.push("SIGALRM", "SIGABRT", "SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
- }
- if (process.platform === "linux") {
- signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT");
- }
-});
-
-// node_modules/signal-exit/dist/mjs/index.js
-class Emitter {
- emitted = {
- afterExit: false,
- exit: false
- };
- listeners = {
- afterExit: [],
- exit: []
- };
- count = 0;
- id = Math.random();
- constructor() {
- if (global2[kExitEmitter]) {
- return global2[kExitEmitter];
- }
- ObjectDefineProperty(global2, kExitEmitter, {
- value: this,
- writable: false,
- enumerable: false,
- configurable: false
- });
- }
- on(ev, fn) {
- this.listeners[ev].push(fn);
- }
- removeListener(ev, fn) {
- const list2 = this.listeners[ev];
- const i2 = list2.indexOf(fn);
- if (i2 === -1) {
- return;
- }
- if (i2 === 0 && list2.length === 1) {
- list2.length = 0;
- } else {
- list2.splice(i2, 1);
- }
- }
- emit(ev, code, signal) {
- if (this.emitted[ev]) {
- return false;
- }
- this.emitted[ev] = true;
- let ret = false;
- for (const fn of this.listeners[ev]) {
- ret = fn(code, signal) === true || ret;
- }
- if (ev === "exit") {
- ret = this.emit("afterExit", code, signal) || ret;
- }
- return ret;
- }
-}
-
-class SignalExitBase {
-}
-var processOk = (process10) => !!process10 && typeof process10 === "object" && typeof process10.removeListener === "function" && typeof process10.emit === "function" && typeof process10.reallyExit === "function" && typeof process10.listeners === "function" && typeof process10.kill === "function" && typeof process10.pid === "number" && typeof process10.on === "function", kExitEmitter, global2, ObjectDefineProperty, signalExitWrap = (handler) => {
- return {
- onExit(cb, opts) {
- return handler.onExit(cb, opts);
- },
- load() {
- return handler.load();
- },
- unload() {
- return handler.unload();
- }
- };
-}, SignalExitFallback, SignalExit, process10, onExit, load, unload;
-var init_mjs = __esm(() => {
- init_signals2();
- kExitEmitter = Symbol.for("signal-exit emitter");
- global2 = globalThis;
- ObjectDefineProperty = Object.defineProperty.bind(Object);
- SignalExitFallback = class SignalExitFallback extends SignalExitBase {
- onExit() {
- return () => {};
- }
- load() {}
- unload() {}
- };
- SignalExit = class SignalExit extends SignalExitBase {
- #hupSig = process10.platform === "win32" ? "SIGINT" : "SIGHUP";
- #emitter = new Emitter;
- #process;
- #originalProcessEmit;
- #originalProcessReallyExit;
- #sigListeners = {};
- #loaded = false;
- constructor(process10) {
- super();
- this.#process = process10;
- this.#sigListeners = {};
- for (const sig of signals) {
- this.#sigListeners[sig] = () => {
- const listeners = this.#process.listeners(sig);
- let { count: count2 } = this.#emitter;
- const p = process10;
- if (typeof p.__signal_exit_emitter__ === "object" && typeof p.__signal_exit_emitter__.count === "number") {
- count2 += p.__signal_exit_emitter__.count;
- }
- if (listeners.length === count2) {
- this.unload();
- const ret = this.#emitter.emit("exit", null, sig);
- const s = sig === "SIGHUP" ? this.#hupSig : sig;
- if (!ret)
- process10.kill(process10.pid, s);
- }
- };
- }
- this.#originalProcessReallyExit = process10.reallyExit;
- this.#originalProcessEmit = process10.emit;
- }
- onExit(cb, opts) {
- if (!processOk(this.#process)) {
- return () => {};
- }
- if (this.#loaded === false) {
- this.load();
- }
- const ev = opts?.alwaysLast ? "afterExit" : "exit";
- this.#emitter.on(ev, cb);
- return () => {
- this.#emitter.removeListener(ev, cb);
- if (this.#emitter.listeners["exit"].length === 0 && this.#emitter.listeners["afterExit"].length === 0) {
- this.unload();
- }
- };
- }
- load() {
- if (this.#loaded) {
- return;
- }
- this.#loaded = true;
- this.#emitter.count += 1;
- for (const sig of signals) {
- try {
- const fn = this.#sigListeners[sig];
- if (fn)
- this.#process.on(sig, fn);
- } catch (_) {}
- }
- this.#process.emit = (ev, ...a2) => {
- return this.#processEmit(ev, ...a2);
- };
- this.#process.reallyExit = (code) => {
- return this.#processReallyExit(code);
- };
- }
- unload() {
- if (!this.#loaded) {
- return;
- }
- this.#loaded = false;
- signals.forEach((sig) => {
- const listener = this.#sigListeners[sig];
- if (!listener) {
- throw new Error("Listener not defined for signal: " + sig);
- }
- try {
- this.#process.removeListener(sig, listener);
- } catch (_) {}
- });
- this.#process.emit = this.#originalProcessEmit;
- this.#process.reallyExit = this.#originalProcessReallyExit;
- this.#emitter.count -= 1;
- }
- #processReallyExit(code) {
- if (!processOk(this.#process)) {
- return 0;
- }
- this.#process.exitCode = code || 0;
- this.#emitter.emit("exit", this.#process.exitCode, null);
- return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
- }
- #processEmit(ev, ...args) {
- const og = this.#originalProcessEmit;
- if (ev === "exit" && processOk(this.#process)) {
- if (typeof args[0] === "number") {
- this.#process.exitCode = args[0];
- }
- const ret = og.call(this.#process, ev, ...args);
- this.#emitter.emit("exit", this.#process.exitCode, null);
- return ret;
- } else {
- return og.call(this.#process, ev, ...args);
- }
- }
- };
- process10 = globalThis.process;
- ({
- onExit,
- load,
- unload
- } = signalExitWrap(processOk(process10) ? new SignalExit(process10) : new SignalExitFallback));
-});
-
-// node_modules/execa/lib/terminate/cleanup.js
-import { addAbortListener as addAbortListener2 } from "events";
-var cleanupOnExit = (subprocess, { cleanup, detached }, { signal }) => {
- if (!cleanup || detached) {
- return;
- }
- const removeExitHandler = onExit(() => {
- subprocess.kill();
- });
- addAbortListener2(signal, () => {
- removeExitHandler();
- });
-};
-var init_cleanup = __esm(() => {
- init_mjs();
-});
-
-// node_modules/execa/lib/pipe/pipe-arguments.js
-var normalizePipeArguments = ({ source, sourcePromise, boundOptions, createNested }, ...pipeArguments) => {
- const startTime = getStartTime();
- const {
- destination,
- destinationStream,
- destinationError,
- from,
- unpipeSignal
- } = getDestinationStream(boundOptions, createNested, pipeArguments);
- const { sourceStream, sourceError } = getSourceStream(source, from);
- const { options: sourceOptions, fileDescriptors } = SUBPROCESS_OPTIONS.get(source);
- return {
- sourcePromise,
- sourceStream,
- sourceOptions,
- sourceError,
- destination,
- destinationStream,
- destinationError,
- unpipeSignal,
- fileDescriptors,
- startTime
- };
-}, getDestinationStream = (boundOptions, createNested, pipeArguments) => {
- try {
- const {
- destination,
- pipeOptions: { from, to, unpipeSignal } = {}
- } = getDestination(boundOptions, createNested, ...pipeArguments);
- const destinationStream = getToStream(destination, to);
- return {
- destination,
- destinationStream,
- from,
- unpipeSignal
- };
- } catch (error) {
- return { destinationError: error };
- }
-}, getDestination = (boundOptions, createNested, firstArgument, ...pipeArguments) => {
- if (Array.isArray(firstArgument)) {
- const destination = createNested(mapDestinationArguments, boundOptions)(firstArgument, ...pipeArguments);
- return { destination, pipeOptions: boundOptions };
- }
- if (typeof firstArgument === "string" || firstArgument instanceof URL || isDenoExecPath(firstArgument)) {
- if (Object.keys(boundOptions).length > 0) {
- throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)("file", ...).');
- }
- const [rawFile, rawArguments, rawOptions] = normalizeParameters(firstArgument, ...pipeArguments);
- const destination = createNested(mapDestinationArguments)(rawFile, rawArguments, rawOptions);
- return { destination, pipeOptions: rawOptions };
- }
- if (SUBPROCESS_OPTIONS.has(firstArgument)) {
- if (Object.keys(boundOptions).length > 0) {
- throw new TypeError("Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).");
- }
- return { destination: firstArgument, pipeOptions: pipeArguments[0] };
- }
- throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);
-}, mapDestinationArguments = ({ options: options2 }) => ({ options: { ...options2, stdin: "pipe", piped: true } }), getSourceStream = (source, from) => {
- try {
- const sourceStream = getFromStream(source, from);
- return { sourceStream };
- } catch (error) {
- return { sourceError: error };
- }
-};
-var init_pipe_arguments = __esm(() => {
- init_parameters();
- init_duration();
- init_fd_options();
- init_file_url();
-});
-
-// node_modules/execa/lib/pipe/throw.js
-var handlePipeArgumentsError = ({
- sourceStream,
- sourceError,
- destinationStream,
- destinationError,
- fileDescriptors,
- sourceOptions,
- startTime
-}) => {
- const error = getPipeArgumentsError({
- sourceStream,
- sourceError,
- destinationStream,
- destinationError
- });
- if (error !== undefined) {
- throw createNonCommandError({
- error,
- fileDescriptors,
- sourceOptions,
- startTime
- });
- }
-}, getPipeArgumentsError = ({ sourceStream, sourceError, destinationStream, destinationError }) => {
- if (sourceError !== undefined && destinationError !== undefined) {
- return destinationError;
- }
- if (destinationError !== undefined) {
- abortSourceStream(sourceStream);
- return destinationError;
- }
- if (sourceError !== undefined) {
- endDestinationStream(destinationStream);
- return sourceError;
- }
-}, createNonCommandError = ({ error, fileDescriptors, sourceOptions, startTime }) => makeEarlyError({
- error,
- command: PIPE_COMMAND_MESSAGE,
- escapedCommand: PIPE_COMMAND_MESSAGE,
- fileDescriptors,
- options: sourceOptions,
- startTime,
- isSync: false
-}), PIPE_COMMAND_MESSAGE = "source.pipe(destination)";
-var init_throw = __esm(() => {
- init_result();
- init_pipeline();
-});
-
-// node_modules/execa/lib/pipe/sequence.js
-var waitForBothSubprocesses = async (subprocessPromises) => {
- const [
- { status: sourceStatus, reason: sourceReason, value: sourceResult = sourceReason },
- { status: destinationStatus, reason: destinationReason, value: destinationResult = destinationReason }
- ] = await subprocessPromises;
- if (!destinationResult.pipedFrom.includes(sourceResult)) {
- destinationResult.pipedFrom.push(sourceResult);
- }
- if (destinationStatus === "rejected") {
- throw destinationResult;
- }
- if (sourceStatus === "rejected") {
- throw sourceResult;
- }
- return destinationResult;
-};
-
-// node_modules/execa/lib/pipe/streaming.js
-import { finished as finished4 } from "stream/promises";
-var pipeSubprocessStream = (sourceStream, destinationStream, maxListenersController) => {
- const mergedStream = MERGED_STREAMS.has(destinationStream) ? pipeMoreSubprocessStream(sourceStream, destinationStream) : pipeFirstSubprocessStream(sourceStream, destinationStream);
- incrementMaxListeners(sourceStream, SOURCE_LISTENERS_PER_PIPE, maxListenersController.signal);
- incrementMaxListeners(destinationStream, DESTINATION_LISTENERS_PER_PIPE, maxListenersController.signal);
- cleanupMergedStreamsMap(destinationStream);
- return mergedStream;
-}, pipeFirstSubprocessStream = (sourceStream, destinationStream) => {
- const mergedStream = mergeStreams([sourceStream]);
- pipeStreams(mergedStream, destinationStream);
- MERGED_STREAMS.set(destinationStream, mergedStream);
- return mergedStream;
-}, pipeMoreSubprocessStream = (sourceStream, destinationStream) => {
- const mergedStream = MERGED_STREAMS.get(destinationStream);
- mergedStream.add(sourceStream);
- return mergedStream;
-}, cleanupMergedStreamsMap = async (destinationStream) => {
- try {
- await finished4(destinationStream, { cleanup: true, readable: false, writable: true });
- } catch {}
- MERGED_STREAMS.delete(destinationStream);
-}, MERGED_STREAMS, SOURCE_LISTENERS_PER_PIPE = 2, DESTINATION_LISTENERS_PER_PIPE = 1;
-var init_streaming2 = __esm(() => {
- init_merge_streams();
- init_max_listeners();
- init_pipeline();
- MERGED_STREAMS = new WeakMap;
-});
-
-// node_modules/execa/lib/pipe/abort.js
-import { aborted } from "util";
-var unpipeOnAbort = (unpipeSignal, unpipeContext) => unpipeSignal === undefined ? [] : [unpipeOnSignalAbort(unpipeSignal, unpipeContext)], unpipeOnSignalAbort = async (unpipeSignal, { sourceStream, mergedStream, fileDescriptors, sourceOptions, startTime }) => {
- await aborted(unpipeSignal, sourceStream);
- await mergedStream.remove(sourceStream);
- const error = new Error("Pipe canceled by `unpipeSignal` option.");
- throw createNonCommandError({
- error,
- fileDescriptors,
- sourceOptions,
- startTime
- });
-};
-var init_abort = __esm(() => {
- init_throw();
-});
-
-// node_modules/execa/lib/pipe/setup.js
-var pipeToSubprocess = (sourceInfo, ...pipeArguments) => {
- if (isPlainObject(pipeArguments[0])) {
- return pipeToSubprocess.bind(undefined, {
- ...sourceInfo,
- boundOptions: { ...sourceInfo.boundOptions, ...pipeArguments[0] }
- });
- }
- const { destination, ...normalizedInfo } = normalizePipeArguments(sourceInfo, ...pipeArguments);
- const promise = handlePipePromise({ ...normalizedInfo, destination });
- promise.pipe = pipeToSubprocess.bind(undefined, {
- ...sourceInfo,
- source: destination,
- sourcePromise: promise,
- boundOptions: {}
- });
- return promise;
-}, handlePipePromise = async ({
- sourcePromise,
- sourceStream,
- sourceOptions,
- sourceError,
- destination,
- destinationStream,
- destinationError,
- unpipeSignal,
- fileDescriptors,
- startTime
-}) => {
- const subprocessPromises = getSubprocessPromises(sourcePromise, destination);
- handlePipeArgumentsError({
- sourceStream,
- sourceError,
- destinationStream,
- destinationError,
- fileDescriptors,
- sourceOptions,
- startTime
- });
- const maxListenersController = new AbortController;
- try {
- const mergedStream = pipeSubprocessStream(sourceStream, destinationStream, maxListenersController);
- return await Promise.race([
- waitForBothSubprocesses(subprocessPromises),
- ...unpipeOnAbort(unpipeSignal, {
- sourceStream,
- mergedStream,
- sourceOptions,
- fileDescriptors,
- startTime
- })
- ]);
- } finally {
- maxListenersController.abort();
- }
-}, getSubprocessPromises = (sourcePromise, destination) => Promise.allSettled([sourcePromise, destination]);
-var init_setup = __esm(() => {
- init_pipe_arguments();
- init_throw();
- init_streaming2();
- init_abort();
-});
-
-// node_modules/execa/lib/io/iterate.js
-import { on as on5 } from "events";
-import { getDefaultHighWaterMark as getDefaultHighWaterMark3 } from "stream";
-var iterateOnSubprocessStream = ({ subprocessStdout, subprocess, binary, shouldEncode, encoding, preserveNewlines }) => {
- const controller = new AbortController;
- stopReadingOnExit(subprocess, controller);
- return iterateOnStream({
- stream: subprocessStdout,
- controller,
- binary,
- shouldEncode: !subprocessStdout.readableObjectMode && shouldEncode,
- encoding,
- shouldSplit: !subprocessStdout.readableObjectMode,
- preserveNewlines
- });
-}, stopReadingOnExit = async (subprocess, controller) => {
- try {
- await subprocess;
- } catch {} finally {
- controller.abort();
- }
-}, iterateForResult = ({ stream, onStreamEnd, lines, encoding, stripFinalNewline: stripFinalNewline2, allMixed }) => {
- const controller = new AbortController;
- stopReadingOnStreamEnd(onStreamEnd, controller, stream);
- const objectMode = stream.readableObjectMode && !allMixed;
- return iterateOnStream({
- stream,
- controller,
- binary: encoding === "buffer",
- shouldEncode: !objectMode,
- encoding,
- shouldSplit: !objectMode && lines,
- preserveNewlines: !stripFinalNewline2
- });
-}, stopReadingOnStreamEnd = async (onStreamEnd, controller, stream) => {
- try {
- await onStreamEnd;
- } catch {
- stream.destroy();
- } finally {
- controller.abort();
- }
-}, iterateOnStream = ({ stream, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines }) => {
- const onStdoutChunk = on5(stream, "data", {
- signal: controller.signal,
- highWaterMark: HIGH_WATER_MARK,
- highWatermark: HIGH_WATER_MARK
- });
- return iterateOnData({
- onStdoutChunk,
- controller,
- binary,
- shouldEncode,
- encoding,
- shouldSplit,
- preserveNewlines
- });
-}, DEFAULT_OBJECT_HIGH_WATER_MARK, HIGH_WATER_MARK, iterateOnData = async function* ({ onStdoutChunk, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines }) {
- const generators = getGenerators({
- binary,
- shouldEncode,
- encoding,
- shouldSplit,
- preserveNewlines
- });
- try {
- for await (const [chunk] of onStdoutChunk) {
- yield* transformChunkSync(chunk, generators, 0);
- }
- } catch (error) {
- if (!controller.signal.aborted) {
- throw error;
- }
- } finally {
- yield* finalChunksSync(generators);
- }
-}, getGenerators = ({ binary, shouldEncode, encoding, shouldSplit, preserveNewlines }) => [
- getEncodingTransformGenerator(binary, encoding, !shouldEncode),
- getSplitLinesGenerator(binary, preserveNewlines, !shouldSplit, {})
-].filter(Boolean);
-var init_iterate = __esm(() => {
- init_encoding_transform();
- init_split();
- DEFAULT_OBJECT_HIGH_WATER_MARK = getDefaultHighWaterMark3(true);
- HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK;
-});
-
-// node_modules/execa/lib/io/contents.js
-import { setImmediate as setImmediate2 } from "timers/promises";
-var getStreamOutput = async ({ stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => {
- const logPromise = logOutputAsync({
- stream,
- onStreamEnd,
- fdNumber,
- encoding,
- allMixed,
- verboseInfo,
- streamInfo
- });
- if (!buffer) {
- await Promise.all([resumeStream(stream), logPromise]);
- return;
- }
- const stripFinalNewlineValue = getStripFinalNewline(stripFinalNewline2, fdNumber);
- const iterable = iterateForResult({
- stream,
- onStreamEnd,
- lines,
- encoding,
- stripFinalNewline: stripFinalNewlineValue,
- allMixed
- });
- const [output] = await Promise.all([
- getStreamContents2({
- stream,
- iterable,
- fdNumber,
- encoding,
- maxBuffer,
- lines
- }),
- logPromise
- ]);
- return output;
-}, logOutputAsync = async ({ stream, onStreamEnd, fdNumber, encoding, allMixed, verboseInfo, streamInfo: { fileDescriptors } }) => {
- if (!shouldLogOutput({
- stdioItems: fileDescriptors[fdNumber]?.stdioItems,
- encoding,
- verboseInfo,
- fdNumber
- })) {
- return;
- }
- const linesIterable = iterateForResult({
- stream,
- onStreamEnd,
- lines: true,
- encoding,
- stripFinalNewline: true,
- allMixed
- });
- await logLines(linesIterable, stream, fdNumber, verboseInfo);
-}, resumeStream = async (stream) => {
- await setImmediate2();
- if (stream.readableFlowing === null) {
- stream.resume();
- }
-}, getStreamContents2 = async ({ stream, stream: { readableObjectMode }, iterable, fdNumber, encoding, maxBuffer, lines }) => {
- try {
- if (readableObjectMode || lines) {
- return await getStreamAsArray(iterable, { maxBuffer });
- }
- if (encoding === "buffer") {
- return new Uint8Array(await getStreamAsArrayBuffer(iterable, { maxBuffer }));
- }
- return await getStreamAsString(iterable, { maxBuffer });
- } catch (error) {
- return handleBufferedData(handleMaxBuffer({
- error,
- stream,
- readableObjectMode,
- lines,
- encoding,
- fdNumber
- }));
- }
-}, getBufferedData = async (streamPromise) => {
- try {
- return await streamPromise;
- } catch (error) {
- return handleBufferedData(error);
- }
-}, handleBufferedData = ({ bufferedData }) => isArrayBuffer(bufferedData) ? new Uint8Array(bufferedData) : bufferedData;
-var init_contents2 = __esm(() => {
- init_source2();
- init_uint_array();
- init_output();
- init_iterate();
- init_max_buffer();
- init_strip_newline();
-});
-
-// node_modules/execa/lib/resolve/wait-stream.js
-import { finished as finished5 } from "stream/promises";
-var waitForStream = async (stream, fdNumber, streamInfo, { isSameDirection, stopOnExit = false } = {}) => {
- const state = handleStdinDestroy(stream, streamInfo);
- const abortController = new AbortController;
- try {
- await Promise.race([
- ...stopOnExit ? [streamInfo.exitPromise] : [],
- finished5(stream, { cleanup: true, signal: abortController.signal })
- ]);
- } catch (error) {
- if (!state.stdinCleanedUp) {
- handleStreamError(error, fdNumber, streamInfo, isSameDirection);
- }
- } finally {
- abortController.abort();
- }
-}, handleStdinDestroy = (stream, { originalStreams: [originalStdin], subprocess }) => {
- const state = { stdinCleanedUp: false };
- if (stream === originalStdin) {
- spyOnStdinDestroy(stream, subprocess, state);
- }
- return state;
-}, spyOnStdinDestroy = (subprocessStdin, subprocess, state) => {
- const { _destroy } = subprocessStdin;
- subprocessStdin._destroy = (...destroyArguments) => {
- setStdinCleanedUp(subprocess, state);
- _destroy.call(subprocessStdin, ...destroyArguments);
- };
-}, setStdinCleanedUp = ({ exitCode, signalCode }, state) => {
- if (exitCode !== null || signalCode !== null) {
- state.stdinCleanedUp = true;
- }
-}, handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {
- if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) {
- throw error;
- }
-}, shouldIgnoreStreamError = (error, fdNumber, streamInfo, isSameDirection = true) => {
- if (streamInfo.propagating) {
- return isStreamEpipe(error) || isStreamAbort(error);
- }
- streamInfo.propagating = true;
- return isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection ? isStreamEpipe(error) : isStreamAbort(error);
-}, isInputFileDescriptor = ({ fileDescriptors }, fdNumber) => fdNumber !== "all" && fileDescriptors[fdNumber].direction === "input", isStreamAbort = (error) => error?.code === "ERR_STREAM_PREMATURE_CLOSE", isStreamEpipe = (error) => error?.code === "EPIPE";
-var init_wait_stream = () => {};
-
-// node_modules/execa/lib/resolve/stdio.js
-var waitForStdioStreams = ({ subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({
- stream,
- fdNumber,
- encoding,
- buffer: buffer[fdNumber],
- maxBuffer: maxBuffer[fdNumber],
- lines: lines[fdNumber],
- allMixed: false,
- stripFinalNewline: stripFinalNewline2,
- verboseInfo,
- streamInfo
-})), waitForSubprocessStream = async ({ stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => {
- if (!stream) {
- return;
- }
- const onStreamEnd = waitForStream(stream, fdNumber, streamInfo);
- if (isInputFileDescriptor(streamInfo, fdNumber)) {
- await onStreamEnd;
- return;
- }
- const [output] = await Promise.all([
- getStreamOutput({
- stream,
- onStreamEnd,
- fdNumber,
- encoding,
- buffer,
- maxBuffer,
- lines,
- allMixed,
- stripFinalNewline: stripFinalNewline2,
- verboseInfo,
- streamInfo
- }),
- onStreamEnd
- ]);
- return output;
-};
-var init_stdio = __esm(() => {
- init_contents2();
- init_wait_stream();
-});
-
-// node_modules/execa/lib/resolve/all-async.js
-var makeAllStream = ({ stdout, stderr }, { all }) => all && (stdout || stderr) ? mergeStreams([stdout, stderr].filter(Boolean)) : undefined, waitForAllStream = ({ subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => waitForSubprocessStream({
- ...getAllStream(subprocess, buffer),
- fdNumber: "all",
- encoding,
- maxBuffer: maxBuffer[1] + maxBuffer[2],
- lines: lines[1] || lines[2],
- allMixed: getAllMixed(subprocess),
- stripFinalNewline: stripFinalNewline2,
- verboseInfo,
- streamInfo
-}), getAllStream = ({ stdout, stderr, all }, [, bufferStdout, bufferStderr]) => {
- const buffer = bufferStdout || bufferStderr;
- if (!buffer) {
- return { stream: all, buffer };
- }
- if (!bufferStdout) {
- return { stream: stderr, buffer };
- }
- if (!bufferStderr) {
- return { stream: stdout, buffer };
- }
- return { stream: all, buffer };
-}, getAllMixed = ({ all, stdout, stderr }) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode;
-var init_all_async = __esm(() => {
- init_merge_streams();
- init_stdio();
-});
-
-// node_modules/execa/lib/verbose/ipc.js
-var shouldLogIpc = (verboseInfo) => isFullVerbose(verboseInfo, "ipc"), logIpcOutput = (message, verboseInfo) => {
- const verboseMessage = serializeVerboseMessage(message);
- verboseLog({
- type: "ipc",
- verboseMessage,
- fdNumber: "ipc",
- verboseInfo
- });
-};
-var init_ipc = __esm(() => {
- init_log();
- init_values();
-});
-
-// node_modules/execa/lib/ipc/buffer-messages.js
-var waitForIpcOutput = async ({
- subprocess,
- buffer: bufferArray,
- maxBuffer: maxBufferArray,
- ipc,
- ipcOutput,
- verboseInfo
-}) => {
- if (!ipc) {
- return ipcOutput;
- }
- const isVerbose2 = shouldLogIpc(verboseInfo);
- const buffer = getFdSpecificValue(bufferArray, "ipc");
- const maxBuffer = getFdSpecificValue(maxBufferArray, "ipc");
- for await (const message of loopOnMessages({
- anyProcess: subprocess,
- channel: subprocess.channel,
- isSubprocess: false,
- ipc,
- shouldAwait: false,
- reference: true
- })) {
- if (buffer) {
- checkIpcMaxBuffer(subprocess, ipcOutput, maxBuffer);
- ipcOutput.push(message);
- }
- if (isVerbose2) {
- logIpcOutput(message, verboseInfo);
- }
- }
- return ipcOutput;
-}, getBufferedIpcOutput = async (ipcOutputPromise, ipcOutput) => {
- await Promise.allSettled([ipcOutputPromise]);
- return ipcOutput;
-};
-var init_buffer_messages = __esm(() => {
- init_max_buffer();
- init_ipc();
- init_specific();
- init_get_each();
-});
-
-// node_modules/execa/lib/resolve/wait-subprocess.js
-import { once as once8 } from "events";
-var waitForSubprocessResult = async ({
- subprocess,
- options: {
- encoding,
- buffer,
- maxBuffer,
- lines,
- timeoutDuration: timeout,
- cancelSignal,
- gracefulCancel,
- forceKillAfterDelay,
- stripFinalNewline: stripFinalNewline2,
- ipc,
- ipcInput
- },
- context,
- verboseInfo,
- fileDescriptors,
- originalStreams,
- onInternalError,
- controller
-}) => {
- const exitPromise = waitForExit(subprocess, context);
- const streamInfo = {
- originalStreams,
- fileDescriptors,
- subprocess,
- exitPromise,
- propagating: false
- };
- const stdioPromises = waitForStdioStreams({
- subprocess,
- encoding,
- buffer,
- maxBuffer,
- lines,
- stripFinalNewline: stripFinalNewline2,
- verboseInfo,
- streamInfo
- });
- const allPromise = waitForAllStream({
- subprocess,
- encoding,
- buffer,
- maxBuffer,
- lines,
- stripFinalNewline: stripFinalNewline2,
- verboseInfo,
- streamInfo
- });
- const ipcOutput = [];
- const ipcOutputPromise = waitForIpcOutput({
- subprocess,
- buffer,
- maxBuffer,
- ipc,
- ipcOutput,
- verboseInfo
- });
- const originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo);
- const customStreamsEndPromises = waitForCustomStreamsEnd(fileDescriptors, streamInfo);
- try {
- return await Promise.race([
- Promise.all([
- {},
- waitForSuccessfulExit(exitPromise),
- Promise.all(stdioPromises),
- allPromise,
- ipcOutputPromise,
- sendIpcInput(subprocess, ipcInput),
- ...originalPromises,
- ...customStreamsEndPromises
- ]),
- onInternalError,
- throwOnSubprocessError(subprocess, controller),
- ...throwOnTimeout(subprocess, timeout, context, controller),
- ...throwOnCancel({
- subprocess,
- cancelSignal,
- gracefulCancel,
- context,
- controller
- }),
- ...throwOnGracefulCancel({
- subprocess,
- cancelSignal,
- gracefulCancel,
- forceKillAfterDelay,
- context,
- controller
- })
- ]);
- } catch (error) {
- context.terminationReason ??= "other";
- return Promise.all([
- { error },
- exitPromise,
- Promise.all(stdioPromises.map((stdioPromise) => getBufferedData(stdioPromise))),
- getBufferedData(allPromise),
- getBufferedIpcOutput(ipcOutputPromise, ipcOutput),
- Promise.allSettled(originalPromises),
- Promise.allSettled(customStreamsEndPromises)
- ]);
- }
-}, waitForOriginalStreams = (originalStreams, subprocess, streamInfo) => originalStreams.map((stream, fdNumber) => stream === subprocess.stdio[fdNumber] ? undefined : waitForStream(stream, fdNumber, streamInfo)), waitForCustomStreamsEnd = (fileDescriptors, streamInfo) => fileDescriptors.flatMap(({ stdioItems }, fdNumber) => stdioItems.filter(({ value, stream = value }) => isStream(stream, { checkOpen: false }) && !isStandardStream(stream)).map(({ type, value, stream = value }) => waitForStream(stream, fdNumber, streamInfo, {
- isSameDirection: TRANSFORM_TYPES.has(type),
- stopOnExit: type === "native"
-}))), throwOnSubprocessError = async (subprocess, { signal }) => {
- const [error] = await once8(subprocess, "error", { signal });
- throw error;
-};
-var init_wait_subprocess = __esm(() => {
- init_timeout();
- init_cancel();
- init_graceful2();
- init_standard_stream();
- init_type();
- init_contents2();
- init_buffer_messages();
- init_ipc_input();
- init_all_async();
- init_stdio();
- init_exit_async();
- init_wait_stream();
-});
-
-// node_modules/execa/lib/convert/concurrent.js
-var initializeConcurrentStreams = () => ({
- readableDestroy: new WeakMap,
- writableFinal: new WeakMap,
- writableDestroy: new WeakMap
-}), addConcurrentStream = (concurrentStreams, stream, waitName) => {
- const weakMap = concurrentStreams[waitName];
- if (!weakMap.has(stream)) {
- weakMap.set(stream, []);
- }
- const promises = weakMap.get(stream);
- const promise = createDeferred();
- promises.push(promise);
- const resolve2 = promise.resolve.bind(promise);
- return { resolve: resolve2, promises };
-}, waitForConcurrentStreams = async ({ resolve: resolve2, promises }, subprocess) => {
- resolve2();
- const [isSubprocessExit] = await Promise.race([
- Promise.allSettled([true, subprocess]),
- Promise.all([false, ...promises])
- ]);
- return !isSubprocessExit;
-};
-var init_concurrent = () => {};
-
-// node_modules/execa/lib/convert/shared.js
-import { finished as finished6 } from "stream/promises";
-var safeWaitForSubprocessStdin = async (subprocessStdin) => {
- if (subprocessStdin === undefined) {
- return;
- }
- try {
- await waitForSubprocessStdin(subprocessStdin);
- } catch {}
-}, safeWaitForSubprocessStdout = async (subprocessStdout) => {
- if (subprocessStdout === undefined) {
- return;
- }
- try {
- await waitForSubprocessStdout(subprocessStdout);
- } catch {}
-}, waitForSubprocessStdin = async (subprocessStdin) => {
- await finished6(subprocessStdin, { cleanup: true, readable: false, writable: true });
-}, waitForSubprocessStdout = async (subprocessStdout) => {
- await finished6(subprocessStdout, { cleanup: true, readable: true, writable: false });
-}, waitForSubprocess = async (subprocess, error) => {
- await subprocess;
- if (error) {
- throw error;
- }
-}, destroyOtherStream = (stream, isOpen, error) => {
- if (error && !isStreamAbort(error)) {
- stream.destroy(error);
- } else if (isOpen) {
- stream.destroy();
- }
-};
-var init_shared2 = __esm(() => {
- init_wait_stream();
-});
-
-// node_modules/execa/lib/convert/readable.js
-import { Readable as Readable3 } from "stream";
-import { callbackify as callbackify2 } from "util";
-var createReadable = ({ subprocess, concurrentStreams, encoding }, { from, binary: binaryOption = true, preserveNewlines = true } = {}) => {
- const binary = binaryOption || BINARY_ENCODINGS.has(encoding);
- const { subprocessStdout, waitReadableDestroy } = getSubprocessStdout(subprocess, from, concurrentStreams);
- const { readableEncoding, readableObjectMode, readableHighWaterMark } = getReadableOptions(subprocessStdout, binary);
- const { read, onStdoutDataDone } = getReadableMethods({
- subprocessStdout,
- subprocess,
- binary,
- encoding,
- preserveNewlines
- });
- const readable2 = new Readable3({
- read,
- destroy: callbackify2(onReadableDestroy.bind(undefined, { subprocessStdout, subprocess, waitReadableDestroy })),
- highWaterMark: readableHighWaterMark,
- objectMode: readableObjectMode,
- encoding: readableEncoding
- });
- onStdoutFinished({
- subprocessStdout,
- onStdoutDataDone,
- readable: readable2,
- subprocess
- });
- return readable2;
-}, getSubprocessStdout = (subprocess, from, concurrentStreams) => {
- const subprocessStdout = getFromStream(subprocess, from);
- const waitReadableDestroy = addConcurrentStream(concurrentStreams, subprocessStdout, "readableDestroy");
- return { subprocessStdout, waitReadableDestroy };
-}, getReadableOptions = ({ readableEncoding, readableObjectMode, readableHighWaterMark }, binary) => binary ? { readableEncoding, readableObjectMode, readableHighWaterMark } : { readableEncoding, readableObjectMode: true, readableHighWaterMark: DEFAULT_OBJECT_HIGH_WATER_MARK }, getReadableMethods = ({ subprocessStdout, subprocess, binary, encoding, preserveNewlines }) => {
- const onStdoutDataDone = createDeferred();
- const onStdoutData = iterateOnSubprocessStream({
- subprocessStdout,
- subprocess,
- binary,
- shouldEncode: !binary,
- encoding,
- preserveNewlines
- });
- return {
- read() {
- onRead(this, onStdoutData, onStdoutDataDone);
- },
- onStdoutDataDone
- };
-}, onRead = async (readable2, onStdoutData, onStdoutDataDone) => {
- try {
- const { value, done } = await onStdoutData.next();
- if (done) {
- onStdoutDataDone.resolve();
- } else {
- readable2.push(value);
- }
- } catch {}
-}, onStdoutFinished = async ({ subprocessStdout, onStdoutDataDone, readable: readable2, subprocess, subprocessStdin }) => {
- try {
- await waitForSubprocessStdout(subprocessStdout);
- await subprocess;
- await safeWaitForSubprocessStdin(subprocessStdin);
- await onStdoutDataDone;
- if (readable2.readable) {
- readable2.push(null);
- }
- } catch (error) {
- await safeWaitForSubprocessStdin(subprocessStdin);
- destroyOtherReadable(readable2, error);
- }
-}, onReadableDestroy = async ({ subprocessStdout, subprocess, waitReadableDestroy }, error) => {
- if (await waitForConcurrentStreams(waitReadableDestroy, subprocess)) {
- destroyOtherReadable(subprocessStdout, error);
- await waitForSubprocess(subprocess, error);
- }
-}, destroyOtherReadable = (stream, error) => {
- destroyOtherStream(stream, stream.readable, error);
-};
-var init_readable = __esm(() => {
- init_encoding_option();
- init_fd_options();
- init_iterate();
- init_concurrent();
- init_shared2();
-});
-
-// node_modules/execa/lib/convert/writable.js
-import { Writable as Writable3 } from "stream";
-import { callbackify as callbackify3 } from "util";
-var createWritable = ({ subprocess, concurrentStreams }, { to } = {}) => {
- const { subprocessStdin, waitWritableFinal, waitWritableDestroy } = getSubprocessStdin(subprocess, to, concurrentStreams);
- const writable2 = new Writable3({
- ...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal),
- destroy: callbackify3(onWritableDestroy.bind(undefined, {
- subprocessStdin,
- subprocess,
- waitWritableFinal,
- waitWritableDestroy
- })),
- highWaterMark: subprocessStdin.writableHighWaterMark,
- objectMode: subprocessStdin.writableObjectMode
- });
- onStdinFinished(subprocessStdin, writable2);
- return writable2;
-}, getSubprocessStdin = (subprocess, to, concurrentStreams) => {
- const subprocessStdin = getToStream(subprocess, to);
- const waitWritableFinal = addConcurrentStream(concurrentStreams, subprocessStdin, "writableFinal");
- const waitWritableDestroy = addConcurrentStream(concurrentStreams, subprocessStdin, "writableDestroy");
- return { subprocessStdin, waitWritableFinal, waitWritableDestroy };
-}, getWritableMethods = (subprocessStdin, subprocess, waitWritableFinal) => ({
- write: onWrite.bind(undefined, subprocessStdin),
- final: callbackify3(onWritableFinal.bind(undefined, subprocessStdin, subprocess, waitWritableFinal))
-}), onWrite = (subprocessStdin, chunk, encoding, done) => {
- if (subprocessStdin.write(chunk, encoding)) {
- done();
- } else {
- subprocessStdin.once("drain", done);
- }
-}, onWritableFinal = async (subprocessStdin, subprocess, waitWritableFinal) => {
- if (await waitForConcurrentStreams(waitWritableFinal, subprocess)) {
- if (subprocessStdin.writable) {
- subprocessStdin.end();
- }
- await subprocess;
- }
-}, onStdinFinished = async (subprocessStdin, writable2, subprocessStdout) => {
- try {
- await waitForSubprocessStdin(subprocessStdin);
- if (writable2.writable) {
- writable2.end();
- }
- } catch (error) {
- await safeWaitForSubprocessStdout(subprocessStdout);
- destroyOtherWritable(writable2, error);
- }
-}, onWritableDestroy = async ({ subprocessStdin, subprocess, waitWritableFinal, waitWritableDestroy }, error) => {
- await waitForConcurrentStreams(waitWritableFinal, subprocess);
- if (await waitForConcurrentStreams(waitWritableDestroy, subprocess)) {
- destroyOtherWritable(subprocessStdin, error);
- await waitForSubprocess(subprocess, error);
- }
-}, destroyOtherWritable = (stream, error) => {
- destroyOtherStream(stream, stream.writable, error);
-};
-var init_writable = __esm(() => {
- init_fd_options();
- init_concurrent();
- init_shared2();
-});
-
-// node_modules/execa/lib/convert/duplex.js
-import { Duplex as Duplex3 } from "stream";
-import { callbackify as callbackify4 } from "util";
-var createDuplex = ({ subprocess, concurrentStreams, encoding }, { from, to, binary: binaryOption = true, preserveNewlines = true } = {}) => {
- const binary = binaryOption || BINARY_ENCODINGS.has(encoding);
- const { subprocessStdout, waitReadableDestroy } = getSubprocessStdout(subprocess, from, concurrentStreams);
- const { subprocessStdin, waitWritableFinal, waitWritableDestroy } = getSubprocessStdin(subprocess, to, concurrentStreams);
- const { readableEncoding, readableObjectMode, readableHighWaterMark } = getReadableOptions(subprocessStdout, binary);
- const { read, onStdoutDataDone } = getReadableMethods({
- subprocessStdout,
- subprocess,
- binary,
- encoding,
- preserveNewlines
- });
- const duplex2 = new Duplex3({
- read,
- ...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal),
- destroy: callbackify4(onDuplexDestroy.bind(undefined, {
- subprocessStdout,
- subprocessStdin,
- subprocess,
- waitReadableDestroy,
- waitWritableFinal,
- waitWritableDestroy
- })),
- readableHighWaterMark,
- writableHighWaterMark: subprocessStdin.writableHighWaterMark,
- readableObjectMode,
- writableObjectMode: subprocessStdin.writableObjectMode,
- encoding: readableEncoding
- });
- onStdoutFinished({
- subprocessStdout,
- onStdoutDataDone,
- readable: duplex2,
- subprocess,
- subprocessStdin
- });
- onStdinFinished(subprocessStdin, duplex2, subprocessStdout);
- return duplex2;
-}, onDuplexDestroy = async ({ subprocessStdout, subprocessStdin, subprocess, waitReadableDestroy, waitWritableFinal, waitWritableDestroy }, error) => {
- await Promise.all([
- onReadableDestroy({ subprocessStdout, subprocess, waitReadableDestroy }, error),
- onWritableDestroy({
- subprocessStdin,
- subprocess,
- waitWritableFinal,
- waitWritableDestroy
- }, error)
- ]);
-};
-var init_duplex = __esm(() => {
- init_encoding_option();
- init_readable();
- init_writable();
-});
-
-// node_modules/execa/lib/convert/iterable.js
-var createIterable = (subprocess, encoding, {
- from,
- binary: binaryOption = false,
- preserveNewlines = false
-} = {}) => {
- const binary = binaryOption || BINARY_ENCODINGS.has(encoding);
- const subprocessStdout = getFromStream(subprocess, from);
- const onStdoutData = iterateOnSubprocessStream({
- subprocessStdout,
- subprocess,
- binary,
- shouldEncode: true,
- encoding,
- preserveNewlines
- });
- return iterateOnStdoutData(onStdoutData, subprocessStdout, subprocess);
-}, iterateOnStdoutData = async function* (onStdoutData, subprocessStdout, subprocess) {
- try {
- yield* onStdoutData;
- } finally {
- if (subprocessStdout.readable) {
- subprocessStdout.destroy();
- }
- await subprocess;
- }
-};
-var init_iterable = __esm(() => {
- init_encoding_option();
- init_fd_options();
- init_iterate();
-});
-
-// node_modules/execa/lib/convert/add.js
-var addConvertedStreams = (subprocess, { encoding }) => {
- const concurrentStreams = initializeConcurrentStreams();
- subprocess.readable = createReadable.bind(undefined, { subprocess, concurrentStreams, encoding });
- subprocess.writable = createWritable.bind(undefined, { subprocess, concurrentStreams });
- subprocess.duplex = createDuplex.bind(undefined, { subprocess, concurrentStreams, encoding });
- subprocess.iterable = createIterable.bind(undefined, subprocess, encoding);
- subprocess[Symbol.asyncIterator] = createIterable.bind(undefined, subprocess, encoding, {});
-};
-var init_add = __esm(() => {
- init_concurrent();
- init_readable();
- init_writable();
- init_duplex();
- init_iterable();
-});
-
-// node_modules/execa/lib/methods/promise.js
-var mergePromise = (subprocess, promise) => {
- for (const [property2, descriptor] of descriptors) {
- const value = descriptor.value.bind(promise);
- Reflect.defineProperty(subprocess, property2, { ...descriptor, value });
- }
-}, nativePromisePrototype, descriptors;
-var init_promise = __esm(() => {
- nativePromisePrototype = (async () => {})().constructor.prototype;
- descriptors = ["then", "catch", "finally"].map((property2) => [
- property2,
- Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property2)
- ]);
-});
-
-// node_modules/execa/lib/methods/main-async.js
-import { setMaxListeners } from "events";
-import { spawn } from "child_process";
-var execaCoreAsync = (rawFile, rawArguments, rawOptions, createNested) => {
- const { file, commandArguments, command, escapedCommand, startTime, verboseInfo, options: options2, fileDescriptors } = handleAsyncArguments(rawFile, rawArguments, rawOptions);
- const { subprocess, promise } = spawnSubprocessAsync({
- file,
- commandArguments,
- options: options2,
- startTime,
- verboseInfo,
- command,
- escapedCommand,
- fileDescriptors
- });
- subprocess.pipe = pipeToSubprocess.bind(undefined, {
- source: subprocess,
- sourcePromise: promise,
- boundOptions: {},
- createNested
- });
- mergePromise(subprocess, promise);
- SUBPROCESS_OPTIONS.set(subprocess, { options: options2, fileDescriptors });
- return subprocess;
-}, handleAsyncArguments = (rawFile, rawArguments, rawOptions) => {
- const { command, escapedCommand, startTime, verboseInfo } = handleCommand(rawFile, rawArguments, rawOptions);
- const { file, commandArguments, options: normalizedOptions } = normalizeOptions(rawFile, rawArguments, rawOptions);
- const options2 = handleAsyncOptions(normalizedOptions);
- const fileDescriptors = handleStdioAsync(options2, verboseInfo);
- return {
- file,
- commandArguments,
- command,
- escapedCommand,
- startTime,
- verboseInfo,
- options: options2,
- fileDescriptors
- };
-}, handleAsyncOptions = ({ timeout, signal, ...options2 }) => {
- if (signal !== undefined) {
- throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');
- }
- return { ...options2, timeoutDuration: timeout };
-}, spawnSubprocessAsync = ({ file, commandArguments, options: options2, startTime, verboseInfo, command, escapedCommand, fileDescriptors }) => {
- let subprocess;
- try {
- subprocess = spawn(...concatenateShell(file, commandArguments, options2));
- } catch (error) {
- return handleEarlyError({
- error,
- command,
- escapedCommand,
- fileDescriptors,
- options: options2,
- startTime,
- verboseInfo
- });
- }
- const controller = new AbortController;
- setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);
- const originalStreams = [...subprocess.stdio];
- pipeOutputAsync(subprocess, fileDescriptors, controller);
- cleanupOnExit(subprocess, options2, controller);
- const context = {};
- const onInternalError = createDeferred();
- subprocess.kill = subprocessKill.bind(undefined, {
- kill: subprocess.kill.bind(subprocess),
- options: options2,
- onInternalError,
- context,
- controller
- });
- subprocess.all = makeAllStream(subprocess, options2);
- addConvertedStreams(subprocess, options2);
- addIpcMethods(subprocess, options2);
- const promise = handlePromise({
- subprocess,
- options: options2,
- startTime,
- verboseInfo,
- fileDescriptors,
- originalStreams,
- command,
- escapedCommand,
- context,
- onInternalError,
- controller
- });
- return { subprocess, promise };
-}, handlePromise = async ({ subprocess, options: options2, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, context, onInternalError, controller }) => {
- const [
- errorInfo,
- [exitCode, signal],
- stdioResults,
- allResult,
- ipcOutput
- ] = await waitForSubprocessResult({
- subprocess,
- options: options2,
- context,
- verboseInfo,
- fileDescriptors,
- originalStreams,
- onInternalError,
- controller
- });
- controller.abort();
- onInternalError.resolve();
- const stdio = stdioResults.map((stdioResult, fdNumber) => stripNewline(stdioResult, options2, fdNumber));
- const all = stripNewline(allResult, options2, "all");
- const result = getAsyncResult({
- errorInfo,
- exitCode,
- signal,
- stdio,
- all,
- ipcOutput,
- context,
- options: options2,
- command,
- escapedCommand,
- startTime
- });
- return handleResult(result, verboseInfo, options2);
-}, getAsyncResult = ({ errorInfo, exitCode, signal, stdio, all, ipcOutput, context, options: options2, command, escapedCommand, startTime }) => ("error" in errorInfo) ? makeError({
- error: errorInfo.error,
- command,
- escapedCommand,
- timedOut: context.terminationReason === "timeout",
- isCanceled: context.terminationReason === "cancel" || context.terminationReason === "gracefulCancel",
- isGracefullyCanceled: context.terminationReason === "gracefulCancel",
- isMaxBuffer: errorInfo.error instanceof MaxBufferError,
- isForcefullyTerminated: context.isForcefullyTerminated,
- exitCode,
- signal,
- stdio,
- all,
- ipcOutput,
- options: options2,
- startTime,
- isSync: false
-}) : makeSuccessResult({
- command,
- escapedCommand,
- stdio,
- all,
- ipcOutput,
- options: options2,
- startTime
-});
-var init_main_async = __esm(() => {
- init_source2();
- init_command();
- init_options();
- init_fd_options();
- init_methods();
- init_result();
- init_reject();
- init_early_error();
- init_handle_async();
- init_strip_newline();
- init_output_async();
- init_kill();
- init_cleanup();
- init_setup();
- init_all_async();
- init_wait_subprocess();
- init_add();
- init_promise();
-});
-
-// node_modules/execa/lib/methods/bind.js
-var mergeOptions = (boundOptions, options2) => {
- const newOptions = Object.fromEntries(Object.entries(options2).map(([optionName, optionValue]) => [
- optionName,
- mergeOption(optionName, boundOptions[optionName], optionValue)
- ]));
- return { ...boundOptions, ...newOptions };
-}, mergeOption = (optionName, boundOptionValue, optionValue) => {
- if (DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue)) {
- return { ...boundOptionValue, ...optionValue };
- }
- return optionValue;
-}, DEEP_OPTIONS;
-var init_bind = __esm(() => {
- init_specific();
- DEEP_OPTIONS = new Set(["env", ...FD_SPECIFIC_OPTIONS]);
-});
-
-// node_modules/execa/lib/methods/create.js
-var createExeca = (mapArguments, boundOptions, deepOptions, setBoundExeca) => {
- const createNested = (mapArguments2, boundOptions2, setBoundExeca2) => createExeca(mapArguments2, boundOptions2, deepOptions, setBoundExeca2);
- const boundExeca = (...execaArguments) => callBoundExeca({
- mapArguments,
- deepOptions,
- boundOptions,
- setBoundExeca,
- createNested
- }, ...execaArguments);
- if (setBoundExeca !== undefined) {
- setBoundExeca(boundExeca, createNested, boundOptions);
- }
- return boundExeca;
-}, callBoundExeca = ({ mapArguments, deepOptions = {}, boundOptions = {}, setBoundExeca, createNested }, firstArgument, ...nextArguments) => {
- if (isPlainObject(firstArgument)) {
- return createNested(mapArguments, mergeOptions(boundOptions, firstArgument), setBoundExeca);
- }
- const { file, commandArguments, options: options2, isSync } = parseArguments({
- mapArguments,
- firstArgument,
- nextArguments,
- deepOptions,
- boundOptions
- });
- return isSync ? execaCoreSync(file, commandArguments, options2) : execaCoreAsync(file, commandArguments, options2, createNested);
-}, parseArguments = ({ mapArguments, firstArgument, nextArguments, deepOptions, boundOptions }) => {
- const callArguments = isTemplateString(firstArgument) ? parseTemplates(firstArgument, nextArguments) : [firstArgument, ...nextArguments];
- const [initialFile, initialArguments, initialOptions] = normalizeParameters(...callArguments);
- const mergedOptions = mergeOptions(mergeOptions(deepOptions, boundOptions), initialOptions);
- const {
- file = initialFile,
- commandArguments = initialArguments,
- options: options2 = mergedOptions,
- isSync = false
- } = mapArguments({ file: initialFile, commandArguments: initialArguments, options: mergedOptions });
- return {
- file,
- commandArguments,
- options: options2,
- isSync
- };
-};
-var init_create = __esm(() => {
- init_parameters();
- init_template();
- init_main_sync();
- init_main_async();
- init_bind();
-});
-
-// node_modules/execa/lib/methods/command.js
-var mapCommandAsync = ({ file, commandArguments }) => parseCommand(file, commandArguments), mapCommandSync = ({ file, commandArguments }) => ({ ...parseCommand(file, commandArguments), isSync: true }), parseCommand = (command, unusedArguments) => {
- if (unusedArguments.length > 0) {
- throw new TypeError(`The command and its arguments must be passed as a single string: ${command} ${unusedArguments}.`);
- }
- const [file, ...commandArguments] = parseCommandString(command);
- return { file, commandArguments };
-}, parseCommandString = (command) => {
- if (typeof command !== "string") {
- throw new TypeError(`The command must be a string: ${String(command)}.`);
- }
- const trimmedCommand = command.trim();
- if (trimmedCommand === "") {
- return [];
- }
- const tokens = [];
- for (const token of trimmedCommand.split(SPACES_REGEXP)) {
- const previousToken = tokens.at(-1);
- if (previousToken && previousToken.endsWith("\\")) {
- tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;
- } else {
- tokens.push(token);
- }
- }
- return tokens;
-}, SPACES_REGEXP;
-var init_command2 = __esm(() => {
- SPACES_REGEXP = / +/g;
-});
-
-// node_modules/execa/lib/methods/script.js
-var setScriptSync = (boundExeca, createNested, boundOptions) => {
- boundExeca.sync = createNested(mapScriptSync, boundOptions);
- boundExeca.s = boundExeca.sync;
-}, mapScriptAsync = ({ options: options2 }) => getScriptOptions(options2), mapScriptSync = ({ options: options2 }) => ({ ...getScriptOptions(options2), isSync: true }), getScriptOptions = (options2) => ({ options: { ...getScriptStdinOption(options2), ...options2 } }), getScriptStdinOption = ({ input, inputFile, stdio }) => input === undefined && inputFile === undefined && stdio === undefined ? { stdin: "inherit" } : {}, deepScriptOptions;
-var init_script = __esm(() => {
- deepScriptOptions = { preferLocal: true };
-});
-
-// node_modules/execa/index.js
-var execa, execaSync, execaCommand, execaCommandSync, execaNode, $, sendMessage2, getOneMessage2, getEachMessage2, getCancelSignal2;
-var init_execa = __esm(() => {
- init_create();
- init_command2();
- init_node2();
- init_script();
- init_methods();
- execa = createExeca(() => ({}));
- execaSync = createExeca(() => ({ isSync: true }));
- execaCommand = createExeca(mapCommandAsync);
- execaCommandSync = createExeca(mapCommandSync);
- execaNode = createExeca(mapNode);
- $ = createExeca(mapScriptAsync, {}, deepScriptOptions, setScriptSync);
- ({
- sendMessage: sendMessage2,
- getOneMessage: getOneMessage2,
- getEachMessage: getEachMessage2,
- getCancelSignal: getCancelSignal2
- } = getIpcExport());
-});
-
-// src/utils/execSyncWrapper.ts
-import {
- execSync as nodeExecSync
-} from "child_process";
-function execSync_DEPRECATED(command, options2) {
- let __stack = [];
- try {
- const _ = __using(__stack, slowLogging`execSync: ${command.slice(0, 100)}`, 0);
- return nodeExecSync(command, options2);
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
-}
-var init_execSyncWrapper = __esm(() => {
- init_slowOperations();
-});
-
-// src/utils/which.ts
-async function whichNodeAsync(command) {
- if (process.platform === "win32") {
- const result2 = await execa(`where.exe ${command}`, {
- shell: true,
- stderr: "ignore",
- reject: false
- });
- if (result2.exitCode !== 0 || !result2.stdout) {
- return null;
- }
- return result2.stdout.trim().split(/\r?\n/)[0] || null;
- }
- const result = await execa(`which ${command}`, {
- shell: true,
- stderr: "ignore",
- reject: false
- });
- if (result.exitCode !== 0 || !result.stdout) {
- return null;
- }
- return result.stdout.trim();
-}
-function whichNodeSync(command) {
- if (process.platform === "win32") {
- try {
- const result = execSync_DEPRECATED(`where.exe ${command}`, {
- encoding: "utf-8",
- stdio: ["ignore", "pipe", "ignore"]
- });
- const output = result.toString().trim();
- return output.split(/\r?\n/)[0] || null;
- } catch {
- return null;
- }
- }
- try {
- const result = execSync_DEPRECATED(`which ${command}`, {
- encoding: "utf-8",
- stdio: ["ignore", "pipe", "ignore"]
- });
- return result.toString().trim() || null;
- } catch {
- return null;
- }
-}
-var bunWhich, which, whichSync;
-var init_which = __esm(() => {
- init_execa();
- init_execSyncWrapper();
- bunWhich = typeof Bun !== "undefined" && typeof Bun.which === "function" ? Bun.which : null;
- which = bunWhich ? async (command) => bunWhich(command) : whichNodeAsync;
- whichSync = bunWhich ?? whichNodeSync;
-});
-
-// src/utils/findExecutable.ts
-function findExecutable(exe, args) {
- const resolved = whichSync(exe);
- return { cmd: resolved ?? exe, args };
-}
-var init_findExecutable = __esm(() => {
- init_which();
-});
-
-// node_modules/axios/lib/helpers/bind.js
-function bind(fn, thisArg) {
- return function wrap() {
- return fn.apply(thisArg, arguments);
- };
-}
-
-// node_modules/axios/lib/utils.js
-function isBuffer2(val) {
- return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction2(val.constructor.isBuffer) && val.constructor.isBuffer(val);
-}
-function isArrayBufferView(val) {
- let result;
- if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
- result = ArrayBuffer.isView(val);
- } else {
- result = val && val.buffer && isArrayBuffer2(val.buffer);
- }
- return result;
-}
-function getGlobal() {
- if (typeof globalThis !== "undefined")
- return globalThis;
- if (typeof self !== "undefined")
- return self;
- if (typeof window !== "undefined")
- return window;
- if (typeof global !== "undefined")
- return global;
- return {};
-}
-function forEach(obj, fn, { allOwnKeys = false } = {}) {
- if (obj === null || typeof obj === "undefined") {
- return;
- }
- let i2;
- let l;
- if (typeof obj !== "object") {
- obj = [obj];
- }
- if (isArray2(obj)) {
- for (i2 = 0, l = obj.length;i2 < l; i2++) {
- fn.call(null, obj[i2], i2, obj);
- }
- } else {
- if (isBuffer2(obj)) {
- return;
- }
- const keys2 = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
- const len = keys2.length;
- let key;
- for (i2 = 0;i2 < len; i2++) {
- key = keys2[i2];
- fn.call(null, obj[key], key, obj);
- }
- }
-}
-function findKey(obj, key) {
- if (isBuffer2(obj)) {
- return null;
- }
- key = key.toLowerCase();
- const keys2 = Object.keys(obj);
- let i2 = keys2.length;
- let _key;
- while (i2-- > 0) {
- _key = keys2[i2];
- if (key === _key.toLowerCase()) {
- return _key;
- }
- }
- return null;
-}
-function merge() {
- const { caseless, skipUndefined } = isContextDefined(this) && this || {};
- const result = {};
- const assignValue2 = (val, key) => {
- if (key === "__proto__" || key === "constructor" || key === "prototype") {
- return;
- }
- const targetKey = caseless && findKey(result, key) || key;
- if (isPlainObject2(result[targetKey]) && isPlainObject2(val)) {
- result[targetKey] = merge(result[targetKey], val);
- } else if (isPlainObject2(val)) {
- result[targetKey] = merge({}, val);
- } else if (isArray2(val)) {
- result[targetKey] = val.slice();
- } else if (!skipUndefined || !isUndefined(val)) {
- result[targetKey] = val;
- }
- };
- for (let i2 = 0, l = arguments.length;i2 < l; i2++) {
- arguments[i2] && forEach(arguments[i2], assignValue2);
- }
- return result;
-}
-function isSpecCompliantForm(thing) {
- return !!(thing && isFunction2(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
-}
-var toString4, getPrototypeOf, iterator, toStringTag, kindOf, kindOfTest = (type) => {
- type = type.toLowerCase();
- return (thing) => kindOf(thing) === type;
-}, typeOfTest = (type) => (thing) => typeof thing === type, isArray2, isUndefined, isArrayBuffer2, isString, isFunction2, isNumber, isObject3 = (thing) => thing !== null && typeof thing === "object", isBoolean = (thing) => thing === true || thing === false, isPlainObject2 = (val) => {
- if (kindOf(val) !== "object") {
- return false;
- }
- const prototype = getPrototypeOf(val);
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(toStringTag in val) && !(iterator in val);
-}, isEmptyObject = (val) => {
- if (!isObject3(val) || isBuffer2(val)) {
- return false;
- }
- try {
- return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
- } catch (e) {
- return false;
- }
-}, isDate, isFile, isReactNativeBlob = (value) => {
- return !!(value && typeof value.uri !== "undefined");
-}, isReactNative = (formData) => formData && typeof formData.getParts !== "undefined", isBlob, isFileList, isStream2 = (val) => isObject3(val) && isFunction2(val.pipe), G, FormDataCtor, isFormData = (thing) => {
- let kind2;
- return thing && (FormDataCtor && thing instanceof FormDataCtor || isFunction2(thing.append) && ((kind2 = kindOf(thing)) === "formdata" || kind2 === "object" && isFunction2(thing.toString) && thing.toString() === "[object FormData]"));
-}, isURLSearchParams, isReadableStream3, isRequest, isResponse, isHeaders, trim = (str) => {
- return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
-}, _global, isContextDefined = (context) => !isUndefined(context) && context !== _global, extend = (a2, b, thisArg, { allOwnKeys } = {}) => {
- forEach(b, (val, key) => {
- if (thisArg && isFunction2(val)) {
- Object.defineProperty(a2, key, {
- value: bind(val, thisArg),
- writable: true,
- enumerable: true,
- configurable: true
- });
- } else {
- Object.defineProperty(a2, key, {
- value: val,
- writable: true,
- enumerable: true,
- configurable: true
- });
- }
- }, { allOwnKeys });
- return a2;
-}, stripBOM = (content) => {
- if (content.charCodeAt(0) === 65279) {
- content = content.slice(1);
- }
- return content;
-}, inherits = (constructor, superConstructor, props, descriptors2) => {
- constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
- Object.defineProperty(constructor.prototype, "constructor", {
- value: constructor,
- writable: true,
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(constructor, "super", {
- value: superConstructor.prototype
- });
- props && Object.assign(constructor.prototype, props);
-}, toFlatObject = (sourceObj, destObj, filter, propFilter) => {
- let props;
- let i2;
- let prop;
- const merged = {};
- destObj = destObj || {};
- if (sourceObj == null)
- return destObj;
- do {
- props = Object.getOwnPropertyNames(sourceObj);
- i2 = props.length;
- while (i2-- > 0) {
- prop = props[i2];
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
- destObj[prop] = sourceObj[prop];
- merged[prop] = true;
- }
- }
- sourceObj = filter !== false && getPrototypeOf(sourceObj);
- } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
- return destObj;
-}, endsWith = (str, searchString, position2) => {
- str = String(str);
- if (position2 === undefined || position2 > str.length) {
- position2 = str.length;
- }
- position2 -= searchString.length;
- const lastIndex = str.indexOf(searchString, position2);
- return lastIndex !== -1 && lastIndex === position2;
-}, toArray = (thing) => {
- if (!thing)
- return null;
- if (isArray2(thing))
- return thing;
- let i2 = thing.length;
- if (!isNumber(i2))
- return null;
- const arr = new Array(i2);
- while (i2-- > 0) {
- arr[i2] = thing[i2];
- }
- return arr;
-}, isTypedArray2, forEachEntry = (obj, fn) => {
- const generator = obj && obj[iterator];
- const _iterator = generator.call(obj);
- let result;
- while ((result = _iterator.next()) && !result.done) {
- const pair = result.value;
- fn.call(obj, pair[0], pair[1]);
- }
-}, matchAll = (regExp, str) => {
- let matches;
- const arr = [];
- while ((matches = regExp.exec(str)) !== null) {
- arr.push(matches);
- }
- return arr;
-}, isHTMLForm, toCamelCase = (str) => {
- return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
- return p1.toUpperCase() + p2;
- });
-}, hasOwnProperty13, isRegExp, reduceDescriptors = (obj, reducer) => {
- const descriptors2 = Object.getOwnPropertyDescriptors(obj);
- const reducedDescriptors = {};
- forEach(descriptors2, (descriptor, name) => {
- let ret;
- if ((ret = reducer(descriptor, name, obj)) !== false) {
- reducedDescriptors[name] = ret || descriptor;
- }
- });
- Object.defineProperties(obj, reducedDescriptors);
-}, freezeMethods = (obj) => {
- reduceDescriptors(obj, (descriptor, name) => {
- if (isFunction2(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
- return false;
- }
- const value = obj[name];
- if (!isFunction2(value))
- return;
- descriptor.enumerable = false;
- if ("writable" in descriptor) {
- descriptor.writable = false;
- return;
- }
- if (!descriptor.set) {
- descriptor.set = () => {
- throw Error("Can not rewrite read-only method '" + name + "'");
- };
- }
- });
-}, toObjectSet = (arrayOrString, delimiter) => {
- const obj = {};
- const define2 = (arr) => {
- arr.forEach((value) => {
- obj[value] = true;
- });
- };
- isArray2(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter));
- return obj;
-}, noop5 = () => {}, toFiniteNumber = (value, defaultValue) => {
- return value != null && Number.isFinite(value = +value) ? value : defaultValue;
-}, toJSONObject = (obj) => {
- const stack = new Array(10);
- const visit = (source, i2) => {
- if (isObject3(source)) {
- if (stack.indexOf(source) >= 0) {
- return;
- }
- if (isBuffer2(source)) {
- return source;
- }
- if (!("toJSON" in source)) {
- stack[i2] = source;
- const target = isArray2(source) ? [] : {};
- forEach(source, (value, key) => {
- const reducedValue = visit(value, i2 + 1);
- !isUndefined(reducedValue) && (target[key] = reducedValue);
- });
- stack[i2] = undefined;
- return target;
- }
- }
- return source;
- };
- return visit(obj, 0);
-}, isAsyncFn, isThenable = (thing) => thing && (isObject3(thing) || isFunction2(thing)) && isFunction2(thing.then) && isFunction2(thing.catch), _setImmediate, asap, isIterable = (thing) => thing != null && isFunction2(thing[iterator]), utils_default;
-var init_utils = __esm(() => {
- ({ toString: toString4 } = Object.prototype);
- ({ getPrototypeOf } = Object);
- ({ iterator, toStringTag } = Symbol);
- kindOf = ((cache2) => (thing) => {
- const str = toString4.call(thing);
- return cache2[str] || (cache2[str] = str.slice(8, -1).toLowerCase());
- })(Object.create(null));
- ({ isArray: isArray2 } = Array);
- isUndefined = typeOfTest("undefined");
- isArrayBuffer2 = kindOfTest("ArrayBuffer");
- isString = typeOfTest("string");
- isFunction2 = typeOfTest("function");
- isNumber = typeOfTest("number");
- isDate = kindOfTest("Date");
- isFile = kindOfTest("File");
- isBlob = kindOfTest("Blob");
- isFileList = kindOfTest("FileList");
- G = getGlobal();
- FormDataCtor = typeof G.FormData !== "undefined" ? G.FormData : undefined;
- isURLSearchParams = kindOfTest("URLSearchParams");
- [isReadableStream3, isRequest, isResponse, isHeaders] = [
- "ReadableStream",
- "Request",
- "Response",
- "Headers"
- ].map(kindOfTest);
- _global = (() => {
- if (typeof globalThis !== "undefined")
- return globalThis;
- return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
- })();
- isTypedArray2 = ((TypedArray) => {
- return (thing) => {
- return TypedArray && thing instanceof TypedArray;
- };
- })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
- isHTMLForm = kindOfTest("HTMLFormElement");
- hasOwnProperty13 = (({ hasOwnProperty: hasOwnProperty14 }) => (obj, prop) => hasOwnProperty14.call(obj, prop))(Object.prototype);
- isRegExp = kindOfTest("RegExp");
- isAsyncFn = kindOfTest("AsyncFunction");
- _setImmediate = ((setImmediateSupported, postMessageSupported) => {
- if (setImmediateSupported) {
- return setImmediate;
- }
- return postMessageSupported ? ((token, callbacks) => {
- _global.addEventListener("message", ({ source, data }) => {
- if (source === _global && data === token) {
- callbacks.length && callbacks.shift()();
- }
- }, false);
- return (cb) => {
- callbacks.push(cb);
- _global.postMessage(token, "*");
- };
- })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
- })(typeof setImmediate === "function", isFunction2(_global.postMessage));
- asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
- utils_default = {
- isArray: isArray2,
- isArrayBuffer: isArrayBuffer2,
- isBuffer: isBuffer2,
- isFormData,
- isArrayBufferView,
- isString,
- isNumber,
- isBoolean,
- isObject: isObject3,
- isPlainObject: isPlainObject2,
- isEmptyObject,
- isReadableStream: isReadableStream3,
- isRequest,
- isResponse,
- isHeaders,
- isUndefined,
- isDate,
- isFile,
- isReactNativeBlob,
- isReactNative,
- isBlob,
- isRegExp,
- isFunction: isFunction2,
- isStream: isStream2,
- isURLSearchParams,
- isTypedArray: isTypedArray2,
- isFileList,
- forEach,
- merge,
- extend,
- trim,
- stripBOM,
- inherits,
- toFlatObject,
- kindOf,
- kindOfTest,
- endsWith,
- toArray,
- forEachEntry,
- matchAll,
- isHTMLForm,
- hasOwnProperty: hasOwnProperty13,
- hasOwnProp: hasOwnProperty13,
- reduceDescriptors,
- freezeMethods,
- toObjectSet,
- toCamelCase,
- noop: noop5,
- toFiniteNumber,
- findKey,
- global: _global,
- isContextDefined,
- isSpecCompliantForm,
- toJSONObject,
- isAsyncFn,
- isThenable,
- setImmediate: _setImmediate,
- asap,
- isIterable
- };
-});
-
-// node_modules/axios/lib/core/AxiosError.js
-var AxiosError, AxiosError_default;
-var init_AxiosError = __esm(() => {
- init_utils();
- AxiosError = class AxiosError extends Error {
- static from(error, code, config, request, response, customProps) {
- const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
- axiosError.cause = error;
- axiosError.name = error.name;
- if (error.status != null && axiosError.status == null) {
- axiosError.status = error.status;
- }
- customProps && Object.assign(axiosError, customProps);
- return axiosError;
- }
- constructor(message, code, config, request, response) {
- super(message);
- Object.defineProperty(this, "message", {
- value: message,
- enumerable: true,
- writable: true,
- configurable: true
- });
- this.name = "AxiosError";
- this.isAxiosError = true;
- code && (this.code = code);
- config && (this.config = config);
- request && (this.request = request);
- if (response) {
- this.response = response;
- this.status = response.status;
- }
- }
- toJSON() {
- return {
- message: this.message,
- name: this.name,
- description: this.description,
- number: this.number,
- fileName: this.fileName,
- lineNumber: this.lineNumber,
- columnNumber: this.columnNumber,
- stack: this.stack,
- config: utils_default.toJSONObject(this.config),
- code: this.code,
- status: this.status
- };
- }
- };
- AxiosError.ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
- AxiosError.ERR_BAD_OPTION = "ERR_BAD_OPTION";
- AxiosError.ECONNABORTED = "ECONNABORTED";
- AxiosError.ETIMEDOUT = "ETIMEDOUT";
- AxiosError.ERR_NETWORK = "ERR_NETWORK";
- AxiosError.ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
- AxiosError.ERR_DEPRECATED = "ERR_DEPRECATED";
- AxiosError.ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
- AxiosError.ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
- AxiosError.ERR_CANCELED = "ERR_CANCELED";
- AxiosError.ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
- AxiosError.ERR_INVALID_URL = "ERR_INVALID_URL";
- AxiosError_default = AxiosError;
-});
-
-// node_modules/delayed-stream/lib/delayed_stream.js
-var require_delayed_stream = __commonJS((exports, module) => {
- var Stream2 = __require("stream").Stream;
- var util = __require("util");
- module.exports = DelayedStream;
- function DelayedStream() {
- this.source = null;
- this.dataSize = 0;
- this.maxDataSize = 1024 * 1024;
- this.pauseStream = true;
- this._maxDataSizeExceeded = false;
- this._released = false;
- this._bufferedEvents = [];
- }
- util.inherits(DelayedStream, Stream2);
- DelayedStream.create = function(source, options2) {
- var delayedStream = new this;
- options2 = options2 || {};
- for (var option in options2) {
- delayedStream[option] = options2[option];
- }
- delayedStream.source = source;
- var realEmit = source.emit;
- source.emit = function() {
- delayedStream._handleEmit(arguments);
- return realEmit.apply(source, arguments);
- };
- source.on("error", function() {});
- if (delayedStream.pauseStream) {
- source.pause();
- }
- return delayedStream;
- };
- Object.defineProperty(DelayedStream.prototype, "readable", {
- configurable: true,
- enumerable: true,
- get: function() {
- return this.source.readable;
- }
- });
- DelayedStream.prototype.setEncoding = function() {
- return this.source.setEncoding.apply(this.source, arguments);
- };
- DelayedStream.prototype.resume = function() {
- if (!this._released) {
- this.release();
- }
- this.source.resume();
- };
- DelayedStream.prototype.pause = function() {
- this.source.pause();
- };
- DelayedStream.prototype.release = function() {
- this._released = true;
- this._bufferedEvents.forEach(function(args) {
- this.emit.apply(this, args);
- }.bind(this));
- this._bufferedEvents = [];
- };
- DelayedStream.prototype.pipe = function() {
- var r = Stream2.prototype.pipe.apply(this, arguments);
- this.resume();
- return r;
- };
- DelayedStream.prototype._handleEmit = function(args) {
- if (this._released) {
- this.emit.apply(this, args);
- return;
- }
- if (args[0] === "data") {
- this.dataSize += args[1].length;
- this._checkIfMaxDataSizeExceeded();
- }
- this._bufferedEvents.push(args);
- };
- DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
- if (this._maxDataSizeExceeded) {
- return;
- }
- if (this.dataSize <= this.maxDataSize) {
- return;
- }
- this._maxDataSizeExceeded = true;
- var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded.";
- this.emit("error", new Error(message));
- };
-});
-
-// node_modules/combined-stream/lib/combined_stream.js
-var require_combined_stream = __commonJS((exports, module) => {
- var util = __require("util");
- var Stream2 = __require("stream").Stream;
- var DelayedStream = require_delayed_stream();
- module.exports = CombinedStream;
- function CombinedStream() {
- this.writable = false;
- this.readable = true;
- this.dataSize = 0;
- this.maxDataSize = 2 * 1024 * 1024;
- this.pauseStreams = true;
- this._released = false;
- this._streams = [];
- this._currentStream = null;
- this._insideLoop = false;
- this._pendingNext = false;
- }
- util.inherits(CombinedStream, Stream2);
- CombinedStream.create = function(options2) {
- var combinedStream = new this;
- options2 = options2 || {};
- for (var option in options2) {
- combinedStream[option] = options2[option];
- }
- return combinedStream;
- };
- CombinedStream.isStreamLike = function(stream) {
- return typeof stream !== "function" && typeof stream !== "string" && typeof stream !== "boolean" && typeof stream !== "number" && !Buffer.isBuffer(stream);
- };
- CombinedStream.prototype.append = function(stream) {
- var isStreamLike = CombinedStream.isStreamLike(stream);
- if (isStreamLike) {
- if (!(stream instanceof DelayedStream)) {
- var newStream = DelayedStream.create(stream, {
- maxDataSize: Infinity,
- pauseStream: this.pauseStreams
- });
- stream.on("data", this._checkDataSize.bind(this));
- stream = newStream;
- }
- this._handleErrors(stream);
- if (this.pauseStreams) {
- stream.pause();
- }
- }
- this._streams.push(stream);
- return this;
- };
- CombinedStream.prototype.pipe = function(dest, options2) {
- Stream2.prototype.pipe.call(this, dest, options2);
- this.resume();
- return dest;
- };
- CombinedStream.prototype._getNext = function() {
- this._currentStream = null;
- if (this._insideLoop) {
- this._pendingNext = true;
- return;
- }
- this._insideLoop = true;
- try {
- do {
- this._pendingNext = false;
- this._realGetNext();
- } while (this._pendingNext);
- } finally {
- this._insideLoop = false;
- }
- };
- CombinedStream.prototype._realGetNext = function() {
- var stream = this._streams.shift();
- if (typeof stream == "undefined") {
- this.end();
- return;
- }
- if (typeof stream !== "function") {
- this._pipeNext(stream);
- return;
- }
- var getStream = stream;
- getStream(function(stream2) {
- var isStreamLike = CombinedStream.isStreamLike(stream2);
- if (isStreamLike) {
- stream2.on("data", this._checkDataSize.bind(this));
- this._handleErrors(stream2);
- }
- this._pipeNext(stream2);
- }.bind(this));
- };
- CombinedStream.prototype._pipeNext = function(stream) {
- this._currentStream = stream;
- var isStreamLike = CombinedStream.isStreamLike(stream);
- if (isStreamLike) {
- stream.on("end", this._getNext.bind(this));
- stream.pipe(this, { end: false });
- return;
- }
- var value = stream;
- this.write(value);
- this._getNext();
- };
- CombinedStream.prototype._handleErrors = function(stream) {
- var self2 = this;
- stream.on("error", function(err) {
- self2._emitError(err);
- });
- };
- CombinedStream.prototype.write = function(data) {
- this.emit("data", data);
- };
- CombinedStream.prototype.pause = function() {
- if (!this.pauseStreams) {
- return;
- }
- if (this.pauseStreams && this._currentStream && typeof this._currentStream.pause == "function")
- this._currentStream.pause();
- this.emit("pause");
- };
- CombinedStream.prototype.resume = function() {
- if (!this._released) {
- this._released = true;
- this.writable = true;
- this._getNext();
- }
- if (this.pauseStreams && this._currentStream && typeof this._currentStream.resume == "function")
- this._currentStream.resume();
- this.emit("resume");
- };
- CombinedStream.prototype.end = function() {
- this._reset();
- this.emit("end");
- };
- CombinedStream.prototype.destroy = function() {
- this._reset();
- this.emit("close");
- };
- CombinedStream.prototype._reset = function() {
- this.writable = false;
- this._streams = [];
- this._currentStream = null;
- };
- CombinedStream.prototype._checkDataSize = function() {
- this._updateDataSize();
- if (this.dataSize <= this.maxDataSize) {
- return;
- }
- var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded.";
- this._emitError(new Error(message));
- };
- CombinedStream.prototype._updateDataSize = function() {
- this.dataSize = 0;
- var self2 = this;
- this._streams.forEach(function(stream) {
- if (!stream.dataSize) {
- return;
- }
- self2.dataSize += stream.dataSize;
- });
- if (this._currentStream && this._currentStream.dataSize) {
- this.dataSize += this._currentStream.dataSize;
- }
- };
- CombinedStream.prototype._emitError = function(err) {
- this._reset();
- this.emit("error", err);
- };
-});
-
-// node_modules/form-data/node_modules/mime-types/node_modules/mime-db/db.json
-var require_db = __commonJS((exports, module) => {
- module.exports = {
- "application/1d-interleaved-parityfec": {
- source: "iana"
- },
- "application/3gpdash-qoe-report+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/3gpp-ims+xml": {
- source: "iana",
- compressible: true
- },
- "application/3gpphal+json": {
- source: "iana",
- compressible: true
- },
- "application/3gpphalforms+json": {
- source: "iana",
- compressible: true
- },
- "application/a2l": {
- source: "iana"
- },
- "application/ace+cbor": {
- source: "iana"
- },
- "application/activemessage": {
- source: "iana"
- },
- "application/activity+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-costmap+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-costmapfilter+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-directory+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-endpointcost+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-endpointcostparams+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-endpointprop+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-endpointpropparams+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-error+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-networkmap+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-networkmapfilter+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-updatestreamcontrol+json": {
- source: "iana",
- compressible: true
- },
- "application/alto-updatestreamparams+json": {
- source: "iana",
- compressible: true
- },
- "application/aml": {
- source: "iana"
- },
- "application/andrew-inset": {
- source: "iana",
- extensions: ["ez"]
- },
- "application/applefile": {
- source: "iana"
- },
- "application/applixware": {
- source: "apache",
- extensions: ["aw"]
- },
- "application/at+jwt": {
- source: "iana"
- },
- "application/atf": {
- source: "iana"
- },
- "application/atfx": {
- source: "iana"
- },
- "application/atom+xml": {
- source: "iana",
- compressible: true,
- extensions: ["atom"]
- },
- "application/atomcat+xml": {
- source: "iana",
- compressible: true,
- extensions: ["atomcat"]
- },
- "application/atomdeleted+xml": {
- source: "iana",
- compressible: true,
- extensions: ["atomdeleted"]
- },
- "application/atomicmail": {
- source: "iana"
- },
- "application/atomsvc+xml": {
- source: "iana",
- compressible: true,
- extensions: ["atomsvc"]
- },
- "application/atsc-dwd+xml": {
- source: "iana",
- compressible: true,
- extensions: ["dwd"]
- },
- "application/atsc-dynamic-event-message": {
- source: "iana"
- },
- "application/atsc-held+xml": {
- source: "iana",
- compressible: true,
- extensions: ["held"]
- },
- "application/atsc-rdt+json": {
- source: "iana",
- compressible: true
- },
- "application/atsc-rsat+xml": {
- source: "iana",
- compressible: true,
- extensions: ["rsat"]
- },
- "application/atxml": {
- source: "iana"
- },
- "application/auth-policy+xml": {
- source: "iana",
- compressible: true
- },
- "application/bacnet-xdd+zip": {
- source: "iana",
- compressible: false
- },
- "application/batch-smtp": {
- source: "iana"
- },
- "application/bdoc": {
- compressible: false,
- extensions: ["bdoc"]
- },
- "application/beep+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/calendar+json": {
- source: "iana",
- compressible: true
- },
- "application/calendar+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xcs"]
- },
- "application/call-completion": {
- source: "iana"
- },
- "application/cals-1840": {
- source: "iana"
- },
- "application/captive+json": {
- source: "iana",
- compressible: true
- },
- "application/cbor": {
- source: "iana"
- },
- "application/cbor-seq": {
- source: "iana"
- },
- "application/cccex": {
- source: "iana"
- },
- "application/ccmp+xml": {
- source: "iana",
- compressible: true
- },
- "application/ccxml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["ccxml"]
- },
- "application/cdfx+xml": {
- source: "iana",
- compressible: true,
- extensions: ["cdfx"]
- },
- "application/cdmi-capability": {
- source: "iana",
- extensions: ["cdmia"]
- },
- "application/cdmi-container": {
- source: "iana",
- extensions: ["cdmic"]
- },
- "application/cdmi-domain": {
- source: "iana",
- extensions: ["cdmid"]
- },
- "application/cdmi-object": {
- source: "iana",
- extensions: ["cdmio"]
- },
- "application/cdmi-queue": {
- source: "iana",
- extensions: ["cdmiq"]
- },
- "application/cdni": {
- source: "iana"
- },
- "application/cea": {
- source: "iana"
- },
- "application/cea-2018+xml": {
- source: "iana",
- compressible: true
- },
- "application/cellml+xml": {
- source: "iana",
- compressible: true
- },
- "application/cfw": {
- source: "iana"
- },
- "application/city+json": {
- source: "iana",
- compressible: true
- },
- "application/clr": {
- source: "iana"
- },
- "application/clue+xml": {
- source: "iana",
- compressible: true
- },
- "application/clue_info+xml": {
- source: "iana",
- compressible: true
- },
- "application/cms": {
- source: "iana"
- },
- "application/cnrp+xml": {
- source: "iana",
- compressible: true
- },
- "application/coap-group+json": {
- source: "iana",
- compressible: true
- },
- "application/coap-payload": {
- source: "iana"
- },
- "application/commonground": {
- source: "iana"
- },
- "application/conference-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/cose": {
- source: "iana"
- },
- "application/cose-key": {
- source: "iana"
- },
- "application/cose-key-set": {
- source: "iana"
- },
- "application/cpl+xml": {
- source: "iana",
- compressible: true,
- extensions: ["cpl"]
- },
- "application/csrattrs": {
- source: "iana"
- },
- "application/csta+xml": {
- source: "iana",
- compressible: true
- },
- "application/cstadata+xml": {
- source: "iana",
- compressible: true
- },
- "application/csvm+json": {
- source: "iana",
- compressible: true
- },
- "application/cu-seeme": {
- source: "apache",
- extensions: ["cu"]
- },
- "application/cwt": {
- source: "iana"
- },
- "application/cybercash": {
- source: "iana"
- },
- "application/dart": {
- compressible: true
- },
- "application/dash+xml": {
- source: "iana",
- compressible: true,
- extensions: ["mpd"]
- },
- "application/dash-patch+xml": {
- source: "iana",
- compressible: true,
- extensions: ["mpp"]
- },
- "application/dashdelta": {
- source: "iana"
- },
- "application/davmount+xml": {
- source: "iana",
- compressible: true,
- extensions: ["davmount"]
- },
- "application/dca-rft": {
- source: "iana"
- },
- "application/dcd": {
- source: "iana"
- },
- "application/dec-dx": {
- source: "iana"
- },
- "application/dialog-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/dicom": {
- source: "iana"
- },
- "application/dicom+json": {
- source: "iana",
- compressible: true
- },
- "application/dicom+xml": {
- source: "iana",
- compressible: true
- },
- "application/dii": {
- source: "iana"
- },
- "application/dit": {
- source: "iana"
- },
- "application/dns": {
- source: "iana"
- },
- "application/dns+json": {
- source: "iana",
- compressible: true
- },
- "application/dns-message": {
- source: "iana"
- },
- "application/docbook+xml": {
- source: "apache",
- compressible: true,
- extensions: ["dbk"]
- },
- "application/dots+cbor": {
- source: "iana"
- },
- "application/dskpp+xml": {
- source: "iana",
- compressible: true
- },
- "application/dssc+der": {
- source: "iana",
- extensions: ["dssc"]
- },
- "application/dssc+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xdssc"]
- },
- "application/dvcs": {
- source: "iana"
- },
- "application/ecmascript": {
- source: "iana",
- compressible: true,
- extensions: ["es", "ecma"]
- },
- "application/edi-consent": {
- source: "iana"
- },
- "application/edi-x12": {
- source: "iana",
- compressible: false
- },
- "application/edifact": {
- source: "iana",
- compressible: false
- },
- "application/efi": {
- source: "iana"
- },
- "application/elm+json": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/elm+xml": {
- source: "iana",
- compressible: true
- },
- "application/emergencycalldata.cap+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/emergencycalldata.comment+xml": {
- source: "iana",
- compressible: true
- },
- "application/emergencycalldata.control+xml": {
- source: "iana",
- compressible: true
- },
- "application/emergencycalldata.deviceinfo+xml": {
- source: "iana",
- compressible: true
- },
- "application/emergencycalldata.ecall.msd": {
- source: "iana"
- },
- "application/emergencycalldata.providerinfo+xml": {
- source: "iana",
- compressible: true
- },
- "application/emergencycalldata.serviceinfo+xml": {
- source: "iana",
- compressible: true
- },
- "application/emergencycalldata.subscriberinfo+xml": {
- source: "iana",
- compressible: true
- },
- "application/emergencycalldata.veds+xml": {
- source: "iana",
- compressible: true
- },
- "application/emma+xml": {
- source: "iana",
- compressible: true,
- extensions: ["emma"]
- },
- "application/emotionml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["emotionml"]
- },
- "application/encaprtp": {
- source: "iana"
- },
- "application/epp+xml": {
- source: "iana",
- compressible: true
- },
- "application/epub+zip": {
- source: "iana",
- compressible: false,
- extensions: ["epub"]
- },
- "application/eshop": {
- source: "iana"
- },
- "application/exi": {
- source: "iana",
- extensions: ["exi"]
- },
- "application/expect-ct-report+json": {
- source: "iana",
- compressible: true
- },
- "application/express": {
- source: "iana",
- extensions: ["exp"]
- },
- "application/fastinfoset": {
- source: "iana"
- },
- "application/fastsoap": {
- source: "iana"
- },
- "application/fdt+xml": {
- source: "iana",
- compressible: true,
- extensions: ["fdt"]
- },
- "application/fhir+json": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/fhir+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/fido.trusted-apps+json": {
- compressible: true
- },
- "application/fits": {
- source: "iana"
- },
- "application/flexfec": {
- source: "iana"
- },
- "application/font-sfnt": {
- source: "iana"
- },
- "application/font-tdpfr": {
- source: "iana",
- extensions: ["pfr"]
- },
- "application/font-woff": {
- source: "iana",
- compressible: false
- },
- "application/framework-attributes+xml": {
- source: "iana",
- compressible: true
- },
- "application/geo+json": {
- source: "iana",
- compressible: true,
- extensions: ["geojson"]
- },
- "application/geo+json-seq": {
- source: "iana"
- },
- "application/geopackage+sqlite3": {
- source: "iana"
- },
- "application/geoxacml+xml": {
- source: "iana",
- compressible: true
- },
- "application/gltf-buffer": {
- source: "iana"
- },
- "application/gml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["gml"]
- },
- "application/gpx+xml": {
- source: "apache",
- compressible: true,
- extensions: ["gpx"]
- },
- "application/gxf": {
- source: "apache",
- extensions: ["gxf"]
- },
- "application/gzip": {
- source: "iana",
- compressible: false,
- extensions: ["gz"]
- },
- "application/h224": {
- source: "iana"
- },
- "application/held+xml": {
- source: "iana",
- compressible: true
- },
- "application/hjson": {
- extensions: ["hjson"]
- },
- "application/http": {
- source: "iana"
- },
- "application/hyperstudio": {
- source: "iana",
- extensions: ["stk"]
- },
- "application/ibe-key-request+xml": {
- source: "iana",
- compressible: true
- },
- "application/ibe-pkg-reply+xml": {
- source: "iana",
- compressible: true
- },
- "application/ibe-pp-data": {
- source: "iana"
- },
- "application/iges": {
- source: "iana"
- },
- "application/im-iscomposing+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/index": {
- source: "iana"
- },
- "application/index.cmd": {
- source: "iana"
- },
- "application/index.obj": {
- source: "iana"
- },
- "application/index.response": {
- source: "iana"
- },
- "application/index.vnd": {
- source: "iana"
- },
- "application/inkml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["ink", "inkml"]
- },
- "application/iotp": {
- source: "iana"
- },
- "application/ipfix": {
- source: "iana",
- extensions: ["ipfix"]
- },
- "application/ipp": {
- source: "iana"
- },
- "application/isup": {
- source: "iana"
- },
- "application/its+xml": {
- source: "iana",
- compressible: true,
- extensions: ["its"]
- },
- "application/java-archive": {
- source: "apache",
- compressible: false,
- extensions: ["jar", "war", "ear"]
- },
- "application/java-serialized-object": {
- source: "apache",
- compressible: false,
- extensions: ["ser"]
- },
- "application/java-vm": {
- source: "apache",
- compressible: false,
- extensions: ["class"]
- },
- "application/javascript": {
- source: "iana",
- charset: "UTF-8",
- compressible: true,
- extensions: ["js", "mjs"]
- },
- "application/jf2feed+json": {
- source: "iana",
- compressible: true
- },
- "application/jose": {
- source: "iana"
- },
- "application/jose+json": {
- source: "iana",
- compressible: true
- },
- "application/jrd+json": {
- source: "iana",
- compressible: true
- },
- "application/jscalendar+json": {
- source: "iana",
- compressible: true
- },
- "application/json": {
- source: "iana",
- charset: "UTF-8",
- compressible: true,
- extensions: ["json", "map"]
- },
- "application/json-patch+json": {
- source: "iana",
- compressible: true
- },
- "application/json-seq": {
- source: "iana"
- },
- "application/json5": {
- extensions: ["json5"]
- },
- "application/jsonml+json": {
- source: "apache",
- compressible: true,
- extensions: ["jsonml"]
- },
- "application/jwk+json": {
- source: "iana",
- compressible: true
- },
- "application/jwk-set+json": {
- source: "iana",
- compressible: true
- },
- "application/jwt": {
- source: "iana"
- },
- "application/kpml-request+xml": {
- source: "iana",
- compressible: true
- },
- "application/kpml-response+xml": {
- source: "iana",
- compressible: true
- },
- "application/ld+json": {
- source: "iana",
- compressible: true,
- extensions: ["jsonld"]
- },
- "application/lgr+xml": {
- source: "iana",
- compressible: true,
- extensions: ["lgr"]
- },
- "application/link-format": {
- source: "iana"
- },
- "application/load-control+xml": {
- source: "iana",
- compressible: true
- },
- "application/lost+xml": {
- source: "iana",
- compressible: true,
- extensions: ["lostxml"]
- },
- "application/lostsync+xml": {
- source: "iana",
- compressible: true
- },
- "application/lpf+zip": {
- source: "iana",
- compressible: false
- },
- "application/lxf": {
- source: "iana"
- },
- "application/mac-binhex40": {
- source: "iana",
- extensions: ["hqx"]
- },
- "application/mac-compactpro": {
- source: "apache",
- extensions: ["cpt"]
- },
- "application/macwriteii": {
- source: "iana"
- },
- "application/mads+xml": {
- source: "iana",
- compressible: true,
- extensions: ["mads"]
- },
- "application/manifest+json": {
- source: "iana",
- charset: "UTF-8",
- compressible: true,
- extensions: ["webmanifest"]
- },
- "application/marc": {
- source: "iana",
- extensions: ["mrc"]
- },
- "application/marcxml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["mrcx"]
- },
- "application/mathematica": {
- source: "iana",
- extensions: ["ma", "nb", "mb"]
- },
- "application/mathml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["mathml"]
- },
- "application/mathml-content+xml": {
- source: "iana",
- compressible: true
- },
- "application/mathml-presentation+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbms-associated-procedure-description+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbms-deregister+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbms-envelope+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbms-msk+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbms-msk-response+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbms-protection-description+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbms-reception-report+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbms-register+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbms-register-response+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbms-schedule+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbms-user-service-description+xml": {
- source: "iana",
- compressible: true
- },
- "application/mbox": {
- source: "iana",
- extensions: ["mbox"]
- },
- "application/media-policy-dataset+xml": {
- source: "iana",
- compressible: true,
- extensions: ["mpf"]
- },
- "application/media_control+xml": {
- source: "iana",
- compressible: true
- },
- "application/mediaservercontrol+xml": {
- source: "iana",
- compressible: true,
- extensions: ["mscml"]
- },
- "application/merge-patch+json": {
- source: "iana",
- compressible: true
- },
- "application/metalink+xml": {
- source: "apache",
- compressible: true,
- extensions: ["metalink"]
- },
- "application/metalink4+xml": {
- source: "iana",
- compressible: true,
- extensions: ["meta4"]
- },
- "application/mets+xml": {
- source: "iana",
- compressible: true,
- extensions: ["mets"]
- },
- "application/mf4": {
- source: "iana"
- },
- "application/mikey": {
- source: "iana"
- },
- "application/mipc": {
- source: "iana"
- },
- "application/missing-blocks+cbor-seq": {
- source: "iana"
- },
- "application/mmt-aei+xml": {
- source: "iana",
- compressible: true,
- extensions: ["maei"]
- },
- "application/mmt-usd+xml": {
- source: "iana",
- compressible: true,
- extensions: ["musd"]
- },
- "application/mods+xml": {
- source: "iana",
- compressible: true,
- extensions: ["mods"]
- },
- "application/moss-keys": {
- source: "iana"
- },
- "application/moss-signature": {
- source: "iana"
- },
- "application/mosskey-data": {
- source: "iana"
- },
- "application/mosskey-request": {
- source: "iana"
- },
- "application/mp21": {
- source: "iana",
- extensions: ["m21", "mp21"]
- },
- "application/mp4": {
- source: "iana",
- extensions: ["mp4s", "m4p"]
- },
- "application/mpeg4-generic": {
- source: "iana"
- },
- "application/mpeg4-iod": {
- source: "iana"
- },
- "application/mpeg4-iod-xmt": {
- source: "iana"
- },
- "application/mrb-consumer+xml": {
- source: "iana",
- compressible: true
- },
- "application/mrb-publish+xml": {
- source: "iana",
- compressible: true
- },
- "application/msc-ivr+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/msc-mixer+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/msword": {
- source: "iana",
- compressible: false,
- extensions: ["doc", "dot"]
- },
- "application/mud+json": {
- source: "iana",
- compressible: true
- },
- "application/multipart-core": {
- source: "iana"
- },
- "application/mxf": {
- source: "iana",
- extensions: ["mxf"]
- },
- "application/n-quads": {
- source: "iana",
- extensions: ["nq"]
- },
- "application/n-triples": {
- source: "iana",
- extensions: ["nt"]
- },
- "application/nasdata": {
- source: "iana"
- },
- "application/news-checkgroups": {
- source: "iana",
- charset: "US-ASCII"
- },
- "application/news-groupinfo": {
- source: "iana",
- charset: "US-ASCII"
- },
- "application/news-transmission": {
- source: "iana"
- },
- "application/nlsml+xml": {
- source: "iana",
- compressible: true
- },
- "application/node": {
- source: "iana",
- extensions: ["cjs"]
- },
- "application/nss": {
- source: "iana"
- },
- "application/oauth-authz-req+jwt": {
- source: "iana"
- },
- "application/oblivious-dns-message": {
- source: "iana"
- },
- "application/ocsp-request": {
- source: "iana"
- },
- "application/ocsp-response": {
- source: "iana"
- },
- "application/octet-stream": {
- source: "iana",
- compressible: false,
- extensions: ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"]
- },
- "application/oda": {
- source: "iana",
- extensions: ["oda"]
- },
- "application/odm+xml": {
- source: "iana",
- compressible: true
- },
- "application/odx": {
- source: "iana"
- },
- "application/oebps-package+xml": {
- source: "iana",
- compressible: true,
- extensions: ["opf"]
- },
- "application/ogg": {
- source: "iana",
- compressible: false,
- extensions: ["ogx"]
- },
- "application/omdoc+xml": {
- source: "apache",
- compressible: true,
- extensions: ["omdoc"]
- },
- "application/onenote": {
- source: "apache",
- extensions: ["onetoc", "onetoc2", "onetmp", "onepkg"]
- },
- "application/opc-nodeset+xml": {
- source: "iana",
- compressible: true
- },
- "application/oscore": {
- source: "iana"
- },
- "application/oxps": {
- source: "iana",
- extensions: ["oxps"]
- },
- "application/p21": {
- source: "iana"
- },
- "application/p21+zip": {
- source: "iana",
- compressible: false
- },
- "application/p2p-overlay+xml": {
- source: "iana",
- compressible: true,
- extensions: ["relo"]
- },
- "application/parityfec": {
- source: "iana"
- },
- "application/passport": {
- source: "iana"
- },
- "application/patch-ops-error+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xer"]
- },
- "application/pdf": {
- source: "iana",
- compressible: false,
- extensions: ["pdf"]
- },
- "application/pdx": {
- source: "iana"
- },
- "application/pem-certificate-chain": {
- source: "iana"
- },
- "application/pgp-encrypted": {
- source: "iana",
- compressible: false,
- extensions: ["pgp"]
- },
- "application/pgp-keys": {
- source: "iana",
- extensions: ["asc"]
- },
- "application/pgp-signature": {
- source: "iana",
- extensions: ["asc", "sig"]
- },
- "application/pics-rules": {
- source: "apache",
- extensions: ["prf"]
- },
- "application/pidf+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/pidf-diff+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/pkcs10": {
- source: "iana",
- extensions: ["p10"]
- },
- "application/pkcs12": {
- source: "iana"
- },
- "application/pkcs7-mime": {
- source: "iana",
- extensions: ["p7m", "p7c"]
- },
- "application/pkcs7-signature": {
- source: "iana",
- extensions: ["p7s"]
- },
- "application/pkcs8": {
- source: "iana",
- extensions: ["p8"]
- },
- "application/pkcs8-encrypted": {
- source: "iana"
- },
- "application/pkix-attr-cert": {
- source: "iana",
- extensions: ["ac"]
- },
- "application/pkix-cert": {
- source: "iana",
- extensions: ["cer"]
- },
- "application/pkix-crl": {
- source: "iana",
- extensions: ["crl"]
- },
- "application/pkix-pkipath": {
- source: "iana",
- extensions: ["pkipath"]
- },
- "application/pkixcmp": {
- source: "iana",
- extensions: ["pki"]
- },
- "application/pls+xml": {
- source: "iana",
- compressible: true,
- extensions: ["pls"]
- },
- "application/poc-settings+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/postscript": {
- source: "iana",
- compressible: true,
- extensions: ["ai", "eps", "ps"]
- },
- "application/ppsp-tracker+json": {
- source: "iana",
- compressible: true
- },
- "application/problem+json": {
- source: "iana",
- compressible: true
- },
- "application/problem+xml": {
- source: "iana",
- compressible: true
- },
- "application/provenance+xml": {
- source: "iana",
- compressible: true,
- extensions: ["provx"]
- },
- "application/prs.alvestrand.titrax-sheet": {
- source: "iana"
- },
- "application/prs.cww": {
- source: "iana",
- extensions: ["cww"]
- },
- "application/prs.cyn": {
- source: "iana",
- charset: "7-BIT"
- },
- "application/prs.hpub+zip": {
- source: "iana",
- compressible: false
- },
- "application/prs.nprend": {
- source: "iana"
- },
- "application/prs.plucker": {
- source: "iana"
- },
- "application/prs.rdf-xml-crypt": {
- source: "iana"
- },
- "application/prs.xsf+xml": {
- source: "iana",
- compressible: true
- },
- "application/pskc+xml": {
- source: "iana",
- compressible: true,
- extensions: ["pskcxml"]
- },
- "application/pvd+json": {
- source: "iana",
- compressible: true
- },
- "application/qsig": {
- source: "iana"
- },
- "application/raml+yaml": {
- compressible: true,
- extensions: ["raml"]
- },
- "application/raptorfec": {
- source: "iana"
- },
- "application/rdap+json": {
- source: "iana",
- compressible: true
- },
- "application/rdf+xml": {
- source: "iana",
- compressible: true,
- extensions: ["rdf", "owl"]
- },
- "application/reginfo+xml": {
- source: "iana",
- compressible: true,
- extensions: ["rif"]
- },
- "application/relax-ng-compact-syntax": {
- source: "iana",
- extensions: ["rnc"]
- },
- "application/remote-printing": {
- source: "iana"
- },
- "application/reputon+json": {
- source: "iana",
- compressible: true
- },
- "application/resource-lists+xml": {
- source: "iana",
- compressible: true,
- extensions: ["rl"]
- },
- "application/resource-lists-diff+xml": {
- source: "iana",
- compressible: true,
- extensions: ["rld"]
- },
- "application/rfc+xml": {
- source: "iana",
- compressible: true
- },
- "application/riscos": {
- source: "iana"
- },
- "application/rlmi+xml": {
- source: "iana",
- compressible: true
- },
- "application/rls-services+xml": {
- source: "iana",
- compressible: true,
- extensions: ["rs"]
- },
- "application/route-apd+xml": {
- source: "iana",
- compressible: true,
- extensions: ["rapd"]
- },
- "application/route-s-tsid+xml": {
- source: "iana",
- compressible: true,
- extensions: ["sls"]
- },
- "application/route-usd+xml": {
- source: "iana",
- compressible: true,
- extensions: ["rusd"]
- },
- "application/rpki-ghostbusters": {
- source: "iana",
- extensions: ["gbr"]
- },
- "application/rpki-manifest": {
- source: "iana",
- extensions: ["mft"]
- },
- "application/rpki-publication": {
- source: "iana"
- },
- "application/rpki-roa": {
- source: "iana",
- extensions: ["roa"]
- },
- "application/rpki-updown": {
- source: "iana"
- },
- "application/rsd+xml": {
- source: "apache",
- compressible: true,
- extensions: ["rsd"]
- },
- "application/rss+xml": {
- source: "apache",
- compressible: true,
- extensions: ["rss"]
- },
- "application/rtf": {
- source: "iana",
- compressible: true,
- extensions: ["rtf"]
- },
- "application/rtploopback": {
- source: "iana"
- },
- "application/rtx": {
- source: "iana"
- },
- "application/samlassertion+xml": {
- source: "iana",
- compressible: true
- },
- "application/samlmetadata+xml": {
- source: "iana",
- compressible: true
- },
- "application/sarif+json": {
- source: "iana",
- compressible: true
- },
- "application/sarif-external-properties+json": {
- source: "iana",
- compressible: true
- },
- "application/sbe": {
- source: "iana"
- },
- "application/sbml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["sbml"]
- },
- "application/scaip+xml": {
- source: "iana",
- compressible: true
- },
- "application/scim+json": {
- source: "iana",
- compressible: true
- },
- "application/scvp-cv-request": {
- source: "iana",
- extensions: ["scq"]
- },
- "application/scvp-cv-response": {
- source: "iana",
- extensions: ["scs"]
- },
- "application/scvp-vp-request": {
- source: "iana",
- extensions: ["spq"]
- },
- "application/scvp-vp-response": {
- source: "iana",
- extensions: ["spp"]
- },
- "application/sdp": {
- source: "iana",
- extensions: ["sdp"]
- },
- "application/secevent+jwt": {
- source: "iana"
- },
- "application/senml+cbor": {
- source: "iana"
- },
- "application/senml+json": {
- source: "iana",
- compressible: true
- },
- "application/senml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["senmlx"]
- },
- "application/senml-etch+cbor": {
- source: "iana"
- },
- "application/senml-etch+json": {
- source: "iana",
- compressible: true
- },
- "application/senml-exi": {
- source: "iana"
- },
- "application/sensml+cbor": {
- source: "iana"
- },
- "application/sensml+json": {
- source: "iana",
- compressible: true
- },
- "application/sensml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["sensmlx"]
- },
- "application/sensml-exi": {
- source: "iana"
- },
- "application/sep+xml": {
- source: "iana",
- compressible: true
- },
- "application/sep-exi": {
- source: "iana"
- },
- "application/session-info": {
- source: "iana"
- },
- "application/set-payment": {
- source: "iana"
- },
- "application/set-payment-initiation": {
- source: "iana",
- extensions: ["setpay"]
- },
- "application/set-registration": {
- source: "iana"
- },
- "application/set-registration-initiation": {
- source: "iana",
- extensions: ["setreg"]
- },
- "application/sgml": {
- source: "iana"
- },
- "application/sgml-open-catalog": {
- source: "iana"
- },
- "application/shf+xml": {
- source: "iana",
- compressible: true,
- extensions: ["shf"]
- },
- "application/sieve": {
- source: "iana",
- extensions: ["siv", "sieve"]
- },
- "application/simple-filter+xml": {
- source: "iana",
- compressible: true
- },
- "application/simple-message-summary": {
- source: "iana"
- },
- "application/simplesymbolcontainer": {
- source: "iana"
- },
- "application/sipc": {
- source: "iana"
- },
- "application/slate": {
- source: "iana"
- },
- "application/smil": {
- source: "iana"
- },
- "application/smil+xml": {
- source: "iana",
- compressible: true,
- extensions: ["smi", "smil"]
- },
- "application/smpte336m": {
- source: "iana"
- },
- "application/soap+fastinfoset": {
- source: "iana"
- },
- "application/soap+xml": {
- source: "iana",
- compressible: true
- },
- "application/sparql-query": {
- source: "iana",
- extensions: ["rq"]
- },
- "application/sparql-results+xml": {
- source: "iana",
- compressible: true,
- extensions: ["srx"]
- },
- "application/spdx+json": {
- source: "iana",
- compressible: true
- },
- "application/spirits-event+xml": {
- source: "iana",
- compressible: true
- },
- "application/sql": {
- source: "iana"
- },
- "application/srgs": {
- source: "iana",
- extensions: ["gram"]
- },
- "application/srgs+xml": {
- source: "iana",
- compressible: true,
- extensions: ["grxml"]
- },
- "application/sru+xml": {
- source: "iana",
- compressible: true,
- extensions: ["sru"]
- },
- "application/ssdl+xml": {
- source: "apache",
- compressible: true,
- extensions: ["ssdl"]
- },
- "application/ssml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["ssml"]
- },
- "application/stix+json": {
- source: "iana",
- compressible: true
- },
- "application/swid+xml": {
- source: "iana",
- compressible: true,
- extensions: ["swidtag"]
- },
- "application/tamp-apex-update": {
- source: "iana"
- },
- "application/tamp-apex-update-confirm": {
- source: "iana"
- },
- "application/tamp-community-update": {
- source: "iana"
- },
- "application/tamp-community-update-confirm": {
- source: "iana"
- },
- "application/tamp-error": {
- source: "iana"
- },
- "application/tamp-sequence-adjust": {
- source: "iana"
- },
- "application/tamp-sequence-adjust-confirm": {
- source: "iana"
- },
- "application/tamp-status-query": {
- source: "iana"
- },
- "application/tamp-status-response": {
- source: "iana"
- },
- "application/tamp-update": {
- source: "iana"
- },
- "application/tamp-update-confirm": {
- source: "iana"
- },
- "application/tar": {
- compressible: true
- },
- "application/taxii+json": {
- source: "iana",
- compressible: true
- },
- "application/td+json": {
- source: "iana",
- compressible: true
- },
- "application/tei+xml": {
- source: "iana",
- compressible: true,
- extensions: ["tei", "teicorpus"]
- },
- "application/tetra_isi": {
- source: "iana"
- },
- "application/thraud+xml": {
- source: "iana",
- compressible: true,
- extensions: ["tfi"]
- },
- "application/timestamp-query": {
- source: "iana"
- },
- "application/timestamp-reply": {
- source: "iana"
- },
- "application/timestamped-data": {
- source: "iana",
- extensions: ["tsd"]
- },
- "application/tlsrpt+gzip": {
- source: "iana"
- },
- "application/tlsrpt+json": {
- source: "iana",
- compressible: true
- },
- "application/tnauthlist": {
- source: "iana"
- },
- "application/token-introspection+jwt": {
- source: "iana"
- },
- "application/toml": {
- compressible: true,
- extensions: ["toml"]
- },
- "application/trickle-ice-sdpfrag": {
- source: "iana"
- },
- "application/trig": {
- source: "iana",
- extensions: ["trig"]
- },
- "application/ttml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["ttml"]
- },
- "application/tve-trigger": {
- source: "iana"
- },
- "application/tzif": {
- source: "iana"
- },
- "application/tzif-leap": {
- source: "iana"
- },
- "application/ubjson": {
- compressible: false,
- extensions: ["ubj"]
- },
- "application/ulpfec": {
- source: "iana"
- },
- "application/urc-grpsheet+xml": {
- source: "iana",
- compressible: true
- },
- "application/urc-ressheet+xml": {
- source: "iana",
- compressible: true,
- extensions: ["rsheet"]
- },
- "application/urc-targetdesc+xml": {
- source: "iana",
- compressible: true,
- extensions: ["td"]
- },
- "application/urc-uisocketdesc+xml": {
- source: "iana",
- compressible: true
- },
- "application/vcard+json": {
- source: "iana",
- compressible: true
- },
- "application/vcard+xml": {
- source: "iana",
- compressible: true
- },
- "application/vemmi": {
- source: "iana"
- },
- "application/vividence.scriptfile": {
- source: "apache"
- },
- "application/vnd.1000minds.decision-model+xml": {
- source: "iana",
- compressible: true,
- extensions: ["1km"]
- },
- "application/vnd.3gpp-prose+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp-prose-pc3ch+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp-v2x-local-service-information": {
- source: "iana"
- },
- "application/vnd.3gpp.5gnas": {
- source: "iana"
- },
- "application/vnd.3gpp.access-transfer-events+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.bsf+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.gmop+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.gtpc": {
- source: "iana"
- },
- "application/vnd.3gpp.interworking-data": {
- source: "iana"
- },
- "application/vnd.3gpp.lpp": {
- source: "iana"
- },
- "application/vnd.3gpp.mc-signalling-ear": {
- source: "iana"
- },
- "application/vnd.3gpp.mcdata-affiliation-command+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcdata-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcdata-payload": {
- source: "iana"
- },
- "application/vnd.3gpp.mcdata-service-config+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcdata-signalling": {
- source: "iana"
- },
- "application/vnd.3gpp.mcdata-ue-config+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcdata-user-profile+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcptt-affiliation-command+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcptt-floor-request+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcptt-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcptt-location-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcptt-mbms-usage-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcptt-service-config+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcptt-signed+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcptt-ue-config+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcptt-ue-init-config+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcptt-user-profile+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcvideo-affiliation-command+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcvideo-affiliation-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcvideo-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcvideo-location-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcvideo-service-config+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcvideo-transmission-request+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcvideo-ue-config+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mcvideo-user-profile+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.mid-call+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.ngap": {
- source: "iana"
- },
- "application/vnd.3gpp.pfcp": {
- source: "iana"
- },
- "application/vnd.3gpp.pic-bw-large": {
- source: "iana",
- extensions: ["plb"]
- },
- "application/vnd.3gpp.pic-bw-small": {
- source: "iana",
- extensions: ["psb"]
- },
- "application/vnd.3gpp.pic-bw-var": {
- source: "iana",
- extensions: ["pvb"]
- },
- "application/vnd.3gpp.s1ap": {
- source: "iana"
- },
- "application/vnd.3gpp.sms": {
- source: "iana"
- },
- "application/vnd.3gpp.sms+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.srvcc-ext+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.srvcc-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.state-and-event-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp.ussd+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp2.bcmcsinfo+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.3gpp2.sms": {
- source: "iana"
- },
- "application/vnd.3gpp2.tcap": {
- source: "iana",
- extensions: ["tcap"]
- },
- "application/vnd.3lightssoftware.imagescal": {
- source: "iana"
- },
- "application/vnd.3m.post-it-notes": {
- source: "iana",
- extensions: ["pwn"]
- },
- "application/vnd.accpac.simply.aso": {
- source: "iana",
- extensions: ["aso"]
- },
- "application/vnd.accpac.simply.imp": {
- source: "iana",
- extensions: ["imp"]
- },
- "application/vnd.acucobol": {
- source: "iana",
- extensions: ["acu"]
- },
- "application/vnd.acucorp": {
- source: "iana",
- extensions: ["atc", "acutc"]
- },
- "application/vnd.adobe.air-application-installer-package+zip": {
- source: "apache",
- compressible: false,
- extensions: ["air"]
- },
- "application/vnd.adobe.flash.movie": {
- source: "iana"
- },
- "application/vnd.adobe.formscentral.fcdt": {
- source: "iana",
- extensions: ["fcdt"]
- },
- "application/vnd.adobe.fxp": {
- source: "iana",
- extensions: ["fxp", "fxpl"]
- },
- "application/vnd.adobe.partial-upload": {
- source: "iana"
- },
- "application/vnd.adobe.xdp+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xdp"]
- },
- "application/vnd.adobe.xfdf": {
- source: "iana",
- extensions: ["xfdf"]
- },
- "application/vnd.aether.imp": {
- source: "iana"
- },
- "application/vnd.afpc.afplinedata": {
- source: "iana"
- },
- "application/vnd.afpc.afplinedata-pagedef": {
- source: "iana"
- },
- "application/vnd.afpc.cmoca-cmresource": {
- source: "iana"
- },
- "application/vnd.afpc.foca-charset": {
- source: "iana"
- },
- "application/vnd.afpc.foca-codedfont": {
- source: "iana"
- },
- "application/vnd.afpc.foca-codepage": {
- source: "iana"
- },
- "application/vnd.afpc.modca": {
- source: "iana"
- },
- "application/vnd.afpc.modca-cmtable": {
- source: "iana"
- },
- "application/vnd.afpc.modca-formdef": {
- source: "iana"
- },
- "application/vnd.afpc.modca-mediummap": {
- source: "iana"
- },
- "application/vnd.afpc.modca-objectcontainer": {
- source: "iana"
- },
- "application/vnd.afpc.modca-overlay": {
- source: "iana"
- },
- "application/vnd.afpc.modca-pagesegment": {
- source: "iana"
- },
- "application/vnd.age": {
- source: "iana",
- extensions: ["age"]
- },
- "application/vnd.ah-barcode": {
- source: "iana"
- },
- "application/vnd.ahead.space": {
- source: "iana",
- extensions: ["ahead"]
- },
- "application/vnd.airzip.filesecure.azf": {
- source: "iana",
- extensions: ["azf"]
- },
- "application/vnd.airzip.filesecure.azs": {
- source: "iana",
- extensions: ["azs"]
- },
- "application/vnd.amadeus+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.amazon.ebook": {
- source: "apache",
- extensions: ["azw"]
- },
- "application/vnd.amazon.mobi8-ebook": {
- source: "iana"
- },
- "application/vnd.americandynamics.acc": {
- source: "iana",
- extensions: ["acc"]
- },
- "application/vnd.amiga.ami": {
- source: "iana",
- extensions: ["ami"]
- },
- "application/vnd.amundsen.maze+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.android.ota": {
- source: "iana"
- },
- "application/vnd.android.package-archive": {
- source: "apache",
- compressible: false,
- extensions: ["apk"]
- },
- "application/vnd.anki": {
- source: "iana"
- },
- "application/vnd.anser-web-certificate-issue-initiation": {
- source: "iana",
- extensions: ["cii"]
- },
- "application/vnd.anser-web-funds-transfer-initiation": {
- source: "apache",
- extensions: ["fti"]
- },
- "application/vnd.antix.game-component": {
- source: "iana",
- extensions: ["atx"]
- },
- "application/vnd.apache.arrow.file": {
- source: "iana"
- },
- "application/vnd.apache.arrow.stream": {
- source: "iana"
- },
- "application/vnd.apache.thrift.binary": {
- source: "iana"
- },
- "application/vnd.apache.thrift.compact": {
- source: "iana"
- },
- "application/vnd.apache.thrift.json": {
- source: "iana"
- },
- "application/vnd.api+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.aplextor.warrp+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.apothekende.reservation+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.apple.installer+xml": {
- source: "iana",
- compressible: true,
- extensions: ["mpkg"]
- },
- "application/vnd.apple.keynote": {
- source: "iana",
- extensions: ["key"]
- },
- "application/vnd.apple.mpegurl": {
- source: "iana",
- extensions: ["m3u8"]
- },
- "application/vnd.apple.numbers": {
- source: "iana",
- extensions: ["numbers"]
- },
- "application/vnd.apple.pages": {
- source: "iana",
- extensions: ["pages"]
- },
- "application/vnd.apple.pkpass": {
- compressible: false,
- extensions: ["pkpass"]
- },
- "application/vnd.arastra.swi": {
- source: "iana"
- },
- "application/vnd.aristanetworks.swi": {
- source: "iana",
- extensions: ["swi"]
- },
- "application/vnd.artisan+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.artsquare": {
- source: "iana"
- },
- "application/vnd.astraea-software.iota": {
- source: "iana",
- extensions: ["iota"]
- },
- "application/vnd.audiograph": {
- source: "iana",
- extensions: ["aep"]
- },
- "application/vnd.autopackage": {
- source: "iana"
- },
- "application/vnd.avalon+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.avistar+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.balsamiq.bmml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["bmml"]
- },
- "application/vnd.balsamiq.bmpr": {
- source: "iana"
- },
- "application/vnd.banana-accounting": {
- source: "iana"
- },
- "application/vnd.bbf.usp.error": {
- source: "iana"
- },
- "application/vnd.bbf.usp.msg": {
- source: "iana"
- },
- "application/vnd.bbf.usp.msg+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.bekitzur-stech+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.bint.med-content": {
- source: "iana"
- },
- "application/vnd.biopax.rdf+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.blink-idb-value-wrapper": {
- source: "iana"
- },
- "application/vnd.blueice.multipass": {
- source: "iana",
- extensions: ["mpm"]
- },
- "application/vnd.bluetooth.ep.oob": {
- source: "iana"
- },
- "application/vnd.bluetooth.le.oob": {
- source: "iana"
- },
- "application/vnd.bmi": {
- source: "iana",
- extensions: ["bmi"]
- },
- "application/vnd.bpf": {
- source: "iana"
- },
- "application/vnd.bpf3": {
- source: "iana"
- },
- "application/vnd.businessobjects": {
- source: "iana",
- extensions: ["rep"]
- },
- "application/vnd.byu.uapi+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.cab-jscript": {
- source: "iana"
- },
- "application/vnd.canon-cpdl": {
- source: "iana"
- },
- "application/vnd.canon-lips": {
- source: "iana"
- },
- "application/vnd.capasystems-pg+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.cendio.thinlinc.clientconf": {
- source: "iana"
- },
- "application/vnd.century-systems.tcp_stream": {
- source: "iana"
- },
- "application/vnd.chemdraw+xml": {
- source: "iana",
- compressible: true,
- extensions: ["cdxml"]
- },
- "application/vnd.chess-pgn": {
- source: "iana"
- },
- "application/vnd.chipnuts.karaoke-mmd": {
- source: "iana",
- extensions: ["mmd"]
- },
- "application/vnd.ciedi": {
- source: "iana"
- },
- "application/vnd.cinderella": {
- source: "iana",
- extensions: ["cdy"]
- },
- "application/vnd.cirpack.isdn-ext": {
- source: "iana"
- },
- "application/vnd.citationstyles.style+xml": {
- source: "iana",
- compressible: true,
- extensions: ["csl"]
- },
- "application/vnd.claymore": {
- source: "iana",
- extensions: ["cla"]
- },
- "application/vnd.cloanto.rp9": {
- source: "iana",
- extensions: ["rp9"]
- },
- "application/vnd.clonk.c4group": {
- source: "iana",
- extensions: ["c4g", "c4d", "c4f", "c4p", "c4u"]
- },
- "application/vnd.cluetrust.cartomobile-config": {
- source: "iana",
- extensions: ["c11amc"]
- },
- "application/vnd.cluetrust.cartomobile-config-pkg": {
- source: "iana",
- extensions: ["c11amz"]
- },
- "application/vnd.coffeescript": {
- source: "iana"
- },
- "application/vnd.collabio.xodocuments.document": {
- source: "iana"
- },
- "application/vnd.collabio.xodocuments.document-template": {
- source: "iana"
- },
- "application/vnd.collabio.xodocuments.presentation": {
- source: "iana"
- },
- "application/vnd.collabio.xodocuments.presentation-template": {
- source: "iana"
- },
- "application/vnd.collabio.xodocuments.spreadsheet": {
- source: "iana"
- },
- "application/vnd.collabio.xodocuments.spreadsheet-template": {
- source: "iana"
- },
- "application/vnd.collection+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.collection.doc+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.collection.next+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.comicbook+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.comicbook-rar": {
- source: "iana"
- },
- "application/vnd.commerce-battelle": {
- source: "iana"
- },
- "application/vnd.commonspace": {
- source: "iana",
- extensions: ["csp"]
- },
- "application/vnd.contact.cmsg": {
- source: "iana",
- extensions: ["cdbcmsg"]
- },
- "application/vnd.coreos.ignition+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.cosmocaller": {
- source: "iana",
- extensions: ["cmc"]
- },
- "application/vnd.crick.clicker": {
- source: "iana",
- extensions: ["clkx"]
- },
- "application/vnd.crick.clicker.keyboard": {
- source: "iana",
- extensions: ["clkk"]
- },
- "application/vnd.crick.clicker.palette": {
- source: "iana",
- extensions: ["clkp"]
- },
- "application/vnd.crick.clicker.template": {
- source: "iana",
- extensions: ["clkt"]
- },
- "application/vnd.crick.clicker.wordbank": {
- source: "iana",
- extensions: ["clkw"]
- },
- "application/vnd.criticaltools.wbs+xml": {
- source: "iana",
- compressible: true,
- extensions: ["wbs"]
- },
- "application/vnd.cryptii.pipe+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.crypto-shade-file": {
- source: "iana"
- },
- "application/vnd.cryptomator.encrypted": {
- source: "iana"
- },
- "application/vnd.cryptomator.vault": {
- source: "iana"
- },
- "application/vnd.ctc-posml": {
- source: "iana",
- extensions: ["pml"]
- },
- "application/vnd.ctct.ws+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.cups-pdf": {
- source: "iana"
- },
- "application/vnd.cups-postscript": {
- source: "iana"
- },
- "application/vnd.cups-ppd": {
- source: "iana",
- extensions: ["ppd"]
- },
- "application/vnd.cups-raster": {
- source: "iana"
- },
- "application/vnd.cups-raw": {
- source: "iana"
- },
- "application/vnd.curl": {
- source: "iana"
- },
- "application/vnd.curl.car": {
- source: "apache",
- extensions: ["car"]
- },
- "application/vnd.curl.pcurl": {
- source: "apache",
- extensions: ["pcurl"]
- },
- "application/vnd.cyan.dean.root+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.cybank": {
- source: "iana"
- },
- "application/vnd.cyclonedx+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.cyclonedx+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.d2l.coursepackage1p0+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.d3m-dataset": {
- source: "iana"
- },
- "application/vnd.d3m-problem": {
- source: "iana"
- },
- "application/vnd.dart": {
- source: "iana",
- compressible: true,
- extensions: ["dart"]
- },
- "application/vnd.data-vision.rdz": {
- source: "iana",
- extensions: ["rdz"]
- },
- "application/vnd.datapackage+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dataresource+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dbf": {
- source: "iana",
- extensions: ["dbf"]
- },
- "application/vnd.debian.binary-package": {
- source: "iana"
- },
- "application/vnd.dece.data": {
- source: "iana",
- extensions: ["uvf", "uvvf", "uvd", "uvvd"]
- },
- "application/vnd.dece.ttml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["uvt", "uvvt"]
- },
- "application/vnd.dece.unspecified": {
- source: "iana",
- extensions: ["uvx", "uvvx"]
- },
- "application/vnd.dece.zip": {
- source: "iana",
- extensions: ["uvz", "uvvz"]
- },
- "application/vnd.denovo.fcselayout-link": {
- source: "iana",
- extensions: ["fe_launch"]
- },
- "application/vnd.desmume.movie": {
- source: "iana"
- },
- "application/vnd.dir-bi.plate-dl-nosuffix": {
- source: "iana"
- },
- "application/vnd.dm.delegation+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dna": {
- source: "iana",
- extensions: ["dna"]
- },
- "application/vnd.document+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dolby.mlp": {
- source: "apache",
- extensions: ["mlp"]
- },
- "application/vnd.dolby.mobile.1": {
- source: "iana"
- },
- "application/vnd.dolby.mobile.2": {
- source: "iana"
- },
- "application/vnd.doremir.scorecloud-binary-document": {
- source: "iana"
- },
- "application/vnd.dpgraph": {
- source: "iana",
- extensions: ["dpg"]
- },
- "application/vnd.dreamfactory": {
- source: "iana",
- extensions: ["dfac"]
- },
- "application/vnd.drive+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ds-keypoint": {
- source: "apache",
- extensions: ["kpxx"]
- },
- "application/vnd.dtg.local": {
- source: "iana"
- },
- "application/vnd.dtg.local.flash": {
- source: "iana"
- },
- "application/vnd.dtg.local.html": {
- source: "iana"
- },
- "application/vnd.dvb.ait": {
- source: "iana",
- extensions: ["ait"]
- },
- "application/vnd.dvb.dvbisl+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dvb.dvbj": {
- source: "iana"
- },
- "application/vnd.dvb.esgcontainer": {
- source: "iana"
- },
- "application/vnd.dvb.ipdcdftnotifaccess": {
- source: "iana"
- },
- "application/vnd.dvb.ipdcesgaccess": {
- source: "iana"
- },
- "application/vnd.dvb.ipdcesgaccess2": {
- source: "iana"
- },
- "application/vnd.dvb.ipdcesgpdd": {
- source: "iana"
- },
- "application/vnd.dvb.ipdcroaming": {
- source: "iana"
- },
- "application/vnd.dvb.iptv.alfec-base": {
- source: "iana"
- },
- "application/vnd.dvb.iptv.alfec-enhancement": {
- source: "iana"
- },
- "application/vnd.dvb.notif-aggregate-root+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dvb.notif-container+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dvb.notif-generic+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dvb.notif-ia-msglist+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dvb.notif-ia-registration-request+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dvb.notif-ia-registration-response+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dvb.notif-init+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.dvb.pfr": {
- source: "iana"
- },
- "application/vnd.dvb.service": {
- source: "iana",
- extensions: ["svc"]
- },
- "application/vnd.dxr": {
- source: "iana"
- },
- "application/vnd.dynageo": {
- source: "iana",
- extensions: ["geo"]
- },
- "application/vnd.dzr": {
- source: "iana"
- },
- "application/vnd.easykaraoke.cdgdownload": {
- source: "iana"
- },
- "application/vnd.ecdis-update": {
- source: "iana"
- },
- "application/vnd.ecip.rlp": {
- source: "iana"
- },
- "application/vnd.eclipse.ditto+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ecowin.chart": {
- source: "iana",
- extensions: ["mag"]
- },
- "application/vnd.ecowin.filerequest": {
- source: "iana"
- },
- "application/vnd.ecowin.fileupdate": {
- source: "iana"
- },
- "application/vnd.ecowin.series": {
- source: "iana"
- },
- "application/vnd.ecowin.seriesrequest": {
- source: "iana"
- },
- "application/vnd.ecowin.seriesupdate": {
- source: "iana"
- },
- "application/vnd.efi.img": {
- source: "iana"
- },
- "application/vnd.efi.iso": {
- source: "iana"
- },
- "application/vnd.emclient.accessrequest+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.enliven": {
- source: "iana",
- extensions: ["nml"]
- },
- "application/vnd.enphase.envoy": {
- source: "iana"
- },
- "application/vnd.eprints.data+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.epson.esf": {
- source: "iana",
- extensions: ["esf"]
- },
- "application/vnd.epson.msf": {
- source: "iana",
- extensions: ["msf"]
- },
- "application/vnd.epson.quickanime": {
- source: "iana",
- extensions: ["qam"]
- },
- "application/vnd.epson.salt": {
- source: "iana",
- extensions: ["slt"]
- },
- "application/vnd.epson.ssf": {
- source: "iana",
- extensions: ["ssf"]
- },
- "application/vnd.ericsson.quickcall": {
- source: "iana"
- },
- "application/vnd.espass-espass+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.eszigno3+xml": {
- source: "iana",
- compressible: true,
- extensions: ["es3", "et3"]
- },
- "application/vnd.etsi.aoc+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.asic-e+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.etsi.asic-s+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.etsi.cug+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.iptvcommand+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.iptvdiscovery+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.iptvprofile+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.iptvsad-bc+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.iptvsad-cod+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.iptvsad-npvr+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.iptvservice+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.iptvsync+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.iptvueprofile+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.mcid+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.mheg5": {
- source: "iana"
- },
- "application/vnd.etsi.overload-control-policy-dataset+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.pstn+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.sci+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.simservs+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.timestamp-token": {
- source: "iana"
- },
- "application/vnd.etsi.tsl+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.etsi.tsl.der": {
- source: "iana"
- },
- "application/vnd.eu.kasparian.car+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.eudora.data": {
- source: "iana"
- },
- "application/vnd.evolv.ecig.profile": {
- source: "iana"
- },
- "application/vnd.evolv.ecig.settings": {
- source: "iana"
- },
- "application/vnd.evolv.ecig.theme": {
- source: "iana"
- },
- "application/vnd.exstream-empower+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.exstream-package": {
- source: "iana"
- },
- "application/vnd.ezpix-album": {
- source: "iana",
- extensions: ["ez2"]
- },
- "application/vnd.ezpix-package": {
- source: "iana",
- extensions: ["ez3"]
- },
- "application/vnd.f-secure.mobile": {
- source: "iana"
- },
- "application/vnd.familysearch.gedcom+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.fastcopy-disk-image": {
- source: "iana"
- },
- "application/vnd.fdf": {
- source: "iana",
- extensions: ["fdf"]
- },
- "application/vnd.fdsn.mseed": {
- source: "iana",
- extensions: ["mseed"]
- },
- "application/vnd.fdsn.seed": {
- source: "iana",
- extensions: ["seed", "dataless"]
- },
- "application/vnd.ffsns": {
- source: "iana"
- },
- "application/vnd.ficlab.flb+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.filmit.zfc": {
- source: "iana"
- },
- "application/vnd.fints": {
- source: "iana"
- },
- "application/vnd.firemonkeys.cloudcell": {
- source: "iana"
- },
- "application/vnd.flographit": {
- source: "iana",
- extensions: ["gph"]
- },
- "application/vnd.fluxtime.clip": {
- source: "iana",
- extensions: ["ftc"]
- },
- "application/vnd.font-fontforge-sfd": {
- source: "iana"
- },
- "application/vnd.framemaker": {
- source: "iana",
- extensions: ["fm", "frame", "maker", "book"]
- },
- "application/vnd.frogans.fnc": {
- source: "iana",
- extensions: ["fnc"]
- },
- "application/vnd.frogans.ltf": {
- source: "iana",
- extensions: ["ltf"]
- },
- "application/vnd.fsc.weblaunch": {
- source: "iana",
- extensions: ["fsc"]
- },
- "application/vnd.fujifilm.fb.docuworks": {
- source: "iana"
- },
- "application/vnd.fujifilm.fb.docuworks.binder": {
- source: "iana"
- },
- "application/vnd.fujifilm.fb.docuworks.container": {
- source: "iana"
- },
- "application/vnd.fujifilm.fb.jfi+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.fujitsu.oasys": {
- source: "iana",
- extensions: ["oas"]
- },
- "application/vnd.fujitsu.oasys2": {
- source: "iana",
- extensions: ["oa2"]
- },
- "application/vnd.fujitsu.oasys3": {
- source: "iana",
- extensions: ["oa3"]
- },
- "application/vnd.fujitsu.oasysgp": {
- source: "iana",
- extensions: ["fg5"]
- },
- "application/vnd.fujitsu.oasysprs": {
- source: "iana",
- extensions: ["bh2"]
- },
- "application/vnd.fujixerox.art-ex": {
- source: "iana"
- },
- "application/vnd.fujixerox.art4": {
- source: "iana"
- },
- "application/vnd.fujixerox.ddd": {
- source: "iana",
- extensions: ["ddd"]
- },
- "application/vnd.fujixerox.docuworks": {
- source: "iana",
- extensions: ["xdw"]
- },
- "application/vnd.fujixerox.docuworks.binder": {
- source: "iana",
- extensions: ["xbd"]
- },
- "application/vnd.fujixerox.docuworks.container": {
- source: "iana"
- },
- "application/vnd.fujixerox.hbpl": {
- source: "iana"
- },
- "application/vnd.fut-misnet": {
- source: "iana"
- },
- "application/vnd.futoin+cbor": {
- source: "iana"
- },
- "application/vnd.futoin+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.fuzzysheet": {
- source: "iana",
- extensions: ["fzs"]
- },
- "application/vnd.genomatix.tuxedo": {
- source: "iana",
- extensions: ["txd"]
- },
- "application/vnd.gentics.grd+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.geo+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.geocube+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.geogebra.file": {
- source: "iana",
- extensions: ["ggb"]
- },
- "application/vnd.geogebra.slides": {
- source: "iana"
- },
- "application/vnd.geogebra.tool": {
- source: "iana",
- extensions: ["ggt"]
- },
- "application/vnd.geometry-explorer": {
- source: "iana",
- extensions: ["gex", "gre"]
- },
- "application/vnd.geonext": {
- source: "iana",
- extensions: ["gxt"]
- },
- "application/vnd.geoplan": {
- source: "iana",
- extensions: ["g2w"]
- },
- "application/vnd.geospace": {
- source: "iana",
- extensions: ["g3w"]
- },
- "application/vnd.gerber": {
- source: "iana"
- },
- "application/vnd.globalplatform.card-content-mgt": {
- source: "iana"
- },
- "application/vnd.globalplatform.card-content-mgt-response": {
- source: "iana"
- },
- "application/vnd.gmx": {
- source: "iana",
- extensions: ["gmx"]
- },
- "application/vnd.google-apps.document": {
- compressible: false,
- extensions: ["gdoc"]
- },
- "application/vnd.google-apps.presentation": {
- compressible: false,
- extensions: ["gslides"]
- },
- "application/vnd.google-apps.spreadsheet": {
- compressible: false,
- extensions: ["gsheet"]
- },
- "application/vnd.google-earth.kml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["kml"]
- },
- "application/vnd.google-earth.kmz": {
- source: "iana",
- compressible: false,
- extensions: ["kmz"]
- },
- "application/vnd.gov.sk.e-form+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.gov.sk.e-form+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.gov.sk.xmldatacontainer+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.grafeq": {
- source: "iana",
- extensions: ["gqf", "gqs"]
- },
- "application/vnd.gridmp": {
- source: "iana"
- },
- "application/vnd.groove-account": {
- source: "iana",
- extensions: ["gac"]
- },
- "application/vnd.groove-help": {
- source: "iana",
- extensions: ["ghf"]
- },
- "application/vnd.groove-identity-message": {
- source: "iana",
- extensions: ["gim"]
- },
- "application/vnd.groove-injector": {
- source: "iana",
- extensions: ["grv"]
- },
- "application/vnd.groove-tool-message": {
- source: "iana",
- extensions: ["gtm"]
- },
- "application/vnd.groove-tool-template": {
- source: "iana",
- extensions: ["tpl"]
- },
- "application/vnd.groove-vcard": {
- source: "iana",
- extensions: ["vcg"]
- },
- "application/vnd.hal+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.hal+xml": {
- source: "iana",
- compressible: true,
- extensions: ["hal"]
- },
- "application/vnd.handheld-entertainment+xml": {
- source: "iana",
- compressible: true,
- extensions: ["zmm"]
- },
- "application/vnd.hbci": {
- source: "iana",
- extensions: ["hbci"]
- },
- "application/vnd.hc+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.hcl-bireports": {
- source: "iana"
- },
- "application/vnd.hdt": {
- source: "iana"
- },
- "application/vnd.heroku+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.hhe.lesson-player": {
- source: "iana",
- extensions: ["les"]
- },
- "application/vnd.hl7cda+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/vnd.hl7v2+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/vnd.hp-hpgl": {
- source: "iana",
- extensions: ["hpgl"]
- },
- "application/vnd.hp-hpid": {
- source: "iana",
- extensions: ["hpid"]
- },
- "application/vnd.hp-hps": {
- source: "iana",
- extensions: ["hps"]
- },
- "application/vnd.hp-jlyt": {
- source: "iana",
- extensions: ["jlt"]
- },
- "application/vnd.hp-pcl": {
- source: "iana",
- extensions: ["pcl"]
- },
- "application/vnd.hp-pclxl": {
- source: "iana",
- extensions: ["pclxl"]
- },
- "application/vnd.httphone": {
- source: "iana"
- },
- "application/vnd.hydrostatix.sof-data": {
- source: "iana",
- extensions: ["sfd-hdstx"]
- },
- "application/vnd.hyper+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.hyper-item+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.hyperdrive+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.hzn-3d-crossword": {
- source: "iana"
- },
- "application/vnd.ibm.afplinedata": {
- source: "iana"
- },
- "application/vnd.ibm.electronic-media": {
- source: "iana"
- },
- "application/vnd.ibm.minipay": {
- source: "iana",
- extensions: ["mpy"]
- },
- "application/vnd.ibm.modcap": {
- source: "iana",
- extensions: ["afp", "listafp", "list3820"]
- },
- "application/vnd.ibm.rights-management": {
- source: "iana",
- extensions: ["irm"]
- },
- "application/vnd.ibm.secure-container": {
- source: "iana",
- extensions: ["sc"]
- },
- "application/vnd.iccprofile": {
- source: "iana",
- extensions: ["icc", "icm"]
- },
- "application/vnd.ieee.1905": {
- source: "iana"
- },
- "application/vnd.igloader": {
- source: "iana",
- extensions: ["igl"]
- },
- "application/vnd.imagemeter.folder+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.imagemeter.image+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.immervision-ivp": {
- source: "iana",
- extensions: ["ivp"]
- },
- "application/vnd.immervision-ivu": {
- source: "iana",
- extensions: ["ivu"]
- },
- "application/vnd.ims.imsccv1p1": {
- source: "iana"
- },
- "application/vnd.ims.imsccv1p2": {
- source: "iana"
- },
- "application/vnd.ims.imsccv1p3": {
- source: "iana"
- },
- "application/vnd.ims.lis.v2.result+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ims.lti.v2.toolconsumerprofile+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ims.lti.v2.toolproxy+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ims.lti.v2.toolproxy.id+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ims.lti.v2.toolsettings+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ims.lti.v2.toolsettings.simple+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.informedcontrol.rms+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.informix-visionary": {
- source: "iana"
- },
- "application/vnd.infotech.project": {
- source: "iana"
- },
- "application/vnd.infotech.project+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.innopath.wamp.notification": {
- source: "iana"
- },
- "application/vnd.insors.igm": {
- source: "iana",
- extensions: ["igm"]
- },
- "application/vnd.intercon.formnet": {
- source: "iana",
- extensions: ["xpw", "xpx"]
- },
- "application/vnd.intergeo": {
- source: "iana",
- extensions: ["i2g"]
- },
- "application/vnd.intertrust.digibox": {
- source: "iana"
- },
- "application/vnd.intertrust.nncp": {
- source: "iana"
- },
- "application/vnd.intu.qbo": {
- source: "iana",
- extensions: ["qbo"]
- },
- "application/vnd.intu.qfx": {
- source: "iana",
- extensions: ["qfx"]
- },
- "application/vnd.iptc.g2.catalogitem+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.iptc.g2.conceptitem+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.iptc.g2.knowledgeitem+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.iptc.g2.newsitem+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.iptc.g2.newsmessage+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.iptc.g2.packageitem+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.iptc.g2.planningitem+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ipunplugged.rcprofile": {
- source: "iana",
- extensions: ["rcprofile"]
- },
- "application/vnd.irepository.package+xml": {
- source: "iana",
- compressible: true,
- extensions: ["irp"]
- },
- "application/vnd.is-xpr": {
- source: "iana",
- extensions: ["xpr"]
- },
- "application/vnd.isac.fcs": {
- source: "iana",
- extensions: ["fcs"]
- },
- "application/vnd.iso11783-10+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.jam": {
- source: "iana",
- extensions: ["jam"]
- },
- "application/vnd.japannet-directory-service": {
- source: "iana"
- },
- "application/vnd.japannet-jpnstore-wakeup": {
- source: "iana"
- },
- "application/vnd.japannet-payment-wakeup": {
- source: "iana"
- },
- "application/vnd.japannet-registration": {
- source: "iana"
- },
- "application/vnd.japannet-registration-wakeup": {
- source: "iana"
- },
- "application/vnd.japannet-setstore-wakeup": {
- source: "iana"
- },
- "application/vnd.japannet-verification": {
- source: "iana"
- },
- "application/vnd.japannet-verification-wakeup": {
- source: "iana"
- },
- "application/vnd.jcp.javame.midlet-rms": {
- source: "iana",
- extensions: ["rms"]
- },
- "application/vnd.jisp": {
- source: "iana",
- extensions: ["jisp"]
- },
- "application/vnd.joost.joda-archive": {
- source: "iana",
- extensions: ["joda"]
- },
- "application/vnd.jsk.isdn-ngn": {
- source: "iana"
- },
- "application/vnd.kahootz": {
- source: "iana",
- extensions: ["ktz", "ktr"]
- },
- "application/vnd.kde.karbon": {
- source: "iana",
- extensions: ["karbon"]
- },
- "application/vnd.kde.kchart": {
- source: "iana",
- extensions: ["chrt"]
- },
- "application/vnd.kde.kformula": {
- source: "iana",
- extensions: ["kfo"]
- },
- "application/vnd.kde.kivio": {
- source: "iana",
- extensions: ["flw"]
- },
- "application/vnd.kde.kontour": {
- source: "iana",
- extensions: ["kon"]
- },
- "application/vnd.kde.kpresenter": {
- source: "iana",
- extensions: ["kpr", "kpt"]
- },
- "application/vnd.kde.kspread": {
- source: "iana",
- extensions: ["ksp"]
- },
- "application/vnd.kde.kword": {
- source: "iana",
- extensions: ["kwd", "kwt"]
- },
- "application/vnd.kenameaapp": {
- source: "iana",
- extensions: ["htke"]
- },
- "application/vnd.kidspiration": {
- source: "iana",
- extensions: ["kia"]
- },
- "application/vnd.kinar": {
- source: "iana",
- extensions: ["kne", "knp"]
- },
- "application/vnd.koan": {
- source: "iana",
- extensions: ["skp", "skd", "skt", "skm"]
- },
- "application/vnd.kodak-descriptor": {
- source: "iana",
- extensions: ["sse"]
- },
- "application/vnd.las": {
- source: "iana"
- },
- "application/vnd.las.las+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.las.las+xml": {
- source: "iana",
- compressible: true,
- extensions: ["lasxml"]
- },
- "application/vnd.laszip": {
- source: "iana"
- },
- "application/vnd.leap+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.liberty-request+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.llamagraphics.life-balance.desktop": {
- source: "iana",
- extensions: ["lbd"]
- },
- "application/vnd.llamagraphics.life-balance.exchange+xml": {
- source: "iana",
- compressible: true,
- extensions: ["lbe"]
- },
- "application/vnd.logipipe.circuit+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.loom": {
- source: "iana"
- },
- "application/vnd.lotus-1-2-3": {
- source: "iana",
- extensions: ["123"]
- },
- "application/vnd.lotus-approach": {
- source: "iana",
- extensions: ["apr"]
- },
- "application/vnd.lotus-freelance": {
- source: "iana",
- extensions: ["pre"]
- },
- "application/vnd.lotus-notes": {
- source: "iana",
- extensions: ["nsf"]
- },
- "application/vnd.lotus-organizer": {
- source: "iana",
- extensions: ["org"]
- },
- "application/vnd.lotus-screencam": {
- source: "iana",
- extensions: ["scm"]
- },
- "application/vnd.lotus-wordpro": {
- source: "iana",
- extensions: ["lwp"]
- },
- "application/vnd.macports.portpkg": {
- source: "iana",
- extensions: ["portpkg"]
- },
- "application/vnd.mapbox-vector-tile": {
- source: "iana",
- extensions: ["mvt"]
- },
- "application/vnd.marlin.drm.actiontoken+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.marlin.drm.conftoken+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.marlin.drm.license+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.marlin.drm.mdcf": {
- source: "iana"
- },
- "application/vnd.mason+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.maxar.archive.3tz+zip": {
- source: "iana",
- compressible: false
- },
- "application/vnd.maxmind.maxmind-db": {
- source: "iana"
- },
- "application/vnd.mcd": {
- source: "iana",
- extensions: ["mcd"]
- },
- "application/vnd.medcalcdata": {
- source: "iana",
- extensions: ["mc1"]
- },
- "application/vnd.mediastation.cdkey": {
- source: "iana",
- extensions: ["cdkey"]
- },
- "application/vnd.meridian-slingshot": {
- source: "iana"
- },
- "application/vnd.mfer": {
- source: "iana",
- extensions: ["mwf"]
- },
- "application/vnd.mfmp": {
- source: "iana",
- extensions: ["mfm"]
- },
- "application/vnd.micro+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.micrografx.flo": {
- source: "iana",
- extensions: ["flo"]
- },
- "application/vnd.micrografx.igx": {
- source: "iana",
- extensions: ["igx"]
- },
- "application/vnd.microsoft.portable-executable": {
- source: "iana"
- },
- "application/vnd.microsoft.windows.thumbnail-cache": {
- source: "iana"
- },
- "application/vnd.miele+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.mif": {
- source: "iana",
- extensions: ["mif"]
- },
- "application/vnd.minisoft-hp3000-save": {
- source: "iana"
- },
- "application/vnd.mitsubishi.misty-guard.trustweb": {
- source: "iana"
- },
- "application/vnd.mobius.daf": {
- source: "iana",
- extensions: ["daf"]
- },
- "application/vnd.mobius.dis": {
- source: "iana",
- extensions: ["dis"]
- },
- "application/vnd.mobius.mbk": {
- source: "iana",
- extensions: ["mbk"]
- },
- "application/vnd.mobius.mqy": {
- source: "iana",
- extensions: ["mqy"]
- },
- "application/vnd.mobius.msl": {
- source: "iana",
- extensions: ["msl"]
- },
- "application/vnd.mobius.plc": {
- source: "iana",
- extensions: ["plc"]
- },
- "application/vnd.mobius.txf": {
- source: "iana",
- extensions: ["txf"]
- },
- "application/vnd.mophun.application": {
- source: "iana",
- extensions: ["mpn"]
- },
- "application/vnd.mophun.certificate": {
- source: "iana",
- extensions: ["mpc"]
- },
- "application/vnd.motorola.flexsuite": {
- source: "iana"
- },
- "application/vnd.motorola.flexsuite.adsi": {
- source: "iana"
- },
- "application/vnd.motorola.flexsuite.fis": {
- source: "iana"
- },
- "application/vnd.motorola.flexsuite.gotap": {
- source: "iana"
- },
- "application/vnd.motorola.flexsuite.kmr": {
- source: "iana"
- },
- "application/vnd.motorola.flexsuite.ttc": {
- source: "iana"
- },
- "application/vnd.motorola.flexsuite.wem": {
- source: "iana"
- },
- "application/vnd.motorola.iprm": {
- source: "iana"
- },
- "application/vnd.mozilla.xul+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xul"]
- },
- "application/vnd.ms-3mfdocument": {
- source: "iana"
- },
- "application/vnd.ms-artgalry": {
- source: "iana",
- extensions: ["cil"]
- },
- "application/vnd.ms-asf": {
- source: "iana"
- },
- "application/vnd.ms-cab-compressed": {
- source: "iana",
- extensions: ["cab"]
- },
- "application/vnd.ms-color.iccprofile": {
- source: "apache"
- },
- "application/vnd.ms-excel": {
- source: "iana",
- compressible: false,
- extensions: ["xls", "xlm", "xla", "xlc", "xlt", "xlw"]
- },
- "application/vnd.ms-excel.addin.macroenabled.12": {
- source: "iana",
- extensions: ["xlam"]
- },
- "application/vnd.ms-excel.sheet.binary.macroenabled.12": {
- source: "iana",
- extensions: ["xlsb"]
- },
- "application/vnd.ms-excel.sheet.macroenabled.12": {
- source: "iana",
- extensions: ["xlsm"]
- },
- "application/vnd.ms-excel.template.macroenabled.12": {
- source: "iana",
- extensions: ["xltm"]
- },
- "application/vnd.ms-fontobject": {
- source: "iana",
- compressible: true,
- extensions: ["eot"]
- },
- "application/vnd.ms-htmlhelp": {
- source: "iana",
- extensions: ["chm"]
- },
- "application/vnd.ms-ims": {
- source: "iana",
- extensions: ["ims"]
- },
- "application/vnd.ms-lrm": {
- source: "iana",
- extensions: ["lrm"]
- },
- "application/vnd.ms-office.activex+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ms-officetheme": {
- source: "iana",
- extensions: ["thmx"]
- },
- "application/vnd.ms-opentype": {
- source: "apache",
- compressible: true
- },
- "application/vnd.ms-outlook": {
- compressible: false,
- extensions: ["msg"]
- },
- "application/vnd.ms-package.obfuscated-opentype": {
- source: "apache"
- },
- "application/vnd.ms-pki.seccat": {
- source: "apache",
- extensions: ["cat"]
- },
- "application/vnd.ms-pki.stl": {
- source: "apache",
- extensions: ["stl"]
- },
- "application/vnd.ms-playready.initiator+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ms-powerpoint": {
- source: "iana",
- compressible: false,
- extensions: ["ppt", "pps", "pot"]
- },
- "application/vnd.ms-powerpoint.addin.macroenabled.12": {
- source: "iana",
- extensions: ["ppam"]
- },
- "application/vnd.ms-powerpoint.presentation.macroenabled.12": {
- source: "iana",
- extensions: ["pptm"]
- },
- "application/vnd.ms-powerpoint.slide.macroenabled.12": {
- source: "iana",
- extensions: ["sldm"]
- },
- "application/vnd.ms-powerpoint.slideshow.macroenabled.12": {
- source: "iana",
- extensions: ["ppsm"]
- },
- "application/vnd.ms-powerpoint.template.macroenabled.12": {
- source: "iana",
- extensions: ["potm"]
- },
- "application/vnd.ms-printdevicecapabilities+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ms-printing.printticket+xml": {
- source: "apache",
- compressible: true
- },
- "application/vnd.ms-printschematicket+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ms-project": {
- source: "iana",
- extensions: ["mpp", "mpt"]
- },
- "application/vnd.ms-tnef": {
- source: "iana"
- },
- "application/vnd.ms-windows.devicepairing": {
- source: "iana"
- },
- "application/vnd.ms-windows.nwprinting.oob": {
- source: "iana"
- },
- "application/vnd.ms-windows.printerpairing": {
- source: "iana"
- },
- "application/vnd.ms-windows.wsd.oob": {
- source: "iana"
- },
- "application/vnd.ms-wmdrm.lic-chlg-req": {
- source: "iana"
- },
- "application/vnd.ms-wmdrm.lic-resp": {
- source: "iana"
- },
- "application/vnd.ms-wmdrm.meter-chlg-req": {
- source: "iana"
- },
- "application/vnd.ms-wmdrm.meter-resp": {
- source: "iana"
- },
- "application/vnd.ms-word.document.macroenabled.12": {
- source: "iana",
- extensions: ["docm"]
- },
- "application/vnd.ms-word.template.macroenabled.12": {
- source: "iana",
- extensions: ["dotm"]
- },
- "application/vnd.ms-works": {
- source: "iana",
- extensions: ["wps", "wks", "wcm", "wdb"]
- },
- "application/vnd.ms-wpl": {
- source: "iana",
- extensions: ["wpl"]
- },
- "application/vnd.ms-xpsdocument": {
- source: "iana",
- compressible: false,
- extensions: ["xps"]
- },
- "application/vnd.msa-disk-image": {
- source: "iana"
- },
- "application/vnd.mseq": {
- source: "iana",
- extensions: ["mseq"]
- },
- "application/vnd.msign": {
- source: "iana"
- },
- "application/vnd.multiad.creator": {
- source: "iana"
- },
- "application/vnd.multiad.creator.cif": {
- source: "iana"
- },
- "application/vnd.music-niff": {
- source: "iana"
- },
- "application/vnd.musician": {
- source: "iana",
- extensions: ["mus"]
- },
- "application/vnd.muvee.style": {
- source: "iana",
- extensions: ["msty"]
- },
- "application/vnd.mynfc": {
- source: "iana",
- extensions: ["taglet"]
- },
- "application/vnd.nacamar.ybrid+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.ncd.control": {
- source: "iana"
- },
- "application/vnd.ncd.reference": {
- source: "iana"
- },
- "application/vnd.nearst.inv+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.nebumind.line": {
- source: "iana"
- },
- "application/vnd.nervana": {
- source: "iana"
- },
- "application/vnd.netfpx": {
- source: "iana"
- },
- "application/vnd.neurolanguage.nlu": {
- source: "iana",
- extensions: ["nlu"]
- },
- "application/vnd.nimn": {
- source: "iana"
- },
- "application/vnd.nintendo.nitro.rom": {
- source: "iana"
- },
- "application/vnd.nintendo.snes.rom": {
- source: "iana"
- },
- "application/vnd.nitf": {
- source: "iana",
- extensions: ["ntf", "nitf"]
- },
- "application/vnd.noblenet-directory": {
- source: "iana",
- extensions: ["nnd"]
- },
- "application/vnd.noblenet-sealer": {
- source: "iana",
- extensions: ["nns"]
- },
- "application/vnd.noblenet-web": {
- source: "iana",
- extensions: ["nnw"]
- },
- "application/vnd.nokia.catalogs": {
- source: "iana"
- },
- "application/vnd.nokia.conml+wbxml": {
- source: "iana"
- },
- "application/vnd.nokia.conml+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.nokia.iptv.config+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.nokia.isds-radio-presets": {
- source: "iana"
- },
- "application/vnd.nokia.landmark+wbxml": {
- source: "iana"
- },
- "application/vnd.nokia.landmark+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.nokia.landmarkcollection+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.nokia.n-gage.ac+xml": {
- source: "iana",
- compressible: true,
- extensions: ["ac"]
- },
- "application/vnd.nokia.n-gage.data": {
- source: "iana",
- extensions: ["ngdat"]
- },
- "application/vnd.nokia.n-gage.symbian.install": {
- source: "iana",
- extensions: ["n-gage"]
- },
- "application/vnd.nokia.ncd": {
- source: "iana"
- },
- "application/vnd.nokia.pcd+wbxml": {
- source: "iana"
- },
- "application/vnd.nokia.pcd+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.nokia.radio-preset": {
- source: "iana",
- extensions: ["rpst"]
- },
- "application/vnd.nokia.radio-presets": {
- source: "iana",
- extensions: ["rpss"]
- },
- "application/vnd.novadigm.edm": {
- source: "iana",
- extensions: ["edm"]
- },
- "application/vnd.novadigm.edx": {
- source: "iana",
- extensions: ["edx"]
- },
- "application/vnd.novadigm.ext": {
- source: "iana",
- extensions: ["ext"]
- },
- "application/vnd.ntt-local.content-share": {
- source: "iana"
- },
- "application/vnd.ntt-local.file-transfer": {
- source: "iana"
- },
- "application/vnd.ntt-local.ogw_remote-access": {
- source: "iana"
- },
- "application/vnd.ntt-local.sip-ta_remote": {
- source: "iana"
- },
- "application/vnd.ntt-local.sip-ta_tcp_stream": {
- source: "iana"
- },
- "application/vnd.oasis.opendocument.chart": {
- source: "iana",
- extensions: ["odc"]
- },
- "application/vnd.oasis.opendocument.chart-template": {
- source: "iana",
- extensions: ["otc"]
- },
- "application/vnd.oasis.opendocument.database": {
- source: "iana",
- extensions: ["odb"]
- },
- "application/vnd.oasis.opendocument.formula": {
- source: "iana",
- extensions: ["odf"]
- },
- "application/vnd.oasis.opendocument.formula-template": {
- source: "iana",
- extensions: ["odft"]
- },
- "application/vnd.oasis.opendocument.graphics": {
- source: "iana",
- compressible: false,
- extensions: ["odg"]
- },
- "application/vnd.oasis.opendocument.graphics-template": {
- source: "iana",
- extensions: ["otg"]
- },
- "application/vnd.oasis.opendocument.image": {
- source: "iana",
- extensions: ["odi"]
- },
- "application/vnd.oasis.opendocument.image-template": {
- source: "iana",
- extensions: ["oti"]
- },
- "application/vnd.oasis.opendocument.presentation": {
- source: "iana",
- compressible: false,
- extensions: ["odp"]
- },
- "application/vnd.oasis.opendocument.presentation-template": {
- source: "iana",
- extensions: ["otp"]
- },
- "application/vnd.oasis.opendocument.spreadsheet": {
- source: "iana",
- compressible: false,
- extensions: ["ods"]
- },
- "application/vnd.oasis.opendocument.spreadsheet-template": {
- source: "iana",
- extensions: ["ots"]
- },
- "application/vnd.oasis.opendocument.text": {
- source: "iana",
- compressible: false,
- extensions: ["odt"]
- },
- "application/vnd.oasis.opendocument.text-master": {
- source: "iana",
- extensions: ["odm"]
- },
- "application/vnd.oasis.opendocument.text-template": {
- source: "iana",
- extensions: ["ott"]
- },
- "application/vnd.oasis.opendocument.text-web": {
- source: "iana",
- extensions: ["oth"]
- },
- "application/vnd.obn": {
- source: "iana"
- },
- "application/vnd.ocf+cbor": {
- source: "iana"
- },
- "application/vnd.oci.image.manifest.v1+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oftn.l10n+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oipf.contentaccessdownload+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oipf.contentaccessstreaming+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oipf.cspg-hexbinary": {
- source: "iana"
- },
- "application/vnd.oipf.dae.svg+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oipf.dae.xhtml+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oipf.mippvcontrolmessage+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oipf.pae.gem": {
- source: "iana"
- },
- "application/vnd.oipf.spdiscovery+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oipf.spdlist+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oipf.ueprofile+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oipf.userprofile+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.olpc-sugar": {
- source: "iana",
- extensions: ["xo"]
- },
- "application/vnd.oma-scws-config": {
- source: "iana"
- },
- "application/vnd.oma-scws-http-request": {
- source: "iana"
- },
- "application/vnd.oma-scws-http-response": {
- source: "iana"
- },
- "application/vnd.oma.bcast.associated-procedure-parameter+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.bcast.drm-trigger+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.bcast.imd+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.bcast.ltkm": {
- source: "iana"
- },
- "application/vnd.oma.bcast.notification+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.bcast.provisioningtrigger": {
- source: "iana"
- },
- "application/vnd.oma.bcast.sgboot": {
- source: "iana"
- },
- "application/vnd.oma.bcast.sgdd+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.bcast.sgdu": {
- source: "iana"
- },
- "application/vnd.oma.bcast.simple-symbol-container": {
- source: "iana"
- },
- "application/vnd.oma.bcast.smartcard-trigger+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.bcast.sprov+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.bcast.stkm": {
- source: "iana"
- },
- "application/vnd.oma.cab-address-book+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.cab-feature-handler+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.cab-pcc+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.cab-subs-invite+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.cab-user-prefs+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.dcd": {
- source: "iana"
- },
- "application/vnd.oma.dcdc": {
- source: "iana"
- },
- "application/vnd.oma.dd2+xml": {
- source: "iana",
- compressible: true,
- extensions: ["dd2"]
- },
- "application/vnd.oma.drm.risd+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.group-usage-list+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.lwm2m+cbor": {
- source: "iana"
- },
- "application/vnd.oma.lwm2m+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.lwm2m+tlv": {
- source: "iana"
- },
- "application/vnd.oma.pal+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.poc.detailed-progress-report+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.poc.final-report+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.poc.groups+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.poc.invocation-descriptor+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.poc.optimized-progress-report+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.push": {
- source: "iana"
- },
- "application/vnd.oma.scidm.messages+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oma.xcap-directory+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.omads-email+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/vnd.omads-file+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/vnd.omads-folder+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/vnd.omaloc-supl-init": {
- source: "iana"
- },
- "application/vnd.onepager": {
- source: "iana"
- },
- "application/vnd.onepagertamp": {
- source: "iana"
- },
- "application/vnd.onepagertamx": {
- source: "iana"
- },
- "application/vnd.onepagertat": {
- source: "iana"
- },
- "application/vnd.onepagertatp": {
- source: "iana"
- },
- "application/vnd.onepagertatx": {
- source: "iana"
- },
- "application/vnd.openblox.game+xml": {
- source: "iana",
- compressible: true,
- extensions: ["obgx"]
- },
- "application/vnd.openblox.game-binary": {
- source: "iana"
- },
- "application/vnd.openeye.oeb": {
- source: "iana"
- },
- "application/vnd.openofficeorg.extension": {
- source: "apache",
- extensions: ["oxt"]
- },
- "application/vnd.openstreetmap.data+xml": {
- source: "iana",
- compressible: true,
- extensions: ["osm"]
- },
- "application/vnd.opentimestamps.ots": {
- source: "iana"
- },
- "application/vnd.openxmlformats-officedocument.custom-properties+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.drawing+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.extended-properties+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.presentation": {
- source: "iana",
- compressible: false,
- extensions: ["pptx"]
- },
- "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.slide": {
- source: "iana",
- extensions: ["sldx"]
- },
- "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.slideshow": {
- source: "iana",
- extensions: ["ppsx"]
- },
- "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.template": {
- source: "iana",
- extensions: ["potx"]
- },
- "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
- source: "iana",
- compressible: false,
- extensions: ["xlsx"]
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.template": {
- source: "iana",
- extensions: ["xltx"]
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.theme+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.themeoverride+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.vmldrawing": {
- source: "iana"
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
- source: "iana",
- compressible: false,
- extensions: ["docx"]
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.template": {
- source: "iana",
- extensions: ["dotx"]
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-package.core-properties+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.openxmlformats-package.relationships+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oracle.resource+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.orange.indata": {
- source: "iana"
- },
- "application/vnd.osa.netdeploy": {
- source: "iana"
- },
- "application/vnd.osgeo.mapguide.package": {
- source: "iana",
- extensions: ["mgp"]
- },
- "application/vnd.osgi.bundle": {
- source: "iana"
- },
- "application/vnd.osgi.dp": {
- source: "iana",
- extensions: ["dp"]
- },
- "application/vnd.osgi.subsystem": {
- source: "iana",
- extensions: ["esa"]
- },
- "application/vnd.otps.ct-kip+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.oxli.countgraph": {
- source: "iana"
- },
- "application/vnd.pagerduty+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.palm": {
- source: "iana",
- extensions: ["pdb", "pqa", "oprc"]
- },
- "application/vnd.panoply": {
- source: "iana"
- },
- "application/vnd.paos.xml": {
- source: "iana"
- },
- "application/vnd.patentdive": {
- source: "iana"
- },
- "application/vnd.patientecommsdoc": {
- source: "iana"
- },
- "application/vnd.pawaafile": {
- source: "iana",
- extensions: ["paw"]
- },
- "application/vnd.pcos": {
- source: "iana"
- },
- "application/vnd.pg.format": {
- source: "iana",
- extensions: ["str"]
- },
- "application/vnd.pg.osasli": {
- source: "iana",
- extensions: ["ei6"]
- },
- "application/vnd.piaccess.application-licence": {
- source: "iana"
- },
- "application/vnd.picsel": {
- source: "iana",
- extensions: ["efif"]
- },
- "application/vnd.pmi.widget": {
- source: "iana",
- extensions: ["wg"]
- },
- "application/vnd.poc.group-advertisement+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.pocketlearn": {
- source: "iana",
- extensions: ["plf"]
- },
- "application/vnd.powerbuilder6": {
- source: "iana",
- extensions: ["pbd"]
- },
- "application/vnd.powerbuilder6-s": {
- source: "iana"
- },
- "application/vnd.powerbuilder7": {
- source: "iana"
- },
- "application/vnd.powerbuilder7-s": {
- source: "iana"
- },
- "application/vnd.powerbuilder75": {
- source: "iana"
- },
- "application/vnd.powerbuilder75-s": {
- source: "iana"
- },
- "application/vnd.preminet": {
- source: "iana"
- },
- "application/vnd.previewsystems.box": {
- source: "iana",
- extensions: ["box"]
- },
- "application/vnd.proteus.magazine": {
- source: "iana",
- extensions: ["mgz"]
- },
- "application/vnd.psfs": {
- source: "iana"
- },
- "application/vnd.publishare-delta-tree": {
- source: "iana",
- extensions: ["qps"]
- },
- "application/vnd.pvi.ptid1": {
- source: "iana",
- extensions: ["ptid"]
- },
- "application/vnd.pwg-multiplexed": {
- source: "iana"
- },
- "application/vnd.pwg-xhtml-print+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.qualcomm.brew-app-res": {
- source: "iana"
- },
- "application/vnd.quarantainenet": {
- source: "iana"
- },
- "application/vnd.quark.quarkxpress": {
- source: "iana",
- extensions: ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"]
- },
- "application/vnd.quobject-quoxdocument": {
- source: "iana"
- },
- "application/vnd.radisys.moml+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-audit+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-audit-conf+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-audit-conn+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-audit-dialog+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-audit-stream+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-conf+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-dialog+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-dialog-base+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-dialog-fax-detect+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-dialog-group+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-dialog-speech+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.radisys.msml-dialog-transform+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.rainstor.data": {
- source: "iana"
- },
- "application/vnd.rapid": {
- source: "iana"
- },
- "application/vnd.rar": {
- source: "iana",
- extensions: ["rar"]
- },
- "application/vnd.realvnc.bed": {
- source: "iana",
- extensions: ["bed"]
- },
- "application/vnd.recordare.musicxml": {
- source: "iana",
- extensions: ["mxl"]
- },
- "application/vnd.recordare.musicxml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["musicxml"]
- },
- "application/vnd.renlearn.rlprint": {
- source: "iana"
- },
- "application/vnd.resilient.logic": {
- source: "iana"
- },
- "application/vnd.restful+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.rig.cryptonote": {
- source: "iana",
- extensions: ["cryptonote"]
- },
- "application/vnd.rim.cod": {
- source: "apache",
- extensions: ["cod"]
- },
- "application/vnd.rn-realmedia": {
- source: "apache",
- extensions: ["rm"]
- },
- "application/vnd.rn-realmedia-vbr": {
- source: "apache",
- extensions: ["rmvb"]
- },
- "application/vnd.route66.link66+xml": {
- source: "iana",
- compressible: true,
- extensions: ["link66"]
- },
- "application/vnd.rs-274x": {
- source: "iana"
- },
- "application/vnd.ruckus.download": {
- source: "iana"
- },
- "application/vnd.s3sms": {
- source: "iana"
- },
- "application/vnd.sailingtracker.track": {
- source: "iana",
- extensions: ["st"]
- },
- "application/vnd.sar": {
- source: "iana"
- },
- "application/vnd.sbm.cid": {
- source: "iana"
- },
- "application/vnd.sbm.mid2": {
- source: "iana"
- },
- "application/vnd.scribus": {
- source: "iana"
- },
- "application/vnd.sealed.3df": {
- source: "iana"
- },
- "application/vnd.sealed.csf": {
- source: "iana"
- },
- "application/vnd.sealed.doc": {
- source: "iana"
- },
- "application/vnd.sealed.eml": {
- source: "iana"
- },
- "application/vnd.sealed.mht": {
- source: "iana"
- },
- "application/vnd.sealed.net": {
- source: "iana"
- },
- "application/vnd.sealed.ppt": {
- source: "iana"
- },
- "application/vnd.sealed.tiff": {
- source: "iana"
- },
- "application/vnd.sealed.xls": {
- source: "iana"
- },
- "application/vnd.sealedmedia.softseal.html": {
- source: "iana"
- },
- "application/vnd.sealedmedia.softseal.pdf": {
- source: "iana"
- },
- "application/vnd.seemail": {
- source: "iana",
- extensions: ["see"]
- },
- "application/vnd.seis+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.sema": {
- source: "iana",
- extensions: ["sema"]
- },
- "application/vnd.semd": {
- source: "iana",
- extensions: ["semd"]
- },
- "application/vnd.semf": {
- source: "iana",
- extensions: ["semf"]
- },
- "application/vnd.shade-save-file": {
- source: "iana"
- },
- "application/vnd.shana.informed.formdata": {
- source: "iana",
- extensions: ["ifm"]
- },
- "application/vnd.shana.informed.formtemplate": {
- source: "iana",
- extensions: ["itp"]
- },
- "application/vnd.shana.informed.interchange": {
- source: "iana",
- extensions: ["iif"]
- },
- "application/vnd.shana.informed.package": {
- source: "iana",
- extensions: ["ipk"]
- },
- "application/vnd.shootproof+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.shopkick+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.shp": {
- source: "iana"
- },
- "application/vnd.shx": {
- source: "iana"
- },
- "application/vnd.sigrok.session": {
- source: "iana"
- },
- "application/vnd.simtech-mindmapper": {
- source: "iana",
- extensions: ["twd", "twds"]
- },
- "application/vnd.siren+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.smaf": {
- source: "iana",
- extensions: ["mmf"]
- },
- "application/vnd.smart.notebook": {
- source: "iana"
- },
- "application/vnd.smart.teacher": {
- source: "iana",
- extensions: ["teacher"]
- },
- "application/vnd.snesdev-page-table": {
- source: "iana"
- },
- "application/vnd.software602.filler.form+xml": {
- source: "iana",
- compressible: true,
- extensions: ["fo"]
- },
- "application/vnd.software602.filler.form-xml-zip": {
- source: "iana"
- },
- "application/vnd.solent.sdkm+xml": {
- source: "iana",
- compressible: true,
- extensions: ["sdkm", "sdkd"]
- },
- "application/vnd.spotfire.dxp": {
- source: "iana",
- extensions: ["dxp"]
- },
- "application/vnd.spotfire.sfs": {
- source: "iana",
- extensions: ["sfs"]
- },
- "application/vnd.sqlite3": {
- source: "iana"
- },
- "application/vnd.sss-cod": {
- source: "iana"
- },
- "application/vnd.sss-dtf": {
- source: "iana"
- },
- "application/vnd.sss-ntf": {
- source: "iana"
- },
- "application/vnd.stardivision.calc": {
- source: "apache",
- extensions: ["sdc"]
- },
- "application/vnd.stardivision.draw": {
- source: "apache",
- extensions: ["sda"]
- },
- "application/vnd.stardivision.impress": {
- source: "apache",
- extensions: ["sdd"]
- },
- "application/vnd.stardivision.math": {
- source: "apache",
- extensions: ["smf"]
- },
- "application/vnd.stardivision.writer": {
- source: "apache",
- extensions: ["sdw", "vor"]
- },
- "application/vnd.stardivision.writer-global": {
- source: "apache",
- extensions: ["sgl"]
- },
- "application/vnd.stepmania.package": {
- source: "iana",
- extensions: ["smzip"]
- },
- "application/vnd.stepmania.stepchart": {
- source: "iana",
- extensions: ["sm"]
- },
- "application/vnd.street-stream": {
- source: "iana"
- },
- "application/vnd.sun.wadl+xml": {
- source: "iana",
- compressible: true,
- extensions: ["wadl"]
- },
- "application/vnd.sun.xml.calc": {
- source: "apache",
- extensions: ["sxc"]
- },
- "application/vnd.sun.xml.calc.template": {
- source: "apache",
- extensions: ["stc"]
- },
- "application/vnd.sun.xml.draw": {
- source: "apache",
- extensions: ["sxd"]
- },
- "application/vnd.sun.xml.draw.template": {
- source: "apache",
- extensions: ["std"]
- },
- "application/vnd.sun.xml.impress": {
- source: "apache",
- extensions: ["sxi"]
- },
- "application/vnd.sun.xml.impress.template": {
- source: "apache",
- extensions: ["sti"]
- },
- "application/vnd.sun.xml.math": {
- source: "apache",
- extensions: ["sxm"]
- },
- "application/vnd.sun.xml.writer": {
- source: "apache",
- extensions: ["sxw"]
- },
- "application/vnd.sun.xml.writer.global": {
- source: "apache",
- extensions: ["sxg"]
- },
- "application/vnd.sun.xml.writer.template": {
- source: "apache",
- extensions: ["stw"]
- },
- "application/vnd.sus-calendar": {
- source: "iana",
- extensions: ["sus", "susp"]
- },
- "application/vnd.svd": {
- source: "iana",
- extensions: ["svd"]
- },
- "application/vnd.swiftview-ics": {
- source: "iana"
- },
- "application/vnd.sycle+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.syft+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.symbian.install": {
- source: "apache",
- extensions: ["sis", "sisx"]
- },
- "application/vnd.syncml+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true,
- extensions: ["xsm"]
- },
- "application/vnd.syncml.dm+wbxml": {
- source: "iana",
- charset: "UTF-8",
- extensions: ["bdm"]
- },
- "application/vnd.syncml.dm+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true,
- extensions: ["xdm"]
- },
- "application/vnd.syncml.dm.notification": {
- source: "iana"
- },
- "application/vnd.syncml.dmddf+wbxml": {
- source: "iana"
- },
- "application/vnd.syncml.dmddf+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true,
- extensions: ["ddf"]
- },
- "application/vnd.syncml.dmtnds+wbxml": {
- source: "iana"
- },
- "application/vnd.syncml.dmtnds+xml": {
- source: "iana",
- charset: "UTF-8",
- compressible: true
- },
- "application/vnd.syncml.ds.notification": {
- source: "iana"
- },
- "application/vnd.tableschema+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.tao.intent-module-archive": {
- source: "iana",
- extensions: ["tao"]
- },
- "application/vnd.tcpdump.pcap": {
- source: "iana",
- extensions: ["pcap", "cap", "dmp"]
- },
- "application/vnd.think-cell.ppttc+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.tmd.mediaflex.api+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.tml": {
- source: "iana"
- },
- "application/vnd.tmobile-livetv": {
- source: "iana",
- extensions: ["tmo"]
- },
- "application/vnd.tri.onesource": {
- source: "iana"
- },
- "application/vnd.trid.tpt": {
- source: "iana",
- extensions: ["tpt"]
- },
- "application/vnd.triscape.mxs": {
- source: "iana",
- extensions: ["mxs"]
- },
- "application/vnd.trueapp": {
- source: "iana",
- extensions: ["tra"]
- },
- "application/vnd.truedoc": {
- source: "iana"
- },
- "application/vnd.ubisoft.webplayer": {
- source: "iana"
- },
- "application/vnd.ufdl": {
- source: "iana",
- extensions: ["ufd", "ufdl"]
- },
- "application/vnd.uiq.theme": {
- source: "iana",
- extensions: ["utz"]
- },
- "application/vnd.umajin": {
- source: "iana",
- extensions: ["umj"]
- },
- "application/vnd.unity": {
- source: "iana",
- extensions: ["unityweb"]
- },
- "application/vnd.uoml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["uoml"]
- },
- "application/vnd.uplanet.alert": {
- source: "iana"
- },
- "application/vnd.uplanet.alert-wbxml": {
- source: "iana"
- },
- "application/vnd.uplanet.bearer-choice": {
- source: "iana"
- },
- "application/vnd.uplanet.bearer-choice-wbxml": {
- source: "iana"
- },
- "application/vnd.uplanet.cacheop": {
- source: "iana"
- },
- "application/vnd.uplanet.cacheop-wbxml": {
- source: "iana"
- },
- "application/vnd.uplanet.channel": {
- source: "iana"
- },
- "application/vnd.uplanet.channel-wbxml": {
- source: "iana"
- },
- "application/vnd.uplanet.list": {
- source: "iana"
- },
- "application/vnd.uplanet.list-wbxml": {
- source: "iana"
- },
- "application/vnd.uplanet.listcmd": {
- source: "iana"
- },
- "application/vnd.uplanet.listcmd-wbxml": {
- source: "iana"
- },
- "application/vnd.uplanet.signal": {
- source: "iana"
- },
- "application/vnd.uri-map": {
- source: "iana"
- },
- "application/vnd.valve.source.material": {
- source: "iana"
- },
- "application/vnd.vcx": {
- source: "iana",
- extensions: ["vcx"]
- },
- "application/vnd.vd-study": {
- source: "iana"
- },
- "application/vnd.vectorworks": {
- source: "iana"
- },
- "application/vnd.vel+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.verimatrix.vcas": {
- source: "iana"
- },
- "application/vnd.veritone.aion+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.veryant.thin": {
- source: "iana"
- },
- "application/vnd.ves.encrypted": {
- source: "iana"
- },
- "application/vnd.vidsoft.vidconference": {
- source: "iana"
- },
- "application/vnd.visio": {
- source: "iana",
- extensions: ["vsd", "vst", "vss", "vsw"]
- },
- "application/vnd.visionary": {
- source: "iana",
- extensions: ["vis"]
- },
- "application/vnd.vividence.scriptfile": {
- source: "iana"
- },
- "application/vnd.vsf": {
- source: "iana",
- extensions: ["vsf"]
- },
- "application/vnd.wap.sic": {
- source: "iana"
- },
- "application/vnd.wap.slc": {
- source: "iana"
- },
- "application/vnd.wap.wbxml": {
- source: "iana",
- charset: "UTF-8",
- extensions: ["wbxml"]
- },
- "application/vnd.wap.wmlc": {
- source: "iana",
- extensions: ["wmlc"]
- },
- "application/vnd.wap.wmlscriptc": {
- source: "iana",
- extensions: ["wmlsc"]
- },
- "application/vnd.webturbo": {
- source: "iana",
- extensions: ["wtb"]
- },
- "application/vnd.wfa.dpp": {
- source: "iana"
- },
- "application/vnd.wfa.p2p": {
- source: "iana"
- },
- "application/vnd.wfa.wsc": {
- source: "iana"
- },
- "application/vnd.windows.devicepairing": {
- source: "iana"
- },
- "application/vnd.wmc": {
- source: "iana"
- },
- "application/vnd.wmf.bootstrap": {
- source: "iana"
- },
- "application/vnd.wolfram.mathematica": {
- source: "iana"
- },
- "application/vnd.wolfram.mathematica.package": {
- source: "iana"
- },
- "application/vnd.wolfram.player": {
- source: "iana",
- extensions: ["nbp"]
- },
- "application/vnd.wordperfect": {
- source: "iana",
- extensions: ["wpd"]
- },
- "application/vnd.wqd": {
- source: "iana",
- extensions: ["wqd"]
- },
- "application/vnd.wrq-hp3000-labelled": {
- source: "iana"
- },
- "application/vnd.wt.stf": {
- source: "iana",
- extensions: ["stf"]
- },
- "application/vnd.wv.csp+wbxml": {
- source: "iana"
- },
- "application/vnd.wv.csp+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.wv.ssp+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.xacml+json": {
- source: "iana",
- compressible: true
- },
- "application/vnd.xara": {
- source: "iana",
- extensions: ["xar"]
- },
- "application/vnd.xfdl": {
- source: "iana",
- extensions: ["xfdl"]
- },
- "application/vnd.xfdl.webform": {
- source: "iana"
- },
- "application/vnd.xmi+xml": {
- source: "iana",
- compressible: true
- },
- "application/vnd.xmpie.cpkg": {
- source: "iana"
- },
- "application/vnd.xmpie.dpkg": {
- source: "iana"
- },
- "application/vnd.xmpie.plan": {
- source: "iana"
- },
- "application/vnd.xmpie.ppkg": {
- source: "iana"
- },
- "application/vnd.xmpie.xlim": {
- source: "iana"
- },
- "application/vnd.yamaha.hv-dic": {
- source: "iana",
- extensions: ["hvd"]
- },
- "application/vnd.yamaha.hv-script": {
- source: "iana",
- extensions: ["hvs"]
- },
- "application/vnd.yamaha.hv-voice": {
- source: "iana",
- extensions: ["hvp"]
- },
- "application/vnd.yamaha.openscoreformat": {
- source: "iana",
- extensions: ["osf"]
- },
- "application/vnd.yamaha.openscoreformat.osfpvg+xml": {
- source: "iana",
- compressible: true,
- extensions: ["osfpvg"]
- },
- "application/vnd.yamaha.remote-setup": {
- source: "iana"
- },
- "application/vnd.yamaha.smaf-audio": {
- source: "iana",
- extensions: ["saf"]
- },
- "application/vnd.yamaha.smaf-phrase": {
- source: "iana",
- extensions: ["spf"]
- },
- "application/vnd.yamaha.through-ngn": {
- source: "iana"
- },
- "application/vnd.yamaha.tunnel-udpencap": {
- source: "iana"
- },
- "application/vnd.yaoweme": {
- source: "iana"
- },
- "application/vnd.yellowriver-custom-menu": {
- source: "iana",
- extensions: ["cmp"]
- },
- "application/vnd.youtube.yt": {
- source: "iana"
- },
- "application/vnd.zul": {
- source: "iana",
- extensions: ["zir", "zirz"]
- },
- "application/vnd.zzazz.deck+xml": {
- source: "iana",
- compressible: true,
- extensions: ["zaz"]
- },
- "application/voicexml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["vxml"]
- },
- "application/voucher-cms+json": {
- source: "iana",
- compressible: true
- },
- "application/vq-rtcpxr": {
- source: "iana"
- },
- "application/wasm": {
- source: "iana",
- compressible: true,
- extensions: ["wasm"]
- },
- "application/watcherinfo+xml": {
- source: "iana",
- compressible: true,
- extensions: ["wif"]
- },
- "application/webpush-options+json": {
- source: "iana",
- compressible: true
- },
- "application/whoispp-query": {
- source: "iana"
- },
- "application/whoispp-response": {
- source: "iana"
- },
- "application/widget": {
- source: "iana",
- extensions: ["wgt"]
- },
- "application/winhlp": {
- source: "apache",
- extensions: ["hlp"]
- },
- "application/wita": {
- source: "iana"
- },
- "application/wordperfect5.1": {
- source: "iana"
- },
- "application/wsdl+xml": {
- source: "iana",
- compressible: true,
- extensions: ["wsdl"]
- },
- "application/wspolicy+xml": {
- source: "iana",
- compressible: true,
- extensions: ["wspolicy"]
- },
- "application/x-7z-compressed": {
- source: "apache",
- compressible: false,
- extensions: ["7z"]
- },
- "application/x-abiword": {
- source: "apache",
- extensions: ["abw"]
- },
- "application/x-ace-compressed": {
- source: "apache",
- extensions: ["ace"]
- },
- "application/x-amf": {
- source: "apache"
- },
- "application/x-apple-diskimage": {
- source: "apache",
- extensions: ["dmg"]
- },
- "application/x-arj": {
- compressible: false,
- extensions: ["arj"]
- },
- "application/x-authorware-bin": {
- source: "apache",
- extensions: ["aab", "x32", "u32", "vox"]
- },
- "application/x-authorware-map": {
- source: "apache",
- extensions: ["aam"]
- },
- "application/x-authorware-seg": {
- source: "apache",
- extensions: ["aas"]
- },
- "application/x-bcpio": {
- source: "apache",
- extensions: ["bcpio"]
- },
- "application/x-bdoc": {
- compressible: false,
- extensions: ["bdoc"]
- },
- "application/x-bittorrent": {
- source: "apache",
- extensions: ["torrent"]
- },
- "application/x-blorb": {
- source: "apache",
- extensions: ["blb", "blorb"]
- },
- "application/x-bzip": {
- source: "apache",
- compressible: false,
- extensions: ["bz"]
- },
- "application/x-bzip2": {
- source: "apache",
- compressible: false,
- extensions: ["bz2", "boz"]
- },
- "application/x-cbr": {
- source: "apache",
- extensions: ["cbr", "cba", "cbt", "cbz", "cb7"]
- },
- "application/x-cdlink": {
- source: "apache",
- extensions: ["vcd"]
- },
- "application/x-cfs-compressed": {
- source: "apache",
- extensions: ["cfs"]
- },
- "application/x-chat": {
- source: "apache",
- extensions: ["chat"]
- },
- "application/x-chess-pgn": {
- source: "apache",
- extensions: ["pgn"]
- },
- "application/x-chrome-extension": {
- extensions: ["crx"]
- },
- "application/x-cocoa": {
- source: "nginx",
- extensions: ["cco"]
- },
- "application/x-compress": {
- source: "apache"
- },
- "application/x-conference": {
- source: "apache",
- extensions: ["nsc"]
- },
- "application/x-cpio": {
- source: "apache",
- extensions: ["cpio"]
- },
- "application/x-csh": {
- source: "apache",
- extensions: ["csh"]
- },
- "application/x-deb": {
- compressible: false
- },
- "application/x-debian-package": {
- source: "apache",
- extensions: ["deb", "udeb"]
- },
- "application/x-dgc-compressed": {
- source: "apache",
- extensions: ["dgc"]
- },
- "application/x-director": {
- source: "apache",
- extensions: ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"]
- },
- "application/x-doom": {
- source: "apache",
- extensions: ["wad"]
- },
- "application/x-dtbncx+xml": {
- source: "apache",
- compressible: true,
- extensions: ["ncx"]
- },
- "application/x-dtbook+xml": {
- source: "apache",
- compressible: true,
- extensions: ["dtb"]
- },
- "application/x-dtbresource+xml": {
- source: "apache",
- compressible: true,
- extensions: ["res"]
- },
- "application/x-dvi": {
- source: "apache",
- compressible: false,
- extensions: ["dvi"]
- },
- "application/x-envoy": {
- source: "apache",
- extensions: ["evy"]
- },
- "application/x-eva": {
- source: "apache",
- extensions: ["eva"]
- },
- "application/x-font-bdf": {
- source: "apache",
- extensions: ["bdf"]
- },
- "application/x-font-dos": {
- source: "apache"
- },
- "application/x-font-framemaker": {
- source: "apache"
- },
- "application/x-font-ghostscript": {
- source: "apache",
- extensions: ["gsf"]
- },
- "application/x-font-libgrx": {
- source: "apache"
- },
- "application/x-font-linux-psf": {
- source: "apache",
- extensions: ["psf"]
- },
- "application/x-font-pcf": {
- source: "apache",
- extensions: ["pcf"]
- },
- "application/x-font-snf": {
- source: "apache",
- extensions: ["snf"]
- },
- "application/x-font-speedo": {
- source: "apache"
- },
- "application/x-font-sunos-news": {
- source: "apache"
- },
- "application/x-font-type1": {
- source: "apache",
- extensions: ["pfa", "pfb", "pfm", "afm"]
- },
- "application/x-font-vfont": {
- source: "apache"
- },
- "application/x-freearc": {
- source: "apache",
- extensions: ["arc"]
- },
- "application/x-futuresplash": {
- source: "apache",
- extensions: ["spl"]
- },
- "application/x-gca-compressed": {
- source: "apache",
- extensions: ["gca"]
- },
- "application/x-glulx": {
- source: "apache",
- extensions: ["ulx"]
- },
- "application/x-gnumeric": {
- source: "apache",
- extensions: ["gnumeric"]
- },
- "application/x-gramps-xml": {
- source: "apache",
- extensions: ["gramps"]
- },
- "application/x-gtar": {
- source: "apache",
- extensions: ["gtar"]
- },
- "application/x-gzip": {
- source: "apache"
- },
- "application/x-hdf": {
- source: "apache",
- extensions: ["hdf"]
- },
- "application/x-httpd-php": {
- compressible: true,
- extensions: ["php"]
- },
- "application/x-install-instructions": {
- source: "apache",
- extensions: ["install"]
- },
- "application/x-iso9660-image": {
- source: "apache",
- extensions: ["iso"]
- },
- "application/x-iwork-keynote-sffkey": {
- extensions: ["key"]
- },
- "application/x-iwork-numbers-sffnumbers": {
- extensions: ["numbers"]
- },
- "application/x-iwork-pages-sffpages": {
- extensions: ["pages"]
- },
- "application/x-java-archive-diff": {
- source: "nginx",
- extensions: ["jardiff"]
- },
- "application/x-java-jnlp-file": {
- source: "apache",
- compressible: false,
- extensions: ["jnlp"]
- },
- "application/x-javascript": {
- compressible: true
- },
- "application/x-keepass2": {
- extensions: ["kdbx"]
- },
- "application/x-latex": {
- source: "apache",
- compressible: false,
- extensions: ["latex"]
- },
- "application/x-lua-bytecode": {
- extensions: ["luac"]
- },
- "application/x-lzh-compressed": {
- source: "apache",
- extensions: ["lzh", "lha"]
- },
- "application/x-makeself": {
- source: "nginx",
- extensions: ["run"]
- },
- "application/x-mie": {
- source: "apache",
- extensions: ["mie"]
- },
- "application/x-mobipocket-ebook": {
- source: "apache",
- extensions: ["prc", "mobi"]
- },
- "application/x-mpegurl": {
- compressible: false
- },
- "application/x-ms-application": {
- source: "apache",
- extensions: ["application"]
- },
- "application/x-ms-shortcut": {
- source: "apache",
- extensions: ["lnk"]
- },
- "application/x-ms-wmd": {
- source: "apache",
- extensions: ["wmd"]
- },
- "application/x-ms-wmz": {
- source: "apache",
- extensions: ["wmz"]
- },
- "application/x-ms-xbap": {
- source: "apache",
- extensions: ["xbap"]
- },
- "application/x-msaccess": {
- source: "apache",
- extensions: ["mdb"]
- },
- "application/x-msbinder": {
- source: "apache",
- extensions: ["obd"]
- },
- "application/x-mscardfile": {
- source: "apache",
- extensions: ["crd"]
- },
- "application/x-msclip": {
- source: "apache",
- extensions: ["clp"]
- },
- "application/x-msdos-program": {
- extensions: ["exe"]
- },
- "application/x-msdownload": {
- source: "apache",
- extensions: ["exe", "dll", "com", "bat", "msi"]
- },
- "application/x-msmediaview": {
- source: "apache",
- extensions: ["mvb", "m13", "m14"]
- },
- "application/x-msmetafile": {
- source: "apache",
- extensions: ["wmf", "wmz", "emf", "emz"]
- },
- "application/x-msmoney": {
- source: "apache",
- extensions: ["mny"]
- },
- "application/x-mspublisher": {
- source: "apache",
- extensions: ["pub"]
- },
- "application/x-msschedule": {
- source: "apache",
- extensions: ["scd"]
- },
- "application/x-msterminal": {
- source: "apache",
- extensions: ["trm"]
- },
- "application/x-mswrite": {
- source: "apache",
- extensions: ["wri"]
- },
- "application/x-netcdf": {
- source: "apache",
- extensions: ["nc", "cdf"]
- },
- "application/x-ns-proxy-autoconfig": {
- compressible: true,
- extensions: ["pac"]
- },
- "application/x-nzb": {
- source: "apache",
- extensions: ["nzb"]
- },
- "application/x-perl": {
- source: "nginx",
- extensions: ["pl", "pm"]
- },
- "application/x-pilot": {
- source: "nginx",
- extensions: ["prc", "pdb"]
- },
- "application/x-pkcs12": {
- source: "apache",
- compressible: false,
- extensions: ["p12", "pfx"]
- },
- "application/x-pkcs7-certificates": {
- source: "apache",
- extensions: ["p7b", "spc"]
- },
- "application/x-pkcs7-certreqresp": {
- source: "apache",
- extensions: ["p7r"]
- },
- "application/x-pki-message": {
- source: "iana"
- },
- "application/x-rar-compressed": {
- source: "apache",
- compressible: false,
- extensions: ["rar"]
- },
- "application/x-redhat-package-manager": {
- source: "nginx",
- extensions: ["rpm"]
- },
- "application/x-research-info-systems": {
- source: "apache",
- extensions: ["ris"]
- },
- "application/x-sea": {
- source: "nginx",
- extensions: ["sea"]
- },
- "application/x-sh": {
- source: "apache",
- compressible: true,
- extensions: ["sh"]
- },
- "application/x-shar": {
- source: "apache",
- extensions: ["shar"]
- },
- "application/x-shockwave-flash": {
- source: "apache",
- compressible: false,
- extensions: ["swf"]
- },
- "application/x-silverlight-app": {
- source: "apache",
- extensions: ["xap"]
- },
- "application/x-sql": {
- source: "apache",
- extensions: ["sql"]
- },
- "application/x-stuffit": {
- source: "apache",
- compressible: false,
- extensions: ["sit"]
- },
- "application/x-stuffitx": {
- source: "apache",
- extensions: ["sitx"]
- },
- "application/x-subrip": {
- source: "apache",
- extensions: ["srt"]
- },
- "application/x-sv4cpio": {
- source: "apache",
- extensions: ["sv4cpio"]
- },
- "application/x-sv4crc": {
- source: "apache",
- extensions: ["sv4crc"]
- },
- "application/x-t3vm-image": {
- source: "apache",
- extensions: ["t3"]
- },
- "application/x-tads": {
- source: "apache",
- extensions: ["gam"]
- },
- "application/x-tar": {
- source: "apache",
- compressible: true,
- extensions: ["tar"]
- },
- "application/x-tcl": {
- source: "apache",
- extensions: ["tcl", "tk"]
- },
- "application/x-tex": {
- source: "apache",
- extensions: ["tex"]
- },
- "application/x-tex-tfm": {
- source: "apache",
- extensions: ["tfm"]
- },
- "application/x-texinfo": {
- source: "apache",
- extensions: ["texinfo", "texi"]
- },
- "application/x-tgif": {
- source: "apache",
- extensions: ["obj"]
- },
- "application/x-ustar": {
- source: "apache",
- extensions: ["ustar"]
- },
- "application/x-virtualbox-hdd": {
- compressible: true,
- extensions: ["hdd"]
- },
- "application/x-virtualbox-ova": {
- compressible: true,
- extensions: ["ova"]
- },
- "application/x-virtualbox-ovf": {
- compressible: true,
- extensions: ["ovf"]
- },
- "application/x-virtualbox-vbox": {
- compressible: true,
- extensions: ["vbox"]
- },
- "application/x-virtualbox-vbox-extpack": {
- compressible: false,
- extensions: ["vbox-extpack"]
- },
- "application/x-virtualbox-vdi": {
- compressible: true,
- extensions: ["vdi"]
- },
- "application/x-virtualbox-vhd": {
- compressible: true,
- extensions: ["vhd"]
- },
- "application/x-virtualbox-vmdk": {
- compressible: true,
- extensions: ["vmdk"]
- },
- "application/x-wais-source": {
- source: "apache",
- extensions: ["src"]
- },
- "application/x-web-app-manifest+json": {
- compressible: true,
- extensions: ["webapp"]
- },
- "application/x-www-form-urlencoded": {
- source: "iana",
- compressible: true
- },
- "application/x-x509-ca-cert": {
- source: "iana",
- extensions: ["der", "crt", "pem"]
- },
- "application/x-x509-ca-ra-cert": {
- source: "iana"
- },
- "application/x-x509-next-ca-cert": {
- source: "iana"
- },
- "application/x-xfig": {
- source: "apache",
- extensions: ["fig"]
- },
- "application/x-xliff+xml": {
- source: "apache",
- compressible: true,
- extensions: ["xlf"]
- },
- "application/x-xpinstall": {
- source: "apache",
- compressible: false,
- extensions: ["xpi"]
- },
- "application/x-xz": {
- source: "apache",
- extensions: ["xz"]
- },
- "application/x-zmachine": {
- source: "apache",
- extensions: ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"]
- },
- "application/x400-bp": {
- source: "iana"
- },
- "application/xacml+xml": {
- source: "iana",
- compressible: true
- },
- "application/xaml+xml": {
- source: "apache",
- compressible: true,
- extensions: ["xaml"]
- },
- "application/xcap-att+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xav"]
- },
- "application/xcap-caps+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xca"]
- },
- "application/xcap-diff+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xdf"]
- },
- "application/xcap-el+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xel"]
- },
- "application/xcap-error+xml": {
- source: "iana",
- compressible: true
- },
- "application/xcap-ns+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xns"]
- },
- "application/xcon-conference-info+xml": {
- source: "iana",
- compressible: true
- },
- "application/xcon-conference-info-diff+xml": {
- source: "iana",
- compressible: true
- },
- "application/xenc+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xenc"]
- },
- "application/xhtml+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xhtml", "xht"]
- },
- "application/xhtml-voice+xml": {
- source: "apache",
- compressible: true
- },
- "application/xliff+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xlf"]
- },
- "application/xml": {
- source: "iana",
- compressible: true,
- extensions: ["xml", "xsl", "xsd", "rng"]
- },
- "application/xml-dtd": {
- source: "iana",
- compressible: true,
- extensions: ["dtd"]
- },
- "application/xml-external-parsed-entity": {
- source: "iana"
- },
- "application/xml-patch+xml": {
- source: "iana",
- compressible: true
- },
- "application/xmpp+xml": {
- source: "iana",
- compressible: true
- },
- "application/xop+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xop"]
- },
- "application/xproc+xml": {
- source: "apache",
- compressible: true,
- extensions: ["xpl"]
- },
- "application/xslt+xml": {
- source: "iana",
- compressible: true,
- extensions: ["xsl", "xslt"]
- },
- "application/xspf+xml": {
- source: "apache",
- compressible: true,
- extensions: ["xspf"]
- },
- "application/xv+xml": {
- source: "iana",
- compressible: true,
- extensions: ["mxml", "xhvml", "xvml", "xvm"]
- },
- "application/yang": {
- source: "iana",
- extensions: ["yang"]
- },
- "application/yang-data+json": {
- source: "iana",
- compressible: true
- },
- "application/yang-data+xml": {
- source: "iana",
- compressible: true
- },
- "application/yang-patch+json": {
- source: "iana",
- compressible: true
- },
- "application/yang-patch+xml": {
- source: "iana",
- compressible: true
- },
- "application/yin+xml": {
- source: "iana",
- compressible: true,
- extensions: ["yin"]
- },
- "application/zip": {
- source: "iana",
- compressible: false,
- extensions: ["zip"]
- },
- "application/zlib": {
- source: "iana"
- },
- "application/zstd": {
- source: "iana"
- },
- "audio/1d-interleaved-parityfec": {
- source: "iana"
- },
- "audio/32kadpcm": {
- source: "iana"
- },
- "audio/3gpp": {
- source: "iana",
- compressible: false,
- extensions: ["3gpp"]
- },
- "audio/3gpp2": {
- source: "iana"
- },
- "audio/aac": {
- source: "iana"
- },
- "audio/ac3": {
- source: "iana"
- },
- "audio/adpcm": {
- source: "apache",
- extensions: ["adp"]
- },
- "audio/amr": {
- source: "iana",
- extensions: ["amr"]
- },
- "audio/amr-wb": {
- source: "iana"
- },
- "audio/amr-wb+": {
- source: "iana"
- },
- "audio/aptx": {
- source: "iana"
- },
- "audio/asc": {
- source: "iana"
- },
- "audio/atrac-advanced-lossless": {
- source: "iana"
- },
- "audio/atrac-x": {
- source: "iana"
- },
- "audio/atrac3": {
- source: "iana"
- },
- "audio/basic": {
- source: "iana",
- compressible: false,
- extensions: ["au", "snd"]
- },
- "audio/bv16": {
- source: "iana"
- },
- "audio/bv32": {
- source: "iana"
- },
- "audio/clearmode": {
- source: "iana"
- },
- "audio/cn": {
- source: "iana"
- },
- "audio/dat12": {
- source: "iana"
- },
- "audio/dls": {
- source: "iana"
- },
- "audio/dsr-es201108": {
- source: "iana"
- },
- "audio/dsr-es202050": {
- source: "iana"
- },
- "audio/dsr-es202211": {
- source: "iana"
- },
- "audio/dsr-es202212": {
- source: "iana"
- },
- "audio/dv": {
- source: "iana"
- },
- "audio/dvi4": {
- source: "iana"
- },
- "audio/eac3": {
- source: "iana"
- },
- "audio/encaprtp": {
- source: "iana"
- },
- "audio/evrc": {
- source: "iana"
- },
- "audio/evrc-qcp": {
- source: "iana"
- },
- "audio/evrc0": {
- source: "iana"
- },
- "audio/evrc1": {
- source: "iana"
- },
- "audio/evrcb": {
- source: "iana"
- },
- "audio/evrcb0": {
- source: "iana"
- },
- "audio/evrcb1": {
- source: "iana"
- },
- "audio/evrcnw": {
- source: "iana"
- },
- "audio/evrcnw0": {
- source: "iana"
- },
- "audio/evrcnw1": {
- source: "iana"
- },
- "audio/evrcwb": {
- source: "iana"
- },
- "audio/evrcwb0": {
- source: "iana"
- },
- "audio/evrcwb1": {
- source: "iana"
- },
- "audio/evs": {
- source: "iana"
- },
- "audio/flexfec": {
- source: "iana"
- },
- "audio/fwdred": {
- source: "iana"
- },
- "audio/g711-0": {
- source: "iana"
- },
- "audio/g719": {
- source: "iana"
- },
- "audio/g722": {
- source: "iana"
- },
- "audio/g7221": {
- source: "iana"
- },
- "audio/g723": {
- source: "iana"
- },
- "audio/g726-16": {
- source: "iana"
- },
- "audio/g726-24": {
- source: "iana"
- },
- "audio/g726-32": {
- source: "iana"
- },
- "audio/g726-40": {
- source: "iana"
- },
- "audio/g728": {
- source: "iana"
- },
- "audio/g729": {
- source: "iana"
- },
- "audio/g7291": {
- source: "iana"
- },
- "audio/g729d": {
- source: "iana"
- },
- "audio/g729e": {
- source: "iana"
- },
- "audio/gsm": {
- source: "iana"
- },
- "audio/gsm-efr": {
- source: "iana"
- },
- "audio/gsm-hr-08": {
- source: "iana"
- },
- "audio/ilbc": {
- source: "iana"
- },
- "audio/ip-mr_v2.5": {
- source: "iana"
- },
- "audio/isac": {
- source: "apache"
- },
- "audio/l16": {
- source: "iana"
- },
- "audio/l20": {
- source: "iana"
- },
- "audio/l24": {
- source: "iana",
- compressible: false
- },
- "audio/l8": {
- source: "iana"
- },
- "audio/lpc": {
- source: "iana"
- },
- "audio/melp": {
- source: "iana"
- },
- "audio/melp1200": {
- source: "iana"
- },
- "audio/melp2400": {
- source: "iana"
- },
- "audio/melp600": {
- source: "iana"
- },
- "audio/mhas": {
- source: "iana"
- },
- "audio/midi": {
- source: "apache",
- extensions: ["mid", "midi", "kar", "rmi"]
- },
- "audio/mobile-xmf": {
- source: "iana",
- extensions: ["mxmf"]
- },
- "audio/mp3": {
- compressible: false,
- extensions: ["mp3"]
- },
- "audio/mp4": {
- source: "iana",
- compressible: false,
- extensions: ["m4a", "mp4a"]
- },
- "audio/mp4a-latm": {
- source: "iana"
- },
- "audio/mpa": {
- source: "iana"
- },
- "audio/mpa-robust": {
- source: "iana"
- },
- "audio/mpeg": {
- source: "iana",
- compressible: false,
- extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"]
- },
- "audio/mpeg4-generic": {
- source: "iana"
- },
- "audio/musepack": {
- source: "apache"
- },
- "audio/ogg": {
- source: "iana",
- compressible: false,
- extensions: ["oga", "ogg", "spx", "opus"]
- },
- "audio/opus": {
- source: "iana"
- },
- "audio/parityfec": {
- source: "iana"
- },
- "audio/pcma": {
- source: "iana"
- },
- "audio/pcma-wb": {
- source: "iana"
- },
- "audio/pcmu": {
- source: "iana"
- },
- "audio/pcmu-wb": {
- source: "iana"
- },
- "audio/prs.sid": {
- source: "iana"
- },
- "audio/qcelp": {
- source: "iana"
- },
- "audio/raptorfec": {
- source: "iana"
- },
- "audio/red": {
- source: "iana"
- },
- "audio/rtp-enc-aescm128": {
- source: "iana"
- },
- "audio/rtp-midi": {
- source: "iana"
- },
- "audio/rtploopback": {
- source: "iana"
- },
- "audio/rtx": {
- source: "iana"
- },
- "audio/s3m": {
- source: "apache",
- extensions: ["s3m"]
- },
- "audio/scip": {
- source: "iana"
- },
- "audio/silk": {
- source: "apache",
- extensions: ["sil"]
- },
- "audio/smv": {
- source: "iana"
- },
- "audio/smv-qcp": {
- source: "iana"
- },
- "audio/smv0": {
- source: "iana"
- },
- "audio/sofa": {
- source: "iana"
- },
- "audio/sp-midi": {
- source: "iana"
- },
- "audio/speex": {
- source: "iana"
- },
- "audio/t140c": {
- source: "iana"
- },
- "audio/t38": {
- source: "iana"
- },
- "audio/telephone-event": {
- source: "iana"
- },
- "audio/tetra_acelp": {
- source: "iana"
- },
- "audio/tetra_acelp_bb": {
- source: "iana"
- },
- "audio/tone": {
- source: "iana"
- },
- "audio/tsvcis": {
- source: "iana"
- },
- "audio/uemclip": {
- source: "iana"
- },
- "audio/ulpfec": {
- source: "iana"
- },
- "audio/usac": {
- source: "iana"
- },
- "audio/vdvi": {
- source: "iana"
- },
- "audio/vmr-wb": {
- source: "iana"
- },
- "audio/vnd.3gpp.iufp": {
- source: "iana"
- },
- "audio/vnd.4sb": {
- source: "iana"
- },
- "audio/vnd.audiokoz": {
- source: "iana"
- },
- "audio/vnd.celp": {
- source: "iana"
- },
- "audio/vnd.cisco.nse": {
- source: "iana"
- },
- "audio/vnd.cmles.radio-events": {
- source: "iana"
- },
- "audio/vnd.cns.anp1": {
- source: "iana"
- },
- "audio/vnd.cns.inf1": {
- source: "iana"
- },
- "audio/vnd.dece.audio": {
- source: "iana",
- extensions: ["uva", "uvva"]
- },
- "audio/vnd.digital-winds": {
- source: "iana",
- extensions: ["eol"]
- },
- "audio/vnd.dlna.adts": {
- source: "iana"
- },
- "audio/vnd.dolby.heaac.1": {
- source: "iana"
- },
- "audio/vnd.dolby.heaac.2": {
- source: "iana"
- },
- "audio/vnd.dolby.mlp": {
- source: "iana"
- },
- "audio/vnd.dolby.mps": {
- source: "iana"
- },
- "audio/vnd.dolby.pl2": {
- source: "iana"
- },
- "audio/vnd.dolby.pl2x": {
- source: "iana"
- },
- "audio/vnd.dolby.pl2z": {
- source: "iana"
- },
- "audio/vnd.dolby.pulse.1": {
- source: "iana"
- },
- "audio/vnd.dra": {
- source: "iana",
- extensions: ["dra"]
- },
- "audio/vnd.dts": {
- source: "iana",
- extensions: ["dts"]
- },
- "audio/vnd.dts.hd": {
- source: "iana",
- extensions: ["dtshd"]
- },
- "audio/vnd.dts.uhd": {
- source: "iana"
- },
- "audio/vnd.dvb.file": {
- source: "iana"
- },
- "audio/vnd.everad.plj": {
- source: "iana"
- },
- "audio/vnd.hns.audio": {
- source: "iana"
- },
- "audio/vnd.lucent.voice": {
- source: "iana",
- extensions: ["lvp"]
- },
- "audio/vnd.ms-playready.media.pya": {
- source: "iana",
- extensions: ["pya"]
- },
- "audio/vnd.nokia.mobile-xmf": {
- source: "iana"
- },
- "audio/vnd.nortel.vbk": {
- source: "iana"
- },
- "audio/vnd.nuera.ecelp4800": {
- source: "iana",
- extensions: ["ecelp4800"]
- },
- "audio/vnd.nuera.ecelp7470": {
- source: "iana",
- extensions: ["ecelp7470"]
- },
- "audio/vnd.nuera.ecelp9600": {
- source: "iana",
- extensions: ["ecelp9600"]
- },
- "audio/vnd.octel.sbc": {
- source: "iana"
- },
- "audio/vnd.presonus.multitrack": {
- source: "iana"
- },
- "audio/vnd.qcelp": {
- source: "iana"
- },
- "audio/vnd.rhetorex.32kadpcm": {
- source: "iana"
- },
- "audio/vnd.rip": {
- source: "iana",
- extensions: ["rip"]
- },
- "audio/vnd.rn-realaudio": {
- compressible: false
- },
- "audio/vnd.sealedmedia.softseal.mpeg": {
- source: "iana"
- },
- "audio/vnd.vmx.cvsd": {
- source: "iana"
- },
- "audio/vnd.wave": {
- compressible: false
- },
- "audio/vorbis": {
- source: "iana",
- compressible: false
- },
- "audio/vorbis-config": {
- source: "iana"
- },
- "audio/wav": {
- compressible: false,
- extensions: ["wav"]
- },
- "audio/wave": {
- compressible: false,
- extensions: ["wav"]
- },
- "audio/webm": {
- source: "apache",
- compressible: false,
- extensions: ["weba"]
- },
- "audio/x-aac": {
- source: "apache",
- compressible: false,
- extensions: ["aac"]
- },
- "audio/x-aiff": {
- source: "apache",
- extensions: ["aif", "aiff", "aifc"]
- },
- "audio/x-caf": {
- source: "apache",
- compressible: false,
- extensions: ["caf"]
- },
- "audio/x-flac": {
- source: "apache",
- extensions: ["flac"]
- },
- "audio/x-m4a": {
- source: "nginx",
- extensions: ["m4a"]
- },
- "audio/x-matroska": {
- source: "apache",
- extensions: ["mka"]
- },
- "audio/x-mpegurl": {
- source: "apache",
- extensions: ["m3u"]
- },
- "audio/x-ms-wax": {
- source: "apache",
- extensions: ["wax"]
- },
- "audio/x-ms-wma": {
- source: "apache",
- extensions: ["wma"]
- },
- "audio/x-pn-realaudio": {
- source: "apache",
- extensions: ["ram", "ra"]
- },
- "audio/x-pn-realaudio-plugin": {
- source: "apache",
- extensions: ["rmp"]
- },
- "audio/x-realaudio": {
- source: "nginx",
- extensions: ["ra"]
- },
- "audio/x-tta": {
- source: "apache"
- },
- "audio/x-wav": {
- source: "apache",
- extensions: ["wav"]
- },
- "audio/xm": {
- source: "apache",
- extensions: ["xm"]
- },
- "chemical/x-cdx": {
- source: "apache",
- extensions: ["cdx"]
- },
- "chemical/x-cif": {
- source: "apache",
- extensions: ["cif"]
- },
- "chemical/x-cmdf": {
- source: "apache",
- extensions: ["cmdf"]
- },
- "chemical/x-cml": {
- source: "apache",
- extensions: ["cml"]
- },
- "chemical/x-csml": {
- source: "apache",
- extensions: ["csml"]
- },
- "chemical/x-pdb": {
- source: "apache"
- },
- "chemical/x-xyz": {
- source: "apache",
- extensions: ["xyz"]
- },
- "font/collection": {
- source: "iana",
- extensions: ["ttc"]
- },
- "font/otf": {
- source: "iana",
- compressible: true,
- extensions: ["otf"]
- },
- "font/sfnt": {
- source: "iana"
- },
- "font/ttf": {
- source: "iana",
- compressible: true,
- extensions: ["ttf"]
- },
- "font/woff": {
- source: "iana",
- extensions: ["woff"]
- },
- "font/woff2": {
- source: "iana",
- extensions: ["woff2"]
- },
- "image/aces": {
- source: "iana",
- extensions: ["exr"]
- },
- "image/apng": {
- compressible: false,
- extensions: ["apng"]
- },
- "image/avci": {
- source: "iana",
- extensions: ["avci"]
- },
- "image/avcs": {
- source: "iana",
- extensions: ["avcs"]
- },
- "image/avif": {
- source: "iana",
- compressible: false,
- extensions: ["avif"]
- },
- "image/bmp": {
- source: "iana",
- compressible: true,
- extensions: ["bmp"]
- },
- "image/cgm": {
- source: "iana",
- extensions: ["cgm"]
- },
- "image/dicom-rle": {
- source: "iana",
- extensions: ["drle"]
- },
- "image/emf": {
- source: "iana",
- extensions: ["emf"]
- },
- "image/fits": {
- source: "iana",
- extensions: ["fits"]
- },
- "image/g3fax": {
- source: "iana",
- extensions: ["g3"]
- },
- "image/gif": {
- source: "iana",
- compressible: false,
- extensions: ["gif"]
- },
- "image/heic": {
- source: "iana",
- extensions: ["heic"]
- },
- "image/heic-sequence": {
- source: "iana",
- extensions: ["heics"]
- },
- "image/heif": {
- source: "iana",
- extensions: ["heif"]
- },
- "image/heif-sequence": {
- source: "iana",
- extensions: ["heifs"]
- },
- "image/hej2k": {
- source: "iana",
- extensions: ["hej2"]
- },
- "image/hsj2": {
- source: "iana",
- extensions: ["hsj2"]
- },
- "image/ief": {
- source: "iana",
- extensions: ["ief"]
- },
- "image/jls": {
- source: "iana",
- extensions: ["jls"]
- },
- "image/jp2": {
- source: "iana",
- compressible: false,
- extensions: ["jp2", "jpg2"]
- },
- "image/jpeg": {
- source: "iana",
- compressible: false,
- extensions: ["jpeg", "jpg", "jpe"]
- },
- "image/jph": {
- source: "iana",
- extensions: ["jph"]
- },
- "image/jphc": {
- source: "iana",
- extensions: ["jhc"]
- },
- "image/jpm": {
- source: "iana",
- compressible: false,
- extensions: ["jpm"]
- },
- "image/jpx": {
- source: "iana",
- compressible: false,
- extensions: ["jpx", "jpf"]
- },
- "image/jxr": {
- source: "iana",
- extensions: ["jxr"]
- },
- "image/jxra": {
- source: "iana",
- extensions: ["jxra"]
- },
- "image/jxrs": {
- source: "iana",
- extensions: ["jxrs"]
- },
- "image/jxs": {
- source: "iana",
- extensions: ["jxs"]
- },
- "image/jxsc": {
- source: "iana",
- extensions: ["jxsc"]
- },
- "image/jxsi": {
- source: "iana",
- extensions: ["jxsi"]
- },
- "image/jxss": {
- source: "iana",
- extensions: ["jxss"]
- },
- "image/ktx": {
- source: "iana",
- extensions: ["ktx"]
- },
- "image/ktx2": {
- source: "iana",
- extensions: ["ktx2"]
- },
- "image/naplps": {
- source: "iana"
- },
- "image/pjpeg": {
- compressible: false
- },
- "image/png": {
- source: "iana",
- compressible: false,
- extensions: ["png"]
- },
- "image/prs.btif": {
- source: "iana",
- extensions: ["btif"]
- },
- "image/prs.pti": {
- source: "iana",
- extensions: ["pti"]
- },
- "image/pwg-raster": {
- source: "iana"
- },
- "image/sgi": {
- source: "apache",
- extensions: ["sgi"]
- },
- "image/svg+xml": {
- source: "iana",
- compressible: true,
- extensions: ["svg", "svgz"]
- },
- "image/t38": {
- source: "iana",
- extensions: ["t38"]
- },
- "image/tiff": {
- source: "iana",
- compressible: false,
- extensions: ["tif", "tiff"]
- },
- "image/tiff-fx": {
- source: "iana",
- extensions: ["tfx"]
- },
- "image/vnd.adobe.photoshop": {
- source: "iana",
- compressible: true,
- extensions: ["psd"]
- },
- "image/vnd.airzip.accelerator.azv": {
- source: "iana",
- extensions: ["azv"]
- },
- "image/vnd.cns.inf2": {
- source: "iana"
- },
- "image/vnd.dece.graphic": {
- source: "iana",
- extensions: ["uvi", "uvvi", "uvg", "uvvg"]
- },
- "image/vnd.djvu": {
- source: "iana",
- extensions: ["djvu", "djv"]
- },
- "image/vnd.dvb.subtitle": {
- source: "iana",
- extensions: ["sub"]
- },
- "image/vnd.dwg": {
- source: "iana",
- extensions: ["dwg"]
- },
- "image/vnd.dxf": {
- source: "iana",
- extensions: ["dxf"]
- },
- "image/vnd.fastbidsheet": {
- source: "iana",
- extensions: ["fbs"]
- },
- "image/vnd.fpx": {
- source: "iana",
- extensions: ["fpx"]
- },
- "image/vnd.fst": {
- source: "iana",
- extensions: ["fst"]
- },
- "image/vnd.fujixerox.edmics-mmr": {
- source: "iana",
- extensions: ["mmr"]
- },
- "image/vnd.fujixerox.edmics-rlc": {
- source: "iana",
- extensions: ["rlc"]
- },
- "image/vnd.globalgraphics.pgb": {
- source: "iana"
- },
- "image/vnd.microsoft.icon": {
- source: "iana",
- compressible: true,
- extensions: ["ico"]
- },
- "image/vnd.mix": {
- source: "iana"
- },
- "image/vnd.mozilla.apng": {
- source: "iana"
- },
- "image/vnd.ms-dds": {
- compressible: true,
- extensions: ["dds"]
- },
- "image/vnd.ms-modi": {
- source: "iana",
- extensions: ["mdi"]
- },
- "image/vnd.ms-photo": {
- source: "apache",
- extensions: ["wdp"]
- },
- "image/vnd.net-fpx": {
- source: "iana",
- extensions: ["npx"]
- },
- "image/vnd.pco.b16": {
- source: "iana",
- extensions: ["b16"]
- },
- "image/vnd.radiance": {
- source: "iana"
- },
- "image/vnd.sealed.png": {
- source: "iana"
- },
- "image/vnd.sealedmedia.softseal.gif": {
- source: "iana"
- },
- "image/vnd.sealedmedia.softseal.jpg": {
- source: "iana"
- },
- "image/vnd.svf": {
- source: "iana"
- },
- "image/vnd.tencent.tap": {
- source: "iana",
- extensions: ["tap"]
- },
- "image/vnd.valve.source.texture": {
- source: "iana",
- extensions: ["vtf"]
- },
- "image/vnd.wap.wbmp": {
- source: "iana",
- extensions: ["wbmp"]
- },
- "image/vnd.xiff": {
- source: "iana",
- extensions: ["xif"]
- },
- "image/vnd.zbrush.pcx": {
- source: "iana",
- extensions: ["pcx"]
- },
- "image/webp": {
- source: "apache",
- extensions: ["webp"]
- },
- "image/wmf": {
- source: "iana",
- extensions: ["wmf"]
- },
- "image/x-3ds": {
- source: "apache",
- extensions: ["3ds"]
- },
- "image/x-cmu-raster": {
- source: "apache",
- extensions: ["ras"]
- },
- "image/x-cmx": {
- source: "apache",
- extensions: ["cmx"]
- },
- "image/x-freehand": {
- source: "apache",
- extensions: ["fh", "fhc", "fh4", "fh5", "fh7"]
- },
- "image/x-icon": {
- source: "apache",
- compressible: true,
- extensions: ["ico"]
- },
- "image/x-jng": {
- source: "nginx",
- extensions: ["jng"]
- },
- "image/x-mrsid-image": {
- source: "apache",
- extensions: ["sid"]
- },
- "image/x-ms-bmp": {
- source: "nginx",
- compressible: true,
- extensions: ["bmp"]
- },
- "image/x-pcx": {
- source: "apache",
- extensions: ["pcx"]
- },
- "image/x-pict": {
- source: "apache",
- extensions: ["pic", "pct"]
- },
- "image/x-portable-anymap": {
- source: "apache",
- extensions: ["pnm"]
- },
- "image/x-portable-bitmap": {
- source: "apache",
- extensions: ["pbm"]
- },
- "image/x-portable-graymap": {
- source: "apache",
- extensions: ["pgm"]
- },
- "image/x-portable-pixmap": {
- source: "apache",
- extensions: ["ppm"]
- },
- "image/x-rgb": {
- source: "apache",
- extensions: ["rgb"]
- },
- "image/x-tga": {
- source: "apache",
- extensions: ["tga"]
- },
- "image/x-xbitmap": {
- source: "apache",
- extensions: ["xbm"]
- },
- "image/x-xcf": {
- compressible: false
- },
- "image/x-xpixmap": {
- source: "apache",
- extensions: ["xpm"]
- },
- "image/x-xwindowdump": {
- source: "apache",
- extensions: ["xwd"]
- },
- "message/cpim": {
- source: "iana"
- },
- "message/delivery-status": {
- source: "iana"
- },
- "message/disposition-notification": {
- source: "iana",
- extensions: [
- "disposition-notification"
- ]
- },
- "message/external-body": {
- source: "iana"
- },
- "message/feedback-report": {
- source: "iana"
- },
- "message/global": {
- source: "iana",
- extensions: ["u8msg"]
- },
- "message/global-delivery-status": {
- source: "iana",
- extensions: ["u8dsn"]
- },
- "message/global-disposition-notification": {
- source: "iana",
- extensions: ["u8mdn"]
- },
- "message/global-headers": {
- source: "iana",
- extensions: ["u8hdr"]
- },
- "message/http": {
- source: "iana",
- compressible: false
- },
- "message/imdn+xml": {
- source: "iana",
- compressible: true
- },
- "message/news": {
- source: "iana"
- },
- "message/partial": {
- source: "iana",
- compressible: false
- },
- "message/rfc822": {
- source: "iana",
- compressible: true,
- extensions: ["eml", "mime"]
- },
- "message/s-http": {
- source: "iana"
- },
- "message/sip": {
- source: "iana"
- },
- "message/sipfrag": {
- source: "iana"
- },
- "message/tracking-status": {
- source: "iana"
- },
- "message/vnd.si.simp": {
- source: "iana"
- },
- "message/vnd.wfa.wsc": {
- source: "iana",
- extensions: ["wsc"]
- },
- "model/3mf": {
- source: "iana",
- extensions: ["3mf"]
- },
- "model/e57": {
- source: "iana"
- },
- "model/gltf+json": {
- source: "iana",
- compressible: true,
- extensions: ["gltf"]
- },
- "model/gltf-binary": {
- source: "iana",
- compressible: true,
- extensions: ["glb"]
- },
- "model/iges": {
- source: "iana",
- compressible: false,
- extensions: ["igs", "iges"]
- },
- "model/mesh": {
- source: "iana",
- compressible: false,
- extensions: ["msh", "mesh", "silo"]
- },
- "model/mtl": {
- source: "iana",
- extensions: ["mtl"]
- },
- "model/obj": {
- source: "iana",
- extensions: ["obj"]
- },
- "model/step": {
- source: "iana"
- },
- "model/step+xml": {
- source: "iana",
- compressible: true,
- extensions: ["stpx"]
- },
- "model/step+zip": {
- source: "iana",
- compressible: false,
- extensions: ["stpz"]
- },
- "model/step-xml+zip": {
- source: "iana",
- compressible: false,
- extensions: ["stpxz"]
- },
- "model/stl": {
- source: "iana",
- extensions: ["stl"]
- },
- "model/vnd.collada+xml": {
- source: "iana",
- compressible: true,
- extensions: ["dae"]
- },
- "model/vnd.dwf": {
- source: "iana",
- extensions: ["dwf"]
- },
- "model/vnd.flatland.3dml": {
- source: "iana"
- },
- "model/vnd.gdl": {
- source: "iana",
- extensions: ["gdl"]
- },
- "model/vnd.gs-gdl": {
- source: "apache"
- },
- "model/vnd.gs.gdl": {
- source: "iana"
- },
- "model/vnd.gtw": {
- source: "iana",
- extensions: ["gtw"]
- },
- "model/vnd.moml+xml": {
- source: "iana",
- compressible: true
- },
- "model/vnd.mts": {
- source: "iana",
- extensions: ["mts"]
- },
- "model/vnd.opengex": {
- source: "iana",
- extensions: ["ogex"]
- },
- "model/vnd.parasolid.transmit.binary": {
- source: "iana",
- extensions: ["x_b"]
- },
- "model/vnd.parasolid.transmit.text": {
- source: "iana",
- extensions: ["x_t"]
- },
- "model/vnd.pytha.pyox": {
- source: "iana"
- },
- "model/vnd.rosette.annotated-data-model": {
- source: "iana"
- },
- "model/vnd.sap.vds": {
- source: "iana",
- extensions: ["vds"]
- },
- "model/vnd.usdz+zip": {
- source: "iana",
- compressible: false,
- extensions: ["usdz"]
- },
- "model/vnd.valve.source.compiled-map": {
- source: "iana",
- extensions: ["bsp"]
- },
- "model/vnd.vtu": {
- source: "iana",
- extensions: ["vtu"]
- },
- "model/vrml": {
- source: "iana",
- compressible: false,
- extensions: ["wrl", "vrml"]
- },
- "model/x3d+binary": {
- source: "apache",
- compressible: false,
- extensions: ["x3db", "x3dbz"]
- },
- "model/x3d+fastinfoset": {
- source: "iana",
- extensions: ["x3db"]
- },
- "model/x3d+vrml": {
- source: "apache",
- compressible: false,
- extensions: ["x3dv", "x3dvz"]
- },
- "model/x3d+xml": {
- source: "iana",
- compressible: true,
- extensions: ["x3d", "x3dz"]
- },
- "model/x3d-vrml": {
- source: "iana",
- extensions: ["x3dv"]
- },
- "multipart/alternative": {
- source: "iana",
- compressible: false
- },
- "multipart/appledouble": {
- source: "iana"
- },
- "multipart/byteranges": {
- source: "iana"
- },
- "multipart/digest": {
- source: "iana"
- },
- "multipart/encrypted": {
- source: "iana",
- compressible: false
- },
- "multipart/form-data": {
- source: "iana",
- compressible: false
- },
- "multipart/header-set": {
- source: "iana"
- },
- "multipart/mixed": {
- source: "iana"
- },
- "multipart/multilingual": {
- source: "iana"
- },
- "multipart/parallel": {
- source: "iana"
- },
- "multipart/related": {
- source: "iana",
- compressible: false
- },
- "multipart/report": {
- source: "iana"
- },
- "multipart/signed": {
- source: "iana",
- compressible: false
- },
- "multipart/vnd.bint.med-plus": {
- source: "iana"
- },
- "multipart/voice-message": {
- source: "iana"
- },
- "multipart/x-mixed-replace": {
- source: "iana"
- },
- "text/1d-interleaved-parityfec": {
- source: "iana"
- },
- "text/cache-manifest": {
- source: "iana",
- compressible: true,
- extensions: ["appcache", "manifest"]
- },
- "text/calendar": {
- source: "iana",
- extensions: ["ics", "ifb"]
- },
- "text/calender": {
- compressible: true
- },
- "text/cmd": {
- compressible: true
- },
- "text/coffeescript": {
- extensions: ["coffee", "litcoffee"]
- },
- "text/cql": {
- source: "iana"
- },
- "text/cql-expression": {
- source: "iana"
- },
- "text/cql-identifier": {
- source: "iana"
- },
- "text/css": {
- source: "iana",
- charset: "UTF-8",
- compressible: true,
- extensions: ["css"]
- },
- "text/csv": {
- source: "iana",
- compressible: true,
- extensions: ["csv"]
- },
- "text/csv-schema": {
- source: "iana"
- },
- "text/directory": {
- source: "iana"
- },
- "text/dns": {
- source: "iana"
- },
- "text/ecmascript": {
- source: "iana"
- },
- "text/encaprtp": {
- source: "iana"
- },
- "text/enriched": {
- source: "iana"
- },
- "text/fhirpath": {
- source: "iana"
- },
- "text/flexfec": {
- source: "iana"
- },
- "text/fwdred": {
- source: "iana"
- },
- "text/gff3": {
- source: "iana"
- },
- "text/grammar-ref-list": {
- source: "iana"
- },
- "text/html": {
- source: "iana",
- compressible: true,
- extensions: ["html", "htm", "shtml"]
- },
- "text/jade": {
- extensions: ["jade"]
- },
- "text/javascript": {
- source: "iana",
- compressible: true
- },
- "text/jcr-cnd": {
- source: "iana"
- },
- "text/jsx": {
- compressible: true,
- extensions: ["jsx"]
- },
- "text/less": {
- compressible: true,
- extensions: ["less"]
- },
- "text/markdown": {
- source: "iana",
- compressible: true,
- extensions: ["markdown", "md"]
- },
- "text/mathml": {
- source: "nginx",
- extensions: ["mml"]
- },
- "text/mdx": {
- compressible: true,
- extensions: ["mdx"]
- },
- "text/mizar": {
- source: "iana"
- },
- "text/n3": {
- source: "iana",
- charset: "UTF-8",
- compressible: true,
- extensions: ["n3"]
- },
- "text/parameters": {
- source: "iana",
- charset: "UTF-8"
- },
- "text/parityfec": {
- source: "iana"
- },
- "text/plain": {
- source: "iana",
- compressible: true,
- extensions: ["txt", "text", "conf", "def", "list", "log", "in", "ini"]
- },
- "text/provenance-notation": {
- source: "iana",
- charset: "UTF-8"
- },
- "text/prs.fallenstein.rst": {
- source: "iana"
- },
- "text/prs.lines.tag": {
- source: "iana",
- extensions: ["dsc"]
- },
- "text/prs.prop.logic": {
- source: "iana"
- },
- "text/raptorfec": {
- source: "iana"
- },
- "text/red": {
- source: "iana"
- },
- "text/rfc822-headers": {
- source: "iana"
- },
- "text/richtext": {
- source: "iana",
- compressible: true,
- extensions: ["rtx"]
- },
- "text/rtf": {
- source: "iana",
- compressible: true,
- extensions: ["rtf"]
- },
- "text/rtp-enc-aescm128": {
- source: "iana"
- },
- "text/rtploopback": {
- source: "iana"
- },
- "text/rtx": {
- source: "iana"
- },
- "text/sgml": {
- source: "iana",
- extensions: ["sgml", "sgm"]
- },
- "text/shaclc": {
- source: "iana"
- },
- "text/shex": {
- source: "iana",
- extensions: ["shex"]
- },
- "text/slim": {
- extensions: ["slim", "slm"]
- },
- "text/spdx": {
- source: "iana",
- extensions: ["spdx"]
- },
- "text/strings": {
- source: "iana"
- },
- "text/stylus": {
- extensions: ["stylus", "styl"]
- },
- "text/t140": {
- source: "iana"
- },
- "text/tab-separated-values": {
- source: "iana",
- compressible: true,
- extensions: ["tsv"]
- },
- "text/troff": {
- source: "iana",
- extensions: ["t", "tr", "roff", "man", "me", "ms"]
- },
- "text/turtle": {
- source: "iana",
- charset: "UTF-8",
- extensions: ["ttl"]
- },
- "text/ulpfec": {
- source: "iana"
- },
- "text/uri-list": {
- source: "iana",
- compressible: true,
- extensions: ["uri", "uris", "urls"]
- },
- "text/vcard": {
- source: "iana",
- compressible: true,
- extensions: ["vcard"]
- },
- "text/vnd.a": {
- source: "iana"
- },
- "text/vnd.abc": {
- source: "iana"
- },
- "text/vnd.ascii-art": {
- source: "iana"
- },
- "text/vnd.curl": {
- source: "iana",
- extensions: ["curl"]
- },
- "text/vnd.curl.dcurl": {
- source: "apache",
- extensions: ["dcurl"]
- },
- "text/vnd.curl.mcurl": {
- source: "apache",
- extensions: ["mcurl"]
- },
- "text/vnd.curl.scurl": {
- source: "apache",
- extensions: ["scurl"]
- },
- "text/vnd.debian.copyright": {
- source: "iana",
- charset: "UTF-8"
- },
- "text/vnd.dmclientscript": {
- source: "iana"
- },
- "text/vnd.dvb.subtitle": {
- source: "iana",
- extensions: ["sub"]
- },
- "text/vnd.esmertec.theme-descriptor": {
- source: "iana",
- charset: "UTF-8"
- },
- "text/vnd.familysearch.gedcom": {
- source: "iana",
- extensions: ["ged"]
- },
- "text/vnd.ficlab.flt": {
- source: "iana"
- },
- "text/vnd.fly": {
- source: "iana",
- extensions: ["fly"]
- },
- "text/vnd.fmi.flexstor": {
- source: "iana",
- extensions: ["flx"]
- },
- "text/vnd.gml": {
- source: "iana"
- },
- "text/vnd.graphviz": {
- source: "iana",
- extensions: ["gv"]
- },
- "text/vnd.hans": {
- source: "iana"
- },
- "text/vnd.hgl": {
- source: "iana"
- },
- "text/vnd.in3d.3dml": {
- source: "iana",
- extensions: ["3dml"]
- },
- "text/vnd.in3d.spot": {
- source: "iana",
- extensions: ["spot"]
- },
- "text/vnd.iptc.newsml": {
- source: "iana"
- },
- "text/vnd.iptc.nitf": {
- source: "iana"
- },
- "text/vnd.latex-z": {
- source: "iana"
- },
- "text/vnd.motorola.reflex": {
- source: "iana"
- },
- "text/vnd.ms-mediapackage": {
- source: "iana"
- },
- "text/vnd.net2phone.commcenter.command": {
- source: "iana"
- },
- "text/vnd.radisys.msml-basic-layout": {
- source: "iana"
- },
- "text/vnd.senx.warpscript": {
- source: "iana"
- },
- "text/vnd.si.uricatalogue": {
- source: "iana"
- },
- "text/vnd.sosi": {
- source: "iana"
- },
- "text/vnd.sun.j2me.app-descriptor": {
- source: "iana",
- charset: "UTF-8",
- extensions: ["jad"]
- },
- "text/vnd.trolltech.linguist": {
- source: "iana",
- charset: "UTF-8"
- },
- "text/vnd.wap.si": {
- source: "iana"
- },
- "text/vnd.wap.sl": {
- source: "iana"
- },
- "text/vnd.wap.wml": {
- source: "iana",
- extensions: ["wml"]
- },
- "text/vnd.wap.wmlscript": {
- source: "iana",
- extensions: ["wmls"]
- },
- "text/vtt": {
- source: "iana",
- charset: "UTF-8",
- compressible: true,
- extensions: ["vtt"]
- },
- "text/x-asm": {
- source: "apache",
- extensions: ["s", "asm"]
- },
- "text/x-c": {
- source: "apache",
- extensions: ["c", "cc", "cxx", "cpp", "h", "hh", "dic"]
- },
- "text/x-component": {
- source: "nginx",
- extensions: ["htc"]
- },
- "text/x-fortran": {
- source: "apache",
- extensions: ["f", "for", "f77", "f90"]
- },
- "text/x-gwt-rpc": {
- compressible: true
- },
- "text/x-handlebars-template": {
- extensions: ["hbs"]
- },
- "text/x-java-source": {
- source: "apache",
- extensions: ["java"]
- },
- "text/x-jquery-tmpl": {
- compressible: true
- },
- "text/x-lua": {
- extensions: ["lua"]
- },
- "text/x-markdown": {
- compressible: true,
- extensions: ["mkd"]
- },
- "text/x-nfo": {
- source: "apache",
- extensions: ["nfo"]
- },
- "text/x-opml": {
- source: "apache",
- extensions: ["opml"]
- },
- "text/x-org": {
- compressible: true,
- extensions: ["org"]
- },
- "text/x-pascal": {
- source: "apache",
- extensions: ["p", "pas"]
- },
- "text/x-processing": {
- compressible: true,
- extensions: ["pde"]
- },
- "text/x-sass": {
- extensions: ["sass"]
- },
- "text/x-scss": {
- extensions: ["scss"]
- },
- "text/x-setext": {
- source: "apache",
- extensions: ["etx"]
- },
- "text/x-sfv": {
- source: "apache",
- extensions: ["sfv"]
- },
- "text/x-suse-ymp": {
- compressible: true,
- extensions: ["ymp"]
- },
- "text/x-uuencode": {
- source: "apache",
- extensions: ["uu"]
- },
- "text/x-vcalendar": {
- source: "apache",
- extensions: ["vcs"]
- },
- "text/x-vcard": {
- source: "apache",
- extensions: ["vcf"]
- },
- "text/xml": {
- source: "iana",
- compressible: true,
- extensions: ["xml"]
- },
- "text/xml-external-parsed-entity": {
- source: "iana"
- },
- "text/yaml": {
- compressible: true,
- extensions: ["yaml", "yml"]
- },
- "video/1d-interleaved-parityfec": {
- source: "iana"
- },
- "video/3gpp": {
- source: "iana",
- extensions: ["3gp", "3gpp"]
- },
- "video/3gpp-tt": {
- source: "iana"
- },
- "video/3gpp2": {
- source: "iana",
- extensions: ["3g2"]
- },
- "video/av1": {
- source: "iana"
- },
- "video/bmpeg": {
- source: "iana"
- },
- "video/bt656": {
- source: "iana"
- },
- "video/celb": {
- source: "iana"
- },
- "video/dv": {
- source: "iana"
- },
- "video/encaprtp": {
- source: "iana"
- },
- "video/ffv1": {
- source: "iana"
- },
- "video/flexfec": {
- source: "iana"
- },
- "video/h261": {
- source: "iana",
- extensions: ["h261"]
- },
- "video/h263": {
- source: "iana",
- extensions: ["h263"]
- },
- "video/h263-1998": {
- source: "iana"
- },
- "video/h263-2000": {
- source: "iana"
- },
- "video/h264": {
- source: "iana",
- extensions: ["h264"]
- },
- "video/h264-rcdo": {
- source: "iana"
- },
- "video/h264-svc": {
- source: "iana"
- },
- "video/h265": {
- source: "iana"
- },
- "video/iso.segment": {
- source: "iana",
- extensions: ["m4s"]
- },
- "video/jpeg": {
- source: "iana",
- extensions: ["jpgv"]
- },
- "video/jpeg2000": {
- source: "iana"
- },
- "video/jpm": {
- source: "apache",
- extensions: ["jpm", "jpgm"]
- },
- "video/jxsv": {
- source: "iana"
- },
- "video/mj2": {
- source: "iana",
- extensions: ["mj2", "mjp2"]
- },
- "video/mp1s": {
- source: "iana"
- },
- "video/mp2p": {
- source: "iana"
- },
- "video/mp2t": {
- source: "iana",
- extensions: ["ts"]
- },
- "video/mp4": {
- source: "iana",
- compressible: false,
- extensions: ["mp4", "mp4v", "mpg4"]
- },
- "video/mp4v-es": {
- source: "iana"
- },
- "video/mpeg": {
- source: "iana",
- compressible: false,
- extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"]
- },
- "video/mpeg4-generic": {
- source: "iana"
- },
- "video/mpv": {
- source: "iana"
- },
- "video/nv": {
- source: "iana"
- },
- "video/ogg": {
- source: "iana",
- compressible: false,
- extensions: ["ogv"]
- },
- "video/parityfec": {
- source: "iana"
- },
- "video/pointer": {
- source: "iana"
- },
- "video/quicktime": {
- source: "iana",
- compressible: false,
- extensions: ["qt", "mov"]
- },
- "video/raptorfec": {
- source: "iana"
- },
- "video/raw": {
- source: "iana"
- },
- "video/rtp-enc-aescm128": {
- source: "iana"
- },
- "video/rtploopback": {
- source: "iana"
- },
- "video/rtx": {
- source: "iana"
- },
- "video/scip": {
- source: "iana"
- },
- "video/smpte291": {
- source: "iana"
- },
- "video/smpte292m": {
- source: "iana"
- },
- "video/ulpfec": {
- source: "iana"
- },
- "video/vc1": {
- source: "iana"
- },
- "video/vc2": {
- source: "iana"
- },
- "video/vnd.cctv": {
- source: "iana"
- },
- "video/vnd.dece.hd": {
- source: "iana",
- extensions: ["uvh", "uvvh"]
- },
- "video/vnd.dece.mobile": {
- source: "iana",
- extensions: ["uvm", "uvvm"]
- },
- "video/vnd.dece.mp4": {
- source: "iana"
- },
- "video/vnd.dece.pd": {
- source: "iana",
- extensions: ["uvp", "uvvp"]
- },
- "video/vnd.dece.sd": {
- source: "iana",
- extensions: ["uvs", "uvvs"]
- },
- "video/vnd.dece.video": {
- source: "iana",
- extensions: ["uvv", "uvvv"]
- },
- "video/vnd.directv.mpeg": {
- source: "iana"
- },
- "video/vnd.directv.mpeg-tts": {
- source: "iana"
- },
- "video/vnd.dlna.mpeg-tts": {
- source: "iana"
- },
- "video/vnd.dvb.file": {
- source: "iana",
- extensions: ["dvb"]
- },
- "video/vnd.fvt": {
- source: "iana",
- extensions: ["fvt"]
- },
- "video/vnd.hns.video": {
- source: "iana"
- },
- "video/vnd.iptvforum.1dparityfec-1010": {
- source: "iana"
- },
- "video/vnd.iptvforum.1dparityfec-2005": {
- source: "iana"
- },
- "video/vnd.iptvforum.2dparityfec-1010": {
- source: "iana"
- },
- "video/vnd.iptvforum.2dparityfec-2005": {
- source: "iana"
- },
- "video/vnd.iptvforum.ttsavc": {
- source: "iana"
- },
- "video/vnd.iptvforum.ttsmpeg2": {
- source: "iana"
- },
- "video/vnd.motorola.video": {
- source: "iana"
- },
- "video/vnd.motorola.videop": {
- source: "iana"
- },
- "video/vnd.mpegurl": {
- source: "iana",
- extensions: ["mxu", "m4u"]
- },
- "video/vnd.ms-playready.media.pyv": {
- source: "iana",
- extensions: ["pyv"]
- },
- "video/vnd.nokia.interleaved-multimedia": {
- source: "iana"
- },
- "video/vnd.nokia.mp4vr": {
- source: "iana"
- },
- "video/vnd.nokia.videovoip": {
- source: "iana"
- },
- "video/vnd.objectvideo": {
- source: "iana"
- },
- "video/vnd.radgamettools.bink": {
- source: "iana"
- },
- "video/vnd.radgamettools.smacker": {
- source: "iana"
- },
- "video/vnd.sealed.mpeg1": {
- source: "iana"
- },
- "video/vnd.sealed.mpeg4": {
- source: "iana"
- },
- "video/vnd.sealed.swf": {
- source: "iana"
- },
- "video/vnd.sealedmedia.softseal.mov": {
- source: "iana"
- },
- "video/vnd.uvvu.mp4": {
- source: "iana",
- extensions: ["uvu", "uvvu"]
- },
- "video/vnd.vivo": {
- source: "iana",
- extensions: ["viv"]
- },
- "video/vnd.youtube.yt": {
- source: "iana"
- },
- "video/vp8": {
- source: "iana"
- },
- "video/vp9": {
- source: "iana"
- },
- "video/webm": {
- source: "apache",
- compressible: false,
- extensions: ["webm"]
- },
- "video/x-f4v": {
- source: "apache",
- extensions: ["f4v"]
- },
- "video/x-fli": {
- source: "apache",
- extensions: ["fli"]
- },
- "video/x-flv": {
- source: "apache",
- compressible: false,
- extensions: ["flv"]
- },
- "video/x-m4v": {
- source: "apache",
- extensions: ["m4v"]
- },
- "video/x-matroska": {
- source: "apache",
- compressible: false,
- extensions: ["mkv", "mk3d", "mks"]
- },
- "video/x-mng": {
- source: "apache",
- extensions: ["mng"]
- },
- "video/x-ms-asf": {
- source: "apache",
- extensions: ["asf", "asx"]
- },
- "video/x-ms-vob": {
- source: "apache",
- extensions: ["vob"]
- },
- "video/x-ms-wm": {
- source: "apache",
- extensions: ["wm"]
- },
- "video/x-ms-wmv": {
- source: "apache",
- compressible: false,
- extensions: ["wmv"]
- },
- "video/x-ms-wmx": {
- source: "apache",
- extensions: ["wmx"]
- },
- "video/x-ms-wvx": {
- source: "apache",
- extensions: ["wvx"]
- },
- "video/x-msvideo": {
- source: "apache",
- extensions: ["avi"]
- },
- "video/x-sgi-movie": {
- source: "apache",
- extensions: ["movie"]
- },
- "video/x-smv": {
- source: "apache",
- extensions: ["smv"]
- },
- "x-conference/x-cooltalk": {
- source: "apache",
- extensions: ["ice"]
- },
- "x-shader/x-fragment": {
- compressible: true
- },
- "x-shader/x-vertex": {
- compressible: true
- }
- };
-});
-
-// node_modules/form-data/node_modules/mime-types/index.js
-var require_mime_types = __commonJS((exports) => {
- /*!
- * mime-types
- * Copyright(c) 2014 Jonathan Ong
- * Copyright(c) 2015 Douglas Christopher Wilson
- * MIT Licensed
- */
- var db = require_db();
- var extname = __require("path").extname;
- var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/;
- var TEXT_TYPE_REGEXP = /^text\//i;
- 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);
- populateMaps(exports.extensions, exports.types);
- function charset(type) {
- if (!type || typeof type !== "string") {
- return false;
- }
- var match = EXTRACT_TYPE_REGEXP.exec(type);
- var mime = match && db[match[1].toLowerCase()];
- if (mime && mime.charset) {
- return mime.charset;
- }
- if (match && TEXT_TYPE_REGEXP.test(match[1])) {
- return "UTF-8";
- }
- return false;
- }
- function contentType(str) {
- if (!str || typeof str !== "string") {
- return false;
- }
- var mime = str.indexOf("/") === -1 ? exports.lookup(str) : str;
- if (!mime) {
- return false;
- }
- if (mime.indexOf("charset") === -1) {
- var charset2 = exports.charset(mime);
- if (charset2)
- mime += "; charset=" + charset2.toLowerCase();
- }
- return mime;
- }
- function extension(type) {
- if (!type || typeof type !== "string") {
- return false;
- }
- var match = EXTRACT_TYPE_REGEXP.exec(type);
- var exts = match && exports.extensions[match[1].toLowerCase()];
- if (!exts || !exts.length) {
- return false;
- }
- return exts[0];
- }
- function lookup(path6) {
- if (!path6 || typeof path6 !== "string") {
- return false;
- }
- var extension2 = extname("x." + path6).toLowerCase().substr(1);
- if (!extension2) {
- return false;
- }
- return exports.types[extension2] || false;
- }
- function populateMaps(extensions, types) {
- 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;
- }
- extensions[type] = exts;
- for (var i2 = 0;i2 < exts.length; i2++) {
- var extension2 = exts[i2];
- if (types[extension2]) {
- var from = preference.indexOf(db[types[extension2]].source);
- var to = preference.indexOf(mime.source);
- if (types[extension2] !== "application/octet-stream" && (from > to || from === to && types[extension2].substr(0, 12) === "application/")) {
- continue;
- }
- }
- types[extension2] = type;
- }
- });
- }
-});
-
-// node_modules/asynckit/lib/defer.js
-var require_defer = __commonJS((exports, module) => {
- module.exports = defer;
- function defer(fn) {
- var nextTick = typeof setImmediate == "function" ? setImmediate : typeof process == "object" && typeof process.nextTick == "function" ? process.nextTick : null;
- if (nextTick) {
- nextTick(fn);
- } else {
- setTimeout(fn, 0);
- }
- }
-});
-
-// node_modules/asynckit/lib/async.js
-var require_async = __commonJS((exports, module) => {
- var defer = require_defer();
- module.exports = async;
- function async(callback) {
- var isAsync = false;
- defer(function() {
- isAsync = true;
- });
- return function async_callback(err, result) {
- if (isAsync) {
- callback(err, result);
- } else {
- defer(function nextTick_callback() {
- callback(err, result);
- });
- }
- };
- }
-});
-
-// node_modules/asynckit/lib/abort.js
-var require_abort = __commonJS((exports, module) => {
- module.exports = abort;
- function abort(state) {
- Object.keys(state.jobs).forEach(clean.bind(state));
- state.jobs = {};
- }
- function clean(key) {
- if (typeof this.jobs[key] == "function") {
- this.jobs[key]();
- }
- }
-});
-
-// node_modules/asynckit/lib/iterate.js
-var require_iterate = __commonJS((exports, module) => {
- var async = require_async();
- var abort = require_abort();
- module.exports = iterate;
- function iterate(list2, iterator2, state, callback) {
- var key = state["keyedList"] ? state["keyedList"][state.index] : state.index;
- state.jobs[key] = runJob(iterator2, key, list2[key], function(error, output) {
- if (!(key in state.jobs)) {
- return;
- }
- delete state.jobs[key];
- if (error) {
- abort(state);
- } else {
- state.results[key] = output;
- }
- callback(error, state.results);
- });
- }
- function runJob(iterator2, key, item, callback) {
- var aborter;
- if (iterator2.length == 2) {
- aborter = iterator2(item, async(callback));
- } else {
- aborter = iterator2(item, key, async(callback));
- }
- return aborter;
- }
-});
-
-// node_modules/asynckit/lib/state.js
-var require_state = __commonJS((exports, module) => {
- module.exports = state;
- function state(list2, sortMethod) {
- var isNamedList = !Array.isArray(list2), initState = {
- index: 0,
- keyedList: isNamedList || sortMethod ? Object.keys(list2) : null,
- jobs: {},
- results: isNamedList ? {} : [],
- size: isNamedList ? Object.keys(list2).length : list2.length
- };
- if (sortMethod) {
- initState.keyedList.sort(isNamedList ? sortMethod : function(a2, b) {
- return sortMethod(list2[a2], list2[b]);
- });
- }
- return initState;
- }
-});
-
-// node_modules/asynckit/lib/terminator.js
-var require_terminator = __commonJS((exports, module) => {
- var abort = require_abort();
- var async = require_async();
- module.exports = terminator;
- function terminator(callback) {
- if (!Object.keys(this.jobs).length) {
- return;
- }
- this.index = this.size;
- abort(this);
- async(callback)(null, this.results);
- }
-});
-
-// node_modules/asynckit/parallel.js
-var require_parallel = __commonJS((exports, module) => {
- var iterate = require_iterate();
- var initState = require_state();
- var terminator = require_terminator();
- module.exports = parallel;
- function parallel(list2, iterator2, callback) {
- var state = initState(list2);
- while (state.index < (state["keyedList"] || list2).length) {
- iterate(list2, iterator2, state, function(error, result) {
- if (error) {
- callback(error, result);
- return;
- }
- if (Object.keys(state.jobs).length === 0) {
- callback(null, state.results);
- return;
- }
- });
- state.index++;
- }
- return terminator.bind(state, callback);
- }
-});
-
-// node_modules/asynckit/serialOrdered.js
-var require_serialOrdered = __commonJS((exports, module) => {
- var iterate = require_iterate();
- var initState = require_state();
- var terminator = require_terminator();
- module.exports = serialOrdered;
- module.exports.ascending = ascending;
- module.exports.descending = descending;
- function serialOrdered(list2, iterator2, sortMethod, callback) {
- var state = initState(list2, sortMethod);
- iterate(list2, iterator2, state, function iteratorHandler(error, result) {
- if (error) {
- callback(error, result);
- return;
- }
- state.index++;
- if (state.index < (state["keyedList"] || list2).length) {
- iterate(list2, iterator2, state, iteratorHandler);
- return;
- }
- callback(null, state.results);
- });
- return terminator.bind(state, callback);
- }
- function ascending(a2, b) {
- return a2 < b ? -1 : a2 > b ? 1 : 0;
- }
- function descending(a2, b) {
- return -1 * ascending(a2, b);
- }
-});
-
-// node_modules/asynckit/serial.js
-var require_serial = __commonJS((exports, module) => {
- var serialOrdered = require_serialOrdered();
- module.exports = serial;
- function serial(list2, iterator2, callback) {
- return serialOrdered(list2, iterator2, null, callback);
- }
-});
-
-// node_modules/asynckit/index.js
-var require_asynckit = __commonJS((exports, module) => {
- module.exports = {
- parallel: require_parallel(),
- serial: require_serial(),
- serialOrdered: require_serialOrdered()
- };
-});
-
-// node_modules/es-object-atoms/index.js
-var require_es_object_atoms = __commonJS((exports, module) => {
- module.exports = Object;
-});
-
-// node_modules/es-errors/index.js
-var require_es_errors = __commonJS((exports, module) => {
- module.exports = Error;
-});
-
-// node_modules/es-errors/eval.js
-var require_eval = __commonJS((exports, module) => {
- module.exports = EvalError;
-});
-
-// node_modules/es-errors/range.js
-var require_range = __commonJS((exports, module) => {
- module.exports = RangeError;
-});
-
-// node_modules/es-errors/ref.js
-var require_ref = __commonJS((exports, module) => {
- module.exports = ReferenceError;
-});
-
-// node_modules/es-errors/syntax.js
-var require_syntax = __commonJS((exports, module) => {
- module.exports = SyntaxError;
-});
-
-// node_modules/es-errors/type.js
-var require_type = __commonJS((exports, module) => {
- module.exports = TypeError;
-});
-
-// node_modules/es-errors/uri.js
-var require_uri = __commonJS((exports, module) => {
- module.exports = URIError;
-});
-
-// node_modules/math-intrinsics/abs.js
-var require_abs = __commonJS((exports, module) => {
- module.exports = Math.abs;
-});
-
-// node_modules/math-intrinsics/floor.js
-var require_floor = __commonJS((exports, module) => {
- module.exports = Math.floor;
-});
-
-// node_modules/math-intrinsics/max.js
-var require_max = __commonJS((exports, module) => {
- module.exports = Math.max;
-});
-
-// node_modules/math-intrinsics/min.js
-var require_min = __commonJS((exports, module) => {
- module.exports = Math.min;
-});
-
-// node_modules/math-intrinsics/pow.js
-var require_pow = __commonJS((exports, module) => {
- module.exports = Math.pow;
-});
-
-// node_modules/math-intrinsics/round.js
-var require_round = __commonJS((exports, module) => {
- module.exports = Math.round;
-});
-
-// node_modules/math-intrinsics/isNaN.js
-var require_isNaN = __commonJS((exports, module) => {
- module.exports = Number.isNaN || function isNaN2(a2) {
- return a2 !== a2;
- };
-});
-
-// node_modules/math-intrinsics/sign.js
-var require_sign = __commonJS((exports, module) => {
- var $isNaN = require_isNaN();
- module.exports = function sign(number) {
- if ($isNaN(number) || number === 0) {
- return number;
- }
- return number < 0 ? -1 : 1;
- };
-});
-
-// node_modules/gopd/gOPD.js
-var require_gOPD = __commonJS((exports, module) => {
- module.exports = Object.getOwnPropertyDescriptor;
-});
-
-// node_modules/gopd/index.js
-var require_gopd = __commonJS((exports, module) => {
- var $gOPD = require_gOPD();
- if ($gOPD) {
- try {
- $gOPD([], "length");
- } catch (e) {
- $gOPD = null;
- }
- }
- module.exports = $gOPD;
-});
-
-// node_modules/es-define-property/index.js
-var require_es_define_property = __commonJS((exports, module) => {
- var $defineProperty = Object.defineProperty || false;
- if ($defineProperty) {
- try {
- $defineProperty({}, "a", { value: 1 });
- } catch (e) {
- $defineProperty = false;
- }
- }
- module.exports = $defineProperty;
-});
-
-// node_modules/has-symbols/shams.js
-var require_shams = __commonJS((exports, module) => {
- module.exports = function hasSymbols() {
- if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") {
- return false;
- }
- if (typeof Symbol.iterator === "symbol") {
- return true;
- }
- 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;
- }
- var symVal = 42;
- obj[sym] = symVal;
- for (var _ in obj) {
- return false;
- }
- 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") {
- var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
- if (descriptor.value !== symVal || descriptor.enumerable !== true) {
- return false;
- }
- }
- return true;
- };
-});
-
-// node_modules/has-symbols/index.js
-var require_has_symbols = __commonJS((exports, module) => {
- var origSymbol = typeof Symbol !== "undefined" && Symbol;
- var hasSymbolSham = require_shams();
- 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();
- };
-});
-
-// node_modules/get-proto/Reflect.getPrototypeOf.js
-var require_Reflect_getPrototypeOf = __commonJS((exports, module) => {
- module.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null;
-});
-
-// node_modules/get-proto/Object.getPrototypeOf.js
-var require_Object_getPrototypeOf = __commonJS((exports, module) => {
- var $Object = require_es_object_atoms();
- module.exports = $Object.getPrototypeOf || null;
-});
-
-// node_modules/function-bind/implementation.js
-var require_implementation = __commonJS((exports, module) => {
- var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
- var toStr = Object.prototype.toString;
- var max = Math.max;
- var funcType = "[object Function]";
- var concatty = function concatty2(a2, b) {
- var arr = [];
- for (var i2 = 0;i2 < a2.length; i2 += 1) {
- arr[i2] = a2[i2];
- }
- for (var j = 0;j < b.length; j += 1) {
- arr[j + a2.length] = b[j];
- }
- return arr;
- };
- var slicy = function slicy2(arrLike, offset) {
- var arr = [];
- for (var i2 = offset || 0, j = 0;i2 < arrLike.length; i2 += 1, j += 1) {
- arr[j] = arrLike[i2];
- }
- return arr;
- };
- var joiny = function(arr, joiner) {
- var str = "";
- for (var i2 = 0;i2 < arr.length; i2 += 1) {
- str += arr[i2];
- if (i2 + 1 < arr.length) {
- str += joiner;
- }
- }
- return str;
- };
- module.exports = function bind2(that) {
- var target = this;
- if (typeof target !== "function" || toStr.apply(target) !== funcType) {
- throw new TypeError(ERROR_MESSAGE + target);
- }
- var args = slicy(arguments, 1);
- var bound;
- var binder = function() {
- if (this instanceof bound) {
- var result = target.apply(this, concatty(args, arguments));
- if (Object(result) === result) {
- return result;
- }
- return this;
- }
- return target.apply(that, concatty(args, arguments));
- };
- var boundLength = max(0, target.length - args.length);
- var boundArgs = [];
- for (var i2 = 0;i2 < boundLength; i2++) {
- boundArgs[i2] = "$" + i2;
- }
- bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
- if (target.prototype) {
- var Empty = function Empty2() {};
- Empty.prototype = target.prototype;
- bound.prototype = new Empty;
- Empty.prototype = null;
- }
- return bound;
- };
-});
-
-// node_modules/function-bind/index.js
-var require_function_bind = __commonJS((exports, module) => {
- var implementation = require_implementation();
- module.exports = Function.prototype.bind || implementation;
-});
-
-// node_modules/call-bind-apply-helpers/functionCall.js
-var require_functionCall = __commonJS((exports, module) => {
- module.exports = Function.prototype.call;
-});
-
-// node_modules/call-bind-apply-helpers/functionApply.js
-var require_functionApply = __commonJS((exports, module) => {
- module.exports = Function.prototype.apply;
-});
-
-// node_modules/call-bind-apply-helpers/reflectApply.js
-var require_reflectApply = __commonJS((exports, module) => {
- module.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
-});
-
-// node_modules/call-bind-apply-helpers/actualApply.js
-var require_actualApply = __commonJS((exports, module) => {
- var bind2 = require_function_bind();
- var $apply = require_functionApply();
- var $call = require_functionCall();
- var $reflectApply = require_reflectApply();
- module.exports = $reflectApply || bind2.call($call, $apply);
-});
-
-// node_modules/call-bind-apply-helpers/index.js
-var require_call_bind_apply_helpers = __commonJS((exports, module) => {
- var bind2 = require_function_bind();
- var $TypeError = require_type();
- var $call = require_functionCall();
- var $actualApply = require_actualApply();
- module.exports = function callBindBasic(args) {
- if (args.length < 1 || typeof args[0] !== "function") {
- throw new $TypeError("a function is required");
- }
- return $actualApply(bind2, $call, args);
- };
-});
-
-// node_modules/dunder-proto/get.js
-var require_get = __commonJS((exports, module) => {
- var callBind = require_call_bind_apply_helpers();
- var gOPD = require_gopd();
- var hasProtoAccessor;
- try {
- hasProtoAccessor = [].__proto__ === Array.prototype;
- } catch (e) {
- if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") {
- throw e;
- }
- }
- var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, "__proto__");
- var $Object = Object;
- var $getPrototypeOf = $Object.getPrototypeOf;
- module.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? function getDunder(value) {
- return $getPrototypeOf(value == null ? value : $Object(value));
- } : false;
-});
-
-// node_modules/get-proto/index.js
-var require_get_proto = __commonJS((exports, module) => {
- var reflectGetProto = require_Reflect_getPrototypeOf();
- var originalGetProto = require_Object_getPrototypeOf();
- var getDunderProto = require_get();
- module.exports = reflectGetProto ? function getProto(O) {
- return reflectGetProto(O);
- } : originalGetProto ? function getProto(O) {
- if (!O || typeof O !== "object" && typeof O !== "function") {
- throw new TypeError("getProto: not an object");
- }
- return originalGetProto(O);
- } : getDunderProto ? function getProto(O) {
- return getDunderProto(O);
- } : null;
-});
-
-// node_modules/hasown/index.js
-var require_hasown = __commonJS((exports, module) => {
- var call = Function.prototype.call;
- var $hasOwn = Object.prototype.hasOwnProperty;
- var bind2 = require_function_bind();
- module.exports = bind2.call(call, $hasOwn);
-});
-
-// node_modules/get-intrinsic/index.js
-var require_get_intrinsic = __commonJS((exports, module) => {
- var undefined2;
- var $Object = require_es_object_atoms();
- var $Error = require_es_errors();
- var $EvalError = require_eval();
- var $RangeError = require_range();
- var $ReferenceError = require_ref();
- var $SyntaxError = require_syntax();
- var $TypeError = require_type();
- var $URIError = require_uri();
- var abs = require_abs();
- var floor = require_floor();
- var max = require_max();
- var min = require_min();
- var pow = require_pow();
- var round = require_round();
- var sign = require_sign();
- var $Function = Function;
- var getEvalledConstructor = function(expressionSyntax) {
- try {
- return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
- } catch (e) {}
- };
- var $gOPD = require_gopd();
- var $defineProperty = require_es_define_property();
- var throwTypeError = function() {
- throw new $TypeError;
- };
- var ThrowTypeError = $gOPD ? function() {
- try {
- arguments.callee;
- return throwTypeError;
- } catch (calleeThrows) {
- try {
- return $gOPD(arguments, "callee").get;
- } catch (gOPDthrows) {
- return throwTypeError;
- }
- }
- }() : throwTypeError;
- var hasSymbols = require_has_symbols()();
- var getProto = require_get_proto();
- var $ObjectGPO = require_Object_getPrototypeOf();
- var $ReflectGPO = require_Reflect_getPrototypeOf();
- var $apply = require_functionApply();
- var $call = require_functionCall();
- var needsEval = {};
- var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array);
- var INTRINSICS = {
- __proto__: null,
- "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError,
- "%Array%": Array,
- "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer,
- "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2,
- "%AsyncFromSyncIteratorPrototype%": undefined2,
- "%AsyncFunction%": needsEval,
- "%AsyncGenerator%": needsEval,
- "%AsyncGeneratorFunction%": needsEval,
- "%AsyncIteratorPrototype%": needsEval,
- "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics,
- "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt,
- "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array,
- "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array,
- "%Boolean%": Boolean,
- "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView,
- "%Date%": Date,
- "%decodeURI%": decodeURI,
- "%decodeURIComponent%": decodeURIComponent,
- "%encodeURI%": encodeURI,
- "%encodeURIComponent%": encodeURIComponent,
- "%Error%": $Error,
- "%eval%": eval,
- "%EvalError%": $EvalError,
- "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array,
- "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array,
- "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array,
- "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry,
- "%Function%": $Function,
- "%GeneratorFunction%": needsEval,
- "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array,
- "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array,
- "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array,
- "%isFinite%": isFinite,
- "%isNaN%": isNaN,
- "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2,
- "%JSON%": typeof JSON === "object" ? JSON : undefined2,
- "%Map%": typeof Map === "undefined" ? undefined2 : Map,
- "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto(new Map()[Symbol.iterator]()),
- "%Math%": Math,
- "%Number%": Number,
- "%Object%": $Object,
- "%Object.getOwnPropertyDescriptor%": $gOPD,
- "%parseFloat%": parseFloat,
- "%parseInt%": parseInt,
- "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise,
- "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy,
- "%RangeError%": $RangeError,
- "%ReferenceError%": $ReferenceError,
- "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect,
- "%RegExp%": RegExp,
- "%Set%": typeof Set === "undefined" ? undefined2 : Set,
- "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto(new Set()[Symbol.iterator]()),
- "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer,
- "%String%": String,
- "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2,
- "%Symbol%": hasSymbols ? Symbol : undefined2,
- "%SyntaxError%": $SyntaxError,
- "%ThrowTypeError%": ThrowTypeError,
- "%TypedArray%": TypedArray,
- "%TypeError%": $TypeError,
- "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array,
- "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray,
- "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array,
- "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array,
- "%URIError%": $URIError,
- "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap,
- "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef,
- "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet,
- "%Function.prototype.call%": $call,
- "%Function.prototype.apply%": $apply,
- "%Object.defineProperty%": $defineProperty,
- "%Object.getPrototypeOf%": $ObjectGPO,
- "%Math.abs%": abs,
- "%Math.floor%": floor,
- "%Math.max%": max,
- "%Math.min%": min,
- "%Math.pow%": pow,
- "%Math.round%": round,
- "%Math.sign%": sign,
- "%Reflect.getPrototypeOf%": $ReflectGPO
- };
- if (getProto) {
- try {
- null.error;
- } catch (e) {
- errorProto = getProto(getProto(e));
- INTRINSICS["%Error.prototype%"] = errorProto;
- }
- }
- var errorProto;
- var doEval = function doEval2(name) {
- var value;
- if (name === "%AsyncFunction%") {
- value = getEvalledConstructor("async function () {}");
- } else if (name === "%GeneratorFunction%") {
- value = getEvalledConstructor("function* () {}");
- } else if (name === "%AsyncGeneratorFunction%") {
- value = getEvalledConstructor("async function* () {}");
- } else if (name === "%AsyncGenerator%") {
- var fn = doEval2("%AsyncGeneratorFunction%");
- if (fn) {
- value = fn.prototype;
- }
- } else if (name === "%AsyncIteratorPrototype%") {
- var gen = doEval2("%AsyncGenerator%");
- if (gen && getProto) {
- value = getProto(gen.prototype);
- }
- }
- INTRINSICS[name] = value;
- return value;
- };
- var LEGACY_ALIASES = {
- __proto__: null,
- "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"],
- "%ArrayPrototype%": ["Array", "prototype"],
- "%ArrayProto_entries%": ["Array", "prototype", "entries"],
- "%ArrayProto_forEach%": ["Array", "prototype", "forEach"],
- "%ArrayProto_keys%": ["Array", "prototype", "keys"],
- "%ArrayProto_values%": ["Array", "prototype", "values"],
- "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"],
- "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"],
- "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"],
- "%BooleanPrototype%": ["Boolean", "prototype"],
- "%DataViewPrototype%": ["DataView", "prototype"],
- "%DatePrototype%": ["Date", "prototype"],
- "%ErrorPrototype%": ["Error", "prototype"],
- "%EvalErrorPrototype%": ["EvalError", "prototype"],
- "%Float32ArrayPrototype%": ["Float32Array", "prototype"],
- "%Float64ArrayPrototype%": ["Float64Array", "prototype"],
- "%FunctionPrototype%": ["Function", "prototype"],
- "%Generator%": ["GeneratorFunction", "prototype"],
- "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"],
- "%Int8ArrayPrototype%": ["Int8Array", "prototype"],
- "%Int16ArrayPrototype%": ["Int16Array", "prototype"],
- "%Int32ArrayPrototype%": ["Int32Array", "prototype"],
- "%JSONParse%": ["JSON", "parse"],
- "%JSONStringify%": ["JSON", "stringify"],
- "%MapPrototype%": ["Map", "prototype"],
- "%NumberPrototype%": ["Number", "prototype"],
- "%ObjectPrototype%": ["Object", "prototype"],
- "%ObjProto_toString%": ["Object", "prototype", "toString"],
- "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"],
- "%PromisePrototype%": ["Promise", "prototype"],
- "%PromiseProto_then%": ["Promise", "prototype", "then"],
- "%Promise_all%": ["Promise", "all"],
- "%Promise_reject%": ["Promise", "reject"],
- "%Promise_resolve%": ["Promise", "resolve"],
- "%RangeErrorPrototype%": ["RangeError", "prototype"],
- "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"],
- "%RegExpPrototype%": ["RegExp", "prototype"],
- "%SetPrototype%": ["Set", "prototype"],
- "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"],
- "%StringPrototype%": ["String", "prototype"],
- "%SymbolPrototype%": ["Symbol", "prototype"],
- "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"],
- "%TypedArrayPrototype%": ["TypedArray", "prototype"],
- "%TypeErrorPrototype%": ["TypeError", "prototype"],
- "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"],
- "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"],
- "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"],
- "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"],
- "%URIErrorPrototype%": ["URIError", "prototype"],
- "%WeakMapPrototype%": ["WeakMap", "prototype"],
- "%WeakSetPrototype%": ["WeakSet", "prototype"]
- };
- var bind2 = require_function_bind();
- var hasOwn2 = require_hasown();
- var $concat = bind2.call($call, Array.prototype.concat);
- var $spliceApply = bind2.call($apply, Array.prototype.splice);
- var $replace = bind2.call($call, String.prototype.replace);
- var $strSlice = bind2.call($call, String.prototype.slice);
- var $exec = bind2.call($call, RegExp.prototype.exec);
- var rePropName2 = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
- var reEscapeChar2 = /\\(\\)?/g;
- var stringToPath2 = function stringToPath3(string) {
- var first = $strSlice(string, 0, 1);
- var last = $strSlice(string, -1);
- if (first === "%" && last !== "%") {
- throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");
- } else if (last === "%" && first !== "%") {
- throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");
- }
- var result = [];
- $replace(string, rePropName2, function(match, number, quote, subString) {
- result[result.length] = quote ? $replace(subString, reEscapeChar2, "$1") : number || match;
- });
- return result;
- };
- var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) {
- var intrinsicName = name;
- var alias;
- if (hasOwn2(LEGACY_ALIASES, intrinsicName)) {
- alias = LEGACY_ALIASES[intrinsicName];
- intrinsicName = "%" + alias[0] + "%";
- }
- if (hasOwn2(INTRINSICS, intrinsicName)) {
- var value = INTRINSICS[intrinsicName];
- if (value === needsEval) {
- value = doEval(intrinsicName);
- }
- if (typeof value === "undefined" && !allowMissing) {
- throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!");
- }
- return {
- alias,
- name: intrinsicName,
- value
- };
- }
- throw new $SyntaxError("intrinsic " + name + " does not exist!");
- };
- module.exports = function GetIntrinsic(name, allowMissing) {
- if (typeof name !== "string" || name.length === 0) {
- throw new $TypeError("intrinsic name must be a non-empty string");
- }
- if (arguments.length > 1 && typeof allowMissing !== "boolean") {
- throw new $TypeError('"allowMissing" argument must be a boolean');
- }
- if ($exec(/^%?[^%]*%?$/, name) === null) {
- throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
- }
- var parts = stringToPath2(name);
- var intrinsicBaseName = parts.length > 0 ? parts[0] : "";
- var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing);
- var intrinsicRealName = intrinsic.name;
- var value = intrinsic.value;
- var skipFurtherCaching = false;
- var alias = intrinsic.alias;
- if (alias) {
- intrinsicBaseName = alias[0];
- $spliceApply(parts, $concat([0, 1], alias));
- }
- for (var i2 = 1, isOwn = true;i2 < parts.length; i2 += 1) {
- var part = parts[i2];
- var first = $strSlice(part, 0, 1);
- var last = $strSlice(part, -1);
- if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) {
- throw new $SyntaxError("property names with quotes must have matching quotes");
- }
- if (part === "constructor" || !isOwn) {
- skipFurtherCaching = true;
- }
- intrinsicBaseName += "." + part;
- intrinsicRealName = "%" + intrinsicBaseName + "%";
- if (hasOwn2(INTRINSICS, intrinsicRealName)) {
- value = INTRINSICS[intrinsicRealName];
- } else if (value != null) {
- if (!(part in value)) {
- if (!allowMissing) {
- throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available.");
- }
- return;
- }
- if ($gOPD && i2 + 1 >= parts.length) {
- var desc = $gOPD(value, part);
- isOwn = !!desc;
- if (isOwn && "get" in desc && !("originalValue" in desc.get)) {
- value = desc.get;
- } else {
- value = value[part];
- }
- } else {
- isOwn = hasOwn2(value, part);
- value = value[part];
- }
- if (isOwn && !skipFurtherCaching) {
- INTRINSICS[intrinsicRealName] = value;
- }
- }
- }
- return value;
- };
-});
-
-// node_modules/has-tostringtag/shams.js
-var require_shams2 = __commonJS((exports, module) => {
- var hasSymbols = require_shams();
- module.exports = function hasToStringTagShams() {
- return hasSymbols() && !!Symbol.toStringTag;
- };
-});
-
-// node_modules/es-set-tostringtag/index.js
-var require_es_set_tostringtag = __commonJS((exports, module) => {
- var GetIntrinsic = require_get_intrinsic();
- var $defineProperty = GetIntrinsic("%Object.defineProperty%", true);
- var hasToStringTag = require_shams2()();
- var hasOwn2 = require_hasown();
- var $TypeError = require_type();
- var toStringTag2 = hasToStringTag ? Symbol.toStringTag : null;
- module.exports = function setToStringTag(object, value) {
- var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force;
- var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable;
- if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") {
- throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans");
- }
- if (toStringTag2 && (overrideIfSet || !hasOwn2(object, toStringTag2))) {
- if ($defineProperty) {
- $defineProperty(object, toStringTag2, {
- configurable: !nonConfigurable,
- enumerable: false,
- value,
- writable: false
- });
- } else {
- object[toStringTag2] = value;
- }
- }
- };
-});
-
-// node_modules/form-data/lib/populate.js
-var require_populate = __commonJS((exports, module) => {
- module.exports = function(dst, src) {
- Object.keys(src).forEach(function(prop) {
- dst[prop] = dst[prop] || src[prop];
- });
- return dst;
- };
-});
-
-// node_modules/form-data/lib/form_data.js
-var require_form_data = __commonJS((exports, module) => {
- var CombinedStream = require_combined_stream();
- var util = __require("util");
- var path6 = __require("path");
- var http = __require("http");
- var https = __require("https");
- var parseUrl = __require("url").parse;
- var fs2 = __require("fs");
- var Stream2 = __require("stream").Stream;
- var crypto2 = __require("crypto");
- var mime = require_mime_types();
- var asynckit = require_asynckit();
- var setToStringTag = require_es_set_tostringtag();
- var hasOwn2 = require_hasown();
- var populate = require_populate();
- function FormData3(options2) {
- if (!(this instanceof FormData3)) {
- return new FormData3(options2);
- }
- this._overheadLength = 0;
- this._valueLength = 0;
- this._valuesToMeasure = [];
- CombinedStream.call(this);
- options2 = options2 || {};
- for (var option in options2) {
- this[option] = options2[option];
- }
- }
- util.inherits(FormData3, CombinedStream);
- FormData3.LINE_BREAK = `\r
-`;
- FormData3.DEFAULT_CONTENT_TYPE = "application/octet-stream";
- FormData3.prototype.append = function(field, value, options2) {
- options2 = options2 || {};
- if (typeof options2 === "string") {
- options2 = { filename: options2 };
- }
- var append = CombinedStream.prototype.append.bind(this);
- if (typeof value === "number" || value == null) {
- value = String(value);
- }
- if (Array.isArray(value)) {
- this._error(new Error("Arrays are not supported."));
- return;
- }
- var header = this._multiPartHeader(field, value, options2);
- var footer = this._multiPartFooter();
- append(header);
- append(value);
- append(footer);
- this._trackLength(header, value, options2);
- };
- FormData3.prototype._trackLength = function(header, value, options2) {
- var valueLength = 0;
- if (options2.knownLength != null) {
- valueLength += Number(options2.knownLength);
- } else if (Buffer.isBuffer(value)) {
- valueLength = value.length;
- } else if (typeof value === "string") {
- valueLength = Buffer.byteLength(value);
- }
- this._valueLength += valueLength;
- this._overheadLength += Buffer.byteLength(header) + FormData3.LINE_BREAK.length;
- if (!value || !value.path && !(value.readable && hasOwn2(value, "httpVersion")) && !(value instanceof Stream2)) {
- return;
- }
- if (!options2.knownLength) {
- this._valuesToMeasure.push(value);
- }
- };
- FormData3.prototype._lengthRetriever = function(value, callback) {
- if (hasOwn2(value, "fd")) {
- if (value.end != null && value.end != Infinity && value.start != null) {
- callback(null, value.end + 1 - (value.start ? value.start : 0));
- } else {
- fs2.stat(value.path, function(err, stat) {
- if (err) {
- callback(err);
- return;
- }
- var fileSize = stat.size - (value.start ? value.start : 0);
- callback(null, fileSize);
- });
- }
- } else if (hasOwn2(value, "httpVersion")) {
- callback(null, Number(value.headers["content-length"]));
- } else if (hasOwn2(value, "httpModule")) {
- value.on("response", function(response) {
- value.pause();
- callback(null, Number(response.headers["content-length"]));
- });
- value.resume();
- } else {
- callback("Unknown stream");
- }
- };
- FormData3.prototype._multiPartHeader = function(field, value, options2) {
- if (typeof options2.header === "string") {
- return options2.header;
- }
- var contentDisposition = this._getContentDisposition(value, options2);
- var contentType = this._getContentType(value, options2);
- var contents = "";
- var headers = {
- "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []),
- "Content-Type": [].concat(contentType || [])
- };
- if (typeof options2.header === "object") {
- populate(headers, options2.header);
- }
- var header;
- for (var prop in headers) {
- if (hasOwn2(headers, prop)) {
- header = headers[prop];
- if (header == null) {
- continue;
- }
- if (!Array.isArray(header)) {
- header = [header];
- }
- if (header.length) {
- contents += prop + ": " + header.join("; ") + FormData3.LINE_BREAK;
- }
- }
- }
- return "--" + this.getBoundary() + FormData3.LINE_BREAK + contents + FormData3.LINE_BREAK;
- };
- FormData3.prototype._getContentDisposition = function(value, options2) {
- var filename;
- if (typeof options2.filepath === "string") {
- filename = path6.normalize(options2.filepath).replace(/\\/g, "/");
- } else if (options2.filename || value && (value.name || value.path)) {
- filename = path6.basename(options2.filename || value && (value.name || value.path));
- } else if (value && value.readable && hasOwn2(value, "httpVersion")) {
- filename = path6.basename(value.client._httpMessage.path || "");
- }
- if (filename) {
- return 'filename="' + filename + '"';
- }
- };
- FormData3.prototype._getContentType = function(value, options2) {
- var contentType = options2.contentType;
- if (!contentType && value && value.name) {
- contentType = mime.lookup(value.name);
- }
- if (!contentType && value && value.path) {
- contentType = mime.lookup(value.path);
- }
- if (!contentType && value && value.readable && hasOwn2(value, "httpVersion")) {
- contentType = value.headers["content-type"];
- }
- if (!contentType && (options2.filepath || options2.filename)) {
- contentType = mime.lookup(options2.filepath || options2.filename);
- }
- if (!contentType && value && typeof value === "object") {
- contentType = FormData3.DEFAULT_CONTENT_TYPE;
- }
- return contentType;
- };
- FormData3.prototype._multiPartFooter = function() {
- return function(next) {
- var footer = FormData3.LINE_BREAK;
- var lastPart = this._streams.length === 0;
- if (lastPart) {
- footer += this._lastBoundary();
- }
- next(footer);
- }.bind(this);
- };
- FormData3.prototype._lastBoundary = function() {
- return "--" + this.getBoundary() + "--" + FormData3.LINE_BREAK;
- };
- FormData3.prototype.getHeaders = function(userHeaders) {
- var header;
- var formHeaders = {
- "content-type": "multipart/form-data; boundary=" + this.getBoundary()
- };
- for (header in userHeaders) {
- if (hasOwn2(userHeaders, header)) {
- formHeaders[header.toLowerCase()] = userHeaders[header];
- }
- }
- return formHeaders;
- };
- FormData3.prototype.setBoundary = function(boundary) {
- if (typeof boundary !== "string") {
- throw new TypeError("FormData boundary must be a string");
- }
- this._boundary = boundary;
- };
- FormData3.prototype.getBoundary = function() {
- if (!this._boundary) {
- this._generateBoundary();
- }
- return this._boundary;
- };
- FormData3.prototype.getBuffer = function() {
- var dataBuffer = new Buffer.alloc(0);
- var boundary = this.getBoundary();
- for (var i2 = 0, len = this._streams.length;i2 < len; i2++) {
- if (typeof this._streams[i2] !== "function") {
- if (Buffer.isBuffer(this._streams[i2])) {
- dataBuffer = Buffer.concat([dataBuffer, this._streams[i2]]);
- } else {
- dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i2])]);
- }
- if (typeof this._streams[i2] !== "string" || this._streams[i2].substring(2, boundary.length + 2) !== boundary) {
- dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData3.LINE_BREAK)]);
- }
- }
- }
- return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]);
- };
- FormData3.prototype._generateBoundary = function() {
- this._boundary = "--------------------------" + crypto2.randomBytes(12).toString("hex");
- };
- FormData3.prototype.getLengthSync = function() {
- var knownLength = this._overheadLength + this._valueLength;
- if (this._streams.length) {
- knownLength += this._lastBoundary().length;
- }
- if (!this.hasKnownLength()) {
- this._error(new Error("Cannot calculate proper length in synchronous way."));
- }
- return knownLength;
- };
- FormData3.prototype.hasKnownLength = function() {
- var hasKnownLength = true;
- if (this._valuesToMeasure.length) {
- hasKnownLength = false;
- }
- return hasKnownLength;
- };
- FormData3.prototype.getLength = function(cb) {
- var knownLength = this._overheadLength + this._valueLength;
- if (this._streams.length) {
- knownLength += this._lastBoundary().length;
- }
- if (!this._valuesToMeasure.length) {
- process.nextTick(cb.bind(this, null, knownLength));
- return;
- }
- asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
- if (err) {
- cb(err);
- return;
- }
- values.forEach(function(length) {
- knownLength += length;
- });
- cb(null, knownLength);
- });
- };
- FormData3.prototype.submit = function(params, cb) {
- var request;
- var options2;
- var defaults = { method: "post" };
- if (typeof params === "string") {
- params = parseUrl(params);
- options2 = populate({
- port: params.port,
- path: params.pathname,
- host: params.hostname,
- protocol: params.protocol
- }, defaults);
- } else {
- options2 = populate(params, defaults);
- if (!options2.port) {
- options2.port = options2.protocol === "https:" ? 443 : 80;
- }
- }
- options2.headers = this.getHeaders(params.headers);
- if (options2.protocol === "https:") {
- request = https.request(options2);
- } else {
- request = http.request(options2);
- }
- this.getLength(function(err, length) {
- if (err && err !== "Unknown stream") {
- this._error(err);
- return;
- }
- if (length) {
- request.setHeader("Content-Length", length);
- }
- this.pipe(request);
- if (cb) {
- var onResponse;
- var callback = function(error, responce) {
- request.removeListener("error", callback);
- request.removeListener("response", onResponse);
- return cb.call(this, error, responce);
- };
- onResponse = callback.bind(this, null);
- request.on("error", callback);
- request.on("response", onResponse);
- }
- }.bind(this));
- return request;
- };
- FormData3.prototype._error = function(err) {
- if (!this.error) {
- this.error = err;
- this.pause();
- this.emit("error", err);
- }
- };
- FormData3.prototype.toString = function() {
- return "[object FormData]";
- };
- setToStringTag(FormData3.prototype, "FormData");
- module.exports = FormData3;
-});
-
-// node_modules/axios/lib/platform/node/classes/FormData.js
-var import_form_data, FormData_default;
-var init_FormData = __esm(() => {
- import_form_data = __toESM(require_form_data(), 1);
- FormData_default = import_form_data.default;
-});
-
-// node_modules/axios/lib/helpers/toFormData.js
-function isVisitable(thing) {
- return utils_default.isPlainObject(thing) || utils_default.isArray(thing);
-}
-function removeBrackets(key) {
- return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key;
-}
-function renderKey(path6, key, dots) {
- if (!path6)
- return key;
- return path6.concat(key).map(function each(token, i2) {
- token = removeBrackets(token);
- return !dots && i2 ? "[" + token + "]" : token;
- }).join(dots ? "." : "");
-}
-function isFlatArray(arr) {
- return utils_default.isArray(arr) && !arr.some(isVisitable);
-}
-function toFormData(obj, formData, options2) {
- if (!utils_default.isObject(obj)) {
- throw new TypeError("target must be an object");
- }
- formData = formData || new (FormData_default || FormData);
- options2 = utils_default.toFlatObject(options2, {
- metaTokens: true,
- dots: false,
- indexes: false
- }, false, function defined(option, source) {
- return !utils_default.isUndefined(source[option]);
- });
- const metaTokens = options2.metaTokens;
- const visitor = options2.visitor || defaultVisitor;
- const dots = options2.dots;
- const indexes = options2.indexes;
- const _Blob = options2.Blob || typeof Blob !== "undefined" && Blob;
- const useBlob = _Blob && utils_default.isSpecCompliantForm(formData);
- if (!utils_default.isFunction(visitor)) {
- throw new TypeError("visitor must be a function");
- }
- function convertValue(value) {
- if (value === null)
- return "";
- if (utils_default.isDate(value)) {
- return value.toISOString();
- }
- if (utils_default.isBoolean(value)) {
- return value.toString();
- }
- if (!useBlob && utils_default.isBlob(value)) {
- throw new AxiosError_default("Blob is not supported. Use a Buffer instead.");
- }
- if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) {
- return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
- }
- return value;
- }
- function defaultVisitor(value, key, path6) {
- let arr = value;
- if (utils_default.isReactNative(formData) && utils_default.isReactNativeBlob(value)) {
- formData.append(renderKey(path6, key, dots), convertValue(value));
- return false;
- }
- if (value && !path6 && typeof value === "object") {
- if (utils_default.endsWith(key, "{}")) {
- key = metaTokens ? key : key.slice(0, -2);
- value = JSON.stringify(value);
- } else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) {
- key = removeBrackets(key);
- arr.forEach(function each(el, index2) {
- !(utils_default.isUndefined(el) || el === null) && formData.append(indexes === true ? renderKey([key], index2, dots) : indexes === null ? key : key + "[]", convertValue(el));
- });
- return false;
- }
- }
- if (isVisitable(value)) {
- return true;
- }
- formData.append(renderKey(path6, key, dots), convertValue(value));
- return false;
- }
- const stack = [];
- const exposedHelpers = Object.assign(predicates, {
- defaultVisitor,
- convertValue,
- isVisitable
- });
- function build(value, path6) {
- if (utils_default.isUndefined(value))
- return;
- if (stack.indexOf(value) !== -1) {
- throw Error("Circular reference detected in " + path6.join("."));
- }
- stack.push(value);
- utils_default.forEach(value, function each(el, key) {
- const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path6, exposedHelpers);
- if (result === true) {
- build(el, path6 ? path6.concat(key) : [key]);
- }
- });
- stack.pop();
- }
- if (!utils_default.isObject(obj)) {
- throw new TypeError("data must be an object");
- }
- build(obj);
- return formData;
-}
-var predicates, toFormData_default;
-var init_toFormData = __esm(() => {
- init_utils();
- init_AxiosError();
- init_FormData();
- predicates = utils_default.toFlatObject(utils_default, {}, null, function filter(prop) {
- return /^is[A-Z]/.test(prop);
- });
- toFormData_default = toFormData;
-});
-
-// node_modules/axios/lib/helpers/AxiosURLSearchParams.js
-function encode(str) {
- const charMap = {
- "!": "%21",
- "'": "%27",
- "(": "%28",
- ")": "%29",
- "~": "%7E",
- "%20": "+",
- "%00": "\x00"
- };
- return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
- return charMap[match];
- });
-}
-function AxiosURLSearchParams(params, options2) {
- this._pairs = [];
- params && toFormData_default(params, this, options2);
-}
-var prototype, AxiosURLSearchParams_default;
-var init_AxiosURLSearchParams = __esm(() => {
- init_toFormData();
- prototype = AxiosURLSearchParams.prototype;
- prototype.append = function append(name, value) {
- this._pairs.push([name, value]);
- };
- prototype.toString = function toString5(encoder) {
- const _encode = encoder ? function(value) {
- return encoder.call(this, value, encode);
- } : encode;
- return this._pairs.map(function each(pair) {
- return _encode(pair[0]) + "=" + _encode(pair[1]);
- }, "").join("&");
- };
- AxiosURLSearchParams_default = AxiosURLSearchParams;
-});
-
-// node_modules/axios/lib/helpers/buildURL.js
-function encode2(val) {
- return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+");
-}
-function buildURL(url, params, options2) {
- if (!params) {
- return url;
- }
- const _encode = options2 && options2.encode || encode2;
- const _options = utils_default.isFunction(options2) ? {
- serialize: options2
- } : options2;
- const serializeFn = _options && _options.serialize;
- let serializedParams;
- if (serializeFn) {
- serializedParams = serializeFn(params, _options);
- } else {
- serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, _options).toString(_encode);
- }
- if (serializedParams) {
- const hashmarkIndex = url.indexOf("#");
- if (hashmarkIndex !== -1) {
- url = url.slice(0, hashmarkIndex);
- }
- url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
- }
- return url;
-}
-var init_buildURL = __esm(() => {
- init_utils();
- init_AxiosURLSearchParams();
-});
-
-// node_modules/axios/lib/core/InterceptorManager.js
-class InterceptorManager {
- constructor() {
- this.handlers = [];
- }
- use(fulfilled, rejected, options2) {
- this.handlers.push({
- fulfilled,
- rejected,
- synchronous: options2 ? options2.synchronous : false,
- runWhen: options2 ? options2.runWhen : null
- });
- return this.handlers.length - 1;
- }
- eject(id) {
- if (this.handlers[id]) {
- this.handlers[id] = null;
- }
- }
- clear() {
- if (this.handlers) {
- this.handlers = [];
- }
- }
- forEach(fn) {
- utils_default.forEach(this.handlers, function forEachHandler(h2) {
- if (h2 !== null) {
- fn(h2);
- }
- });
- }
-}
-var InterceptorManager_default;
-var init_InterceptorManager = __esm(() => {
- init_utils();
- InterceptorManager_default = InterceptorManager;
-});
-
-// node_modules/axios/lib/defaults/transitional.js
-var transitional_default;
-var init_transitional = __esm(() => {
- transitional_default = {
- silentJSONParsing: true,
- forcedJSONParsing: true,
- clarifyTimeoutError: false,
- legacyInterceptorReqResOrdering: true
- };
-});
-
-// node_modules/axios/lib/platform/node/classes/URLSearchParams.js
-import url from "url";
-var URLSearchParams_default;
-var init_URLSearchParams = __esm(() => {
- URLSearchParams_default = url.URLSearchParams;
-});
-
-// node_modules/axios/lib/platform/node/index.js
-import crypto2 from "crypto";
-var ALPHA = "abcdefghijklmnopqrstuvwxyz", DIGIT = "0123456789", ALPHABET, generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
- let str = "";
- const { length } = alphabet;
- const randomValues = new Uint32Array(size);
- crypto2.randomFillSync(randomValues);
- for (let i2 = 0;i2 < size; i2++) {
- str += alphabet[randomValues[i2] % length];
- }
- return str;
-}, node_default;
-var init_node3 = __esm(() => {
- init_URLSearchParams();
- init_FormData();
- ALPHABET = {
- DIGIT,
- ALPHA,
- ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
- };
- node_default = {
- isNode: true,
- classes: {
- URLSearchParams: URLSearchParams_default,
- FormData: FormData_default,
- Blob: typeof Blob !== "undefined" && Blob || null
- },
- ALPHABET,
- generateString,
- protocols: ["http", "https", "file", "data"]
- };
-});
-
-// node_modules/axios/lib/platform/common/utils.js
-var exports_utils = {};
-__export(exports_utils, {
- origin: () => origin,
- navigator: () => _navigator,
- hasStandardBrowserWebWorkerEnv: () => hasStandardBrowserWebWorkerEnv,
- hasStandardBrowserEnv: () => hasStandardBrowserEnv,
- hasBrowserEnv: () => hasBrowserEnv
-});
-var hasBrowserEnv, _navigator, hasStandardBrowserEnv, hasStandardBrowserWebWorkerEnv, origin;
-var init_utils2 = __esm(() => {
- hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
- _navigator = typeof navigator === "object" && navigator || undefined;
- hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
- hasStandardBrowserWebWorkerEnv = (() => {
- return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
- })();
- origin = hasBrowserEnv && window.location.href || "http://localhost";
-});
-
-// node_modules/axios/lib/platform/index.js
-var platform_default;
-var init_platform = __esm(() => {
- init_node3();
- init_utils2();
- platform_default = {
- ...exports_utils,
- ...node_default
- };
-});
-
-// node_modules/axios/lib/helpers/toURLEncodedForm.js
-function toURLEncodedForm(data, options2) {
- return toFormData_default(data, new platform_default.classes.URLSearchParams, {
- visitor: function(value, key, path6, helpers3) {
- if (platform_default.isNode && utils_default.isBuffer(value)) {
- this.append(key, value.toString("base64"));
- return false;
- }
- return helpers3.defaultVisitor.apply(this, arguments);
- },
- ...options2
- });
-}
-var init_toURLEncodedForm = __esm(() => {
- init_utils();
- init_toFormData();
- init_platform();
-});
-
-// node_modules/axios/lib/helpers/formDataToJSON.js
-function parsePropPath(name) {
- return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
- return match[0] === "[]" ? "" : match[1] || match[0];
- });
-}
-function arrayToObject(arr) {
- const obj = {};
- const keys2 = Object.keys(arr);
- let i2;
- const len = keys2.length;
- let key;
- for (i2 = 0;i2 < len; i2++) {
- key = keys2[i2];
- obj[key] = arr[key];
- }
- return obj;
-}
-function formDataToJSON(formData) {
- function buildPath(path6, value, target, index2) {
- let name = path6[index2++];
- if (name === "__proto__")
- return true;
- const isNumericKey = Number.isFinite(+name);
- const isLast = index2 >= path6.length;
- name = !name && utils_default.isArray(target) ? target.length : name;
- if (isLast) {
- if (utils_default.hasOwnProp(target, name)) {
- target[name] = [target[name], value];
- } else {
- target[name] = value;
- }
- return !isNumericKey;
- }
- if (!target[name] || !utils_default.isObject(target[name])) {
- target[name] = [];
- }
- const result = buildPath(path6, value, target[name], index2);
- if (result && utils_default.isArray(target[name])) {
- target[name] = arrayToObject(target[name]);
- }
- return !isNumericKey;
- }
- if (utils_default.isFormData(formData) && utils_default.isFunction(formData.entries)) {
- const obj = {};
- utils_default.forEachEntry(formData, (name, value) => {
- buildPath(parsePropPath(name), value, obj, 0);
- });
- return obj;
- }
- return null;
-}
-var formDataToJSON_default;
-var init_formDataToJSON = __esm(() => {
- init_utils();
- formDataToJSON_default = formDataToJSON;
-});
-
-// node_modules/axios/lib/defaults/index.js
-function stringifySafely(rawValue, parser2, encoder) {
- if (utils_default.isString(rawValue)) {
- try {
- (parser2 || JSON.parse)(rawValue);
- return utils_default.trim(rawValue);
- } catch (e) {
- if (e.name !== "SyntaxError") {
- throw e;
- }
- }
- }
- return (encoder || JSON.stringify)(rawValue);
-}
-var defaults, defaults_default;
-var init_defaults = __esm(() => {
- init_utils();
- init_AxiosError();
- init_transitional();
- init_toFormData();
- init_toURLEncodedForm();
- init_platform();
- init_formDataToJSON();
- defaults = {
- transitional: transitional_default,
- adapter: ["xhr", "http", "fetch"],
- transformRequest: [
- function transformRequest(data, headers) {
- const contentType = headers.getContentType() || "";
- const hasJSONContentType = contentType.indexOf("application/json") > -1;
- const isObjectPayload = utils_default.isObject(data);
- if (isObjectPayload && utils_default.isHTMLForm(data)) {
- data = new FormData(data);
- }
- const isFormData2 = utils_default.isFormData(data);
- if (isFormData2) {
- return hasJSONContentType ? JSON.stringify(formDataToJSON_default(data)) : data;
- }
- if (utils_default.isArrayBuffer(data) || utils_default.isBuffer(data) || utils_default.isStream(data) || utils_default.isFile(data) || utils_default.isBlob(data) || utils_default.isReadableStream(data)) {
- return data;
- }
- if (utils_default.isArrayBufferView(data)) {
- return data.buffer;
- }
- if (utils_default.isURLSearchParams(data)) {
- headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
- return data.toString();
- }
- let isFileList2;
- if (isObjectPayload) {
- if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
- return toURLEncodedForm(data, this.formSerializer).toString();
- }
- if ((isFileList2 = utils_default.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
- const _FormData = this.env && this.env.FormData;
- return toFormData_default(isFileList2 ? { "files[]": data } : data, _FormData && new _FormData, this.formSerializer);
- }
- }
- if (isObjectPayload || hasJSONContentType) {
- headers.setContentType("application/json", false);
- return stringifySafely(data);
- }
- return data;
- }
- ],
- transformResponse: [
- function transformResponse(data) {
- const transitional = this.transitional || defaults.transitional;
- const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
- const JSONRequested = this.responseType === "json";
- if (utils_default.isResponse(data) || utils_default.isReadableStream(data)) {
- return data;
- }
- if (data && utils_default.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
- const silentJSONParsing = transitional && transitional.silentJSONParsing;
- const strictJSONParsing = !silentJSONParsing && JSONRequested;
- try {
- return JSON.parse(data, this.parseReviver);
- } catch (e) {
- if (strictJSONParsing) {
- if (e.name === "SyntaxError") {
- throw AxiosError_default.from(e, AxiosError_default.ERR_BAD_RESPONSE, this, null, this.response);
- }
- throw e;
- }
- }
- }
- return data;
- }
- ],
- timeout: 0,
- xsrfCookieName: "XSRF-TOKEN",
- xsrfHeaderName: "X-XSRF-TOKEN",
- maxContentLength: -1,
- maxBodyLength: -1,
- env: {
- FormData: platform_default.classes.FormData,
- Blob: platform_default.classes.Blob
- },
- validateStatus: function validateStatus(status) {
- return status >= 200 && status < 300;
- },
- headers: {
- common: {
- Accept: "application/json, text/plain, */*",
- "Content-Type": undefined
- }
- }
- };
- utils_default.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
- defaults.headers[method] = {};
- });
- defaults_default = defaults;
-});
-
-// node_modules/axios/lib/helpers/parseHeaders.js
-var ignoreDuplicateOf, parseHeaders_default = (rawHeaders) => {
- const parsed = {};
- let key;
- let val;
- let i2;
- rawHeaders && rawHeaders.split(`
-`).forEach(function parser2(line) {
- i2 = line.indexOf(":");
- key = line.substring(0, i2).trim().toLowerCase();
- val = line.substring(i2 + 1).trim();
- if (!key || parsed[key] && ignoreDuplicateOf[key]) {
- return;
- }
- if (key === "set-cookie") {
- if (parsed[key]) {
- parsed[key].push(val);
- } else {
- parsed[key] = [val];
- }
- } else {
- parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
- }
- });
- return parsed;
-};
-var init_parseHeaders = __esm(() => {
- init_utils();
- ignoreDuplicateOf = utils_default.toObjectSet([
- "age",
- "authorization",
- "content-length",
- "content-type",
- "etag",
- "expires",
- "from",
- "host",
- "if-modified-since",
- "if-unmodified-since",
- "last-modified",
- "location",
- "max-forwards",
- "proxy-authorization",
- "referer",
- "retry-after",
- "user-agent"
- ]);
-});
-
-// node_modules/axios/lib/core/AxiosHeaders.js
-function normalizeHeader(header) {
- return header && String(header).trim().toLowerCase();
-}
-function normalizeValue(value) {
- if (value === false || value == null) {
- return value;
- }
- return utils_default.isArray(value) ? value.map(normalizeValue) : String(value).replace(/[\r\n]+$/, "");
-}
-function parseTokens(str) {
- const tokens = Object.create(null);
- const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
- let match;
- while (match = tokensRE.exec(str)) {
- tokens[match[1]] = match[2];
- }
- return tokens;
-}
-function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) {
- if (utils_default.isFunction(filter2)) {
- return filter2.call(this, value, header);
- }
- if (isHeaderNameFilter) {
- value = header;
- }
- if (!utils_default.isString(value))
- return;
- if (utils_default.isString(filter2)) {
- return value.indexOf(filter2) !== -1;
- }
- if (utils_default.isRegExp(filter2)) {
- return filter2.test(value);
- }
-}
-function formatHeader(header) {
- return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
- return char.toUpperCase() + str;
- });
-}
-function buildAccessors(obj, header) {
- const accessorName = utils_default.toCamelCase(" " + header);
- ["get", "set", "has"].forEach((methodName) => {
- Object.defineProperty(obj, methodName + accessorName, {
- value: function(arg1, arg2, arg3) {
- return this[methodName].call(this, header, arg1, arg2, arg3);
- },
- configurable: true
- });
- });
-}
-var $internals, isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()), AxiosHeaders, AxiosHeaders_default;
-var init_AxiosHeaders = __esm(() => {
- init_utils();
- init_parseHeaders();
- $internals = Symbol("internals");
- AxiosHeaders = class AxiosHeaders {
- constructor(headers) {
- headers && this.set(headers);
- }
- set(header, valueOrRewrite, rewrite) {
- const self2 = this;
- function setHeader(_value, _header, _rewrite) {
- const lHeader = normalizeHeader(_header);
- if (!lHeader) {
- throw new Error("header name must be a non-empty string");
- }
- const key = utils_default.findKey(self2, lHeader);
- if (!key || self2[key] === undefined || _rewrite === true || _rewrite === undefined && self2[key] !== false) {
- self2[key || _header] = normalizeValue(_value);
- }
- }
- const setHeaders = (headers, _rewrite) => utils_default.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
- if (utils_default.isPlainObject(header) || header instanceof this.constructor) {
- setHeaders(header, valueOrRewrite);
- } else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
- setHeaders(parseHeaders_default(header), valueOrRewrite);
- } else if (utils_default.isObject(header) && utils_default.isIterable(header)) {
- let obj = {}, dest, key;
- for (const entry of header) {
- if (!utils_default.isArray(entry)) {
- throw TypeError("Object iterator must return a key-value pair");
- }
- obj[key = entry[0]] = (dest = obj[key]) ? utils_default.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
- }
- setHeaders(obj, valueOrRewrite);
- } else {
- header != null && setHeader(valueOrRewrite, header, rewrite);
- }
- return this;
- }
- get(header, parser2) {
- header = normalizeHeader(header);
- if (header) {
- const key = utils_default.findKey(this, header);
- if (key) {
- const value = this[key];
- if (!parser2) {
- return value;
- }
- if (parser2 === true) {
- return parseTokens(value);
- }
- if (utils_default.isFunction(parser2)) {
- return parser2.call(this, value, key);
- }
- if (utils_default.isRegExp(parser2)) {
- return parser2.exec(value);
- }
- throw new TypeError("parser must be boolean|regexp|function");
- }
- }
- }
- has(header, matcher) {
- header = normalizeHeader(header);
- if (header) {
- const key = utils_default.findKey(this, header);
- return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
- }
- return false;
- }
- delete(header, matcher) {
- const self2 = this;
- let deleted = false;
- function deleteHeader(_header) {
- _header = normalizeHeader(_header);
- if (_header) {
- const key = utils_default.findKey(self2, _header);
- if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
- delete self2[key];
- deleted = true;
- }
- }
- }
- if (utils_default.isArray(header)) {
- header.forEach(deleteHeader);
- } else {
- deleteHeader(header);
- }
- return deleted;
- }
- clear(matcher) {
- const keys2 = Object.keys(this);
- let i2 = keys2.length;
- let deleted = false;
- while (i2--) {
- const key = keys2[i2];
- if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
- delete this[key];
- deleted = true;
- }
- }
- return deleted;
- }
- normalize(format2) {
- const self2 = this;
- const headers = {};
- utils_default.forEach(this, (value, header) => {
- const key = utils_default.findKey(headers, header);
- if (key) {
- self2[key] = normalizeValue(value);
- delete self2[header];
- return;
- }
- const normalized = format2 ? formatHeader(header) : String(header).trim();
- if (normalized !== header) {
- delete self2[header];
- }
- self2[normalized] = normalizeValue(value);
- headers[normalized] = true;
- });
- return this;
- }
- concat(...targets) {
- return this.constructor.concat(this, ...targets);
- }
- toJSON(asStrings) {
- const obj = Object.create(null);
- utils_default.forEach(this, (value, header) => {
- value != null && value !== false && (obj[header] = asStrings && utils_default.isArray(value) ? value.join(", ") : value);
- });
- return obj;
- }
- [Symbol.iterator]() {
- return Object.entries(this.toJSON())[Symbol.iterator]();
- }
- toString() {
- return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join(`
-`);
- }
- getSetCookie() {
- return this.get("set-cookie") || [];
- }
- get [Symbol.toStringTag]() {
- return "AxiosHeaders";
- }
- static from(thing) {
- return thing instanceof this ? thing : new this(thing);
- }
- static concat(first, ...targets) {
- const computed = new this(first);
- targets.forEach((target) => computed.set(target));
- return computed;
- }
- static accessor(header) {
- const internals = this[$internals] = this[$internals] = {
- accessors: {}
- };
- const accessors = internals.accessors;
- const prototype2 = this.prototype;
- function defineAccessor(_header) {
- const lHeader = normalizeHeader(_header);
- if (!accessors[lHeader]) {
- buildAccessors(prototype2, _header);
- accessors[lHeader] = true;
- }
- }
- utils_default.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
- return this;
- }
- };
- AxiosHeaders.accessor([
- "Content-Type",
- "Content-Length",
- "Accept",
- "Accept-Encoding",
- "User-Agent",
- "Authorization"
- ]);
- utils_default.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
- let mapped = key[0].toUpperCase() + key.slice(1);
- return {
- get: () => value,
- set(headerValue) {
- this[mapped] = headerValue;
- }
- };
- });
- utils_default.freezeMethods(AxiosHeaders);
- AxiosHeaders_default = AxiosHeaders;
-});
-
-// node_modules/axios/lib/core/transformData.js
-function transformData(fns, response) {
- const config = this || defaults_default;
- const context = response || config;
- const headers = AxiosHeaders_default.from(context.headers);
- let data = context.data;
- utils_default.forEach(fns, function transform(fn) {
- data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
- });
- headers.normalize();
- return data;
-}
-var init_transformData = __esm(() => {
- init_utils();
- init_defaults();
- init_AxiosHeaders();
-});
-
-// node_modules/axios/lib/cancel/isCancel.js
-function isCancel(value) {
- return !!(value && value.__CANCEL__);
-}
-
-// node_modules/axios/lib/cancel/CanceledError.js
-var CanceledError, CanceledError_default;
-var init_CanceledError = __esm(() => {
- init_AxiosError();
- CanceledError = class CanceledError extends AxiosError_default {
- constructor(message, config, request) {
- super(message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config, request);
- this.name = "CanceledError";
- this.__CANCEL__ = true;
- }
- };
- CanceledError_default = CanceledError;
-});
-
-// node_modules/axios/lib/core/settle.js
-function settle(resolve2, reject, response) {
- const validateStatus2 = response.config.validateStatus;
- if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
- resolve2(response);
- } else {
- reject(new AxiosError_default("Request failed with status code " + response.status, [AxiosError_default.ERR_BAD_REQUEST, AxiosError_default.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.request, response));
- }
-}
-var init_settle = __esm(() => {
- init_AxiosError();
-});
-
-// node_modules/axios/lib/helpers/isAbsoluteURL.js
-function isAbsoluteURL2(url2) {
- if (typeof url2 !== "string") {
- return false;
- }
- return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url2);
-}
-
-// node_modules/axios/lib/helpers/combineURLs.js
-function combineURLs(baseURL, relativeURL) {
- return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
-}
-
-// node_modules/axios/lib/core/buildFullPath.js
-function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
- let isRelativeUrl = !isAbsoluteURL2(requestedURL);
- if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
- return combineURLs(baseURL, requestedURL);
- }
- return requestedURL;
-}
-var init_buildFullPath = () => {};
-
-// node_modules/proxy-from-env/index.js
-function parseUrl(urlString) {
- try {
- return new URL(urlString);
- } catch {
- return null;
- }
-}
-function getProxyForUrl(url2) {
- var parsedUrl = (typeof url2 === "string" ? parseUrl(url2) : url2) || {};
- var proto2 = parsedUrl.protocol;
- var hostname = parsedUrl.host;
- var port = parsedUrl.port;
- if (typeof hostname !== "string" || !hostname || typeof proto2 !== "string") {
- return "";
- }
- proto2 = proto2.split(":", 1)[0];
- hostname = hostname.replace(/:\d*$/, "");
- port = parseInt(port) || DEFAULT_PORTS[proto2] || 0;
- if (!shouldProxy(hostname, port)) {
- return "";
- }
- var proxy = getEnv2(proto2 + "_proxy") || getEnv2("all_proxy");
- if (proxy && proxy.indexOf("://") === -1) {
- proxy = proto2 + "://" + proxy;
- }
- return proxy;
-}
-function shouldProxy(hostname, port) {
- var NO_PROXY = getEnv2("no_proxy").toLowerCase();
- if (!NO_PROXY) {
- return true;
- }
- if (NO_PROXY === "*") {
- return false;
- }
- return NO_PROXY.split(/[,\s]/).every(function(proxy) {
- if (!proxy) {
- return true;
- }
- var parsedProxy = proxy.match(/^(.+):(\d+)$/);
- var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
- var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
- if (parsedProxyPort && parsedProxyPort !== port) {
- return true;
- }
- if (!/^[.*]/.test(parsedProxyHostname)) {
- return hostname !== parsedProxyHostname;
- }
- if (parsedProxyHostname.charAt(0) === "*") {
- parsedProxyHostname = parsedProxyHostname.slice(1);
- }
- return !hostname.endsWith(parsedProxyHostname);
- });
-}
-function getEnv2(key) {
- return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || "";
-}
-var DEFAULT_PORTS;
-var init_proxy_from_env = __esm(() => {
- DEFAULT_PORTS = {
- ftp: 21,
- gopher: 70,
- http: 80,
- https: 443,
- ws: 80,
- wss: 443
- };
-});
-
-// node_modules/ms/index.js
-var require_ms = __commonJS((exports, module) => {
- var s = 1000;
- var m = s * 60;
- var h2 = m * 60;
- var d = h2 * 24;
- var w = d * 7;
- var y = d * 365.25;
- module.exports = function(val, options2) {
- options2 = options2 || {};
- var type = typeof val;
- if (type === "string" && val.length > 0) {
- return parse(val);
- } else if (type === "number" && isFinite(val)) {
- return options2.long ? fmtLong(val) : fmtShort(val);
- }
- throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val));
- };
- 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 n2 = parseFloat(match[1]);
- var type = (match[2] || "ms").toLowerCase();
- switch (type) {
- case "years":
- case "year":
- case "yrs":
- case "yr":
- case "y":
- return n2 * y;
- case "weeks":
- case "week":
- case "w":
- return n2 * w;
- case "days":
- case "day":
- case "d":
- return n2 * d;
- case "hours":
- case "hour":
- case "hrs":
- case "hr":
- case "h":
- return n2 * h2;
- case "minutes":
- case "minute":
- case "mins":
- case "min":
- case "m":
- return n2 * m;
- case "seconds":
- case "second":
- case "secs":
- case "sec":
- case "s":
- return n2 * s;
- case "milliseconds":
- case "millisecond":
- case "msecs":
- case "msec":
- case "ms":
- return n2;
- default:
- return;
- }
- }
- function fmtShort(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return Math.round(ms / d) + "d";
- }
- if (msAbs >= h2) {
- return Math.round(ms / h2) + "h";
- }
- if (msAbs >= m) {
- return Math.round(ms / m) + "m";
- }
- if (msAbs >= s) {
- return Math.round(ms / s) + "s";
- }
- return ms + "ms";
- }
- function fmtLong(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return plural(ms, msAbs, d, "day");
- }
- if (msAbs >= h2) {
- return plural(ms, msAbs, h2, "hour");
- }
- if (msAbs >= m) {
- return plural(ms, msAbs, m, "minute");
- }
- if (msAbs >= s) {
- return plural(ms, msAbs, s, "second");
- }
- return ms + " ms";
- }
- function plural(ms, msAbs, n2, name) {
- var isPlural = msAbs >= n2 * 1.5;
- return Math.round(ms / n2) + " " + name + (isPlural ? "s" : "");
- }
-});
-
-// node_modules/debug/src/common.js
-var require_common = __commonJS((exports, module) => {
- function setup(env2) {
- createDebug.debug = createDebug;
- createDebug.default = createDebug;
- createDebug.coerce = coerce;
- createDebug.disable = disable;
- createDebug.enable = enable;
- createDebug.enabled = enabled;
- createDebug.humanize = require_ms();
- createDebug.destroy = destroy;
- Object.keys(env2).forEach((key) => {
- createDebug[key] = env2[key];
- });
- createDebug.names = [];
- createDebug.skips = [];
- createDebug.formatters = {};
- function selectColor(namespace) {
- let hash2 = 0;
- for (let i2 = 0;i2 < namespace.length; i2++) {
- hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i2);
- hash2 |= 0;
- }
- return createDebug.colors[Math.abs(hash2) % createDebug.colors.length];
- }
- createDebug.selectColor = selectColor;
- function createDebug(namespace) {
- let prevTime;
- let enableOverride = null;
- let namespacesCache;
- let enabledCache;
- function debug2(...args) {
- if (!debug2.enabled) {
- return;
- }
- const self2 = debug2;
- const curr = Number(new Date);
- const ms = curr - (prevTime || curr);
- self2.diff = ms;
- self2.prev = prevTime;
- self2.curr = curr;
- prevTime = curr;
- args[0] = createDebug.coerce(args[0]);
- if (typeof args[0] !== "string") {
- args.unshift("%O");
- }
- let index2 = 0;
- args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format2) => {
- if (match === "%%") {
- return "%";
- }
- index2++;
- const formatter = createDebug.formatters[format2];
- if (typeof formatter === "function") {
- const val = args[index2];
- match = formatter.call(self2, val);
- args.splice(index2, 1);
- index2--;
- }
- return match;
- });
- createDebug.formatArgs.call(self2, args);
- const logFn = self2.log || createDebug.log;
- logFn.apply(self2, args);
- }
- debug2.namespace = namespace;
- debug2.useColors = createDebug.useColors();
- debug2.color = createDebug.selectColor(namespace);
- debug2.extend = extend2;
- debug2.destroy = createDebug.destroy;
- Object.defineProperty(debug2, "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;
- }
- });
- if (typeof createDebug.init === "function") {
- createDebug.init(debug2);
- }
- return debug2;
- }
- function extend2(namespace, delimiter) {
- const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
- newDebug.log = this.log;
- return newDebug;
- }
- function enable(namespaces) {
- createDebug.save(namespaces);
- createDebug.namespaces = namespaces;
- createDebug.names = [];
- createDebug.skips = [];
- const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
- for (const ns of split) {
- if (ns[0] === "-") {
- createDebug.skips.push(ns.slice(1));
- } else {
- createDebug.names.push(ns);
- }
- }
- }
- 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] === "*")) {
- if (template[templateIndex] === "*") {
- starIndex = templateIndex;
- matchIndex = searchIndex;
- templateIndex++;
- } else {
- searchIndex++;
- templateIndex++;
- }
- } else if (starIndex !== -1) {
- templateIndex = starIndex + 1;
- matchIndex++;
- searchIndex = matchIndex;
- } else {
- return false;
- }
- }
- while (templateIndex < template.length && template[templateIndex] === "*") {
- templateIndex++;
- }
- return templateIndex === template.length;
- }
- function disable() {
- const namespaces = [
- ...createDebug.names,
- ...createDebug.skips.map((namespace) => "-" + namespace)
- ].join(",");
- createDebug.enable("");
- return namespaces;
- }
- function enabled(name) {
- for (const skip of createDebug.skips) {
- if (matchesTemplate(name, skip)) {
- return false;
- }
- }
- for (const ns of createDebug.names) {
- if (matchesTemplate(name, ns)) {
- return true;
- }
- }
- return false;
- }
- function coerce(val) {
- if (val instanceof Error) {
- return val.stack || val.message;
- }
- return val;
- }
- function destroy() {
- console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
- }
- createDebug.enable(createDebug.load());
- return createDebug;
- }
- module.exports = setup;
-});
-
-// node_modules/debug/src/browser.js
-var require_browser = __commonJS((exports, module) => {
- exports.formatArgs = formatArgs;
- exports.save = save;
- exports.load = load2;
- 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`.");
- }
- };
- })();
- 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"
- ];
- function useColors() {
- if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
- return true;
- }
- if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
- return false;
- }
- let m;
- return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
- }
- 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 c3 = "color: " + this.color;
- args.splice(1, 0, c3, "color: inherit");
- let index2 = 0;
- let lastC = 0;
- args[0].replace(/%[a-zA-Z%]/g, (match) => {
- if (match === "%%") {
- return;
- }
- index2++;
- if (match === "%c") {
- lastC = index2;
- }
- });
- args.splice(lastC, 0, c3);
- }
- exports.log = console.debug || console.log || (() => {});
- function save(namespaces) {
- try {
- if (namespaces) {
- exports.storage.setItem("debug", namespaces);
- } else {
- exports.storage.removeItem("debug");
- }
- } catch (error) {}
- }
- function load2() {
- let r;
- try {
- r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
- } catch (error) {}
- if (!r && typeof process !== "undefined" && "env" in process) {
- r = process.env.DEBUG;
- }
- return r;
- }
- function localstorage() {
- try {
- return localStorage;
- } catch (error) {}
- }
- module.exports = require_common()(exports);
- var { formatters } = module.exports;
- formatters.j = function(v) {
- try {
- return JSON.stringify(v);
- } catch (error) {
- return "[UnexpectedJSONParseError]: " + error.message;
- }
- };
-});
-
-// node_modules/has-flag/index.js
-var require_has_flag = __commonJS((exports, module) => {
- module.exports = (flag, argv = process.argv) => {
- const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
- const position2 = argv.indexOf(prefix + flag);
- const terminatorPosition = argv.indexOf("--");
- return position2 !== -1 && (terminatorPosition === -1 || position2 < terminatorPosition);
- };
-});
-
-// node_modules/supports-color/index.js
-var require_supports_color = __commonJS((exports, module) => {
- var os2 = __require("os");
- var tty4 = __require("tty");
- var hasFlag2 = require_has_flag();
- var { env: env2 } = process;
- var forceColor;
- if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false") || hasFlag2("color=never")) {
- forceColor = 0;
- } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
- forceColor = 1;
- }
- if ("FORCE_COLOR" in env2) {
- if (env2.FORCE_COLOR === "true") {
- forceColor = 1;
- } else if (env2.FORCE_COLOR === "false") {
- forceColor = 0;
- } else {
- forceColor = env2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env2.FORCE_COLOR, 10), 3);
- }
- }
- function translateLevel2(level) {
- if (level === 0) {
- return false;
- }
- return {
- level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3
- };
- }
- function supportsColor2(haveStream, streamIsTTY) {
- if (forceColor === 0) {
- return 0;
- }
- if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
- return 3;
- }
- if (hasFlag2("color=256")) {
- return 2;
- }
- if (haveStream && !streamIsTTY && forceColor === undefined) {
- return 0;
- }
- const min = forceColor || 0;
- if (env2.TERM === "dumb") {
- return min;
- }
- if (process.platform === "win32") {
- const osRelease = os2.release().split(".");
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
- }
- return 1;
- }
- if ("CI" in env2) {
- if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => (sign in env2)) || env2.CI_NAME === "codeship") {
- return 1;
- }
- return min;
- }
- if ("TEAMCITY_VERSION" in env2) {
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env2.TEAMCITY_VERSION) ? 1 : 0;
- }
- if (env2.COLORTERM === "truecolor") {
- return 3;
- }
- if ("TERM_PROGRAM" in env2) {
- const version = parseInt((env2.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
- switch (env2.TERM_PROGRAM) {
- case "iTerm.app":
- return version >= 3 ? 3 : 2;
- case "Apple_Terminal":
- return 2;
- }
- }
- if (/-256(color)?$/i.test(env2.TERM)) {
- return 2;
- }
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env2.TERM)) {
- return 1;
- }
- if ("COLORTERM" in env2) {
- return 1;
- }
- return min;
- }
- function getSupportLevel(stream) {
- const level = supportsColor2(stream, stream && stream.isTTY);
- return translateLevel2(level);
- }
- module.exports = {
- supportsColor: getSupportLevel,
- stdout: translateLevel2(supportsColor2(true, tty4.isatty(1))),
- stderr: translateLevel2(supportsColor2(true, tty4.isatty(2)))
- };
-});
-
-// node_modules/debug/src/node.js
-var require_node = __commonJS((exports, module) => {
- var tty4 = __require("tty");
- var util = __require("util");
- exports.init = init;
- exports.log = log;
- exports.formatArgs = formatArgs;
- exports.save = save;
- exports.load = load2;
- 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`.");
- exports.colors = [6, 2, 3, 4, 5, 1];
- try {
- const supportsColor2 = require_supports_color();
- if (supportsColor2 && (supportsColor2.stderr || supportsColor2).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) {}
- exports.inspectOpts = Object.keys(process.env).filter((key) => {
- return /^debug_/i.test(key);
- }).reduce((obj, key) => {
- const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
- return k.toUpperCase();
- });
- 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;
- }, {});
- function useColors() {
- return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty4.isatty(process.stderr.fd);
- }
- function formatArgs(args) {
- const { namespace: name, useColors: useColors2 } = this;
- if (useColors2) {
- const c3 = this.color;
- const colorCode = "\x1B[3" + (c3 < 8 ? c3 : "8;5;" + c3);
- const prefix = ` ${colorCode};1m${name} \x1B[0m`;
- args[0] = prefix + args[0].split(`
-`).join(`
-` + prefix);
- args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
- } else {
- args[0] = getDate() + name + " " + args[0];
- }
- }
- function getDate() {
- if (exports.inspectOpts.hideDate) {
- return "";
- }
- return new Date().toISOString() + " ";
- }
- function log(...args) {
- return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + `
-`);
- }
- function save(namespaces) {
- if (namespaces) {
- process.env.DEBUG = namespaces;
- } else {
- delete process.env.DEBUG;
- }
- }
- function load2() {
- return process.env.DEBUG;
- }
- function init(debug2) {
- debug2.inspectOpts = {};
- const keys2 = Object.keys(exports.inspectOpts);
- for (let i2 = 0;i2 < keys2.length; i2++) {
- debug2.inspectOpts[keys2[i2]] = exports.inspectOpts[keys2[i2]];
- }
- }
- module.exports = require_common()(exports);
- var { formatters } = module.exports;
- formatters.o = function(v) {
- this.inspectOpts.colors = this.useColors;
- return util.inspect(v, this.inspectOpts).split(`
-`).map((str) => str.trim()).join(" ");
- };
- formatters.O = function(v) {
- this.inspectOpts.colors = this.useColors;
- return util.inspect(v, this.inspectOpts);
- };
-});
-
-// node_modules/debug/src/index.js
-var require_src = __commonJS((exports, module) => {
- if (typeof process === "undefined" || process.type === "renderer" || false || process.__nwjs) {
- module.exports = require_browser();
- } else {
- module.exports = require_node();
- }
-});
-
-// node_modules/follow-redirects/debug.js
-var require_debug = __commonJS((exports, module) => {
- var debug2;
- module.exports = function() {
- if (!debug2) {
- try {
- debug2 = require_src()("follow-redirects");
- } catch (error) {}
- if (typeof debug2 !== "function") {
- debug2 = function() {};
- }
- }
- debug2.apply(null, arguments);
- };
-});
-
-// node_modules/follow-redirects/index.js
-var require_follow_redirects = __commonJS((exports, module) => {
- var url2 = __require("url");
- var URL2 = url2.URL;
- var http = __require("http");
- var https = __require("https");
- var Writable4 = __require("stream").Writable;
- var assert = __require("assert");
- var debug2 = require_debug();
- (function detectUnsupportedEnvironment() {
- var looksLikeNode = typeof process !== "undefined";
- var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined";
- var looksLikeV8 = isFunction3(Error.captureStackTrace);
- if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) {
- console.warn("The follow-redirects package should be excluded from browser builds.");
- }
- })();
- var useNativeURL = false;
- try {
- assert(new URL2(""));
- } catch (error) {
- useNativeURL = error.code === "ERR_INVALID_URL";
- }
- var preservedUrlFields = [
- "auth",
- "host",
- "hostname",
- "href",
- "path",
- "pathname",
- "port",
- "protocol",
- "query",
- "search",
- "hash"
- ];
- var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
- var eventHandlers = Object.create(null);
- events.forEach(function(event) {
- eventHandlers[event] = function(arg1, arg2, arg3) {
- this._redirectable.emit(event, arg1, arg2, arg3);
- };
- });
- var InvalidUrlError = createErrorType("ERR_INVALID_URL", "Invalid URL", TypeError);
- var RedirectionError = createErrorType("ERR_FR_REDIRECTION_FAILURE", "Redirected request failed");
- var TooManyRedirectsError = createErrorType("ERR_FR_TOO_MANY_REDIRECTS", "Maximum number of redirects exceeded", RedirectionError);
- var MaxBodyLengthExceededError = createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED", "Request body larger than maxBodyLength limit");
- var WriteAfterEndError = createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end");
- var destroy = Writable4.prototype.destroy || noop6;
- function RedirectableRequest(options2, responseCallback) {
- Writable4.call(this);
- this._sanitizeOptions(options2);
- this._options = options2;
- this._ended = false;
- this._ending = false;
- this._redirectCount = 0;
- this._redirects = [];
- this._requestBodyLength = 0;
- this._requestBodyBuffers = [];
- if (responseCallback) {
- this.on("response", responseCallback);
- }
- var self2 = this;
- this._onNativeResponse = function(response) {
- try {
- self2._processResponse(response);
- } catch (cause) {
- self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause }));
- }
- };
- this._performRequest();
- }
- RedirectableRequest.prototype = Object.create(Writable4.prototype);
- RedirectableRequest.prototype.abort = function() {
- destroyRequest(this._currentRequest);
- this._currentRequest.abort();
- this.emit("abort");
- };
- RedirectableRequest.prototype.destroy = function(error) {
- destroyRequest(this._currentRequest, error);
- destroy.call(this, error);
- return this;
- };
- RedirectableRequest.prototype.write = function(data, encoding, callback) {
- if (this._ending) {
- throw new WriteAfterEndError;
- }
- if (!isString2(data) && !isBuffer3(data)) {
- throw new TypeError("data should be a string, Buffer or Uint8Array");
- }
- if (isFunction3(encoding)) {
- callback = encoding;
- encoding = null;
- }
- if (data.length === 0) {
- if (callback) {
- callback();
- }
- return;
- }
- if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
- this._requestBodyLength += data.length;
- this._requestBodyBuffers.push({ data, encoding });
- this._currentRequest.write(data, encoding, callback);
- } else {
- this.emit("error", new MaxBodyLengthExceededError);
- this.abort();
- }
- };
- RedirectableRequest.prototype.end = function(data, encoding, callback) {
- if (isFunction3(data)) {
- callback = data;
- data = encoding = null;
- } else if (isFunction3(encoding)) {
- callback = encoding;
- encoding = null;
- }
- if (!data) {
- this._ended = this._ending = true;
- this._currentRequest.end(null, null, callback);
- } else {
- var self2 = this;
- var currentRequest = this._currentRequest;
- this.write(data, encoding, function() {
- self2._ended = true;
- currentRequest.end(null, null, callback);
- });
- this._ending = true;
- }
- };
- RedirectableRequest.prototype.setHeader = function(name, value) {
- this._options.headers[name] = value;
- this._currentRequest.setHeader(name, value);
- };
- RedirectableRequest.prototype.removeHeader = function(name) {
- delete this._options.headers[name];
- this._currentRequest.removeHeader(name);
- };
- RedirectableRequest.prototype.setTimeout = function(msecs, callback) {
- var self2 = this;
- function destroyOnTimeout(socket) {
- socket.setTimeout(msecs);
- socket.removeListener("timeout", socket.destroy);
- socket.addListener("timeout", socket.destroy);
- }
- function startTimer(socket) {
- if (self2._timeout) {
- clearTimeout(self2._timeout);
- }
- self2._timeout = setTimeout(function() {
- self2.emit("timeout");
- clearTimer();
- }, msecs);
- destroyOnTimeout(socket);
- }
- function clearTimer() {
- if (self2._timeout) {
- clearTimeout(self2._timeout);
- self2._timeout = null;
- }
- self2.removeListener("abort", clearTimer);
- self2.removeListener("error", clearTimer);
- self2.removeListener("response", clearTimer);
- self2.removeListener("close", clearTimer);
- if (callback) {
- self2.removeListener("timeout", callback);
- }
- if (!self2.socket) {
- self2._currentRequest.removeListener("socket", startTimer);
- }
- }
- if (callback) {
- this.on("timeout", callback);
- }
- if (this.socket) {
- startTimer(this.socket);
- } else {
- this._currentRequest.once("socket", startTimer);
- }
- this.on("socket", destroyOnTimeout);
- this.on("abort", clearTimer);
- this.on("error", clearTimer);
- this.on("response", clearTimer);
- this.on("close", clearTimer);
- return this;
- };
- [
- "flushHeaders",
- "getHeader",
- "setNoDelay",
- "setSocketKeepAlive"
- ].forEach(function(method) {
- RedirectableRequest.prototype[method] = function(a2, b) {
- return this._currentRequest[method](a2, b);
- };
- });
- ["aborted", "connection", "socket"].forEach(function(property2) {
- Object.defineProperty(RedirectableRequest.prototype, property2, {
- get: function() {
- return this._currentRequest[property2];
- }
- });
- });
- RedirectableRequest.prototype._sanitizeOptions = function(options2) {
- if (!options2.headers) {
- options2.headers = {};
- }
- if (options2.host) {
- if (!options2.hostname) {
- options2.hostname = options2.host;
- }
- delete options2.host;
- }
- if (!options2.pathname && options2.path) {
- var searchPos = options2.path.indexOf("?");
- if (searchPos < 0) {
- options2.pathname = options2.path;
- } else {
- options2.pathname = options2.path.substring(0, searchPos);
- options2.search = options2.path.substring(searchPos);
- }
- }
- };
- RedirectableRequest.prototype._performRequest = function() {
- var protocol = this._options.protocol;
- var nativeProtocol = this._options.nativeProtocols[protocol];
- if (!nativeProtocol) {
- throw new TypeError("Unsupported protocol " + protocol);
- }
- if (this._options.agents) {
- var scheme = protocol.slice(0, -1);
- this._options.agent = this._options.agents[scheme];
- }
- var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse);
- request._redirectable = this;
- for (var event of events) {
- request.on(event, eventHandlers[event]);
- }
- this._currentUrl = /^\//.test(this._options.path) ? url2.format(this._options) : this._options.path;
- if (this._isRedirect) {
- var i2 = 0;
- var self2 = this;
- var buffers = this._requestBodyBuffers;
- (function writeNext(error) {
- if (request === self2._currentRequest) {
- if (error) {
- self2.emit("error", error);
- } else if (i2 < buffers.length) {
- var buffer = buffers[i2++];
- if (!request.finished) {
- request.write(buffer.data, buffer.encoding, writeNext);
- }
- } else if (self2._ended) {
- request.end();
- }
- }
- })();
- }
- };
- RedirectableRequest.prototype._processResponse = function(response) {
- var statusCode = response.statusCode;
- if (this._options.trackRedirects) {
- this._redirects.push({
- url: this._currentUrl,
- headers: response.headers,
- statusCode
- });
- }
- var location = response.headers.location;
- if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) {
- response.responseUrl = this._currentUrl;
- response.redirects = this._redirects;
- this.emit("response", response);
- this._requestBodyBuffers = [];
- return;
- }
- destroyRequest(this._currentRequest);
- response.destroy();
- if (++this._redirectCount > this._options.maxRedirects) {
- throw new TooManyRedirectsError;
- }
- var requestHeaders;
- var beforeRedirect = this._options.beforeRedirect;
- if (beforeRedirect) {
- requestHeaders = Object.assign({
- Host: response.req.getHeader("host")
- }, this._options.headers);
- }
- var method = this._options.method;
- if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) {
- this._options.method = "GET";
- this._requestBodyBuffers = [];
- removeMatchingHeaders(/^content-/i, this._options.headers);
- }
- var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
- var currentUrlParts = parseUrl2(this._currentUrl);
- var currentHost = currentHostHeader || currentUrlParts.host;
- var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url2.format(Object.assign(currentUrlParts, { host: currentHost }));
- var redirectUrl = resolveUrl(location, currentUrl);
- debug2("redirecting to", redirectUrl.href);
- this._isRedirect = true;
- spreadUrlObject(redirectUrl, this._options);
- if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) {
- removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
- }
- if (isFunction3(beforeRedirect)) {
- var responseDetails = {
- headers: response.headers,
- statusCode
- };
- var requestDetails = {
- url: currentUrl,
- method,
- headers: requestHeaders
- };
- beforeRedirect(this._options, responseDetails, requestDetails);
- this._sanitizeOptions(this._options);
- }
- this._performRequest();
- };
- function wrap(protocols) {
- var exports2 = {
- maxRedirects: 21,
- maxBodyLength: 10 * 1024 * 1024
- };
- var nativeProtocols = {};
- Object.keys(protocols).forEach(function(scheme) {
- var protocol = scheme + ":";
- var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
- var wrappedProtocol = exports2[scheme] = Object.create(nativeProtocol);
- function request(input, options2, callback) {
- if (isURL(input)) {
- input = spreadUrlObject(input);
- } else if (isString2(input)) {
- input = spreadUrlObject(parseUrl2(input));
- } else {
- callback = options2;
- options2 = validateUrl(input);
- input = { protocol };
- }
- if (isFunction3(options2)) {
- callback = options2;
- options2 = null;
- }
- options2 = Object.assign({
- maxRedirects: exports2.maxRedirects,
- maxBodyLength: exports2.maxBodyLength
- }, input, options2);
- options2.nativeProtocols = nativeProtocols;
- if (!isString2(options2.host) && !isString2(options2.hostname)) {
- options2.hostname = "::1";
- }
- assert.equal(options2.protocol, protocol, "protocol mismatch");
- debug2("options", options2);
- return new RedirectableRequest(options2, callback);
- }
- function get2(input, options2, callback) {
- var wrappedRequest = wrappedProtocol.request(input, options2, callback);
- wrappedRequest.end();
- return wrappedRequest;
- }
- Object.defineProperties(wrappedProtocol, {
- request: { value: request, configurable: true, enumerable: true, writable: true },
- get: { value: get2, configurable: true, enumerable: true, writable: true }
- });
- });
- return exports2;
- }
- function noop6() {}
- function parseUrl2(input) {
- var parsed;
- if (useNativeURL) {
- parsed = new URL2(input);
- } else {
- parsed = validateUrl(url2.parse(input));
- if (!isString2(parsed.protocol)) {
- throw new InvalidUrlError({ input });
- }
- }
- return parsed;
- }
- function resolveUrl(relative, base2) {
- return useNativeURL ? new URL2(relative, base2) : parseUrl2(url2.resolve(base2, relative));
- }
- function validateUrl(input) {
- if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
- throw new InvalidUrlError({ input: input.href || input });
- }
- if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
- throw new InvalidUrlError({ input: input.href || input });
- }
- return input;
- }
- function spreadUrlObject(urlObject, target) {
- var spread = target || {};
- for (var key of preservedUrlFields) {
- spread[key] = urlObject[key];
- }
- if (spread.hostname.startsWith("[")) {
- spread.hostname = spread.hostname.slice(1, -1);
- }
- if (spread.port !== "") {
- spread.port = Number(spread.port);
- }
- spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
- return spread;
- }
- function removeMatchingHeaders(regex2, headers) {
- var lastValue;
- for (var header in headers) {
- if (regex2.test(header)) {
- lastValue = headers[header];
- delete headers[header];
- }
- }
- return lastValue === null || typeof lastValue === "undefined" ? undefined : String(lastValue).trim();
- }
- function createErrorType(code, message, baseClass) {
- function CustomError(properties) {
- if (isFunction3(Error.captureStackTrace)) {
- Error.captureStackTrace(this, this.constructor);
- }
- Object.assign(this, properties || {});
- this.code = code;
- this.message = this.cause ? message + ": " + this.cause.message : message;
- }
- CustomError.prototype = new (baseClass || Error);
- Object.defineProperties(CustomError.prototype, {
- constructor: {
- value: CustomError,
- enumerable: false
- },
- name: {
- value: "Error [" + code + "]",
- enumerable: false
- }
- });
- return CustomError;
- }
- function destroyRequest(request, error) {
- for (var event of events) {
- request.removeListener(event, eventHandlers[event]);
- }
- request.on("error", noop6);
- request.destroy(error);
- }
- function isSubdomain(subdomain, domain) {
- assert(isString2(subdomain) && isString2(domain));
- var dot = subdomain.length - domain.length - 1;
- return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
- }
- function isString2(value) {
- return typeof value === "string" || value instanceof String;
- }
- function isFunction3(value) {
- return typeof value === "function";
- }
- function isBuffer3(value) {
- return typeof value === "object" && "length" in value;
- }
- function isURL(value) {
- return URL2 && value instanceof URL2;
- }
- module.exports = wrap({ http, https });
- module.exports.wrap = wrap;
-});
-
-// node_modules/axios/lib/env/data.js
-var VERSION2 = "1.14.0";
-
-// node_modules/axios/lib/helpers/parseProtocol.js
-function parseProtocol(url2) {
- const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url2);
- return match && match[1] || "";
-}
-
-// node_modules/axios/lib/helpers/fromDataURI.js
-function fromDataURI(uri, asBlob, options2) {
- const _Blob = options2 && options2.Blob || platform_default.classes.Blob;
- const protocol = parseProtocol(uri);
- if (asBlob === undefined && _Blob) {
- asBlob = true;
- }
- if (protocol === "data") {
- uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
- const match = DATA_URL_PATTERN.exec(uri);
- if (!match) {
- throw new AxiosError_default("Invalid URL", AxiosError_default.ERR_INVALID_URL);
- }
- const mime = match[1];
- const isBase64 = match[2];
- const body = match[3];
- const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? "base64" : "utf8");
- if (asBlob) {
- if (!_Blob) {
- throw new AxiosError_default("Blob is not supported", AxiosError_default.ERR_NOT_SUPPORT);
- }
- return new _Blob([buffer], { type: mime });
- }
- return buffer;
- }
- throw new AxiosError_default("Unsupported protocol " + protocol, AxiosError_default.ERR_NOT_SUPPORT);
-}
-var DATA_URL_PATTERN;
-var init_fromDataURI = __esm(() => {
- init_AxiosError();
- init_platform();
- DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
-});
-
-// node_modules/axios/lib/helpers/AxiosTransformStream.js
-import stream from "stream";
-var kInternals, AxiosTransformStream, AxiosTransformStream_default;
-var init_AxiosTransformStream = __esm(() => {
- init_utils();
- kInternals = Symbol("internals");
- AxiosTransformStream = class AxiosTransformStream extends stream.Transform {
- constructor(options2) {
- options2 = utils_default.toFlatObject(options2, {
- maxRate: 0,
- chunkSize: 64 * 1024,
- minChunkSize: 100,
- timeWindow: 500,
- ticksRate: 2,
- samplesCount: 15
- }, null, (prop, source) => {
- return !utils_default.isUndefined(source[prop]);
- });
- super({
- readableHighWaterMark: options2.chunkSize
- });
- const internals = this[kInternals] = {
- timeWindow: options2.timeWindow,
- chunkSize: options2.chunkSize,
- maxRate: options2.maxRate,
- minChunkSize: options2.minChunkSize,
- bytesSeen: 0,
- isCaptured: false,
- notifiedBytesLoaded: 0,
- ts: Date.now(),
- bytes: 0,
- onReadCallback: null
- };
- this.on("newListener", (event) => {
- if (event === "progress") {
- if (!internals.isCaptured) {
- internals.isCaptured = true;
- }
- }
- });
- }
- _read(size) {
- const internals = this[kInternals];
- if (internals.onReadCallback) {
- internals.onReadCallback();
- }
- return super._read(size);
- }
- _transform(chunk, encoding, callback) {
- const internals = this[kInternals];
- const maxRate = internals.maxRate;
- const readableHighWaterMark = this.readableHighWaterMark;
- const timeWindow = internals.timeWindow;
- const divider = 1000 / timeWindow;
- const bytesThreshold = maxRate / divider;
- const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
- const pushChunk = (_chunk, _callback) => {
- const bytes = Buffer.byteLength(_chunk);
- internals.bytesSeen += bytes;
- internals.bytes += bytes;
- internals.isCaptured && this.emit("progress", internals.bytesSeen);
- if (this.push(_chunk)) {
- process.nextTick(_callback);
- } else {
- internals.onReadCallback = () => {
- internals.onReadCallback = null;
- process.nextTick(_callback);
- };
- }
- };
- const transformChunk2 = (_chunk, _callback) => {
- const chunkSize = Buffer.byteLength(_chunk);
- let chunkRemainder = null;
- let maxChunkSize = readableHighWaterMark;
- let bytesLeft;
- let passed = 0;
- if (maxRate) {
- const now = Date.now();
- if (!internals.ts || (passed = now - internals.ts) >= timeWindow) {
- internals.ts = now;
- bytesLeft = bytesThreshold - internals.bytes;
- internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
- passed = 0;
- }
- bytesLeft = bytesThreshold - internals.bytes;
- }
- if (maxRate) {
- if (bytesLeft <= 0) {
- return setTimeout(() => {
- _callback(null, _chunk);
- }, timeWindow - passed);
- }
- if (bytesLeft < maxChunkSize) {
- maxChunkSize = bytesLeft;
- }
- }
- if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) {
- chunkRemainder = _chunk.subarray(maxChunkSize);
- _chunk = _chunk.subarray(0, maxChunkSize);
- }
- pushChunk(_chunk, chunkRemainder ? () => {
- process.nextTick(_callback, null, chunkRemainder);
- } : _callback);
- };
- transformChunk2(chunk, function transformNextChunk(err, _chunk) {
- if (err) {
- return callback(err);
- }
- if (_chunk) {
- transformChunk2(_chunk, transformNextChunk);
- } else {
- callback(null);
- }
- });
- }
- };
- AxiosTransformStream_default = AxiosTransformStream;
-});
-
-// node_modules/axios/lib/helpers/readBlob.js
-var asyncIterator, readBlob = async function* (blob) {
- if (blob.stream) {
- yield* blob.stream();
- } else if (blob.arrayBuffer) {
- yield await blob.arrayBuffer();
- } else if (blob[asyncIterator]) {
- yield* blob[asyncIterator]();
- } else {
- yield blob;
- }
-}, readBlob_default;
-var init_readBlob = __esm(() => {
- ({ asyncIterator } = Symbol);
- readBlob_default = readBlob;
-});
-
-// node_modules/axios/lib/helpers/formDataToStream.js
-import util from "util";
-import { Readable as Readable4 } from "stream";
-
-class FormDataPart {
- constructor(name, value) {
- const { escapeName } = this.constructor;
- const isStringValue = utils_default.isString(value);
- let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF}`;
- if (isStringValue) {
- value = textEncoder3.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
- } else {
- headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`;
- }
- this.headers = textEncoder3.encode(headers + CRLF);
- this.contentLength = isStringValue ? value.byteLength : value.size;
- this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
- this.name = name;
- this.value = value;
- }
- async* encode() {
- yield this.headers;
- const { value } = this;
- if (utils_default.isTypedArray(value)) {
- yield value;
- } else {
- yield* readBlob_default(value);
- }
- yield CRLF_BYTES;
- }
- static escapeName(name) {
- return String(name).replace(/[\r\n"]/g, (match) => ({
- "\r": "%0D",
- "\n": "%0A",
- '"': "%22"
- })[match]);
- }
-}
-var BOUNDARY_ALPHABET, textEncoder3, CRLF = `\r
-`, CRLF_BYTES, CRLF_BYTES_COUNT = 2, formDataToStream = (form, headersHandler, options2) => {
- const {
- tag: tag2 = "form-data-boundary",
- size = 25,
- boundary = tag2 + "-" + platform_default.generateString(size, BOUNDARY_ALPHABET)
- } = options2 || {};
- if (!utils_default.isFormData(form)) {
- throw TypeError("FormData instance required");
- }
- if (boundary.length < 1 || boundary.length > 70) {
- throw Error("boundary must be 10-70 characters long");
- }
- const boundaryBytes = textEncoder3.encode("--" + boundary + CRLF);
- const footerBytes = textEncoder3.encode("--" + boundary + "--" + CRLF);
- let contentLength = footerBytes.byteLength;
- const parts = Array.from(form.entries()).map(([name, value]) => {
- const part = new FormDataPart(name, value);
- contentLength += part.size;
- return part;
- });
- contentLength += boundaryBytes.byteLength * parts.length;
- contentLength = utils_default.toFiniteNumber(contentLength);
- const computedHeaders = {
- "Content-Type": `multipart/form-data; boundary=${boundary}`
- };
- if (Number.isFinite(contentLength)) {
- computedHeaders["Content-Length"] = contentLength;
- }
- headersHandler && headersHandler(computedHeaders);
- return Readable4.from(async function* () {
- for (const part of parts) {
- yield boundaryBytes;
- yield* part.encode();
- }
- yield footerBytes;
- }());
-}, formDataToStream_default;
-var init_formDataToStream = __esm(() => {
- init_utils();
- init_readBlob();
- init_platform();
- BOUNDARY_ALPHABET = platform_default.ALPHABET.ALPHA_DIGIT + "-_";
- textEncoder3 = typeof TextEncoder === "function" ? new TextEncoder : new util.TextEncoder;
- CRLF_BYTES = textEncoder3.encode(CRLF);
- formDataToStream_default = formDataToStream;
-});
-
-// node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js
-import stream2 from "stream";
-var ZlibHeaderTransformStream, ZlibHeaderTransformStream_default;
-var init_ZlibHeaderTransformStream = __esm(() => {
- ZlibHeaderTransformStream = class ZlibHeaderTransformStream extends stream2.Transform {
- __transform(chunk, encoding, callback) {
- this.push(chunk);
- callback();
- }
- _transform(chunk, encoding, callback) {
- if (chunk.length !== 0) {
- this._transform = this.__transform;
- if (chunk[0] !== 120) {
- const header = Buffer.alloc(2);
- header[0] = 120;
- header[1] = 156;
- this.push(header, encoding);
- }
- }
- this.__transform(chunk, encoding, callback);
- }
- };
- ZlibHeaderTransformStream_default = ZlibHeaderTransformStream;
-});
-
-// node_modules/axios/lib/helpers/callbackify.js
-var callbackify5 = (fn, reducer) => {
- return utils_default.isAsyncFn(fn) ? function(...args) {
- const cb = args.pop();
- fn.apply(this, args).then((value) => {
- try {
- reducer ? cb(null, ...reducer(value)) : cb(null, value);
- } catch (err) {
- cb(err);
- }
- }, cb);
- } : fn;
-}, callbackify_default;
-var init_callbackify = __esm(() => {
- init_utils();
- callbackify_default = callbackify5;
-});
-
-// node_modules/axios/lib/helpers/speedometer.js
-function speedometer(samplesCount, min) {
- samplesCount = samplesCount || 10;
- const bytes = new Array(samplesCount);
- const timestamps = new Array(samplesCount);
- let head = 0;
- let tail = 0;
- let firstSampleTS;
- min = min !== undefined ? min : 1000;
- return function push(chunkLength) {
- const now = Date.now();
- const startedAt = timestamps[tail];
- if (!firstSampleTS) {
- firstSampleTS = now;
- }
- bytes[head] = chunkLength;
- timestamps[head] = now;
- let i2 = tail;
- let bytesCount = 0;
- while (i2 !== head) {
- bytesCount += bytes[i2++];
- i2 = i2 % samplesCount;
- }
- head = (head + 1) % samplesCount;
- if (head === tail) {
- tail = (tail + 1) % samplesCount;
- }
- if (now - firstSampleTS < min) {
- return;
- }
- const passed = startedAt && now - startedAt;
- return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
- };
-}
-var speedometer_default;
-var init_speedometer = __esm(() => {
- speedometer_default = speedometer;
-});
-
-// node_modules/axios/lib/helpers/throttle.js
-function throttle(fn, freq) {
- let timestamp = 0;
- let threshold = 1000 / freq;
- let lastArgs;
- let timer;
- const invoke = (args, now = Date.now()) => {
- timestamp = now;
- lastArgs = null;
- if (timer) {
- clearTimeout(timer);
- timer = null;
- }
- fn(...args);
- };
- const throttled = (...args) => {
- const now = Date.now();
- const passed = now - timestamp;
- if (passed >= threshold) {
- invoke(args, now);
- } else {
- lastArgs = args;
- if (!timer) {
- timer = setTimeout(() => {
- timer = null;
- invoke(lastArgs);
- }, threshold - passed);
- }
- }
- };
- const flush = () => lastArgs && invoke(lastArgs);
- return [throttled, flush];
-}
-var throttle_default;
-var init_throttle = __esm(() => {
- throttle_default = throttle;
-});
-
-// node_modules/axios/lib/helpers/progressEventReducer.js
-var progressEventReducer = (listener, isDownloadStream, freq = 3) => {
- let bytesNotified = 0;
- const _speedometer = speedometer_default(50, 250);
- return throttle_default((e) => {
- const loaded = e.loaded;
- const total = e.lengthComputable ? e.total : undefined;
- const progressBytes = loaded - bytesNotified;
- const rate = _speedometer(progressBytes);
- const inRange2 = loaded <= total;
- bytesNotified = loaded;
- const data = {
- loaded,
- total,
- progress: total ? loaded / total : undefined,
- bytes: progressBytes,
- rate: rate ? rate : undefined,
- estimated: rate && total && inRange2 ? (total - loaded) / rate : undefined,
- event: e,
- lengthComputable: total != null,
- [isDownloadStream ? "download" : "upload"]: true
- };
- listener(data);
- }, freq);
-}, progressEventDecorator = (total, throttled) => {
- const lengthComputable = total != null;
- return [
- (loaded) => throttled[0]({
- lengthComputable,
- total,
- loaded
- }),
- throttled[1]
- ];
-}, asyncDecorator = (fn) => (...args) => utils_default.asap(() => fn(...args));
-var init_progressEventReducer = __esm(() => {
- init_speedometer();
- init_throttle();
- init_utils();
-});
-
-// node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js
-function estimateDataURLDecodedBytes(url2) {
- if (!url2 || typeof url2 !== "string")
- return 0;
- if (!url2.startsWith("data:"))
- return 0;
- const comma = url2.indexOf(",");
- if (comma < 0)
- return 0;
- const meta = url2.slice(5, comma);
- const body = url2.slice(comma + 1);
- const isBase64 = /;base64/i.test(meta);
- if (isBase64) {
- let effectiveLen = body.length;
- const len = body.length;
- for (let i2 = 0;i2 < len; i2++) {
- if (body.charCodeAt(i2) === 37 && i2 + 2 < len) {
- const a2 = body.charCodeAt(i2 + 1);
- const b = body.charCodeAt(i2 + 2);
- const isHex = (a2 >= 48 && a2 <= 57 || a2 >= 65 && a2 <= 70 || a2 >= 97 && a2 <= 102) && (b >= 48 && b <= 57 || b >= 65 && b <= 70 || b >= 97 && b <= 102);
- if (isHex) {
- effectiveLen -= 2;
- i2 += 2;
- }
- }
- }
- let pad = 0;
- let idx = len - 1;
- const tailIsPct3D = (j) => j >= 2 && body.charCodeAt(j - 2) === 37 && body.charCodeAt(j - 1) === 51 && (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100);
- if (idx >= 0) {
- if (body.charCodeAt(idx) === 61) {
- pad++;
- idx--;
- } else if (tailIsPct3D(idx)) {
- pad++;
- idx -= 3;
- }
- }
- if (pad === 1 && idx >= 0) {
- if (body.charCodeAt(idx) === 61) {
- pad++;
- } else if (tailIsPct3D(idx)) {
- pad++;
- }
- }
- const groups = Math.floor(effectiveLen / 4);
- const bytes = groups * 3 - (pad || 0);
- return bytes > 0 ? bytes : 0;
- }
- return Buffer.byteLength(body, "utf8");
-}
-
-// node_modules/axios/lib/adapters/http.js
-import http from "http";
-import https from "https";
-import http2 from "http2";
-import util2 from "util";
-import zlib from "zlib";
-import stream3 from "stream";
-import { EventEmitter as EventEmitter2 } from "events";
-
-class Http2Sessions {
- constructor() {
- this.sessions = Object.create(null);
- }
- getSession(authority, options2) {
- options2 = Object.assign({
- sessionTimeout: 1000
- }, options2);
- let authoritySessions = this.sessions[authority];
- if (authoritySessions) {
- let len = authoritySessions.length;
- for (let i2 = 0;i2 < len; i2++) {
- const [sessionHandle, sessionOptions] = authoritySessions[i2];
- if (!sessionHandle.destroyed && !sessionHandle.closed && util2.isDeepStrictEqual(sessionOptions, options2)) {
- return sessionHandle;
- }
- }
- }
- const session = http2.connect(authority, options2);
- let removed;
- const removeSession = () => {
- if (removed) {
- return;
- }
- removed = true;
- let entries = authoritySessions, len = entries.length, i2 = len;
- while (i2--) {
- if (entries[i2][0] === session) {
- if (len === 1) {
- delete this.sessions[authority];
- } else {
- entries.splice(i2, 1);
- }
- if (!session.closed) {
- session.close();
- }
- return;
- }
- }
- };
- const originalRequestFn = session.request;
- const { sessionTimeout } = options2;
- if (sessionTimeout != null) {
- let timer;
- let streamsCount = 0;
- session.request = function() {
- const stream4 = originalRequestFn.apply(this, arguments);
- streamsCount++;
- if (timer) {
- clearTimeout(timer);
- timer = null;
- }
- stream4.once("close", () => {
- if (!--streamsCount) {
- timer = setTimeout(() => {
- timer = null;
- removeSession();
- }, sessionTimeout);
- }
- });
- return stream4;
- };
- }
- session.once("close", removeSession);
- let entry = [session, options2];
- authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry];
- return session;
- }
-}
-function dispatchBeforeRedirect(options2, responseDetails) {
- if (options2.beforeRedirects.proxy) {
- options2.beforeRedirects.proxy(options2);
- }
- if (options2.beforeRedirects.config) {
- options2.beforeRedirects.config(options2, responseDetails);
- }
-}
-function setProxy(options2, configProxy, location) {
- let proxy = configProxy;
- if (!proxy && proxy !== false) {
- const proxyUrl = getProxyForUrl(location);
- if (proxyUrl) {
- proxy = new URL(proxyUrl);
- }
- }
- if (proxy) {
- if (proxy.username) {
- proxy.auth = (proxy.username || "") + ":" + (proxy.password || "");
- }
- if (proxy.auth) {
- const validProxyAuth = Boolean(proxy.auth.username || proxy.auth.password);
- if (validProxyAuth) {
- proxy.auth = (proxy.auth.username || "") + ":" + (proxy.auth.password || "");
- } else if (typeof proxy.auth === "object") {
- throw new AxiosError_default("Invalid proxy authorization", AxiosError_default.ERR_BAD_OPTION, { proxy });
- }
- const base64 = Buffer.from(proxy.auth, "utf8").toString("base64");
- options2.headers["Proxy-Authorization"] = "Basic " + base64;
- }
- options2.headers.host = options2.hostname + (options2.port ? ":" + options2.port : "");
- const proxyHost = proxy.hostname || proxy.host;
- options2.hostname = proxyHost;
- options2.host = proxyHost;
- options2.port = proxy.port;
- options2.path = location;
- if (proxy.protocol) {
- options2.protocol = proxy.protocol.includes(":") ? proxy.protocol : `${proxy.protocol}:`;
- }
- }
- options2.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
- setProxy(redirectOptions, configProxy, redirectOptions.href);
- };
-}
-var import_follow_redirects, zlibOptions, brotliOptions, isBrotliSupported, httpFollow, httpsFollow, isHttps, supportedProtocols, flushOnFinish = (stream4, [throttled, flush]) => {
- stream4.on("end", flush).on("error", flush);
- return throttled;
-}, http2Sessions, isHttpAdapterSupported, wrapAsync = (asyncExecutor) => {
- return new Promise((resolve2, reject) => {
- let onDone;
- let isDone;
- const done = (value, isRejected) => {
- if (isDone)
- return;
- isDone = true;
- onDone && onDone(value, isRejected);
- };
- const _resolve = (value) => {
- done(value);
- resolve2(value);
- };
- const _reject = (reason) => {
- done(reason, true);
- reject(reason);
- };
- asyncExecutor(_resolve, _reject, (onDoneHandler) => onDone = onDoneHandler).catch(_reject);
- });
-}, resolveFamily = ({ address, family }) => {
- if (!utils_default.isString(address)) {
- throw TypeError("address must be a string");
- }
- return {
- address,
- family: family || (address.indexOf(".") < 0 ? 6 : 4)
- };
-}, buildAddressEntry = (address, family) => resolveFamily(utils_default.isObject(address) ? address : { address, family }), http2Transport, http_default;
-var init_http = __esm(() => {
- init_utils();
- init_settle();
- init_buildFullPath();
- init_buildURL();
- init_proxy_from_env();
- init_transitional();
- init_AxiosError();
- init_CanceledError();
- init_platform();
- init_fromDataURI();
- init_AxiosHeaders();
- init_AxiosTransformStream();
- init_formDataToStream();
- init_readBlob();
- init_ZlibHeaderTransformStream();
- init_callbackify();
- init_progressEventReducer();
- import_follow_redirects = __toESM(require_follow_redirects(), 1);
- zlibOptions = {
- flush: zlib.constants.Z_SYNC_FLUSH,
- finishFlush: zlib.constants.Z_SYNC_FLUSH
- };
- brotliOptions = {
- flush: zlib.constants.BROTLI_OPERATION_FLUSH,
- finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
- };
- isBrotliSupported = utils_default.isFunction(zlib.createBrotliDecompress);
- ({ http: httpFollow, https: httpsFollow } = import_follow_redirects.default);
- isHttps = /https:?/;
- supportedProtocols = platform_default.protocols.map((protocol) => {
- return protocol + ":";
- });
- http2Sessions = new Http2Sessions;
- isHttpAdapterSupported = typeof process !== "undefined" && utils_default.kindOf(process) === "process";
- http2Transport = {
- request(options2, cb) {
- const authority = options2.protocol + "//" + options2.hostname + ":" + (options2.port || (options2.protocol === "https:" ? 443 : 80));
- const { http2Options, headers } = options2;
- const session = http2Sessions.getSession(authority, http2Options);
- const { HTTP2_HEADER_SCHEME, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = http2.constants;
- const http2Headers = {
- [HTTP2_HEADER_SCHEME]: options2.protocol.replace(":", ""),
- [HTTP2_HEADER_METHOD]: options2.method,
- [HTTP2_HEADER_PATH]: options2.path
- };
- utils_default.forEach(headers, (header, name) => {
- name.charAt(0) !== ":" && (http2Headers[name] = header);
- });
- const req = session.request(http2Headers);
- req.once("response", (responseHeaders) => {
- const response = req;
- responseHeaders = Object.assign({}, responseHeaders);
- const status = responseHeaders[HTTP2_HEADER_STATUS];
- delete responseHeaders[HTTP2_HEADER_STATUS];
- response.headers = responseHeaders;
- response.statusCode = +status;
- cb(response);
- });
- return req;
- }
- };
- http_default = isHttpAdapterSupported && function httpAdapter(config) {
- return wrapAsync(async function dispatchHttpRequest(resolve2, reject, onDone) {
- let { data, lookup, family, httpVersion = 1, http2Options } = config;
- const { responseType, responseEncoding } = config;
- const method = config.method.toUpperCase();
- let isDone;
- let rejected = false;
- let req;
- httpVersion = +httpVersion;
- if (Number.isNaN(httpVersion)) {
- throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);
- }
- if (httpVersion !== 1 && httpVersion !== 2) {
- throw TypeError(`Unsupported protocol version '${httpVersion}'`);
- }
- const isHttp2 = httpVersion === 2;
- if (lookup) {
- const _lookup = callbackify_default(lookup, (value) => utils_default.isArray(value) ? value : [value]);
- lookup = (hostname, opt, cb) => {
- _lookup(hostname, opt, (err, arg0, arg1) => {
- if (err) {
- return cb(err);
- }
- const addresses = utils_default.isArray(arg0) ? arg0.map((addr) => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
- opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
- });
- };
- }
- const abortEmitter = new EventEmitter2;
- function abort(reason) {
- try {
- abortEmitter.emit("abort", !reason || reason.type ? new CanceledError_default(null, config, req) : reason);
- } catch (err) {
- console.warn("emit error", err);
- }
- }
- abortEmitter.once("abort", reject);
- const onFinished = () => {
- if (config.cancelToken) {
- config.cancelToken.unsubscribe(abort);
- }
- if (config.signal) {
- config.signal.removeEventListener("abort", abort);
- }
- abortEmitter.removeAllListeners();
- };
- if (config.cancelToken || config.signal) {
- config.cancelToken && config.cancelToken.subscribe(abort);
- if (config.signal) {
- config.signal.aborted ? abort() : config.signal.addEventListener("abort", abort);
- }
- }
- onDone((response, isRejected) => {
- isDone = true;
- if (isRejected) {
- rejected = true;
- onFinished();
- return;
- }
- const { data: data2 } = response;
- if (data2 instanceof stream3.Readable || data2 instanceof stream3.Duplex) {
- const offListeners = stream3.finished(data2, () => {
- offListeners();
- onFinished();
- });
- } else {
- onFinished();
- }
- });
- const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
- const parsed = new URL(fullPath, platform_default.hasBrowserEnv ? platform_default.origin : undefined);
- const protocol = parsed.protocol || supportedProtocols[0];
- if (protocol === "data:") {
- if (config.maxContentLength > -1) {
- const dataUrl = String(config.url || fullPath || "");
- const estimated = estimateDataURLDecodedBytes(dataUrl);
- if (estimated > config.maxContentLength) {
- return reject(new AxiosError_default("maxContentLength size of " + config.maxContentLength + " exceeded", AxiosError_default.ERR_BAD_RESPONSE, config));
- }
- }
- let convertedData;
- if (method !== "GET") {
- return settle(resolve2, reject, {
- status: 405,
- statusText: "method not allowed",
- headers: {},
- config
- });
- }
- try {
- convertedData = fromDataURI(config.url, responseType === "blob", {
- Blob: config.env && config.env.Blob
- });
- } catch (err) {
- throw AxiosError_default.from(err, AxiosError_default.ERR_BAD_REQUEST, config);
- }
- if (responseType === "text") {
- convertedData = convertedData.toString(responseEncoding);
- if (!responseEncoding || responseEncoding === "utf8") {
- convertedData = utils_default.stripBOM(convertedData);
- }
- } else if (responseType === "stream") {
- convertedData = stream3.Readable.from(convertedData);
- }
- return settle(resolve2, reject, {
- data: convertedData,
- status: 200,
- statusText: "OK",
- headers: new AxiosHeaders_default,
- config
- });
- }
- if (supportedProtocols.indexOf(protocol) === -1) {
- return reject(new AxiosError_default("Unsupported protocol " + protocol, AxiosError_default.ERR_BAD_REQUEST, config));
- }
- const headers = AxiosHeaders_default.from(config.headers).normalize();
- headers.set("User-Agent", "axios/" + VERSION2, false);
- const { onUploadProgress, onDownloadProgress } = config;
- const maxRate = config.maxRate;
- let maxUploadRate = undefined;
- let maxDownloadRate = undefined;
- if (utils_default.isSpecCompliantForm(data)) {
- const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
- data = formDataToStream_default(data, (formHeaders) => {
- headers.set(formHeaders);
- }, {
- tag: `axios-${VERSION2}-boundary`,
- boundary: userBoundary && userBoundary[1] || undefined
- });
- } else if (utils_default.isFormData(data) && utils_default.isFunction(data.getHeaders)) {
- headers.set(data.getHeaders());
- if (!headers.hasContentLength()) {
- try {
- const knownLength = await util2.promisify(data.getLength).call(data);
- Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
- } catch (e) {}
- }
- } else if (utils_default.isBlob(data) || utils_default.isFile(data)) {
- data.size && headers.setContentType(data.type || "application/octet-stream");
- headers.setContentLength(data.size || 0);
- data = stream3.Readable.from(readBlob_default(data));
- } else if (data && !utils_default.isStream(data)) {
- if (Buffer.isBuffer(data)) {} else if (utils_default.isArrayBuffer(data)) {
- data = Buffer.from(new Uint8Array(data));
- } else if (utils_default.isString(data)) {
- data = Buffer.from(data, "utf-8");
- } else {
- return reject(new AxiosError_default("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream", AxiosError_default.ERR_BAD_REQUEST, config));
- }
- headers.setContentLength(data.length, false);
- if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
- return reject(new AxiosError_default("Request body larger than maxBodyLength limit", AxiosError_default.ERR_BAD_REQUEST, config));
- }
- }
- const contentLength = utils_default.toFiniteNumber(headers.getContentLength());
- if (utils_default.isArray(maxRate)) {
- maxUploadRate = maxRate[0];
- maxDownloadRate = maxRate[1];
- } else {
- maxUploadRate = maxDownloadRate = maxRate;
- }
- if (data && (onUploadProgress || maxUploadRate)) {
- if (!utils_default.isStream(data)) {
- data = stream3.Readable.from(data, { objectMode: false });
- }
- data = stream3.pipeline([
- data,
- new AxiosTransformStream_default({
- maxRate: utils_default.toFiniteNumber(maxUploadRate)
- })
- ], utils_default.noop);
- onUploadProgress && data.on("progress", flushOnFinish(data, progressEventDecorator(contentLength, progressEventReducer(asyncDecorator(onUploadProgress), false, 3))));
- }
- let auth = undefined;
- if (config.auth) {
- const username = config.auth.username || "";
- const password = config.auth.password || "";
- auth = username + ":" + password;
- }
- if (!auth && parsed.username) {
- const urlUsername = parsed.username;
- const urlPassword = parsed.password;
- auth = urlUsername + ":" + urlPassword;
- }
- auth && headers.delete("authorization");
- let path6;
- try {
- path6 = buildURL(parsed.pathname + parsed.search, config.params, config.paramsSerializer).replace(/^\?/, "");
- } catch (err) {
- const customErr = new Error(err.message);
- customErr.config = config;
- customErr.url = config.url;
- customErr.exists = true;
- return reject(customErr);
- }
- headers.set("Accept-Encoding", "gzip, compress, deflate" + (isBrotliSupported ? ", br" : ""), false);
- const options2 = {
- path: path6,
- method,
- headers: headers.toJSON(),
- agents: { http: config.httpAgent, https: config.httpsAgent },
- auth,
- protocol,
- family,
- beforeRedirect: dispatchBeforeRedirect,
- beforeRedirects: {},
- http2Options
- };
- !utils_default.isUndefined(lookup) && (options2.lookup = lookup);
- if (config.socketPath) {
- options2.socketPath = config.socketPath;
- } else {
- options2.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;
- options2.port = parsed.port;
- setProxy(options2, config.proxy, protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options2.path);
- }
- let transport;
- const isHttpsRequest = isHttps.test(options2.protocol);
- options2.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
- if (isHttp2) {
- transport = http2Transport;
- } else {
- if (config.transport) {
- transport = config.transport;
- } else if (config.maxRedirects === 0) {
- transport = isHttpsRequest ? https : http;
- } else {
- if (config.maxRedirects) {
- options2.maxRedirects = config.maxRedirects;
- }
- if (config.beforeRedirect) {
- options2.beforeRedirects.config = config.beforeRedirect;
- }
- transport = isHttpsRequest ? httpsFollow : httpFollow;
- }
- }
- if (config.maxBodyLength > -1) {
- options2.maxBodyLength = config.maxBodyLength;
- } else {
- options2.maxBodyLength = Infinity;
- }
- if (config.insecureHTTPParser) {
- options2.insecureHTTPParser = config.insecureHTTPParser;
- }
- req = transport.request(options2, function handleResponse(res) {
- if (req.destroyed)
- return;
- const streams2 = [res];
- const responseLength = utils_default.toFiniteNumber(res.headers["content-length"]);
- if (onDownloadProgress || maxDownloadRate) {
- const transformStream = new AxiosTransformStream_default({
- maxRate: utils_default.toFiniteNumber(maxDownloadRate)
- });
- onDownloadProgress && transformStream.on("progress", flushOnFinish(transformStream, progressEventDecorator(responseLength, progressEventReducer(asyncDecorator(onDownloadProgress), true, 3))));
- streams2.push(transformStream);
- }
- let responseStream = res;
- const lastRequest = res.req || req;
- if (config.decompress !== false && res.headers["content-encoding"]) {
- if (method === "HEAD" || res.statusCode === 204) {
- delete res.headers["content-encoding"];
- }
- switch ((res.headers["content-encoding"] || "").toLowerCase()) {
- case "gzip":
- case "x-gzip":
- case "compress":
- case "x-compress":
- streams2.push(zlib.createUnzip(zlibOptions));
- delete res.headers["content-encoding"];
- break;
- case "deflate":
- streams2.push(new ZlibHeaderTransformStream_default);
- streams2.push(zlib.createUnzip(zlibOptions));
- delete res.headers["content-encoding"];
- break;
- case "br":
- if (isBrotliSupported) {
- streams2.push(zlib.createBrotliDecompress(brotliOptions));
- delete res.headers["content-encoding"];
- }
- }
- }
- responseStream = streams2.length > 1 ? stream3.pipeline(streams2, utils_default.noop) : streams2[0];
- const response = {
- status: res.statusCode,
- statusText: res.statusMessage,
- headers: new AxiosHeaders_default(res.headers),
- config,
- request: lastRequest
- };
- if (responseType === "stream") {
- response.data = responseStream;
- settle(resolve2, reject, response);
- } else {
- const responseBuffer = [];
- let totalResponseBytes = 0;
- responseStream.on("data", function handleStreamData(chunk) {
- responseBuffer.push(chunk);
- totalResponseBytes += chunk.length;
- if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
- rejected = true;
- responseStream.destroy();
- abort(new AxiosError_default("maxContentLength size of " + config.maxContentLength + " exceeded", AxiosError_default.ERR_BAD_RESPONSE, config, lastRequest));
- }
- });
- responseStream.on("aborted", function handlerStreamAborted() {
- if (rejected) {
- return;
- }
- const err = new AxiosError_default("stream has been aborted", AxiosError_default.ERR_BAD_RESPONSE, config, lastRequest);
- responseStream.destroy(err);
- reject(err);
- });
- responseStream.on("error", function handleStreamError2(err) {
- if (req.destroyed)
- return;
- reject(AxiosError_default.from(err, null, config, lastRequest));
- });
- responseStream.on("end", function handleStreamEnd2() {
- try {
- let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
- if (responseType !== "arraybuffer") {
- responseData = responseData.toString(responseEncoding);
- if (!responseEncoding || responseEncoding === "utf8") {
- responseData = utils_default.stripBOM(responseData);
- }
- }
- response.data = responseData;
- } catch (err) {
- return reject(AxiosError_default.from(err, null, config, response.request, response));
- }
- settle(resolve2, reject, response);
- });
- }
- abortEmitter.once("abort", (err) => {
- if (!responseStream.destroyed) {
- responseStream.emit("error", err);
- responseStream.destroy();
- }
- });
- });
- abortEmitter.once("abort", (err) => {
- if (req.close) {
- req.close();
- } else {
- req.destroy(err);
- }
- });
- req.on("error", function handleRequestError(err) {
- reject(AxiosError_default.from(err, null, config, req));
- });
- req.on("socket", function handleRequestSocket(socket) {
- socket.setKeepAlive(true, 1000 * 60);
- });
- if (config.timeout) {
- const timeout = parseInt(config.timeout, 10);
- if (Number.isNaN(timeout)) {
- abort(new AxiosError_default("error trying to parse `config.timeout` to int", AxiosError_default.ERR_BAD_OPTION_VALUE, config, req));
- return;
- }
- req.setTimeout(timeout, function handleRequestTimeout() {
- if (isDone)
- return;
- let timeoutErrorMessage = config.timeout ? "timeout of " + config.timeout + "ms exceeded" : "timeout exceeded";
- const transitional = config.transitional || transitional_default;
- if (config.timeoutErrorMessage) {
- timeoutErrorMessage = config.timeoutErrorMessage;
- }
- abort(new AxiosError_default(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED, config, req));
- });
- } else {
- req.setTimeout(0);
- }
- if (utils_default.isStream(data)) {
- let ended = false;
- let errored = false;
- data.on("end", () => {
- ended = true;
- });
- data.once("error", (err) => {
- errored = true;
- req.destroy(err);
- });
- data.on("close", () => {
- if (!ended && !errored) {
- abort(new CanceledError_default("Request stream has been aborted", config, req));
- }
- });
- data.pipe(req);
- } else {
- data && req.write(data);
- req.end();
- }
- });
- };
-});
-
-// node_modules/axios/lib/helpers/isURLSameOrigin.js
-var isURLSameOrigin_default;
-var init_isURLSameOrigin = __esm(() => {
- init_platform();
- isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? ((origin2, isMSIE) => (url2) => {
- url2 = new URL(url2, platform_default.origin);
- return origin2.protocol === url2.protocol && origin2.host === url2.host && (isMSIE || origin2.port === url2.port);
- })(new URL(platform_default.origin), platform_default.navigator && /(msie|trident)/i.test(platform_default.navigator.userAgent)) : () => true;
-});
-
-// node_modules/axios/lib/helpers/cookies.js
-var cookies_default;
-var init_cookies = __esm(() => {
- init_utils();
- init_platform();
- cookies_default = platform_default.hasStandardBrowserEnv ? {
- write(name, value, expires, path6, domain, secure, sameSite) {
- if (typeof document === "undefined")
- return;
- const cookie = [`${name}=${encodeURIComponent(value)}`];
- if (utils_default.isNumber(expires)) {
- cookie.push(`expires=${new Date(expires).toUTCString()}`);
- }
- if (utils_default.isString(path6)) {
- cookie.push(`path=${path6}`);
- }
- if (utils_default.isString(domain)) {
- cookie.push(`domain=${domain}`);
- }
- if (secure === true) {
- cookie.push("secure");
- }
- if (utils_default.isString(sameSite)) {
- cookie.push(`SameSite=${sameSite}`);
- }
- document.cookie = cookie.join("; ");
- },
- read(name) {
- if (typeof document === "undefined")
- return null;
- const match = document.cookie.match(new RegExp("(?:^|; )" + name + "=([^;]*)"));
- return match ? decodeURIComponent(match[1]) : null;
- },
- remove(name) {
- this.write(name, "", Date.now() - 86400000, "/");
- }
- } : {
- write() {},
- read() {
- return null;
- },
- remove() {}
- };
-});
-
-// node_modules/axios/lib/core/mergeConfig.js
-function mergeConfig(config1, config2) {
- config2 = config2 || {};
- const config = {};
- function getMergedValue(target, source, prop, caseless) {
- if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source)) {
- return utils_default.merge.call({ caseless }, target, source);
- } else if (utils_default.isPlainObject(source)) {
- return utils_default.merge({}, source);
- } else if (utils_default.isArray(source)) {
- return source.slice();
- }
- return source;
- }
- function mergeDeepProperties(a2, b, prop, caseless) {
- if (!utils_default.isUndefined(b)) {
- return getMergedValue(a2, b, prop, caseless);
- } else if (!utils_default.isUndefined(a2)) {
- return getMergedValue(undefined, a2, prop, caseless);
- }
- }
- function valueFromConfig2(a2, b) {
- if (!utils_default.isUndefined(b)) {
- return getMergedValue(undefined, b);
- }
- }
- function defaultToConfig2(a2, b) {
- if (!utils_default.isUndefined(b)) {
- return getMergedValue(undefined, b);
- } else if (!utils_default.isUndefined(a2)) {
- return getMergedValue(undefined, a2);
- }
- }
- function mergeDirectKeys(a2, b, prop) {
- if (prop in config2) {
- return getMergedValue(a2, b);
- } else if (prop in config1) {
- return getMergedValue(undefined, a2);
- }
- }
- const mergeMap = {
- url: valueFromConfig2,
- method: valueFromConfig2,
- data: valueFromConfig2,
- baseURL: defaultToConfig2,
- transformRequest: defaultToConfig2,
- transformResponse: defaultToConfig2,
- paramsSerializer: defaultToConfig2,
- timeout: defaultToConfig2,
- timeoutMessage: defaultToConfig2,
- withCredentials: defaultToConfig2,
- withXSRFToken: defaultToConfig2,
- adapter: defaultToConfig2,
- responseType: defaultToConfig2,
- xsrfCookieName: defaultToConfig2,
- xsrfHeaderName: defaultToConfig2,
- onUploadProgress: defaultToConfig2,
- onDownloadProgress: defaultToConfig2,
- decompress: defaultToConfig2,
- maxContentLength: defaultToConfig2,
- maxBodyLength: defaultToConfig2,
- beforeRedirect: defaultToConfig2,
- transport: defaultToConfig2,
- httpAgent: defaultToConfig2,
- httpsAgent: defaultToConfig2,
- cancelToken: defaultToConfig2,
- socketPath: defaultToConfig2,
- responseEncoding: defaultToConfig2,
- validateStatus: mergeDirectKeys,
- headers: (a2, b, prop) => mergeDeepProperties(headersToObject(a2), headersToObject(b), prop, true)
- };
- utils_default.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
- if (prop === "__proto__" || prop === "constructor" || prop === "prototype")
- return;
- const merge2 = utils_default.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
- const configValue = merge2(config1[prop], config2[prop], prop);
- utils_default.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue);
- });
- return config;
-}
-var headersToObject = (thing) => thing instanceof AxiosHeaders_default ? { ...thing } : thing;
-var init_mergeConfig = __esm(() => {
- init_utils();
- init_AxiosHeaders();
-});
-
-// node_modules/axios/lib/helpers/resolveConfig.js
-var resolveConfig_default = (config) => {
- const newConfig = mergeConfig({}, config);
- let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
- newConfig.headers = headers = AxiosHeaders_default.from(headers);
- newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
- if (auth) {
- headers.set("Authorization", "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : "")));
- }
- if (utils_default.isFormData(data)) {
- if (platform_default.hasStandardBrowserEnv || platform_default.hasStandardBrowserWebWorkerEnv) {
- headers.setContentType(undefined);
- } else if (utils_default.isFunction(data.getHeaders)) {
- const formHeaders = data.getHeaders();
- const allowedHeaders = ["content-type", "content-length"];
- Object.entries(formHeaders).forEach(([key, val]) => {
- if (allowedHeaders.includes(key.toLowerCase())) {
- headers.set(key, val);
- }
- });
- }
- }
- if (platform_default.hasStandardBrowserEnv) {
- withXSRFToken && utils_default.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
- if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin_default(newConfig.url)) {
- const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies_default.read(xsrfCookieName);
- if (xsrfValue) {
- headers.set(xsrfHeaderName, xsrfValue);
- }
- }
- }
- return newConfig;
-};
-var init_resolveConfig = __esm(() => {
- init_platform();
- init_utils();
- init_isURLSameOrigin();
- init_cookies();
- init_buildFullPath();
- init_mergeConfig();
- init_AxiosHeaders();
- init_buildURL();
-});
-
-// node_modules/axios/lib/adapters/xhr.js
-var isXHRAdapterSupported, xhr_default;
-var init_xhr = __esm(() => {
- init_utils();
- init_settle();
- init_transitional();
- init_AxiosError();
- init_CanceledError();
- init_platform();
- init_AxiosHeaders();
- init_progressEventReducer();
- init_resolveConfig();
- isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
- xhr_default = isXHRAdapterSupported && function(config) {
- return new Promise(function dispatchXhrRequest(resolve2, reject) {
- const _config = resolveConfig_default(config);
- let requestData = _config.data;
- const requestHeaders = AxiosHeaders_default.from(_config.headers).normalize();
- let { responseType, onUploadProgress, onDownloadProgress } = _config;
- let onCanceled;
- let uploadThrottled, downloadThrottled;
- let flushUpload, flushDownload;
- function done() {
- flushUpload && flushUpload();
- flushDownload && flushDownload();
- _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
- _config.signal && _config.signal.removeEventListener("abort", onCanceled);
- }
- let request = new XMLHttpRequest;
- request.open(_config.method.toUpperCase(), _config.url, true);
- request.timeout = _config.timeout;
- function onloadend() {
- if (!request) {
- return;
- }
- const responseHeaders = AxiosHeaders_default.from("getAllResponseHeaders" in request && request.getAllResponseHeaders());
- const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
- const response = {
- data: responseData,
- status: request.status,
- statusText: request.statusText,
- headers: responseHeaders,
- config,
- request
- };
- settle(function _resolve(value) {
- resolve2(value);
- done();
- }, function _reject(err) {
- reject(err);
- done();
- }, response);
- request = null;
- }
- if ("onloadend" in request) {
- request.onloadend = onloadend;
- } else {
- request.onreadystatechange = function handleLoad() {
- if (!request || request.readyState !== 4) {
- return;
- }
- if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
- return;
- }
- setTimeout(onloadend);
- };
- }
- request.onabort = function handleAbort2() {
- if (!request) {
- return;
- }
- reject(new AxiosError_default("Request aborted", AxiosError_default.ECONNABORTED, config, request));
- request = null;
- };
- request.onerror = function handleError(event) {
- const msg = event && event.message ? event.message : "Network Error";
- const err = new AxiosError_default(msg, AxiosError_default.ERR_NETWORK, config, request);
- err.event = event || null;
- reject(err);
- request = null;
- };
- request.ontimeout = function handleTimeout() {
- let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
- const transitional = _config.transitional || transitional_default;
- if (_config.timeoutErrorMessage) {
- timeoutErrorMessage = _config.timeoutErrorMessage;
- }
- reject(new AxiosError_default(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED, config, request));
- request = null;
- };
- requestData === undefined && requestHeaders.setContentType(null);
- if ("setRequestHeader" in request) {
- utils_default.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
- request.setRequestHeader(key, val);
- });
- }
- if (!utils_default.isUndefined(_config.withCredentials)) {
- request.withCredentials = !!_config.withCredentials;
- }
- if (responseType && responseType !== "json") {
- request.responseType = _config.responseType;
- }
- if (onDownloadProgress) {
- [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
- request.addEventListener("progress", downloadThrottled);
- }
- if (onUploadProgress && request.upload) {
- [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
- request.upload.addEventListener("progress", uploadThrottled);
- request.upload.addEventListener("loadend", flushUpload);
- }
- if (_config.cancelToken || _config.signal) {
- onCanceled = (cancel) => {
- if (!request) {
- return;
- }
- reject(!cancel || cancel.type ? new CanceledError_default(null, config, request) : cancel);
- request.abort();
- request = null;
- };
- _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
- if (_config.signal) {
- _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
- }
- }
- const protocol = parseProtocol(_config.url);
- if (protocol && platform_default.protocols.indexOf(protocol) === -1) {
- reject(new AxiosError_default("Unsupported protocol " + protocol + ":", AxiosError_default.ERR_BAD_REQUEST, config));
- return;
- }
- request.send(requestData || null);
- });
- };
-});
-
-// node_modules/axios/lib/helpers/composeSignals.js
-var composeSignals = (signals2, timeout) => {
- const { length } = signals2 = signals2 ? signals2.filter(Boolean) : [];
- if (timeout || length) {
- let controller = new AbortController;
- let aborted2;
- const onabort = function(reason) {
- if (!aborted2) {
- aborted2 = true;
- unsubscribe2();
- const err = reason instanceof Error ? reason : this.reason;
- controller.abort(err instanceof AxiosError_default ? err : new CanceledError_default(err instanceof Error ? err.message : err));
- }
- };
- let timer = timeout && setTimeout(() => {
- timer = null;
- onabort(new AxiosError_default(`timeout of ${timeout}ms exceeded`, AxiosError_default.ETIMEDOUT));
- }, timeout);
- const unsubscribe2 = () => {
- if (signals2) {
- timer && clearTimeout(timer);
- timer = null;
- signals2.forEach((signal2) => {
- signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
- });
- signals2 = null;
- }
- };
- signals2.forEach((signal2) => signal2.addEventListener("abort", onabort));
- const { signal } = controller;
- signal.unsubscribe = () => utils_default.asap(unsubscribe2);
- return signal;
- }
-}, composeSignals_default;
-var init_composeSignals = __esm(() => {
- init_CanceledError();
- init_AxiosError();
- init_utils();
- composeSignals_default = composeSignals;
-});
-
-// node_modules/axios/lib/helpers/trackStream.js
-var streamChunk = function* (chunk, chunkSize) {
- let len = chunk.byteLength;
- if (!chunkSize || len < chunkSize) {
- yield chunk;
- return;
- }
- let pos = 0;
- let end;
- while (pos < len) {
- end = pos + chunkSize;
- yield chunk.slice(pos, end);
- pos = end;
- }
-}, readBytes = async function* (iterable, chunkSize) {
- for await (const chunk of readStream(iterable)) {
- yield* streamChunk(chunk, chunkSize);
- }
-}, readStream = async function* (stream4) {
- if (stream4[Symbol.asyncIterator]) {
- yield* stream4;
- return;
- }
- const reader = stream4.getReader();
- try {
- for (;; ) {
- const { done, value } = await reader.read();
- if (done) {
- break;
- }
- yield value;
- }
- } finally {
- await reader.cancel();
- }
-}, trackStream = (stream4, chunkSize, onProgress, onFinish) => {
- const iterator2 = readBytes(stream4, chunkSize);
- let bytes = 0;
- let done;
- let _onFinish = (e) => {
- if (!done) {
- done = true;
- onFinish && onFinish(e);
- }
- };
- return new ReadableStream({
- async pull(controller) {
- try {
- const { done: done2, value } = await iterator2.next();
- if (done2) {
- _onFinish();
- controller.close();
- return;
- }
- let len = value.byteLength;
- if (onProgress) {
- let loadedBytes = bytes += len;
- onProgress(loadedBytes);
- }
- controller.enqueue(new Uint8Array(value));
- } catch (err) {
- _onFinish(err);
- throw err;
- }
- },
- cancel(reason) {
- _onFinish(reason);
- return iterator2.return();
- }
- }, {
- highWaterMark: 2
- });
-};
-
-// node_modules/axios/lib/adapters/fetch.js
-var DEFAULT_CHUNK_SIZE, isFunction3, globalFetchAPI, ReadableStream3, TextEncoder2, test = (fn, ...args) => {
- try {
- return !!fn(...args);
- } catch (e) {
- return false;
- }
-}, factory = (env2) => {
- env2 = utils_default.merge.call({
- skipUndefined: true
- }, globalFetchAPI, env2);
- const { fetch: envFetch, Request: Request3, Response: Response3 } = env2;
- const isFetchSupported = envFetch ? isFunction3(envFetch) : typeof fetch === "function";
- const isRequestSupported = isFunction3(Request3);
- const isResponseSupported = isFunction3(Response3);
- if (!isFetchSupported) {
- return false;
- }
- const isReadableStreamSupported = isFetchSupported && isFunction3(ReadableStream3);
- const encodeText = isFetchSupported && (typeof TextEncoder2 === "function" ? ((encoder) => (str) => encoder.encode(str))(new TextEncoder2) : async (str) => new Uint8Array(await new Request3(str).arrayBuffer()));
- const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
- let duplexAccessed = false;
- const body = new ReadableStream3;
- const hasContentType = new Request3(platform_default.origin, {
- body,
- method: "POST",
- get duplex() {
- duplexAccessed = true;
- return "half";
- }
- }).headers.has("Content-Type");
- body.cancel();
- return duplexAccessed && !hasContentType;
- });
- const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils_default.isReadableStream(new Response3("").body));
- const resolvers = {
- stream: supportsResponseStream && ((res) => res.body)
- };
- isFetchSupported && (() => {
- ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => {
- !resolvers[type] && (resolvers[type] = (res, config) => {
- let method = res && res[type];
- if (method) {
- return method.call(res);
- }
- throw new AxiosError_default(`Response type '${type}' is not supported`, AxiosError_default.ERR_NOT_SUPPORT, config);
- });
- });
- })();
- const getBodyLength = async (body) => {
- if (body == null) {
- return 0;
- }
- if (utils_default.isBlob(body)) {
- return body.size;
- }
- if (utils_default.isSpecCompliantForm(body)) {
- const _request = new Request3(platform_default.origin, {
- method: "POST",
- body
- });
- return (await _request.arrayBuffer()).byteLength;
- }
- if (utils_default.isArrayBufferView(body) || utils_default.isArrayBuffer(body)) {
- return body.byteLength;
- }
- if (utils_default.isURLSearchParams(body)) {
- body = body + "";
- }
- if (utils_default.isString(body)) {
- return (await encodeText(body)).byteLength;
- }
- };
- const resolveBodyLength = async (headers, body) => {
- const length = utils_default.toFiniteNumber(headers.getContentLength());
- return length == null ? getBodyLength(body) : length;
- };
- return async (config) => {
- let {
- url: url2,
- method,
- data,
- signal,
- cancelToken,
- timeout,
- onDownloadProgress,
- onUploadProgress,
- responseType,
- headers,
- withCredentials = "same-origin",
- fetchOptions
- } = resolveConfig_default(config);
- let _fetch = envFetch || fetch;
- responseType = responseType ? (responseType + "").toLowerCase() : "text";
- let composedSignal = composeSignals_default([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
- let request = null;
- const unsubscribe2 = composedSignal && composedSignal.unsubscribe && (() => {
- composedSignal.unsubscribe();
- });
- let requestContentLength;
- try {
- if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
- let _request = new Request3(url2, {
- method: "POST",
- body: data,
- duplex: "half"
- });
- let contentTypeHeader;
- if (utils_default.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
- headers.setContentType(contentTypeHeader);
- }
- if (_request.body) {
- const [onProgress, flush] = progressEventDecorator(requestContentLength, progressEventReducer(asyncDecorator(onUploadProgress)));
- data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
- }
- }
- if (!utils_default.isString(withCredentials)) {
- withCredentials = withCredentials ? "include" : "omit";
- }
- const isCredentialsSupported = isRequestSupported && "credentials" in Request3.prototype;
- const resolvedOptions = {
- ...fetchOptions,
- signal: composedSignal,
- method: method.toUpperCase(),
- headers: headers.normalize().toJSON(),
- body: data,
- duplex: "half",
- credentials: isCredentialsSupported ? withCredentials : undefined
- };
- request = isRequestSupported && new Request3(url2, resolvedOptions);
- let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url2, resolvedOptions));
- const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
- if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe2)) {
- const options2 = {};
- ["status", "statusText", "headers"].forEach((prop) => {
- options2[prop] = response[prop];
- });
- const responseContentLength = utils_default.toFiniteNumber(response.headers.get("content-length"));
- const [onProgress, flush] = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || [];
- response = new Response3(trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
- flush && flush();
- unsubscribe2 && unsubscribe2();
- }), options2);
- }
- responseType = responseType || "text";
- let responseData = await resolvers[utils_default.findKey(resolvers, responseType) || "text"](response, config);
- !isStreamResponse && unsubscribe2 && unsubscribe2();
- return await new Promise((resolve2, reject) => {
- settle(resolve2, reject, {
- data: responseData,
- headers: AxiosHeaders_default.from(response.headers),
- status: response.status,
- statusText: response.statusText,
- config,
- request
- });
- });
- } catch (err) {
- unsubscribe2 && unsubscribe2();
- if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) {
- throw Object.assign(new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config, request, err && err.response), {
- cause: err.cause || err
- });
- }
- throw AxiosError_default.from(err, err && err.code, config, request, err && err.response);
- }
- };
-}, seedCache, getFetch = (config) => {
- let env2 = config && config.env || {};
- const { fetch: fetch3, Request: Request3, Response: Response3 } = env2;
- const seeds = [Request3, Response3, fetch3];
- let len = seeds.length, i2 = len, seed, target, map = seedCache;
- while (i2--) {
- seed = seeds[i2];
- target = map.get(seed);
- target === undefined && map.set(seed, target = i2 ? new Map : factory(env2));
- map = target;
- }
- return target;
-}, adapter;
-var init_fetch = __esm(() => {
- init_platform();
- init_utils();
- init_AxiosError();
- init_composeSignals();
- init_AxiosHeaders();
- init_progressEventReducer();
- init_resolveConfig();
- init_settle();
- DEFAULT_CHUNK_SIZE = 64 * 1024;
- ({ isFunction: isFunction3 } = utils_default);
- globalFetchAPI = (({ Request: Request3, Response: Response3 }) => ({
- Request: Request3,
- Response: Response3
- }))(utils_default.global);
- ({ ReadableStream: ReadableStream3, TextEncoder: TextEncoder2 } = utils_default.global);
- seedCache = new Map;
- adapter = getFetch();
-});
-
-// node_modules/axios/lib/adapters/adapters.js
-function getAdapter(adapters, config) {
- adapters = utils_default.isArray(adapters) ? adapters : [adapters];
- const { length } = adapters;
- let nameOrAdapter;
- let adapter2;
- const rejectedReasons = {};
- for (let i2 = 0;i2 < length; i2++) {
- nameOrAdapter = adapters[i2];
- let id;
- adapter2 = nameOrAdapter;
- if (!isResolvedHandle(nameOrAdapter)) {
- adapter2 = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
- if (adapter2 === undefined) {
- throw new AxiosError_default(`Unknown adapter '${id}'`);
- }
- }
- if (adapter2 && (utils_default.isFunction(adapter2) || (adapter2 = adapter2.get(config)))) {
- break;
- }
- rejectedReasons[id || "#" + i2] = adapter2;
- }
- if (!adapter2) {
- const reasons = Object.entries(rejectedReasons).map(([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build"));
- let s = length ? reasons.length > 1 ? `since :
-` + reasons.map(renderReason).join(`
-`) : " " + renderReason(reasons[0]) : "as no adapter specified";
- throw new AxiosError_default(`There is no suitable adapter to dispatch the request ` + s, "ERR_NOT_SUPPORT");
- }
- return adapter2;
-}
-var knownAdapters, renderReason = (reason) => `- ${reason}`, isResolvedHandle = (adapter2) => utils_default.isFunction(adapter2) || adapter2 === null || adapter2 === false, adapters_default;
-var init_adapters = __esm(() => {
- init_utils();
- init_http();
- init_xhr();
- init_fetch();
- init_AxiosError();
- knownAdapters = {
- http: http_default,
- xhr: xhr_default,
- fetch: {
- get: getFetch
- }
- };
- utils_default.forEach(knownAdapters, (fn, value) => {
- if (fn) {
- try {
- Object.defineProperty(fn, "name", { value });
- } catch (e) {}
- Object.defineProperty(fn, "adapterName", { value });
- }
- });
- adapters_default = {
- getAdapter,
- adapters: knownAdapters
- };
-});
-
-// node_modules/axios/lib/core/dispatchRequest.js
-function throwIfCancellationRequested(config) {
- if (config.cancelToken) {
- config.cancelToken.throwIfRequested();
- }
- if (config.signal && config.signal.aborted) {
- throw new CanceledError_default(null, config);
- }
-}
-function dispatchRequest(config) {
- throwIfCancellationRequested(config);
- config.headers = AxiosHeaders_default.from(config.headers);
- config.data = transformData.call(config, config.transformRequest);
- if (["post", "put", "patch"].indexOf(config.method) !== -1) {
- config.headers.setContentType("application/x-www-form-urlencoded", false);
- }
- const adapter2 = adapters_default.getAdapter(config.adapter || defaults_default.adapter, config);
- return adapter2(config).then(function onAdapterResolution(response) {
- throwIfCancellationRequested(config);
- response.data = transformData.call(config, config.transformResponse, response);
- response.headers = AxiosHeaders_default.from(response.headers);
- return response;
- }, function onAdapterRejection(reason) {
- if (!isCancel(reason)) {
- throwIfCancellationRequested(config);
- if (reason && reason.response) {
- reason.response.data = transformData.call(config, config.transformResponse, reason.response);
- reason.response.headers = AxiosHeaders_default.from(reason.response.headers);
- }
- }
- return Promise.reject(reason);
- });
-}
-var init_dispatchRequest = __esm(() => {
- init_transformData();
- init_defaults();
- init_CanceledError();
- init_AxiosHeaders();
- init_adapters();
-});
-
-// node_modules/axios/lib/helpers/validator.js
-function assertOptions(options2, schema, allowUnknown) {
- if (typeof options2 !== "object") {
- throw new AxiosError_default("options must be an object", AxiosError_default.ERR_BAD_OPTION_VALUE);
- }
- const keys2 = Object.keys(options2);
- let i2 = keys2.length;
- while (i2-- > 0) {
- const opt = keys2[i2];
- const validator = schema[opt];
- if (validator) {
- const value = options2[opt];
- const result = value === undefined || validator(value, opt, options2);
- if (result !== true) {
- throw new AxiosError_default("option " + opt + " must be " + result, AxiosError_default.ERR_BAD_OPTION_VALUE);
- }
- continue;
- }
- if (allowUnknown !== true) {
- throw new AxiosError_default("Unknown option " + opt, AxiosError_default.ERR_BAD_OPTION);
- }
- }
-}
-var validators, deprecatedWarnings, validator_default;
-var init_validator = __esm(() => {
- init_AxiosError();
- validators = {};
- ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i2) => {
- validators[type] = function validator(thing) {
- return typeof thing === type || "a" + (i2 < 1 ? "n " : " ") + type;
- };
- });
- deprecatedWarnings = {};
- validators.transitional = function transitional(validator, version, message) {
- function formatMessage(opt, desc) {
- return "[Axios v" + VERSION2 + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
- }
- return (value, opt, opts) => {
- if (validator === false) {
- throw new AxiosError_default(formatMessage(opt, " has been removed" + (version ? " in " + version : "")), AxiosError_default.ERR_DEPRECATED);
- }
- if (version && !deprecatedWarnings[opt]) {
- deprecatedWarnings[opt] = true;
- console.warn(formatMessage(opt, " has been deprecated since v" + version + " and will be removed in the near future"));
- }
- return validator ? validator(value, opt, opts) : true;
- };
- };
- validators.spelling = function spelling(correctSpelling) {
- return (value, opt) => {
- console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
- return true;
- };
- };
- validator_default = {
- assertOptions,
- validators
- };
-});
-
-// node_modules/axios/lib/core/Axios.js
-class Axios {
- constructor(instanceConfig) {
- this.defaults = instanceConfig || {};
- this.interceptors = {
- request: new InterceptorManager_default,
- response: new InterceptorManager_default
- };
- }
- async request(configOrUrl, config) {
- try {
- return await this._request(configOrUrl, config);
- } catch (err) {
- if (err instanceof Error) {
- let dummy = {};
- Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error;
- const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
- try {
- if (!err.stack) {
- err.stack = stack;
- } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
- err.stack += `
-` + stack;
- }
- } catch (e) {}
- }
- throw err;
- }
- }
- _request(configOrUrl, config) {
- if (typeof configOrUrl === "string") {
- config = config || {};
- config.url = configOrUrl;
- } else {
- config = configOrUrl || {};
- }
- config = mergeConfig(this.defaults, config);
- const { transitional: transitional2, paramsSerializer, headers } = config;
- if (transitional2 !== undefined) {
- validator_default.assertOptions(transitional2, {
- silentJSONParsing: validators2.transitional(validators2.boolean),
- forcedJSONParsing: validators2.transitional(validators2.boolean),
- clarifyTimeoutError: validators2.transitional(validators2.boolean),
- legacyInterceptorReqResOrdering: validators2.transitional(validators2.boolean)
- }, false);
- }
- if (paramsSerializer != null) {
- if (utils_default.isFunction(paramsSerializer)) {
- config.paramsSerializer = {
- serialize: paramsSerializer
- };
- } else {
- validator_default.assertOptions(paramsSerializer, {
- encode: validators2.function,
- serialize: validators2.function
- }, true);
- }
- }
- if (config.allowAbsoluteUrls !== undefined) {} else if (this.defaults.allowAbsoluteUrls !== undefined) {
- config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
- } else {
- config.allowAbsoluteUrls = true;
- }
- validator_default.assertOptions(config, {
- baseUrl: validators2.spelling("baseURL"),
- withXsrfToken: validators2.spelling("withXSRFToken")
- }, true);
- config.method = (config.method || this.defaults.method || "get").toLowerCase();
- let contextHeaders = headers && utils_default.merge(headers.common, headers[config.method]);
- headers && utils_default.forEach(["delete", "get", "head", "post", "put", "patch", "common"], (method) => {
- delete headers[method];
- });
- config.headers = AxiosHeaders_default.concat(contextHeaders, headers);
- const requestInterceptorChain = [];
- let synchronousRequestInterceptors = true;
- this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
- if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) {
- return;
- }
- synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
- const transitional3 = config.transitional || transitional_default;
- const legacyInterceptorReqResOrdering = transitional3 && transitional3.legacyInterceptorReqResOrdering;
- if (legacyInterceptorReqResOrdering) {
- requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
- } else {
- requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
- }
- });
- const responseInterceptorChain = [];
- this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
- responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
- });
- let promise;
- let i2 = 0;
- let len;
- if (!synchronousRequestInterceptors) {
- const chain = [dispatchRequest.bind(this), undefined];
- chain.unshift(...requestInterceptorChain);
- chain.push(...responseInterceptorChain);
- len = chain.length;
- promise = Promise.resolve(config);
- while (i2 < len) {
- promise = promise.then(chain[i2++], chain[i2++]);
- }
- return promise;
- }
- len = requestInterceptorChain.length;
- let newConfig = config;
- while (i2 < len) {
- const onFulfilled = requestInterceptorChain[i2++];
- const onRejected = requestInterceptorChain[i2++];
- try {
- newConfig = onFulfilled(newConfig);
- } catch (error) {
- onRejected.call(this, error);
- break;
- }
- }
- try {
- promise = dispatchRequest.call(this, newConfig);
- } catch (error) {
- return Promise.reject(error);
- }
- i2 = 0;
- len = responseInterceptorChain.length;
- while (i2 < len) {
- promise = promise.then(responseInterceptorChain[i2++], responseInterceptorChain[i2++]);
- }
- return promise;
- }
- getUri(config) {
- config = mergeConfig(this.defaults, config);
- const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
- return buildURL(fullPath, config.params, config.paramsSerializer);
- }
-}
-var validators2, Axios_default;
-var init_Axios = __esm(() => {
- init_utils();
- init_buildURL();
- init_InterceptorManager();
- init_dispatchRequest();
- init_mergeConfig();
- init_buildFullPath();
- init_validator();
- init_AxiosHeaders();
- init_transitional();
- validators2 = validator_default.validators;
- utils_default.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
- Axios.prototype[method] = function(url2, config) {
- return this.request(mergeConfig(config || {}, {
- method,
- url: url2,
- data: (config || {}).data
- }));
- };
- });
- utils_default.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
- function generateHTTPMethod(isForm) {
- return function httpMethod(url2, data, config) {
- return this.request(mergeConfig(config || {}, {
- method,
- headers: isForm ? {
- "Content-Type": "multipart/form-data"
- } : {},
- url: url2,
- data
- }));
- };
- }
- Axios.prototype[method] = generateHTTPMethod();
- Axios.prototype[method + "Form"] = generateHTTPMethod(true);
- });
- Axios_default = Axios;
-});
-
-// node_modules/axios/lib/cancel/CancelToken.js
-class CancelToken {
- constructor(executor) {
- if (typeof executor !== "function") {
- throw new TypeError("executor must be a function.");
- }
- let resolvePromise;
- this.promise = new Promise(function promiseExecutor(resolve2) {
- resolvePromise = resolve2;
- });
- const token = this;
- this.promise.then((cancel) => {
- if (!token._listeners)
- return;
- let i2 = token._listeners.length;
- while (i2-- > 0) {
- token._listeners[i2](cancel);
- }
- token._listeners = null;
- });
- this.promise.then = (onfulfilled) => {
- let _resolve;
- const promise = new Promise((resolve2) => {
- token.subscribe(resolve2);
- _resolve = resolve2;
- }).then(onfulfilled);
- promise.cancel = function reject() {
- token.unsubscribe(_resolve);
- };
- return promise;
- };
- executor(function cancel(message, config, request) {
- if (token.reason) {
- return;
- }
- token.reason = new CanceledError_default(message, config, request);
- resolvePromise(token.reason);
- });
- }
- throwIfRequested() {
- if (this.reason) {
- throw this.reason;
- }
- }
- subscribe(listener) {
- if (this.reason) {
- listener(this.reason);
- return;
- }
- if (this._listeners) {
- this._listeners.push(listener);
- } else {
- this._listeners = [listener];
- }
- }
- unsubscribe(listener) {
- if (!this._listeners) {
- return;
- }
- const index2 = this._listeners.indexOf(listener);
- if (index2 !== -1) {
- this._listeners.splice(index2, 1);
- }
- }
- toAbortSignal() {
- const controller = new AbortController;
- const abort = (err) => {
- controller.abort(err);
- };
- this.subscribe(abort);
- controller.signal.unsubscribe = () => this.unsubscribe(abort);
- return controller.signal;
- }
- static source() {
- let cancel;
- const token = new CancelToken(function executor(c3) {
- cancel = c3;
- });
- return {
- token,
- cancel
- };
- }
-}
-var CancelToken_default;
-var init_CancelToken = __esm(() => {
- init_CanceledError();
- CancelToken_default = CancelToken;
-});
-
-// node_modules/axios/lib/helpers/spread.js
-function spread(callback) {
- return function wrap(arr) {
- return callback.apply(null, arr);
- };
-}
-
-// node_modules/axios/lib/helpers/isAxiosError.js
-function isAxiosError(payload) {
- return utils_default.isObject(payload) && payload.isAxiosError === true;
-}
-var init_isAxiosError = __esm(() => {
- init_utils();
-});
-
-// node_modules/axios/lib/helpers/HttpStatusCode.js
-var HttpStatusCode, HttpStatusCode_default;
-var init_HttpStatusCode = __esm(() => {
- HttpStatusCode = {
- Continue: 100,
- SwitchingProtocols: 101,
- Processing: 102,
- EarlyHints: 103,
- Ok: 200,
- Created: 201,
- Accepted: 202,
- NonAuthoritativeInformation: 203,
- NoContent: 204,
- ResetContent: 205,
- PartialContent: 206,
- MultiStatus: 207,
- AlreadyReported: 208,
- ImUsed: 226,
- MultipleChoices: 300,
- MovedPermanently: 301,
- Found: 302,
- SeeOther: 303,
- NotModified: 304,
- UseProxy: 305,
- Unused: 306,
- TemporaryRedirect: 307,
- PermanentRedirect: 308,
- BadRequest: 400,
- Unauthorized: 401,
- PaymentRequired: 402,
- Forbidden: 403,
- NotFound: 404,
- MethodNotAllowed: 405,
- NotAcceptable: 406,
- ProxyAuthenticationRequired: 407,
- RequestTimeout: 408,
- Conflict: 409,
- Gone: 410,
- LengthRequired: 411,
- PreconditionFailed: 412,
- PayloadTooLarge: 413,
- UriTooLong: 414,
- UnsupportedMediaType: 415,
- RangeNotSatisfiable: 416,
- ExpectationFailed: 417,
- ImATeapot: 418,
- MisdirectedRequest: 421,
- UnprocessableEntity: 422,
- Locked: 423,
- FailedDependency: 424,
- TooEarly: 425,
- UpgradeRequired: 426,
- PreconditionRequired: 428,
- TooManyRequests: 429,
- RequestHeaderFieldsTooLarge: 431,
- UnavailableForLegalReasons: 451,
- InternalServerError: 500,
- NotImplemented: 501,
- BadGateway: 502,
- ServiceUnavailable: 503,
- GatewayTimeout: 504,
- HttpVersionNotSupported: 505,
- VariantAlsoNegotiates: 506,
- InsufficientStorage: 507,
- LoopDetected: 508,
- NotExtended: 510,
- NetworkAuthenticationRequired: 511,
- WebServerIsDown: 521,
- ConnectionTimedOut: 522,
- OriginIsUnreachable: 523,
- TimeoutOccurred: 524,
- SslHandshakeFailed: 525,
- InvalidSslCertificate: 526
- };
- Object.entries(HttpStatusCode).forEach(([key, value]) => {
- HttpStatusCode[value] = key;
- });
- HttpStatusCode_default = HttpStatusCode;
-});
-
-// node_modules/axios/lib/axios.js
-function createInstance(defaultConfig) {
- const context = new Axios_default(defaultConfig);
- const instance = bind(Axios_default.prototype.request, context);
- utils_default.extend(instance, Axios_default.prototype, context, { allOwnKeys: true });
- utils_default.extend(instance, context, null, { allOwnKeys: true });
- instance.create = function create(instanceConfig) {
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
- };
- return instance;
-}
-var axios, axios_default;
-var init_axios = __esm(() => {
- init_utils();
- init_Axios();
- init_mergeConfig();
- init_defaults();
- init_formDataToJSON();
- init_CanceledError();
- init_CancelToken();
- init_toFormData();
- init_AxiosError();
- init_isAxiosError();
- init_AxiosHeaders();
- init_adapters();
- init_HttpStatusCode();
- axios = createInstance(defaults_default);
- axios.Axios = Axios_default;
- axios.CanceledError = CanceledError_default;
- axios.CancelToken = CancelToken_default;
- axios.isCancel = isCancel;
- axios.VERSION = VERSION2;
- axios.toFormData = toFormData_default;
- axios.AxiosError = AxiosError_default;
- axios.Cancel = axios.CanceledError;
- axios.all = function all(promises) {
- return Promise.all(promises);
- };
- axios.spread = spread;
- axios.isAxiosError = isAxiosError;
- axios.mergeConfig = mergeConfig;
- axios.AxiosHeaders = AxiosHeaders_default;
- axios.formToJSON = (thing) => formDataToJSON_default(utils_default.isHTMLForm(thing) ? new FormData(thing) : thing);
- axios.getAdapter = adapters_default.getAdapter;
- axios.HttpStatusCode = HttpStatusCode_default;
- axios.default = axios;
- axios_default = axios;
-});
-
-// node_modules/axios/index.js
-var exports_axios = {};
-__export(exports_axios, {
- toFormData: () => toFormData2,
- spread: () => spread2,
- mergeConfig: () => mergeConfig2,
- isCancel: () => isCancel2,
- isAxiosError: () => isAxiosError2,
- getAdapter: () => getAdapter2,
- formToJSON: () => formToJSON,
- default: () => axios_default,
- all: () => all2,
- VERSION: () => VERSION3,
- HttpStatusCode: () => HttpStatusCode2,
- CanceledError: () => CanceledError2,
- CancelToken: () => CancelToken2,
- Cancel: () => Cancel,
- AxiosHeaders: () => AxiosHeaders2,
- AxiosError: () => AxiosError2,
- Axios: () => Axios2
-});
-var Axios2, AxiosError2, CanceledError2, isCancel2, CancelToken2, VERSION3, all2, Cancel, isAxiosError2, spread2, toFormData2, AxiosHeaders2, HttpStatusCode2, formToJSON, getAdapter2, mergeConfig2;
-var init_axios2 = __esm(() => {
- init_axios();
- ({
- Axios: Axios2,
- AxiosError: AxiosError2,
- CanceledError: CanceledError2,
- isCancel: isCancel2,
- CancelToken: CancelToken2,
- VERSION: VERSION3,
- all: all2,
- Cancel,
- isAxiosError: isAxiosError2,
- spread: spread2,
- toFormData: toFormData2,
- AxiosHeaders: AxiosHeaders2,
- HttpStatusCode: HttpStatusCode2,
- formToJSON,
- getAdapter: getAdapter2,
- mergeConfig: mergeConfig2
- } = axios_default);
-});
-
-// src/utils/env.ts
-import { homedir as homedir4 } from "os";
-import { join as join6 } from "path";
-async function isCommandAvailable(command) {
- try {
- return !!await which(command);
- } catch {
- return false;
- }
-}
-function isConductor() {
- return process.env.__CFBundleIdentifier === "com.conductor.app";
-}
-function detectTerminal() {
- if (process.env.CURSOR_TRACE_ID)
- return "cursor";
- if (process.env.VSCODE_GIT_ASKPASS_MAIN?.includes("cursor")) {
- return "cursor";
- }
- if (process.env.VSCODE_GIT_ASKPASS_MAIN?.includes("windsurf")) {
- return "windsurf";
- }
- if (process.env.VSCODE_GIT_ASKPASS_MAIN?.includes("antigravity")) {
- return "antigravity";
- }
- const bundleId = process.env.__CFBundleIdentifier?.toLowerCase();
- if (bundleId?.includes("vscodium"))
- return "codium";
- if (bundleId?.includes("windsurf"))
- return "windsurf";
- if (bundleId?.includes("com.google.android.studio"))
- return "androidstudio";
- if (bundleId) {
- for (const ide of JETBRAINS_IDES) {
- if (bundleId.includes(ide))
- return ide;
- }
- }
- if (process.env.VisualStudioVersion) {
- return "visualstudio";
- }
- if (process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm") {
- if (process.platform === "darwin")
- return "pycharm";
- return "pycharm";
- }
- if (process.env.TERM === "xterm-ghostty") {
- return "ghostty";
- }
- if (process.env.TERM?.includes("kitty")) {
- return "kitty";
- }
- if (process.env.TERM_PROGRAM) {
- return process.env.TERM_PROGRAM;
- }
- if (process.env.TMUX)
- return "tmux";
- if (process.env.STY)
- return "screen";
- if (process.env.KONSOLE_VERSION)
- return "konsole";
- if (process.env.GNOME_TERMINAL_SERVICE)
- return "gnome-terminal";
- if (process.env.XTERM_VERSION)
- return "xterm";
- if (process.env.VTE_VERSION)
- return "vte-based";
- if (process.env.TERMINATOR_UUID)
- return "terminator";
- if (process.env.KITTY_WINDOW_ID) {
- return "kitty";
- }
- if (process.env.ALACRITTY_LOG)
- return "alacritty";
- if (process.env.TILIX_ID)
- return "tilix";
- if (process.env.WT_SESSION)
- return "windows-terminal";
- if (process.env.SESSIONNAME && process.env.TERM === "cygwin")
- return "cygwin";
- if (process.env.MSYSTEM)
- return process.env.MSYSTEM.toLowerCase();
- if (process.env.ConEmuANSI || process.env.ConEmuPID || process.env.ConEmuTask) {
- return "conemu";
- }
- if (process.env.WSL_DISTRO_NAME)
- return `wsl-${process.env.WSL_DISTRO_NAME}`;
- if (isSSHSession()) {
- return "ssh-session";
- }
- if (process.env.TERM) {
- const term = process.env.TERM;
- if (term.includes("alacritty"))
- return "alacritty";
- if (term.includes("rxvt"))
- return "rxvt";
- if (term.includes("termite"))
- return "termite";
- return process.env.TERM;
- }
- if (!process.stdout.isTTY)
- return "non-interactive";
- return null;
-}
-function isSSHSession() {
- return !!(process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY);
-}
-function getHostPlatformForAnalytics() {
- const override = process.env.CLAUDE_CODE_HOST_PLATFORM;
- if (override === "win32" || override === "darwin" || override === "linux") {
- return override;
- }
- return env2.platform;
-}
-var getGlobalClaudeFile, hasInternetAccess, detectPackageManagers, detectRuntimes, isWslEnvironment, isNpmFromWindowsPath, JETBRAINS_IDES, detectDeploymentEnvironment, env2;
-var init_env = __esm(() => {
- init_memoize();
- init_oauth();
- init_envUtils();
- init_findExecutable();
- init_fsOperations();
- init_which();
- getGlobalClaudeFile = memoize_default(() => {
- if (getFsImplementation().existsSync(join6(getClaudeConfigHomeDir(), ".config.json"))) {
- return join6(getClaudeConfigHomeDir(), ".config.json");
- }
- const filename = `.claude${fileSuffixForOauthConfig()}.json`;
- return join6(process.env.CLAUDE_CONFIG_DIR || homedir4(), filename);
- });
- hasInternetAccess = memoize_default(async () => {
- try {
- const { default: axiosClient } = await Promise.resolve().then(() => (init_axios2(), exports_axios));
- await axiosClient.head("http://1.1.1.1", {
- signal: AbortSignal.timeout(1000)
- });
- return true;
- } catch {
- return false;
- }
- });
- detectPackageManagers = memoize_default(async () => {
- const packageManagers = [];
- if (await isCommandAvailable("npm"))
- packageManagers.push("npm");
- if (await isCommandAvailable("yarn"))
- packageManagers.push("yarn");
- if (await isCommandAvailable("pnpm"))
- packageManagers.push("pnpm");
- return packageManagers;
- });
- detectRuntimes = memoize_default(async () => {
- const runtimes = [];
- if (await isCommandAvailable("bun"))
- runtimes.push("bun");
- if (await isCommandAvailable("deno"))
- runtimes.push("deno");
- if (await isCommandAvailable("node"))
- runtimes.push("node");
- return runtimes;
- });
- isWslEnvironment = memoize_default(() => {
- try {
- return getFsImplementation().existsSync("/proc/sys/fs/binfmt_misc/WSLInterop");
- } catch (_error) {
- return false;
- }
- });
- isNpmFromWindowsPath = memoize_default(() => {
- try {
- if (!isWslEnvironment()) {
- return false;
- }
- const { cmd } = findExecutable("npm", []);
- return cmd.startsWith("/mnt/c/");
- } catch (_error) {
- return false;
- }
- });
- JETBRAINS_IDES = [
- "pycharm",
- "intellij",
- "webstorm",
- "phpstorm",
- "rubymine",
- "clion",
- "goland",
- "rider",
- "datagrip",
- "appcode",
- "dataspell",
- "aqua",
- "gateway",
- "fleet",
- "jetbrains",
- "androidstudio"
- ];
- detectDeploymentEnvironment = memoize_default(() => {
- if (isEnvTruthy(process.env.CODESPACES))
- return "codespaces";
- if (process.env.GITPOD_WORKSPACE_ID)
- return "gitpod";
- if (process.env.REPL_ID || process.env.REPL_SLUG)
- return "replit";
- if (process.env.PROJECT_DOMAIN)
- return "glitch";
- if (isEnvTruthy(process.env.VERCEL))
- return "vercel";
- if (process.env.RAILWAY_ENVIRONMENT_NAME || process.env.RAILWAY_SERVICE_NAME) {
- return "railway";
- }
- if (isEnvTruthy(process.env.RENDER))
- return "render";
- if (isEnvTruthy(process.env.NETLIFY))
- return "netlify";
- if (process.env.DYNO)
- return "heroku";
- if (process.env.FLY_APP_NAME || process.env.FLY_MACHINE_ID)
- return "fly.io";
- if (isEnvTruthy(process.env.CF_PAGES))
- return "cloudflare-pages";
- if (process.env.DENO_DEPLOYMENT_ID)
- return "deno-deploy";
- if (process.env.AWS_LAMBDA_FUNCTION_NAME)
- return "aws-lambda";
- if (process.env.AWS_EXECUTION_ENV === "AWS_ECS_FARGATE")
- return "aws-fargate";
- if (process.env.AWS_EXECUTION_ENV === "AWS_ECS_EC2")
- return "aws-ecs";
- try {
- const uuid = getFsImplementation().readFileSync("/sys/hypervisor/uuid", { encoding: "utf8" }).trim().toLowerCase();
- if (uuid.startsWith("ec2"))
- return "aws-ec2";
- } catch {}
- if (process.env.K_SERVICE)
- return "gcp-cloud-run";
- if (process.env.GOOGLE_CLOUD_PROJECT)
- return "gcp";
- if (process.env.WEBSITE_SITE_NAME || process.env.WEBSITE_SKU)
- return "azure-app-service";
- if (process.env.AZURE_FUNCTIONS_ENVIRONMENT)
- return "azure-functions";
- if (process.env.APP_URL?.includes("ondigitalocean.app")) {
- return "digitalocean-app-platform";
- }
- if (process.env.SPACE_CREATOR_USER_ID)
- return "huggingface-spaces";
- if (isEnvTruthy(process.env.GITHUB_ACTIONS))
- return "github-actions";
- if (isEnvTruthy(process.env.GITLAB_CI))
- return "gitlab-ci";
- if (process.env.CIRCLECI)
- return "circleci";
- if (process.env.BUILDKITE)
- return "buildkite";
- if (isEnvTruthy(process.env.CI))
- return "ci";
- if (process.env.KUBERNETES_SERVICE_HOST)
- return "kubernetes";
- try {
- if (getFsImplementation().existsSync("/.dockerenv"))
- return "docker";
- } catch {}
- if (env2.platform === "darwin")
- return "unknown-darwin";
- if (env2.platform === "linux")
- return "unknown-linux";
- if (env2.platform === "win32")
- return "unknown-win32";
- return "unknown";
- });
- env2 = {
- hasInternetAccess,
- isCI: isEnvTruthy(process.env.CI),
- platform: ["win32", "darwin"].includes(process.platform) ? process.platform : "linux",
- arch: process.arch,
- nodeVersion: process.version,
- terminal: detectTerminal(),
- isSSH: isSSHSession,
- getPackageManagers: detectPackageManagers,
- getRuntimes: detectRuntimes,
- isRunningWithBun: memoize_default(isRunningWithBun),
- isWslEnvironment,
- isNpmFromWindowsPath,
- isConductor,
- detectDeploymentEnvironment
- };
-});
-
-// src/utils/fileRead.ts
-function detectEncodingForResolvedPath(resolvedPath) {
- const { buffer, bytesRead } = getFsImplementation().readSync(resolvedPath, {
- length: 4096
- });
- if (bytesRead === 0) {
- return "utf8";
- }
- if (bytesRead >= 2) {
- if (buffer[0] === 255 && buffer[1] === 254)
- return "utf16le";
- }
- if (bytesRead >= 3 && buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191) {
- return "utf8";
- }
- return "utf8";
-}
-function detectLineEndingsForString(content) {
- let crlfCount = 0;
- let lfCount = 0;
- for (let i2 = 0;i2 < content.length; i2++) {
- if (content[i2] === `
-`) {
- if (i2 > 0 && content[i2 - 1] === "\r") {
- crlfCount++;
- } else {
- lfCount++;
- }
- }
- }
- return crlfCount > lfCount ? "CRLF" : "LF";
-}
-function readFileSyncWithMetadata(filePath) {
- const fs2 = getFsImplementation();
- const { resolvedPath, isSymlink } = safeResolvePath(fs2, filePath);
- if (isSymlink) {
- logForDebugging(`Reading through symlink: ${filePath} -> ${resolvedPath}`);
- }
- const encoding = detectEncodingForResolvedPath(resolvedPath);
- const raw = fs2.readFileSync(resolvedPath, { encoding });
- const lineEndings = detectLineEndingsForString(raw.slice(0, 4096));
- return {
- content: raw.replaceAll(`\r
-`, `
-`),
- encoding,
- lineEndings
- };
-}
-function readFileSync4(filePath) {
- return readFileSyncWithMetadata(filePath).content;
-}
-var init_fileRead = __esm(() => {
- init_debug();
- init_fsOperations();
-});
-
-// src/utils/fileReadCache.ts
-class FileReadCache {
- cache = new Map;
- maxCacheSize = 1000;
- readFile(filePath) {
- const fs2 = getFsImplementation();
- let stats;
- try {
- stats = fs2.statSync(filePath);
- } catch (error) {
- this.cache.delete(filePath);
- throw error;
- }
- const cacheKey = filePath;
- const cachedData = this.cache.get(cacheKey);
- if (cachedData && cachedData.mtime === stats.mtimeMs) {
- return {
- content: cachedData.content,
- encoding: cachedData.encoding
- };
- }
- const encoding = detectFileEncoding(filePath);
- const content = fs2.readFileSync(filePath, { encoding }).replaceAll(`\r
-`, `
-`);
- this.cache.set(cacheKey, {
- content,
- encoding,
- mtime: stats.mtimeMs
- });
- if (this.cache.size > this.maxCacheSize) {
- const firstKey = this.cache.keys().next().value;
- if (firstKey) {
- this.cache.delete(firstKey);
- }
- }
- return { content, encoding };
- }
- clear() {
- this.cache.clear();
- }
- invalidate(filePath) {
- this.cache.delete(filePath);
- }
- getStats() {
- return {
- size: this.cache.size,
- entries: Array.from(this.cache.keys())
- };
- }
-}
-var fileReadCache;
-var init_fileReadCache = __esm(() => {
- init_file();
- init_fsOperations();
- fileReadCache = new FileReadCache;
-});
-
-// src/constants/xml.ts
-var COMMAND_NAME_TAG = "command-name", COMMAND_MESSAGE_TAG = "command-message", COMMAND_ARGS_TAG = "command-args", BASH_INPUT_TAG = "bash-input", BASH_STDOUT_TAG = "bash-stdout", BASH_STDERR_TAG = "bash-stderr", LOCAL_COMMAND_STDOUT_TAG = "local-command-stdout", LOCAL_COMMAND_STDERR_TAG = "local-command-stderr", LOCAL_COMMAND_CAVEAT_TAG = "local-command-caveat", TERMINAL_OUTPUT_TAGS, TICK_TAG = "tick", TASK_NOTIFICATION_TAG = "task-notification", TASK_ID_TAG = "task-id", TOOL_USE_ID_TAG = "tool-use-id", TASK_TYPE_TAG = "task-type", OUTPUT_FILE_TAG = "output-file", STATUS_TAG = "status", SUMMARY_TAG = "summary", WORKTREE_TAG = "worktree", WORKTREE_PATH_TAG = "worktreePath", WORKTREE_BRANCH_TAG = "worktreeBranch", REMOTE_REVIEW_TAG = "remote-review", REMOTE_REVIEW_PROGRESS_TAG = "remote-review-progress", TEAMMATE_MESSAGE_TAG = "teammate-message", CHANNEL_TAG = "channel", FORK_BOILERPLATE_TAG = "fork-boilerplate", FORK_DIRECTIVE_PREFIX = "Your directive: ", COMMON_HELP_ARGS, COMMON_INFO_ARGS;
-var init_xml = __esm(() => {
- TERMINAL_OUTPUT_TAGS = [
- BASH_INPUT_TAG,
- BASH_STDOUT_TAG,
- BASH_STDERR_TAG,
- LOCAL_COMMAND_STDOUT_TAG,
- LOCAL_COMMAND_STDERR_TAG,
- LOCAL_COMMAND_CAVEAT_TAG
- ];
- COMMON_HELP_ARGS = ["help", "-h", "--help"];
- COMMON_INFO_ARGS = [
- "list",
- "show",
- "display",
- "current",
- "view",
- "get",
- "check",
- "describe",
- "print",
- "version",
- "about",
- "status",
- "?"
- ];
-});
-
-// src/types/logs.ts
-function sortLogs(logs) {
- return logs.sort((a2, b) => {
- const modifiedDiff = b.modified.getTime() - a2.modified.getTime();
- if (modifiedDiff !== 0) {
- return modifiedDiff;
- }
- return b.created.getTime() - a2.created.getTime();
- });
-}
-
-// node_modules/env-paths/index.js
-import path6 from "path";
-import os2 from "os";
-import process11 from "process";
-function envPaths(name, { suffix = "nodejs" } = {}) {
- if (typeof name !== "string") {
- throw new TypeError(`Expected a string, got ${typeof name}`);
- }
- if (suffix) {
- name += `-${suffix}`;
- }
- if (process11.platform === "darwin") {
- return macos(name);
- }
- if (process11.platform === "win32") {
- return windows(name);
- }
- return linux(name);
-}
-var homedir5, tmpdir, env3, macos = (name) => {
- const library = path6.join(homedir5, "Library");
- return {
- data: path6.join(library, "Application Support", name),
- config: path6.join(library, "Preferences", name),
- cache: path6.join(library, "Caches", name),
- log: path6.join(library, "Logs", name),
- temp: path6.join(tmpdir, name)
- };
-}, windows = (name) => {
- const appData = env3.APPDATA || path6.join(homedir5, "AppData", "Roaming");
- const localAppData = env3.LOCALAPPDATA || path6.join(homedir5, "AppData", "Local");
- return {
- data: path6.join(localAppData, name, "Data"),
- config: path6.join(appData, name, "Config"),
- cache: path6.join(localAppData, name, "Cache"),
- log: path6.join(localAppData, name, "Log"),
- temp: path6.join(tmpdir, name)
- };
-}, linux = (name) => {
- const username = path6.basename(homedir5);
- return {
- data: path6.join(env3.XDG_DATA_HOME || path6.join(homedir5, ".local", "share"), name),
- config: path6.join(env3.XDG_CONFIG_HOME || path6.join(homedir5, ".config"), name),
- cache: path6.join(env3.XDG_CACHE_HOME || path6.join(homedir5, ".cache"), name),
- log: path6.join(env3.XDG_STATE_HOME || path6.join(homedir5, ".local", "state"), name),
- temp: path6.join(tmpdir, username, name)
- };
-};
-var init_env_paths = __esm(() => {
- homedir5 = os2.homedir();
- tmpdir = os2.tmpdir();
- ({ env: env3 } = process11);
-});
-
-// src/utils/hash.ts
-function djb2Hash(str) {
- let hash2 = 0;
- for (let i2 = 0;i2 < str.length; i2++) {
- hash2 = (hash2 << 5) - hash2 + str.charCodeAt(i2) | 0;
- }
- return hash2;
-}
-function hashContent(content) {
- if (typeof Bun !== "undefined") {
- return Bun.hash(content).toString();
- }
- const crypto3 = __require("crypto");
- return crypto3.createHash("sha256").update(content).digest("hex");
-}
-function hashPair(a2, b) {
- if (typeof Bun !== "undefined") {
- return Bun.hash(b, Bun.hash(a2)).toString();
- }
- const crypto3 = __require("crypto");
- return crypto3.createHash("sha256").update(a2).update("\x00").update(b).digest("hex");
-}
-
-// src/utils/cachePaths.ts
-import { join as join7 } from "path";
-function sanitizePath(name) {
- const sanitized = name.replace(/[^a-zA-Z0-9]/g, "-");
- if (sanitized.length <= MAX_SANITIZED_LENGTH) {
- return sanitized;
- }
- return `${sanitized.slice(0, MAX_SANITIZED_LENGTH)}-${Math.abs(djb2Hash(name)).toString(36)}`;
-}
-function getProjectDir(cwd2) {
- return sanitizePath(cwd2);
-}
-var paths, MAX_SANITIZED_LENGTH = 200, CACHE_PATHS;
-var init_cachePaths = __esm(() => {
- init_env_paths();
- init_fsOperations();
- paths = envPaths("claude-cli");
- CACHE_PATHS = {
- baseLogs: () => join7(paths.cache, getProjectDir(getFsImplementation().cwd())),
- errors: () => join7(paths.cache, getProjectDir(getFsImplementation().cwd()), "errors"),
- messages: () => join7(paths.cache, getProjectDir(getFsImplementation().cwd()), "messages"),
- mcpLogs: (serverName) => join7(paths.cache, getProjectDir(getFsImplementation().cwd()), `mcp-logs-${sanitizePath(serverName)}`)
- };
-});
-
-// src/utils/displayTags.ts
-function stripDisplayTags(text) {
- const result = text.replace(XML_TAG_BLOCK_PATTERN, "").trim();
- return result || text;
-}
-function stripDisplayTagsAllowEmpty(text) {
- return text.replace(XML_TAG_BLOCK_PATTERN, "").trim();
-}
-function stripIdeContextTags(text) {
- return text.replace(IDE_CONTEXT_TAGS_PATTERN, "").trim();
-}
-var XML_TAG_BLOCK_PATTERN, IDE_CONTEXT_TAGS_PATTERN;
-var init_displayTags = __esm(() => {
- XML_TAG_BLOCK_PATTERN = /<([a-z][\w-]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>\n?/g;
- IDE_CONTEXT_TAGS_PATTERN = /<(ide_opened_file|ide_selection)(?:\s[^>]*)?>[\s\S]*?<\/\1>\n?/g;
-});
-
-// src/utils/privacyLevel.ts
-function getPrivacyLevel() {
- if (process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC) {
- return "essential-traffic";
- }
- if (process.env.DISABLE_TELEMETRY) {
- return "no-telemetry";
- }
- return "default";
-}
-function isEssentialTrafficOnly() {
- return getPrivacyLevel() === "essential-traffic";
-}
-function isTelemetryDisabled() {
- return getPrivacyLevel() !== "default";
-}
-function getEssentialTrafficOnlyReason() {
- if (process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC) {
- return "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC";
- }
- return null;
-}
-
-// src/utils/log.ts
-function getLogDisplayTitle(log, defaultTitle) {
- const isAutonomousPrompt = log.firstPrompt?.startsWith(`<${TICK_TAG}>`);
- const strippedFirstPrompt = log.firstPrompt ? stripDisplayTagsAllowEmpty(log.firstPrompt) : "";
- const useFirstPrompt = strippedFirstPrompt && !isAutonomousPrompt;
- const title = log.agentName || log.customTitle || log.summary || (useFirstPrompt ? strippedFirstPrompt : undefined) || defaultTitle || (isAutonomousPrompt ? "Autonomous session" : undefined) || (log.sessionId ? log.sessionId.slice(0, 8) : "") || "";
- return stripDisplayTags(title).trim();
-}
-function dateToFilename(date) {
- return date.toISOString().replace(/[:.]/g, "-");
-}
-function addToInMemoryErrorLog2(errorInfo) {
- if (inMemoryErrorLog.length >= MAX_IN_MEMORY_ERRORS) {
- inMemoryErrorLog.shift();
- }
- inMemoryErrorLog.push(errorInfo);
-}
-function attachErrorLogSink(newSink) {
- if (errorLogSink !== null) {
- return;
- }
- errorLogSink = newSink;
- if (errorQueue.length > 0) {
- const queuedEvents = [...errorQueue];
- errorQueue.length = 0;
- for (const event of queuedEvents) {
- switch (event.type) {
- case "error":
- errorLogSink.logError(event.error);
- break;
- case "mcpError":
- errorLogSink.logMCPError(event.serverName, event.error);
- break;
- case "mcpDebug":
- errorLogSink.logMCPDebug(event.serverName, event.message);
- break;
- }
- }
- }
-}
-function logError2(error) {
- const err = toError(error);
- if (false) {}
- try {
- if (isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) || isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) || isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY) || process.env.DISABLE_ERROR_REPORTING || isEssentialTrafficOnly()) {
- return;
- }
- const errorStr = err.stack || err.message;
- const errorInfo = {
- error: errorStr,
- timestamp: new Date().toISOString()
- };
- addToInMemoryErrorLog2(errorInfo);
- if (errorLogSink === null) {
- errorQueue.push({ type: "error", error: err });
- return;
- }
- errorLogSink.logError(err);
- } catch {}
-}
-function getInMemoryErrors() {
- return [...inMemoryErrorLog];
-}
-function logMCPError(serverName, error) {
- try {
- if (errorLogSink === null) {
- errorQueue.push({ type: "mcpError", serverName, error });
- return;
- }
- errorLogSink.logMCPError(serverName, error);
- } catch {}
-}
-function logMCPDebug(serverName, message) {
- try {
- if (errorLogSink === null) {
- errorQueue.push({ type: "mcpDebug", serverName, message });
- return;
- }
- errorLogSink.logMCPDebug(serverName, message);
- } catch {}
-}
-function captureAPIRequest(params, querySource) {
- if (!querySource || !querySource.startsWith("repl_main_thread")) {
- return;
- }
- const { messages, ...paramsWithoutMessages } = params;
- setLastAPIRequest(paramsWithoutMessages);
- setLastAPIRequestMessages(process.env.USER_TYPE === "ant" ? messages : null);
-}
-var MAX_IN_MEMORY_ERRORS = 100, inMemoryErrorLog, errorQueue, errorLogSink = null, isHardFailMode;
-var init_log2 = __esm(() => {
- init_memoize();
- init_state();
- init_xml();
- init_cachePaths();
- init_displayTags();
- init_envUtils();
- init_errors();
- init_slowOperations();
- inMemoryErrorLog = [];
- errorQueue = [];
- isHardFailMode = memoize_default(() => {
- return process.argv.includes("--hard-fail");
- });
-});
-
-// src/utils/platform.ts
-import { readdir, readFile } from "fs/promises";
-import { release as osRelease } from "os";
-async function detectVcs(dir) {
- const detected = new Set;
- if (process.env.P4PORT) {
- detected.add("perforce");
- }
- try {
- const targetDir = dir ?? getFsImplementation().cwd();
- const entries = new Set(await readdir(targetDir));
- for (const [marker, vcs] of VCS_MARKERS) {
- if (entries.has(marker)) {
- detected.add(vcs);
- }
- }
- } catch {}
- return [...detected];
-}
-var SUPPORTED_PLATFORMS, getPlatform, getWslVersion, getLinuxDistroInfo, VCS_MARKERS;
-var init_platform2 = __esm(() => {
- init_memoize();
- init_fsOperations();
- init_log2();
- SUPPORTED_PLATFORMS = ["macos", "wsl"];
- getPlatform = memoize_default(() => {
- try {
- if (process.platform === "darwin") {
- return "macos";
- }
- if (process.platform === "win32") {
- return "windows";
- }
- if (process.platform === "linux") {
- try {
- const procVersion = getFsImplementation().readFileSync("/proc/version", { encoding: "utf8" });
- if (procVersion.toLowerCase().includes("microsoft") || procVersion.toLowerCase().includes("wsl")) {
- return "wsl";
- }
- } catch (error) {
- logError2(error);
- }
- return "linux";
- }
- return "unknown";
- } catch (error) {
- logError2(error);
- return "unknown";
- }
- });
- getWslVersion = memoize_default(() => {
- if (process.platform !== "linux") {
- return;
- }
- try {
- const procVersion = getFsImplementation().readFileSync("/proc/version", {
- encoding: "utf8"
- });
- const wslVersionMatch = procVersion.match(/WSL(\d+)/i);
- if (wslVersionMatch && wslVersionMatch[1]) {
- return wslVersionMatch[1];
- }
- if (procVersion.toLowerCase().includes("microsoft")) {
- return "1";
- }
- return;
- } catch (error) {
- logError2(error);
- return;
- }
- });
- getLinuxDistroInfo = memoize_default(async () => {
- if (process.platform !== "linux") {
- return;
- }
- const result = {
- linuxKernel: osRelease()
- };
- try {
- const content = await readFile("/etc/os-release", "utf8");
- for (const line of content.split(`
-`)) {
- const match = line.match(/^(ID|VERSION_ID)=(.*)$/);
- if (match && match[1] && match[2]) {
- const value = match[2].replace(/^"|"$/g, "");
- if (match[1] === "ID") {
- result.linuxDistroId = value;
- } else {
- result.linuxDistroVersion = value;
- }
- }
- }
- } catch {}
- return result;
- });
- VCS_MARKERS = [
- [".git", "git"],
- [".hg", "mercurial"],
- [".svn", "svn"],
- [".p4config", "perforce"],
- ["$tf", "tfs"],
- [".tfvc", "tfs"],
- [".jj", "jujutsu"],
- [".sl", "sapling"]
- ];
-});
-
-// node_modules/lru-cache/dist/esm/index.min.js
-var x, I, R, U = (c3, t, e, i2) => {
- typeof R.emitWarning == "function" ? R.emitWarning(c3, t, e, i2) : console.error(`[${e}] ${t}: ${c3}`);
-}, C, D, G2 = (c3) => !I.has(c3), H, y = (c3) => c3 && c3 === Math.floor(c3) && c3 > 0 && isFinite(c3), M = (c3) => y(c3) ? c3 <= Math.pow(2, 8) ? Uint8Array : c3 <= Math.pow(2, 16) ? Uint16Array : c3 <= Math.pow(2, 32) ? Uint32Array : c3 <= Number.MAX_SAFE_INTEGER ? z : null : null, z, W = class c3 {
- heap;
- length;
- static #o = false;
- static create(t) {
- let e = M(t);
- if (!e)
- return [];
- c3.#o = true;
- let i2 = new c3(t, e);
- return c3.#o = false, i2;
- }
- constructor(t, e) {
- if (!c3.#o)
- throw new TypeError("instantiate Stack using Stack.create(n)");
- this.heap = new e(t), this.length = 0;
- }
- push(t) {
- this.heap[this.length++] = t;
- }
- pop() {
- return this.heap[--this.length];
- }
-}, L;
-var init_index_min = __esm(() => {
- x = typeof performance == "object" && performance && typeof performance.now == "function" ? performance : Date;
- I = new Set;
- R = typeof process == "object" && process ? process : {};
- C = globalThis.AbortController;
- D = globalThis.AbortSignal;
- if (typeof C > "u") {
- D = class {
- onabort;
- _onabort = [];
- reason;
- aborted = false;
- addEventListener(i2, s) {
- this._onabort.push(s);
- }
- }, C = class {
- constructor() {
- t();
- }
- signal = new D;
- abort(i2) {
- if (!this.signal.aborted) {
- this.signal.reason = i2, this.signal.aborted = true;
- for (let s of this.signal._onabort)
- s(i2);
- this.signal.onabort?.(i2);
- }
- }
- };
- let c3 = R.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1", t = () => {
- c3 && (c3 = false, U("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", t));
- };
- }
- H = Symbol("type");
- z = class extends Array {
- constructor(t) {
- super(t), this.fill(0);
- }
- };
- L = class c4 {
- #o;
- #c;
- #w;
- #C;
- #S;
- #L;
- #I;
- #m;
- get perf() {
- return this.#m;
- }
- ttl;
- ttlResolution;
- ttlAutopurge;
- updateAgeOnGet;
- updateAgeOnHas;
- allowStale;
- noDisposeOnSet;
- noUpdateTTL;
- maxEntrySize;
- sizeCalculation;
- noDeleteOnFetchRejection;
- noDeleteOnStaleGet;
- allowStaleOnFetchAbort;
- allowStaleOnFetchRejection;
- ignoreFetchAbort;
- #n;
- #_;
- #s;
- #i;
- #t;
- #a;
- #u;
- #l;
- #h;
- #b;
- #r;
- #y;
- #A;
- #d;
- #g;
- #T;
- #v;
- #f;
- #U;
- static unsafeExposeInternals(t) {
- return { starts: t.#A, ttls: t.#d, autopurgeTimers: t.#g, sizes: t.#y, keyMap: t.#s, keyList: t.#i, valList: t.#t, next: t.#a, prev: t.#u, get head() {
- return t.#l;
- }, get tail() {
- return t.#h;
- }, free: t.#b, isBackgroundFetch: (e) => t.#e(e), backgroundFetch: (e, i2, s, n2) => t.#G(e, i2, s, n2), moveToTail: (e) => t.#D(e), indexes: (e) => t.#F(e), rindexes: (e) => t.#O(e), isStale: (e) => t.#p(e) };
- }
- get max() {
- return this.#o;
- }
- get maxSize() {
- return this.#c;
- }
- get calculatedSize() {
- return this.#_;
- }
- get size() {
- return this.#n;
- }
- get fetchMethod() {
- return this.#L;
- }
- get memoMethod() {
- return this.#I;
- }
- get dispose() {
- return this.#w;
- }
- get onInsert() {
- return this.#C;
- }
- get disposeAfter() {
- return this.#S;
- }
- constructor(t) {
- let { max: e = 0, ttl: i2, ttlResolution: s = 1, ttlAutopurge: n2, updateAgeOnGet: o2, updateAgeOnHas: h2, allowStale: r, dispose: a2, onInsert: w, disposeAfter: f, noDisposeOnSet: d, noUpdateTTL: g, maxSize: A = 0, maxEntrySize: p = 0, sizeCalculation: _, fetchMethod: l, memoMethod: S, noDeleteOnFetchRejection: b, noDeleteOnStaleGet: m, allowStaleOnFetchRejection: u2, allowStaleOnFetchAbort: T, ignoreFetchAbort: F, perf: v } = t;
- if (v !== undefined && typeof v?.now != "function")
- throw new TypeError("perf option must have a now() method if specified");
- if (this.#m = v ?? x, e !== 0 && !y(e))
- throw new TypeError("max option must be a nonnegative integer");
- let O = e ? M(e) : Array;
- if (!O)
- throw new Error("invalid max value: " + e);
- if (this.#o = e, this.#c = A, this.maxEntrySize = p || this.#c, this.sizeCalculation = _, this.sizeCalculation) {
- if (!this.#c && !this.maxEntrySize)
- throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
- if (typeof this.sizeCalculation != "function")
- throw new TypeError("sizeCalculation set to non-function");
- }
- if (S !== undefined && typeof S != "function")
- throw new TypeError("memoMethod must be a function if defined");
- if (this.#I = S, l !== undefined && typeof l != "function")
- throw new TypeError("fetchMethod must be a function if specified");
- if (this.#L = l, this.#v = !!l, this.#s = new Map, this.#i = new Array(e).fill(undefined), this.#t = new Array(e).fill(undefined), this.#a = new O(e), this.#u = new O(e), this.#l = 0, this.#h = 0, this.#b = W.create(e), this.#n = 0, this.#_ = 0, typeof a2 == "function" && (this.#w = a2), typeof w == "function" && (this.#C = w), typeof f == "function" ? (this.#S = f, this.#r = []) : (this.#S = undefined, this.#r = undefined), this.#T = !!this.#w, this.#U = !!this.#C, this.#f = !!this.#S, this.noDisposeOnSet = !!d, this.noUpdateTTL = !!g, this.noDeleteOnFetchRejection = !!b, this.allowStaleOnFetchRejection = !!u2, this.allowStaleOnFetchAbort = !!T, this.ignoreFetchAbort = !!F, this.maxEntrySize !== 0) {
- if (this.#c !== 0 && !y(this.#c))
- throw new TypeError("maxSize must be a positive integer if specified");
- if (!y(this.maxEntrySize))
- throw new TypeError("maxEntrySize must be a positive integer if specified");
- this.#B();
- }
- if (this.allowStale = !!r, this.noDeleteOnStaleGet = !!m, this.updateAgeOnGet = !!o2, this.updateAgeOnHas = !!h2, this.ttlResolution = y(s) || s === 0 ? s : 1, this.ttlAutopurge = !!n2, this.ttl = i2 || 0, this.ttl) {
- if (!y(this.ttl))
- throw new TypeError("ttl must be a positive integer if specified");
- this.#j();
- }
- if (this.#o === 0 && this.ttl === 0 && this.#c === 0)
- throw new TypeError("At least one of max, maxSize, or ttl is required");
- if (!this.ttlAutopurge && !this.#o && !this.#c) {
- let E = "LRU_CACHE_UNBOUNDED";
- G2(E) && (I.add(E), U("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.", "UnboundedCacheWarning", E, c4));
- }
- }
- getRemainingTTL(t) {
- return this.#s.has(t) ? 1 / 0 : 0;
- }
- #j() {
- let t = new z(this.#o), e = new z(this.#o);
- this.#d = t, this.#A = e;
- let i2 = this.ttlAutopurge ? new Array(this.#o) : undefined;
- this.#g = i2, this.#N = (h2, r, a2 = this.#m.now()) => {
- e[h2] = r !== 0 ? a2 : 0, t[h2] = r, s(h2, r);
- }, this.#R = (h2) => {
- e[h2] = t[h2] !== 0 ? this.#m.now() : 0, s(h2, t[h2]);
- };
- let s = this.ttlAutopurge ? (h2, r) => {
- if (i2?.[h2] && (clearTimeout(i2[h2]), i2[h2] = undefined), r && r !== 0 && i2) {
- let a2 = setTimeout(() => {
- this.#p(h2) && this.#E(this.#i[h2], "expire");
- }, r + 1);
- a2.unref && a2.unref(), i2[h2] = a2;
- }
- } : () => {};
- this.#z = (h2, r) => {
- if (t[r]) {
- let a2 = t[r], w = e[r];
- if (!a2 || !w)
- return;
- h2.ttl = a2, h2.start = w, h2.now = n2 || o2();
- let f = h2.now - w;
- h2.remainingTTL = a2 - f;
- }
- };
- let n2 = 0, o2 = () => {
- let h2 = this.#m.now();
- if (this.ttlResolution > 0) {
- n2 = h2;
- let r = setTimeout(() => n2 = 0, this.ttlResolution);
- r.unref && r.unref();
- }
- return h2;
- };
- this.getRemainingTTL = (h2) => {
- let r = this.#s.get(h2);
- if (r === undefined)
- return 0;
- let a2 = t[r], w = e[r];
- if (!a2 || !w)
- return 1 / 0;
- let f = (n2 || o2()) - w;
- return a2 - f;
- }, this.#p = (h2) => {
- let r = e[h2], a2 = t[h2];
- return !!a2 && !!r && (n2 || o2()) - r > a2;
- };
- }
- #R = () => {};
- #z = () => {};
- #N = () => {};
- #p = () => false;
- #B() {
- let t = new z(this.#o);
- this.#_ = 0, this.#y = t, this.#W = (e) => {
- this.#_ -= t[e], t[e] = 0;
- }, this.#P = (e, i2, s, n2) => {
- if (this.#e(i2))
- return 0;
- if (!y(s))
- if (n2) {
- if (typeof n2 != "function")
- throw new TypeError("sizeCalculation must be a function");
- if (s = n2(i2, e), !y(s))
- throw new TypeError("sizeCalculation return invalid (expect positive integer)");
- } else
- throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
- return s;
- }, this.#M = (e, i2, s) => {
- if (t[e] = i2, this.#c) {
- let n2 = this.#c - t[e];
- for (;this.#_ > n2; )
- this.#x(true);
- }
- this.#_ += t[e], s && (s.entrySize = i2, s.totalCalculatedSize = this.#_);
- };
- }
- #W = (t) => {};
- #M = (t, e, i2) => {};
- #P = (t, e, i2, s) => {
- if (i2 || s)
- throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
- return 0;
- };
- *#F({ allowStale: t = this.allowStale } = {}) {
- if (this.#n)
- for (let e = this.#h;!(!this.#H(e) || ((t || !this.#p(e)) && (yield e), e === this.#l)); )
- e = this.#u[e];
- }
- *#O({ allowStale: t = this.allowStale } = {}) {
- if (this.#n)
- for (let e = this.#l;!(!this.#H(e) || ((t || !this.#p(e)) && (yield e), e === this.#h)); )
- e = this.#a[e];
- }
- #H(t) {
- return t !== undefined && this.#s.get(this.#i[t]) === t;
- }
- *entries() {
- for (let t of this.#F())
- this.#t[t] !== undefined && this.#i[t] !== undefined && !this.#e(this.#t[t]) && (yield [this.#i[t], this.#t[t]]);
- }
- *rentries() {
- for (let t of this.#O())
- this.#t[t] !== undefined && this.#i[t] !== undefined && !this.#e(this.#t[t]) && (yield [this.#i[t], this.#t[t]]);
- }
- *keys() {
- for (let t of this.#F()) {
- let e = this.#i[t];
- e !== undefined && !this.#e(this.#t[t]) && (yield e);
- }
- }
- *rkeys() {
- for (let t of this.#O()) {
- let e = this.#i[t];
- e !== undefined && !this.#e(this.#t[t]) && (yield e);
- }
- }
- *values() {
- for (let t of this.#F())
- this.#t[t] !== undefined && !this.#e(this.#t[t]) && (yield this.#t[t]);
- }
- *rvalues() {
- for (let t of this.#O())
- this.#t[t] !== undefined && !this.#e(this.#t[t]) && (yield this.#t[t]);
- }
- [Symbol.iterator]() {
- return this.entries();
- }
- [Symbol.toStringTag] = "LRUCache";
- find(t, e = {}) {
- for (let i2 of this.#F()) {
- let s = this.#t[i2], n2 = this.#e(s) ? s.__staleWhileFetching : s;
- if (n2 !== undefined && t(n2, this.#i[i2], this))
- return this.get(this.#i[i2], e);
- }
- }
- forEach(t, e = this) {
- for (let i2 of this.#F()) {
- let s = this.#t[i2], n2 = this.#e(s) ? s.__staleWhileFetching : s;
- n2 !== undefined && t.call(e, n2, this.#i[i2], this);
- }
- }
- rforEach(t, e = this) {
- for (let i2 of this.#O()) {
- let s = this.#t[i2], n2 = this.#e(s) ? s.__staleWhileFetching : s;
- n2 !== undefined && t.call(e, n2, this.#i[i2], this);
- }
- }
- purgeStale() {
- let t = false;
- for (let e of this.#O({ allowStale: true }))
- this.#p(e) && (this.#E(this.#i[e], "expire"), t = true);
- return t;
- }
- info(t) {
- let e = this.#s.get(t);
- if (e === undefined)
- return;
- let i2 = this.#t[e], s = this.#e(i2) ? i2.__staleWhileFetching : i2;
- if (s === undefined)
- return;
- let n2 = { value: s };
- if (this.#d && this.#A) {
- let o2 = this.#d[e], h2 = this.#A[e];
- if (o2 && h2) {
- let r = o2 - (this.#m.now() - h2);
- n2.ttl = r, n2.start = Date.now();
- }
- }
- return this.#y && (n2.size = this.#y[e]), n2;
- }
- dump() {
- let t = [];
- for (let e of this.#F({ allowStale: true })) {
- let i2 = this.#i[e], s = this.#t[e], n2 = this.#e(s) ? s.__staleWhileFetching : s;
- if (n2 === undefined || i2 === undefined)
- continue;
- let o2 = { value: n2 };
- if (this.#d && this.#A) {
- o2.ttl = this.#d[e];
- let h2 = this.#m.now() - this.#A[e];
- o2.start = Math.floor(Date.now() - h2);
- }
- this.#y && (o2.size = this.#y[e]), t.unshift([i2, o2]);
- }
- return t;
- }
- load(t) {
- this.clear();
- for (let [e, i2] of t) {
- if (i2.start) {
- let s = Date.now() - i2.start;
- i2.start = this.#m.now() - s;
- }
- this.set(e, i2.value, i2);
- }
- }
- set(t, e, i2 = {}) {
- if (e === undefined)
- return this.delete(t), this;
- let { ttl: s = this.ttl, start: n2, noDisposeOnSet: o2 = this.noDisposeOnSet, sizeCalculation: h2 = this.sizeCalculation, status: r } = i2, { noUpdateTTL: a2 = this.noUpdateTTL } = i2, w = this.#P(t, e, i2.size || 0, h2);
- if (this.maxEntrySize && w > this.maxEntrySize)
- return r && (r.set = "miss", r.maxEntrySizeExceeded = true), this.#E(t, "set"), this;
- let f = this.#n === 0 ? undefined : this.#s.get(t);
- if (f === undefined)
- f = this.#n === 0 ? this.#h : this.#b.length !== 0 ? this.#b.pop() : this.#n === this.#o ? this.#x(false) : this.#n, this.#i[f] = t, this.#t[f] = e, this.#s.set(t, f), this.#a[this.#h] = f, this.#u[f] = this.#h, this.#h = f, this.#n++, this.#M(f, w, r), r && (r.set = "add"), a2 = false, this.#U && this.#C?.(e, t, "add");
- else {
- this.#D(f);
- let d = this.#t[f];
- if (e !== d) {
- if (this.#v && this.#e(d)) {
- d.__abortController.abort(new Error("replaced"));
- let { __staleWhileFetching: g } = d;
- g !== undefined && !o2 && (this.#T && this.#w?.(g, t, "set"), this.#f && this.#r?.push([g, t, "set"]));
- } else
- o2 || (this.#T && this.#w?.(d, t, "set"), this.#f && this.#r?.push([d, t, "set"]));
- if (this.#W(f), this.#M(f, w, r), this.#t[f] = e, r) {
- r.set = "replace";
- let g = d && this.#e(d) ? d.__staleWhileFetching : d;
- g !== undefined && (r.oldValue = g);
- }
- } else
- r && (r.set = "update");
- this.#U && this.onInsert?.(e, t, e === d ? "update" : "replace");
- }
- if (s !== 0 && !this.#d && this.#j(), this.#d && (a2 || this.#N(f, s, n2), r && this.#z(r, f)), !o2 && this.#f && this.#r) {
- let d = this.#r, g;
- for (;g = d?.shift(); )
- this.#S?.(...g);
- }
- return this;
- }
- pop() {
- try {
- for (;this.#n; ) {
- let t = this.#t[this.#l];
- if (this.#x(true), this.#e(t)) {
- if (t.__staleWhileFetching)
- return t.__staleWhileFetching;
- } else if (t !== undefined)
- return t;
- }
- } finally {
- if (this.#f && this.#r) {
- let t = this.#r, e;
- for (;e = t?.shift(); )
- this.#S?.(...e);
- }
- }
- }
- #x(t) {
- let e = this.#l, i2 = this.#i[e], s = this.#t[e];
- return this.#v && this.#e(s) ? s.__abortController.abort(new Error("evicted")) : (this.#T || this.#f) && (this.#T && this.#w?.(s, i2, "evict"), this.#f && this.#r?.push([s, i2, "evict"])), this.#W(e), this.#g?.[e] && (clearTimeout(this.#g[e]), this.#g[e] = undefined), t && (this.#i[e] = undefined, this.#t[e] = undefined, this.#b.push(e)), this.#n === 1 ? (this.#l = this.#h = 0, this.#b.length = 0) : this.#l = this.#a[e], this.#s.delete(i2), this.#n--, e;
- }
- has(t, e = {}) {
- let { updateAgeOnHas: i2 = this.updateAgeOnHas, status: s } = e, n2 = this.#s.get(t);
- if (n2 !== undefined) {
- let o2 = this.#t[n2];
- if (this.#e(o2) && o2.__staleWhileFetching === undefined)
- return false;
- if (this.#p(n2))
- s && (s.has = "stale", this.#z(s, n2));
- else
- return i2 && this.#R(n2), s && (s.has = "hit", this.#z(s, n2)), true;
- } else
- s && (s.has = "miss");
- return false;
- }
- peek(t, e = {}) {
- let { allowStale: i2 = this.allowStale } = e, s = this.#s.get(t);
- if (s === undefined || !i2 && this.#p(s))
- return;
- let n2 = this.#t[s];
- return this.#e(n2) ? n2.__staleWhileFetching : n2;
- }
- #G(t, e, i2, s) {
- let n2 = e === undefined ? undefined : this.#t[e];
- if (this.#e(n2))
- return n2;
- let o2 = new C, { signal: h2 } = i2;
- h2?.addEventListener("abort", () => o2.abort(h2.reason), { signal: o2.signal });
- let r = { signal: o2.signal, options: i2, context: s }, a2 = (p, _ = false) => {
- let { aborted: l } = o2.signal, S = i2.ignoreFetchAbort && p !== undefined, b = i2.ignoreFetchAbort || !!(i2.allowStaleOnFetchAbort && p !== undefined);
- if (i2.status && (l && !_ ? (i2.status.fetchAborted = true, i2.status.fetchError = o2.signal.reason, S && (i2.status.fetchAbortIgnored = true)) : i2.status.fetchResolved = true), l && !S && !_)
- return f(o2.signal.reason, b);
- let m = g, u2 = this.#t[e];
- return (u2 === g || S && _ && u2 === undefined) && (p === undefined ? m.__staleWhileFetching !== undefined ? this.#t[e] = m.__staleWhileFetching : this.#E(t, "fetch") : (i2.status && (i2.status.fetchUpdated = true), this.set(t, p, r.options))), p;
- }, w = (p) => (i2.status && (i2.status.fetchRejected = true, i2.status.fetchError = p), f(p, false)), f = (p, _) => {
- let { aborted: l } = o2.signal, S = l && i2.allowStaleOnFetchAbort, b = S || i2.allowStaleOnFetchRejection, m = b || i2.noDeleteOnFetchRejection, u2 = g;
- if (this.#t[e] === g && (!m || !_ && u2.__staleWhileFetching === undefined ? this.#E(t, "fetch") : S || (this.#t[e] = u2.__staleWhileFetching)), b)
- return i2.status && u2.__staleWhileFetching !== undefined && (i2.status.returnedStale = true), u2.__staleWhileFetching;
- if (u2.__returned === u2)
- throw p;
- }, d = (p, _) => {
- let l = this.#L?.(t, n2, r);
- l && l instanceof Promise && l.then((S) => p(S === undefined ? undefined : S), _), o2.signal.addEventListener("abort", () => {
- (!i2.ignoreFetchAbort || i2.allowStaleOnFetchAbort) && (p(undefined), i2.allowStaleOnFetchAbort && (p = (S) => a2(S, true)));
- });
- };
- i2.status && (i2.status.fetchDispatched = true);
- let g = new Promise(d).then(a2, w), A = Object.assign(g, { __abortController: o2, __staleWhileFetching: n2, __returned: undefined });
- return e === undefined ? (this.set(t, A, { ...r.options, status: undefined }), e = this.#s.get(t)) : this.#t[e] = A, A;
- }
- #e(t) {
- if (!this.#v)
- return false;
- let e = t;
- return !!e && e instanceof Promise && e.hasOwnProperty("__staleWhileFetching") && e.__abortController instanceof C;
- }
- async fetch(t, e = {}) {
- let { allowStale: i2 = this.allowStale, updateAgeOnGet: s = this.updateAgeOnGet, noDeleteOnStaleGet: n2 = this.noDeleteOnStaleGet, ttl: o2 = this.ttl, noDisposeOnSet: h2 = this.noDisposeOnSet, size: r = 0, sizeCalculation: a2 = this.sizeCalculation, noUpdateTTL: w = this.noUpdateTTL, noDeleteOnFetchRejection: f = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection: d = this.allowStaleOnFetchRejection, ignoreFetchAbort: g = this.ignoreFetchAbort, allowStaleOnFetchAbort: A = this.allowStaleOnFetchAbort, context: p, forceRefresh: _ = false, status: l, signal: S } = e;
- if (!this.#v)
- return l && (l.fetch = "get"), this.get(t, { allowStale: i2, updateAgeOnGet: s, noDeleteOnStaleGet: n2, status: l });
- let b = { allowStale: i2, updateAgeOnGet: s, noDeleteOnStaleGet: n2, ttl: o2, noDisposeOnSet: h2, size: r, sizeCalculation: a2, noUpdateTTL: w, noDeleteOnFetchRejection: f, allowStaleOnFetchRejection: d, allowStaleOnFetchAbort: A, ignoreFetchAbort: g, status: l, signal: S }, m = this.#s.get(t);
- if (m === undefined) {
- l && (l.fetch = "miss");
- let u2 = this.#G(t, m, b, p);
- return u2.__returned = u2;
- } else {
- let u2 = this.#t[m];
- if (this.#e(u2)) {
- let E = i2 && u2.__staleWhileFetching !== undefined;
- return l && (l.fetch = "inflight", E && (l.returnedStale = true)), E ? u2.__staleWhileFetching : u2.__returned = u2;
- }
- let T = this.#p(m);
- if (!_ && !T)
- return l && (l.fetch = "hit"), this.#D(m), s && this.#R(m), l && this.#z(l, m), u2;
- let F = this.#G(t, m, b, p), O = F.__staleWhileFetching !== undefined && i2;
- return l && (l.fetch = T ? "stale" : "refresh", O && T && (l.returnedStale = true)), O ? F.__staleWhileFetching : F.__returned = F;
- }
- }
- async forceFetch(t, e = {}) {
- let i2 = await this.fetch(t, e);
- if (i2 === undefined)
- throw new Error("fetch() returned undefined");
- return i2;
- }
- memo(t, e = {}) {
- let i2 = this.#I;
- if (!i2)
- throw new Error("no memoMethod provided to constructor");
- let { context: s, forceRefresh: n2, ...o2 } = e, h2 = this.get(t, o2);
- if (!n2 && h2 !== undefined)
- return h2;
- let r = i2(t, h2, { options: o2, context: s });
- return this.set(t, r, o2), r;
- }
- get(t, e = {}) {
- let { allowStale: i2 = this.allowStale, updateAgeOnGet: s = this.updateAgeOnGet, noDeleteOnStaleGet: n2 = this.noDeleteOnStaleGet, status: o2 } = e, h2 = this.#s.get(t);
- if (h2 !== undefined) {
- let r = this.#t[h2], a2 = this.#e(r);
- return o2 && this.#z(o2, h2), this.#p(h2) ? (o2 && (o2.get = "stale"), a2 ? (o2 && i2 && r.__staleWhileFetching !== undefined && (o2.returnedStale = true), i2 ? r.__staleWhileFetching : undefined) : (n2 || this.#E(t, "expire"), o2 && i2 && (o2.returnedStale = true), i2 ? r : undefined)) : (o2 && (o2.get = "hit"), a2 ? r.__staleWhileFetching : (this.#D(h2), s && this.#R(h2), r));
- } else
- o2 && (o2.get = "miss");
- }
- #k(t, e) {
- this.#u[e] = t, this.#a[t] = e;
- }
- #D(t) {
- t !== this.#h && (t === this.#l ? this.#l = this.#a[t] : this.#k(this.#u[t], this.#a[t]), this.#k(this.#h, t), this.#h = t);
- }
- delete(t) {
- return this.#E(t, "delete");
- }
- #E(t, e) {
- let i2 = false;
- if (this.#n !== 0) {
- let s = this.#s.get(t);
- if (s !== undefined)
- if (this.#g?.[s] && (clearTimeout(this.#g?.[s]), this.#g[s] = undefined), i2 = true, this.#n === 1)
- this.#V(e);
- else {
- this.#W(s);
- let n2 = this.#t[s];
- if (this.#e(n2) ? n2.__abortController.abort(new Error("deleted")) : (this.#T || this.#f) && (this.#T && this.#w?.(n2, t, e), this.#f && this.#r?.push([n2, t, e])), this.#s.delete(t), this.#i[s] = undefined, this.#t[s] = undefined, s === this.#h)
- this.#h = this.#u[s];
- else if (s === this.#l)
- this.#l = this.#a[s];
- else {
- let o2 = this.#u[s];
- this.#a[o2] = this.#a[s];
- let h2 = this.#a[s];
- this.#u[h2] = this.#u[s];
- }
- this.#n--, this.#b.push(s);
- }
- }
- if (this.#f && this.#r?.length) {
- let s = this.#r, n2;
- for (;n2 = s?.shift(); )
- this.#S?.(...n2);
- }
- return i2;
- }
- clear() {
- return this.#V("delete");
- }
- #V(t) {
- for (let e of this.#O({ allowStale: true })) {
- let i2 = this.#t[e];
- if (this.#e(i2))
- i2.__abortController.abort(new Error("deleted"));
- else {
- let s = this.#i[e];
- this.#T && this.#w?.(i2, s, t), this.#f && this.#r?.push([i2, s, t]);
- }
- }
- if (this.#s.clear(), this.#t.fill(undefined), this.#i.fill(undefined), this.#d && this.#A) {
- this.#d.fill(0), this.#A.fill(0);
- for (let e of this.#g ?? [])
- e !== undefined && clearTimeout(e);
- this.#g?.fill(undefined);
- }
- if (this.#y && this.#y.fill(0), this.#l = 0, this.#h = 0, this.#b.length = 0, this.#_ = 0, this.#n = 0, this.#f && this.#r) {
- let e = this.#r, i2;
- for (;i2 = e?.shift(); )
- this.#S?.(...i2);
- }
- }
- };
-});
-
-// src/utils/memoize.ts
-function memoizeWithTTLAsync(f, cacheLifetimeMs = 5 * 60 * 1000) {
- const cache2 = new Map;
- const inFlight = new Map;
- const memoized = async (...args) => {
- const key = jsonStringify(args);
- const cached = cache2.get(key);
- const now = Date.now();
- if (!cached) {
- const pending = inFlight.get(key);
- if (pending)
- return pending;
- const promise = f(...args);
- inFlight.set(key, promise);
- try {
- const result = await promise;
- if (inFlight.get(key) === promise) {
- cache2.set(key, {
- value: result,
- timestamp: now,
- refreshing: false
- });
- }
- return result;
- } finally {
- if (inFlight.get(key) === promise) {
- inFlight.delete(key);
- }
- }
- }
- if (cached && now - cached.timestamp > cacheLifetimeMs && !cached.refreshing) {
- cached.refreshing = true;
- const staleEntry = cached;
- f(...args).then((newValue) => {
- if (cache2.get(key) === staleEntry) {
- cache2.set(key, {
- value: newValue,
- timestamp: Date.now(),
- refreshing: false
- });
- }
- }).catch((e) => {
- logError2(e);
- if (cache2.get(key) === staleEntry) {
- cache2.delete(key);
- }
- });
- return cached.value;
- }
- return cache2.get(key).value;
- };
- memoized.cache = {
- clear: () => {
- cache2.clear();
- inFlight.clear();
- }
- };
- return memoized;
-}
-function memoizeWithLRU(f, cacheFn, maxCacheSize = 100) {
- const cache2 = new L({
- max: maxCacheSize
- });
- const memoized = (...args) => {
- const key = cacheFn(...args);
- const cached = cache2.get(key);
- if (cached !== undefined) {
- return cached;
- }
- const result = f(...args);
- cache2.set(key, result);
- return result;
- };
- memoized.cache = {
- clear: () => cache2.clear(),
- size: () => cache2.size,
- delete: (key) => cache2.delete(key),
- get: (key) => cache2.peek(key),
- has: (key) => cache2.has(key)
- };
- return memoized;
-}
-var init_memoize2 = __esm(() => {
- init_index_min();
- init_log2();
- init_slowOperations();
-});
-
-// src/utils/windowsPaths.ts
-import * as path7 from "path";
-import * as pathWin32 from "path/win32";
-function checkPathExists(path8) {
- try {
- execSync_DEPRECATED(`dir "${path8}"`, { stdio: "pipe" });
- return true;
- } catch {
- return false;
- }
-}
-function findExecutable2(executable) {
- if (executable === "git") {
- const defaultLocations = [
- "C:\\Program Files\\Git\\cmd\\git.exe",
- "C:\\Program Files (x86)\\Git\\cmd\\git.exe"
- ];
- for (const location of defaultLocations) {
- if (checkPathExists(location)) {
- return location;
- }
- }
- }
- try {
- const result = execSync_DEPRECATED(`where.exe ${executable}`, {
- stdio: "pipe",
- encoding: "utf8"
- }).trim();
- const paths2 = result.split(`\r
-`).filter(Boolean);
- const cwd2 = getCwd().toLowerCase();
- for (const candidatePath of paths2) {
- const normalizedPath = path7.resolve(candidatePath).toLowerCase();
- const pathDir = path7.dirname(normalizedPath).toLowerCase();
- if (pathDir === cwd2 || normalizedPath.startsWith(cwd2 + path7.sep)) {
- logForDebugging(`Skipping potentially malicious executable in current directory: ${candidatePath}`);
- continue;
- }
- return candidatePath;
- }
- return null;
- } catch {
- return null;
- }
-}
-function setShellIfWindows() {
- if (getPlatform() === "windows") {
- const gitBashPath = findGitBashPath();
- process.env.SHELL = gitBashPath;
- logForDebugging(`Using bash path: "${gitBashPath}"`);
- }
-}
-var findGitBashPath, windowsPathToPosixPath, posixPathToWindowsPath;
-var init_windowsPaths = __esm(() => {
- init_memoize();
- init_cwd();
- init_debug();
- init_execSyncWrapper();
- init_memoize2();
- init_platform2();
- findGitBashPath = memoize_default(() => {
- if (process.env.CLAUDE_CODE_GIT_BASH_PATH) {
- if (checkPathExists(process.env.CLAUDE_CODE_GIT_BASH_PATH)) {
- return process.env.CLAUDE_CODE_GIT_BASH_PATH;
- }
- console.error(`Claude Code was unable to find CLAUDE_CODE_GIT_BASH_PATH path "${process.env.CLAUDE_CODE_GIT_BASH_PATH}"`);
- process.exit(1);
- }
- const gitPath = findExecutable2("git");
- if (gitPath) {
- const bashPath = pathWin32.join(gitPath, "..", "..", "bin", "bash.exe");
- if (checkPathExists(bashPath)) {
- return bashPath;
- }
- }
- console.error("Claude Code on Windows requires git-bash (https://git-scm.com/downloads/win). If installed but not in PATH, set environment variable pointing to your bash.exe, similar to: CLAUDE_CODE_GIT_BASH_PATH=C:\\Program Files\\Git\\bin\\bash.exe");
- process.exit(1);
- });
- windowsPathToPosixPath = memoizeWithLRU((windowsPath) => {
- if (windowsPath.startsWith("\\\\")) {
- return windowsPath.replace(/\\/g, "/");
- }
- const match = windowsPath.match(/^([A-Za-z]):[/\\]/);
- if (match) {
- const driveLetter = match[1].toLowerCase();
- return "/" + driveLetter + windowsPath.slice(2).replace(/\\/g, "/");
- }
- return windowsPath.replace(/\\/g, "/");
- }, (p) => p, 500);
- posixPathToWindowsPath = memoizeWithLRU((posixPath) => {
- if (posixPath.startsWith("//")) {
- return posixPath.replace(/\//g, "\\");
- }
- const cygdriveMatch = posixPath.match(/^\/cygdrive\/([A-Za-z])(\/|$)/);
- if (cygdriveMatch) {
- const driveLetter = cygdriveMatch[1].toUpperCase();
- const rest = posixPath.slice(("/cygdrive/" + cygdriveMatch[1]).length);
- return driveLetter + ":" + (rest || "\\").replace(/\//g, "\\");
- }
- const driveMatch = posixPath.match(/^\/([A-Za-z])(\/|$)/);
- if (driveMatch) {
- const driveLetter = driveMatch[1].toUpperCase();
- const rest = posixPath.slice(2);
- return driveLetter + ":" + (rest || "\\").replace(/\//g, "\\");
- }
- return posixPath.replace(/\//g, "\\");
- }, (p) => p, 500);
-});
-
-// src/utils/getWorktreePathsPortable.ts
-import { execFile as execFileCb } from "child_process";
-import { promisify as promisify3 } from "util";
-async function getWorktreePathsPortable(cwd2) {
- try {
- const { stdout } = await execFileAsync("git", ["worktree", "list", "--porcelain"], { cwd: cwd2, timeout: 5000 });
- if (!stdout)
- return [];
- return stdout.split(`
-`).filter((line) => line.startsWith("worktree ")).map((line) => line.slice("worktree ".length).normalize("NFC"));
- } catch {
- return [];
- }
-}
-var execFileAsync;
-var init_getWorktreePathsPortable = __esm(() => {
- execFileAsync = promisify3(execFileCb);
-});
-
-// src/utils/sessionStoragePortable.ts
-import { open as fsOpen, readdir as readdir2, realpath, stat } from "fs/promises";
-import { join as join9 } from "path";
-function validateUuid(maybeUuid) {
- if (typeof maybeUuid !== "string")
- return null;
- return uuidRegex.test(maybeUuid) ? maybeUuid : null;
-}
-function unescapeJsonString(raw) {
- if (!raw.includes("\\"))
- return raw;
- try {
- return JSON.parse(`"${raw}"`);
- } catch {
- return raw;
- }
-}
-function extractJsonStringField(text, key) {
- const patterns = [`"${key}":"`, `"${key}": "`];
- for (const pattern of patterns) {
- const idx = text.indexOf(pattern);
- if (idx < 0)
- continue;
- const valueStart = idx + pattern.length;
- let i2 = valueStart;
- while (i2 < text.length) {
- if (text[i2] === "\\") {
- i2 += 2;
- continue;
- }
- if (text[i2] === '"') {
- return unescapeJsonString(text.slice(valueStart, i2));
- }
- i2++;
- }
- }
- return;
-}
-function extractLastJsonStringField(text, key) {
- const patterns = [`"${key}":"`, `"${key}": "`];
- let lastValue;
- for (const pattern of patterns) {
- let searchFrom = 0;
- while (true) {
- const idx = text.indexOf(pattern, searchFrom);
- if (idx < 0)
- break;
- const valueStart = idx + pattern.length;
- let i2 = valueStart;
- while (i2 < text.length) {
- if (text[i2] === "\\") {
- i2 += 2;
- continue;
- }
- if (text[i2] === '"') {
- lastValue = unescapeJsonString(text.slice(valueStart, i2));
- break;
- }
- i2++;
- }
- searchFrom = i2 + 1;
- }
- }
- return lastValue;
-}
-async function readHeadAndTail(filePath, fileSize, buf) {
- try {
- const fh = await fsOpen(filePath, "r");
- try {
- const headResult = await fh.read(buf, 0, LITE_READ_BUF_SIZE, 0);
- if (headResult.bytesRead === 0)
- return { head: "", tail: "" };
- const head = buf.toString("utf8", 0, headResult.bytesRead);
- const tailOffset = Math.max(0, fileSize - LITE_READ_BUF_SIZE);
- let tail = head;
- if (tailOffset > 0) {
- const tailResult = await fh.read(buf, 0, LITE_READ_BUF_SIZE, tailOffset);
- tail = buf.toString("utf8", 0, tailResult.bytesRead);
- }
- return { head, tail };
- } finally {
- await fh.close();
- }
- } catch {
- return { head: "", tail: "" };
- }
-}
-function simpleHash(str) {
- return Math.abs(djb2Hash(str)).toString(36);
-}
-function sanitizePath2(name) {
- const sanitized = name.replace(/[^a-zA-Z0-9]/g, "-");
- if (sanitized.length <= MAX_SANITIZED_LENGTH2) {
- return sanitized;
- }
- const hash2 = typeof Bun !== "undefined" ? Bun.hash(name).toString(36) : simpleHash(name);
- return `${sanitized.slice(0, MAX_SANITIZED_LENGTH2)}-${hash2}`;
-}
-function getProjectsDir() {
- return join9(getClaudeConfigHomeDir(), "projects");
-}
-function compactBoundaryMarker() {
- return _compactBoundaryMarker ??= Buffer.from('"compact_boundary"');
-}
-function parseBoundaryLine(line) {
- try {
- const parsed = JSON.parse(line);
- if (parsed.type !== "system" || parsed.subtype !== "compact_boundary") {
- return null;
- }
- return {
- hasPreservedSegment: Boolean(parsed.compactMetadata?.preservedSegment)
- };
- } catch {
- return null;
- }
-}
-function sinkWrite(s, src, start, end) {
- const n2 = end - start;
- if (n2 <= 0)
- return;
- if (s.len + n2 > s.buf.length) {
- const grown = Buffer.allocUnsafe(Math.min(Math.max(s.buf.length * 2, s.len + n2), s.cap));
- s.buf.copy(grown, 0, 0, s.len);
- s.buf = grown;
- }
- src.copy(s.buf, s.len, start, end);
- s.len += n2;
-}
-function hasPrefix(src, prefix, at, end) {
- return end - at >= prefix.length && src.compare(prefix, 0, prefix.length, at, at + prefix.length) === 0;
-}
-function processStraddle(s, chunk, bytesRead) {
- s.straddleSnapCarryLen = 0;
- s.straddleSnapTailEnd = 0;
- if (s.carryLen === 0)
- return 0;
- const cb = s.carryBuf;
- const firstNl = chunk.indexOf(LF2);
- if (firstNl === -1 || firstNl >= bytesRead)
- return 0;
- const tailEnd = firstNl + 1;
- if (hasPrefix(cb, ATTR_SNAP_PREFIX, 0, s.carryLen)) {
- s.straddleSnapCarryLen = s.carryLen;
- s.straddleSnapTailEnd = tailEnd;
- s.lastSnapSrc = null;
- } else if (s.carryLen < ATTR_SNAP_PREFIX.length) {
- return 0;
- } else {
- if (hasPrefix(cb, SYSTEM_PREFIX, 0, s.carryLen)) {
- const hit = parseBoundaryLine(cb.toString("utf-8", 0, s.carryLen) + chunk.toString("utf-8", 0, firstNl));
- if (hit?.hasPreservedSegment) {
- s.hasPreservedSegment = true;
- } else if (hit) {
- s.out.len = 0;
- s.boundaryStartOffset = s.bufFileOff;
- s.hasPreservedSegment = false;
- s.lastSnapSrc = null;
- }
- }
- sinkWrite(s.out, cb, 0, s.carryLen);
- sinkWrite(s.out, chunk, 0, tailEnd);
- }
- s.bufFileOff += s.carryLen + tailEnd;
- s.carryLen = 0;
- return tailEnd;
-}
-function scanChunkLines(s, buf, boundaryMarker) {
- let boundaryAt = buf.indexOf(boundaryMarker);
- let runStart = 0;
- let lineStart = 0;
- let lastSnapStart = -1;
- let lastSnapEnd = -1;
- let nl = buf.indexOf(LF2);
- while (nl !== -1) {
- const lineEnd = nl + 1;
- if (boundaryAt !== -1 && boundaryAt < lineStart) {
- boundaryAt = buf.indexOf(boundaryMarker, lineStart);
- }
- if (hasPrefix(buf, ATTR_SNAP_PREFIX, lineStart, lineEnd)) {
- sinkWrite(s.out, buf, runStart, lineStart);
- lastSnapStart = lineStart;
- lastSnapEnd = lineEnd;
- runStart = lineEnd;
- } else if (boundaryAt >= lineStart && boundaryAt < Math.min(lineStart + BOUNDARY_SEARCH_BOUND, lineEnd)) {
- const hit = parseBoundaryLine(buf.toString("utf-8", lineStart, nl));
- if (hit?.hasPreservedSegment) {
- s.hasPreservedSegment = true;
- } else if (hit) {
- s.out.len = 0;
- s.boundaryStartOffset = s.bufFileOff + lineStart;
- s.hasPreservedSegment = false;
- s.lastSnapSrc = null;
- lastSnapStart = -1;
- s.straddleSnapCarryLen = 0;
- runStart = lineStart;
- }
- boundaryAt = buf.indexOf(boundaryMarker, boundaryAt + boundaryMarker.length);
- }
- lineStart = lineEnd;
- nl = buf.indexOf(LF2, lineStart);
- }
- sinkWrite(s.out, buf, runStart, lineStart);
- return { lastSnapStart, lastSnapEnd, trailStart: lineStart };
-}
-function captureSnap(s, buf, chunk, lastSnapStart, lastSnapEnd) {
- if (lastSnapStart !== -1) {
- s.lastSnapLen = lastSnapEnd - lastSnapStart;
- if (s.lastSnapBuf === undefined || s.lastSnapLen > s.lastSnapBuf.length) {
- s.lastSnapBuf = Buffer.allocUnsafe(s.lastSnapLen);
- }
- buf.copy(s.lastSnapBuf, 0, lastSnapStart, lastSnapEnd);
- s.lastSnapSrc = s.lastSnapBuf;
- } else if (s.straddleSnapCarryLen > 0) {
- s.lastSnapLen = s.straddleSnapCarryLen + s.straddleSnapTailEnd;
- if (s.lastSnapBuf === undefined || s.lastSnapLen > s.lastSnapBuf.length) {
- s.lastSnapBuf = Buffer.allocUnsafe(s.lastSnapLen);
- }
- s.carryBuf.copy(s.lastSnapBuf, 0, 0, s.straddleSnapCarryLen);
- chunk.copy(s.lastSnapBuf, s.straddleSnapCarryLen, 0, s.straddleSnapTailEnd);
- s.lastSnapSrc = s.lastSnapBuf;
- }
-}
-function captureCarry(s, buf, trailStart) {
- s.carryLen = buf.length - trailStart;
- if (s.carryLen > 0) {
- if (s.carryBuf === undefined || s.carryLen > s.carryBuf.length) {
- s.carryBuf = Buffer.allocUnsafe(s.carryLen);
- }
- buf.copy(s.carryBuf, 0, trailStart, buf.length);
- }
-}
-function finalizeOutput(s) {
- if (s.carryLen > 0) {
- const cb = s.carryBuf;
- if (hasPrefix(cb, ATTR_SNAP_PREFIX, 0, s.carryLen)) {
- s.lastSnapSrc = cb;
- s.lastSnapLen = s.carryLen;
- } else {
- sinkWrite(s.out, cb, 0, s.carryLen);
- }
- }
- if (s.lastSnapSrc) {
- if (s.out.len > 0 && s.out.buf[s.out.len - 1] !== LF2) {
- sinkWrite(s.out, LF_BYTE, 0, 1);
- }
- sinkWrite(s.out, s.lastSnapSrc, 0, s.lastSnapLen);
- }
-}
-async function readTranscriptForLoad(filePath, fileSize) {
- const boundaryMarker = compactBoundaryMarker();
- const CHUNK_SIZE = TRANSCRIPT_READ_CHUNK_SIZE;
- const s = {
- out: {
- buf: Buffer.allocUnsafe(Math.min(fileSize, 8 * 1024 * 1024)),
- len: 0,
- cap: fileSize + 1
- },
- boundaryStartOffset: 0,
- hasPreservedSegment: false,
- lastSnapSrc: null,
- lastSnapLen: 0,
- lastSnapBuf: undefined,
- bufFileOff: 0,
- carryLen: 0,
- carryBuf: undefined,
- straddleSnapCarryLen: 0,
- straddleSnapTailEnd: 0
- };
- const chunk = Buffer.allocUnsafe(CHUNK_SIZE);
- const fd = await fsOpen(filePath, "r");
- try {
- let filePos = 0;
- while (filePos < fileSize) {
- const { bytesRead } = await fd.read(chunk, 0, Math.min(CHUNK_SIZE, fileSize - filePos), filePos);
- if (bytesRead === 0)
- break;
- filePos += bytesRead;
- const chunkOff = processStraddle(s, chunk, bytesRead);
- let buf;
- if (s.carryLen > 0) {
- const bufLen = s.carryLen + (bytesRead - chunkOff);
- buf = Buffer.allocUnsafe(bufLen);
- s.carryBuf.copy(buf, 0, 0, s.carryLen);
- chunk.copy(buf, s.carryLen, chunkOff, bytesRead);
- } else {
- buf = chunk.subarray(chunkOff, bytesRead);
- }
- const r = scanChunkLines(s, buf, boundaryMarker);
- captureSnap(s, buf, chunk, r.lastSnapStart, r.lastSnapEnd);
- captureCarry(s, buf, r.trailStart);
- s.bufFileOff += r.trailStart;
- }
- finalizeOutput(s);
- } finally {
- await fd.close();
- }
- return {
- boundaryStartOffset: s.boundaryStartOffset,
- postBoundaryBuf: s.out.buf.subarray(0, s.out.len),
- hasPreservedSegment: s.hasPreservedSegment
- };
-}
-var LITE_READ_BUF_SIZE = 65536, uuidRegex, MAX_SANITIZED_LENGTH2 = 200, TRANSCRIPT_READ_CHUNK_SIZE, SKIP_PRECOMPACT_THRESHOLD, _compactBoundaryMarker, ATTR_SNAP_PREFIX, SYSTEM_PREFIX, LF2 = 10, LF_BYTE, BOUNDARY_SEARCH_BOUND = 256;
-var init_sessionStoragePortable = __esm(() => {
- init_envUtils();
- init_getWorktreePathsPortable();
- uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
- TRANSCRIPT_READ_CHUNK_SIZE = 1024 * 1024;
- SKIP_PRECOMPACT_THRESHOLD = 5 * 1024 * 1024;
- ATTR_SNAP_PREFIX = Buffer.from('{"type":"attribution-snapshot"');
- SYSTEM_PREFIX = Buffer.from('{"type":"system"');
- LF_BYTE = Buffer.from([LF2]);
-});
-
-// src/utils/path.ts
-import { homedir as homedir6 } from "os";
-import { dirname as dirname6, isAbsolute as isAbsolute2, join as join10, normalize, relative, resolve as resolve3 } from "path";
-function expandPath(path8, baseDir) {
- const actualBaseDir = baseDir ?? getCwd() ?? getFsImplementation().cwd();
- if (typeof path8 !== "string") {
- throw new TypeError(`Path must be a string, received ${typeof path8}`);
- }
- if (typeof actualBaseDir !== "string") {
- throw new TypeError(`Base directory must be a string, received ${typeof actualBaseDir}`);
- }
- if (path8.includes("\x00") || actualBaseDir.includes("\x00")) {
- throw new Error("Path contains null bytes");
- }
- const trimmedPath = path8.trim();
- if (!trimmedPath) {
- return normalize(actualBaseDir).normalize("NFC");
- }
- if (trimmedPath === "~") {
- return homedir6().normalize("NFC");
- }
- if (trimmedPath.startsWith("~/")) {
- return join10(homedir6(), trimmedPath.slice(2)).normalize("NFC");
- }
- let processedPath = trimmedPath;
- if (getPlatform() === "windows" && trimmedPath.match(/^\/[a-z]\//i)) {
- try {
- processedPath = posixPathToWindowsPath(trimmedPath);
- } catch {
- processedPath = trimmedPath;
- }
- }
- if (isAbsolute2(processedPath)) {
- return normalize(processedPath).normalize("NFC");
- }
- return resolve3(actualBaseDir, processedPath).normalize("NFC");
-}
-function toRelativePath(absolutePath) {
- const relativePath = relative(getCwd(), absolutePath);
- return relativePath.startsWith("..") ? absolutePath : relativePath;
-}
-function getDirectoryForPath(path8) {
- const absolutePath = expandPath(path8);
- if (absolutePath.startsWith("\\\\") || absolutePath.startsWith("//")) {
- return dirname6(absolutePath);
- }
- try {
- const stats = getFsImplementation().statSync(absolutePath);
- if (stats.isDirectory()) {
- return absolutePath;
- }
- } catch {}
- return dirname6(absolutePath);
-}
-function containsPathTraversal(path8) {
- return /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(path8);
-}
-function normalizePathForConfigKey(path8) {
- const normalized = normalize(path8);
- return normalized.replace(/\\/g, "/");
-}
-var init_path = __esm(() => {
- init_cwd();
- init_fsOperations();
- init_platform2();
- init_windowsPaths();
- init_sessionStoragePortable();
-});
-
-// src/utils/file.ts
-import { chmodSync, writeFileSync as fsWriteFileSync2 } from "fs";
-import { realpath as realpath2, stat as stat2 } from "fs/promises";
-import { homedir as homedir7 } from "os";
-import {
- basename as basename2,
- dirname as dirname7,
- extname,
- isAbsolute as isAbsolute3,
- join as join11,
- normalize as normalize2,
- relative as relative2,
- resolve as resolve4,
- sep as sep2
-} from "path";
-async function pathExists(path8) {
- try {
- await stat2(path8);
- return true;
- } catch {
- return false;
- }
-}
-function readFileSafe(filepath) {
- try {
- const fs2 = getFsImplementation();
- return fs2.readFileSync(filepath, { encoding: "utf8" });
- } catch (error) {
- logError2(error);
- return null;
- }
-}
-function getFileModificationTime(filePath) {
- const fs2 = getFsImplementation();
- return Math.floor(fs2.statSync(filePath).mtimeMs);
-}
-async function getFileModificationTimeAsync(filePath) {
- const s = await getFsImplementation().stat(filePath);
- return Math.floor(s.mtimeMs);
-}
-function writeTextContent(filePath, content, encoding, endings) {
- let toWrite = content;
- if (endings === "CRLF") {
- toWrite = content.replaceAll(`\r
-`, `
-`).split(`
-`).join(`\r
-`);
- }
- writeFileSyncAndFlush_DEPRECATED(filePath, toWrite, { encoding });
-}
-function detectFileEncoding(filePath) {
- try {
- const fs2 = getFsImplementation();
- const { resolvedPath } = safeResolvePath(fs2, filePath);
- return detectEncodingForResolvedPath(resolvedPath);
- } catch (error) {
- if (isFsInaccessible(error)) {
- logForDebugging(`detectFileEncoding failed for expected reason: ${error.code}`, {
- level: "debug"
- });
- } else {
- logError2(error);
- }
- return "utf8";
- }
-}
-function detectLineEndings(filePath, encoding = "utf8") {
- try {
- const fs2 = getFsImplementation();
- const { resolvedPath } = safeResolvePath(fs2, filePath);
- const { buffer, bytesRead } = fs2.readSync(resolvedPath, { length: 4096 });
- const content = buffer.toString(encoding, 0, bytesRead);
- return detectLineEndingsForString(content);
- } catch (error) {
- logError2(error);
- return "LF";
- }
-}
-function convertLeadingTabsToSpaces(content) {
- if (!content.includes("\t"))
- return content;
- return content.replace(/^\t+/gm, (_) => " ".repeat(_.length));
-}
-function getAbsoluteAndRelativePaths(path8) {
- const absolutePath = path8 ? expandPath(path8) : undefined;
- const relativePath = absolutePath ? relative2(getCwd(), absolutePath) : undefined;
- return { absolutePath, relativePath };
-}
-function getDisplayPath(filePath) {
- const { relativePath } = getAbsoluteAndRelativePaths(filePath);
- if (relativePath && !relativePath.startsWith("..")) {
- return relativePath;
- }
- const homeDir = homedir7();
- if (filePath.startsWith(homeDir + sep2)) {
- return "~" + filePath.slice(homeDir.length);
- }
- return filePath;
-}
-function findSimilarFile(filePath) {
- const fs2 = getFsImplementation();
- try {
- const dir = dirname7(filePath);
- const fileBaseName = basename2(filePath, extname(filePath));
- const files = fs2.readdirSync(dir);
- const similarFiles = files.filter((file) => basename2(file.name, extname(file.name)) === fileBaseName && join11(dir, file.name) !== filePath);
- const firstMatch = similarFiles[0];
- if (firstMatch) {
- return firstMatch.name;
- }
- return;
- } catch (error) {
- if (!isENOENT(error)) {
- logError2(error);
- }
- return;
- }
-}
-async function suggestPathUnderCwd(requestedPath) {
- const cwd2 = getCwd();
- const cwdParent = dirname7(cwd2);
- let resolvedPath = requestedPath;
- try {
- const resolvedDir = await realpath2(dirname7(requestedPath));
- resolvedPath = join11(resolvedDir, basename2(requestedPath));
- } catch {}
- const cwdParentPrefix = cwdParent === sep2 ? sep2 : cwdParent + sep2;
- if (!resolvedPath.startsWith(cwdParentPrefix) || resolvedPath.startsWith(cwd2 + sep2) || resolvedPath === cwd2) {
- return;
- }
- const relFromParent = relative2(cwdParent, resolvedPath);
- const correctedPath = join11(cwd2, relFromParent);
- try {
- await stat2(correctedPath);
- return correctedPath;
- } catch {
- return;
- }
-}
-function isCompactLinePrefixEnabled() {
- return !getFeatureValue_CACHED_MAY_BE_STALE("tengu_compact_line_prefix_killswitch", false);
-}
-function addLineNumbers({
- content,
- startLine
-}) {
- if (!content) {
- return "";
- }
- const lines = content.split(/\r?\n/);
- if (isCompactLinePrefixEnabled()) {
- return lines.map((line, index2) => `${index2 + startLine} ${line}`).join(`
-`);
- }
- return lines.map((line, index2) => {
- const numStr = String(index2 + startLine);
- if (numStr.length >= 6) {
- return `${numStr}\u2192${line}`;
- }
- return `${numStr.padStart(6, " ")}\u2192${line}`;
- }).join(`
-`);
-}
-function stripLineNumberPrefix(line) {
- const match = line.match(/^\s*\d+[\u2192\t](.*)$/);
- return match?.[1] ?? line;
-}
-function isDirEmpty(dirPath) {
- try {
- return getFsImplementation().isDirEmptySync(dirPath);
- } catch (e) {
- return isENOENT(e);
- }
-}
-function readFileSyncCached(filePath) {
- const { content } = fileReadCache.readFile(filePath);
- return content;
-}
-function writeFileSyncAndFlush_DEPRECATED(filePath, content, options2 = { encoding: "utf-8" }) {
- const fs2 = getFsImplementation();
- let targetPath = filePath;
- try {
- const linkTarget = fs2.readlinkSync(filePath);
- targetPath = isAbsolute3(linkTarget) ? linkTarget : resolve4(dirname7(filePath), linkTarget);
- logForDebugging(`Writing through symlink: ${filePath} -> ${targetPath}`);
- } catch {}
- const tempPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
- let targetMode;
- let targetExists = false;
- try {
- targetMode = fs2.statSync(targetPath).mode;
- targetExists = true;
- logForDebugging(`Preserving file permissions: ${targetMode.toString(8)}`);
- } catch (e) {
- if (!isENOENT(e))
- throw e;
- if (options2.mode !== undefined) {
- targetMode = options2.mode;
- logForDebugging(`Setting permissions for new file: ${targetMode.toString(8)}`);
- }
- }
- try {
- logForDebugging(`Writing to temp file: ${tempPath}`);
- const writeOptions = {
- encoding: options2.encoding,
- flush: true
- };
- if (!targetExists && options2.mode !== undefined) {
- writeOptions.mode = options2.mode;
- }
- fsWriteFileSync2(tempPath, content, writeOptions);
- logForDebugging(`Temp file written successfully, size: ${content.length} bytes`);
- if (targetExists && targetMode !== undefined) {
- chmodSync(tempPath, targetMode);
- logForDebugging(`Applied original permissions to temp file`);
- }
- logForDebugging(`Renaming ${tempPath} to ${targetPath}`);
- fs2.renameSync(tempPath, targetPath);
- logForDebugging(`File ${targetPath} written atomically`);
- } catch (atomicError) {
- logForDebugging(`Failed to write file atomically: ${atomicError}`, {
- level: "error"
- });
- logEvent("tengu_atomic_write_error", {});
- try {
- logForDebugging(`Cleaning up temp file: ${tempPath}`);
- fs2.unlinkSync(tempPath);
- } catch (cleanupError) {
- logForDebugging(`Failed to clean up temp file: ${cleanupError}`);
- }
- logForDebugging(`Falling back to non-atomic write for ${targetPath}`);
- try {
- const fallbackOptions = {
- encoding: options2.encoding,
- flush: true
- };
- if (!targetExists && options2.mode !== undefined) {
- fallbackOptions.mode = options2.mode;
- }
- fsWriteFileSync2(targetPath, content, fallbackOptions);
- logForDebugging(`File ${targetPath} written successfully with non-atomic fallback`);
- } catch (fallbackError) {
- logForDebugging(`Non-atomic write also failed: ${fallbackError}`);
- throw fallbackError;
- }
- }
-}
-function getDesktopPath() {
- const platform2 = getPlatform();
- const homeDir = homedir7();
- if (platform2 === "macos") {
- return join11(homeDir, "Desktop");
- }
- if (platform2 === "windows") {
- const windowsHome = process.env.USERPROFILE ? process.env.USERPROFILE.replace(/\\/g, "/") : null;
- if (windowsHome) {
- const wslPath = windowsHome.replace(/^[A-Z]:/, "");
- const desktopPath2 = `/mnt/c${wslPath}/Desktop`;
- if (getFsImplementation().existsSync(desktopPath2)) {
- return desktopPath2;
- }
- }
- try {
- const usersDir = "/mnt/c/Users";
- const userDirs = getFsImplementation().readdirSync(usersDir);
- for (const user of userDirs) {
- if (user.name === "Public" || user.name === "Default" || user.name === "Default User" || user.name === "All Users") {
- continue;
- }
- const potentialDesktopPath = join11(usersDir, user.name, "Desktop");
- if (getFsImplementation().existsSync(potentialDesktopPath)) {
- return potentialDesktopPath;
- }
- }
- } catch (error) {
- logError2(error);
- }
- }
- const desktopPath = join11(homeDir, "Desktop");
- if (getFsImplementation().existsSync(desktopPath)) {
- return desktopPath;
- }
- return homeDir;
-}
-function isFileWithinReadSizeLimit(filePath, maxSizeBytes = MAX_OUTPUT_SIZE) {
- try {
- const stats = getFsImplementation().statSync(filePath);
- return stats.size <= maxSizeBytes;
- } catch {
- return false;
- }
-}
-function normalizePathForComparison(filePath) {
- let normalized = normalize2(filePath);
- if (getPlatform() === "windows") {
- normalized = normalized.replace(/\//g, "\\").toLowerCase();
- }
- return normalized;
-}
-function pathsEqual(path1, path22) {
- return normalizePathForComparison(path1) === normalizePathForComparison(path22);
-}
-var MAX_OUTPUT_SIZE, FILE_NOT_FOUND_CWD_NOTE = "Note: your current working directory is";
-var init_file = __esm(() => {
- init_analytics();
- init_growthbook();
- init_cwd();
- init_debug();
- init_errors();
- init_fileRead();
- init_fileReadCache();
- init_fsOperations();
- init_log2();
- init_path();
- init_platform2();
- MAX_OUTPUT_SIZE = 0.25 * 1024 * 1024;
-});
-
-// src/constants/files.ts
-function hasBinaryExtension(filePath) {
- const ext = filePath.slice(filePath.lastIndexOf(".")).toLowerCase();
- return BINARY_EXTENSIONS.has(ext);
-}
-function isBinaryContent(buffer) {
- const checkSize = Math.min(buffer.length, BINARY_CHECK_SIZE);
- let nonPrintable = 0;
- for (let i2 = 0;i2 < checkSize; i2++) {
- const byte = buffer[i2];
- if (byte === 0) {
- return true;
- }
- if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {
- nonPrintable++;
- }
- }
- return nonPrintable / checkSize > 0.1;
-}
-var BINARY_EXTENSIONS, BINARY_CHECK_SIZE = 8192;
-var init_files = __esm(() => {
- BINARY_EXTENSIONS = new Set([
- ".png",
- ".jpg",
- ".jpeg",
- ".gif",
- ".bmp",
- ".ico",
- ".webp",
- ".tiff",
- ".tif",
- ".mp4",
- ".mov",
- ".avi",
- ".mkv",
- ".webm",
- ".wmv",
- ".flv",
- ".m4v",
- ".mpeg",
- ".mpg",
- ".mp3",
- ".wav",
- ".ogg",
- ".flac",
- ".aac",
- ".m4a",
- ".wma",
- ".aiff",
- ".opus",
- ".zip",
- ".tar",
- ".gz",
- ".bz2",
- ".7z",
- ".rar",
- ".xz",
- ".z",
- ".tgz",
- ".iso",
- ".exe",
- ".dll",
- ".so",
- ".dylib",
- ".bin",
- ".o",
- ".a",
- ".obj",
- ".lib",
- ".app",
- ".msi",
- ".deb",
- ".rpm",
- ".pdf",
- ".doc",
- ".docx",
- ".xls",
- ".xlsx",
- ".ppt",
- ".pptx",
- ".odt",
- ".ods",
- ".odp",
- ".ttf",
- ".otf",
- ".woff",
- ".woff2",
- ".eot",
- ".pyc",
- ".pyo",
- ".class",
- ".jar",
- ".war",
- ".ear",
- ".node",
- ".wasm",
- ".rlib",
- ".sqlite",
- ".sqlite3",
- ".db",
- ".mdb",
- ".idx",
- ".psd",
- ".ai",
- ".eps",
- ".sketch",
- ".fig",
- ".xd",
- ".blend",
- ".3ds",
- ".max",
- ".swf",
- ".fla",
- ".lockb",
- ".dat",
- ".data"
- ]);
-});
-
-// src/utils/execFileNoThrowPortable.ts
-function execSyncWithDefaults_DEPRECATED(command, optionsOrAbortSignal, timeout = 10 * SECONDS_IN_MINUTE * MS_IN_SECOND) {
- let __stack = [];
- try {
- let options2;
- if (optionsOrAbortSignal === undefined) {
- options2 = {};
- } else if (optionsOrAbortSignal instanceof AbortSignal) {
- options2 = {
- abortSignal: optionsOrAbortSignal,
- timeout
- };
- } else {
- options2 = optionsOrAbortSignal;
- }
- const {
- abortSignal,
- timeout: finalTimeout = 10 * SECONDS_IN_MINUTE * MS_IN_SECOND,
- input,
- stdio = ["ignore", "pipe", "pipe"]
- } = options2;
- abortSignal?.throwIfAborted();
- const _ = __using(__stack, slowLogging`exec: ${command.slice(0, 200)}`, 0);
- try {
- const result = execaSync(command, {
- env: process.env,
- maxBuffer: 1e6,
- timeout: finalTimeout,
- cwd: getCwd(),
- stdio,
- shell: true,
- reject: false,
- input
- });
- if (!result.stdout) {
- return null;
- }
- return result.stdout.trim() || null;
- } catch {
- return null;
- }
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- __callDispose(__stack, _err, _hasErr);
- }
-}
-var MS_IN_SECOND = 1000, SECONDS_IN_MINUTE = 60;
-var init_execFileNoThrowPortable = __esm(() => {
- init_execa();
- init_cwd();
- init_slowOperations();
-});
-
-// src/utils/execFileNoThrow.ts
-function execFileNoThrow(file, args, options2 = {
- timeout: 10 * SECONDS_IN_MINUTE2 * MS_IN_SECOND2,
- preserveOutputOnError: true,
- useCwd: true
-}) {
- return execFileNoThrowWithCwd(file, args, {
- abortSignal: options2.abortSignal,
- timeout: options2.timeout,
- preserveOutputOnError: options2.preserveOutputOnError,
- cwd: options2.useCwd ? getCwd() : undefined,
- env: options2.env,
- stdin: options2.stdin,
- input: options2.input
- });
-}
-function getErrorMessage(result, errorCode) {
- if (result.shortMessage) {
- return result.shortMessage;
- }
- if (typeof result.signal === "string") {
- return result.signal;
- }
- return String(errorCode);
-}
-function execFileNoThrowWithCwd(file, args, {
- abortSignal,
- timeout: finalTimeout = 10 * SECONDS_IN_MINUTE2 * MS_IN_SECOND2,
- preserveOutputOnError: finalPreserveOutput = true,
- cwd: finalCwd,
- env: finalEnv,
- maxBuffer,
- shell,
- stdin: finalStdin,
- input: finalInput
-} = {
- timeout: 10 * SECONDS_IN_MINUTE2 * MS_IN_SECOND2,
- preserveOutputOnError: true,
- maxBuffer: 1e6
-}) {
- return new Promise((resolve5) => {
- execa(file, args, {
- maxBuffer,
- signal: abortSignal,
- timeout: finalTimeout,
- cwd: finalCwd,
- env: finalEnv,
- shell,
- stdin: finalStdin,
- input: finalInput,
- reject: false
- }).then((result) => {
- if (result.failed) {
- if (finalPreserveOutput) {
- const errorCode = result.exitCode ?? 1;
- resolve5({
- stdout: result.stdout || "",
- stderr: result.stderr || "",
- code: errorCode,
- error: getErrorMessage(result, errorCode)
- });
- } else {
- resolve5({ stdout: "", stderr: "", code: result.exitCode ?? 1 });
- }
- } else {
- resolve5({
- stdout: result.stdout,
- stderr: result.stderr,
- code: 0
- });
- }
- }).catch((error) => {
- logError2(error);
- resolve5({ stdout: "", stderr: "", code: 1 });
- });
- });
-}
-var MS_IN_SECOND2 = 1000, SECONDS_IN_MINUTE2 = 60;
-var init_execFileNoThrow = __esm(() => {
- init_execa();
- init_cwd();
- init_log2();
- init_execFileNoThrowPortable();
-});
-
-// src/utils/git/gitConfigParser.ts
-import { readFile as readFile2 } from "fs/promises";
-import { join as join12 } from "path";
-async function parseGitConfigValue(gitDir, section, subsection, key) {
- try {
- const config = await readFile2(join12(gitDir, "config"), "utf-8");
- return parseConfigString(config, section, subsection, key);
- } catch {
- return null;
- }
-}
-function parseConfigString(config, section, subsection, key) {
- const lines = config.split(`
-`);
- const sectionLower = section.toLowerCase();
- const keyLower = key.toLowerCase();
- let inSection = false;
- for (const line of lines) {
- const trimmed = line.trim();
- if (trimmed.length === 0 || trimmed[0] === "#" || trimmed[0] === ";") {
- continue;
- }
- if (trimmed[0] === "[") {
- inSection = matchesSectionHeader(trimmed, sectionLower, subsection);
- continue;
- }
- if (!inSection) {
- continue;
- }
- const parsed = parseKeyValue(trimmed);
- if (parsed && parsed.key.toLowerCase() === keyLower) {
- return parsed.value;
- }
- }
- return null;
-}
-function parseKeyValue(line) {
- let i2 = 0;
- while (i2 < line.length && isKeyChar(line[i2])) {
- i2++;
- }
- if (i2 === 0) {
- return null;
- }
- const key = line.slice(0, i2);
- while (i2 < line.length && (line[i2] === " " || line[i2] === "\t")) {
- i2++;
- }
- if (i2 >= line.length || line[i2] !== "=") {
- return null;
- }
- i2++;
- while (i2 < line.length && (line[i2] === " " || line[i2] === "\t")) {
- i2++;
- }
- const value = parseValue(line, i2);
- return { key, value };
-}
-function parseValue(line, start) {
- let result = "";
- let inQuote = false;
- let i2 = start;
- while (i2 < line.length) {
- const ch = line[i2];
- if (!inQuote && (ch === "#" || ch === ";")) {
- break;
- }
- if (ch === '"') {
- inQuote = !inQuote;
- i2++;
- continue;
- }
- if (ch === "\\" && i2 + 1 < line.length) {
- const next = line[i2 + 1];
- if (inQuote) {
- switch (next) {
- case "n":
- result += `
-`;
- break;
- case "t":
- result += "\t";
- break;
- case "b":
- result += "\b";
- break;
- case '"':
- result += '"';
- break;
- case "\\":
- result += "\\";
- break;
- default:
- result += next;
- break;
- }
- i2 += 2;
- continue;
- }
- if (next === "\\") {
- result += "\\";
- i2 += 2;
- continue;
- }
- }
- result += ch;
- i2++;
- }
- if (!inQuote) {
- result = trimTrailingWhitespace(result);
- }
- return result;
-}
-function trimTrailingWhitespace(s) {
- let end = s.length;
- while (end > 0 && (s[end - 1] === " " || s[end - 1] === "\t")) {
- end--;
- }
- return s.slice(0, end);
-}
-function matchesSectionHeader(line, sectionLower, subsection) {
- let i2 = 1;
- while (i2 < line.length && line[i2] !== "]" && line[i2] !== " " && line[i2] !== "\t" && line[i2] !== '"') {
- i2++;
- }
- const foundSection = line.slice(1, i2).toLowerCase();
- if (foundSection !== sectionLower) {
- return false;
- }
- if (subsection === null) {
- return i2 < line.length && line[i2] === "]";
- }
- while (i2 < line.length && (line[i2] === " " || line[i2] === "\t")) {
- i2++;
- }
- if (i2 >= line.length || line[i2] !== '"') {
- return false;
- }
- i2++;
- let foundSubsection = "";
- while (i2 < line.length && line[i2] !== '"') {
- if (line[i2] === "\\" && i2 + 1 < line.length) {
- const next = line[i2 + 1];
- if (next === "\\" || next === '"') {
- foundSubsection += next;
- i2 += 2;
- continue;
- }
- foundSubsection += next;
- i2 += 2;
- continue;
- }
- foundSubsection += line[i2];
- i2++;
- }
- if (i2 >= line.length || line[i2] !== '"') {
- return false;
- }
- i2++;
- if (i2 >= line.length || line[i2] !== "]") {
- return false;
- }
- return foundSubsection === subsection;
-}
-function isKeyChar(ch) {
- return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch >= "0" && ch <= "9" || ch === "-";
-}
-var init_gitConfigParser = () => {};
-
-// src/utils/git/gitFilesystem.ts
-import { unwatchFile, watchFile } from "fs";
-import { readdir as readdir3, readFile as readFile3, stat as stat3 } from "fs/promises";
-import { join as join13, resolve as resolve5 } from "path";
-function clearResolveGitDirCache() {
- resolveGitDirCache.clear();
-}
-async function resolveGitDir(startPath) {
- const cwd2 = resolve5(startPath ?? getCwd());
- const cached = resolveGitDirCache.get(cwd2);
- if (cached !== undefined) {
- return cached;
- }
- const root2 = findGitRoot(cwd2);
- if (!root2) {
- resolveGitDirCache.set(cwd2, null);
- return null;
- }
- const gitPath = join13(root2, ".git");
- try {
- const st = await stat3(gitPath);
- if (st.isFile()) {
- const content = (await readFile3(gitPath, "utf-8")).trim();
- if (content.startsWith("gitdir:")) {
- const rawDir = content.slice("gitdir:".length).trim();
- const resolved = resolve5(root2, rawDir);
- resolveGitDirCache.set(cwd2, resolved);
- return resolved;
- }
- }
- resolveGitDirCache.set(cwd2, gitPath);
- return gitPath;
- } catch {
- resolveGitDirCache.set(cwd2, null);
- return null;
- }
-}
-function isSafeRefName(name) {
- if (!name || name.startsWith("-") || name.startsWith("/")) {
- return false;
- }
- if (name.includes("..")) {
- return false;
- }
- if (name.split("/").some((c5) => c5 === "." || c5 === "")) {
- return false;
- }
- if (!/^[a-zA-Z0-9/._+@-]+$/.test(name)) {
- return false;
- }
- return true;
-}
-function isValidGitSha(s) {
- return /^[0-9a-f]{40}$/.test(s) || /^[0-9a-f]{64}$/.test(s);
-}
-async function readGitHead(gitDir) {
- try {
- const content = (await readFile3(join13(gitDir, "HEAD"), "utf-8")).trim();
- if (content.startsWith("ref:")) {
- const ref = content.slice("ref:".length).trim();
- if (ref.startsWith("refs/heads/")) {
- const name = ref.slice("refs/heads/".length);
- if (!isSafeRefName(name)) {
- return null;
- }
- return { type: "branch", name };
- }
- if (!isSafeRefName(ref)) {
- return null;
- }
- const sha = await resolveRef(gitDir, ref);
- return sha ? { type: "detached", sha } : { type: "detached", sha: "" };
- }
- if (!isValidGitSha(content)) {
- return null;
- }
- return { type: "detached", sha: content };
- } catch {
- return null;
- }
-}
-async function resolveRef(gitDir, ref) {
- const result = await resolveRefInDir(gitDir, ref);
- if (result) {
- return result;
- }
- const commonDir = await getCommonDir(gitDir);
- if (commonDir && commonDir !== gitDir) {
- return resolveRefInDir(commonDir, ref);
- }
- return null;
-}
-async function resolveRefInDir(dir, ref) {
- try {
- const content = (await readFile3(join13(dir, ref), "utf-8")).trim();
- if (content.startsWith("ref:")) {
- const target = content.slice("ref:".length).trim();
- if (!isSafeRefName(target)) {
- return null;
- }
- return resolveRef(dir, target);
- }
- if (!isValidGitSha(content)) {
- return null;
- }
- return content;
- } catch {}
- try {
- const packed = await readFile3(join13(dir, "packed-refs"), "utf-8");
- for (const line of packed.split(`
-`)) {
- if (line.startsWith("#") || line.startsWith("^")) {
- continue;
- }
- const spaceIdx = line.indexOf(" ");
- if (spaceIdx === -1) {
- continue;
- }
- if (line.slice(spaceIdx + 1) === ref) {
- const sha = line.slice(0, spaceIdx);
- return isValidGitSha(sha) ? sha : null;
- }
- }
- } catch {}
- return null;
-}
-async function getCommonDir(gitDir) {
- try {
- const content = (await readFile3(join13(gitDir, "commondir"), "utf-8")).trim();
- return resolve5(gitDir, content);
- } catch {
- return null;
- }
-}
-async function readRawSymref(gitDir, refPath, branchPrefix) {
- try {
- const content = (await readFile3(join13(gitDir, refPath), "utf-8")).trim();
- if (content.startsWith("ref:")) {
- const target = content.slice("ref:".length).trim();
- if (target.startsWith(branchPrefix)) {
- const name = target.slice(branchPrefix.length);
- if (!isSafeRefName(name)) {
- return null;
- }
- return name;
- }
- }
- } catch {}
- return null;
-}
-
-class GitFileWatcher {
- gitDir = null;
- commonDir = null;
- initialized = false;
- initPromise = null;
- watchedPaths = [];
- branchRefPath = null;
- cache = new Map;
- async ensureStarted() {
- if (this.initialized) {
- return;
- }
- if (this.initPromise) {
- return this.initPromise;
- }
- this.initPromise = this.start();
- return this.initPromise;
- }
- async start() {
- this.gitDir = await resolveGitDir();
- this.initialized = true;
- if (!this.gitDir) {
- return;
- }
- this.commonDir = await getCommonDir(this.gitDir);
- this.watchPath(join13(this.gitDir, "HEAD"), () => {
- this.onHeadChanged();
- });
- this.watchPath(join13(this.commonDir ?? this.gitDir, "config"), () => {
- this.invalidate();
- });
- await this.watchCurrentBranchRef();
- registerCleanup(async () => {
- this.stopWatching();
- });
- }
- watchPath(path8, callback) {
- this.watchedPaths.push(path8);
- watchFile(path8, { interval: WATCH_INTERVAL_MS }, callback);
- }
- async watchCurrentBranchRef() {
- if (!this.gitDir) {
- return;
- }
- const head = await readGitHead(this.gitDir);
- const refsDir = this.commonDir ?? this.gitDir;
- const refPath = head?.type === "branch" ? join13(refsDir, "refs", "heads", head.name) : null;
- if (refPath === this.branchRefPath) {
- return;
- }
- if (this.branchRefPath) {
- unwatchFile(this.branchRefPath);
- this.watchedPaths = this.watchedPaths.filter((p) => p !== this.branchRefPath);
- }
- this.branchRefPath = refPath;
- if (!refPath) {
- return;
- }
- this.watchPath(refPath, () => {
- this.invalidate();
- });
- }
- async onHeadChanged() {
- this.invalidate();
- await waitForScrollIdle();
- await this.watchCurrentBranchRef();
- }
- invalidate() {
- for (const entry of this.cache.values()) {
- entry.dirty = true;
- }
- }
- stopWatching() {
- for (const path8 of this.watchedPaths) {
- unwatchFile(path8);
- }
- this.watchedPaths = [];
- this.branchRefPath = null;
- }
- async get(key, compute) {
- await this.ensureStarted();
- const existing = this.cache.get(key);
- if (existing && !existing.dirty) {
- return existing.value;
- }
- if (existing) {
- existing.dirty = false;
- }
- const value = await compute();
- const entry = this.cache.get(key);
- if (entry && !entry.dirty) {
- entry.value = value;
- }
- if (!entry) {
- this.cache.set(key, { value, dirty: false, compute });
- }
- return value;
- }
- reset() {
- this.stopWatching();
- this.cache.clear();
- this.initialized = false;
- this.initPromise = null;
- this.gitDir = null;
- this.commonDir = null;
- }
-}
-async function computeBranch() {
- const gitDir = await resolveGitDir();
- if (!gitDir) {
- return "HEAD";
- }
- const head = await readGitHead(gitDir);
- if (!head) {
- return "HEAD";
- }
- return head.type === "branch" ? head.name : "HEAD";
-}
-async function computeHead() {
- const gitDir = await resolveGitDir();
- if (!gitDir) {
- return "";
- }
- const head = await readGitHead(gitDir);
- if (!head) {
- return "";
- }
- if (head.type === "branch") {
- return await resolveRef(gitDir, `refs/heads/${head.name}`) ?? "";
- }
- return head.sha;
-}
-async function computeRemoteUrl() {
- const gitDir = await resolveGitDir();
- if (!gitDir) {
- return null;
- }
- const url2 = await parseGitConfigValue(gitDir, "remote", "origin", "url");
- if (url2) {
- return url2;
- }
- const commonDir = await getCommonDir(gitDir);
- if (commonDir && commonDir !== gitDir) {
- return parseGitConfigValue(commonDir, "remote", "origin", "url");
- }
- return null;
-}
-async function computeDefaultBranch() {
- const gitDir = await resolveGitDir();
- if (!gitDir) {
- return "main";
- }
- const commonDir = await getCommonDir(gitDir) ?? gitDir;
- const branchFromSymref = await readRawSymref(commonDir, "refs/remotes/origin/HEAD", "refs/remotes/origin/");
- if (branchFromSymref) {
- return branchFromSymref;
- }
- for (const candidate of ["main", "master"]) {
- const sha = await resolveRef(commonDir, `refs/remotes/origin/${candidate}`);
- if (sha) {
- return candidate;
- }
- }
- return "main";
-}
-function getCachedBranch() {
- return gitWatcher.get("branch", computeBranch);
-}
-function getCachedHead() {
- return gitWatcher.get("head", computeHead);
-}
-function getCachedRemoteUrl() {
- return gitWatcher.get("remoteUrl", computeRemoteUrl);
-}
-function getCachedDefaultBranch() {
- return gitWatcher.get("defaultBranch", computeDefaultBranch);
-}
-async function getHeadForDir(cwd2) {
- const gitDir = await resolveGitDir(cwd2);
- if (!gitDir) {
- return null;
- }
- const head = await readGitHead(gitDir);
- if (!head) {
- return null;
- }
- if (head.type === "branch") {
- return resolveRef(gitDir, `refs/heads/${head.name}`);
- }
- return head.sha;
-}
-async function readWorktreeHeadSha(worktreePath) {
- let gitDir;
- try {
- const ptr = (await readFile3(join13(worktreePath, ".git"), "utf-8")).trim();
- if (!ptr.startsWith("gitdir:")) {
- return null;
- }
- gitDir = resolve5(worktreePath, ptr.slice("gitdir:".length).trim());
- } catch {
- return null;
- }
- const head = await readGitHead(gitDir);
- if (!head) {
- return null;
- }
- if (head.type === "branch") {
- return resolveRef(gitDir, `refs/heads/${head.name}`);
- }
- return head.sha;
-}
-async function getRemoteUrlForDir(cwd2) {
- const gitDir = await resolveGitDir(cwd2);
- if (!gitDir) {
- return null;
- }
- const url2 = await parseGitConfigValue(gitDir, "remote", "origin", "url");
- if (url2) {
- return url2;
- }
- const commonDir = await getCommonDir(gitDir);
- if (commonDir && commonDir !== gitDir) {
- return parseGitConfigValue(commonDir, "remote", "origin", "url");
- }
- return null;
-}
-async function isShallowClone() {
- const gitDir = await resolveGitDir();
- if (!gitDir) {
- return false;
- }
- const commonDir = await getCommonDir(gitDir) ?? gitDir;
- try {
- await stat3(join13(commonDir, "shallow"));
- return true;
- } catch {
- return false;
- }
-}
-async function getWorktreeCountFromFs() {
- try {
- const gitDir = await resolveGitDir();
- if (!gitDir) {
- return 0;
- }
- const commonDir = await getCommonDir(gitDir) ?? gitDir;
- const entries = await readdir3(join13(commonDir, "worktrees"));
- return entries.length + 1;
- } catch {
- return 1;
- }
-}
-var resolveGitDirCache, WATCH_INTERVAL_MS = 1000, gitWatcher;
-var init_gitFilesystem = __esm(() => {
- init_state();
- init_cleanupRegistry();
- init_cwd();
- init_git();
- init_gitConfigParser();
- resolveGitDirCache = new Map;
- gitWatcher = new GitFileWatcher;
-});
-
-// src/utils/detectRepository.ts
-var exports_detectRepository = {};
-__export(exports_detectRepository, {
- parseGitRemote: () => parseGitRemote,
- parseGitHubRepository: () => parseGitHubRepository,
- getCachedRepository: () => getCachedRepository,
- detectCurrentRepositoryWithHost: () => detectCurrentRepositoryWithHost,
- detectCurrentRepository: () => detectCurrentRepository,
- clearRepositoryCaches: () => clearRepositoryCaches
-});
-function clearRepositoryCaches() {
- repositoryWithHostCache.clear();
-}
-async function detectCurrentRepository() {
- const result = await detectCurrentRepositoryWithHost();
- if (!result)
- return null;
- if (result.host !== "github.com")
- return null;
- return `${result.owner}/${result.name}`;
-}
-async function detectCurrentRepositoryWithHost() {
- const cwd2 = getCwd();
- if (repositoryWithHostCache.has(cwd2)) {
- return repositoryWithHostCache.get(cwd2) ?? null;
- }
- try {
- const remoteUrl = await getRemoteUrl();
- logForDebugging(`Git remote URL: ${remoteUrl}`);
- if (!remoteUrl) {
- logForDebugging("No git remote URL found");
- repositoryWithHostCache.set(cwd2, null);
- return null;
- }
- const parsed = parseGitRemote(remoteUrl);
- logForDebugging(`Parsed repository: ${parsed ? `${parsed.host}/${parsed.owner}/${parsed.name}` : null} from URL: ${remoteUrl}`);
- repositoryWithHostCache.set(cwd2, parsed);
- return parsed;
- } catch (error) {
- logForDebugging(`Error detecting repository: ${error}`);
- repositoryWithHostCache.set(cwd2, null);
- return null;
- }
-}
-function getCachedRepository() {
- const parsed = repositoryWithHostCache.get(getCwd());
- if (!parsed || parsed.host !== "github.com")
- return null;
- return `${parsed.owner}/${parsed.name}`;
-}
-function parseGitRemote(input) {
- const trimmed = input.trim();
- const sshMatch = trimmed.match(/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/);
- if (sshMatch?.[1] && sshMatch[2] && sshMatch[3]) {
- if (!looksLikeRealHostname(sshMatch[1]))
- return null;
- return {
- host: sshMatch[1],
- owner: sshMatch[2],
- name: sshMatch[3]
- };
- }
- const urlMatch = trimmed.match(/^(https?|ssh|git):\/\/(?:[^@]+@)?([^/:]+(?::\d+)?)\/([^/]+)\/([^/]+?)(?:\.git)?$/);
- if (urlMatch?.[1] && urlMatch[2] && urlMatch[3] && urlMatch[4]) {
- const protocol = urlMatch[1];
- const hostWithPort = urlMatch[2];
- const hostWithoutPort = hostWithPort.split(":")[0] ?? "";
- if (!looksLikeRealHostname(hostWithoutPort))
- return null;
- const host = protocol === "https" || protocol === "http" ? hostWithPort : hostWithoutPort;
- return {
- host,
- owner: urlMatch[3],
- name: urlMatch[4]
- };
- }
- return null;
-}
-function parseGitHubRepository(input) {
- const trimmed = input.trim();
- const parsed = parseGitRemote(trimmed);
- if (parsed) {
- if (parsed.host !== "github.com")
- return null;
- return `${parsed.owner}/${parsed.name}`;
- }
- if (!trimmed.includes("://") && !trimmed.includes("@") && trimmed.includes("/")) {
- const parts = trimmed.split("/");
- if (parts.length === 2 && parts[0] && parts[1]) {
- const repo = parts[1].replace(/\.git$/, "");
- return `${parts[0]}/${repo}`;
- }
- }
- logForDebugging(`Could not parse repository from: ${trimmed}`);
- return null;
-}
-function looksLikeRealHostname(host) {
- if (!host.includes("."))
- return false;
- const lastSegment = host.split(".").pop();
- if (!lastSegment)
- return false;
- return /^[a-zA-Z]+$/.test(lastSegment);
-}
-var repositoryWithHostCache;
-var init_detectRepository = __esm(() => {
- init_cwd();
- init_debug();
- init_git();
- repositoryWithHostCache = new Map;
-});
-
-// src/utils/git.ts
-var exports_git = {};
-__export(exports_git, {
- stashToCleanState: () => stashToCleanState,
- preserveGitStateForIssue: () => preserveGitStateForIssue,
- normalizeGitRemoteUrl: () => normalizeGitRemoteUrl,
- isCurrentDirectoryBareGitRepo: () => isCurrentDirectoryBareGitRepo,
- isAtGitRoot: () => isAtGitRoot,
- hasUnpushedCommits: () => hasUnpushedCommits,
- gitExe: () => gitExe,
- getWorktreeCount: () => getWorktreeCount,
- getRepoRemoteHash: () => getRepoRemoteHash,
- getRemoteUrl: () => getRemoteUrl,
- getIsHeadOnRemote: () => getIsHeadOnRemote,
- getIsGit: () => getIsGit,
- getIsClean: () => getIsClean,
- getHead: () => getHead,
- getGithubRepo: () => getGithubRepo,
- getGitState: () => getGitState,
- getGitDir: () => getGitDir,
- getFileStatus: () => getFileStatus,
- getDefaultBranch: () => getDefaultBranch,
- getChangedFiles: () => getChangedFiles,
- getBranch: () => getBranch,
- findRemoteBase: () => findRemoteBase,
- findGitRoot: () => findGitRoot,
- findCanonicalGitRoot: () => findCanonicalGitRoot,
- dirIsInGitRepo: () => dirIsInGitRepo
-});
-import { createHash as createHash2 } from "crypto";
-import { readFileSync as readFileSync5, realpathSync as realpathSync3, statSync as statSync3 } from "fs";
-import { open as open2, readFile as readFile4, realpath as realpath3, stat as stat4 } from "fs/promises";
-import { basename as basename3, dirname as dirname8, join as join14, resolve as resolve6, sep as sep3 } from "path";
-function createFindGitRoot() {
- function wrapper(startPath) {
- const result = findGitRootImpl(startPath);
- return result === GIT_ROOT_NOT_FOUND ? null : result;
- }
- wrapper.cache = findGitRootImpl.cache;
- return wrapper;
-}
-function createFindCanonicalGitRoot() {
- function wrapper(startPath) {
- const root2 = findGitRoot(startPath);
- if (!root2) {
- return null;
- }
- return resolveCanonicalRoot(root2);
- }
- wrapper.cache = resolveCanonicalRoot.cache;
- return wrapper;
-}
-function getGitDir(cwd2) {
- return resolveGitDir(cwd2);
-}
-async function isAtGitRoot() {
- const cwd2 = getCwd();
- const gitRoot = findGitRoot(cwd2);
- if (!gitRoot) {
- return false;
- }
- try {
- const [resolvedCwd, resolvedGitRoot] = await Promise.all([
- realpath3(cwd2),
- realpath3(gitRoot)
- ]);
- return resolvedCwd === resolvedGitRoot;
- } catch {
- return cwd2 === gitRoot;
- }
-}
-function normalizeGitRemoteUrl(url2) {
- const trimmed = url2.trim();
- if (!trimmed)
- return null;
- const sshMatch = trimmed.match(/^git@([^:]+):(.+?)(?:\.git)?$/);
- if (sshMatch && sshMatch[1] && sshMatch[2]) {
- return `${sshMatch[1]}/${sshMatch[2]}`.toLowerCase();
- }
- const urlMatch = trimmed.match(/^(?:https?|ssh):\/\/(?:[^@]+@)?([^/]+)\/(.+?)(?:\.git)?$/);
- if (urlMatch && urlMatch[1] && urlMatch[2]) {
- const host = urlMatch[1];
- const path8 = urlMatch[2];
- if (isLocalHost(host) && path8.startsWith("git/")) {
- const proxyPath = path8.slice(4);
- const segments = proxyPath.split("/");
- if (segments.length >= 3 && segments[0].includes(".")) {
- return proxyPath.toLowerCase();
- }
- return `github.com/${proxyPath}`.toLowerCase();
- }
- return `${host}/${path8}`.toLowerCase();
- }
- return null;
-}
-async function getRepoRemoteHash() {
- const remoteUrl = await getRemoteUrl();
- if (!remoteUrl)
- return null;
- const normalized = normalizeGitRemoteUrl(remoteUrl);
- if (!normalized)
- return null;
- const hash2 = createHash2("sha256").update(normalized).digest("hex");
- return hash2.substring(0, 16);
-}
-async function getGitState() {
- try {
- const [
- commitHash,
- branchName,
- remoteUrl,
- isHeadOnRemote,
- isClean,
- worktreeCount
- ] = await Promise.all([
- getHead(),
- getBranch(),
- getRemoteUrl(),
- getIsHeadOnRemote(),
- getIsClean(),
- getWorktreeCount()
- ]);
- return {
- commitHash,
- branchName,
- remoteUrl,
- isHeadOnRemote,
- isClean,
- worktreeCount
- };
- } catch (_) {
- return null;
- }
-}
-async function getGithubRepo() {
- const { parseGitRemote: parseGitRemote2 } = await Promise.resolve().then(() => (init_detectRepository(), exports_detectRepository));
- const remoteUrl = await getRemoteUrl();
- if (!remoteUrl) {
- logForDebugging("Local GitHub repo: unknown");
- return null;
- }
- const parsed = parseGitRemote2(remoteUrl);
- if (parsed && parsed.host === "github.com") {
- const result = `${parsed.owner}/${parsed.name}`;
- logForDebugging(`Local GitHub repo: ${result}`);
- return result;
- }
- logForDebugging("Local GitHub repo: unknown");
- return null;
-}
-async function findRemoteBase() {
- const { stdout: trackingBranch, code: trackingCode } = await execFileNoThrow(gitExe(), ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], { preserveOutputOnError: false });
- if (trackingCode === 0 && trackingBranch.trim()) {
- return trackingBranch.trim();
- }
- const { stdout: remoteRefs, code: remoteCode } = await execFileNoThrow(gitExe(), ["remote", "show", "origin", "--", "HEAD"], { preserveOutputOnError: false });
- if (remoteCode === 0) {
- const match = remoteRefs.match(/HEAD branch: (\S+)/);
- if (match && match[1]) {
- return `origin/${match[1]}`;
- }
- }
- const candidates = ["origin/main", "origin/staging", "origin/master"];
- for (const candidate of candidates) {
- const { code } = await execFileNoThrow(gitExe(), ["rev-parse", "--verify", candidate], { preserveOutputOnError: false });
- if (code === 0) {
- return candidate;
- }
- }
- return null;
-}
-function isShallowClone2() {
- return isShallowClone();
-}
-async function captureUntrackedFiles() {
- const { stdout, code } = await execFileNoThrow(gitExe(), ["ls-files", "--others", "--exclude-standard"], { preserveOutputOnError: false });
- const trimmed = stdout.trim();
- if (code !== 0 || !trimmed) {
- return [];
- }
- const files = trimmed.split(`
-`).filter(Boolean);
- const result = [];
- let totalSize = 0;
- for (const filePath of files) {
- if (result.length >= MAX_FILE_COUNT) {
- logForDebugging(`Untracked file capture: reached max file count (${MAX_FILE_COUNT})`);
- break;
- }
- if (hasBinaryExtension(filePath)) {
- continue;
- }
- try {
- const stats = await stat4(filePath);
- const fileSize = stats.size;
- if (fileSize > MAX_FILE_SIZE_BYTES) {
- logForDebugging(`Untracked file capture: skipping ${filePath} (exceeds ${MAX_FILE_SIZE_BYTES} bytes)`);
- continue;
- }
- if (totalSize + fileSize > MAX_TOTAL_SIZE_BYTES) {
- logForDebugging(`Untracked file capture: reached total size limit (${MAX_TOTAL_SIZE_BYTES} bytes)`);
- break;
- }
- if (fileSize === 0) {
- result.push({ path: filePath, content: "" });
- continue;
- }
- const sniffSize = Math.min(SNIFF_BUFFER_SIZE, fileSize);
- const fd = await open2(filePath, "r");
- try {
- const sniffBuf = Buffer.alloc(sniffSize);
- const { bytesRead } = await fd.read(sniffBuf, 0, sniffSize, 0);
- const sniff = sniffBuf.subarray(0, bytesRead);
- if (isBinaryContent(sniff)) {
- continue;
- }
- let content;
- if (fileSize <= sniffSize) {
- content = sniff.toString("utf-8");
- } else {
- content = await readFile4(filePath, "utf-8");
- }
- result.push({ path: filePath, content });
- totalSize += fileSize;
- } finally {
- await fd.close();
- }
- } catch (err) {
- logForDebugging(`Failed to read untracked file ${filePath}: ${err}`);
- }
- }
- return result;
-}
-async function preserveGitStateForIssue() {
- try {
- const isGit = await getIsGit();
- if (!isGit) {
- return null;
- }
- if (await isShallowClone2()) {
- logForDebugging("Shallow clone detected, using HEAD-only mode for issue");
- const [{ stdout: patch2 }, untrackedFiles2] = await Promise.all([
- execFileNoThrow(gitExe(), ["diff", "HEAD"]),
- captureUntrackedFiles()
- ]);
- return {
- remote_base_sha: null,
- remote_base: null,
- patch: patch2 || "",
- untracked_files: untrackedFiles2,
- format_patch: null,
- head_sha: null,
- branch_name: null
- };
- }
- const remoteBase = await findRemoteBase();
- if (!remoteBase) {
- logForDebugging("No remote found, using HEAD-only mode for issue");
- const [{ stdout: patch2 }, untrackedFiles2] = await Promise.all([
- execFileNoThrow(gitExe(), ["diff", "HEAD"]),
- captureUntrackedFiles()
- ]);
- return {
- remote_base_sha: null,
- remote_base: null,
- patch: patch2 || "",
- untracked_files: untrackedFiles2,
- format_patch: null,
- head_sha: null,
- branch_name: null
- };
- }
- const { stdout: mergeBase, code: mergeBaseCode } = await execFileNoThrow(gitExe(), ["merge-base", "HEAD", remoteBase], { preserveOutputOnError: false });
- if (mergeBaseCode !== 0 || !mergeBase.trim()) {
- logForDebugging("Merge-base failed, using HEAD-only mode for issue");
- const [{ stdout: patch2 }, untrackedFiles2] = await Promise.all([
- execFileNoThrow(gitExe(), ["diff", "HEAD"]),
- captureUntrackedFiles()
- ]);
- return {
- remote_base_sha: null,
- remote_base: null,
- patch: patch2 || "",
- untracked_files: untrackedFiles2,
- format_patch: null,
- head_sha: null,
- branch_name: null
- };
- }
- const remoteBaseSha = mergeBase.trim();
- const [
- { stdout: patch },
- untrackedFiles,
- { stdout: formatPatchOut, code: formatPatchCode },
- { stdout: headSha },
- { stdout: branchName }
- ] = await Promise.all([
- execFileNoThrow(gitExe(), ["diff", remoteBaseSha]),
- captureUntrackedFiles(),
- execFileNoThrow(gitExe(), [
- "format-patch",
- `${remoteBaseSha}..HEAD`,
- "--stdout"
- ]),
- execFileNoThrow(gitExe(), ["rev-parse", "HEAD"]),
- execFileNoThrow(gitExe(), ["rev-parse", "--abbrev-ref", "HEAD"])
- ]);
- let formatPatch = null;
- if (formatPatchCode === 0 && formatPatchOut && formatPatchOut.trim()) {
- formatPatch = formatPatchOut;
- }
- const trimmedBranch = branchName?.trim();
- return {
- remote_base_sha: remoteBaseSha,
- remote_base: remoteBase,
- patch: patch || "",
- untracked_files: untrackedFiles,
- format_patch: formatPatch,
- head_sha: headSha?.trim() || null,
- branch_name: trimmedBranch && trimmedBranch !== "HEAD" ? trimmedBranch : null
- };
- } catch (err) {
- logError2(err);
- return null;
- }
-}
-function isLocalHost(host) {
- const hostWithoutPort = host.split(":")[0] ?? "";
- return hostWithoutPort === "localhost" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostWithoutPort);
-}
-function isCurrentDirectoryBareGitRepo() {
- const fs2 = getFsImplementation();
- const cwd2 = getCwd();
- const gitPath = join14(cwd2, ".git");
- try {
- const stats = fs2.statSync(gitPath);
- if (stats.isFile()) {
- return false;
- }
- if (stats.isDirectory()) {
- const gitHeadPath = join14(gitPath, "HEAD");
- try {
- if (fs2.statSync(gitHeadPath).isFile()) {
- return false;
- }
- } catch {}
- }
- } catch {}
- try {
- if (fs2.statSync(join14(cwd2, "HEAD")).isFile())
- return true;
- } catch {}
- try {
- if (fs2.statSync(join14(cwd2, "objects")).isDirectory())
- return true;
- } catch {}
- try {
- if (fs2.statSync(join14(cwd2, "refs")).isDirectory())
- return true;
- } catch {}
- return false;
-}
-var GIT_ROOT_NOT_FOUND, findGitRootImpl, findGitRoot, resolveCanonicalRoot, findCanonicalGitRoot, gitExe, getIsGit, dirIsInGitRepo = async (cwd2) => {
- return findGitRoot(cwd2) !== null;
-}, getHead = async () => {
- return getCachedHead();
-}, getBranch = async () => {
- return getCachedBranch();
-}, getDefaultBranch = async () => {
- return getCachedDefaultBranch();
-}, getRemoteUrl = async () => {
- return getCachedRemoteUrl();
-}, getIsHeadOnRemote = async () => {
- const { code } = await execFileNoThrow(gitExe(), ["rev-parse", "@{u}"], {
- preserveOutputOnError: false
- });
- return code === 0;
-}, hasUnpushedCommits = async () => {
- const { stdout, code } = await execFileNoThrow(gitExe(), ["rev-list", "--count", "@{u}..HEAD"], { preserveOutputOnError: false });
- return code === 0 && parseInt(stdout.trim(), 10) > 0;
-}, getIsClean = async (options2) => {
- const args = ["--no-optional-locks", "status", "--porcelain"];
- if (options2?.ignoreUntracked) {
- args.push("-uno");
- }
- const { stdout } = await execFileNoThrow(gitExe(), args, {
- preserveOutputOnError: false
- });
- return stdout.trim().length === 0;
-}, getChangedFiles = async () => {
- const { stdout } = await execFileNoThrow(gitExe(), ["--no-optional-locks", "status", "--porcelain"], {
- preserveOutputOnError: false
- });
- return stdout.trim().split(`
-`).map((line) => line.trim().split(" ", 2)[1]?.trim()).filter((line) => typeof line === "string");
-}, getFileStatus = async () => {
- const { stdout } = await execFileNoThrow(gitExe(), ["--no-optional-locks", "status", "--porcelain"], {
- preserveOutputOnError: false
- });
- const tracked = [];
- const untracked = [];
- stdout.trim().split(`
-`).filter((line) => line.length > 0).forEach((line) => {
- const status = line.substring(0, 2);
- const filename = line.substring(2).trim();
- if (status === "??") {
- untracked.push(filename);
- } else if (filename) {
- tracked.push(filename);
- }
- });
- return { tracked, untracked };
-}, getWorktreeCount = async () => {
- return getWorktreeCountFromFs();
-}, stashToCleanState = async (message) => {
- try {
- const stashMessage = message || `Claude Code auto-stash - ${new Date().toISOString()}`;
- const { untracked } = await getFileStatus();
- if (untracked.length > 0) {
- const { code: addCode } = await execFileNoThrow(gitExe(), ["add", ...untracked], { preserveOutputOnError: false });
- if (addCode !== 0) {
- return false;
- }
- }
- const { code } = await execFileNoThrow(gitExe(), ["stash", "push", "--message", stashMessage], { preserveOutputOnError: false });
- return code === 0;
- } catch (_) {
- return false;
- }
-}, MAX_FILE_SIZE_BYTES = 524288000, MAX_TOTAL_SIZE_BYTES = 5368709120, MAX_FILE_COUNT = 20000, SNIFF_BUFFER_SIZE = 65536;
-var init_git = __esm(() => {
- init_memoize();
- init_files();
- init_cwd();
- init_debug();
- init_diagLogs();
- init_execFileNoThrow();
- init_fsOperations();
- init_gitFilesystem();
- init_log2();
- init_memoize2();
- init_which();
- GIT_ROOT_NOT_FOUND = Symbol("git-root-not-found");
- findGitRootImpl = memoizeWithLRU((startPath) => {
- const startTime = Date.now();
- logForDiagnosticsNoPII("info", "find_git_root_started");
- let current = resolve6(startPath);
- const root2 = current.substring(0, current.indexOf(sep3) + 1) || sep3;
- let statCount = 0;
- while (current !== root2) {
- try {
- const gitPath = join14(current, ".git");
- statCount++;
- const stat5 = statSync3(gitPath);
- if (stat5.isDirectory() || stat5.isFile()) {
- logForDiagnosticsNoPII("info", "find_git_root_completed", {
- duration_ms: Date.now() - startTime,
- stat_count: statCount,
- found: true
- });
- return current.normalize("NFC");
- }
- } catch {}
- const parent = dirname8(current);
- if (parent === current) {
- break;
- }
- current = parent;
- }
- try {
- const gitPath = join14(root2, ".git");
- statCount++;
- const stat5 = statSync3(gitPath);
- if (stat5.isDirectory() || stat5.isFile()) {
- logForDiagnosticsNoPII("info", "find_git_root_completed", {
- duration_ms: Date.now() - startTime,
- stat_count: statCount,
- found: true
- });
- return root2.normalize("NFC");
- }
- } catch {}
- logForDiagnosticsNoPII("info", "find_git_root_completed", {
- duration_ms: Date.now() - startTime,
- stat_count: statCount,
- found: false
- });
- return GIT_ROOT_NOT_FOUND;
- }, (path8) => path8, 50);
- findGitRoot = createFindGitRoot();
- resolveCanonicalRoot = memoizeWithLRU((gitRoot) => {
- try {
- const gitContent = readFileSync5(join14(gitRoot, ".git"), "utf-8").trim();
- if (!gitContent.startsWith("gitdir:")) {
- return gitRoot;
- }
- const worktreeGitDir = resolve6(gitRoot, gitContent.slice("gitdir:".length).trim());
- const commonDir = resolve6(worktreeGitDir, readFileSync5(join14(worktreeGitDir, "commondir"), "utf-8").trim());
- if (resolve6(dirname8(worktreeGitDir)) !== join14(commonDir, "worktrees")) {
- return gitRoot;
- }
- const backlink = realpathSync3(readFileSync5(join14(worktreeGitDir, "gitdir"), "utf-8").trim());
- if (backlink !== join14(realpathSync3(gitRoot), ".git")) {
- return gitRoot;
- }
- if (basename3(commonDir) !== ".git") {
- return commonDir.normalize("NFC");
- }
- return dirname8(commonDir).normalize("NFC");
- } catch {
- return gitRoot;
- }
- }, (root2) => root2, 50);
- findCanonicalGitRoot = createFindCanonicalGitRoot();
- gitExe = memoize_default(() => {
- return whichSync("git") || "git";
- });
- getIsGit = memoize_default(async () => {
- const startTime = Date.now();
- logForDiagnosticsNoPII("info", "is_git_check_started");
- const isGit = findGitRoot(getCwd()) !== null;
- logForDiagnosticsNoPII("info", "is_git_check_completed", {
- duration_ms: Date.now() - startTime,
- is_git: isGit
- });
- return isGit;
- });
-});
-
-// node_modules/jsonc-parser/lib/esm/impl/scanner.js
-function createScanner(text, ignoreTrivia = false) {
- const len = text.length;
- let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
- function scanHexDigits(count2, exact) {
- let digits = 0;
- let value2 = 0;
- while (digits < count2 || !exact) {
- let ch = text.charCodeAt(pos);
- if (ch >= 48 && ch <= 57) {
- value2 = value2 * 16 + ch - 48;
- } else if (ch >= 65 && ch <= 70) {
- value2 = value2 * 16 + ch - 65 + 10;
- } else if (ch >= 97 && ch <= 102) {
- value2 = value2 * 16 + ch - 97 + 10;
- } else {
- break;
- }
- pos++;
- digits++;
- }
- if (digits < count2) {
- value2 = -1;
- }
- return value2;
- }
- function setPosition(newPosition) {
- pos = newPosition;
- value = "";
- tokenOffset = 0;
- token = 16;
- scanError = 0;
- }
- function scanNumber() {
- let start = pos;
- if (text.charCodeAt(pos) === 48) {
- pos++;
- } else {
- pos++;
- while (pos < text.length && isDigit(text.charCodeAt(pos))) {
- pos++;
- }
- }
- if (pos < text.length && text.charCodeAt(pos) === 46) {
- pos++;
- if (pos < text.length && isDigit(text.charCodeAt(pos))) {
- pos++;
- while (pos < text.length && isDigit(text.charCodeAt(pos))) {
- pos++;
- }
- } else {
- scanError = 3;
- return text.substring(start, pos);
- }
- }
- let end = pos;
- if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
- pos++;
- if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
- pos++;
- }
- if (pos < text.length && isDigit(text.charCodeAt(pos))) {
- pos++;
- while (pos < text.length && isDigit(text.charCodeAt(pos))) {
- pos++;
- }
- end = pos;
- } else {
- scanError = 3;
- }
- }
- return text.substring(start, end);
- }
- function scanString() {
- let result = "", start = pos;
- while (true) {
- if (pos >= len) {
- result += text.substring(start, pos);
- scanError = 2;
- break;
- }
- const ch = text.charCodeAt(pos);
- if (ch === 34) {
- result += text.substring(start, pos);
- pos++;
- break;
- }
- if (ch === 92) {
- result += text.substring(start, pos);
- pos++;
- if (pos >= len) {
- scanError = 2;
- break;
- }
- const ch2 = text.charCodeAt(pos++);
- switch (ch2) {
- case 34:
- result += '"';
- break;
- case 92:
- result += "\\";
- break;
- case 47:
- result += "/";
- break;
- case 98:
- result += "\b";
- break;
- case 102:
- result += "\f";
- break;
- case 110:
- result += `
-`;
- break;
- case 114:
- result += "\r";
- break;
- case 116:
- result += "\t";
- break;
- case 117:
- const ch3 = scanHexDigits(4, true);
- if (ch3 >= 0) {
- result += String.fromCharCode(ch3);
- } else {
- scanError = 4;
- }
- break;
- default:
- scanError = 5;
- }
- start = pos;
- continue;
- }
- if (ch >= 0 && ch <= 31) {
- if (isLineBreak(ch)) {
- result += text.substring(start, pos);
- scanError = 2;
- break;
- } else {
- scanError = 6;
- }
- }
- pos++;
- }
- return result;
- }
- function scanNext() {
- value = "";
- scanError = 0;
- tokenOffset = pos;
- lineStartOffset = lineNumber;
- prevTokenLineStartOffset = tokenLineStartOffset;
- if (pos >= len) {
- tokenOffset = len;
- return token = 17;
- }
- let code = text.charCodeAt(pos);
- if (isWhiteSpace(code)) {
- do {
- pos++;
- value += String.fromCharCode(code);
- code = text.charCodeAt(pos);
- } while (isWhiteSpace(code));
- return token = 15;
- }
- if (isLineBreak(code)) {
- pos++;
- value += String.fromCharCode(code);
- if (code === 13 && text.charCodeAt(pos) === 10) {
- pos++;
- value += `
-`;
- }
- lineNumber++;
- tokenLineStartOffset = pos;
- return token = 14;
- }
- switch (code) {
- case 123:
- pos++;
- return token = 1;
- case 125:
- pos++;
- return token = 2;
- case 91:
- pos++;
- return token = 3;
- case 93:
- pos++;
- return token = 4;
- case 58:
- pos++;
- return token = 6;
- case 44:
- pos++;
- return token = 5;
- case 34:
- pos++;
- value = scanString();
- return token = 10;
- case 47:
- const start = pos - 1;
- if (text.charCodeAt(pos + 1) === 47) {
- pos += 2;
- while (pos < len) {
- if (isLineBreak(text.charCodeAt(pos))) {
- break;
- }
- pos++;
- }
- value = text.substring(start, pos);
- return token = 12;
- }
- if (text.charCodeAt(pos + 1) === 42) {
- pos += 2;
- const safeLength = len - 1;
- let commentClosed = false;
- while (pos < safeLength) {
- const ch = text.charCodeAt(pos);
- if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
- pos += 2;
- commentClosed = true;
- break;
- }
- pos++;
- if (isLineBreak(ch)) {
- if (ch === 13 && text.charCodeAt(pos) === 10) {
- pos++;
- }
- lineNumber++;
- tokenLineStartOffset = pos;
- }
- }
- if (!commentClosed) {
- pos++;
- scanError = 1;
- }
- value = text.substring(start, pos);
- return token = 13;
- }
- value += String.fromCharCode(code);
- pos++;
- return token = 16;
- case 45:
- value += String.fromCharCode(code);
- pos++;
- if (pos === len || !isDigit(text.charCodeAt(pos))) {
- return token = 16;
- }
- case 48:
- case 49:
- case 50:
- case 51:
- case 52:
- case 53:
- case 54:
- case 55:
- case 56:
- case 57:
- value += scanNumber();
- return token = 11;
- default:
- while (pos < len && isUnknownContentCharacter(code)) {
- pos++;
- code = text.charCodeAt(pos);
- }
- if (tokenOffset !== pos) {
- value = text.substring(tokenOffset, pos);
- switch (value) {
- case "true":
- return token = 8;
- case "false":
- return token = 9;
- case "null":
- return token = 7;
- }
- return token = 16;
- }
- value += String.fromCharCode(code);
- pos++;
- return token = 16;
- }
- }
- function isUnknownContentCharacter(code) {
- if (isWhiteSpace(code) || isLineBreak(code)) {
- return false;
- }
- switch (code) {
- case 125:
- case 93:
- case 123:
- case 91:
- case 34:
- case 58:
- case 44:
- case 47:
- return false;
- }
- return true;
- }
- function scanNextNonTrivia() {
- let result;
- do {
- result = scanNext();
- } while (result >= 12 && result <= 15);
- return result;
- }
- return {
- setPosition,
- getPosition: () => pos,
- scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
- getToken: () => token,
- getTokenValue: () => value,
- getTokenOffset: () => tokenOffset,
- getTokenLength: () => pos - tokenOffset,
- getTokenStartLine: () => lineStartOffset,
- getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
- getTokenError: () => scanError
- };
-}
-function isWhiteSpace(ch) {
- return ch === 32 || ch === 9;
-}
-function isLineBreak(ch) {
- return ch === 10 || ch === 13;
-}
-function isDigit(ch) {
- return ch >= 48 && ch <= 57;
-}
-var CharacterCodes;
-var init_scanner = __esm(() => {
- (function(CharacterCodes2) {
- CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
- CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
- CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
- CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
- CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
- CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
- CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
- CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
- CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
- CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
- CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
- CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
- CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
- CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
- CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
- CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
- CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
- CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
- CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
- CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
- CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
- CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
- CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
- CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
- CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
- CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
- CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
- CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
- CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
- CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
- CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
- CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
- CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
- CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
- CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
- CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
- CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
- CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
- CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
- CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
- CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
- CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
- CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
- CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
- CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
- CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
- CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
- CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
- CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
- CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
- CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
- CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
- CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
- CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
- CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
- CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
- CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
- CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
- CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
- CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
- CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
- CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
- CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
- CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
- CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
- CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
- CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
- CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
- CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
- CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
- CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
- CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
- CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
- CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
- CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
- CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
- CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
- CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
- CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
- CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
- })(CharacterCodes || (CharacterCodes = {}));
-});
-
-// node_modules/jsonc-parser/lib/esm/impl/string-intern.js
-var cachedSpaces, maxCachedValues = 200, cachedBreakLinesWithSpaces, supportedEols;
-var init_string_intern = __esm(() => {
- cachedSpaces = new Array(20).fill(0).map((_, index2) => {
- return " ".repeat(index2);
- });
- cachedBreakLinesWithSpaces = {
- " ": {
- "\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
- return `
-` + " ".repeat(index2);
- }),
- "\r": new Array(maxCachedValues).fill(0).map((_, index2) => {
- return "\r" + " ".repeat(index2);
- }),
- "\r\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
- return `\r
-` + " ".repeat(index2);
- })
- },
- "\t": {
- "\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
- return `
-` + "\t".repeat(index2);
- }),
- "\r": new Array(maxCachedValues).fill(0).map((_, index2) => {
- return "\r" + "\t".repeat(index2);
- }),
- "\r\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
- return `\r
-` + "\t".repeat(index2);
- })
- }
- };
- supportedEols = [`
-`, "\r", `\r
-`];
-});
-
-// node_modules/jsonc-parser/lib/esm/impl/format.js
-function format2(documentText, range, options2) {
- let initialIndentLevel;
- let formatText;
- let formatTextStart;
- let rangeStart;
- let rangeEnd;
- if (range) {
- rangeStart = range.offset;
- rangeEnd = rangeStart + range.length;
- formatTextStart = rangeStart;
- while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
- formatTextStart--;
- }
- let endOffset = rangeEnd;
- while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
- endOffset++;
- }
- formatText = documentText.substring(formatTextStart, endOffset);
- initialIndentLevel = computeIndentLevel(formatText, options2);
- } else {
- formatText = documentText;
- initialIndentLevel = 0;
- formatTextStart = 0;
- rangeStart = 0;
- rangeEnd = documentText.length;
- }
- const eol = getEOL(options2, documentText);
- const eolFastPathSupported = supportedEols.includes(eol);
- let numberLineBreaks = 0;
- let indentLevel = 0;
- let indentValue;
- if (options2.insertSpaces) {
- indentValue = cachedSpaces[options2.tabSize || 4] ?? repeat(cachedSpaces[1], options2.tabSize || 4);
- } else {
- indentValue = "\t";
- }
- const indentType = indentValue === "\t" ? "\t" : " ";
- let scanner = createScanner(formatText, false);
- let hasError = false;
- function newLinesAndIndent() {
- if (numberLineBreaks > 1) {
- return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
- }
- const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);
- if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {
- return eol + repeat(indentValue, initialIndentLevel + indentLevel);
- }
- if (amountOfSpaces <= 0) {
- return eol;
- }
- return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];
- }
- function scanNext() {
- let token = scanner.scan();
- numberLineBreaks = 0;
- while (token === 15 || token === 14) {
- if (token === 14 && options2.keepLines) {
- numberLineBreaks += 1;
- } else if (token === 14) {
- numberLineBreaks = 1;
- }
- token = scanner.scan();
- }
- hasError = token === 16 || scanner.getTokenError() !== 0;
- return token;
- }
- const editOperations = [];
- function addEdit(text, startOffset, endOffset) {
- if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) {
- editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
- }
- }
- let firstToken = scanNext();
- if (options2.keepLines && numberLineBreaks > 0) {
- addEdit(repeat(eol, numberLineBreaks), 0, 0);
- }
- if (firstToken !== 17) {
- let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
- let initialIndent = indentValue.length * initialIndentLevel < 20 && options2.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel);
- addEdit(initialIndent, formatTextStart, firstTokenStart);
- }
- while (firstToken !== 17) {
- let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
- let secondToken = scanNext();
- let replaceContent = "";
- let needsLineBreak = false;
- while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
- let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
- addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);
- firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
- needsLineBreak = secondToken === 12;
- replaceContent = needsLineBreak ? newLinesAndIndent() : "";
- secondToken = scanNext();
- }
- if (secondToken === 2) {
- if (firstToken !== 1) {
- indentLevel--;
- }
- if (options2.keepLines && numberLineBreaks > 0 || !options2.keepLines && firstToken !== 1) {
- replaceContent = newLinesAndIndent();
- } else if (options2.keepLines) {
- replaceContent = cachedSpaces[1];
- }
- } else if (secondToken === 4) {
- if (firstToken !== 3) {
- indentLevel--;
- }
- if (options2.keepLines && numberLineBreaks > 0 || !options2.keepLines && firstToken !== 3) {
- replaceContent = newLinesAndIndent();
- } else if (options2.keepLines) {
- replaceContent = cachedSpaces[1];
- }
- } else {
- switch (firstToken) {
- case 3:
- case 1:
- indentLevel++;
- if (options2.keepLines && numberLineBreaks > 0 || !options2.keepLines) {
- replaceContent = newLinesAndIndent();
- } else {
- replaceContent = cachedSpaces[1];
- }
- break;
- case 5:
- if (options2.keepLines && numberLineBreaks > 0 || !options2.keepLines) {
- replaceContent = newLinesAndIndent();
- } else {
- replaceContent = cachedSpaces[1];
- }
- break;
- case 12:
- replaceContent = newLinesAndIndent();
- break;
- case 13:
- if (numberLineBreaks > 0) {
- replaceContent = newLinesAndIndent();
- } else if (!needsLineBreak) {
- replaceContent = cachedSpaces[1];
- }
- break;
- case 6:
- if (options2.keepLines && numberLineBreaks > 0) {
- replaceContent = newLinesAndIndent();
- } else if (!needsLineBreak) {
- replaceContent = cachedSpaces[1];
- }
- break;
- case 10:
- if (options2.keepLines && numberLineBreaks > 0) {
- replaceContent = newLinesAndIndent();
- } else if (secondToken === 6 && !needsLineBreak) {
- replaceContent = "";
- }
- break;
- case 7:
- case 8:
- case 9:
- case 11:
- case 2:
- case 4:
- if (options2.keepLines && numberLineBreaks > 0) {
- replaceContent = newLinesAndIndent();
- } else {
- if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) {
- replaceContent = cachedSpaces[1];
- } else if (secondToken !== 5 && secondToken !== 17) {
- hasError = true;
- }
- }
- break;
- case 16:
- hasError = true;
- break;
- }
- if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) {
- replaceContent = newLinesAndIndent();
- }
- }
- if (secondToken === 17) {
- if (options2.keepLines && numberLineBreaks > 0) {
- replaceContent = newLinesAndIndent();
- } else {
- replaceContent = options2.insertFinalNewline ? eol : "";
- }
- }
- const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
- addEdit(replaceContent, firstTokenEnd, secondTokenStart);
- firstToken = secondToken;
- }
- return editOperations;
-}
-function repeat(s, count2) {
- let result = "";
- for (let i2 = 0;i2 < count2; i2++) {
- result += s;
- }
- return result;
-}
-function computeIndentLevel(content, options2) {
- let i2 = 0;
- let nChars = 0;
- const tabSize = options2.tabSize || 4;
- while (i2 < content.length) {
- let ch = content.charAt(i2);
- if (ch === cachedSpaces[1]) {
- nChars++;
- } else if (ch === "\t") {
- nChars += tabSize;
- } else {
- break;
- }
- i2++;
- }
- return Math.floor(nChars / tabSize);
-}
-function getEOL(options2, text) {
- for (let i2 = 0;i2 < text.length; i2++) {
- const ch = text.charAt(i2);
- if (ch === "\r") {
- if (i2 + 1 < text.length && text.charAt(i2 + 1) === `
-`) {
- return `\r
-`;
- }
- return "\r";
- } else if (ch === `
-`) {
- return `
-`;
- }
- }
- return options2 && options2.eol || `
-`;
-}
-function isEOL(text, offset) {
- return `\r
-`.indexOf(text.charAt(offset)) !== -1;
-}
-var init_format2 = __esm(() => {
- init_scanner();
- init_string_intern();
-});
-
-// node_modules/jsonc-parser/lib/esm/impl/parser.js
-function parse(text, errors = [], options2 = ParseOptions.DEFAULT) {
- let currentProperty = null;
- let currentParent = [];
- const previousParents = [];
- function onValue(value) {
- if (Array.isArray(currentParent)) {
- currentParent.push(value);
- } else if (currentProperty !== null) {
- currentParent[currentProperty] = value;
- }
- }
- const visitor = {
- onObjectBegin: () => {
- const object = {};
- onValue(object);
- previousParents.push(currentParent);
- currentParent = object;
- currentProperty = null;
- },
- onObjectProperty: (name) => {
- currentProperty = name;
- },
- onObjectEnd: () => {
- currentParent = previousParents.pop();
- },
- onArrayBegin: () => {
- const array = [];
- onValue(array);
- previousParents.push(currentParent);
- currentParent = array;
- currentProperty = null;
- },
- onArrayEnd: () => {
- currentParent = previousParents.pop();
- },
- onLiteralValue: onValue,
- onError: (error, offset, length) => {
- errors.push({ error, offset, length });
- }
- };
- visit(text, visitor, options2);
- return currentParent[0];
-}
-function parseTree(text, errors = [], options2 = ParseOptions.DEFAULT) {
- let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: undefined };
- function ensurePropertyComplete(endOffset) {
- if (currentParent.type === "property") {
- currentParent.length = endOffset - currentParent.offset;
- currentParent = currentParent.parent;
- }
- }
- function onValue(valueNode) {
- currentParent.children.push(valueNode);
- return valueNode;
- }
- const visitor = {
- onObjectBegin: (offset) => {
- currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] });
- },
- onObjectProperty: (name, offset, length) => {
- currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] });
- currentParent.children.push({ type: "string", value: name, offset, length, parent: currentParent });
- },
- onObjectEnd: (offset, length) => {
- ensurePropertyComplete(offset + length);
- currentParent.length = offset + length - currentParent.offset;
- currentParent = currentParent.parent;
- ensurePropertyComplete(offset + length);
- },
- onArrayBegin: (offset, length) => {
- currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] });
- },
- onArrayEnd: (offset, length) => {
- currentParent.length = offset + length - currentParent.offset;
- currentParent = currentParent.parent;
- ensurePropertyComplete(offset + length);
- },
- onLiteralValue: (value, offset, length) => {
- onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });
- ensurePropertyComplete(offset + length);
- },
- onSeparator: (sep4, offset, length) => {
- if (currentParent.type === "property") {
- if (sep4 === ":") {
- currentParent.colonOffset = offset;
- } else if (sep4 === ",") {
- ensurePropertyComplete(offset);
- }
- }
- },
- onError: (error, offset, length) => {
- errors.push({ error, offset, length });
- }
- };
- visit(text, visitor, options2);
- const result = currentParent.children[0];
- if (result) {
- delete result.parent;
- }
- return result;
-}
-function findNodeAtLocation(root2, path8) {
- if (!root2) {
- return;
- }
- let node = root2;
- for (let segment of path8) {
- if (typeof segment === "string") {
- if (node.type !== "object" || !Array.isArray(node.children)) {
- return;
- }
- let found = false;
- for (const propertyNode of node.children) {
- if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
- node = propertyNode.children[1];
- found = true;
- break;
- }
- }
- if (!found) {
- return;
- }
- } else {
- const index2 = segment;
- if (node.type !== "array" || index2 < 0 || !Array.isArray(node.children) || index2 >= node.children.length) {
- return;
- }
- node = node.children[index2];
- }
- }
- return node;
-}
-function visit(text, visitor, options2 = ParseOptions.DEFAULT) {
- const _scanner = createScanner(text, false);
- const _jsonPath = [];
- let suppressedCallbacks = 0;
- function toNoArgVisit(visitFunction) {
- return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
- }
- function toOneArgVisit(visitFunction) {
- return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
- }
- function toOneArgVisitWithPath(visitFunction) {
- return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
- }
- function toBeginVisit(visitFunction) {
- return visitFunction ? () => {
- if (suppressedCallbacks > 0) {
- suppressedCallbacks++;
- } else {
- let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());
- if (cbReturn === false) {
- suppressedCallbacks = 1;
- }
- }
- } : () => true;
- }
- function toEndVisit(visitFunction) {
- return visitFunction ? () => {
- if (suppressedCallbacks > 0) {
- suppressedCallbacks--;
- }
- if (suppressedCallbacks === 0) {
- visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
- }
- } : () => true;
- }
- const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
- const disallowComments = options2 && options2.disallowComments;
- const allowTrailingComma = options2 && options2.allowTrailingComma;
- function scanNext() {
- while (true) {
- const token = _scanner.scan();
- switch (_scanner.getTokenError()) {
- case 4:
- handleError(14);
- break;
- case 5:
- handleError(15);
- break;
- case 3:
- handleError(13);
- break;
- case 1:
- if (!disallowComments) {
- handleError(11);
- }
- break;
- case 2:
- handleError(12);
- break;
- case 6:
- handleError(16);
- break;
- }
- switch (token) {
- case 12:
- case 13:
- if (disallowComments) {
- handleError(10);
- } else {
- onComment();
- }
- break;
- case 16:
- handleError(1);
- break;
- case 15:
- case 14:
- break;
- default:
- return token;
- }
- }
- }
- function handleError(error, skipUntilAfter = [], skipUntil = []) {
- onError(error);
- if (skipUntilAfter.length + skipUntil.length > 0) {
- let token = _scanner.getToken();
- while (token !== 17) {
- if (skipUntilAfter.indexOf(token) !== -1) {
- scanNext();
- break;
- } else if (skipUntil.indexOf(token) !== -1) {
- break;
- }
- token = scanNext();
- }
- }
- }
- function parseString(isValue) {
- const value = _scanner.getTokenValue();
- if (isValue) {
- onLiteralValue(value);
- } else {
- onObjectProperty(value);
- _jsonPath.push(value);
- }
- scanNext();
- return true;
- }
- function parseLiteral() {
- switch (_scanner.getToken()) {
- case 11:
- const tokenValue = _scanner.getTokenValue();
- let value = Number(tokenValue);
- if (isNaN(value)) {
- handleError(2);
- value = 0;
- }
- onLiteralValue(value);
- break;
- case 7:
- onLiteralValue(null);
- break;
- case 8:
- onLiteralValue(true);
- break;
- case 9:
- onLiteralValue(false);
- break;
- default:
- return false;
- }
- scanNext();
- return true;
- }
- function parseProperty() {
- if (_scanner.getToken() !== 10) {
- handleError(3, [], [2, 5]);
- return false;
- }
- parseString(false);
- if (_scanner.getToken() === 6) {
- onSeparator(":");
- scanNext();
- if (!parseValue2()) {
- handleError(4, [], [2, 5]);
- }
- } else {
- handleError(5, [], [2, 5]);
- }
- _jsonPath.pop();
- return true;
- }
- function parseObject() {
- onObjectBegin();
- scanNext();
- let needsComma = false;
- while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
- if (_scanner.getToken() === 5) {
- if (!needsComma) {
- handleError(4, [], []);
- }
- onSeparator(",");
- scanNext();
- if (_scanner.getToken() === 2 && allowTrailingComma) {
- break;
- }
- } else if (needsComma) {
- handleError(6, [], []);
- }
- if (!parseProperty()) {
- handleError(4, [], [2, 5]);
- }
- needsComma = true;
- }
- onObjectEnd();
- if (_scanner.getToken() !== 2) {
- handleError(7, [2], []);
- } else {
- scanNext();
- }
- return true;
- }
- function parseArray() {
- onArrayBegin();
- scanNext();
- let isFirstElement = true;
- let needsComma = false;
- while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
- if (_scanner.getToken() === 5) {
- if (!needsComma) {
- handleError(4, [], []);
- }
- onSeparator(",");
- scanNext();
- if (_scanner.getToken() === 4 && allowTrailingComma) {
- break;
- }
- } else if (needsComma) {
- handleError(6, [], []);
- }
- if (isFirstElement) {
- _jsonPath.push(0);
- isFirstElement = false;
- } else {
- _jsonPath[_jsonPath.length - 1]++;
- }
- if (!parseValue2()) {
- handleError(4, [], [4, 5]);
- }
- needsComma = true;
- }
- onArrayEnd();
- if (!isFirstElement) {
- _jsonPath.pop();
- }
- if (_scanner.getToken() !== 4) {
- handleError(8, [4], []);
- } else {
- scanNext();
- }
- return true;
- }
- function parseValue2() {
- switch (_scanner.getToken()) {
- case 3:
- return parseArray();
- case 1:
- return parseObject();
- case 10:
- return parseString(true);
- default:
- return parseLiteral();
- }
- }
- scanNext();
- if (_scanner.getToken() === 17) {
- if (options2.allowEmptyContent) {
- return true;
- }
- handleError(4, [], []);
- return false;
- }
- if (!parseValue2()) {
- handleError(4, [], []);
- return false;
- }
- if (_scanner.getToken() !== 17) {
- handleError(9, [], []);
- }
- return true;
-}
-function getNodeType(value) {
- switch (typeof value) {
- case "boolean":
- return "boolean";
- case "number":
- return "number";
- case "string":
- return "string";
- case "object": {
- if (!value) {
- return "null";
- } else if (Array.isArray(value)) {
- return "array";
- }
- return "object";
- }
- default:
- return "null";
- }
-}
-var ParseOptions;
-var init_parser2 = __esm(() => {
- init_scanner();
- (function(ParseOptions2) {
- ParseOptions2.DEFAULT = {
- allowTrailingComma: false
- };
- })(ParseOptions || (ParseOptions = {}));
-});
-
-// node_modules/jsonc-parser/lib/esm/impl/edit.js
-function setProperty(text, originalPath, value, options2) {
- const path8 = originalPath.slice();
- const errors = [];
- const root2 = parseTree(text, errors);
- let parent = undefined;
- let lastSegment = undefined;
- while (path8.length > 0) {
- lastSegment = path8.pop();
- parent = findNodeAtLocation(root2, path8);
- if (parent === undefined && value !== undefined) {
- if (typeof lastSegment === "string") {
- value = { [lastSegment]: value };
- } else {
- value = [value];
- }
- } else {
- break;
- }
- }
- if (!parent) {
- if (value === undefined) {
- throw new Error("Can not delete in empty document");
- }
- return withFormatting(text, { offset: root2 ? root2.offset : 0, length: root2 ? root2.length : 0, content: JSON.stringify(value) }, options2);
- } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
- const existing = findNodeAtLocation(parent, [lastSegment]);
- if (existing !== undefined) {
- if (value === undefined) {
- if (!existing.parent) {
- throw new Error("Malformed AST");
- }
- const propertyIndex = parent.children.indexOf(existing.parent);
- let removeBegin;
- let removeEnd = existing.parent.offset + existing.parent.length;
- if (propertyIndex > 0) {
- let previous = parent.children[propertyIndex - 1];
- removeBegin = previous.offset + previous.length;
- } else {
- removeBegin = parent.offset + 1;
- if (parent.children.length > 1) {
- let next = parent.children[1];
- removeEnd = next.offset;
- }
- }
- return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, options2);
- } else {
- return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options2);
- }
- } else {
- if (value === undefined) {
- return [];
- }
- const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
- const index2 = options2.getInsertionIndex ? options2.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
- let edit2;
- if (index2 > 0) {
- let previous = parent.children[index2 - 1];
- edit2 = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
- } else if (parent.children.length === 0) {
- edit2 = { offset: parent.offset + 1, length: 0, content: newProperty };
- } else {
- edit2 = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
- }
- return withFormatting(text, edit2, options2);
- }
- } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
- const insertIndex = lastSegment;
- if (insertIndex === -1) {
- const newProperty = `${JSON.stringify(value)}`;
- let edit2;
- if (parent.children.length === 0) {
- edit2 = { offset: parent.offset + 1, length: 0, content: newProperty };
- } else {
- const previous = parent.children[parent.children.length - 1];
- edit2 = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
- }
- return withFormatting(text, edit2, options2);
- } else if (value === undefined && parent.children.length >= 0) {
- const removalIndex = lastSegment;
- const toRemove = parent.children[removalIndex];
- let edit2;
- if (parent.children.length === 1) {
- edit2 = { offset: parent.offset + 1, length: parent.length - 2, content: "" };
- } else if (parent.children.length - 1 === removalIndex) {
- let previous = parent.children[removalIndex - 1];
- let offset = previous.offset + previous.length;
- let parentEndOffset = parent.offset + parent.length;
- edit2 = { offset, length: parentEndOffset - 2 - offset, content: "" };
- } else {
- edit2 = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
- }
- return withFormatting(text, edit2, options2);
- } else if (value !== undefined) {
- let edit2;
- const newProperty = `${JSON.stringify(value)}`;
- if (!options2.isArrayInsertion && parent.children.length > lastSegment) {
- const toModify = parent.children[lastSegment];
- edit2 = { offset: toModify.offset, length: toModify.length, content: newProperty };
- } else if (parent.children.length === 0 || lastSegment === 0) {
- edit2 = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + "," };
- } else {
- const index2 = lastSegment > parent.children.length ? parent.children.length : lastSegment;
- const previous = parent.children[index2 - 1];
- edit2 = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
- }
- return withFormatting(text, edit2, options2);
- } else {
- throw new Error(`Can not ${value === undefined ? "remove" : options2.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
- }
- } else {
- throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
- }
-}
-function withFormatting(text, edit2, options2) {
- if (!options2.formattingOptions) {
- return [edit2];
- }
- let newText = applyEdit(text, edit2);
- let begin = edit2.offset;
- let end = edit2.offset + edit2.content.length;
- if (edit2.length === 0 || edit2.content.length === 0) {
- while (begin > 0 && !isEOL(newText, begin - 1)) {
- begin--;
- }
- while (end < newText.length && !isEOL(newText, end)) {
- end++;
- }
- }
- const edits = format2(newText, { offset: begin, length: end - begin }, { ...options2.formattingOptions, keepLines: false });
- for (let i2 = edits.length - 1;i2 >= 0; i2--) {
- const edit3 = edits[i2];
- newText = applyEdit(newText, edit3);
- begin = Math.min(begin, edit3.offset);
- end = Math.max(end, edit3.offset + edit3.length);
- end += edit3.content.length - edit3.length;
- }
- const editLength = text.length - (newText.length - end) - begin;
- return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
-}
-function applyEdit(text, edit2) {
- return text.substring(0, edit2.offset) + edit2.content + text.substring(edit2.offset + edit2.length);
-}
-var init_edit = __esm(() => {
- init_format2();
- init_parser2();
-});
-
-// node_modules/jsonc-parser/lib/esm/main.js
-function modify(text, path8, value, options2) {
- return setProperty(text, path8, value, options2);
-}
-function applyEdits(text, edits) {
- let sortedEdits = edits.slice(0).sort((a2, b) => {
- const diff = a2.offset - b.offset;
- if (diff === 0) {
- return a2.length - b.length;
- }
- return diff;
- });
- let lastModifiedOffset = text.length;
- for (let i2 = sortedEdits.length - 1;i2 >= 0; i2--) {
- let e = sortedEdits[i2];
- if (e.offset + e.length <= lastModifiedOffset) {
- text = applyEdit(text, e);
- } else {
- throw new Error("Overlapping edit");
- }
- lastModifiedOffset = e.offset;
- }
- return text;
-}
-var ScanError, SyntaxKind, parse2, ParseErrorCode;
-var init_main2 = __esm(() => {
- init_format2();
- init_edit();
- init_scanner();
- init_parser2();
- (function(ScanError2) {
- ScanError2[ScanError2["None"] = 0] = "None";
- ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
- ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
- ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
- ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
- ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
- ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
- })(ScanError || (ScanError = {}));
- (function(SyntaxKind2) {
- SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
- SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
- SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
- SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
- SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
- SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
- SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
- SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
- SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
- SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
- SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
- SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
- SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
- SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
- SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
- SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
- SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
- })(SyntaxKind || (SyntaxKind = {}));
- parse2 = parse;
- (function(ParseErrorCode2) {
- ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
- ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
- ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
- ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
- ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
- ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
- ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
- ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
- ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
- ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
- ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
- ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
- ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
- ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
- ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
- ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
- })(ParseErrorCode || (ParseErrorCode = {}));
-});
-
-// src/utils/jsonRead.ts
-function stripBOM2(content) {
- return content.startsWith(UTF8_BOM) ? content.slice(1) : content;
-}
-var UTF8_BOM = "\uFEFF";
-
-// src/utils/json.ts
-import { open as open3, readFile as readFile5, stat as stat5 } from "fs/promises";
-function parseJSONUncached(json, shouldLogError) {
- try {
- return { ok: true, value: JSON.parse(stripBOM2(json)) };
- } catch (e) {
- if (shouldLogError) {
- logError2(e);
- }
- return { ok: false };
- }
-}
-function safeParseJSONC(json) {
- if (!json) {
- return null;
- }
- try {
- return parse2(stripBOM2(json));
- } catch (e) {
- logError2(e);
- return null;
- }
-}
-function parseJSONLBun(data) {
- const parse3 = bunJSONLParse;
- const len = data.length;
- const result = parse3(data);
- if (!result.error || result.done || result.read >= len) {
- return result.values;
- }
- let values = result.values;
- let offset = result.read;
- while (offset < len) {
- const newlineIndex = typeof data === "string" ? data.indexOf(`
-`, offset) : data.indexOf(10, offset);
- if (newlineIndex === -1)
- break;
- offset = newlineIndex + 1;
- const next = parse3(data, offset);
- if (next.values.length > 0) {
- values = values.concat(next.values);
- }
- if (!next.error || next.done || next.read >= len)
- break;
- offset = next.read;
- }
- return values;
-}
-function parseJSONLBuffer(buf) {
- const bufLen = buf.length;
- let start = 0;
- if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) {
- start = 3;
- }
- const results = [];
- while (start < bufLen) {
- let end = buf.indexOf(10, start);
- if (end === -1)
- end = bufLen;
- const line = buf.toString("utf8", start, end).trim();
- start = end + 1;
- if (!line)
- continue;
- try {
- results.push(JSON.parse(line));
- } catch {}
- }
- return results;
-}
-function parseJSONLString(data) {
- const stripped = stripBOM2(data);
- const len = stripped.length;
- let start = 0;
- const results = [];
- while (start < len) {
- let end = stripped.indexOf(`
-`, start);
- if (end === -1)
- end = len;
- const line = stripped.substring(start, end).trim();
- start = end + 1;
- if (!line)
- continue;
- try {
- results.push(JSON.parse(line));
- } catch {}
- }
- return results;
-}
-function parseJSONL(data) {
- if (bunJSONLParse) {
- return parseJSONLBun(data);
- }
- if (typeof data === "string") {
- return parseJSONLString(data);
- }
- return parseJSONLBuffer(data);
-}
-async function readJSONLFile(filePath) {
- let __stack = [];
- try {
- const { size } = await stat5(filePath);
- if (size <= MAX_JSONL_READ_BYTES) {
- return parseJSONL(await readFile5(filePath));
- }
- const fd = __using(__stack, await open3(filePath, "r"), 1);
- const buf = Buffer.allocUnsafe(MAX_JSONL_READ_BYTES);
- let totalRead = 0;
- const fileOffset = size - MAX_JSONL_READ_BYTES;
- while (totalRead < MAX_JSONL_READ_BYTES) {
- const { bytesRead } = await fd.read(buf, totalRead, MAX_JSONL_READ_BYTES - totalRead, fileOffset + totalRead);
- if (bytesRead === 0)
- break;
- totalRead += bytesRead;
- }
- const newlineIndex = buf.indexOf(10);
- if (newlineIndex !== -1 && newlineIndex < totalRead - 1) {
- return parseJSONL(buf.subarray(newlineIndex + 1, totalRead));
- }
- return parseJSONL(buf.subarray(0, totalRead));
- } catch (_catch) {
- var _err = _catch, _hasErr = 1;
- } finally {
- var _promise = __callDispose(__stack, _err, _hasErr);
- _promise && await _promise;
- }
-}
-function addItemToJSONCArray(content, newItem) {
- try {
- if (!content || content.trim() === "") {
- return jsonStringify([newItem], null, 4);
- }
- const cleanContent = stripBOM2(content);
- const parsedContent = parse2(cleanContent);
- if (Array.isArray(parsedContent)) {
- const arrayLength = parsedContent.length;
- const isEmpty = arrayLength === 0;
- const insertPath = isEmpty ? [0] : [arrayLength];
- const edits = modify(cleanContent, insertPath, newItem, {
- formattingOptions: { insertSpaces: true, tabSize: 4 },
- isArrayInsertion: true
- });
- if (!edits || edits.length === 0) {
- const copy = [...parsedContent, newItem];
- return jsonStringify(copy, null, 4);
- }
- return applyEdits(cleanContent, edits);
- } else {
- return jsonStringify([newItem], null, 4);
- }
- } catch (e) {
- logError2(e);
- return jsonStringify([newItem], null, 4);
- }
-}
-var PARSE_CACHE_MAX_KEY_BYTES, parseJSONCached, safeParseJSON, bunJSONLParse, MAX_JSONL_READ_BYTES;
-var init_json = __esm(() => {
- init_main2();
- init_log2();
- init_memoize2();
- init_slowOperations();
- PARSE_CACHE_MAX_KEY_BYTES = 8 * 1024;
- parseJSONCached = memoizeWithLRU(parseJSONUncached, (json) => json, 50);
- safeParseJSON = Object.assign(function safeParseJSON2(json, shouldLogError = true) {
- if (!json)
- return null;
- const result = json.length > PARSE_CACHE_MAX_KEY_BYTES ? parseJSONUncached(json, shouldLogError) : parseJSONCached(json, shouldLogError);
- return result.ok ? result.value : null;
- }, { cache: parseJSONCached.cache });
- bunJSONLParse = (() => {
- if (typeof Bun === "undefined")
- return false;
- const b = Bun;
- const jsonl = b.JSONL;
- if (!jsonl?.parseChunk)
- return false;
- return jsonl.parseChunk;
- })();
- MAX_JSONL_READ_BYTES = 100 * 1024 * 1024;
-});
-
-// node_modules/graceful-fs/polyfills.js
-var require_polyfills = __commonJS((exports, module) => {
- var constants4 = __require("constants");
- var origCwd = process.cwd;
- var cwd2 = null;
- var platform2 = process.env.GRACEFUL_FS_PLATFORM || process.platform;
- process.cwd = function() {
- if (!cwd2)
- cwd2 = origCwd.call(process);
- return cwd2;
- };
- try {
- process.cwd();
- } catch (er) {}
- if (typeof process.chdir === "function") {
- chdir = process.chdir;
- process.chdir = function(d) {
- cwd2 = null;
- chdir.call(process, d);
- };
- if (Object.setPrototypeOf)
- Object.setPrototypeOf(process.chdir, chdir);
- }
- var chdir;
- module.exports = patch;
- function patch(fs2) {
- if (constants4.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
- patchLchmod(fs2);
- }
- if (!fs2.lutimes) {
- patchLutimes(fs2);
- }
- fs2.chown = chownFix(fs2.chown);
- fs2.fchown = chownFix(fs2.fchown);
- fs2.lchown = chownFix(fs2.lchown);
- fs2.chmod = chmodFix(fs2.chmod);
- fs2.fchmod = chmodFix(fs2.fchmod);
- fs2.lchmod = chmodFix(fs2.lchmod);
- fs2.chownSync = chownFixSync(fs2.chownSync);
- fs2.fchownSync = chownFixSync(fs2.fchownSync);
- fs2.lchownSync = chownFixSync(fs2.lchownSync);
- fs2.chmodSync = chmodFixSync(fs2.chmodSync);
- fs2.fchmodSync = chmodFixSync(fs2.fchmodSync);
- fs2.lchmodSync = chmodFixSync(fs2.lchmodSync);
- fs2.stat = statFix(fs2.stat);
- fs2.fstat = statFix(fs2.fstat);
- fs2.lstat = statFix(fs2.lstat);
- fs2.statSync = statFixSync(fs2.statSync);
- fs2.fstatSync = statFixSync(fs2.fstatSync);
- fs2.lstatSync = statFixSync(fs2.lstatSync);
- if (fs2.chmod && !fs2.lchmod) {
- fs2.lchmod = function(path8, mode, cb) {
- if (cb)
- process.nextTick(cb);
- };
- fs2.lchmodSync = function() {};
- }
- if (fs2.chown && !fs2.lchown) {
- fs2.lchown = function(path8, uid, gid, cb) {
- if (cb)
- process.nextTick(cb);
- };
- fs2.lchownSync = function() {};
- }
- if (platform2 === "win32") {
- fs2.rename = typeof fs2.rename !== "function" ? fs2.rename : function(fs$rename) {
- function rename(from, to, cb) {
- var start = Date.now();
- var backoff = 0;
- fs$rename(from, to, function CB(er) {
- if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 60000) {
- setTimeout(function() {
- fs2.stat(to, function(stater, st) {
- if (stater && stater.code === "ENOENT")
- fs$rename(from, to, CB);
- else
- cb(er);
- });
- }, backoff);
- if (backoff < 100)
- backoff += 10;
- return;
- }
- if (cb)
- cb(er);
- });
- }
- if (Object.setPrototypeOf)
- Object.setPrototypeOf(rename, fs$rename);
- return rename;
- }(fs2.rename);
- }
- fs2.read = typeof fs2.read !== "function" ? fs2.read : function(fs$read) {
- function read(fd, buffer, offset, length, position2, callback_) {
- var callback;
- if (callback_ && typeof callback_ === "function") {
- var eagCounter = 0;
- callback = function(er, _, __) {
- if (er && er.code === "EAGAIN" && eagCounter < 10) {
- eagCounter++;
- return fs$read.call(fs2, fd, buffer, offset, length, position2, callback);
- }
- callback_.apply(this, arguments);
- };
- }
- return fs$read.call(fs2, fd, buffer, offset, length, position2, callback);
- }
- if (Object.setPrototypeOf)
- Object.setPrototypeOf(read, fs$read);
- return read;
- }(fs2.read);
- fs2.readSync = typeof fs2.readSync !== "function" ? fs2.readSync : function(fs$readSync) {
- return function(fd, buffer, offset, length, position2) {
- var eagCounter = 0;
- while (true) {
- try {
- return fs$readSync.call(fs2, fd, buffer, offset, length, position2);
- } catch (er) {
- if (er.code === "EAGAIN" && eagCounter < 10) {
- eagCounter++;
- continue;
- }
- throw er;
- }
- }
- };
- }(fs2.readSync);
- function patchLchmod(fs3) {
- fs3.lchmod = function(path8, mode, callback) {
- fs3.open(path8, constants4.O_WRONLY | constants4.O_SYMLINK, mode, function(err, fd) {
- if (err) {
- if (callback)
- callback(err);
- return;
- }
- fs3.fchmod(fd, mode, function(err2) {
- fs3.close(fd, function(err22) {
- if (callback)
- callback(err2 || err22);
- });
- });
- });
- };
- fs3.lchmodSync = function(path8, mode) {
- var fd = fs3.openSync(path8, constants4.O_WRONLY | constants4.O_SYMLINK, mode);
- var threw = true;
- var ret;
- try {
- ret = fs3.fchmodSync(fd, mode);
- threw = false;
- } finally {
- if (threw) {
- try {
- fs3.closeSync(fd);
- } catch (er) {}
- } else {
- fs3.closeSync(fd);
- }
- }
- return ret;
- };
- }
- function patchLutimes(fs3) {
- if (constants4.hasOwnProperty("O_SYMLINK") && fs3.futimes) {
- fs3.lutimes = function(path8, at, mt, cb) {
- fs3.open(path8, constants4.O_SYMLINK, function(er, fd) {
- if (er) {
- if (cb)
- cb(er);
- return;
- }
- fs3.futimes(fd, at, mt, function(er2) {
- fs3.close(fd, function(er22) {
- if (cb)
- cb(er2 || er22);
- });
- });
- });
- };
- fs3.lutimesSync = function(path8, at, mt) {
- var fd = fs3.openSync(path8, constants4.O_SYMLINK);
- var ret;
- var threw = true;
- try {
- ret = fs3.futimesSync(fd, at, mt);
- threw = false;
- } finally {
- if (threw) {
- try {
- fs3.closeSync(fd);
- } catch (er) {}
- } else {
- fs3.closeSync(fd);
- }
- }
- return ret;
- };
- } else if (fs3.futimes) {
- fs3.lutimes = function(_a2, _b, _c, cb) {
- if (cb)
- process.nextTick(cb);
- };
- fs3.lutimesSync = function() {};
- }
- }
- function chmodFix(orig) {
- if (!orig)
- return orig;
- return function(target, mode, cb) {
- return orig.call(fs2, target, mode, function(er) {
- if (chownErOk(er))
- er = null;
- if (cb)
- cb.apply(this, arguments);
- });
- };
- }
- function chmodFixSync(orig) {
- if (!orig)
- return orig;
- return function(target, mode) {
- try {
- return orig.call(fs2, target, mode);
- } catch (er) {
- if (!chownErOk(er))
- throw er;
- }
- };
- }
- function chownFix(orig) {
- if (!orig)
- return orig;
- return function(target, uid, gid, cb) {
- return orig.call(fs2, target, uid, gid, function(er) {
- if (chownErOk(er))
- er = null;
- if (cb)
- cb.apply(this, arguments);
- });
- };
- }
- function chownFixSync(orig) {
- if (!orig)
- return orig;
- return function(target, uid, gid) {
- try {
- return orig.call(fs2, target, uid, gid);
- } catch (er) {
- if (!chownErOk(er))
- throw er;
- }
- };
- }
- function statFix(orig) {
- if (!orig)
- return orig;
- return function(target, options2, cb) {
- if (typeof options2 === "function") {
- cb = options2;
- options2 = null;
- }
- function callback(er, stats) {
- if (stats) {
- if (stats.uid < 0)
- stats.uid += 4294967296;
- if (stats.gid < 0)
- stats.gid += 4294967296;
- }
- if (cb)
- cb.apply(this, arguments);
- }
- return options2 ? orig.call(fs2, target, options2, callback) : orig.call(fs2, target, callback);
- };
- }
- function statFixSync(orig) {
- if (!orig)
- return orig;
- return function(target, options2) {
- var stats = options2 ? orig.call(fs2, target, options2) : orig.call(fs2, target);
- if (stats) {
- if (stats.uid < 0)
- stats.uid += 4294967296;
- if (stats.gid < 0)
- stats.gid += 4294967296;
- }
- return stats;
- };
- }
- function chownErOk(er) {
- if (!er)
- return true;
- if (er.code === "ENOSYS")
- return true;
- var nonroot = !process.getuid || process.getuid() !== 0;
- if (nonroot) {
- if (er.code === "EINVAL" || er.code === "EPERM")
- return true;
- }
- return false;
- }
- }
-});
-
-// node_modules/graceful-fs/legacy-streams.js
-var require_legacy_streams = __commonJS((exports, module) => {
- var Stream2 = __require("stream").Stream;
- module.exports = legacy;
- function legacy(fs2) {
- return {
- ReadStream,
- WriteStream
- };
- function ReadStream(path8, options2) {
- if (!(this instanceof ReadStream))
- return new ReadStream(path8, options2);
- Stream2.call(this);
- var self2 = this;
- this.path = path8;
- this.fd = null;
- this.readable = true;
- this.paused = false;
- this.flags = "r";
- this.mode = 438;
- this.bufferSize = 64 * 1024;
- options2 = options2 || {};
- var keys2 = Object.keys(options2);
- for (var index2 = 0, length = keys2.length;index2 < length; index2++) {
- var key = keys2[index2];
- this[key] = options2[key];
- }
- if (this.encoding)
- this.setEncoding(this.encoding);
- if (this.start !== undefined) {
- if (typeof this.start !== "number") {
- throw TypeError("start must be a Number");
- }
- if (this.end === undefined) {
- this.end = Infinity;
- } else if (typeof this.end !== "number") {
- throw TypeError("end must be a Number");
- }
- if (this.start > this.end) {
- throw new Error("start must be <= end");
- }
- this.pos = this.start;
- }
- if (this.fd !== null) {
- process.nextTick(function() {
- self2._read();
- });
- return;
- }
- fs2.open(this.path, this.flags, this.mode, function(err, fd) {
- if (err) {
- self2.emit("error", err);
- self2.readable = false;
- return;
- }
- self2.fd = fd;
- self2.emit("open", fd);
- self2._read();
- });
- }
- function WriteStream(path8, options2) {
- if (!(this instanceof WriteStream))
- return new WriteStream(path8, options2);
- Stream2.call(this);
- this.path = path8;
- this.fd = null;
- this.writable = true;
- this.flags = "w";
- this.encoding = "binary";
- this.mode = 438;
- this.bytesWritten = 0;
- options2 = options2 || {};
- var keys2 = Object.keys(options2);
- for (var index2 = 0, length = keys2.length;index2 < length; index2++) {
- var key = keys2[index2];
- this[key] = options2[key];
- }
- if (this.start !== undefined) {
- if (typeof this.start !== "number") {
- throw TypeError("start must be a Number");
- }
- if (this.start < 0) {
- throw new Error("start must be >= zero");
- }
- this.pos = this.start;
- }
- this.busy = false;
- this._queue = [];
- if (this.fd === null) {
- this._open = fs2.open;
- this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
- this.flush();
- }
- }
- }
-});
-
-// node_modules/graceful-fs/clone.js
-var require_clone = __commonJS((exports, module) => {
- module.exports = clone2;
- var getPrototypeOf2 = Object.getPrototypeOf || function(obj) {
- return obj.__proto__;
- };
- function clone2(obj) {
- if (obj === null || typeof obj !== "object")
- return obj;
- if (obj instanceof Object)
- var copy = { __proto__: getPrototypeOf2(obj) };
- else
- var copy = Object.create(null);
- Object.getOwnPropertyNames(obj).forEach(function(key) {
- Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
- });
- return copy;
- }
-});
-
-// node_modules/graceful-fs/graceful-fs.js
-var require_graceful_fs = __commonJS((exports, module) => {
- var fs2 = __require("fs");
- var polyfills3 = require_polyfills();
- var legacy = require_legacy_streams();
- var clone2 = require_clone();
- var util3 = __require("util");
- var gracefulQueue;
- var previousSymbol;
- if (typeof Symbol === "function" && typeof Symbol.for === "function") {
- gracefulQueue = Symbol.for("graceful-fs.queue");
- previousSymbol = Symbol.for("graceful-fs.previous");
- } else {
- gracefulQueue = "___graceful-fs.queue";
- previousSymbol = "___graceful-fs.previous";
- }
- function noop6() {}
- function publishQueue(context, queue2) {
- Object.defineProperty(context, gracefulQueue, {
- get: function() {
- return queue2;
- }
- });
- }
- var debug2 = noop6;
- if (util3.debuglog)
- debug2 = util3.debuglog("gfs4");
- else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
- debug2 = function() {
- var m = util3.format.apply(util3, arguments);
- m = "GFS4: " + m.split(/\n/).join(`
-GFS4: `);
- console.error(m);
- };
- if (!fs2[gracefulQueue]) {
- queue = global[gracefulQueue] || [];
- publishQueue(fs2, queue);
- fs2.close = function(fs$close) {
- function close(fd, cb) {
- return fs$close.call(fs2, fd, function(err) {
- if (!err) {
- resetQueue();
- }
- if (typeof cb === "function")
- cb.apply(this, arguments);
- });
- }
- Object.defineProperty(close, previousSymbol, {
- value: fs$close
- });
- return close;
- }(fs2.close);
- fs2.closeSync = function(fs$closeSync) {
- function closeSync3(fd) {
- fs$closeSync.apply(fs2, arguments);
- resetQueue();
- }
- Object.defineProperty(closeSync3, previousSymbol, {
- value: fs$closeSync
- });
- return closeSync3;
- }(fs2.closeSync);
- if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
- process.on("exit", function() {
- debug2(fs2[gracefulQueue]);
- __require("assert").equal(fs2[gracefulQueue].length, 0);
- });
- }
- }
- var queue;
- if (!global[gracefulQueue]) {
- publishQueue(global, fs2[gracefulQueue]);
- }
- module.exports = patch(clone2(fs2));
- if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs2.__patched) {
- module.exports = patch(fs2);
- fs2.__patched = true;
- }
- function patch(fs3) {
- polyfills3(fs3);
- fs3.gracefulify = patch;
- fs3.createReadStream = createReadStream2;
- fs3.createWriteStream = createWriteStream3;
- var fs$readFile = fs3.readFile;
- fs3.readFile = readFile6;
- function readFile6(path8, options2, cb) {
- if (typeof options2 === "function")
- cb = options2, options2 = null;
- return go$readFile(path8, options2, cb);
- function go$readFile(path9, options3, cb2, startTime) {
- return fs$readFile(path9, options3, function(err) {
- if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
- enqueue([go$readFile, [path9, options3, cb2], err, startTime || Date.now(), Date.now()]);
- else {
- if (typeof cb2 === "function")
- cb2.apply(this, arguments);
- }
- });
- }
- }
- var fs$writeFile = fs3.writeFile;
- fs3.writeFile = writeFile;
- function writeFile(path8, data, options2, cb) {
- if (typeof options2 === "function")
- cb = options2, options2 = null;
- return go$writeFile(path8, data, options2, cb);
- function go$writeFile(path9, data2, options3, cb2, startTime) {
- return fs$writeFile(path9, data2, options3, function(err) {
- if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
- enqueue([go$writeFile, [path9, data2, options3, cb2], err, startTime || Date.now(), Date.now()]);
- else {
- if (typeof cb2 === "function")
- cb2.apply(this, arguments);
- }
- });
- }
- }
- var fs$appendFile = fs3.appendFile;
- if (fs$appendFile)
- fs3.appendFile = appendFile2;
- function appendFile2(path8, data, options2, cb) {
- if (typeof options2 === "function")
- cb = options2, options2 = null;
- return go$appendFile(path8, data, options2, cb);
- function go$appendFile(path9, data2, options3, cb2, startTime) {
- return fs$appendFile(path9, data2, options3, function(err) {
- if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
- enqueue([go$appendFile, [path9, data2, options3, cb2], err, startTime || Date.now(), Date.now()]);
- else {
- if (typeof cb2 === "function")
- cb2.apply(this, arguments);
- }
- });
- }
- }
- var fs$copyFile = fs3.copyFile;
- if (fs$copyFile)
- fs3.copyFile = copyFile;
- function copyFile(src, dest, flags, cb) {
- if (typeof flags === "function") {
- cb = flags;
- flags = 0;
- }
- return go$copyFile(src, dest, flags, cb);
- function go$copyFile(src2, dest2, flags2, cb2, startTime) {
- return fs$copyFile(src2, dest2, flags2, function(err) {
- if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
- enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
- else {
- if (typeof cb2 === "function")
- cb2.apply(this, arguments);
- }
- });
- }
- }
- var fs$readdir = fs3.readdir;
- fs3.readdir = readdir4;
- var noReaddirOptionVersions = /^v[0-5]\./;
- function readdir4(path8, options2, cb) {
- if (typeof options2 === "function")
- cb = options2, options2 = null;
- var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path9, options3, cb2, startTime) {
- return fs$readdir(path9, fs$readdirCallback(path9, options3, cb2, startTime));
- } : function go$readdir2(path9, options3, cb2, startTime) {
- return fs$readdir(path9, options3, fs$readdirCallback(path9, options3, cb2, startTime));
- };
- return go$readdir(path8, options2, cb);
- function fs$readdirCallback(path9, options3, cb2, startTime) {
- return function(err, files) {
- if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
- enqueue([
- go$readdir,
- [path9, options3, cb2],
- err,
- startTime || Date.now(),
- Date.now()
- ]);
- else {
- if (files && files.sort)
- files.sort();
- if (typeof cb2 === "function")
- cb2.call(this, err, files);
- }
- };
- }
- }
- if (process.version.substr(0, 4) === "v0.8") {
- var legStreams = legacy(fs3);
- ReadStream = legStreams.ReadStream;
- WriteStream = legStreams.WriteStream;
- }
- var fs$ReadStream = fs3.ReadStream;
- if (fs$ReadStream) {
- ReadStream.prototype = Object.create(fs$ReadStream.prototype);
- ReadStream.prototype.open = ReadStream$open;
- }
- var fs$WriteStream = fs3.WriteStream;
- if (fs$WriteStream) {
- WriteStream.prototype = Object.create(fs$WriteStream.prototype);
- WriteStream.prototype.open = WriteStream$open;
- }
- Object.defineProperty(fs3, "ReadStream", {
- get: function() {
- return ReadStream;
- },
- set: function(val) {
- ReadStream = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(fs3, "WriteStream", {
- get: function() {
- return WriteStream;
- },
- set: function(val) {
- WriteStream = val;
- },
- enumerable: true,
- configurable: true
- });
- var FileReadStream = ReadStream;
- Object.defineProperty(fs3, "FileReadStream", {
- get: function() {
- return FileReadStream;
- },
- set: function(val) {
- FileReadStream = val;
- },
- enumerable: true,
- configurable: true
- });
- var FileWriteStream = WriteStream;
- Object.defineProperty(fs3, "FileWriteStream", {
- get: function() {
- return FileWriteStream;
- },
- set: function(val) {
- FileWriteStream = val;
- },
- enumerable: true,
- configurable: true
- });
- function ReadStream(path8, options2) {
- if (this instanceof ReadStream)
- return fs$ReadStream.apply(this, arguments), this;
- else
- return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
- }
- function ReadStream$open() {
- var that = this;
- open4(that.path, that.flags, that.mode, function(err, fd) {
- if (err) {
- if (that.autoClose)
- that.destroy();
- that.emit("error", err);
- } else {
- that.fd = fd;
- that.emit("open", fd);
- that.read();
- }
- });
- }
- function WriteStream(path8, options2) {
- if (this instanceof WriteStream)
- return fs$WriteStream.apply(this, arguments), this;
- else
- return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
- }
- function WriteStream$open() {
- var that = this;
- open4(that.path, that.flags, that.mode, function(err, fd) {
- if (err) {
- that.destroy();
- that.emit("error", err);
- } else {
- that.fd = fd;
- that.emit("open", fd);
- }
- });
- }
- function createReadStream2(path8, options2) {
- return new fs3.ReadStream(path8, options2);
- }
- function createWriteStream3(path8, options2) {
- return new fs3.WriteStream(path8, options2);
- }
- var fs$open = fs3.open;
- fs3.open = open4;
- function open4(path8, flags, mode, cb) {
- if (typeof mode === "function")
- cb = mode, mode = null;
- return go$open(path8, flags, mode, cb);
- function go$open(path9, flags2, mode2, cb2, startTime) {
- return fs$open(path9, flags2, mode2, function(err, fd) {
- if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
- enqueue([go$open, [path9, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
- else {
- if (typeof cb2 === "function")
- cb2.apply(this, arguments);
- }
- });
- }
- }
- return fs3;
- }
- function enqueue(elem) {
- debug2("ENQUEUE", elem[0].name, elem[1]);
- fs2[gracefulQueue].push(elem);
- retry();
- }
- var retryTimer;
- function resetQueue() {
- var now = Date.now();
- for (var i2 = 0;i2 < fs2[gracefulQueue].length; ++i2) {
- if (fs2[gracefulQueue][i2].length > 2) {
- fs2[gracefulQueue][i2][3] = now;
- fs2[gracefulQueue][i2][4] = now;
- }
- }
- retry();
- }
- function retry() {
- clearTimeout(retryTimer);
- retryTimer = undefined;
- if (fs2[gracefulQueue].length === 0)
- return;
- var elem = fs2[gracefulQueue].shift();
- var fn = elem[0];
- var args = elem[1];
- var err = elem[2];
- var startTime = elem[3];
- var lastTime = elem[4];
- if (startTime === undefined) {
- debug2("RETRY", fn.name, args);
- fn.apply(null, args);
- } else if (Date.now() - startTime >= 60000) {
- debug2("TIMEOUT", fn.name, args);
- var cb = args.pop();
- if (typeof cb === "function")
- cb.call(null, err);
- } else {
- var sinceAttempt = Date.now() - lastTime;
- var sinceStart = Math.max(lastTime - startTime, 1);
- var desiredDelay = Math.min(sinceStart * 1.2, 100);
- if (sinceAttempt >= desiredDelay) {
- debug2("RETRY", fn.name, args);
- fn.apply(null, args.concat([startTime]));
- } else {
- fs2[gracefulQueue].push(elem);
- }
- }
- if (retryTimer === undefined) {
- retryTimer = setTimeout(retry, 0);
- }
- }
-});
-
-// node_modules/retry/lib/retry_operation.js
-var require_retry_operation = __commonJS((exports, module) => {
- function RetryOperation(timeouts, options2) {
- if (typeof options2 === "boolean") {
- options2 = { forever: options2 };
- }
- this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
- this._timeouts = timeouts;
- this._options = options2 || {};
- this._maxRetryTime = options2 && options2.maxRetryTime || Infinity;
- this._fn = null;
- this._errors = [];
- this._attempts = 1;
- this._operationTimeout = null;
- this._operationTimeoutCb = null;
- this._timeout = null;
- this._operationStart = 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;
- };
- RetryOperation.prototype.stop = function() {
- if (this._timeout) {
- clearTimeout(this._timeout);
- }
- 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.unshift(new Error("RetryOperation timeout occurred"));
- return false;
- }
- this._errors.push(err);
- var timeout = this._timeouts.shift();
- if (timeout === undefined) {
- if (this._cachedTimeouts) {
- this._errors.splice(this._errors.length - 1, this._errors.length);
- this._timeouts = this._cachedTimeouts.slice(0);
- timeout = this._timeouts.shift();
- } else {
- return false;
- }
- }
- var self2 = this;
- var timer = setTimeout(function() {
- self2._attempts++;
- if (self2._operationTimeoutCb) {
- self2._timeout = setTimeout(function() {
- self2._operationTimeoutCb(self2._attempts);
- }, self2._operationTimeout);
- if (self2._options.unref) {
- self2._timeout.unref();
- }
- }
- self2._fn(self2._attempts);
- }, timeout);
- if (this._options.unref) {
- timer.unref();
- }
- return true;
- };
- RetryOperation.prototype.attempt = function(fn, timeoutOps) {
- this._fn = fn;
- if (timeoutOps) {
- if (timeoutOps.timeout) {
- this._operationTimeout = timeoutOps.timeout;
- }
- if (timeoutOps.cb) {
- this._operationTimeoutCb = timeoutOps.cb;
- }
- }
- var self2 = this;
- if (this._operationTimeoutCb) {
- this._timeout = setTimeout(function() {
- self2._operationTimeoutCb();
- }, self2._operationTimeout);
- }
- this._operationStart = new Date().getTime();
- this._fn(this._attempts);
- };
- RetryOperation.prototype.try = function(fn) {
- console.log("Using RetryOperation.try() is deprecated");
- this.attempt(fn);
- };
- RetryOperation.prototype.start = function(fn) {
- console.log("Using RetryOperation.start() is deprecated");
- this.attempt(fn);
- };
- 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 i2 = 0;i2 < this._errors.length; i2++) {
- var error = this._errors[i2];
- var message = error.message;
- var count2 = (counts[message] || 0) + 1;
- counts[message] = count2;
- if (count2 >= mainErrorCount) {
- mainError = error;
- mainErrorCount = count2;
- }
- }
- return mainError;
- };
-});
-
-// node_modules/retry/lib/retry.js
-var require_retry = __commonJS((exports) => {
- var RetryOperation = require_retry_operation();
- exports.operation = function(options2) {
- var timeouts = exports.timeouts(options2);
- return new RetryOperation(timeouts, {
- forever: options2 && options2.forever,
- unref: options2 && options2.unref,
- maxRetryTime: options2 && options2.maxRetryTime
- });
- };
- exports.timeouts = function(options2) {
- if (options2 instanceof Array) {
- return [].concat(options2);
- }
- var opts = {
- retries: 10,
- factor: 2,
- minTimeout: 1 * 1000,
- maxTimeout: Infinity,
- randomize: false
- };
- for (var key in options2) {
- opts[key] = options2[key];
- }
- if (opts.minTimeout > opts.maxTimeout) {
- throw new Error("minTimeout is greater than maxTimeout");
- }
- var timeouts = [];
- for (var i2 = 0;i2 < opts.retries; i2++) {
- timeouts.push(this.createTimeout(i2, opts));
- }
- if (options2 && options2.forever && !timeouts.length) {
- timeouts.push(this.createTimeout(i2, opts));
- }
- timeouts.sort(function(a2, b) {
- return a2 - b;
- });
- return timeouts;
- };
- exports.createTimeout = function(attempt, opts) {
- var random = opts.randomize ? Math.random() + 1 : 1;
- var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
- timeout = Math.min(timeout, opts.maxTimeout);
- return timeout;
- };
- exports.wrap = function(obj, options2, methods) {
- if (options2 instanceof Array) {
- methods = options2;
- options2 = null;
- }
- if (!methods) {
- methods = [];
- for (var key in obj) {
- if (typeof obj[key] === "function") {
- methods.push(key);
- }
- }
- }
- for (var i2 = 0;i2 < methods.length; i2++) {
- var method = methods[i2];
- var original = obj[method];
- obj[method] = function retryWrapper(original2) {
- var op = exports.operation(options2);
- 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() {
- original2.apply(obj, args);
- });
- }.bind(obj, original);
- obj[method].options = options2;
- }
- };
-});
-
-// node_modules/proper-lockfile/node_modules/signal-exit/signals.js
-var require_signals = __commonJS((exports, module) => {
- module.exports = [
- "SIGABRT",
- "SIGALRM",
- "SIGHUP",
- "SIGINT",
- "SIGTERM"
- ];
- if (process.platform !== "win32") {
- module.exports.push("SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
- }
- if (process.platform === "linux") {
- module.exports.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT", "SIGUNUSED");
- }
-});
-
-// node_modules/proper-lockfile/node_modules/signal-exit/index.js
-var require_signal_exit = __commonJS((exports, module) => {
- var process12 = global.process;
- var processOk2 = function(process13) {
- return process13 && typeof process13 === "object" && typeof process13.removeListener === "function" && typeof process13.emit === "function" && typeof process13.reallyExit === "function" && typeof process13.listeners === "function" && typeof process13.kill === "function" && typeof process13.pid === "number" && typeof process13.on === "function";
- };
- if (!processOk2(process12)) {
- module.exports = function() {
- return function() {};
- };
- } else {
- assert = __require("assert");
- signals2 = require_signals();
- isWin = /^win/i.test(process12.platform);
- EE = __require("events");
- if (typeof EE !== "function") {
- EE = EE.EventEmitter;
- }
- if (process12.__signal_exit_emitter__) {
- emitter = process12.__signal_exit_emitter__;
- } else {
- emitter = process12.__signal_exit_emitter__ = new EE;
- emitter.count = 0;
- emitter.emitted = {};
- }
- if (!emitter.infinite) {
- emitter.setMaxListeners(Infinity);
- emitter.infinite = true;
- }
- module.exports = function(cb, opts) {
- if (!processOk2(global.process)) {
- return function() {};
- }
- assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
- if (loaded === false) {
- load2();
- }
- var ev = "exit";
- if (opts && opts.alwaysLast) {
- ev = "afterexit";
- }
- var remove = function() {
- emitter.removeListener(ev, cb);
- if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
- unload2();
- }
- };
- emitter.on(ev, cb);
- return remove;
- };
- unload2 = function unload3() {
- if (!loaded || !processOk2(global.process)) {
- return;
- }
- loaded = false;
- signals2.forEach(function(sig) {
- try {
- process12.removeListener(sig, sigListeners[sig]);
- } catch (er) {}
- });
- process12.emit = originalProcessEmit;
- process12.reallyExit = originalProcessReallyExit;
- emitter.count -= 1;
- };
- module.exports.unload = unload2;
- emit = function emit2(event, code, signal) {
- if (emitter.emitted[event]) {
- return;
- }
- emitter.emitted[event] = true;
- emitter.emit(event, code, signal);
- };
- sigListeners = {};
- signals2.forEach(function(sig) {
- sigListeners[sig] = function listener() {
- if (!processOk2(global.process)) {
- return;
- }
- var listeners = process12.listeners(sig);
- if (listeners.length === emitter.count) {
- unload2();
- emit("exit", null, sig);
- emit("afterexit", null, sig);
- if (isWin && sig === "SIGHUP") {
- sig = "SIGINT";
- }
- process12.kill(process12.pid, sig);
- }
- };
- });
- module.exports.signals = function() {
- return signals2;
- };
- loaded = false;
- load2 = function load3() {
- if (loaded || !processOk2(global.process)) {
- return;
- }
- loaded = true;
- emitter.count += 1;
- signals2 = signals2.filter(function(sig) {
- try {
- process12.on(sig, sigListeners[sig]);
- return true;
- } catch (er) {
- return false;
- }
- });
- process12.emit = processEmit;
- process12.reallyExit = processReallyExit;
- };
- module.exports.load = load2;
- originalProcessReallyExit = process12.reallyExit;
- processReallyExit = function processReallyExit2(code) {
- if (!processOk2(global.process)) {
- return;
- }
- process12.exitCode = code || 0;
- emit("exit", process12.exitCode, null);
- emit("afterexit", process12.exitCode, null);
- originalProcessReallyExit.call(process12, process12.exitCode);
- };
- originalProcessEmit = process12.emit;
- processEmit = function processEmit2(ev, arg) {
- if (ev === "exit" && processOk2(global.process)) {
- if (arg !== undefined) {
- process12.exitCode = arg;
- }
- var ret = originalProcessEmit.apply(this, arguments);
- emit("exit", process12.exitCode, null);
- emit("afterexit", process12.exitCode, null);
- return ret;
- } else {
- return originalProcessEmit.apply(this, arguments);
- }
- };
- }
- var assert;
- var signals2;
- var isWin;
- var EE;
- var emitter;
- var unload2;
- var emit;
- var sigListeners;
- var loaded;
- var load2;
- var originalProcessReallyExit;
- var processReallyExit;
- var originalProcessEmit;
- var processEmit;
-});
-
-// node_modules/proper-lockfile/lib/mtime-precision.js
-var require_mtime_precision = __commonJS((exports, module) => {
- var cacheSymbol = Symbol();
- function probe(file, fs2, callback) {
- const cachedPrecision = fs2[cacheSymbol];
- if (cachedPrecision) {
- return fs2.stat(file, (err, stat6) => {
- if (err) {
- return callback(err);
- }
- callback(null, stat6.mtime, cachedPrecision);
- });
- }
- const mtime = new Date(Math.ceil(Date.now() / 1000) * 1000 + 5);
- fs2.utimes(file, mtime, mtime, (err) => {
- if (err) {
- return callback(err);
- }
- fs2.stat(file, (err2, stat6) => {
- if (err2) {
- return callback(err2);
- }
- const precision = stat6.mtime.getTime() % 1000 === 0 ? "s" : "ms";
- Object.defineProperty(fs2, cacheSymbol, { value: precision });
- callback(null, stat6.mtime, precision);
- });
- });
- }
- function getMtime(precision) {
- let now = Date.now();
- if (precision === "s") {
- now = Math.ceil(now / 1000) * 1000;
- }
- return new Date(now);
- }
- exports.probe = probe;
- exports.getMtime = getMtime;
-});
-
-// node_modules/proper-lockfile/lib/lockfile.js
-var require_lockfile = __commonJS((exports, module) => {
- var path8 = __require("path");
- var fs2 = require_graceful_fs();
- var retry = require_retry();
- var onExit2 = require_signal_exit();
- var mtimePrecision = require_mtime_precision();
- var locks = {};
- function getLockFile(file, options2) {
- return options2.lockfilePath || `${file}.lock`;
- }
- function resolveCanonicalPath(file, options2, callback) {
- if (!options2.realpath) {
- return callback(null, path8.resolve(file));
- }
- options2.fs.realpath(file, callback);
- }
- function acquireLock(file, options2, callback) {
- const lockfilePath = getLockFile(file, options2);
- options2.fs.mkdir(lockfilePath, (err) => {
- if (!err) {
- return mtimePrecision.probe(lockfilePath, options2.fs, (err2, mtime, mtimePrecision2) => {
- if (err2) {
- options2.fs.rmdir(lockfilePath, () => {});
- return callback(err2);
- }
- callback(null, mtime, mtimePrecision2);
- });
- }
- if (err.code !== "EEXIST") {
- return callback(err);
- }
- if (options2.stale <= 0) {
- return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
- }
- options2.fs.stat(lockfilePath, (err2, stat6) => {
- if (err2) {
- if (err2.code === "ENOENT") {
- return acquireLock(file, { ...options2, stale: 0 }, callback);
- }
- return callback(err2);
- }
- if (!isLockStale(stat6, options2)) {
- return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
- }
- removeLock(file, options2, (err3) => {
- if (err3) {
- return callback(err3);
- }
- acquireLock(file, { ...options2, stale: 0 }, callback);
- });
- });
- });
- }
- function isLockStale(stat6, options2) {
- return stat6.mtime.getTime() < Date.now() - options2.stale;
- }
- function removeLock(file, options2, callback) {
- options2.fs.rmdir(getLockFile(file, options2), (err) => {
- if (err && err.code !== "ENOENT") {
- return callback(err);
- }
- callback();
- });
- }
- function updateLock(file, options2) {
- const lock2 = locks[file];
- if (lock2.updateTimeout) {
- return;
- }
- lock2.updateDelay = lock2.updateDelay || options2.update;
- lock2.updateTimeout = setTimeout(() => {
- lock2.updateTimeout = null;
- options2.fs.stat(lock2.lockfilePath, (err, stat6) => {
- const isOverThreshold = lock2.lastUpdate + options2.stale < Date.now();
- if (err) {
- if (err.code === "ENOENT" || isOverThreshold) {
- return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" }));
- }
- lock2.updateDelay = 1000;
- return updateLock(file, options2);
- }
- const isMtimeOurs = lock2.mtime.getTime() === stat6.mtime.getTime();
- if (!isMtimeOurs) {
- return setLockAsCompromised(file, lock2, Object.assign(new Error("Unable to update lock within the stale threshold"), { code: "ECOMPROMISED" }));
- }
- const mtime = mtimePrecision.getMtime(lock2.mtimePrecision);
- options2.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => {
- const isOverThreshold2 = lock2.lastUpdate + options2.stale < Date.now();
- if (lock2.released) {
- return;
- }
- if (err2) {
- if (err2.code === "ENOENT" || isOverThreshold2) {
- return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" }));
- }
- lock2.updateDelay = 1000;
- return updateLock(file, options2);
- }
- lock2.mtime = mtime;
- lock2.lastUpdate = Date.now();
- lock2.updateDelay = null;
- updateLock(file, options2);
- });
- });
- }, lock2.updateDelay);
- if (lock2.updateTimeout.unref) {
- lock2.updateTimeout.unref();
- }
- }
- function setLockAsCompromised(file, lock2, err) {
- lock2.released = true;
- if (lock2.updateTimeout) {
- clearTimeout(lock2.updateTimeout);
- }
- if (locks[file] === lock2) {
- delete locks[file];
- }
- lock2.options.onCompromised(err);
- }
- function lock(file, options2, callback) {
- options2 = {
- stale: 1e4,
- update: null,
- realpath: true,
- retries: 0,
- fs: fs2,
- onCompromised: (err) => {
- throw err;
- },
- ...options2
- };
- options2.retries = options2.retries || 0;
- options2.retries = typeof options2.retries === "number" ? { retries: options2.retries } : options2.retries;
- options2.stale = Math.max(options2.stale || 0, 2000);
- options2.update = options2.update == null ? options2.stale / 2 : options2.update || 0;
- options2.update = Math.max(Math.min(options2.update, options2.stale / 2), 1000);
- resolveCanonicalPath(file, options2, (err, file2) => {
- if (err) {
- return callback(err);
- }
- const operation = retry.operation(options2.retries);
- operation.attempt(() => {
- acquireLock(file2, options2, (err2, mtime, mtimePrecision2) => {
- if (operation.retry(err2)) {
- return;
- }
- if (err2) {
- return callback(operation.mainError());
- }
- const lock2 = locks[file2] = {
- lockfilePath: getLockFile(file2, options2),
- mtime,
- mtimePrecision: mtimePrecision2,
- options: options2,
- lastUpdate: Date.now()
- };
- updateLock(file2, options2);
- callback(null, (releasedCallback) => {
- if (lock2.released) {
- return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
- }
- unlock(file2, { ...options2, realpath: false }, releasedCallback);
- });
- });
- });
- });
- }
- function unlock(file, options2, callback) {
- options2 = {
- fs: fs2,
- realpath: true,
- ...options2
- };
- resolveCanonicalPath(file, options2, (err, file2) => {
- if (err) {
- return callback(err);
- }
- const lock2 = locks[file2];
- if (!lock2) {
- return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
- }
- lock2.updateTimeout && clearTimeout(lock2.updateTimeout);
- lock2.released = true;
- delete locks[file2];
- removeLock(file2, options2, callback);
- });
- }
- function check(file, options2, callback) {
- options2 = {
- stale: 1e4,
- realpath: true,
- fs: fs2,
- ...options2
- };
- options2.stale = Math.max(options2.stale || 0, 2000);
- resolveCanonicalPath(file, options2, (err, file2) => {
- if (err) {
- return callback(err);
- }
- options2.fs.stat(getLockFile(file2, options2), (err2, stat6) => {
- if (err2) {
- return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
- }
- return callback(null, !isLockStale(stat6, options2));
- });
- });
- }
- function getLocks() {
- return locks;
- }
- onExit2(() => {
- for (const file in locks) {
- const options2 = locks[file].options;
- try {
- options2.fs.rmdirSync(getLockFile(file, options2));
- } catch (e) {}
- }
- });
- exports.lock = lock;
- exports.unlock = unlock;
- exports.check = check;
- exports.getLocks = getLocks;
-});
-
-// node_modules/proper-lockfile/lib/adapter.js
-var require_adapter = __commonJS((exports, module) => {
- var fs2 = require_graceful_fs();
- function createSyncFs(fs3) {
- const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
- const newFs = { ...fs3 };
- methods.forEach((method) => {
- newFs[method] = (...args) => {
- const callback = args.pop();
- let ret;
- try {
- ret = fs3[`${method}Sync`](...args);
- } catch (err) {
- return callback(err);
- }
- callback(null, ret);
- };
- });
- return newFs;
- }
- function toPromise(method) {
- return (...args) => new Promise((resolve7, reject) => {
- args.push((err, result) => {
- if (err) {
- reject(err);
- } else {
- resolve7(result);
- }
- });
- method(...args);
- });
- }
- function toSync(method) {
- return (...args) => {
- let err;
- let result;
- args.push((_err, _result) => {
- err = _err;
- result = _result;
- });
- method(...args);
- if (err) {
- throw err;
- }
- return result;
- };
- }
- function toSyncOptions(options2) {
- options2 = { ...options2 };
- options2.fs = createSyncFs(options2.fs || fs2);
- if (typeof options2.retries === "number" && options2.retries > 0 || options2.retries && typeof options2.retries.retries === "number" && options2.retries.retries > 0) {
- throw Object.assign(new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
- }
- return options2;
- }
- module.exports = {
- toPromise,
- toSync,
- toSyncOptions
- };
-});
-
-// node_modules/proper-lockfile/index.js
-var require_proper_lockfile = __commonJS((exports, module) => {
- var lockfile = require_lockfile();
- var { toPromise, toSync, toSyncOptions } = require_adapter();
- async function lock(file, options2) {
- const release = await toPromise(lockfile.lock)(file, options2);
- return toPromise(release);
- }
- function lockSync(file, options2) {
- const release = toSync(lockfile.lock)(file, toSyncOptions(options2));
- return toSync(release);
- }
- function unlock(file, options2) {
- return toPromise(lockfile.unlock)(file, options2);
- }
- function unlockSync(file, options2) {
- return toSync(lockfile.unlock)(file, toSyncOptions(options2));
- }
- function check(file, options2) {
- return toPromise(lockfile.check)(file, options2);
- }
- function checkSync(file, options2) {
- return toSync(lockfile.check)(file, toSyncOptions(options2));
- }
- module.exports = lock;
- module.exports.lock = lock;
- module.exports.unlock = unlock;
- module.exports.lockSync = lockSync;
- module.exports.unlockSync = unlockSync;
- module.exports.check = check;
- module.exports.checkSync = checkSync;
-});
-
-// src/utils/lockfile.ts
-function getLockfile() {
- if (!_lockfile) {
- _lockfile = require_proper_lockfile();
- }
- return _lockfile;
-}
-function lock(file, options2) {
- return getLockfile().lock(file, options2);
-}
-function lockSync(file, options2) {
- return getLockfile().lockSync(file, options2);
-}
-function unlock(file, options2) {
- return getLockfile().unlock(file, options2);
-}
-function check(file, options2) {
- return getLockfile().check(file, options2);
-}
-var _lockfile;
-
-// src/utils/settings/managedPath.ts
-import { join as join15 } from "path";
-var getManagedFilePath, getManagedSettingsDropInDir;
-var init_managedPath = __esm(() => {
- init_memoize();
- init_platform2();
- getManagedFilePath = memoize_default(function() {
- if (process.env.USER_TYPE === "ant" && process.env.CLAUDE_CODE_MANAGED_SETTINGS_PATH) {
- return process.env.CLAUDE_CODE_MANAGED_SETTINGS_PATH;
- }
- switch (getPlatform()) {
- case "macos":
- return "/Library/Application Support/ClaudeCode";
- case "windows":
- return "C:\\Program Files\\ClaudeCode";
- default:
- return "/etc/claude-code";
- }
- });
- getManagedSettingsDropInDir = memoize_default(function() {
- return join15(getManagedFilePath(), "managed-settings.d");
- });
-});
-
-// src/utils/configConstants.ts
-var NOTIFICATION_CHANNELS, EDITOR_MODES, TEAMMATE_MODES;
-var init_configConstants = __esm(() => {
- NOTIFICATION_CHANNELS = [
- "auto",
- "iterm2",
- "iterm2_with_bell",
- "terminal_bell",
- "kitty",
- "ghostty",
- "notifications_disabled"
- ];
- EDITOR_MODES = ["normal", "vim"];
- TEAMMATE_MODES = ["auto", "tmux", "in-process"];
-});
-
-// src/utils/config.ts
-import { randomBytes } from "crypto";
-import { unwatchFile as unwatchFile2, watchFile as watchFile2 } from "fs";
-import { basename as basename4, dirname as dirname9, join as join16, resolve as resolve7 } from "path";
-function createDefaultGlobalConfig() {
- return {
- numStartups: 0,
- installMethod: undefined,
- autoUpdates: undefined,
- theme: "dark",
- preferredNotifChannel: "auto",
- verbose: false,
- editorMode: "normal",
- autoCompactEnabled: true,
- showTurnDuration: true,
- hasSeenTasksHint: false,
- hasUsedStash: false,
- hasUsedBackgroundTask: false,
- queuedCommandUpHintCount: 0,
- diffTool: "auto",
- customApiKeyResponses: {
- approved: [],
- rejected: []
- },
- env: {},
- tipsHistory: {},
- memoryUsageCount: 0,
- promptQueueUseCount: 0,
- btwUseCount: 0,
- todoFeatureEnabled: true,
- showExpandedTodos: false,
- messageIdleNotifThresholdMs: 60000,
- autoConnectIde: false,
- autoInstallIdeExtension: true,
- fileCheckpointingEnabled: true,
- terminalProgressBarEnabled: true,
- cachedStatsigGates: {},
- cachedDynamicConfigs: {},
- cachedGrowthBookFeatures: {},
- respectGitignore: true,
- copyFullResponse: false
- };
-}
-function checkHasTrustDialogAccepted() {
- return _trustAccepted ||= computeTrustDialogAccepted();
-}
-function computeTrustDialogAccepted() {
- if (getSessionTrustAccepted()) {
- return true;
- }
- const config = getGlobalConfig();
- const projectPath = getProjectPathForConfig();
- const projectConfig = config.projects?.[projectPath];
- if (projectConfig?.hasTrustDialogAccepted) {
- return true;
- }
- let currentPath = normalizePathForConfigKey(getCwd());
- while (true) {
- const pathConfig = config.projects?.[currentPath];
- if (pathConfig?.hasTrustDialogAccepted) {
- return true;
- }
- const parentPath = normalizePathForConfigKey(resolve7(currentPath, ".."));
- if (parentPath === currentPath) {
- break;
- }
- currentPath = parentPath;
- }
- return false;
-}
-function wouldLoseAuthState(fresh) {
- const cached = globalConfigCache.config;
- if (!cached)
- return false;
- const lostOauth = cached.oauthAccount !== undefined && fresh.oauthAccount === undefined;
- const lostOnboarding = cached.hasCompletedOnboarding === true && fresh.hasCompletedOnboarding !== true;
- return lostOauth || lostOnboarding;
-}
-function saveGlobalConfig(updater) {
- if (false) {}
- let written = null;
- try {
- const didWrite = saveConfigWithLock(getGlobalClaudeFile(), createDefaultGlobalConfig, (current) => {
- const config = updater(current);
- if (config === current) {
- return current;
- }
- written = {
- ...config,
- projects: removeProjectHistory(current.projects)
- };
- return written;
- });
- if (didWrite && written) {
- writeThroughGlobalConfigCache(written);
- }
- } catch (error) {
- logForDebugging(`Failed to save config with lock: ${error}`, {
- level: "error"
- });
- const currentConfig = getConfig(getGlobalClaudeFile(), createDefaultGlobalConfig);
- if (wouldLoseAuthState(currentConfig)) {
- logForDebugging("saveGlobalConfig fallback: re-read config is missing auth that cache has; refusing to write. See GH #3117.", { level: "error" });
- logEvent("tengu_config_auth_loss_prevented", {});
- return;
- }
- const config = updater(currentConfig);
- if (config === currentConfig) {
- return;
- }
- written = {
- ...config,
- projects: removeProjectHistory(currentConfig.projects)
- };
- saveConfig(getGlobalClaudeFile(), written, DEFAULT_GLOBAL_CONFIG);
- writeThroughGlobalConfigCache(written);
- }
-}
-function reportConfigCacheStats() {
- const total = configCacheHits + configCacheMisses;
- if (total > 0) {
- logEvent("tengu_config_cache_stats", {
- cache_hits: configCacheHits,
- cache_misses: configCacheMisses,
- hit_rate: configCacheHits / total
- });
- }
- configCacheHits = 0;
- configCacheMisses = 0;
-}
-function migrateConfigFields(config) {
- if (config.installMethod !== undefined) {
- return config;
- }
- const legacy = config;
- let installMethod = "unknown";
- let autoUpdates = config.autoUpdates ?? true;
- switch (legacy.autoUpdaterStatus) {
- case "migrated":
- installMethod = "local";
- break;
- case "installed":
- installMethod = "native";
- break;
- case "disabled":
- autoUpdates = false;
- break;
- case "enabled":
- case "no_permissions":
- case "not_configured":
- installMethod = "global";
- break;
- case undefined:
- break;
- }
- return {
- ...config,
- installMethod,
- autoUpdates
- };
-}
-function removeProjectHistory(projects) {
- if (!projects) {
- return projects;
- }
- const cleanedProjects = {};
- let needsCleaning = false;
- for (const [path8, projectConfig] of Object.entries(projects)) {
- const legacy = projectConfig;
- if (legacy.history !== undefined) {
- needsCleaning = true;
- const { history, ...cleanedConfig } = legacy;
- cleanedProjects[path8] = cleanedConfig;
- } else {
- cleanedProjects[path8] = projectConfig;
- }
- }
- return needsCleaning ? cleanedProjects : projects;
-}
-function startGlobalConfigFreshnessWatcher() {
- if (freshnessWatcherStarted || false)
- return;
- freshnessWatcherStarted = true;
- const file = getGlobalClaudeFile();
- watchFile2(file, { interval: CONFIG_FRESHNESS_POLL_MS, persistent: false }, (curr) => {
- if (curr.mtimeMs <= globalConfigCache.mtime)
- return;
- getFsImplementation().readFile(file, { encoding: "utf-8" }).then((content) => {
- if (curr.mtimeMs <= globalConfigCache.mtime)
- return;
- const parsed = safeParseJSON(stripBOM2(content));
- if (parsed === null || typeof parsed !== "object")
- return;
- globalConfigCache = {
- config: migrateConfigFields({
- ...createDefaultGlobalConfig(),
- ...parsed
- }),
- mtime: curr.mtimeMs
- };
- lastReadFileStats = { mtime: curr.mtimeMs, size: curr.size };
- }).catch(() => {});
- });
- registerCleanup(async () => {
- unwatchFile2(file);
- freshnessWatcherStarted = false;
- });
-}
-function writeThroughGlobalConfigCache(config) {
- globalConfigCache = { config, mtime: Date.now() };
- lastReadFileStats = null;
-}
-function getGlobalConfig() {
- if (false) {}
- if (globalConfigCache.config) {
- configCacheHits++;
- return globalConfigCache.config;
- }
- configCacheMisses++;
- try {
- let stats = null;
- try {
- stats = getFsImplementation().statSync(getGlobalClaudeFile());
- } catch {}
- const config = migrateConfigFields(getConfig(getGlobalClaudeFile(), createDefaultGlobalConfig));
- globalConfigCache = {
- config,
- mtime: stats?.mtimeMs ?? Date.now()
- };
- lastReadFileStats = stats ? { mtime: stats.mtimeMs, size: stats.size } : null;
- startGlobalConfigFreshnessWatcher();
- return config;
- } catch {
- return migrateConfigFields(getConfig(getGlobalClaudeFile(), createDefaultGlobalConfig));
- }
-}
-function getRemoteControlAtStartup() {
- const explicit = getGlobalConfig().remoteControlAtStartup;
- if (explicit !== undefined)
- return explicit;
- if (false) {}
- return false;
-}
-function getCustomApiKeyStatus(truncatedApiKey) {
- const config = getGlobalConfig();
- if (config.customApiKeyResponses?.approved?.includes(truncatedApiKey)) {
- return "approved";
- }
- if (config.customApiKeyResponses?.rejected?.includes(truncatedApiKey)) {
- return "rejected";
- }
- return "new";
-}
-function saveConfig(file, config, defaultConfig) {
- const dir = dirname9(file);
- const fs2 = getFsImplementation();
- fs2.mkdirSync(dir);
- const filteredConfig = pickBy_default(config, (value, key) => jsonStringify(value) !== jsonStringify(defaultConfig[key]));
- writeFileSyncAndFlush_DEPRECATED(file, jsonStringify(filteredConfig, null, 2), {
- encoding: "utf-8",
- mode: 384
- });
- if (file === getGlobalClaudeFile()) {
- globalConfigWriteCount++;
- }
-}
-function saveConfigWithLock(file, createDefault, mergeFn) {
- const defaultConfig = createDefault();
- const dir = dirname9(file);
- const fs2 = getFsImplementation();
- fs2.mkdirSync(dir);
- let release;
- try {
- const lockFilePath = `${file}.lock`;
- const startTime = Date.now();
- release = lockSync(file, {
- lockfilePath: lockFilePath,
- onCompromised: (err) => {
- logForDebugging(`Config lock compromised: ${err}`, { level: "error" });
- }
- });
- const lockTime = Date.now() - startTime;
- if (lockTime > 100) {
- logForDebugging("Lock acquisition took longer than expected - another Claude instance may be running");
- logEvent("tengu_config_lock_contention", {
- lock_time_ms: lockTime
- });
- }
- if (lastReadFileStats && file === getGlobalClaudeFile()) {
- try {
- const currentStats = fs2.statSync(file);
- if (currentStats.mtimeMs !== lastReadFileStats.mtime || currentStats.size !== lastReadFileStats.size) {
- logEvent("tengu_config_stale_write", {
- read_mtime: lastReadFileStats.mtime,
- write_mtime: currentStats.mtimeMs,
- read_size: lastReadFileStats.size,
- write_size: currentStats.size
- });
- }
- } catch (e) {
- const code = getErrnoCode(e);
- if (code !== "ENOENT") {
- throw e;
- }
- }
- }
- const currentConfig = getConfig(file, createDefault);
- if (file === getGlobalClaudeFile() && wouldLoseAuthState(currentConfig)) {
- logForDebugging("saveConfigWithLock: re-read config is missing auth that cache has; refusing to write to avoid wiping ~/.claude.json. See GH #3117.", { level: "error" });
- logEvent("tengu_config_auth_loss_prevented", {});
- return false;
- }
- const mergedConfig = mergeFn(currentConfig);
- if (mergedConfig === currentConfig) {
- return false;
- }
- const filteredConfig = pickBy_default(mergedConfig, (value, key) => jsonStringify(value) !== jsonStringify(defaultConfig[key]));
- try {
- const fileBase = basename4(file);
- const backupDir = getConfigBackupDir();
- try {
- fs2.mkdirSync(backupDir);
- } catch (mkdirErr) {
- const mkdirCode = getErrnoCode(mkdirErr);
- if (mkdirCode !== "EEXIST") {
- throw mkdirErr;
- }
- }
- const MIN_BACKUP_INTERVAL_MS = 60000;
- const existingBackups = fs2.readdirStringSync(backupDir).filter((f) => f.startsWith(`${fileBase}.backup.`)).sort().reverse();
- const mostRecentBackup = existingBackups[0];
- const mostRecentTimestamp = mostRecentBackup ? Number(mostRecentBackup.split(".backup.").pop()) : 0;
- const shouldCreateBackup = Number.isNaN(mostRecentTimestamp) || Date.now() - mostRecentTimestamp >= MIN_BACKUP_INTERVAL_MS;
- if (shouldCreateBackup) {
- const backupPath = join16(backupDir, `${fileBase}.backup.${Date.now()}`);
- fs2.copyFileSync(file, backupPath);
- }
- const MAX_BACKUPS = 5;
- const backupsForCleanup = shouldCreateBackup ? fs2.readdirStringSync(backupDir).filter((f) => f.startsWith(`${fileBase}.backup.`)).sort().reverse() : existingBackups;
- for (const oldBackup of backupsForCleanup.slice(MAX_BACKUPS)) {
- try {
- fs2.unlinkSync(join16(backupDir, oldBackup));
- } catch {}
- }
- } catch (e) {
- const code = getErrnoCode(e);
- if (code !== "ENOENT") {
- logForDebugging(`Failed to backup config: ${e}`, {
- level: "error"
- });
- }
- }
- writeFileSyncAndFlush_DEPRECATED(file, jsonStringify(filteredConfig, null, 2), {
- encoding: "utf-8",
- mode: 384
- });
- if (file === getGlobalClaudeFile()) {
- globalConfigWriteCount++;
- }
- return true;
- } finally {
- if (release) {
- release();
- }
- }
-}
-function enableConfigs() {
- if (configReadingAllowed) {
- return;
- }
- const startTime = Date.now();
- logForDiagnosticsNoPII("info", "enable_configs_started");
- configReadingAllowed = true;
- getConfig(getGlobalClaudeFile(), createDefaultGlobalConfig, true);
- logForDiagnosticsNoPII("info", "enable_configs_completed", {
- duration_ms: Date.now() - startTime
- });
-}
-function getConfigBackupDir() {
- return join16(getClaudeConfigHomeDir(), "backups");
-}
-function findMostRecentBackup(file) {
- const fs2 = getFsImplementation();
- const fileBase = basename4(file);
- const backupDir = getConfigBackupDir();
- try {
- const backups = fs2.readdirStringSync(backupDir).filter((f) => f.startsWith(`${fileBase}.backup.`)).sort();
- const mostRecent = backups.at(-1);
- if (mostRecent) {
- return join16(backupDir, mostRecent);
- }
- } catch {}
- const fileDir = dirname9(file);
- try {
- const backups = fs2.readdirStringSync(fileDir).filter((f) => f.startsWith(`${fileBase}.backup.`)).sort();
- const mostRecent = backups.at(-1);
- if (mostRecent) {
- return join16(fileDir, mostRecent);
- }
- const legacyBackup = `${file}.backup`;
- try {
- fs2.statSync(legacyBackup);
- return legacyBackup;
- } catch {}
- } catch {}
- return null;
-}
-function getConfig(file, createDefault, throwOnInvalid) {
- if (!configReadingAllowed && true) {
- throw new Error("Config accessed before allowed.");
- }
- const fs2 = getFsImplementation();
- try {
- const fileContent = fs2.readFileSync(file, {
- encoding: "utf-8"
- });
- try {
- const parsedConfig = jsonParse(stripBOM2(fileContent));
- return {
- ...createDefault(),
- ...parsedConfig
- };
- } catch (error) {
- const errorMessage2 = error instanceof Error ? error.message : String(error);
- throw new ConfigParseError(errorMessage2, file, createDefault());
- }
- } catch (error) {
- const errCode = getErrnoCode(error);
- if (errCode === "ENOENT") {
- const backupPath = findMostRecentBackup(file);
- if (backupPath) {
- process.stderr.write(`
-Claude configuration file not found at: ${file}
-` + `A backup file exists at: ${backupPath}
-` + `You can manually restore it by running: cp "${backupPath}" "${file}"
-
-`);
- }
- return createDefault();
- }
- if (error instanceof ConfigParseError && throwOnInvalid) {
- throw error;
- }
- if (error instanceof ConfigParseError) {
- logForDebugging(`Config file corrupted, resetting to defaults: ${error.message}`, { level: "error" });
- if (!insideGetConfig) {
- insideGetConfig = true;
- try {
- logError2(error);
- let hasBackup = false;
- try {
- fs2.statSync(`${file}.backup`);
- hasBackup = true;
- } catch {}
- logEvent("tengu_config_parse_error", {
- has_backup: hasBackup
- });
- } finally {
- insideGetConfig = false;
- }
- }
- process.stderr.write(`
-Claude configuration file at ${file} is corrupted: ${error.message}
-`);
- const fileBase = basename4(file);
- const corruptedBackupDir = getConfigBackupDir();
- try {
- fs2.mkdirSync(corruptedBackupDir);
- } catch (mkdirErr) {
- const mkdirCode = getErrnoCode(mkdirErr);
- if (mkdirCode !== "EEXIST") {
- throw mkdirErr;
- }
- }
- const existingCorruptedBackups = fs2.readdirStringSync(corruptedBackupDir).filter((f) => f.startsWith(`${fileBase}.corrupted.`));
- let corruptedBackupPath;
- let alreadyBackedUp = false;
- const currentContent = fs2.readFileSync(file, { encoding: "utf-8" });
- for (const backup of existingCorruptedBackups) {
- try {
- const backupContent = fs2.readFileSync(join16(corruptedBackupDir, backup), { encoding: "utf-8" });
- if (currentContent === backupContent) {
- alreadyBackedUp = true;
- break;
- }
- } catch {}
- }
- if (!alreadyBackedUp) {
- corruptedBackupPath = join16(corruptedBackupDir, `${fileBase}.corrupted.${Date.now()}`);
- try {
- fs2.copyFileSync(file, corruptedBackupPath);
- logForDebugging(`Corrupted config backed up to: ${corruptedBackupPath}`, {
- level: "error"
- });
- } catch {}
- }
- const backupPath = findMostRecentBackup(file);
- if (corruptedBackupPath) {
- process.stderr.write(`The corrupted file has been backed up to: ${corruptedBackupPath}
-`);
- } else if (alreadyBackedUp) {
- process.stderr.write(`The corrupted file has already been backed up.
-`);
- }
- if (backupPath) {
- process.stderr.write(`A backup file exists at: ${backupPath}
-` + `You can manually restore it by running: cp "${backupPath}" "${file}"
-
-`);
- } else {
- process.stderr.write(`
-`);
- }
- }
- return createDefault();
- }
-}
-function getCurrentProjectConfig() {
- if (false) {}
- const absolutePath = getProjectPathForConfig();
- const config = getGlobalConfig();
- if (!config.projects) {
- return DEFAULT_PROJECT_CONFIG;
- }
- const projectConfig = config.projects[absolutePath] ?? DEFAULT_PROJECT_CONFIG;
- if (typeof projectConfig.allowedTools === "string") {
- projectConfig.allowedTools = safeParseJSON(projectConfig.allowedTools) ?? [];
- }
- return projectConfig;
-}
-function saveCurrentProjectConfig(updater) {
- if (false) {}
- const absolutePath = getProjectPathForConfig();
- let written = null;
- try {
- const didWrite = saveConfigWithLock(getGlobalClaudeFile(), createDefaultGlobalConfig, (current) => {
- const currentProjectConfig = current.projects?.[absolutePath] ?? DEFAULT_PROJECT_CONFIG;
- const newProjectConfig = updater(currentProjectConfig);
- if (newProjectConfig === currentProjectConfig) {
- return current;
- }
- written = {
- ...current,
- projects: {
- ...current.projects,
- [absolutePath]: newProjectConfig
- }
- };
- return written;
- });
- if (didWrite && written) {
- writeThroughGlobalConfigCache(written);
- }
- } catch (error) {
- logForDebugging(`Failed to save config with lock: ${error}`, {
- level: "error"
- });
- const config = getConfig(getGlobalClaudeFile(), createDefaultGlobalConfig);
- if (wouldLoseAuthState(config)) {
- logForDebugging("saveCurrentProjectConfig fallback: re-read config is missing auth that cache has; refusing to write. See GH #3117.", { level: "error" });
- logEvent("tengu_config_auth_loss_prevented", {});
- return;
- }
- const currentProjectConfig = config.projects?.[absolutePath] ?? DEFAULT_PROJECT_CONFIG;
- const newProjectConfig = updater(currentProjectConfig);
- if (newProjectConfig === currentProjectConfig) {
- return;
- }
- written = {
- ...config,
- projects: {
- ...config.projects,
- [absolutePath]: newProjectConfig
- }
- };
- saveConfig(getGlobalClaudeFile(), written, DEFAULT_GLOBAL_CONFIG);
- writeThroughGlobalConfigCache(written);
- }
-}
-function isAutoUpdaterDisabled() {
- return getAutoUpdaterDisabledReason() !== null;
-}
-function shouldSkipPluginAutoupdate() {
- return isAutoUpdaterDisabled() && !isEnvTruthy(process.env.FORCE_AUTOUPDATE_PLUGINS);
-}
-function formatAutoUpdaterDisabledReason(reason) {
- switch (reason.type) {
- case "development":
- return "development build";
- case "env":
- return `${reason.envVar} set`;
- case "config":
- return "config";
- }
-}
-function getAutoUpdaterDisabledReason() {
- if (true) {
- return { type: "development" };
- }
- if (isEnvTruthy(process.env.DISABLE_AUTOUPDATER)) {
- return { type: "env", envVar: "DISABLE_AUTOUPDATER" };
- }
- const essentialTrafficEnvVar = getEssentialTrafficOnlyReason();
- if (essentialTrafficEnvVar) {
- return { type: "env", envVar: essentialTrafficEnvVar };
- }
- const config = getGlobalConfig();
- if (config.autoUpdates === false && (config.installMethod !== "native" || config.autoUpdatesProtectedForNative !== true)) {
- return { type: "config" };
- }
- return null;
-}
-function getOrCreateUserID() {
- const config = getGlobalConfig();
- if (config.userID) {
- return config.userID;
- }
- const userID = randomBytes(32).toString("hex");
- saveGlobalConfig((current) => ({ ...current, userID }));
- return userID;
-}
-function recordFirstStartTime() {
- const config = getGlobalConfig();
- if (!config.firstStartTime) {
- const firstStartTime = new Date().toISOString();
- saveGlobalConfig((current) => ({
- ...current,
- firstStartTime: current.firstStartTime ?? firstStartTime
- }));
- }
-}
-function getMemoryPath(memoryType) {
- const cwd2 = getOriginalCwd();
- switch (memoryType) {
- case "User":
- return join16(getClaudeConfigHomeDir(), "CLAUDE.md");
- case "Local":
- return join16(cwd2, "CLAUDE.local.md");
- case "Project":
- return join16(cwd2, "CLAUDE.md");
- case "Managed":
- return join16(getManagedFilePath(), "CLAUDE.md");
- case "AutoMem":
- return getAutoMemEntrypoint();
- }
- if (false) {}
- return "";
-}
-function getManagedClaudeRulesDir() {
- return join16(getManagedFilePath(), ".claude", "rules");
-}
-function getUserClaudeRulesDir() {
- return join16(getClaudeConfigHomeDir(), "rules");
-}
-var insideGetConfig = false, DEFAULT_PROJECT_CONFIG, DEFAULT_GLOBAL_CONFIG, _trustAccepted = false, TEST_GLOBAL_CONFIG_FOR_TESTING, TEST_PROJECT_CONFIG_FOR_TESTING, globalConfigCache, lastReadFileStats = null, configCacheHits = 0, configCacheMisses = 0, globalConfigWriteCount = 0, CONFIG_FRESHNESS_POLL_MS = 1000, freshnessWatcherStarted = false, configReadingAllowed = false, getProjectPathForConfig;
-var init_config = __esm(() => {
- init_memoize();
- init_pickBy();
- init_state();
- init_paths();
- init_analytics();
- init_cwd();
- init_cleanupRegistry();
- init_debug();
- init_diagLogs();
- init_env();
- init_envUtils();
- init_errors();
- init_file();
- init_fsOperations();
- init_git();
- init_json();
- init_log2();
- init_path();
- init_managedPath();
- init_slowOperations();
- init_configConstants();
- DEFAULT_PROJECT_CONFIG = {
- allowedTools: [],
- mcpContextUris: [],
- mcpServers: {},
- enabledMcpjsonServers: [],
- disabledMcpjsonServers: [],
- hasTrustDialogAccepted: false,
- projectOnboardingSeenCount: 0,
- hasClaudeMdExternalIncludesApproved: false,
- hasClaudeMdExternalIncludesWarningShown: false
- };
- DEFAULT_GLOBAL_CONFIG = createDefaultGlobalConfig();
- TEST_GLOBAL_CONFIG_FOR_TESTING = {
- ...DEFAULT_GLOBAL_CONFIG,
- autoUpdates: false
- };
- TEST_PROJECT_CONFIG_FOR_TESTING = {
- ...DEFAULT_PROJECT_CONFIG
- };
- globalConfigCache = {
- config: null,
- mtime: 0
- };
- registerCleanup(async () => {
- reportConfigCacheStats();
- });
- getProjectPathForConfig = memoize_default(() => {
- const originalCwd = getOriginalCwd();
- const gitRoot = findCanonicalGitRoot(originalCwd);
- if (gitRoot) {
- return normalizePathForConfigKey(gitRoot);
- }
- return normalizePathForConfigKey(resolve7(originalCwd));
- });
-});
-
-// src/utils/sequential.ts
-function sequential(fn) {
- const queue = [];
- let processing = false;
- async function processQueue() {
- if (processing)
- return;
- if (queue.length === 0)
- return;
- processing = true;
- while (queue.length > 0) {
- const { args, resolve: resolve8, reject, context } = queue.shift();
- try {
- const result = await fn.apply(context, args);
- resolve8(result);
- } catch (error) {
- reject(error);
- }
- }
- processing = false;
- if (queue.length > 0) {
- processQueue();
- }
- }
- return function(...args) {
- return new Promise((resolve8, reject) => {
- queue.push({ args, resolve: resolve8, reject, context: this });
- processQueue();
- });
- };
-}
-
-// node_modules/lodash-es/_assignMergeValue.js
-function assignMergeValue(object, key, value) {
- if (value !== undefined && !eq_default(object[key], value) || value === undefined && !(key in object)) {
- _baseAssignValue_default(object, key, value);
- }
-}
-var _assignMergeValue_default;
-var init__assignMergeValue = __esm(() => {
- init__baseAssignValue();
- init_eq();
- _assignMergeValue_default = assignMergeValue;
-});
-
-// node_modules/lodash-es/isArrayLikeObject.js
-function isArrayLikeObject(value) {
- return isObjectLike_default(value) && isArrayLike_default(value);
-}
-var isArrayLikeObject_default;
-var init_isArrayLikeObject = __esm(() => {
- init_isArrayLike();
- init_isObjectLike();
- isArrayLikeObject_default = isArrayLikeObject;
-});
-
-// node_modules/lodash-es/isPlainObject.js
-function isPlainObject3(value) {
- if (!isObjectLike_default(value) || _baseGetTag_default(value) != objectTag5) {
- return false;
- }
- var proto2 = _getPrototype_default(value);
- if (proto2 === null) {
- return true;
- }
- var Ctor = hasOwnProperty14.call(proto2, "constructor") && proto2.constructor;
- return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString3.call(Ctor) == objectCtorString;
-}
-var objectTag5 = "[object Object]", funcProto3, objectProto16, funcToString3, hasOwnProperty14, objectCtorString, isPlainObject_default;
-var init_isPlainObject = __esm(() => {
- init__baseGetTag();
- init__getPrototype();
- init_isObjectLike();
- funcProto3 = Function.prototype;
- objectProto16 = Object.prototype;
- funcToString3 = funcProto3.toString;
- hasOwnProperty14 = objectProto16.hasOwnProperty;
- objectCtorString = funcToString3.call(Object);
- isPlainObject_default = isPlainObject3;
-});
-
-// node_modules/lodash-es/_safeGet.js
-function safeGet(object, key) {
- if (key === "constructor" && typeof object[key] === "function") {
- return;
- }
- if (key == "__proto__") {
- return;
- }
- return object[key];
-}
-var _safeGet_default;
-var init__safeGet = __esm(() => {
- _safeGet_default = safeGet;
-});
-
-// node_modules/lodash-es/toPlainObject.js
-function toPlainObject(value) {
- return _copyObject_default(value, keysIn_default(value));
-}
-var toPlainObject_default;
-var init_toPlainObject = __esm(() => {
- init__copyObject();
- init_keysIn();
- toPlainObject_default = toPlainObject;
-});
-
-// node_modules/lodash-es/_baseMergeDeep.js
-function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
- var objValue = _safeGet_default(object, key), srcValue = _safeGet_default(source, key), stacked = stack.get(srcValue);
- if (stacked) {
- _assignMergeValue_default(object, key, stacked);
- return;
- }
- var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : undefined;
- var isCommon = newValue === undefined;
- if (isCommon) {
- var isArr = isArray_default(srcValue), isBuff = !isArr && isBuffer_default(srcValue), isTyped = !isArr && !isBuff && isTypedArray_default(srcValue);
- newValue = srcValue;
- if (isArr || isBuff || isTyped) {
- if (isArray_default(objValue)) {
- newValue = objValue;
- } else if (isArrayLikeObject_default(objValue)) {
- newValue = _copyArray_default(objValue);
- } else if (isBuff) {
- isCommon = false;
- newValue = _cloneBuffer_default(srcValue, true);
- } else if (isTyped) {
- isCommon = false;
- newValue = _cloneTypedArray_default(srcValue, true);
- } else {
- newValue = [];
- }
- } else if (isPlainObject_default(srcValue) || isArguments_default(srcValue)) {
- newValue = objValue;
- if (isArguments_default(objValue)) {
- newValue = toPlainObject_default(objValue);
- } else if (!isObject_default(objValue) || isFunction_default(objValue)) {
- newValue = _initCloneObject_default(srcValue);
- }
- } else {
- isCommon = false;
- }
- }
- if (isCommon) {
- stack.set(srcValue, newValue);
- mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
- stack["delete"](srcValue);
- }
- _assignMergeValue_default(object, key, newValue);
-}
-var _baseMergeDeep_default;
-var init__baseMergeDeep = __esm(() => {
- init__assignMergeValue();
- init__cloneBuffer();
- init__cloneTypedArray();
- init__copyArray();
- init__initCloneObject();
- init_isArguments();
- init_isArray();
- init_isArrayLikeObject();
- init_isBuffer();
- init_isFunction();
- init_isObject();
- init_isPlainObject();
- init_isTypedArray();
- init__safeGet();
- init_toPlainObject();
- _baseMergeDeep_default = baseMergeDeep;
-});
-
-// node_modules/lodash-es/_baseMerge.js
-function baseMerge(object, source, srcIndex, customizer, stack) {
- if (object === source) {
- return;
- }
- _baseFor_default(source, function(srcValue, key) {
- stack || (stack = new _Stack_default);
- if (isObject_default(srcValue)) {
- _baseMergeDeep_default(object, source, key, srcIndex, baseMerge, customizer, stack);
- } else {
- var newValue = customizer ? customizer(_safeGet_default(object, key), srcValue, key + "", object, source, stack) : undefined;
- if (newValue === undefined) {
- newValue = srcValue;
- }
- _assignMergeValue_default(object, key, newValue);
- }
- }, keysIn_default);
-}
-var _baseMerge_default;
-var init__baseMerge = __esm(() => {
- init__Stack();
- init__assignMergeValue();
- init__baseFor();
- init__baseMergeDeep();
- init_isObject();
- init_keysIn();
- init__safeGet();
- _baseMerge_default = baseMerge;
-});
-
-// node_modules/lodash-es/_apply.js
-function apply(func, thisArg, args) {
- switch (args.length) {
- case 0:
- return func.call(thisArg);
- case 1:
- return func.call(thisArg, args[0]);
- case 2:
- return func.call(thisArg, args[0], args[1]);
- case 3:
- return func.call(thisArg, args[0], args[1], args[2]);
- }
- return func.apply(thisArg, args);
-}
-var _apply_default;
-var init__apply = __esm(() => {
- _apply_default = apply;
-});
-
-// node_modules/lodash-es/_overRest.js
-function overRest(func, start, transform) {
- start = nativeMax(start === undefined ? func.length - 1 : start, 0);
- return function() {
- var args = arguments, index2 = -1, length = nativeMax(args.length - start, 0), array = Array(length);
- while (++index2 < length) {
- array[index2] = args[start + index2];
- }
- index2 = -1;
- var otherArgs = Array(start + 1);
- while (++index2 < start) {
- otherArgs[index2] = args[index2];
- }
- otherArgs[start] = transform(array);
- return _apply_default(func, this, otherArgs);
- };
-}
-var nativeMax, _overRest_default;
-var init__overRest = __esm(() => {
- init__apply();
- nativeMax = Math.max;
- _overRest_default = overRest;
-});
-
-// node_modules/lodash-es/constant.js
-function constant(value) {
- return function() {
- return value;
- };
-}
-var constant_default;
-var init_constant = __esm(() => {
- constant_default = constant;
-});
-
-// node_modules/lodash-es/_baseSetToString.js
-var baseSetToString, _baseSetToString_default;
-var init__baseSetToString = __esm(() => {
- init_constant();
- init__defineProperty();
- init_identity();
- baseSetToString = !_defineProperty_default ? identity_default : function(func, string) {
- return _defineProperty_default(func, "toString", {
- configurable: true,
- enumerable: false,
- value: constant_default(string),
- writable: true
- });
- };
- _baseSetToString_default = baseSetToString;
-});
-
-// node_modules/lodash-es/_shortOut.js
-function shortOut(func) {
- var count2 = 0, lastCalled = 0;
- return function() {
- var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled);
- lastCalled = stamp;
- if (remaining > 0) {
- if (++count2 >= HOT_COUNT) {
- return arguments[0];
- }
- } else {
- count2 = 0;
- }
- return func.apply(undefined, arguments);
- };
-}
-var HOT_COUNT = 800, HOT_SPAN = 16, nativeNow, _shortOut_default;
-var init__shortOut = __esm(() => {
- nativeNow = Date.now;
- _shortOut_default = shortOut;
-});
-
-// node_modules/lodash-es/_setToString.js
-var setToString, _setToString_default;
-var init__setToString = __esm(() => {
- init__baseSetToString();
- init__shortOut();
- setToString = _shortOut_default(_baseSetToString_default);
- _setToString_default = setToString;
-});
-
-// node_modules/lodash-es/_baseRest.js
-function baseRest(func, start) {
- return _setToString_default(_overRest_default(func, start, identity_default), func + "");
-}
-var _baseRest_default;
-var init__baseRest = __esm(() => {
- init_identity();
- init__overRest();
- init__setToString();
- _baseRest_default = baseRest;
-});
-
-// node_modules/lodash-es/_isIterateeCall.js
-function isIterateeCall(value, index2, object) {
- if (!isObject_default(object)) {
- return false;
- }
- var type = typeof index2;
- if (type == "number" ? isArrayLike_default(object) && _isIndex_default(index2, object.length) : type == "string" && (index2 in object)) {
- return eq_default(object[index2], value);
- }
- return false;
-}
-var _isIterateeCall_default;
-var init__isIterateeCall = __esm(() => {
- init_eq();
- init_isArrayLike();
- init__isIndex();
- init_isObject();
- _isIterateeCall_default = isIterateeCall;
-});
-
-// node_modules/lodash-es/_createAssigner.js
-function createAssigner(assigner) {
- return _baseRest_default(function(object, sources) {
- var index2 = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined;
- customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined;
- if (guard && _isIterateeCall_default(sources[0], sources[1], guard)) {
- customizer = length < 3 ? undefined : customizer;
- length = 1;
- }
- object = Object(object);
- while (++index2 < length) {
- var source = sources[index2];
- if (source) {
- assigner(object, source, index2, customizer);
- }
- }
- return object;
- });
-}
-var _createAssigner_default;
-var init__createAssigner = __esm(() => {
- init__baseRest();
- init__isIterateeCall();
- _createAssigner_default = createAssigner;
-});
-
-// node_modules/lodash-es/mergeWith.js
-var mergeWith, mergeWith_default;
-var init_mergeWith = __esm(() => {
- init__baseMerge();
- init__createAssigner();
- mergeWith = _createAssigner_default(function(object, source, srcIndex, customizer) {
- _baseMerge_default(object, source, srcIndex, customizer);
- });
- mergeWith_default = mergeWith;
-});
-
-// node_modules/zod/v4/core/core.js
-function $constructor(name, initializer, params) {
- function init(inst, def2) {
- var _a2;
- Object.defineProperty(inst, "_zod", {
- value: inst._zod ?? {},
- enumerable: false
- });
- (_a2 = inst._zod).traits ?? (_a2.traits = new Set);
- inst._zod.traits.add(name);
- initializer(inst, def2);
- for (const k in _.prototype) {
- if (!(k in inst))
- Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
- }
- inst._zod.constr = _;
- inst._zod.def = def2;
- }
- const Parent = params?.Parent ?? Object;
-
- class Definition extends Parent {
- }
- Object.defineProperty(Definition, "name", { value: name });
- function _(def2) {
- var _a2;
- const inst = params?.Parent ? new Definition : this;
- init(inst, def2);
- (_a2 = inst._zod).deferred ?? (_a2.deferred = []);
- for (const fn of inst._zod.deferred) {
- fn();
- }
- return inst;
- }
- Object.defineProperty(_, "init", { value: init });
- Object.defineProperty(_, Symbol.hasInstance, {
- value: (inst) => {
- if (params?.Parent && inst instanceof params.Parent)
- return true;
- return inst?._zod?.traits?.has(name);
- }
- });
- Object.defineProperty(_, "name", { value: name });
- return _;
-}
-function config(newConfig) {
- if (newConfig)
- Object.assign(globalConfig, newConfig);
- return globalConfig;
-}
-var NEVER, $brand, $ZodAsyncError, globalConfig;
-var init_core4 = __esm(() => {
- NEVER = Object.freeze({
- status: "aborted"
- });
- $brand = Symbol("zod_brand");
- $ZodAsyncError = class $ZodAsyncError extends Error {
- constructor() {
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
- }
- };
- globalConfig = {};
-});
-
-// node_modules/zod/v4/core/util.js
-var exports_util = {};
-__export(exports_util, {
- unwrapMessage: () => unwrapMessage,
- stringifyPrimitive: () => stringifyPrimitive,
- required: () => required,
- randomString: () => randomString,
- propertyKeyTypes: () => propertyKeyTypes,
- promiseAllObject: () => promiseAllObject,
- primitiveTypes: () => primitiveTypes,
- prefixIssues: () => prefixIssues,
- pick: () => pick,
- partial: () => partial,
- optionalKeys: () => optionalKeys,
- omit: () => omit,
- numKeys: () => numKeys,
- nullish: () => nullish,
- normalizeParams: () => normalizeParams,
- merge: () => merge2,
- jsonStringifyReplacer: () => jsonStringifyReplacer,
- joinValues: () => joinValues,
- issue: () => issue,
- isPlainObject: () => isPlainObject4,
- isObject: () => isObject4,
- getSizableOrigin: () => getSizableOrigin,
- getParsedType: () => getParsedType,
- getLengthableOrigin: () => getLengthableOrigin,
- getEnumValues: () => getEnumValues,
- getElementAtPath: () => getElementAtPath,
- floatSafeRemainder: () => floatSafeRemainder,
- finalizeIssue: () => finalizeIssue,
- extend: () => extend2,
- escapeRegex: () => escapeRegex,
- esc: () => esc,
- defineLazy: () => defineLazy,
- createTransparentProxy: () => createTransparentProxy,
- clone: () => clone2,
- cleanRegex: () => cleanRegex,
- cleanEnum: () => cleanEnum,
- captureStackTrace: () => captureStackTrace,
- cached: () => cached,
- assignProp: () => assignProp,
- assertNotEqual: () => assertNotEqual,
- assertNever: () => assertNever,
- assertIs: () => assertIs,
- assertEqual: () => assertEqual,
- assert: () => assert,
- allowsEval: () => allowsEval,
- aborted: () => aborted2,
- NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES,
- Class: () => Class,
- BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES
-});
-function assertEqual(val) {
- return val;
-}
-function assertNotEqual(val) {
- return val;
-}
-function assertIs(_arg) {}
-function assertNever(_x) {
- throw new Error;
-}
-function assert(_) {}
-function getEnumValues(entries) {
- const numericValues = Object.values(entries).filter((v) => typeof v === "number");
- const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
- return values;
-}
-function joinValues(array, separator = "|") {
- return array.map((val) => stringifyPrimitive(val)).join(separator);
-}
-function jsonStringifyReplacer(_, value) {
- if (typeof value === "bigint")
- return value.toString();
- return value;
-}
-function cached(getter) {
- const set = false;
- return {
- get value() {
- if (!set) {
- const value = getter();
- Object.defineProperty(this, "value", { value });
- return value;
- }
- throw new Error("cached value already set");
- }
- };
-}
-function nullish(input) {
- return input === null || input === undefined;
-}
-function cleanRegex(source) {
- const start = source.startsWith("^") ? 1 : 0;
- const end = source.endsWith("$") ? source.length - 1 : source.length;
- return source.slice(start, end);
-}
-function floatSafeRemainder(val, step) {
- const valDecCount = (val.toString().split(".")[1] || "").length;
- const stepDecCount = (step.toString().split(".")[1] || "").length;
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
- return valInt % stepInt / 10 ** decCount;
-}
-function defineLazy(object, key, getter) {
- const set = false;
- Object.defineProperty(object, key, {
- get() {
- if (!set) {
- const value = getter();
- object[key] = value;
- return value;
- }
- throw new Error("cached value already set");
- },
- set(v) {
- Object.defineProperty(object, key, {
- value: v
- });
- },
- configurable: true
- });
-}
-function assignProp(target, prop, value) {
- Object.defineProperty(target, prop, {
- value,
- writable: true,
- enumerable: true,
- configurable: true
- });
-}
-function getElementAtPath(obj, path8) {
- if (!path8)
- return obj;
- return path8.reduce((acc, key) => acc?.[key], obj);
-}
-function promiseAllObject(promisesObj) {
- const keys2 = Object.keys(promisesObj);
- const promises = keys2.map((key) => promisesObj[key]);
- return Promise.all(promises).then((results) => {
- const resolvedObj = {};
- for (let i2 = 0;i2 < keys2.length; i2++) {
- resolvedObj[keys2[i2]] = results[i2];
- }
- return resolvedObj;
- });
-}
-function randomString(length = 10) {
- const chars = "abcdefghijklmnopqrstuvwxyz";
- let str = "";
- for (let i2 = 0;i2 < length; i2++) {
- str += chars[Math.floor(Math.random() * chars.length)];
- }
- return str;
-}
-function esc(str) {
- return JSON.stringify(str);
-}
-function isObject4(data) {
- return typeof data === "object" && data !== null && !Array.isArray(data);
-}
-function isPlainObject4(o2) {
- if (isObject4(o2) === false)
- return false;
- const ctor = o2.constructor;
- if (ctor === undefined)
- return true;
- const prot = ctor.prototype;
- if (isObject4(prot) === false)
- return false;
- if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
- return false;
- }
- return true;
-}
-function numKeys(data) {
- let keyCount = 0;
- for (const key in data) {
- if (Object.prototype.hasOwnProperty.call(data, key)) {
- keyCount++;
- }
- }
- return keyCount;
-}
-function escapeRegex(str) {
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-}
-function clone2(inst, def2, params) {
- const cl = new inst._zod.constr(def2 ?? inst._zod.def);
- if (!def2 || params?.parent)
- cl._zod.parent = inst;
- return cl;
-}
-function normalizeParams(_params) {
- const params = _params;
- if (!params)
- return {};
- if (typeof params === "string")
- return { error: () => params };
- if (params?.message !== undefined) {
- if (params?.error !== undefined)
- throw new Error("Cannot specify both `message` and `error` params");
- params.error = params.message;
- }
- delete params.message;
- if (typeof params.error === "string")
- return { ...params, error: () => params.error };
- return params;
-}
-function createTransparentProxy(getter) {
- let target;
- return new Proxy({}, {
- get(_, prop, receiver) {
- target ?? (target = getter());
- return Reflect.get(target, prop, receiver);
- },
- set(_, prop, value, receiver) {
- target ?? (target = getter());
- return Reflect.set(target, prop, value, receiver);
- },
- has(_, prop) {
- target ?? (target = getter());
- return Reflect.has(target, prop);
- },
- deleteProperty(_, prop) {
- target ?? (target = getter());
- return Reflect.deleteProperty(target, prop);
- },
- ownKeys(_) {
- target ?? (target = getter());
- return Reflect.ownKeys(target);
- },
- getOwnPropertyDescriptor(_, prop) {
- target ?? (target = getter());
- return Reflect.getOwnPropertyDescriptor(target, prop);
- },
- defineProperty(_, prop, descriptor) {
- target ?? (target = getter());
- return Reflect.defineProperty(target, prop, descriptor);
- }
- });
-}
-function stringifyPrimitive(value) {
- if (typeof value === "bigint")
- return value.toString() + "n";
- if (typeof value === "string")
- return `"${value}"`;
- return `${value}`;
-}
-function optionalKeys(shape) {
- return Object.keys(shape).filter((k) => {
- return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
- });
-}
-function pick(schema, mask) {
- const newShape = {};
- const currDef = schema._zod.def;
- for (const key in mask) {
- if (!(key in currDef.shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- newShape[key] = currDef.shape[key];
- }
- return clone2(schema, {
- ...schema._zod.def,
- shape: newShape,
- checks: []
- });
-}
-function omit(schema, mask) {
- const newShape = { ...schema._zod.def.shape };
- const currDef = schema._zod.def;
- for (const key in mask) {
- if (!(key in currDef.shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- delete newShape[key];
- }
- return clone2(schema, {
- ...schema._zod.def,
- shape: newShape,
- checks: []
- });
-}
-function extend2(schema, shape) {
- if (!isPlainObject4(shape)) {
- throw new Error("Invalid input to extend: expected a plain object");
- }
- const def2 = {
- ...schema._zod.def,
- get shape() {
- const _shape = { ...schema._zod.def.shape, ...shape };
- assignProp(this, "shape", _shape);
- return _shape;
- },
- checks: []
- };
- return clone2(schema, def2);
-}
-function merge2(a2, b) {
- return clone2(a2, {
- ...a2._zod.def,
- get shape() {
- const _shape = { ...a2._zod.def.shape, ...b._zod.def.shape };
- assignProp(this, "shape", _shape);
- return _shape;
- },
- catchall: b._zod.def.catchall,
- checks: []
- });
-}
-function partial(Class, schema, mask) {
- const oldShape = schema._zod.def.shape;
- const shape = { ...oldShape };
- if (mask) {
- for (const key in mask) {
- if (!(key in oldShape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- shape[key] = Class ? new Class({
- type: "optional",
- innerType: oldShape[key]
- }) : oldShape[key];
- }
- } else {
- for (const key in oldShape) {
- shape[key] = Class ? new Class({
- type: "optional",
- innerType: oldShape[key]
- }) : oldShape[key];
- }
- }
- return clone2(schema, {
- ...schema._zod.def,
- shape,
- checks: []
- });
-}
-function required(Class, schema, mask) {
- const oldShape = schema._zod.def.shape;
- const shape = { ...oldShape };
- if (mask) {
- for (const key in mask) {
- if (!(key in shape)) {
- throw new Error(`Unrecognized key: "${key}"`);
- }
- if (!mask[key])
- continue;
- shape[key] = new Class({
- type: "nonoptional",
- innerType: oldShape[key]
- });
- }
- } else {
- for (const key in oldShape) {
- shape[key] = new Class({
- type: "nonoptional",
- innerType: oldShape[key]
- });
- }
- }
- return clone2(schema, {
- ...schema._zod.def,
- shape,
- checks: []
- });
-}
-function aborted2(x2, startIndex = 0) {
- for (let i2 = startIndex;i2 < x2.issues.length; i2++) {
- if (x2.issues[i2]?.continue !== true)
- return true;
- }
- return false;
-}
-function prefixIssues(path8, issues) {
- return issues.map((iss) => {
- var _a2;
- (_a2 = iss).path ?? (_a2.path = []);
- iss.path.unshift(path8);
- return iss;
- });
-}
-function unwrapMessage(message) {
- return typeof message === "string" ? message : message?.message;
-}
-function finalizeIssue(iss, ctx, config2) {
- const full = { ...iss, path: iss.path ?? [] };
- if (!iss.message) {
- const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
- full.message = message;
- }
- delete full.inst;
- delete full.continue;
- if (!ctx?.reportInput) {
- delete full.input;
- }
- return full;
-}
-function getSizableOrigin(input) {
- if (input instanceof Set)
- return "set";
- if (input instanceof Map)
- return "map";
- if (input instanceof File)
- return "file";
- return "unknown";
-}
-function getLengthableOrigin(input) {
- if (Array.isArray(input))
- return "array";
- if (typeof input === "string")
- return "string";
- return "unknown";
-}
-function issue(...args) {
- const [iss, input, inst] = args;
- if (typeof iss === "string") {
- return {
- message: iss,
- code: "custom",
- input,
- inst
- };
- }
- return { ...iss };
-}
-function cleanEnum(obj) {
- return Object.entries(obj).filter(([k, _]) => {
- return Number.isNaN(Number.parseInt(k, 10));
- }).map((el) => el[1]);
-}
-
-class Class {
- constructor(..._args) {}
-}
-var captureStackTrace, allowsEval, getParsedType = (data) => {
- const t = typeof data;
- switch (t) {
- case "undefined":
- return "undefined";
- case "string":
- return "string";
- case "number":
- return Number.isNaN(data) ? "nan" : "number";
- case "boolean":
- return "boolean";
- case "function":
- return "function";
- case "bigint":
- return "bigint";
- case "symbol":
- return "symbol";
- case "object":
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
- return "promise";
- }
- if (typeof Map !== "undefined" && data instanceof Map) {
- return "map";
- }
- if (typeof Set !== "undefined" && data instanceof Set) {
- return "set";
- }
- if (typeof Date !== "undefined" && data instanceof Date) {
- return "date";
- }
- if (typeof File !== "undefined" && data instanceof File) {
- return "file";
- }
- return "object";
- default:
- throw new Error(`Unknown data type: ${t}`);
- }
-}, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES;
-var init_util2 = __esm(() => {
- captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {};
- allowsEval = cached(() => {
- if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
- return false;
- }
- try {
- const F = Function;
- new F("");
- return true;
- } catch (_) {
- return false;
- }
- });
- propertyKeyTypes = new Set(["string", "number", "symbol"]);
- primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
- NUMBER_FORMAT_RANGES = {
- safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
- int32: [-2147483648, 2147483647],
- uint32: [0, 4294967295],
- float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
- float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
- };
- BIGINT_FORMAT_RANGES = {
- int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
- uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
- };
-});
-
-// node_modules/zod/v4/core/errors.js
-function flattenError(error, mapper = (issue2) => issue2.message) {
- const fieldErrors = {};
- const formErrors = [];
- for (const sub of error.issues) {
- if (sub.path.length > 0) {
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
- fieldErrors[sub.path[0]].push(mapper(sub));
- } else {
- formErrors.push(mapper(sub));
- }
- }
- return { formErrors, fieldErrors };
-}
-function formatError(error, _mapper) {
- const mapper = _mapper || function(issue2) {
- return issue2.message;
- };
- const fieldErrors = { _errors: [] };
- const processError = (error2) => {
- for (const issue2 of error2.issues) {
- if (issue2.code === "invalid_union" && issue2.errors.length) {
- issue2.errors.map((issues) => processError({ issues }));
- } else if (issue2.code === "invalid_key") {
- processError({ issues: issue2.issues });
- } else if (issue2.code === "invalid_element") {
- processError({ issues: issue2.issues });
- } else if (issue2.path.length === 0) {
- fieldErrors._errors.push(mapper(issue2));
- } else {
- let curr = fieldErrors;
- let i2 = 0;
- while (i2 < issue2.path.length) {
- const el = issue2.path[i2];
- const terminal = i2 === issue2.path.length - 1;
- if (!terminal) {
- curr[el] = curr[el] || { _errors: [] };
- } else {
- curr[el] = curr[el] || { _errors: [] };
- curr[el]._errors.push(mapper(issue2));
- }
- curr = curr[el];
- i2++;
- }
- }
- }
- };
- processError(error);
- return fieldErrors;
-}
-function treeifyError(error, _mapper) {
- const mapper = _mapper || function(issue2) {
- return issue2.message;
- };
- const result = { errors: [] };
- const processError = (error2, path8 = []) => {
- var _a2, _b;
- for (const issue2 of error2.issues) {
- if (issue2.code === "invalid_union" && issue2.errors.length) {
- issue2.errors.map((issues) => processError({ issues }, issue2.path));
- } else if (issue2.code === "invalid_key") {
- processError({ issues: issue2.issues }, issue2.path);
- } else if (issue2.code === "invalid_element") {
- processError({ issues: issue2.issues }, issue2.path);
- } else {
- const fullpath = [...path8, ...issue2.path];
- if (fullpath.length === 0) {
- result.errors.push(mapper(issue2));
- continue;
- }
- let curr = result;
- let i2 = 0;
- while (i2 < fullpath.length) {
- const el = fullpath[i2];
- const terminal = i2 === fullpath.length - 1;
- if (typeof el === "string") {
- curr.properties ?? (curr.properties = {});
- (_a2 = curr.properties)[el] ?? (_a2[el] = { errors: [] });
- curr = curr.properties[el];
- } else {
- curr.items ?? (curr.items = []);
- (_b = curr.items)[el] ?? (_b[el] = { errors: [] });
- curr = curr.items[el];
- }
- if (terminal) {
- curr.errors.push(mapper(issue2));
- }
- i2++;
- }
- }
- }
- };
- processError(error);
- return result;
-}
-function toDotPath(path8) {
- const segs = [];
- for (const seg of path8) {
- if (typeof seg === "number")
- segs.push(`[${seg}]`);
- else if (typeof seg === "symbol")
- segs.push(`[${JSON.stringify(String(seg))}]`);
- else if (/[^\w$]/.test(seg))
- segs.push(`[${JSON.stringify(seg)}]`);
- else {
- if (segs.length)
- segs.push(".");
- segs.push(seg);
- }
- }
- return segs.join("");
-}
-function prettifyError(error) {
- const lines = [];
- const issues = [...error.issues].sort((a2, b) => a2.path.length - b.path.length);
- for (const issue2 of issues) {
- lines.push(`\u2716 ${issue2.message}`);
- if (issue2.path?.length)
- lines.push(` \u2192 at ${toDotPath(issue2.path)}`);
- }
- return lines.join(`
-`);
-}
-var initializer = (inst, def2) => {
- inst.name = "$ZodError";
- Object.defineProperty(inst, "_zod", {
- value: inst._zod,
- enumerable: false
- });
- Object.defineProperty(inst, "issues", {
- value: def2,
- enumerable: false
- });
- Object.defineProperty(inst, "message", {
- get() {
- return JSON.stringify(def2, jsonStringifyReplacer, 2);
- },
- enumerable: true
- });
- Object.defineProperty(inst, "toString", {
- value: () => inst.message,
- enumerable: false
- });
-}, $ZodError, $ZodRealError;
-var init_errors2 = __esm(() => {
- init_core4();
- init_util2();
- $ZodError = $constructor("$ZodError", initializer);
- $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
-});
-
-// node_modules/zod/v4/core/parse.js
-var _parse = (_Err) => (schema, value, _ctx, _params) => {
- const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
- const result = schema._zod.run({ value, issues: [] }, ctx);
- if (result instanceof Promise) {
- throw new $ZodAsyncError;
- }
- if (result.issues.length) {
- const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
- captureStackTrace(e, _params?.callee);
- throw e;
- }
- return result.value;
-}, parse3, _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
- let result = schema._zod.run({ value, issues: [] }, ctx);
- if (result instanceof Promise)
- result = await result;
- if (result.issues.length) {
- const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
- captureStackTrace(e, params?.callee);
- throw e;
- }
- return result.value;
-}, parseAsync, _safeParse = (_Err) => (schema, value, _ctx) => {
- const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
- const result = schema._zod.run({ value, issues: [] }, ctx);
- if (result instanceof Promise) {
- throw new $ZodAsyncError;
- }
- return result.issues.length ? {
- success: false,
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
- } : { success: true, data: result.value };
-}, safeParse, _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
- let result = schema._zod.run({ value, issues: [] }, ctx);
- if (result instanceof Promise)
- result = await result;
- return result.issues.length ? {
- success: false,
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
- } : { success: true, data: result.value };
-}, safeParseAsync;
-var init_parse = __esm(() => {
- init_core4();
- init_errors2();
- init_util2();
- parse3 = /* @__PURE__ */ _parse($ZodRealError);
- parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);
- safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
- safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
-});
-
-// node_modules/zod/v4/core/regexes.js
-var exports_regexes = {};
-__export(exports_regexes, {
- xid: () => xid,
- uuid7: () => uuid7,
- uuid6: () => uuid6,
- uuid4: () => uuid42,
- uuid: () => uuid,
- uppercase: () => uppercase,
- unicodeEmail: () => unicodeEmail,
- undefined: () => _undefined,
- ulid: () => ulid,
- time: () => time,
- string: () => string,
- rfc5322Email: () => rfc5322Email,
- number: () => number,
- null: () => _null,
- nanoid: () => nanoid,
- lowercase: () => lowercase,
- ksuid: () => ksuid,
- ipv6: () => ipv6,
- ipv4: () => ipv4,
- integer: () => integer,
- html5Email: () => html5Email,
- hostname: () => hostname,
- guid: () => guid,
- extendedDuration: () => extendedDuration,
- emoji: () => emoji,
- email: () => email,
- e164: () => e164,
- duration: () => duration,
- domain: () => domain,
- datetime: () => datetime,
- date: () => date,
- cuid2: () => cuid2,
- cuid: () => cuid,
- cidrv6: () => cidrv6,
- cidrv4: () => cidrv4,
- browserEmail: () => browserEmail,
- boolean: () => boolean,
- bigint: () => bigint,
- base64url: () => base64url,
- base64: () => base64,
- _emoji: () => _emoji
-});
-function emoji() {
- return new RegExp(_emoji, "u");
-}
-function timeSource(args) {
- const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
- const regex2 = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
- return regex2;
-}
-function time(args) {
- return new RegExp(`^${timeSource(args)}$`);
-}
-function datetime(args) {
- const time2 = timeSource({ precision: args.precision });
- const opts = ["Z"];
- if (args.local)
- opts.push("");
- if (args.offset)
- opts.push(`([+-]\\d{2}:\\d{2})`);
- const timeRegex = `${time2}(?:${opts.join("|")})`;
- return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
-}
-var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid = (version) => {
- if (!version)
- return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
-}, uuid42, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, browserEmail, _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, hostname, domain, e164, dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`, date, string = (params) => {
- const regex2 = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
- return new RegExp(`^${regex2}$`);
-}, bigint, integer, number, boolean, _null, _undefined, lowercase, uppercase;
-var init_regexes = __esm(() => {
- cuid = /^[cC][^\s-]{8,}$/;
- cuid2 = /^[0-9a-z]+$/;
- ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
- xid = /^[0-9a-vA-V]{20}$/;
- ksuid = /^[A-Za-z0-9]{27}$/;
- nanoid = /^[a-zA-Z0-9_-]{21}$/;
- duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
- extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
- guid = /^([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})$/;
- uuid42 = /* @__PURE__ */ uuid(4);
- uuid6 = /* @__PURE__ */ uuid(6);
- uuid7 = /* @__PURE__ */ uuid(7);
- email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
- html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
- rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
- unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
- browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
- ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
- ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
- cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
- cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
- base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
- base64url = /^[A-Za-z0-9_-]*$/;
- hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
- domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
- e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
- date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
- bigint = /^\d+n?$/;
- integer = /^\d+$/;
- number = /^-?\d+(?:\.\d+)?/i;
- boolean = /true|false/i;
- _null = /null/i;
- _undefined = /undefined/i;
- lowercase = /^[^A-Z]*$/;
- uppercase = /^[^a-z]*$/;
-});
-
-// node_modules/zod/v4/core/checks.js
-function handleCheckPropertyResult(result, payload, property2) {
- if (result.issues.length) {
- payload.issues.push(...prefixIssues(property2, result.issues));
- }
-}
-var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite;
-var init_checks = __esm(() => {
- init_core4();
- init_regexes();
- init_util2();
- $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def2) => {
- var _a2;
- inst._zod ?? (inst._zod = {});
- inst._zod.def = def2;
- (_a2 = inst._zod).onattach ?? (_a2.onattach = []);
- });
- numericOriginMap = {
- number: "number",
- bigint: "bigint",
- object: "date"
- };
- $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- const origin2 = numericOriginMap[typeof def2.value];
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- const curr = (def2.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
- if (def2.value < curr) {
- if (def2.inclusive)
- bag.maximum = def2.value;
- else
- bag.exclusiveMaximum = def2.value;
- }
- });
- inst._zod.check = (payload) => {
- if (def2.inclusive ? payload.value <= def2.value : payload.value < def2.value) {
- return;
- }
- payload.issues.push({
- origin: origin2,
- code: "too_big",
- maximum: def2.value,
- input: payload.value,
- inclusive: def2.inclusive,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- const origin2 = numericOriginMap[typeof def2.value];
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- const curr = (def2.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
- if (def2.value > curr) {
- if (def2.inclusive)
- bag.minimum = def2.value;
- else
- bag.exclusiveMinimum = def2.value;
- }
- });
- inst._zod.check = (payload) => {
- if (def2.inclusive ? payload.value >= def2.value : payload.value > def2.value) {
- return;
- }
- payload.issues.push({
- origin: origin2,
- code: "too_small",
- minimum: def2.value,
- input: payload.value,
- inclusive: def2.inclusive,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- inst._zod.onattach.push((inst2) => {
- var _a2;
- (_a2 = inst2._zod.bag).multipleOf ?? (_a2.multipleOf = def2.value);
- });
- inst._zod.check = (payload) => {
- if (typeof payload.value !== typeof def2.value)
- throw new Error("Cannot mix number and bigint in multiple_of check.");
- const isMultiple = typeof payload.value === "bigint" ? payload.value % def2.value === BigInt(0) : floatSafeRemainder(payload.value, def2.value) === 0;
- if (isMultiple)
- return;
- payload.issues.push({
- origin: typeof payload.value,
- code: "not_multiple_of",
- divisor: def2.value,
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- def2.format = def2.format || "float64";
- const isInt = def2.format?.includes("int");
- const origin2 = isInt ? "int" : "number";
- const [minimum, maximum] = NUMBER_FORMAT_RANGES[def2.format];
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- bag.format = def2.format;
- bag.minimum = minimum;
- bag.maximum = maximum;
- if (isInt)
- bag.pattern = integer;
- });
- inst._zod.check = (payload) => {
- const input = payload.value;
- if (isInt) {
- if (!Number.isInteger(input)) {
- payload.issues.push({
- expected: origin2,
- format: def2.format,
- code: "invalid_type",
- input,
- inst
- });
- return;
- }
- if (!Number.isSafeInteger(input)) {
- if (input > 0) {
- payload.issues.push({
- input,
- code: "too_big",
- maximum: Number.MAX_SAFE_INTEGER,
- note: "Integers must be within the safe integer range.",
- inst,
- origin: origin2,
- continue: !def2.abort
- });
- } else {
- payload.issues.push({
- input,
- code: "too_small",
- minimum: Number.MIN_SAFE_INTEGER,
- note: "Integers must be within the safe integer range.",
- inst,
- origin: origin2,
- continue: !def2.abort
- });
- }
- return;
- }
- }
- if (input < minimum) {
- payload.issues.push({
- origin: "number",
- input,
- code: "too_small",
- minimum,
- inclusive: true,
- inst,
- continue: !def2.abort
- });
- }
- if (input > maximum) {
- payload.issues.push({
- origin: "number",
- input,
- code: "too_big",
- maximum,
- inst
- });
- }
- };
- });
- $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- const [minimum, maximum] = BIGINT_FORMAT_RANGES[def2.format];
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- bag.format = def2.format;
- bag.minimum = minimum;
- bag.maximum = maximum;
- });
- inst._zod.check = (payload) => {
- const input = payload.value;
- if (input < minimum) {
- payload.issues.push({
- origin: "bigint",
- input,
- code: "too_small",
- minimum,
- inclusive: true,
- inst,
- continue: !def2.abort
- });
- }
- if (input > maximum) {
- payload.issues.push({
- origin: "bigint",
- input,
- code: "too_big",
- maximum,
- inst
- });
- }
- };
- });
- $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def2) => {
- var _a2;
- $ZodCheck.init(inst, def2);
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.size !== undefined;
- });
- inst._zod.onattach.push((inst2) => {
- const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
- if (def2.maximum < curr)
- inst2._zod.bag.maximum = def2.maximum;
- });
- inst._zod.check = (payload) => {
- const input = payload.value;
- const size = input.size;
- if (size <= def2.maximum)
- return;
- payload.issues.push({
- origin: getSizableOrigin(input),
- code: "too_big",
- maximum: def2.maximum,
- input,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def2) => {
- var _a2;
- $ZodCheck.init(inst, def2);
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.size !== undefined;
- });
- inst._zod.onattach.push((inst2) => {
- const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
- if (def2.minimum > curr)
- inst2._zod.bag.minimum = def2.minimum;
- });
- inst._zod.check = (payload) => {
- const input = payload.value;
- const size = input.size;
- if (size >= def2.minimum)
- return;
- payload.issues.push({
- origin: getSizableOrigin(input),
- code: "too_small",
- minimum: def2.minimum,
- input,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def2) => {
- var _a2;
- $ZodCheck.init(inst, def2);
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.size !== undefined;
- });
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- bag.minimum = def2.size;
- bag.maximum = def2.size;
- bag.size = def2.size;
- });
- inst._zod.check = (payload) => {
- const input = payload.value;
- const size = input.size;
- if (size === def2.size)
- return;
- const tooBig = size > def2.size;
- payload.issues.push({
- origin: getSizableOrigin(input),
- ...tooBig ? { code: "too_big", maximum: def2.size } : { code: "too_small", minimum: def2.size },
- inclusive: true,
- exact: true,
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def2) => {
- var _a2;
- $ZodCheck.init(inst, def2);
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst2) => {
- const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
- if (def2.maximum < curr)
- inst2._zod.bag.maximum = def2.maximum;
- });
- inst._zod.check = (payload) => {
- const input = payload.value;
- const length = input.length;
- if (length <= def2.maximum)
- return;
- const origin2 = getLengthableOrigin(input);
- payload.issues.push({
- origin: origin2,
- code: "too_big",
- maximum: def2.maximum,
- inclusive: true,
- input,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def2) => {
- var _a2;
- $ZodCheck.init(inst, def2);
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst2) => {
- const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
- if (def2.minimum > curr)
- inst2._zod.bag.minimum = def2.minimum;
- });
- inst._zod.check = (payload) => {
- const input = payload.value;
- const length = input.length;
- if (length >= def2.minimum)
- return;
- const origin2 = getLengthableOrigin(input);
- payload.issues.push({
- origin: origin2,
- code: "too_small",
- minimum: def2.minimum,
- inclusive: true,
- input,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def2) => {
- var _a2;
- $ZodCheck.init(inst, def2);
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
- const val = payload.value;
- return !nullish(val) && val.length !== undefined;
- });
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- bag.minimum = def2.length;
- bag.maximum = def2.length;
- bag.length = def2.length;
- });
- inst._zod.check = (payload) => {
- const input = payload.value;
- const length = input.length;
- if (length === def2.length)
- return;
- const origin2 = getLengthableOrigin(input);
- const tooBig = length > def2.length;
- payload.issues.push({
- origin: origin2,
- ...tooBig ? { code: "too_big", maximum: def2.length } : { code: "too_small", minimum: def2.length },
- inclusive: true,
- exact: true,
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def2) => {
- var _a2, _b;
- $ZodCheck.init(inst, def2);
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- bag.format = def2.format;
- if (def2.pattern) {
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(def2.pattern);
- }
- });
- if (def2.pattern)
- (_a2 = inst._zod).check ?? (_a2.check = (payload) => {
- def2.pattern.lastIndex = 0;
- if (def2.pattern.test(payload.value))
- return;
- payload.issues.push({
- origin: "string",
- code: "invalid_format",
- format: def2.format,
- input: payload.value,
- ...def2.pattern ? { pattern: def2.pattern.toString() } : {},
- inst,
- continue: !def2.abort
- });
- });
- else
- (_b = inst._zod).check ?? (_b.check = () => {});
- });
- $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def2) => {
- $ZodCheckStringFormat.init(inst, def2);
- inst._zod.check = (payload) => {
- def2.pattern.lastIndex = 0;
- if (def2.pattern.test(payload.value))
- return;
- payload.issues.push({
- origin: "string",
- code: "invalid_format",
- format: "regex",
- input: payload.value,
- pattern: def2.pattern.toString(),
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def2) => {
- def2.pattern ?? (def2.pattern = lowercase);
- $ZodCheckStringFormat.init(inst, def2);
- });
- $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def2) => {
- def2.pattern ?? (def2.pattern = uppercase);
- $ZodCheckStringFormat.init(inst, def2);
- });
- $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- const escapedRegex = escapeRegex(def2.includes);
- const pattern = new RegExp(typeof def2.position === "number" ? `^.{${def2.position}}${escapedRegex}` : escapedRegex);
- def2.pattern = pattern;
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
- inst._zod.check = (payload) => {
- if (payload.value.includes(def2.includes, def2.position))
- return;
- payload.issues.push({
- origin: "string",
- code: "invalid_format",
- format: "includes",
- includes: def2.includes,
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- const pattern = new RegExp(`^${escapeRegex(def2.prefix)}.*`);
- def2.pattern ?? (def2.pattern = pattern);
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
- inst._zod.check = (payload) => {
- if (payload.value.startsWith(def2.prefix))
- return;
- payload.issues.push({
- origin: "string",
- code: "invalid_format",
- format: "starts_with",
- prefix: def2.prefix,
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- const pattern = new RegExp(`.*${escapeRegex(def2.suffix)}$`);
- def2.pattern ?? (def2.pattern = pattern);
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- bag.patterns ?? (bag.patterns = new Set);
- bag.patterns.add(pattern);
- });
- inst._zod.check = (payload) => {
- if (payload.value.endsWith(def2.suffix))
- return;
- payload.issues.push({
- origin: "string",
- code: "invalid_format",
- format: "ends_with",
- suffix: def2.suffix,
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- inst._zod.check = (payload) => {
- const result = def2.schema._zod.run({
- value: payload.value[def2.property],
- issues: []
- }, {});
- if (result instanceof Promise) {
- return result.then((result2) => handleCheckPropertyResult(result2, payload, def2.property));
- }
- handleCheckPropertyResult(result, payload, def2.property);
- return;
- };
- });
- $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- const mimeSet = new Set(def2.mime);
- inst._zod.onattach.push((inst2) => {
- inst2._zod.bag.mime = def2.mime;
- });
- inst._zod.check = (payload) => {
- if (mimeSet.has(payload.value.type))
- return;
- payload.issues.push({
- code: "invalid_value",
- values: def2.mime,
- input: payload.value.type,
- inst
- });
- };
- });
- $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- inst._zod.check = (payload) => {
- payload.value = def2.tx(payload.value);
- };
- });
-});
-
-// node_modules/zod/v4/core/doc.js
-class Doc {
- constructor(args = []) {
- this.content = [];
- this.indent = 0;
- if (this)
- this.args = args;
- }
- indented(fn) {
- this.indent += 1;
- fn(this);
- this.indent -= 1;
- }
- write(arg) {
- if (typeof arg === "function") {
- arg(this, { execution: "sync" });
- arg(this, { execution: "async" });
- return;
- }
- const content = arg;
- const lines = content.split(`
-`).filter((x2) => x2);
- const minIndent = Math.min(...lines.map((x2) => x2.length - x2.trimStart().length));
- const dedented = lines.map((x2) => x2.slice(minIndent)).map((x2) => " ".repeat(this.indent * 2) + x2);
- for (const line of dedented) {
- this.content.push(line);
- }
- }
- compile() {
- const F = Function;
- const args = this?.args;
- const content = this?.content ?? [``];
- const lines = [...content.map((x2) => ` ${x2}`)];
- return new F(...args, lines.join(`
-`));
- }
-}
-
-// node_modules/zod/v4/core/versions.js
-var version;
-var init_versions = __esm(() => {
- version = {
- major: 4,
- minor: 0,
- patch: 0
- };
-});
-
-// node_modules/zod/v4/core/schemas.js
-function isValidBase64(data) {
- if (data === "")
- return true;
- if (data.length % 4 !== 0)
- return false;
- try {
- atob(data);
- return true;
- } catch {
- return false;
- }
-}
-function isValidBase64URL(data) {
- if (!base64url.test(data))
- return false;
- const base642 = data.replace(/[-_]/g, (c5) => c5 === "-" ? "+" : "/");
- const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "=");
- return isValidBase64(padded);
-}
-function isValidJWT(token, algorithm = null) {
- try {
- const tokensParts = token.split(".");
- if (tokensParts.length !== 3)
- return false;
- const [header] = tokensParts;
- if (!header)
- return false;
- const parsedHeader = JSON.parse(atob(header));
- if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
- return false;
- if (!parsedHeader.alg)
- return false;
- if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
- return false;
- return true;
- } catch {
- return false;
- }
-}
-function handleArrayResult(result, final, index2) {
- if (result.issues.length) {
- final.issues.push(...prefixIssues(index2, result.issues));
- }
- final.value[index2] = result.value;
-}
-function handleObjectResult(result, final, key) {
- if (result.issues.length) {
- final.issues.push(...prefixIssues(key, result.issues));
- }
- final.value[key] = result.value;
-}
-function handleOptionalObjectResult(result, final, key, input) {
- if (result.issues.length) {
- if (input[key] === undefined) {
- if (key in input) {
- final.value[key] = undefined;
- } else {
- final.value[key] = result.value;
- }
- } else {
- final.issues.push(...prefixIssues(key, result.issues));
- }
- } else if (result.value === undefined) {
- if (key in input)
- final.value[key] = undefined;
- } else {
- final.value[key] = result.value;
- }
-}
-function handleUnionResults(results, final, inst, ctx) {
- for (const result of results) {
- if (result.issues.length === 0) {
- final.value = result.value;
- return final;
- }
- }
- final.issues.push({
- code: "invalid_union",
- input: final.value,
- inst,
- errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
- });
- return final;
-}
-function mergeValues(a2, b) {
- if (a2 === b) {
- return { valid: true, data: a2 };
- }
- if (a2 instanceof Date && b instanceof Date && +a2 === +b) {
- return { valid: true, data: a2 };
- }
- if (isPlainObject4(a2) && isPlainObject4(b)) {
- const bKeys = Object.keys(b);
- const sharedKeys = Object.keys(a2).filter((key) => bKeys.indexOf(key) !== -1);
- const newObj = { ...a2, ...b };
- for (const key of sharedKeys) {
- const sharedValue = mergeValues(a2[key], b[key]);
- if (!sharedValue.valid) {
- return {
- valid: false,
- mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
- };
- }
- newObj[key] = sharedValue.data;
- }
- return { valid: true, data: newObj };
- }
- if (Array.isArray(a2) && Array.isArray(b)) {
- if (a2.length !== b.length) {
- return { valid: false, mergeErrorPath: [] };
- }
- const newArray = [];
- for (let index2 = 0;index2 < a2.length; index2++) {
- const itemA = a2[index2];
- const itemB = b[index2];
- const sharedValue = mergeValues(itemA, itemB);
- if (!sharedValue.valid) {
- return {
- valid: false,
- mergeErrorPath: [index2, ...sharedValue.mergeErrorPath]
- };
- }
- newArray.push(sharedValue.data);
- }
- return { valid: true, data: newArray };
- }
- return { valid: false, mergeErrorPath: [] };
-}
-function handleIntersectionResults(result, left, right) {
- if (left.issues.length) {
- result.issues.push(...left.issues);
- }
- if (right.issues.length) {
- result.issues.push(...right.issues);
- }
- if (aborted2(result))
- return result;
- const merged = mergeValues(left.value, right.value);
- if (!merged.valid) {
- throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
- }
- result.value = merged.data;
- return result;
-}
-function handleTupleResult(result, final, index2) {
- if (result.issues.length) {
- final.issues.push(...prefixIssues(index2, result.issues));
- }
- final.value[index2] = result.value;
-}
-function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
- if (keyResult.issues.length) {
- if (propertyKeyTypes.has(typeof key)) {
- final.issues.push(...prefixIssues(key, keyResult.issues));
- } else {
- final.issues.push({
- origin: "map",
- code: "invalid_key",
- input,
- inst,
- issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
- });
- }
- }
- if (valueResult.issues.length) {
- if (propertyKeyTypes.has(typeof key)) {
- final.issues.push(...prefixIssues(key, valueResult.issues));
- } else {
- final.issues.push({
- origin: "map",
- code: "invalid_element",
- input,
- inst,
- key,
- issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
- });
- }
- }
- final.value.set(keyResult.value, valueResult.value);
-}
-function handleSetResult(result, final) {
- if (result.issues.length) {
- final.issues.push(...result.issues);
- }
- final.value.add(result.value);
-}
-function handleDefaultResult(payload, def2) {
- if (payload.value === undefined) {
- payload.value = def2.defaultValue;
- }
- return payload;
-}
-function handleNonOptionalResult(payload, inst) {
- if (!payload.issues.length && payload.value === undefined) {
- payload.issues.push({
- code: "invalid_type",
- expected: "nonoptional",
- input: payload.value,
- inst
- });
- }
- return payload;
-}
-function handlePipeResult(left, def2, ctx) {
- if (aborted2(left)) {
- return left;
- }
- return def2.out._zod.run({ value: left.value, issues: left.issues }, ctx);
-}
-function handleReadonlyResult(payload) {
- payload.value = Object.freeze(payload.value);
- return payload;
-}
-function handleRefineResult(result, payload, input, inst) {
- if (!result) {
- const _iss = {
- code: "custom",
- input,
- inst,
- path: [...inst._zod.def.path ?? []],
- continue: !inst._zod.def.abort
- };
- if (inst._zod.def.params)
- _iss.params = inst._zod.def.params;
- payload.issues.push(issue(_iss));
- }
-}
-var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodReadonly, $ZodTemplateLiteral, $ZodPromise, $ZodLazy, $ZodCustom;
-var init_schemas = __esm(() => {
- init_checks();
- init_core4();
- init_parse();
- init_regexes();
- init_util2();
- init_versions();
- init_util2();
- $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def2) => {
- var _a2;
- inst ?? (inst = {});
- inst._zod.def = def2;
- inst._zod.bag = inst._zod.bag || {};
- inst._zod.version = version;
- const checks = [...inst._zod.def.checks ?? []];
- if (inst._zod.traits.has("$ZodCheck")) {
- checks.unshift(inst);
- }
- for (const ch of checks) {
- for (const fn of ch._zod.onattach) {
- fn(inst);
- }
- }
- if (checks.length === 0) {
- (_a2 = inst._zod).deferred ?? (_a2.deferred = []);
- inst._zod.deferred?.push(() => {
- inst._zod.run = inst._zod.parse;
- });
- } else {
- const runChecks = (payload, checks2, ctx) => {
- let isAborted = aborted2(payload);
- let asyncResult;
- for (const ch of checks2) {
- if (ch._zod.def.when) {
- const shouldRun = ch._zod.def.when(payload);
- if (!shouldRun)
- continue;
- } else if (isAborted) {
- continue;
- }
- const currLen = payload.issues.length;
- const _ = ch._zod.check(payload);
- if (_ instanceof Promise && ctx?.async === false) {
- throw new $ZodAsyncError;
- }
- if (asyncResult || _ instanceof Promise) {
- asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
- await _;
- const nextLen = payload.issues.length;
- if (nextLen === currLen)
- return;
- if (!isAborted)
- isAborted = aborted2(payload, currLen);
- });
- } else {
- const nextLen = payload.issues.length;
- if (nextLen === currLen)
- continue;
- if (!isAborted)
- isAborted = aborted2(payload, currLen);
- }
- }
- if (asyncResult) {
- return asyncResult.then(() => {
- return payload;
- });
- }
- return payload;
- };
- inst._zod.run = (payload, ctx) => {
- const result = inst._zod.parse(payload, ctx);
- if (result instanceof Promise) {
- if (ctx.async === false)
- throw new $ZodAsyncError;
- return result.then((result2) => runChecks(result2, checks, ctx));
- }
- return runChecks(result, checks, ctx);
- };
- }
- inst["~standard"] = {
- validate: (value) => {
- try {
- const r = safeParse(inst, value);
- return r.success ? { value: r.data } : { issues: r.error?.issues };
- } catch (_) {
- return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
- }
- },
- vendor: "zod",
- version: 1
- };
- });
- $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
- inst._zod.parse = (payload, _) => {
- if (def2.coerce)
- try {
- payload.value = String(payload.value);
- } catch (_2) {}
- if (typeof payload.value === "string")
- return payload;
- payload.issues.push({
- expected: "string",
- code: "invalid_type",
- input: payload.value,
- inst
- });
- return payload;
- };
- });
- $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def2) => {
- $ZodCheckStringFormat.init(inst, def2);
- $ZodString.init(inst, def2);
- });
- $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def2) => {
- def2.pattern ?? (def2.pattern = guid);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def2) => {
- if (def2.version) {
- const versionMap = {
- v1: 1,
- v2: 2,
- v3: 3,
- v4: 4,
- v5: 5,
- v6: 6,
- v7: 7,
- v8: 8
- };
- const v = versionMap[def2.version];
- if (v === undefined)
- throw new Error(`Invalid UUID version: "${def2.version}"`);
- def2.pattern ?? (def2.pattern = uuid(v));
- } else
- def2.pattern ?? (def2.pattern = uuid());
- $ZodStringFormat.init(inst, def2);
- });
- $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def2) => {
- def2.pattern ?? (def2.pattern = email);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def2) => {
- $ZodStringFormat.init(inst, def2);
- inst._zod.check = (payload) => {
- try {
- const orig = payload.value;
- const url2 = new URL(orig);
- const href = url2.href;
- if (def2.hostname) {
- def2.hostname.lastIndex = 0;
- if (!def2.hostname.test(url2.hostname)) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- note: "Invalid hostname",
- pattern: hostname.source,
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- }
- }
- if (def2.protocol) {
- def2.protocol.lastIndex = 0;
- if (!def2.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- note: "Invalid protocol",
- pattern: def2.protocol.source,
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- }
- }
- if (!orig.endsWith("/") && href.endsWith("/")) {
- payload.value = href.slice(0, -1);
- } else {
- payload.value = href;
- }
- return;
- } catch (_) {
- payload.issues.push({
- code: "invalid_format",
- format: "url",
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- }
- };
- });
- $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def2) => {
- def2.pattern ?? (def2.pattern = emoji());
- $ZodStringFormat.init(inst, def2);
- });
- $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def2) => {
- def2.pattern ?? (def2.pattern = nanoid);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def2) => {
- def2.pattern ?? (def2.pattern = cuid);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def2) => {
- def2.pattern ?? (def2.pattern = cuid2);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def2) => {
- def2.pattern ?? (def2.pattern = ulid);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def2) => {
- def2.pattern ?? (def2.pattern = xid);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def2) => {
- def2.pattern ?? (def2.pattern = ksuid);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def2) => {
- def2.pattern ?? (def2.pattern = datetime(def2));
- $ZodStringFormat.init(inst, def2);
- });
- $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def2) => {
- def2.pattern ?? (def2.pattern = date);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def2) => {
- def2.pattern ?? (def2.pattern = time(def2));
- $ZodStringFormat.init(inst, def2);
- });
- $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def2) => {
- def2.pattern ?? (def2.pattern = duration);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def2) => {
- def2.pattern ?? (def2.pattern = ipv4);
- $ZodStringFormat.init(inst, def2);
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- bag.format = `ipv4`;
- });
- });
- $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def2) => {
- def2.pattern ?? (def2.pattern = ipv6);
- $ZodStringFormat.init(inst, def2);
- inst._zod.onattach.push((inst2) => {
- const bag = inst2._zod.bag;
- bag.format = `ipv6`;
- });
- inst._zod.check = (payload) => {
- try {
- new URL(`http://[${payload.value}]`);
- } catch {
- payload.issues.push({
- code: "invalid_format",
- format: "ipv6",
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- }
- };
- });
- $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def2) => {
- def2.pattern ?? (def2.pattern = cidrv4);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def2) => {
- def2.pattern ?? (def2.pattern = cidrv6);
- $ZodStringFormat.init(inst, def2);
- inst._zod.check = (payload) => {
- const [address, prefix] = payload.value.split("/");
- try {
- if (!prefix)
- throw new Error;
- const prefixNum = Number(prefix);
- if (`${prefixNum}` !== prefix)
- throw new Error;
- if (prefixNum < 0 || prefixNum > 128)
- throw new Error;
- new URL(`http://[${address}]`);
- } catch {
- payload.issues.push({
- code: "invalid_format",
- format: "cidrv6",
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- }
- };
- });
- $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def2) => {
- def2.pattern ?? (def2.pattern = base64);
- $ZodStringFormat.init(inst, def2);
- inst._zod.onattach.push((inst2) => {
- inst2._zod.bag.contentEncoding = "base64";
- });
- inst._zod.check = (payload) => {
- if (isValidBase64(payload.value))
- return;
- payload.issues.push({
- code: "invalid_format",
- format: "base64",
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def2) => {
- def2.pattern ?? (def2.pattern = base64url);
- $ZodStringFormat.init(inst, def2);
- inst._zod.onattach.push((inst2) => {
- inst2._zod.bag.contentEncoding = "base64url";
- });
- inst._zod.check = (payload) => {
- if (isValidBase64URL(payload.value))
- return;
- payload.issues.push({
- code: "invalid_format",
- format: "base64url",
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def2) => {
- def2.pattern ?? (def2.pattern = e164);
- $ZodStringFormat.init(inst, def2);
- });
- $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def2) => {
- $ZodStringFormat.init(inst, def2);
- inst._zod.check = (payload) => {
- if (isValidJWT(payload.value, def2.alg))
- return;
- payload.issues.push({
- code: "invalid_format",
- format: "jwt",
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def2) => {
- $ZodStringFormat.init(inst, def2);
- inst._zod.check = (payload) => {
- if (def2.fn(payload.value))
- return;
- payload.issues.push({
- code: "invalid_format",
- format: def2.format,
- input: payload.value,
- inst,
- continue: !def2.abort
- });
- };
- });
- $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.pattern = inst._zod.bag.pattern ?? number;
- inst._zod.parse = (payload, _ctx) => {
- if (def2.coerce)
- try {
- payload.value = Number(payload.value);
- } catch (_) {}
- const input = payload.value;
- if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
- return payload;
- }
- const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : undefined : undefined;
- payload.issues.push({
- expected: "number",
- code: "invalid_type",
- input,
- inst,
- ...received ? { received } : {}
- });
- return payload;
- };
- });
- $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def2) => {
- $ZodCheckNumberFormat.init(inst, def2);
- $ZodNumber.init(inst, def2);
- });
- $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.pattern = boolean;
- inst._zod.parse = (payload, _ctx) => {
- if (def2.coerce)
- try {
- payload.value = Boolean(payload.value);
- } catch (_) {}
- const input = payload.value;
- if (typeof input === "boolean")
- return payload;
- payload.issues.push({
- expected: "boolean",
- code: "invalid_type",
- input,
- inst
- });
- return payload;
- };
- });
- $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.pattern = bigint;
- inst._zod.parse = (payload, _ctx) => {
- if (def2.coerce)
- try {
- payload.value = BigInt(payload.value);
- } catch (_) {}
- if (typeof payload.value === "bigint")
- return payload;
- payload.issues.push({
- expected: "bigint",
- code: "invalid_type",
- input: payload.value,
- inst
- });
- return payload;
- };
- });
- $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def2) => {
- $ZodCheckBigIntFormat.init(inst, def2);
- $ZodBigInt.init(inst, def2);
- });
- $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, _ctx) => {
- const input = payload.value;
- if (typeof input === "symbol")
- return payload;
- payload.issues.push({
- expected: "symbol",
- code: "invalid_type",
- input,
- inst
- });
- return payload;
- };
- });
- $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.pattern = _undefined;
- inst._zod.values = new Set([undefined]);
- inst._zod.optin = "optional";
- inst._zod.optout = "optional";
- inst._zod.parse = (payload, _ctx) => {
- const input = payload.value;
- if (typeof input === "undefined")
- return payload;
- payload.issues.push({
- expected: "undefined",
- code: "invalid_type",
- input,
- inst
- });
- return payload;
- };
- });
- $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.pattern = _null;
- inst._zod.values = new Set([null]);
- inst._zod.parse = (payload, _ctx) => {
- const input = payload.value;
- if (input === null)
- return payload;
- payload.issues.push({
- expected: "null",
- code: "invalid_type",
- input,
- inst
- });
- return payload;
- };
- });
- $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload) => payload;
- });
- $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload) => payload;
- });
- $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, _ctx) => {
- payload.issues.push({
- expected: "never",
- code: "invalid_type",
- input: payload.value,
- inst
- });
- return payload;
- };
- });
- $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, _ctx) => {
- const input = payload.value;
- if (typeof input === "undefined")
- return payload;
- payload.issues.push({
- expected: "void",
- code: "invalid_type",
- input,
- inst
- });
- return payload;
- };
- });
- $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, _ctx) => {
- if (def2.coerce) {
- try {
- payload.value = new Date(payload.value);
- } catch (_err) {}
- }
- const input = payload.value;
- const isDate2 = input instanceof Date;
- const isValidDate = isDate2 && !Number.isNaN(input.getTime());
- if (isValidDate)
- return payload;
- payload.issues.push({
- expected: "date",
- code: "invalid_type",
- input,
- ...isDate2 ? { received: "Invalid Date" } : {},
- inst
- });
- return payload;
- };
- });
- $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, ctx) => {
- const input = payload.value;
- if (!Array.isArray(input)) {
- payload.issues.push({
- expected: "array",
- code: "invalid_type",
- input,
- inst
- });
- return payload;
- }
- payload.value = Array(input.length);
- const proms = [];
- for (let i2 = 0;i2 < input.length; i2++) {
- const item = input[i2];
- const result = def2.element._zod.run({
- value: item,
- issues: []
- }, ctx);
- if (result instanceof Promise) {
- proms.push(result.then((result2) => handleArrayResult(result2, payload, i2)));
- } else {
- handleArrayResult(result, payload, i2);
- }
- }
- if (proms.length) {
- return Promise.all(proms).then(() => payload);
- }
- return payload;
- };
- });
- $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def2) => {
- $ZodType.init(inst, def2);
- const _normalized = cached(() => {
- const keys2 = Object.keys(def2.shape);
- for (const k of keys2) {
- if (!(def2.shape[k] instanceof $ZodType)) {
- throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
- }
- }
- const okeys = optionalKeys(def2.shape);
- return {
- shape: def2.shape,
- keys: keys2,
- keySet: new Set(keys2),
- numKeys: keys2.length,
- optionalKeys: new Set(okeys)
- };
- });
- defineLazy(inst._zod, "propValues", () => {
- const shape = def2.shape;
- const propValues = {};
- for (const key in shape) {
- const field = shape[key]._zod;
- if (field.values) {
- propValues[key] ?? (propValues[key] = new Set);
- for (const v of field.values)
- propValues[key].add(v);
- }
- }
- return propValues;
- });
- const generateFastpass = (shape) => {
- const doc = new Doc(["shape", "payload", "ctx"]);
- const normalized = _normalized.value;
- const parseStr = (key) => {
- const k = esc(key);
- return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
- };
- doc.write(`const input = payload.value;`);
- const ids = Object.create(null);
- let counter = 0;
- for (const key of normalized.keys) {
- ids[key] = `key_${counter++}`;
- }
- doc.write(`const newResult = {}`);
- for (const key of normalized.keys) {
- if (normalized.optionalKeys.has(key)) {
- const id = ids[key];
- doc.write(`const ${id} = ${parseStr(key)};`);
- const k = esc(key);
- doc.write(`
- if (${id}.issues.length) {
- if (input[${k}] === undefined) {
- if (${k} in input) {
- newResult[${k}] = undefined;
- }
- } else {
- payload.issues = payload.issues.concat(
- ${id}.issues.map((iss) => ({
- ...iss,
- path: iss.path ? [${k}, ...iss.path] : [${k}],
- }))
- );
- }
- } else if (${id}.value === undefined) {
- if (${k} in input) newResult[${k}] = undefined;
- } else {
- newResult[${k}] = ${id}.value;
- }
- `);
- } else {
- const id = ids[key];
- doc.write(`const ${id} = ${parseStr(key)};`);
- doc.write(`
- if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
- ...iss,
- path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
- })));`);
- doc.write(`newResult[${esc(key)}] = ${id}.value`);
- }
- }
- doc.write(`payload.value = newResult;`);
- doc.write(`return payload;`);
- const fn = doc.compile();
- return (payload, ctx) => fn(shape, payload, ctx);
- };
- let fastpass;
- const isObject5 = isObject4;
- const jit = !globalConfig.jitless;
- const allowsEval2 = allowsEval;
- const fastEnabled = jit && allowsEval2.value;
- const catchall = def2.catchall;
- let value;
- inst._zod.parse = (payload, ctx) => {
- value ?? (value = _normalized.value);
- const input = payload.value;
- if (!isObject5(input)) {
- payload.issues.push({
- expected: "object",
- code: "invalid_type",
- input,
- inst
- });
- return payload;
- }
- const proms = [];
- if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
- if (!fastpass)
- fastpass = generateFastpass(def2.shape);
- payload = fastpass(payload, ctx);
- } else {
- payload.value = {};
- const shape = value.shape;
- for (const key of value.keys) {
- const el = shape[key];
- const r = el._zod.run({ value: input[key], issues: [] }, ctx);
- const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
- if (r instanceof Promise) {
- proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key)));
- } else if (isOptional) {
- handleOptionalObjectResult(r, payload, key, input);
- } else {
- handleObjectResult(r, payload, key);
- }
- }
- }
- if (!catchall) {
- return proms.length ? Promise.all(proms).then(() => payload) : payload;
- }
- const unrecognized = [];
- const keySet = value.keySet;
- const _catchall = catchall._zod;
- const t = _catchall.def.type;
- for (const key of Object.keys(input)) {
- if (keySet.has(key))
- continue;
- if (t === "never") {
- unrecognized.push(key);
- continue;
- }
- const r = _catchall.run({ value: input[key], issues: [] }, ctx);
- if (r instanceof Promise) {
- proms.push(r.then((r2) => handleObjectResult(r2, payload, key)));
- } else {
- handleObjectResult(r, payload, key);
- }
- }
- if (unrecognized.length) {
- payload.issues.push({
- code: "unrecognized_keys",
- keys: unrecognized,
- input,
- inst
- });
- }
- if (!proms.length)
- return payload;
- return Promise.all(proms).then(() => {
- return payload;
- });
- };
- });
- $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def2) => {
- $ZodType.init(inst, def2);
- defineLazy(inst._zod, "optin", () => def2.options.some((o2) => o2._zod.optin === "optional") ? "optional" : undefined);
- defineLazy(inst._zod, "optout", () => def2.options.some((o2) => o2._zod.optout === "optional") ? "optional" : undefined);
- defineLazy(inst._zod, "values", () => {
- if (def2.options.every((o2) => o2._zod.values)) {
- return new Set(def2.options.flatMap((option) => Array.from(option._zod.values)));
- }
- return;
- });
- defineLazy(inst._zod, "pattern", () => {
- if (def2.options.every((o2) => o2._zod.pattern)) {
- const patterns = def2.options.map((o2) => o2._zod.pattern);
- return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
- }
- return;
- });
- inst._zod.parse = (payload, ctx) => {
- let async = false;
- const results = [];
- for (const option of def2.options) {
- const result = option._zod.run({
- value: payload.value,
- issues: []
- }, ctx);
- if (result instanceof Promise) {
- results.push(result);
- async = true;
- } else {
- if (result.issues.length === 0)
- return result;
- results.push(result);
- }
- }
- if (!async)
- return handleUnionResults(results, payload, inst, ctx);
- return Promise.all(results).then((results2) => {
- return handleUnionResults(results2, payload, inst, ctx);
- });
- };
- });
- $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def2) => {
- $ZodUnion.init(inst, def2);
- const _super = inst._zod.parse;
- defineLazy(inst._zod, "propValues", () => {
- const propValues = {};
- for (const option of def2.options) {
- const pv = option._zod.propValues;
- if (!pv || Object.keys(pv).length === 0)
- throw new Error(`Invalid discriminated union option at index "${def2.options.indexOf(option)}"`);
- for (const [k, v] of Object.entries(pv)) {
- if (!propValues[k])
- propValues[k] = new Set;
- for (const val of v) {
- propValues[k].add(val);
- }
- }
- }
- return propValues;
- });
- const disc = cached(() => {
- const opts = def2.options;
- const map = new Map;
- for (const o2 of opts) {
- const values = o2._zod.propValues[def2.discriminator];
- if (!values || values.size === 0)
- throw new Error(`Invalid discriminated union option at index "${def2.options.indexOf(o2)}"`);
- for (const v of values) {
- if (map.has(v)) {
- throw new Error(`Duplicate discriminator value "${String(v)}"`);
- }
- map.set(v, o2);
- }
- }
- return map;
- });
- inst._zod.parse = (payload, ctx) => {
- const input = payload.value;
- if (!isObject4(input)) {
- payload.issues.push({
- code: "invalid_type",
- expected: "object",
- input,
- inst
- });
- return payload;
- }
- const opt = disc.value.get(input?.[def2.discriminator]);
- if (opt) {
- return opt._zod.run(payload, ctx);
- }
- if (def2.unionFallback) {
- return _super(payload, ctx);
- }
- payload.issues.push({
- code: "invalid_union",
- errors: [],
- note: "No matching discriminator",
- input,
- path: [def2.discriminator],
- inst
- });
- return payload;
- };
- });
- $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, ctx) => {
- const input = payload.value;
- const left = def2.left._zod.run({ value: input, issues: [] }, ctx);
- const right = def2.right._zod.run({ value: input, issues: [] }, ctx);
- const async = left instanceof Promise || right instanceof Promise;
- if (async) {
- return Promise.all([left, right]).then(([left2, right2]) => {
- return handleIntersectionResults(payload, left2, right2);
- });
- }
- return handleIntersectionResults(payload, left, right);
- };
- });
- $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def2) => {
- $ZodType.init(inst, def2);
- const items = def2.items;
- const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional");
- inst._zod.parse = (payload, ctx) => {
- const input = payload.value;
- if (!Array.isArray(input)) {
- payload.issues.push({
- input,
- inst,
- expected: "tuple",
- code: "invalid_type"
- });
- return payload;
- }
- payload.value = [];
- const proms = [];
- if (!def2.rest) {
- const tooBig = input.length > items.length;
- const tooSmall = input.length < optStart - 1;
- if (tooBig || tooSmall) {
- payload.issues.push({
- input,
- inst,
- origin: "array",
- ...tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }
- });
- return payload;
- }
- }
- let i2 = -1;
- for (const item of items) {
- i2++;
- if (i2 >= input.length) {
- if (i2 >= optStart)
- continue;
- }
- const result = item._zod.run({
- value: input[i2],
- issues: []
- }, ctx);
- if (result instanceof Promise) {
- proms.push(result.then((result2) => handleTupleResult(result2, payload, i2)));
- } else {
- handleTupleResult(result, payload, i2);
- }
- }
- if (def2.rest) {
- const rest = input.slice(items.length);
- for (const el of rest) {
- i2++;
- const result = def2.rest._zod.run({
- value: el,
- issues: []
- }, ctx);
- if (result instanceof Promise) {
- proms.push(result.then((result2) => handleTupleResult(result2, payload, i2)));
- } else {
- handleTupleResult(result, payload, i2);
- }
- }
- }
- if (proms.length)
- return Promise.all(proms).then(() => payload);
- return payload;
- };
- });
- $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, ctx) => {
- const input = payload.value;
- if (!isPlainObject4(input)) {
- payload.issues.push({
- expected: "record",
- code: "invalid_type",
- input,
- inst
- });
- return payload;
- }
- const proms = [];
- if (def2.keyType._zod.values) {
- const values = def2.keyType._zod.values;
- payload.value = {};
- for (const key of values) {
- if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
- const result = def2.valueType._zod.run({ value: input[key], issues: [] }, ctx);
- if (result instanceof Promise) {
- proms.push(result.then((result2) => {
- if (result2.issues.length) {
- payload.issues.push(...prefixIssues(key, result2.issues));
- }
- payload.value[key] = result2.value;
- }));
- } else {
- if (result.issues.length) {
- payload.issues.push(...prefixIssues(key, result.issues));
- }
- payload.value[key] = result.value;
- }
- }
- }
- let unrecognized;
- for (const key in input) {
- if (!values.has(key)) {
- unrecognized = unrecognized ?? [];
- unrecognized.push(key);
- }
- }
- if (unrecognized && unrecognized.length > 0) {
- payload.issues.push({
- code: "unrecognized_keys",
- input,
- inst,
- keys: unrecognized
- });
- }
- } else {
- payload.value = {};
- for (const key of Reflect.ownKeys(input)) {
- if (key === "__proto__")
- continue;
- const keyResult = def2.keyType._zod.run({ value: key, issues: [] }, ctx);
- if (keyResult instanceof Promise) {
- throw new Error("Async schemas not supported in object keys currently");
- }
- if (keyResult.issues.length) {
- payload.issues.push({
- origin: "record",
- code: "invalid_key",
- issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
- input: key,
- path: [key],
- inst
- });
- payload.value[keyResult.value] = keyResult.value;
- continue;
- }
- const result = def2.valueType._zod.run({ value: input[key], issues: [] }, ctx);
- if (result instanceof Promise) {
- proms.push(result.then((result2) => {
- if (result2.issues.length) {
- payload.issues.push(...prefixIssues(key, result2.issues));
- }
- payload.value[keyResult.value] = result2.value;
- }));
- } else {
- if (result.issues.length) {
- payload.issues.push(...prefixIssues(key, result.issues));
- }
- payload.value[keyResult.value] = result.value;
- }
- }
- }
- if (proms.length) {
- return Promise.all(proms).then(() => payload);
- }
- return payload;
- };
- });
- $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, ctx) => {
- const input = payload.value;
- if (!(input instanceof Map)) {
- payload.issues.push({
- expected: "map",
- code: "invalid_type",
- input,
- inst
- });
- return payload;
- }
- const proms = [];
- payload.value = new Map;
- for (const [key, value] of input) {
- const keyResult = def2.keyType._zod.run({ value: key, issues: [] }, ctx);
- const valueResult = def2.valueType._zod.run({ value, issues: [] }, ctx);
- if (keyResult instanceof Promise || valueResult instanceof Promise) {
- proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => {
- handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx);
- }));
- } else {
- handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
- }
- }
- if (proms.length)
- return Promise.all(proms).then(() => payload);
- return payload;
- };
- });
- $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, ctx) => {
- const input = payload.value;
- if (!(input instanceof Set)) {
- payload.issues.push({
- input,
- inst,
- expected: "set",
- code: "invalid_type"
- });
- return payload;
- }
- const proms = [];
- payload.value = new Set;
- for (const item of input) {
- const result = def2.valueType._zod.run({ value: item, issues: [] }, ctx);
- if (result instanceof Promise) {
- proms.push(result.then((result2) => handleSetResult(result2, payload)));
- } else
- handleSetResult(result, payload);
- }
- if (proms.length)
- return Promise.all(proms).then(() => payload);
- return payload;
- };
- });
- $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def2) => {
- $ZodType.init(inst, def2);
- const values = getEnumValues(def2.entries);
- inst._zod.values = new Set(values);
- inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o2) => typeof o2 === "string" ? escapeRegex(o2) : o2.toString()).join("|")})$`);
- inst._zod.parse = (payload, _ctx) => {
- const input = payload.value;
- if (inst._zod.values.has(input)) {
- return payload;
- }
- payload.issues.push({
- code: "invalid_value",
- values,
- input,
- inst
- });
- return payload;
- };
- });
- $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.values = new Set(def2.values);
- inst._zod.pattern = new RegExp(`^(${def2.values.map((o2) => typeof o2 === "string" ? escapeRegex(o2) : o2 ? o2.toString() : String(o2)).join("|")})$`);
- inst._zod.parse = (payload, _ctx) => {
- const input = payload.value;
- if (inst._zod.values.has(input)) {
- return payload;
- }
- payload.issues.push({
- code: "invalid_value",
- values: def2.values,
- input,
- inst
- });
- return payload;
- };
- });
- $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, _ctx) => {
- const input = payload.value;
- if (input instanceof File)
- return payload;
- payload.issues.push({
- expected: "file",
- code: "invalid_type",
- input,
- inst
- });
- return payload;
- };
- });
- $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, _ctx) => {
- const _out = def2.transform(payload.value, payload);
- if (_ctx.async) {
- const output = _out instanceof Promise ? _out : Promise.resolve(_out);
- return output.then((output2) => {
- payload.value = output2;
- return payload;
- });
- }
- if (_out instanceof Promise) {
- throw new $ZodAsyncError;
- }
- payload.value = _out;
- return payload;
- };
- });
- $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.optin = "optional";
- inst._zod.optout = "optional";
- defineLazy(inst._zod, "values", () => {
- return def2.innerType._zod.values ? new Set([...def2.innerType._zod.values, undefined]) : undefined;
- });
- defineLazy(inst._zod, "pattern", () => {
- const pattern = def2.innerType._zod.pattern;
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
- });
- inst._zod.parse = (payload, ctx) => {
- if (def2.innerType._zod.optin === "optional") {
- return def2.innerType._zod.run(payload, ctx);
- }
- if (payload.value === undefined) {
- return payload;
- }
- return def2.innerType._zod.run(payload, ctx);
- };
- });
- $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def2) => {
- $ZodType.init(inst, def2);
- defineLazy(inst._zod, "optin", () => def2.innerType._zod.optin);
- defineLazy(inst._zod, "optout", () => def2.innerType._zod.optout);
- defineLazy(inst._zod, "pattern", () => {
- const pattern = def2.innerType._zod.pattern;
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined;
- });
- defineLazy(inst._zod, "values", () => {
- return def2.innerType._zod.values ? new Set([...def2.innerType._zod.values, null]) : undefined;
- });
- inst._zod.parse = (payload, ctx) => {
- if (payload.value === null)
- return payload;
- return def2.innerType._zod.run(payload, ctx);
- };
- });
- $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "values", () => def2.innerType._zod.values);
- inst._zod.parse = (payload, ctx) => {
- if (payload.value === undefined) {
- payload.value = def2.defaultValue;
- return payload;
- }
- const result = def2.innerType._zod.run(payload, ctx);
- if (result instanceof Promise) {
- return result.then((result2) => handleDefaultResult(result2, def2));
- }
- return handleDefaultResult(result, def2);
- };
- });
- $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "values", () => def2.innerType._zod.values);
- inst._zod.parse = (payload, ctx) => {
- if (payload.value === undefined) {
- payload.value = def2.defaultValue;
- }
- return def2.innerType._zod.run(payload, ctx);
- };
- });
- $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def2) => {
- $ZodType.init(inst, def2);
- defineLazy(inst._zod, "values", () => {
- const v = def2.innerType._zod.values;
- return v ? new Set([...v].filter((x2) => x2 !== undefined)) : undefined;
- });
- inst._zod.parse = (payload, ctx) => {
- const result = def2.innerType._zod.run(payload, ctx);
- if (result instanceof Promise) {
- return result.then((result2) => handleNonOptionalResult(result2, inst));
- }
- return handleNonOptionalResult(result, inst);
- };
- });
- $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, ctx) => {
- const result = def2.innerType._zod.run(payload, ctx);
- if (result instanceof Promise) {
- return result.then((result2) => {
- payload.value = result2.issues.length === 0;
- return payload;
- });
- }
- payload.value = result.issues.length === 0;
- return payload;
- };
- });
- $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.optin = "optional";
- defineLazy(inst._zod, "optout", () => def2.innerType._zod.optout);
- defineLazy(inst._zod, "values", () => def2.innerType._zod.values);
- inst._zod.parse = (payload, ctx) => {
- const result = def2.innerType._zod.run(payload, ctx);
- if (result instanceof Promise) {
- return result.then((result2) => {
- payload.value = result2.value;
- if (result2.issues.length) {
- payload.value = def2.catchValue({
- ...payload,
- error: {
- issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
- },
- input: payload.value
- });
- payload.issues = [];
- }
- return payload;
- });
- }
- payload.value = result.value;
- if (result.issues.length) {
- payload.value = def2.catchValue({
- ...payload,
- error: {
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
- },
- input: payload.value
- });
- payload.issues = [];
- }
- return payload;
- };
- });
- $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, _ctx) => {
- if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
- payload.issues.push({
- input: payload.value,
- inst,
- expected: "nan",
- code: "invalid_type"
- });
- return payload;
- }
- return payload;
- };
- });
- $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def2) => {
- $ZodType.init(inst, def2);
- defineLazy(inst._zod, "values", () => def2.in._zod.values);
- defineLazy(inst._zod, "optin", () => def2.in._zod.optin);
- defineLazy(inst._zod, "optout", () => def2.out._zod.optout);
- inst._zod.parse = (payload, ctx) => {
- const left = def2.in._zod.run(payload, ctx);
- if (left instanceof Promise) {
- return left.then((left2) => handlePipeResult(left2, def2, ctx));
- }
- return handlePipeResult(left, def2, ctx);
- };
- });
- $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def2) => {
- $ZodType.init(inst, def2);
- defineLazy(inst._zod, "propValues", () => def2.innerType._zod.propValues);
- defineLazy(inst._zod, "values", () => def2.innerType._zod.values);
- defineLazy(inst._zod, "optin", () => def2.innerType._zod.optin);
- defineLazy(inst._zod, "optout", () => def2.innerType._zod.optout);
- inst._zod.parse = (payload, ctx) => {
- const result = def2.innerType._zod.run(payload, ctx);
- if (result instanceof Promise) {
- return result.then(handleReadonlyResult);
- }
- return handleReadonlyResult(result);
- };
- });
- $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def2) => {
- $ZodType.init(inst, def2);
- const regexParts = [];
- for (const part of def2.parts) {
- if (part instanceof $ZodType) {
- if (!part._zod.pattern) {
- throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
- }
- const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
- if (!source)
- throw new Error(`Invalid template literal part: ${part._zod.traits}`);
- const start = source.startsWith("^") ? 1 : 0;
- const end = source.endsWith("$") ? source.length - 1 : source.length;
- regexParts.push(source.slice(start, end));
- } else if (part === null || primitiveTypes.has(typeof part)) {
- regexParts.push(escapeRegex(`${part}`));
- } else {
- throw new Error(`Invalid template literal part: ${part}`);
- }
- }
- inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
- inst._zod.parse = (payload, _ctx) => {
- if (typeof payload.value !== "string") {
- payload.issues.push({
- input: payload.value,
- inst,
- expected: "template_literal",
- code: "invalid_type"
- });
- return payload;
- }
- inst._zod.pattern.lastIndex = 0;
- if (!inst._zod.pattern.test(payload.value)) {
- payload.issues.push({
- input: payload.value,
- inst,
- code: "invalid_format",
- format: "template_literal",
- pattern: inst._zod.pattern.source
- });
- return payload;
- }
- return payload;
- };
- });
- $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, ctx) => {
- return Promise.resolve(payload.value).then((inner) => def2.innerType._zod.run({ value: inner, issues: [] }, ctx));
- };
- });
- $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def2) => {
- $ZodType.init(inst, def2);
- defineLazy(inst._zod, "innerType", () => def2.getter());
- defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern);
- defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues);
- defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin);
- defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout);
- inst._zod.parse = (payload, ctx) => {
- const inner = inst._zod.innerType;
- return inner._zod.run(payload, ctx);
- };
- });
- $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def2) => {
- $ZodCheck.init(inst, def2);
- $ZodType.init(inst, def2);
- inst._zod.parse = (payload, _) => {
- return payload;
- };
- inst._zod.check = (payload) => {
- const input = payload.value;
- const r = def2.fn(input);
- if (r instanceof Promise) {
- return r.then((r2) => handleRefineResult(r2, payload, input, inst));
- }
- handleRefineResult(r, payload, input, inst);
- return;
- };
- });
-});
-
-// node_modules/zod/v4/locales/ar.js
-function ar_default() {
- return {
- localeError: error()
- };
-}
-var error = () => {
- const Sizable = {
- string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
- file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
- array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
- set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "number";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u0645\u062F\u062E\u0644",
- email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",
- url: "\u0631\u0627\u0628\u0637",
- emoji: "\u0625\u064A\u0645\u0648\u062C\u064A",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
- date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
- time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
- duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
- ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4",
- ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6",
- cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",
- cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",
- base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",
- base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",
- json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",
- e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",
- jwt: "JWT",
- template_literal: "\u0645\u062F\u062E\u0644"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${parsedType(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`;
- return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`;
- return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`;
- if (_issue.format === "ends_with")
- return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`;
- return `${Nouns[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`;
- }
- case "not_multiple_of":
- return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`;
- case "unrecognized_keys":
- return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
- case "invalid_key":
- return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
- case "invalid_union":
- return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
- case "invalid_element":
- return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
- default:
- return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
- }
- };
-};
-var init_ar = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/az.js
-function az_default() {
- return {
- localeError: error2()
- };
-}
-var error2 = () => {
- const Sizable = {
- string: { unit: "simvol", verb: "olmal\u0131d\u0131r" },
- file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
- array: { unit: "element", verb: "olmal\u0131d\u0131r" },
- set: { unit: "element", verb: "olmal\u0131d\u0131r" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "number";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "input",
- email: "email address",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO datetime",
- date: "ISO date",
- time: "ISO time",
- duration: "ISO duration",
- ipv4: "IPv4 address",
- ipv6: "IPv6 address",
- cidrv4: "IPv4 range",
- cidrv6: "IPv6 range",
- base64: "base64-encoded string",
- base64url: "base64url-encoded string",
- json_string: "JSON string",
- e164: "E.164 number",
- jwt: "JWT",
- template_literal: "input"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${issue2.expected}, daxil olan ${parsedType(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`;
- return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
- return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;
- if (_issue.format === "ends_with")
- return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`;
- if (_issue.format === "includes")
- return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`;
- if (_issue.format === "regex")
- return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;
- return `Yanl\u0131\u015F ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;
- case "unrecognized_keys":
- return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;
- case "invalid_union":
- return "Yanl\u0131\u015F d\u0259y\u0259r";
- case "invalid_element":
- return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;
- default:
- return `Yanl\u0131\u015F d\u0259y\u0259r`;
- }
- };
-};
-var init_az = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/be.js
-function getBelarusianPlural(count2, one, few, many) {
- const absCount = Math.abs(count2);
- const lastDigit = absCount % 10;
- const lastTwoDigits = absCount % 100;
- if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
- return many;
- }
- if (lastDigit === 1) {
- return one;
- }
- if (lastDigit >= 2 && lastDigit <= 4) {
- return few;
- }
- return many;
-}
-function be_default() {
- return {
- localeError: error3()
- };
-}
-var error3 = () => {
- const Sizable = {
- string: {
- unit: {
- one: "\u0441\u0456\u043C\u0432\u0430\u043B",
- few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B",
- many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"
- },
- verb: "\u043C\u0435\u0446\u044C"
- },
- array: {
- unit: {
- one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
- few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
- many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
- },
- verb: "\u043C\u0435\u0446\u044C"
- },
- set: {
- unit: {
- one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
- few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
- many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
- },
- verb: "\u043C\u0435\u0446\u044C"
- },
- file: {
- unit: {
- one: "\u0431\u0430\u0439\u0442",
- few: "\u0431\u0430\u0439\u0442\u044B",
- many: "\u0431\u0430\u0439\u0442\u0430\u045E"
- },
- verb: "\u043C\u0435\u0446\u044C"
- }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "\u043B\u0456\u043A";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u043C\u0430\u0441\u0456\u045E";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u0443\u0432\u043E\u0434",
- email: "email \u0430\u0434\u0440\u0430\u0441",
- url: "URL",
- emoji: "\u044D\u043C\u043E\u0434\u0437\u0456",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",
- date: "ISO \u0434\u0430\u0442\u0430",
- time: "ISO \u0447\u0430\u0441",
- duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",
- ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441",
- ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441",
- cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
- cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
- base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",
- base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",
- json_string: "JSON \u0440\u0430\u0434\u043E\u043A",
- e164: "\u043D\u0443\u043C\u0430\u0440 E.164",
- jwt: "JWT",
- template_literal: "\u0443\u0432\u043E\u0434"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${parsedType(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- const maxValue = Number(issue2.maximum);
- const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
- return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`;
- }
- return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- const minValue = Number(issue2.minimum);
- const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
- return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`;
- }
- return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
- case "unrecognized_keys":
- return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
- case "invalid_union":
- return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";
- case "invalid_element":
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`;
- default:
- return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`;
- }
- };
-};
-var init_be = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/ca.js
-function ca_default() {
- return {
- localeError: error4()
- };
-}
-var error4 = () => {
- const Sizable = {
- string: { unit: "car\xE0cters", verb: "contenir" },
- file: { unit: "bytes", verb: "contenir" },
- array: { unit: "elements", verb: "contenir" },
- set: { unit: "elements", verb: "contenir" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "number";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "entrada",
- email: "adre\xE7a electr\xF2nica",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "data i hora ISO",
- date: "data ISO",
- time: "hora ISO",
- duration: "durada ISO",
- ipv4: "adre\xE7a IPv4",
- ipv6: "adre\xE7a IPv6",
- cidrv4: "rang IPv4",
- cidrv6: "rang IPv6",
- base64: "cadena codificada en base64",
- base64url: "cadena codificada en base64url",
- json_string: "cadena JSON",
- e164: "n\xFAmero E.164",
- jwt: "JWT",
- template_literal: "entrada"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Tipus inv\xE0lid: s'esperava ${issue2.expected}, s'ha rebut ${parsedType(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;
- return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
- return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`;
- }
- if (_issue.format === "ends_with")
- return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`;
- return `Format inv\xE0lid per a ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Clau inv\xE0lida a ${issue2.origin}`;
- case "invalid_union":
- return "Entrada inv\xE0lida";
- case "invalid_element":
- return `Element inv\xE0lid a ${issue2.origin}`;
- default:
- return `Entrada inv\xE0lida`;
- }
- };
-};
-var init_ca = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/cs.js
-function cs_default() {
- return {
- localeError: error5()
- };
-}
-var error5 = () => {
- const Sizable = {
- string: { unit: "znak\u016F", verb: "m\xEDt" },
- file: { unit: "bajt\u016F", verb: "m\xEDt" },
- array: { unit: "prvk\u016F", verb: "m\xEDt" },
- set: { unit: "prvk\u016F", verb: "m\xEDt" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "\u010D\xEDslo";
- }
- case "string": {
- return "\u0159et\u011Bzec";
- }
- case "boolean": {
- return "boolean";
- }
- case "bigint": {
- return "bigint";
- }
- case "function": {
- return "funkce";
- }
- case "symbol": {
- return "symbol";
- }
- case "undefined": {
- return "undefined";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "pole";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "regul\xE1rn\xED v\xFDraz",
- email: "e-mailov\xE1 adresa",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "datum a \u010Das ve form\xE1tu ISO",
- date: "datum ve form\xE1tu ISO",
- time: "\u010Das ve form\xE1tu ISO",
- duration: "doba trv\xE1n\xED ISO",
- ipv4: "IPv4 adresa",
- ipv6: "IPv6 adresa",
- cidrv4: "rozsah IPv4",
- cidrv6: "rozsah IPv6",
- base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",
- base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",
- json_string: "\u0159et\u011Bzec ve form\xE1tu JSON",
- e164: "\u010D\xEDslo E.164",
- jwt: "JWT",
- template_literal: "vstup"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${issue2.expected}, obdr\u017Eeno ${parsedType(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`;
- return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
- }
- return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
- }
- return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`;
- return `Neplatn\xFD form\xE1t ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`;
- case "invalid_union":
- return "Neplatn\xFD vstup";
- case "invalid_element":
- return `Neplatn\xE1 hodnota v ${issue2.origin}`;
- default:
- return `Neplatn\xFD vstup`;
- }
- };
-};
-var init_cs = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/de.js
-function de_default() {
- return {
- localeError: error6()
- };
-}
-var error6 = () => {
- const Sizable = {
- string: { unit: "Zeichen", verb: "zu haben" },
- file: { unit: "Bytes", verb: "zu haben" },
- array: { unit: "Elemente", verb: "zu haben" },
- set: { unit: "Elemente", verb: "zu haben" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "Zahl";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "Array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "Eingabe",
- email: "E-Mail-Adresse",
- url: "URL",
- emoji: "Emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO-Datum und -Uhrzeit",
- date: "ISO-Datum",
- time: "ISO-Uhrzeit",
- duration: "ISO-Dauer",
- ipv4: "IPv4-Adresse",
- ipv6: "IPv6-Adresse",
- cidrv4: "IPv4-Bereich",
- cidrv6: "IPv6-Bereich",
- base64: "Base64-codierter String",
- base64url: "Base64-URL-codierter String",
- json_string: "JSON-String",
- e164: "E.164-Nummer",
- jwt: "JWT",
- template_literal: "Eingabe"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Ung\xFCltige Eingabe: erwartet ${issue2.expected}, erhalten ${parsedType(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;
- return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`;
- return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`;
- }
- return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`;
- if (_issue.format === "ends_with")
- return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`;
- if (_issue.format === "includes")
- return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`;
- if (_issue.format === "regex")
- return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`;
- return `Ung\xFCltig: ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;
- case "unrecognized_keys":
- return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`;
- case "invalid_union":
- return "Ung\xFCltige Eingabe";
- case "invalid_element":
- return `Ung\xFCltiger Wert in ${issue2.origin}`;
- default:
- return `Ung\xFCltige Eingabe`;
- }
- };
-};
-var init_de = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/en.js
-function en_default() {
- return {
- localeError: error7()
- };
-}
-var parsedType = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "number";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
-}, error7 = () => {
- const Sizable = {
- string: { unit: "characters", verb: "to have" },
- file: { unit: "bytes", verb: "to have" },
- array: { unit: "items", verb: "to have" },
- set: { unit: "items", verb: "to have" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const Nouns = {
- regex: "input",
- email: "email address",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO datetime",
- date: "ISO date",
- time: "ISO time",
- duration: "ISO duration",
- ipv4: "IPv4 address",
- ipv6: "IPv6 address",
- cidrv4: "IPv4 range",
- cidrv6: "IPv6 range",
- base64: "base64-encoded string",
- base64url: "base64url-encoded string",
- json_string: "JSON string",
- e164: "E.164 number",
- jwt: "JWT",
- template_literal: "input"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
- return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
- return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `Invalid string: must start with "${_issue.prefix}"`;
- }
- if (_issue.format === "ends_with")
- return `Invalid string: must end with "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Invalid string: must include "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Invalid string: must match pattern ${_issue.pattern}`;
- return `Invalid ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Invalid number: must be a multiple of ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Invalid key in ${issue2.origin}`;
- case "invalid_union":
- return "Invalid input";
- case "invalid_element":
- return `Invalid value in ${issue2.origin}`;
- default:
- return `Invalid input`;
- }
- };
-};
-var init_en = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/eo.js
-function eo_default() {
- return {
- localeError: error8()
- };
-}
-var parsedType2 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "nombro";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "tabelo";
- }
- if (data === null) {
- return "senvalora";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
-}, error8 = () => {
- const Sizable = {
- string: { unit: "karaktrojn", verb: "havi" },
- file: { unit: "bajtojn", verb: "havi" },
- array: { unit: "elementojn", verb: "havi" },
- set: { unit: "elementojn", verb: "havi" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const Nouns = {
- regex: "enigo",
- email: "retadreso",
- url: "URL",
- emoji: "emo\u011Dio",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO-datotempo",
- date: "ISO-dato",
- time: "ISO-tempo",
- duration: "ISO-da\u016Dro",
- ipv4: "IPv4-adreso",
- ipv6: "IPv6-adreso",
- cidrv4: "IPv4-rango",
- cidrv6: "IPv6-rango",
- base64: "64-ume kodita karaktraro",
- base64url: "URL-64-ume kodita karaktraro",
- json_string: "JSON-karaktraro",
- e164: "E.164-nombro",
- jwt: "JWT",
- template_literal: "enigo"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Nevalida enigo: atendi\u011Dis ${issue2.expected}, ricevi\u011Dis ${parsedType2(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`;
- return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`;
- return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;
- return `Nevalida ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Nevalida \u015Dlosilo en ${issue2.origin}`;
- case "invalid_union":
- return "Nevalida enigo";
- case "invalid_element":
- return `Nevalida valoro en ${issue2.origin}`;
- default:
- return `Nevalida enigo`;
- }
- };
-};
-var init_eo = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/es.js
-function es_default() {
- return {
- localeError: error9()
- };
-}
-var error9 = () => {
- const Sizable = {
- string: { unit: "caracteres", verb: "tener" },
- file: { unit: "bytes", verb: "tener" },
- array: { unit: "elementos", verb: "tener" },
- set: { unit: "elementos", verb: "tener" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "n\xFAmero";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "arreglo";
- }
- if (data === null) {
- return "nulo";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "entrada",
- email: "direcci\xF3n de correo electr\xF3nico",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "fecha y hora ISO",
- date: "fecha ISO",
- time: "hora ISO",
- duration: "duraci\xF3n ISO",
- ipv4: "direcci\xF3n IPv4",
- ipv6: "direcci\xF3n IPv6",
- cidrv4: "rango IPv4",
- cidrv6: "rango IPv6",
- base64: "cadena codificada en base64",
- base64url: "URL codificada en base64",
- json_string: "cadena JSON",
- e164: "n\xFAmero E.164",
- jwt: "JWT",
- template_literal: "entrada"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Entrada inv\xE1lida: se esperaba ${issue2.expected}, recibido ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;
- return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Demasiado grande: se esperaba que ${issue2.origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
- return `Demasiado grande: se esperaba que ${issue2.origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Demasiado peque\xF1o: se esperaba que ${issue2.origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Demasiado peque\xF1o: se esperaba que ${issue2.origin} fuera ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`;
- return `Inv\xE1lido ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Llave inv\xE1lida en ${issue2.origin}`;
- case "invalid_union":
- return "Entrada inv\xE1lida";
- case "invalid_element":
- return `Valor inv\xE1lido en ${issue2.origin}`;
- default:
- return `Entrada inv\xE1lida`;
- }
- };
-};
-var init_es = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/fa.js
-function fa_default() {
- return {
- localeError: error10()
- };
-}
-var error10 = () => {
- const Sizable = {
- string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
- file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
- array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
- set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u0622\u0631\u0627\u06CC\u0647";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u0648\u0631\u0648\u062F\u06CC",
- email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",
- url: "URL",
- emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
- date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",
- time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
- duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
- ipv4: "IPv4 \u0622\u062F\u0631\u0633",
- ipv6: "IPv6 \u0622\u062F\u0631\u0633",
- cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647",
- cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647",
- base64: "base64-encoded \u0631\u0634\u062A\u0647",
- base64url: "base64url-encoded \u0631\u0634\u062A\u0647",
- json_string: "JSON \u0631\u0634\u062A\u0647",
- e164: "E.164 \u0639\u062F\u062F",
- jwt: "JWT",
- template_literal: "\u0648\u0631\u0648\u062F\u06CC"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${parsedType3(issue2.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;
- case "invalid_value":
- if (issue2.values.length === 1) {
- return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;
- }
- return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;
- }
- return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`;
- }
- return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;
- }
- if (_issue.format === "ends_with") {
- return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;
- }
- if (_issue.format === "includes") {
- return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`;
- }
- if (_issue.format === "regex") {
- return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;
- }
- return `${Nouns[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
- }
- case "not_multiple_of":
- return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`;
- case "unrecognized_keys":
- return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`;
- case "invalid_union":
- return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
- case "invalid_element":
- return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`;
- default:
- return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
- }
- };
-};
-var init_fa = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/fi.js
-function fi_default() {
- return {
- localeError: error11()
- };
-}
-var error11 = () => {
- const Sizable = {
- string: { unit: "merkki\xE4", subject: "merkkijonon" },
- file: { unit: "tavua", subject: "tiedoston" },
- array: { unit: "alkiota", subject: "listan" },
- set: { unit: "alkiota", subject: "joukon" },
- number: { unit: "", subject: "luvun" },
- bigint: { unit: "", subject: "suuren kokonaisluvun" },
- int: { unit: "", subject: "kokonaisluvun" },
- date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "number";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "s\xE4\xE4nn\xF6llinen lauseke",
- email: "s\xE4hk\xF6postiosoite",
- url: "URL-osoite",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO-aikaleima",
- date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",
- time: "ISO-aika",
- duration: "ISO-kesto",
- ipv4: "IPv4-osoite",
- ipv6: "IPv6-osoite",
- cidrv4: "IPv4-alue",
- cidrv6: "IPv6-alue",
- base64: "base64-koodattu merkkijono",
- base64url: "base64url-koodattu merkkijono",
- json_string: "JSON-merkkijono",
- e164: "E.164-luku",
- jwt: "JWT",
- template_literal: "templaattimerkkijono"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Virheellinen tyyppi: odotettiin ${issue2.expected}, oli ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`;
- return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim();
- }
- return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim();
- }
- return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`;
- if (_issue.format === "regex") {
- return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`;
- }
- return `Virheellinen ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`;
- case "unrecognized_keys":
- return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return "Virheellinen avain tietueessa";
- case "invalid_union":
- return "Virheellinen unioni";
- case "invalid_element":
- return "Virheellinen arvo joukossa";
- default:
- return `Virheellinen sy\xF6te`;
- }
- };
-};
-var init_fi = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/fr.js
-function fr_default() {
- return {
- localeError: error12()
- };
-}
-var error12 = () => {
- const Sizable = {
- string: { unit: "caract\xE8res", verb: "avoir" },
- file: { unit: "octets", verb: "avoir" },
- array: { unit: "\xE9l\xE9ments", verb: "avoir" },
- set: { unit: "\xE9l\xE9ments", verb: "avoir" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "nombre";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "tableau";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "entr\xE9e",
- email: "adresse e-mail",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "date et heure ISO",
- date: "date ISO",
- time: "heure ISO",
- duration: "dur\xE9e ISO",
- ipv4: "adresse IPv4",
- ipv6: "adresse IPv6",
- cidrv4: "plage IPv4",
- cidrv6: "plage IPv6",
- base64: "cha\xEEne encod\xE9e en base64",
- base64url: "cha\xEEne encod\xE9e en base64url",
- json_string: "cha\xEEne JSON",
- e164: "num\xE9ro E.164",
- jwt: "JWT",
- template_literal: "entr\xE9e"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Entr\xE9e invalide : ${issue2.expected} attendu, ${parsedType3(issue2.input)} re\xE7u`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;
- return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Trop grand : ${issue2.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`;
- return `Trop grand : ${issue2.origin ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`;
- return `${Nouns[_issue.format] ?? issue2.format} invalide`;
- }
- case "not_multiple_of":
- return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Cl\xE9 invalide dans ${issue2.origin}`;
- case "invalid_union":
- return "Entr\xE9e invalide";
- case "invalid_element":
- return `Valeur invalide dans ${issue2.origin}`;
- default:
- return `Entr\xE9e invalide`;
- }
- };
-};
-var init_fr = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/fr-CA.js
-function fr_CA_default() {
- return {
- localeError: error13()
- };
-}
-var error13 = () => {
- const Sizable = {
- string: { unit: "caract\xE8res", verb: "avoir" },
- file: { unit: "octets", verb: "avoir" },
- array: { unit: "\xE9l\xE9ments", verb: "avoir" },
- set: { unit: "\xE9l\xE9ments", verb: "avoir" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "number";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "entr\xE9e",
- email: "adresse courriel",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "date-heure ISO",
- date: "date ISO",
- time: "heure ISO",
- duration: "dur\xE9e ISO",
- ipv4: "adresse IPv4",
- ipv6: "adresse IPv6",
- cidrv4: "plage IPv4",
- cidrv6: "plage IPv6",
- base64: "cha\xEEne encod\xE9e en base64",
- base64url: "cha\xEEne encod\xE9e en base64url",
- json_string: "cha\xEEne JSON",
- e164: "num\xE9ro E.164",
- jwt: "JWT",
- template_literal: "entr\xE9e"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Entr\xE9e invalide : attendu ${issue2.expected}, re\xE7u ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;
- return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "\u2264" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
- return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? "\u2265" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
- }
- if (_issue.format === "ends_with")
- return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`;
- return `${Nouns[_issue.format] ?? issue2.format} invalide`;
- }
- case "not_multiple_of":
- return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Cl\xE9 invalide dans ${issue2.origin}`;
- case "invalid_union":
- return "Entr\xE9e invalide";
- case "invalid_element":
- return `Valeur invalide dans ${issue2.origin}`;
- default:
- return `Entr\xE9e invalide`;
- }
- };
-};
-var init_fr_CA = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/he.js
-function he_default() {
- return {
- localeError: error14()
- };
-}
-var error14 = () => {
- const Sizable = {
- string: { unit: "\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" },
- file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" },
- array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" },
- set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "number";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u05E7\u05DC\u05D8",
- email: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",
- url: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",
- emoji: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",
- date: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO",
- time: "\u05D6\u05DE\u05DF ISO",
- duration: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",
- ipv4: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",
- ipv6: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",
- cidrv4: "\u05D8\u05D5\u05D5\u05D7 IPv4",
- cidrv6: "\u05D8\u05D5\u05D5\u05D7 IPv6",
- base64: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",
- base64url: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",
- json_string: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",
- e164: "\u05DE\u05E1\u05E4\u05E8 E.164",
- jwt: "JWT",
- template_literal: "\u05E7\u05DC\u05D8"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${stringifyPrimitive(issue2.values[0])}`;
- return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue2.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
- return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue2.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`;
- return `${Nouns[_issue.format] ?? issue2.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;
- }
- case "not_multiple_of":
- return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`;
- case "unrecognized_keys":
- return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`;
- case "invalid_union":
- return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";
- case "invalid_element":
- return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`;
- default:
- return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;
- }
- };
-};
-var init_he = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/hu.js
-function hu_default() {
- return {
- localeError: error15()
- };
-}
-var error15 = () => {
- const Sizable = {
- string: { unit: "karakter", verb: "legyen" },
- file: { unit: "byte", verb: "legyen" },
- array: { unit: "elem", verb: "legyen" },
- set: { unit: "elem", verb: "legyen" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "sz\xE1m";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "t\xF6mb";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "bemenet",
- email: "email c\xEDm",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO id\u0151b\xE9lyeg",
- date: "ISO d\xE1tum",
- time: "ISO id\u0151",
- duration: "ISO id\u0151intervallum",
- ipv4: "IPv4 c\xEDm",
- ipv6: "IPv6 c\xEDm",
- cidrv4: "IPv4 tartom\xE1ny",
- cidrv6: "IPv6 tartom\xE1ny",
- base64: "base64-k\xF3dolt string",
- base64url: "base64url-k\xF3dolt string",
- json_string: "JSON string",
- e164: "E.164 sz\xE1m",
- jwt: "JWT",
- template_literal: "bemenet"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${issue2.expected}, a kapott \xE9rt\xE9k ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`;
- return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`;
- return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;
- if (_issue.format === "ends_with")
- return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;
- if (_issue.format === "includes")
- return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`;
- if (_issue.format === "regex")
- return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`;
- return `\xC9rv\xE9nytelen ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;
- case "unrecognized_keys":
- return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`;
- case "invalid_union":
- return "\xC9rv\xE9nytelen bemenet";
- case "invalid_element":
- return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`;
- default:
- return `\xC9rv\xE9nytelen bemenet`;
- }
- };
-};
-var init_hu = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/id.js
-function id_default() {
- return {
- localeError: error16()
- };
-}
-var error16 = () => {
- const Sizable = {
- string: { unit: "karakter", verb: "memiliki" },
- file: { unit: "byte", verb: "memiliki" },
- array: { unit: "item", verb: "memiliki" },
- set: { unit: "item", verb: "memiliki" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "number";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "input",
- email: "alamat email",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "tanggal dan waktu format ISO",
- date: "tanggal format ISO",
- time: "jam format ISO",
- duration: "durasi format ISO",
- ipv4: "alamat IPv4",
- ipv6: "alamat IPv6",
- cidrv4: "rentang alamat IPv4",
- cidrv6: "rentang alamat IPv6",
- base64: "string dengan enkode base64",
- base64url: "string dengan enkode base64url",
- json_string: "string JSON",
- e164: "angka E.164",
- jwt: "JWT",
- template_literal: "input"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Input tidak valid: diharapkan ${issue2.expected}, diterima ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;
- return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
- return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `String tidak valid: harus menyertakan "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `String tidak valid: harus sesuai pola ${_issue.pattern}`;
- return `${Nouns[_issue.format] ?? issue2.format} tidak valid`;
- }
- case "not_multiple_of":
- return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Kunci tidak valid di ${issue2.origin}`;
- case "invalid_union":
- return "Input tidak valid";
- case "invalid_element":
- return `Nilai tidak valid di ${issue2.origin}`;
- default:
- return `Input tidak valid`;
- }
- };
-};
-var init_id = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/it.js
-function it_default() {
- return {
- localeError: error17()
- };
-}
-var error17 = () => {
- const Sizable = {
- string: { unit: "caratteri", verb: "avere" },
- file: { unit: "byte", verb: "avere" },
- array: { unit: "elementi", verb: "avere" },
- set: { unit: "elementi", verb: "avere" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "numero";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "vettore";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "input",
- email: "indirizzo email",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "data e ora ISO",
- date: "data ISO",
- time: "ora ISO",
- duration: "durata ISO",
- ipv4: "indirizzo IPv4",
- ipv6: "indirizzo IPv6",
- cidrv4: "intervallo IPv4",
- cidrv6: "intervallo IPv6",
- base64: "stringa codificata in base64",
- base64url: "URL codificata in base64",
- json_string: "stringa JSON",
- e164: "numero E.164",
- jwt: "JWT",
- template_literal: "input"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Input non valido: atteso ${issue2.expected}, ricevuto ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;
- return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`;
- return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Stringa non valida: deve includere "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
- return `Invalid ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Chiave non valida in ${issue2.origin}`;
- case "invalid_union":
- return "Input non valido";
- case "invalid_element":
- return `Valore non valido in ${issue2.origin}`;
- default:
- return `Input non valido`;
- }
- };
-};
-var init_it = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/ja.js
-function ja_default() {
- return {
- localeError: error18()
- };
-}
-var error18 = () => {
- const Sizable = {
- string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" },
- file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" },
- array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" },
- set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "\u6570\u5024";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u914D\u5217";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u5165\u529B\u5024",
- email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",
- url: "URL",
- emoji: "\u7D75\u6587\u5B57",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO\u65E5\u6642",
- date: "ISO\u65E5\u4ED8",
- time: "ISO\u6642\u523B",
- duration: "ISO\u671F\u9593",
- ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9",
- ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9",
- cidrv4: "IPv4\u7BC4\u56F2",
- cidrv6: "IPv6\u7BC4\u56F2",
- base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
- base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
- json_string: "JSON\u6587\u5B57\u5217",
- e164: "E.164\u756A\u53F7",
- jwt: "JWT",
- template_literal: "\u5165\u529B\u5024"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u7121\u52B9\u306A\u5165\u529B: ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${parsedType3(issue2.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;
- return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
- case "too_big": {
- const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
- return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
- return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
- if (_issue.format === "ends_with")
- return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
- if (_issue.format === "includes")
- return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
- if (_issue.format === "regex")
- return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
- return `\u7121\u52B9\u306A${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
- case "unrecognized_keys":
- return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`;
- case "invalid_key":
- return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;
- case "invalid_union":
- return "\u7121\u52B9\u306A\u5165\u529B";
- case "invalid_element":
- return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;
- default:
- return `\u7121\u52B9\u306A\u5165\u529B`;
- }
- };
-};
-var init_ja = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/kh.js
-function kh_default() {
- return {
- localeError: error19()
- };
-}
-var error19 = () => {
- const Sizable = {
- string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
- file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
- array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
- set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)" : "\u179B\u17C1\u1781";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u17A2\u17B6\u179A\u17C1 (Array)";
- }
- if (data === null) {
- return "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",
- email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",
- url: "URL",
- emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",
- date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",
- time: "\u1798\u17C9\u17C4\u1784 ISO",
- duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",
- ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
- ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
- cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
- cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
- base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",
- base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",
- json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",
- e164: "\u179B\u17C1\u1781 E.164",
- jwt: "JWT",
- template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`;
- return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`;
- return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`;
- }
- if (_issue.format === "ends_with")
- return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`;
- return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`;
- case "unrecognized_keys":
- return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
- case "invalid_union":
- return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
- case "invalid_element":
- return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
- default:
- return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
- }
- };
-};
-var init_kh = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/ko.js
-function ko_default() {
- return {
- localeError: error20()
- };
-}
-var error20 = () => {
- const Sizable = {
- string: { unit: "\uBB38\uC790", verb: "to have" },
- file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" },
- array: { unit: "\uAC1C", verb: "to have" },
- set: { unit: "\uAC1C", verb: "to have" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "number";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\uC785\uB825",
- email: "\uC774\uBA54\uC77C \uC8FC\uC18C",
- url: "URL",
- emoji: "\uC774\uBAA8\uC9C0",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04",
- date: "ISO \uB0A0\uC9DC",
- time: "ISO \uC2DC\uAC04",
- duration: "ISO \uAE30\uAC04",
- ipv4: "IPv4 \uC8FC\uC18C",
- ipv6: "IPv6 \uC8FC\uC18C",
- cidrv4: "IPv4 \uBC94\uC704",
- cidrv6: "IPv6 \uBC94\uC704",
- base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
- base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
- json_string: "JSON \uBB38\uC790\uC5F4",
- e164: "E.164 \uBC88\uD638",
- jwt: "JWT",
- template_literal: "\uC785\uB825"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${parsedType3(issue2.input)}\uC785\uB2C8\uB2E4`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;
- return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
- case "too_big": {
- const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC";
- const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
- const sizing = getSizing(issue2.origin);
- const unit = sizing?.unit ?? "\uC694\uC18C";
- if (sizing)
- return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`;
- return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC";
- const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
- const sizing = getSizing(issue2.origin);
- const unit = sizing?.unit ?? "\uC694\uC18C";
- if (sizing) {
- return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`;
- }
- return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;
- }
- if (_issue.format === "ends_with")
- return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;
- if (_issue.format === "includes")
- return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;
- if (_issue.format === "regex")
- return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;
- return `\uC798\uBABB\uB41C ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
- case "unrecognized_keys":
- return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`;
- case "invalid_union":
- return `\uC798\uBABB\uB41C \uC785\uB825`;
- case "invalid_element":
- return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`;
- default:
- return `\uC798\uBABB\uB41C \uC785\uB825`;
- }
- };
-};
-var init_ko = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/mk.js
-function mk_default() {
- return {
- localeError: error21()
- };
-}
-var error21 = () => {
- const Sizable = {
- string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
- file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
- array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
- set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "\u0431\u0440\u043E\u0458";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u043D\u0438\u0437\u0430";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u0432\u043D\u0435\u0441",
- email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",
- url: "URL",
- emoji: "\u0435\u043C\u043E\u045F\u0438",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",
- date: "ISO \u0434\u0430\u0442\u0443\u043C",
- time: "ISO \u0432\u0440\u0435\u043C\u0435",
- duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",
- ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",
- ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",
- cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433",
- cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433",
- base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
- base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
- json_string: "JSON \u043D\u0438\u0437\u0430",
- e164: "E.164 \u0431\u0440\u043E\u0458",
- jwt: "JWT",
- template_literal: "\u0432\u043D\u0435\u0441"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
- return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;
- return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`;
- }
- if (_issue.format === "ends_with")
- return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`;
- return `Invalid ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`;
- case "unrecognized_keys":
- return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`;
- case "invalid_union":
- return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";
- case "invalid_element":
- return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`;
- default:
- return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`;
- }
- };
-};
-var init_mk = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/ms.js
-function ms_default() {
- return {
- localeError: error22()
- };
-}
-var error22 = () => {
- const Sizable = {
- string: { unit: "aksara", verb: "mempunyai" },
- file: { unit: "bait", verb: "mempunyai" },
- array: { unit: "elemen", verb: "mempunyai" },
- set: { unit: "elemen", verb: "mempunyai" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "nombor";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "input",
- email: "alamat e-mel",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "tarikh masa ISO",
- date: "tarikh ISO",
- time: "masa ISO",
- duration: "tempoh ISO",
- ipv4: "alamat IPv4",
- ipv6: "alamat IPv6",
- cidrv4: "julat IPv4",
- cidrv6: "julat IPv6",
- base64: "string dikodkan base64",
- base64url: "string dikodkan base64url",
- json_string: "string JSON",
- e164: "nombor E.164",
- jwt: "JWT",
- template_literal: "input"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Input tidak sah: dijangka ${issue2.expected}, diterima ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;
- return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
- return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `String tidak sah: mesti mengandungi "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;
- return `${Nouns[_issue.format] ?? issue2.format} tidak sah`;
- }
- case "not_multiple_of":
- return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Kunci tidak sah dalam ${issue2.origin}`;
- case "invalid_union":
- return "Input tidak sah";
- case "invalid_element":
- return `Nilai tidak sah dalam ${issue2.origin}`;
- default:
- return `Input tidak sah`;
- }
- };
-};
-var init_ms = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/nl.js
-function nl_default() {
- return {
- localeError: error23()
- };
-}
-var error23 = () => {
- const Sizable = {
- string: { unit: "tekens" },
- file: { unit: "bytes" },
- array: { unit: "elementen" },
- set: { unit: "elementen" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "getal";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "invoer",
- email: "emailadres",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO datum en tijd",
- date: "ISO datum",
- time: "ISO tijd",
- duration: "ISO duur",
- ipv4: "IPv4-adres",
- ipv6: "IPv6-adres",
- cidrv4: "IPv4-bereik",
- cidrv6: "IPv6-bereik",
- base64: "base64-gecodeerde tekst",
- base64url: "base64 URL-gecodeerde tekst",
- json_string: "JSON string",
- e164: "E.164-nummer",
- jwt: "JWT",
- template_literal: "invoer"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Ongeldige invoer: verwacht ${issue2.expected}, ontving ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;
- return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Te lang: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} bevat`;
- return `Te lang: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} bevat`;
- }
- return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;
- }
- if (_issue.format === "ends_with")
- return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;
- if (_issue.format === "includes")
- return `Ongeldige tekst: moet "${_issue.includes}" bevatten`;
- if (_issue.format === "regex")
- return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;
- return `Ongeldig: ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;
- case "unrecognized_keys":
- return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Ongeldige key in ${issue2.origin}`;
- case "invalid_union":
- return "Ongeldige invoer";
- case "invalid_element":
- return `Ongeldige waarde in ${issue2.origin}`;
- default:
- return `Ongeldige invoer`;
- }
- };
-};
-var init_nl = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/no.js
-function no_default() {
- return {
- localeError: error24()
- };
-}
-var error24 = () => {
- const Sizable = {
- string: { unit: "tegn", verb: "\xE5 ha" },
- file: { unit: "bytes", verb: "\xE5 ha" },
- array: { unit: "elementer", verb: "\xE5 inneholde" },
- set: { unit: "elementer", verb: "\xE5 inneholde" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "tall";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "liste";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "input",
- email: "e-postadresse",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO dato- og klokkeslett",
- date: "ISO-dato",
- time: "ISO-klokkeslett",
- duration: "ISO-varighet",
- ipv4: "IPv4-omr\xE5de",
- ipv6: "IPv6-omr\xE5de",
- cidrv4: "IPv4-spekter",
- cidrv6: "IPv6-spekter",
- base64: "base64-enkodet streng",
- base64url: "base64url-enkodet streng",
- json_string: "JSON-streng",
- e164: "E.164-nummer",
- jwt: "JWT",
- template_literal: "input"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Ugyldig input: forventet ${issue2.expected}, fikk ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;
- return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`;
- return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`;
- return `Ugyldig ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`;
- case "unrecognized_keys":
- return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Ugyldig n\xF8kkel i ${issue2.origin}`;
- case "invalid_union":
- return "Ugyldig input";
- case "invalid_element":
- return `Ugyldig verdi i ${issue2.origin}`;
- default:
- return `Ugyldig input`;
- }
- };
-};
-var init_no = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/ota.js
-function ota_default() {
- return {
- localeError: error25()
- };
-}
-var error25 = () => {
- const Sizable = {
- string: { unit: "harf", verb: "olmal\u0131d\u0131r" },
- file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
- array: { unit: "unsur", verb: "olmal\u0131d\u0131r" },
- set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "numara";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "saf";
- }
- if (data === null) {
- return "gayb";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "giren",
- email: "epostag\xE2h",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO heng\xE2m\u0131",
- date: "ISO tarihi",
- time: "ISO zaman\u0131",
- duration: "ISO m\xFCddeti",
- ipv4: "IPv4 ni\u015F\xE2n\u0131",
- ipv6: "IPv6 ni\u015F\xE2n\u0131",
- cidrv4: "IPv4 menzili",
- cidrv6: "IPv6 menzili",
- base64: "base64-\u015Fifreli metin",
- base64url: "base64url-\u015Fifreli metin",
- json_string: "JSON metin",
- e164: "E.164 say\u0131s\u0131",
- jwt: "JWT",
- template_literal: "giren"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `F\xE2sit giren: umulan ${issue2.expected}, al\u0131nan ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;
- return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`;
- return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`;
- }
- return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`;
- if (_issue.format === "ends_with")
- return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`;
- if (_issue.format === "includes")
- return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`;
- if (_issue.format === "regex")
- return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`;
- return `F\xE2sit ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`;
- case "unrecognized_keys":
- return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`;
- case "invalid_union":
- return "Giren tan\u0131namad\u0131.";
- case "invalid_element":
- return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;
- default:
- return `K\u0131ymet tan\u0131namad\u0131.`;
- }
- };
-};
-var init_ota = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/ps.js
-function ps_default() {
- return {
- localeError: error26()
- };
-}
-var error26 = () => {
- const Sizable = {
- string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" },
- file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" },
- array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" },
- set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u0627\u0631\u06D0";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u0648\u0631\u0648\u062F\u064A",
- email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",
- url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644",
- emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",
- date: "\u0646\u06D0\u067C\u0647",
- time: "\u0648\u062E\u062A",
- duration: "\u0645\u0648\u062F\u0647",
- ipv4: "\u062F IPv4 \u067E\u062A\u0647",
- ipv6: "\u062F IPv6 \u067E\u062A\u0647",
- cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647",
- cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647",
- base64: "base64-encoded \u0645\u062A\u0646",
- base64url: "base64url-encoded \u0645\u062A\u0646",
- json_string: "JSON \u0645\u062A\u0646",
- e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",
- jwt: "JWT",
- template_literal: "\u0648\u0631\u0648\u062F\u064A"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${parsedType3(issue2.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;
- case "invalid_value":
- if (issue2.values.length === 1) {
- return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`;
- }
- return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;
- }
- return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`;
- }
- return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;
- }
- if (_issue.format === "ends_with") {
- return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;
- }
- if (_issue.format === "includes") {
- return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`;
- }
- if (_issue.format === "regex") {
- return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;
- }
- return `${Nouns[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`;
- }
- case "not_multiple_of":
- return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;
- case "unrecognized_keys":
- return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
- case "invalid_union":
- return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
- case "invalid_element":
- return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
- default:
- return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
- }
- };
-};
-var init_ps = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/pl.js
-function pl_default() {
- return {
- localeError: error27()
- };
-}
-var error27 = () => {
- const Sizable = {
- string: { unit: "znak\xF3w", verb: "mie\u0107" },
- file: { unit: "bajt\xF3w", verb: "mie\u0107" },
- array: { unit: "element\xF3w", verb: "mie\u0107" },
- set: { unit: "element\xF3w", verb: "mie\u0107" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "liczba";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "tablica";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "wyra\u017Cenie",
- email: "adres email",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "data i godzina w formacie ISO",
- date: "data w formacie ISO",
- time: "godzina w formacie ISO",
- duration: "czas trwania ISO",
- ipv4: "adres IPv4",
- ipv6: "adres IPv6",
- cidrv4: "zakres IPv4",
- cidrv6: "zakres IPv6",
- base64: "ci\u0105g znak\xF3w zakodowany w formacie base64",
- base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url",
- json_string: "ci\u0105g znak\xF3w w formacie JSON",
- e164: "liczba E.164",
- jwt: "JWT",
- template_literal: "wej\u015Bcie"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${issue2.expected}, otrzymano ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;
- return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`;
- }
- return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`;
- }
- return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`;
- return `Nieprawid\u0142ow(y/a/e) ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Nieprawid\u0142owy klucz w ${issue2.origin}`;
- case "invalid_union":
- return "Nieprawid\u0142owe dane wej\u015Bciowe";
- case "invalid_element":
- return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`;
- default:
- return `Nieprawid\u0142owe dane wej\u015Bciowe`;
- }
- };
-};
-var init_pl = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/pt.js
-function pt_default() {
- return {
- localeError: error28()
- };
-}
-var error28 = () => {
- const Sizable = {
- string: { unit: "caracteres", verb: "ter" },
- file: { unit: "bytes", verb: "ter" },
- array: { unit: "itens", verb: "ter" },
- set: { unit: "itens", verb: "ter" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "n\xFAmero";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "nulo";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "padr\xE3o",
- email: "endere\xE7o de e-mail",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "data e hora ISO",
- date: "data ISO",
- time: "hora ISO",
- duration: "dura\xE7\xE3o ISO",
- ipv4: "endere\xE7o IPv4",
- ipv6: "endere\xE7o IPv6",
- cidrv4: "faixa de IPv4",
- cidrv6: "faixa de IPv6",
- base64: "texto codificado em base64",
- base64url: "URL codificada em base64",
- json_string: "texto JSON",
- e164: "n\xFAmero E.164",
- jwt: "JWT",
- template_literal: "entrada"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Tipo inv\xE1lido: esperado ${issue2.expected}, recebido ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`;
- return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
- return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`;
- return `${Nouns[_issue.format] ?? issue2.format} inv\xE1lido`;
- }
- case "not_multiple_of":
- return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Chave inv\xE1lida em ${issue2.origin}`;
- case "invalid_union":
- return "Entrada inv\xE1lida";
- case "invalid_element":
- return `Valor inv\xE1lido em ${issue2.origin}`;
- default:
- return `Campo inv\xE1lido`;
- }
- };
-};
-var init_pt = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/ru.js
-function getRussianPlural(count2, one, few, many) {
- const absCount = Math.abs(count2);
- const lastDigit = absCount % 10;
- const lastTwoDigits = absCount % 100;
- if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
- return many;
- }
- if (lastDigit === 1) {
- return one;
- }
- if (lastDigit >= 2 && lastDigit <= 4) {
- return few;
- }
- return many;
-}
-function ru_default() {
- return {
- localeError: error29()
- };
-}
-var error29 = () => {
- const Sizable = {
- string: {
- unit: {
- one: "\u0441\u0438\u043C\u0432\u043E\u043B",
- few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430",
- many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"
- },
- verb: "\u0438\u043C\u0435\u0442\u044C"
- },
- file: {
- unit: {
- one: "\u0431\u0430\u0439\u0442",
- few: "\u0431\u0430\u0439\u0442\u0430",
- many: "\u0431\u0430\u0439\u0442"
- },
- verb: "\u0438\u043C\u0435\u0442\u044C"
- },
- array: {
- unit: {
- one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
- few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
- many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
- },
- verb: "\u0438\u043C\u0435\u0442\u044C"
- },
- set: {
- unit: {
- one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
- few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
- many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
- },
- verb: "\u0438\u043C\u0435\u0442\u044C"
- }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u043C\u0430\u0441\u0441\u0438\u0432";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u0432\u0432\u043E\u0434",
- email: "email \u0430\u0434\u0440\u0435\u0441",
- url: "URL",
- emoji: "\u044D\u043C\u043E\u0434\u0437\u0438",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",
- date: "ISO \u0434\u0430\u0442\u0430",
- time: "ISO \u0432\u0440\u0435\u043C\u044F",
- duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",
- ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441",
- ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441",
- cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
- cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
- base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",
- base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",
- json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430",
- e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
- jwt: "JWT",
- template_literal: "\u0432\u0432\u043E\u0434"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`;
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- const maxValue = Number(issue2.maximum);
- const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
- return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`;
- }
- return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- const minValue = Number(issue2.minimum);
- const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
- return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`;
- }
- return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
- case "unrecognized_keys":
- return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;
- case "invalid_union":
- return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";
- case "invalid_element":
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`;
- default:
- return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`;
- }
- };
-};
-var init_ru = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/sl.js
-function sl_default() {
- return {
- localeError: error30()
- };
-}
-var error30 = () => {
- const Sizable = {
- string: { unit: "znakov", verb: "imeti" },
- file: { unit: "bajtov", verb: "imeti" },
- array: { unit: "elementov", verb: "imeti" },
- set: { unit: "elementov", verb: "imeti" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "\u0161tevilo";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "tabela";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "vnos",
- email: "e-po\u0161tni naslov",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO datum in \u010Das",
- date: "ISO datum",
- time: "ISO \u010Das",
- duration: "ISO trajanje",
- ipv4: "IPv4 naslov",
- ipv6: "IPv6 naslov",
- cidrv4: "obseg IPv4",
- cidrv6: "obseg IPv6",
- base64: "base64 kodiran niz",
- base64url: "base64url kodiran niz",
- json_string: "JSON niz",
- e164: "E.164 \u0161tevilka",
- jwt: "JWT",
- template_literal: "vnos"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Neveljaven vnos: pri\u010Dakovano ${issue2.expected}, prejeto ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`;
- return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`;
- return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`;
- }
- if (_issue.format === "ends_with")
- return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Neveljaven niz: mora vsebovati "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;
- return `Neveljaven ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Neveljaven klju\u010D v ${issue2.origin}`;
- case "invalid_union":
- return "Neveljaven vnos";
- case "invalid_element":
- return `Neveljavna vrednost v ${issue2.origin}`;
- default:
- return "Neveljaven vnos";
- }
- };
-};
-var init_sl = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/sv.js
-function sv_default() {
- return {
- localeError: error31()
- };
-}
-var error31 = () => {
- const Sizable = {
- string: { unit: "tecken", verb: "att ha" },
- file: { unit: "bytes", verb: "att ha" },
- array: { unit: "objekt", verb: "att inneh\xE5lla" },
- set: { unit: "objekt", verb: "att inneh\xE5lla" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "antal";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "lista";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "regulj\xE4rt uttryck",
- email: "e-postadress",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO-datum och tid",
- date: "ISO-datum",
- time: "ISO-tid",
- duration: "ISO-varaktighet",
- ipv4: "IPv4-intervall",
- ipv6: "IPv6-intervall",
- cidrv4: "IPv4-spektrum",
- cidrv6: "IPv6-spektrum",
- base64: "base64-kodad str\xE4ng",
- base64url: "base64url-kodad str\xE4ng",
- json_string: "JSON-str\xE4ng",
- e164: "E.164-nummer",
- jwt: "JWT",
- template_literal: "mall-literal"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Ogiltig inmatning: f\xF6rv\xE4ntat ${issue2.expected}, fick ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`;
- return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
- }
- return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`;
- }
- if (_issue.format === "ends_with")
- return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`;
- return `Ogiltig(t) ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`;
- case "unrecognized_keys":
- return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`;
- case "invalid_union":
- return "Ogiltig input";
- case "invalid_element":
- return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`;
- default:
- return `Ogiltig input`;
- }
- };
-};
-var init_sv = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/ta.js
-function ta_default() {
- return {
- localeError: error32()
- };
-}
-var error32 = () => {
- const Sizable = {
- string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
- file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
- array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
- set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1" : "\u0B8E\u0BA3\u0BCD";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u0B85\u0BA3\u0BBF";
- }
- if (data === null) {
- return "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",
- email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
- date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF",
- time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
- duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",
- ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
- ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
- cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
- cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
- base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
- base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
- json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD",
- e164: "E.164 \u0B8E\u0BA3\u0BCD",
- jwt: "JWT",
- template_literal: "input"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`;
- return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
- }
- return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
- }
- return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
- if (_issue.format === "ends_with")
- return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
- if (_issue.format === "includes")
- return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
- if (_issue.format === "regex")
- return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
- return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
- case "unrecognized_keys":
- return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;
- case "invalid_union":
- return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";
- case "invalid_element":
- return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;
- default:
- return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`;
- }
- };
-};
-var init_ta = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/th.js
-function th_default() {
- return {
- localeError: error33()
- };
-}
-var error33 = () => {
- const Sizable = {
- string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
- file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
- array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
- set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)" : "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";
- }
- if (data === null) {
- return "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",
- email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",
- url: "URL",
- emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
- date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",
- time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
- duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
- ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",
- ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",
- cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",
- cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",
- base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",
- base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",
- json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",
- e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",
- jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",
- template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`;
- return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;
- return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`;
- }
- if (_issue.format === "ends_with")
- return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;
- if (_issue.format === "regex")
- return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`;
- return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;
- case "unrecognized_keys":
- return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
- case "invalid_union":
- return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";
- case "invalid_element":
- return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
- default:
- return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`;
- }
- };
-};
-var init_th = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/tr.js
-function tr_default() {
- return {
- localeError: error34()
- };
-}
-var parsedType3 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "number";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
-}, error34 = () => {
- const Sizable = {
- string: { unit: "karakter", verb: "olmal\u0131" },
- file: { unit: "bayt", verb: "olmal\u0131" },
- array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" },
- set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const Nouns = {
- regex: "girdi",
- email: "e-posta adresi",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO tarih ve saat",
- date: "ISO tarih",
- time: "ISO saat",
- duration: "ISO s\xFCre",
- ipv4: "IPv4 adresi",
- ipv6: "IPv6 adresi",
- cidrv4: "IPv4 aral\u0131\u011F\u0131",
- cidrv6: "IPv6 aral\u0131\u011F\u0131",
- base64: "base64 ile \u015Fifrelenmi\u015F metin",
- base64url: "base64url ile \u015Fifrelenmi\u015F metin",
- json_string: "JSON dizesi",
- e164: "E.164 say\u0131s\u0131",
- jwt: "JWT",
- template_literal: "\u015Eablon dizesi"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `Ge\xE7ersiz de\u011Fer: beklenen ${issue2.expected}, al\u0131nan ${parsedType3(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`;
- return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`;
- return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`;
- if (_issue.format === "ends_with")
- return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`;
- if (_issue.format === "includes")
- return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`;
- if (_issue.format === "regex")
- return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`;
- return `Ge\xE7ersiz ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`;
- case "unrecognized_keys":
- return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`;
- case "invalid_union":
- return "Ge\xE7ersiz de\u011Fer";
- case "invalid_element":
- return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;
- default:
- return `Ge\xE7ersiz de\u011Fer`;
- }
- };
-};
-var init_tr = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/ua.js
-function ua_default() {
- return {
- localeError: error35()
- };
-}
-var error35 = () => {
- const Sizable = {
- string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
- file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
- array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
- set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType4 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u043C\u0430\u0441\u0438\u0432";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",
- email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",
- url: "URL",
- emoji: "\u0435\u043C\u043E\u0434\u0437\u0456",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",
- date: "\u0434\u0430\u0442\u0430 ISO",
- time: "\u0447\u0430\u0441 ISO",
- duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",
- ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",
- ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",
- cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",
- cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",
- base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",
- base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",
- json_string: "\u0440\u044F\u0434\u043E\u043A JSON",
- e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
- jwt: "JWT",
- template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${parsedType4(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;
- return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`;
- case "unrecognized_keys":
- return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
- case "invalid_union":
- return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";
- case "invalid_element":
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`;
- default:
- return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`;
- }
- };
-};
-var init_ua = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/ur.js
-function ur_default() {
- return {
- localeError: error36()
- };
-}
-var error36 = () => {
- const Sizable = {
- string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" },
- file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" },
- array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" },
- set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType4 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "\u0646\u0645\u0628\u0631";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u0622\u0631\u06D2";
- }
- if (data === null) {
- return "\u0646\u0644";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u0627\u0646 \u067E\u0679",
- email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",
- url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",
- emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
- uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
- uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",
- uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",
- nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",
- guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
- cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
- cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",
- ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",
- xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",
- ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
- datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",
- date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",
- time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",
- duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",
- ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",
- ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",
- cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",
- cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",
- base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
- base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
- json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",
- e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631",
- jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",
- template_literal: "\u0627\u0646 \u067E\u0679"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${parsedType4(issue2.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
- return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
- return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
- }
- return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
- }
- if (_issue.format === "ends_with")
- return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
- if (_issue.format === "includes")
- return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
- if (_issue.format === "regex")
- return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
- return `\u063A\u0644\u0637 ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
- case "unrecognized_keys":
- return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
- case "invalid_key":
- return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;
- case "invalid_union":
- return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";
- case "invalid_element":
- return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;
- default:
- return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`;
- }
- };
-};
-var init_ur = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/vi.js
-function vi_default() {
- return {
- localeError: error37()
- };
-}
-var error37 = () => {
- const Sizable = {
- string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" },
- file: { unit: "byte", verb: "c\xF3" },
- array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" },
- set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType4 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "s\u1ED1";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "m\u1EA3ng";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u0111\u1EA7u v\xE0o",
- email: "\u0111\u1ECBa ch\u1EC9 email",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ng\xE0y gi\u1EDD ISO",
- date: "ng\xE0y ISO",
- time: "gi\u1EDD ISO",
- duration: "kho\u1EA3ng th\u1EDDi gian ISO",
- ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4",
- ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6",
- cidrv4: "d\u1EA3i IPv4",
- cidrv6: "d\u1EA3i IPv6",
- base64: "chu\u1ED7i m\xE3 h\xF3a base64",
- base64url: "chu\u1ED7i m\xE3 h\xF3a base64url",
- json_string: "chu\u1ED7i JSON",
- e164: "s\u1ED1 E.164",
- jwt: "JWT",
- template_literal: "\u0111\u1EA7u v\xE0o"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${parsedType4(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`;
- return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`;
- return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`;
- if (_issue.format === "ends_with")
- return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`;
- if (_issue.format === "includes")
- return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`;
- return `${Nouns[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`;
- }
- case "not_multiple_of":
- return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`;
- case "unrecognized_keys":
- return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
- case "invalid_union":
- return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";
- case "invalid_element":
- return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
- default:
- return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`;
- }
- };
-};
-var init_vi = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/zh-CN.js
-function zh_CN_default() {
- return {
- localeError: error38()
- };
-}
-var error38 = () => {
- const Sizable = {
- string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" },
- file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" },
- array: { unit: "\u9879", verb: "\u5305\u542B" },
- set: { unit: "\u9879", verb: "\u5305\u542B" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType4 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "\u975E\u6570\u5B57(NaN)" : "\u6570\u5B57";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "\u6570\u7EC4";
- }
- if (data === null) {
- return "\u7A7A\u503C(null)";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u8F93\u5165",
- email: "\u7535\u5B50\u90AE\u4EF6",
- url: "URL",
- emoji: "\u8868\u60C5\u7B26\u53F7",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO\u65E5\u671F\u65F6\u95F4",
- date: "ISO\u65E5\u671F",
- time: "ISO\u65F6\u95F4",
- duration: "ISO\u65F6\u957F",
- ipv4: "IPv4\u5730\u5740",
- ipv6: "IPv6\u5730\u5740",
- cidrv4: "IPv4\u7F51\u6BB5",
- cidrv6: "IPv6\u7F51\u6BB5",
- base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32",
- base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32",
- json_string: "JSON\u5B57\u7B26\u4E32",
- e164: "E.164\u53F7\u7801",
- jwt: "JWT",
- template_literal: "\u8F93\u5165"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${parsedType4(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`;
- return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`;
- return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with")
- return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`;
- if (_issue.format === "ends_with")
- return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`;
- if (_issue.format === "includes")
- return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`;
- return `\u65E0\u6548${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`;
- case "unrecognized_keys":
- return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`;
- case "invalid_key":
- return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;
- case "invalid_union":
- return "\u65E0\u6548\u8F93\u5165";
- case "invalid_element":
- return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;
- default:
- return `\u65E0\u6548\u8F93\u5165`;
- }
- };
-};
-var init_zh_CN = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/zh-TW.js
-function zh_TW_default() {
- return {
- localeError: error39()
- };
-}
-var error39 = () => {
- const Sizable = {
- string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" },
- file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" },
- array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" },
- set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }
- };
- function getSizing(origin2) {
- return Sizable[origin2] ?? null;
- }
- const parsedType4 = (data) => {
- const t = typeof data;
- switch (t) {
- case "number": {
- return Number.isNaN(data) ? "NaN" : "number";
- }
- case "object": {
- if (Array.isArray(data)) {
- return "array";
- }
- if (data === null) {
- return "null";
- }
- if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
- return data.constructor.name;
- }
- }
- }
- return t;
- };
- const Nouns = {
- regex: "\u8F38\u5165",
- email: "\u90F5\u4EF6\u5730\u5740",
- url: "URL",
- emoji: "emoji",
- uuid: "UUID",
- uuidv4: "UUIDv4",
- uuidv6: "UUIDv6",
- nanoid: "nanoid",
- guid: "GUID",
- cuid: "cuid",
- cuid2: "cuid2",
- ulid: "ULID",
- xid: "XID",
- ksuid: "KSUID",
- datetime: "ISO \u65E5\u671F\u6642\u9593",
- date: "ISO \u65E5\u671F",
- time: "ISO \u6642\u9593",
- duration: "ISO \u671F\u9593",
- ipv4: "IPv4 \u4F4D\u5740",
- ipv6: "IPv6 \u4F4D\u5740",
- cidrv4: "IPv4 \u7BC4\u570D",
- cidrv6: "IPv6 \u7BC4\u570D",
- base64: "base64 \u7DE8\u78BC\u5B57\u4E32",
- base64url: "base64url \u7DE8\u78BC\u5B57\u4E32",
- json_string: "JSON \u5B57\u4E32",
- e164: "E.164 \u6578\u503C",
- jwt: "JWT",
- template_literal: "\u8F38\u5165"
- };
- return (issue2) => {
- switch (issue2.code) {
- case "invalid_type":
- return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${parsedType4(issue2.input)}`;
- case "invalid_value":
- if (issue2.values.length === 1)
- return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`;
- return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
- case "too_big": {
- const adj = issue2.inclusive ? "<=" : "<";
- const sizing = getSizing(issue2.origin);
- if (sizing)
- return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`;
- return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`;
- }
- case "too_small": {
- const adj = issue2.inclusive ? ">=" : ">";
- const sizing = getSizing(issue2.origin);
- if (sizing) {
- return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
- }
- return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`;
- }
- case "invalid_format": {
- const _issue = issue2;
- if (_issue.format === "starts_with") {
- return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`;
- }
- if (_issue.format === "ends_with")
- return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`;
- if (_issue.format === "includes")
- return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`;
- if (_issue.format === "regex")
- return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`;
- return `\u7121\u6548\u7684 ${Nouns[_issue.format] ?? issue2.format}`;
- }
- case "not_multiple_of":
- return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`;
- case "unrecognized_keys":
- return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`;
- case "invalid_key":
- return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;
- case "invalid_union":
- return "\u7121\u6548\u7684\u8F38\u5165\u503C";
- case "invalid_element":
- return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;
- default:
- return `\u7121\u6548\u7684\u8F38\u5165\u503C`;
- }
- };
-};
-var init_zh_TW = __esm(() => {
- init_util2();
-});
-
-// node_modules/zod/v4/locales/index.js
-var exports_locales = {};
-__export(exports_locales, {
- zhTW: () => zh_TW_default,
- zhCN: () => zh_CN_default,
- vi: () => vi_default,
- ur: () => ur_default,
- ua: () => ua_default,
- tr: () => tr_default,
- th: () => th_default,
- ta: () => ta_default,
- sv: () => sv_default,
- sl: () => sl_default,
- ru: () => ru_default,
- pt: () => pt_default,
- ps: () => ps_default,
- pl: () => pl_default,
- ota: () => ota_default,
- no: () => no_default,
- nl: () => nl_default,
- ms: () => ms_default,
- mk: () => mk_default,
- ko: () => ko_default,
- kh: () => kh_default,
- ja: () => ja_default,
- it: () => it_default,
- id: () => id_default,
- hu: () => hu_default,
- he: () => he_default,
- frCA: () => fr_CA_default,
- fr: () => fr_default,
- fi: () => fi_default,
- fa: () => fa_default,
- es: () => es_default,
- eo: () => eo_default,
- en: () => en_default,
- de: () => de_default,
- cs: () => cs_default,
- ca: () => ca_default,
- be: () => be_default,
- az: () => az_default,
- ar: () => ar_default
-});
-var init_locales = __esm(() => {
- init_ar();
- init_az();
- init_be();
- init_ca();
- init_cs();
- init_de();
- init_en();
- init_eo();
- init_es();
- init_fa();
- init_fi();
- init_fr();
- init_fr_CA();
- init_he();
- init_hu();
- init_id();
- init_it();
- init_ja();
- init_kh();
- init_ko();
- init_mk();
- init_ms();
- init_nl();
- init_no();
- init_ota();
- init_ps();
- init_pl();
- init_pt();
- init_ru();
- init_sl();
- init_sv();
- init_ta();
- init_th();
- init_tr();
- init_ua();
- init_ur();
- init_vi();
- init_zh_CN();
- init_zh_TW();
-});
-
-// node_modules/zod/v4/core/registries.js
-class $ZodRegistry {
- constructor() {
- this._map = new Map;
- this._idmap = new Map;
- }
- add(schema, ..._meta) {
- const meta = _meta[0];
- this._map.set(schema, meta);
- if (meta && typeof meta === "object" && "id" in meta) {
- if (this._idmap.has(meta.id)) {
- throw new Error(`ID ${meta.id} already exists in the registry`);
- }
- this._idmap.set(meta.id, schema);
- }
- return this;
- }
- clear() {
- this._map = new Map;
- this._idmap = new Map;
- return this;
- }
- remove(schema) {
- const meta = this._map.get(schema);
- if (meta && typeof meta === "object" && "id" in meta) {
- this._idmap.delete(meta.id);
- }
- this._map.delete(schema);
- return this;
- }
- get(schema) {
- const p = schema._zod.parent;
- if (p) {
- const pm = { ...this.get(p) ?? {} };
- delete pm.id;
- return { ...pm, ...this._map.get(schema) };
- }
- return this._map.get(schema);
- }
- has(schema) {
- return this._map.has(schema);
- }
-}
-function registry2() {
- return new $ZodRegistry;
-}
-var $output, $input, globalRegistry;
-var init_registries = __esm(() => {
- $output = Symbol("ZodOutput");
- $input = Symbol("ZodInput");
- globalRegistry = /* @__PURE__ */ registry2();
-});
-
-// node_modules/zod/v4/core/api.js
-function _string(Class2, params) {
- return new Class2({
- type: "string",
- ...normalizeParams(params)
- });
-}
-function _coercedString(Class2, params) {
- return new Class2({
- type: "string",
- coerce: true,
- ...normalizeParams(params)
- });
-}
-function _email(Class2, params) {
- return new Class2({
- type: "string",
- format: "email",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _guid(Class2, params) {
- return new Class2({
- type: "string",
- format: "guid",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _uuid(Class2, params) {
- return new Class2({
- type: "string",
- format: "uuid",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _uuidv4(Class2, params) {
- return new Class2({
- type: "string",
- format: "uuid",
- check: "string_format",
- abort: false,
- version: "v4",
- ...normalizeParams(params)
- });
-}
-function _uuidv6(Class2, params) {
- return new Class2({
- type: "string",
- format: "uuid",
- check: "string_format",
- abort: false,
- version: "v6",
- ...normalizeParams(params)
- });
-}
-function _uuidv7(Class2, params) {
- return new Class2({
- type: "string",
- format: "uuid",
- check: "string_format",
- abort: false,
- version: "v7",
- ...normalizeParams(params)
- });
-}
-function _url(Class2, params) {
- return new Class2({
- type: "string",
- format: "url",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _emoji2(Class2, params) {
- return new Class2({
- type: "string",
- format: "emoji",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _nanoid(Class2, params) {
- return new Class2({
- type: "string",
- format: "nanoid",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _cuid(Class2, params) {
- return new Class2({
- type: "string",
- format: "cuid",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _cuid2(Class2, params) {
- return new Class2({
- type: "string",
- format: "cuid2",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _ulid(Class2, params) {
- return new Class2({
- type: "string",
- format: "ulid",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _xid(Class2, params) {
- return new Class2({
- type: "string",
- format: "xid",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _ksuid(Class2, params) {
- return new Class2({
- type: "string",
- format: "ksuid",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _ipv4(Class2, params) {
- return new Class2({
- type: "string",
- format: "ipv4",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _ipv6(Class2, params) {
- return new Class2({
- type: "string",
- format: "ipv6",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _cidrv4(Class2, params) {
- return new Class2({
- type: "string",
- format: "cidrv4",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _cidrv6(Class2, params) {
- return new Class2({
- type: "string",
- format: "cidrv6",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _base64(Class2, params) {
- return new Class2({
- type: "string",
- format: "base64",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _base64url(Class2, params) {
- return new Class2({
- type: "string",
- format: "base64url",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _e164(Class2, params) {
- return new Class2({
- type: "string",
- format: "e164",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _jwt(Class2, params) {
- return new Class2({
- type: "string",
- format: "jwt",
- check: "string_format",
- abort: false,
- ...normalizeParams(params)
- });
-}
-function _isoDateTime(Class2, params) {
- return new Class2({
- type: "string",
- format: "datetime",
- check: "string_format",
- offset: false,
- local: false,
- precision: null,
- ...normalizeParams(params)
- });
-}
-function _isoDate(Class2, params) {
- return new Class2({
- type: "string",
- format: "date",
- check: "string_format",
- ...normalizeParams(params)
- });
-}
-function _isoTime(Class2, params) {
- return new Class2({
- type: "string",
- format: "time",
- check: "string_format",
- precision: null,
- ...normalizeParams(params)
- });
-}
-function _isoDuration(Class2, params) {
- return new Class2({
- type: "string",
- format: "duration",
- check: "string_format",
- ...normalizeParams(params)
- });
-}
-function _number(Class2, params) {
- return new Class2({
- type: "number",
- checks: [],
- ...normalizeParams(params)
- });
-}
-function _coercedNumber(Class2, params) {
- return new Class2({
- type: "number",
- coerce: true,
- checks: [],
- ...normalizeParams(params)
- });
-}
-function _int(Class2, params) {
- return new Class2({
- type: "number",
- check: "number_format",
- abort: false,
- format: "safeint",
- ...normalizeParams(params)
- });
-}
-function _float32(Class2, params) {
- return new Class2({
- type: "number",
- check: "number_format",
- abort: false,
- format: "float32",
- ...normalizeParams(params)
- });
-}
-function _float64(Class2, params) {
- return new Class2({
- type: "number",
- check: "number_format",
- abort: false,
- format: "float64",
- ...normalizeParams(params)
- });
-}
-function _int32(Class2, params) {
- return new Class2({
- type: "number",
- check: "number_format",
- abort: false,
- format: "int32",
- ...normalizeParams(params)
- });
-}
-function _uint32(Class2, params) {
- return new Class2({
- type: "number",
- check: "number_format",
- abort: false,
- format: "uint32",
- ...normalizeParams(params)
- });
-}
-function _boolean(Class2, params) {
- return new Class2({
- type: "boolean",
- ...normalizeParams(params)
- });
-}
-function _coercedBoolean(Class2, params) {
- return new Class2({
- type: "boolean",
- coerce: true,
- ...normalizeParams(params)
- });
-}
-function _bigint(Class2, params) {
- return new Class2({
- type: "bigint",
- ...normalizeParams(params)
- });
-}
-function _coercedBigint(Class2, params) {
- return new Class2({
- type: "bigint",
- coerce: true,
- ...normalizeParams(params)
- });
-}
-function _int64(Class2, params) {
- return new Class2({
- type: "bigint",
- check: "bigint_format",
- abort: false,
- format: "int64",
- ...normalizeParams(params)
- });
-}
-function _uint64(Class2, params) {
- return new Class2({
- type: "bigint",
- check: "bigint_format",
- abort: false,
- format: "uint64",
- ...normalizeParams(params)
- });
-}
-function _symbol(Class2, params) {
- return new Class2({
- type: "symbol",
- ...normalizeParams(params)
- });
-}
-function _undefined2(Class2, params) {
- return new Class2({
- type: "undefined",
- ...normalizeParams(params)
- });
-}
-function _null2(Class2, params) {
- return new Class2({
- type: "null",
- ...normalizeParams(params)
- });
-}
-function _any(Class2) {
- return new Class2({
- type: "any"
- });
-}
-function _unknown(Class2) {
- return new Class2({
- type: "unknown"
- });
-}
-function _never(Class2, params) {
- return new Class2({
- type: "never",
- ...normalizeParams(params)
- });
-}
-function _void(Class2, params) {
- return new Class2({
- type: "void",
- ...normalizeParams(params)
- });
-}
-function _date(Class2, params) {
- return new Class2({
- type: "date",
- ...normalizeParams(params)
- });
-}
-function _coercedDate(Class2, params) {
- return new Class2({
- type: "date",
- coerce: true,
- ...normalizeParams(params)
- });
-}
-function _nan(Class2, params) {
- return new Class2({
- type: "nan",
- ...normalizeParams(params)
- });
-}
-function _lt(value, params) {
- return new $ZodCheckLessThan({
- check: "less_than",
- ...normalizeParams(params),
- value,
- inclusive: false
- });
-}
-function _lte(value, params) {
- return new $ZodCheckLessThan({
- check: "less_than",
- ...normalizeParams(params),
- value,
- inclusive: true
- });
-}
-function _gt(value, params) {
- return new $ZodCheckGreaterThan({
- check: "greater_than",
- ...normalizeParams(params),
- value,
- inclusive: false
- });
-}
-function _gte(value, params) {
- return new $ZodCheckGreaterThan({
- check: "greater_than",
- ...normalizeParams(params),
- value,
- inclusive: true
- });
-}
-function _positive(params) {
- return _gt(0, params);
-}
-function _negative(params) {
- return _lt(0, params);
-}
-function _nonpositive(params) {
- return _lte(0, params);
-}
-function _nonnegative(params) {
- return _gte(0, params);
-}
-function _multipleOf(value, params) {
- return new $ZodCheckMultipleOf({
- check: "multiple_of",
- ...normalizeParams(params),
- value
- });
-}
-function _maxSize(maximum, params) {
- return new $ZodCheckMaxSize({
- check: "max_size",
- ...normalizeParams(params),
- maximum
- });
-}
-function _minSize(minimum, params) {
- return new $ZodCheckMinSize({
- check: "min_size",
- ...normalizeParams(params),
- minimum
- });
-}
-function _size(size, params) {
- return new $ZodCheckSizeEquals({
- check: "size_equals",
- ...normalizeParams(params),
- size
- });
-}
-function _maxLength(maximum, params) {
- const ch = new $ZodCheckMaxLength({
- check: "max_length",
- ...normalizeParams(params),
- maximum
- });
- return ch;
-}
-function _minLength(minimum, params) {
- return new $ZodCheckMinLength({
- check: "min_length",
- ...normalizeParams(params),
- minimum
- });
-}
-function _length(length, params) {
- return new $ZodCheckLengthEquals({
- check: "length_equals",
- ...normalizeParams(params),
- length
- });
-}
-function _regex(pattern, params) {
- return new $ZodCheckRegex({
- check: "string_format",
- format: "regex",
- ...normalizeParams(params),
- pattern
- });
-}
-function _lowercase(params) {
- return new $ZodCheckLowerCase({
- check: "string_format",
- format: "lowercase",
- ...normalizeParams(params)
- });
-}
-function _uppercase(params) {
- return new $ZodCheckUpperCase({
- check: "string_format",
- format: "uppercase",
- ...normalizeParams(params)
- });
-}
-function _includes(includes, params) {
- return new $ZodCheckIncludes({
- check: "string_format",
- format: "includes",
- ...normalizeParams(params),
- includes
- });
-}
-function _startsWith(prefix, params) {
- return new $ZodCheckStartsWith({
- check: "string_format",
- format: "starts_with",
- ...normalizeParams(params),
- prefix
- });
-}
-function _endsWith(suffix, params) {
- return new $ZodCheckEndsWith({
- check: "string_format",
- format: "ends_with",
- ...normalizeParams(params),
- suffix
- });
-}
-function _property(property2, schema, params) {
- return new $ZodCheckProperty({
- check: "property",
- property: property2,
- schema,
- ...normalizeParams(params)
- });
-}
-function _mime(types, params) {
- return new $ZodCheckMimeType({
- check: "mime_type",
- mime: types,
- ...normalizeParams(params)
- });
-}
-function _overwrite(tx) {
- return new $ZodCheckOverwrite({
- check: "overwrite",
- tx
- });
-}
-function _normalize(form) {
- return _overwrite((input) => input.normalize(form));
-}
-function _trim() {
- return _overwrite((input) => input.trim());
-}
-function _toLowerCase() {
- return _overwrite((input) => input.toLowerCase());
-}
-function _toUpperCase() {
- return _overwrite((input) => input.toUpperCase());
-}
-function _array(Class2, element, params) {
- return new Class2({
- type: "array",
- element,
- ...normalizeParams(params)
- });
-}
-function _union(Class2, options2, params) {
- return new Class2({
- type: "union",
- options: options2,
- ...normalizeParams(params)
- });
-}
-function _discriminatedUnion(Class2, discriminator, options2, params) {
- return new Class2({
- type: "union",
- options: options2,
- discriminator,
- ...normalizeParams(params)
- });
-}
-function _intersection(Class2, left, right) {
- return new Class2({
- type: "intersection",
- left,
- right
- });
-}
-function _tuple(Class2, items, _paramsOrRest, _params) {
- const hasRest = _paramsOrRest instanceof $ZodType;
- const params = hasRest ? _params : _paramsOrRest;
- const rest = hasRest ? _paramsOrRest : null;
- return new Class2({
- type: "tuple",
- items,
- rest,
- ...normalizeParams(params)
- });
-}
-function _record(Class2, keyType, valueType, params) {
- return new Class2({
- type: "record",
- keyType,
- valueType,
- ...normalizeParams(params)
- });
-}
-function _map(Class2, keyType, valueType, params) {
- return new Class2({
- type: "map",
- keyType,
- valueType,
- ...normalizeParams(params)
- });
-}
-function _set(Class2, valueType, params) {
- return new Class2({
- type: "set",
- valueType,
- ...normalizeParams(params)
- });
-}
-function _enum(Class2, values, params) {
- const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
- return new Class2({
- type: "enum",
- entries,
- ...normalizeParams(params)
- });
-}
-function _nativeEnum(Class2, entries, params) {
- return new Class2({
- type: "enum",
- entries,
- ...normalizeParams(params)
- });
-}
-function _literal(Class2, value, params) {
- return new Class2({
- type: "literal",
- values: Array.isArray(value) ? value : [value],
- ...normalizeParams(params)
- });
-}
-function _file(Class2, params) {
- return new Class2({
- type: "file",
- ...normalizeParams(params)
- });
-}
-function _transform(Class2, fn) {
- return new Class2({
- type: "transform",
- transform: fn
- });
-}
-function _optional(Class2, innerType) {
- return new Class2({
- type: "optional",
- innerType
- });
-}
-function _nullable(Class2, innerType) {
- return new Class2({
- type: "nullable",
- innerType
- });
-}
-function _default(Class2, innerType, defaultValue) {
- return new Class2({
- type: "default",
- innerType,
- get defaultValue() {
- return typeof defaultValue === "function" ? defaultValue() : defaultValue;
- }
- });
-}
-function _nonoptional(Class2, innerType, params) {
- return new Class2({
- type: "nonoptional",
- innerType,
- ...normalizeParams(params)
- });
-}
-function _success(Class2, innerType) {
- return new Class2({
- type: "success",
- innerType
- });
-}
-function _catch(Class2, innerType, catchValue) {
- return new Class2({
- type: "catch",
- innerType,
- catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
- });
-}
-function _pipe(Class2, in_, out) {
- return new Class2({
- type: "pipe",
- in: in_,
- out
- });
-}
-function _readonly(Class2, innerType) {
- return new Class2({
- type: "readonly",
- innerType
- });
-}
-function _templateLiteral(Class2, parts, params) {
- return new Class2({
- type: "template_literal",
- parts,
- ...normalizeParams(params)
- });
-}
-function _lazy(Class2, getter) {
- return new Class2({
- type: "lazy",
- getter
- });
-}
-function _promise(Class2, innerType) {
- return new Class2({
- type: "promise",
- innerType
- });
-}
-function _custom(Class2, fn, _params) {
- const norm = normalizeParams(_params);
- norm.abort ?? (norm.abort = true);
- const schema = new Class2({
- type: "custom",
- check: "custom",
- fn,
- ...norm
- });
- return schema;
-}
-function _refine(Class2, fn, _params) {
- const schema = new Class2({
- type: "custom",
- check: "custom",
- fn,
- ...normalizeParams(_params)
- });
- return schema;
-}
-function _stringbool(Classes, _params) {
- const params = normalizeParams(_params);
- let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"];
- let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"];
- if (params.case !== "sensitive") {
- truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
- falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
- }
- const truthySet = new Set(truthyArray);
- const falsySet = new Set(falsyArray);
- const _Pipe = Classes.Pipe ?? $ZodPipe;
- const _Boolean = Classes.Boolean ?? $ZodBoolean;
- const _String = Classes.String ?? $ZodString;
- const _Transform = Classes.Transform ?? $ZodTransform;
- const tx = new _Transform({
- type: "transform",
- transform: (input, payload) => {
- let data = input;
- if (params.case !== "sensitive")
- data = data.toLowerCase();
- if (truthySet.has(data)) {
- return true;
- } else if (falsySet.has(data)) {
- return false;
- } else {
- payload.issues.push({
- code: "invalid_value",
- expected: "stringbool",
- values: [...truthySet, ...falsySet],
- input: payload.value,
- inst: tx
- });
- return {};
- }
- },
- error: params.error
- });
- const innerPipe = new _Pipe({
- type: "pipe",
- in: new _String({ type: "string", error: params.error }),
- out: tx,
- error: params.error
- });
- const outerPipe = new _Pipe({
- type: "pipe",
- in: innerPipe,
- out: new _Boolean({
- type: "boolean",
- error: params.error
- }),
- error: params.error
- });
- return outerPipe;
-}
-function _stringFormat(Class2, format3, fnOrRegex, _params = {}) {
- const params = normalizeParams(_params);
- const def2 = {
- ...normalizeParams(_params),
- check: "string_format",
- type: "string",
- format: format3,
- fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
- ...params
- };
- if (fnOrRegex instanceof RegExp) {
- def2.pattern = fnOrRegex;
- }
- const inst = new Class2(def2);
- return inst;
-}
-var TimePrecision;
-var init_api = __esm(() => {
- init_checks();
- init_schemas();
- init_util2();
- TimePrecision = {
- Any: null,
- Minute: -1,
- Second: 0,
- Millisecond: 3,
- Microsecond: 6
- };
-});
-
-// node_modules/zod/v4/core/function.js
-class $ZodFunction {
- constructor(def2) {
- this._def = def2;
- this.def = def2;
- }
- implement(func) {
- if (typeof func !== "function") {
- throw new Error("implement() must be called with a function");
- }
- const impl = (...args) => {
- const parsedArgs = this._def.input ? parse3(this._def.input, args, undefined, { callee: impl }) : args;
- if (!Array.isArray(parsedArgs)) {
- throw new Error("Invalid arguments schema: not an array or tuple schema.");
- }
- const output = func(...parsedArgs);
- return this._def.output ? parse3(this._def.output, output, undefined, { callee: impl }) : output;
- };
- return impl;
- }
- implementAsync(func) {
- if (typeof func !== "function") {
- throw new Error("implement() must be called with a function");
- }
- const impl = async (...args) => {
- const parsedArgs = this._def.input ? await parseAsync(this._def.input, args, undefined, { callee: impl }) : args;
- if (!Array.isArray(parsedArgs)) {
- throw new Error("Invalid arguments schema: not an array or tuple schema.");
- }
- const output = await func(...parsedArgs);
- return this._def.output ? parseAsync(this._def.output, output, undefined, { callee: impl }) : output;
- };
- return impl;
- }
- input(...args) {
- const F = this.constructor;
- if (Array.isArray(args[0])) {
- return new F({
- type: "function",
- input: new $ZodTuple({
- type: "tuple",
- items: args[0],
- rest: args[1]
- }),
- output: this._def.output
- });
- }
- return new F({
- type: "function",
- input: args[0],
- output: this._def.output
- });
- }
- output(output) {
- const F = this.constructor;
- return new F({
- type: "function",
- input: this._def.input,
- output
- });
- }
-}
-function _function(params) {
- return new $ZodFunction({
- type: "function",
- input: Array.isArray(params?.input) ? _tuple($ZodTuple, params?.input) : params?.input ?? _array($ZodArray, _unknown($ZodUnknown)),
- output: params?.output ?? _unknown($ZodUnknown)
- });
-}
-var init_function = __esm(() => {
- init_api();
- init_parse();
- init_schemas();
- init_schemas();
-});
-
-// node_modules/zod/v4/core/to-json-schema.js
-class JSONSchemaGenerator {
- constructor(params) {
- this.counter = 0;
- this.metadataRegistry = params?.metadata ?? globalRegistry;
- this.target = params?.target ?? "draft-2020-12";
- this.unrepresentable = params?.unrepresentable ?? "throw";
- this.override = params?.override ?? (() => {});
- this.io = params?.io ?? "output";
- this.seen = new Map;
- }
- process(schema, _params = { path: [], schemaPath: [] }) {
- var _a2;
- const def2 = schema._zod.def;
- const formatMap = {
- guid: "uuid",
- url: "uri",
- datetime: "date-time",
- json_string: "json-string",
- regex: ""
- };
- const seen = this.seen.get(schema);
- if (seen) {
- seen.count++;
- const isCycle = _params.schemaPath.includes(schema);
- if (isCycle) {
- seen.cycle = _params.path;
- }
- return seen.schema;
- }
- const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
- this.seen.set(schema, result);
- const overrideSchema = schema._zod.toJSONSchema?.();
- if (overrideSchema) {
- result.schema = overrideSchema;
- } else {
- const params = {
- ..._params,
- schemaPath: [..._params.schemaPath, schema],
- path: _params.path
- };
- const parent = schema._zod.parent;
- if (parent) {
- result.ref = parent;
- this.process(parent, params);
- this.seen.get(parent).isParent = true;
- } else {
- const _json = result.schema;
- switch (def2.type) {
- case "string": {
- const json = _json;
- json.type = "string";
- const { minimum, maximum, format: format3, patterns, contentEncoding } = schema._zod.bag;
- if (typeof minimum === "number")
- json.minLength = minimum;
- if (typeof maximum === "number")
- json.maxLength = maximum;
- if (format3) {
- json.format = formatMap[format3] ?? format3;
- if (json.format === "")
- delete json.format;
- }
- if (contentEncoding)
- json.contentEncoding = contentEncoding;
- if (patterns && patterns.size > 0) {
- const regexes = [...patterns];
- if (regexes.length === 1)
- json.pattern = regexes[0].source;
- else if (regexes.length > 1) {
- result.schema.allOf = [
- ...regexes.map((regex2) => ({
- ...this.target === "draft-7" ? { type: "string" } : {},
- pattern: regex2.source
- }))
- ];
- }
- }
- break;
- }
- case "number": {
- const json = _json;
- const { minimum, maximum, format: format3, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
- if (typeof format3 === "string" && format3.includes("int"))
- json.type = "integer";
- else
- json.type = "number";
- if (typeof exclusiveMinimum === "number")
- json.exclusiveMinimum = exclusiveMinimum;
- if (typeof minimum === "number") {
- json.minimum = minimum;
- if (typeof exclusiveMinimum === "number") {
- if (exclusiveMinimum >= minimum)
- delete json.minimum;
- else
- delete json.exclusiveMinimum;
- }
- }
- if (typeof exclusiveMaximum === "number")
- json.exclusiveMaximum = exclusiveMaximum;
- if (typeof maximum === "number") {
- json.maximum = maximum;
- if (typeof exclusiveMaximum === "number") {
- if (exclusiveMaximum <= maximum)
- delete json.maximum;
- else
- delete json.exclusiveMaximum;
- }
- }
- if (typeof multipleOf === "number")
- json.multipleOf = multipleOf;
- break;
- }
- case "boolean": {
- const json = _json;
- json.type = "boolean";
- break;
- }
- case "bigint": {
- if (this.unrepresentable === "throw") {
- throw new Error("BigInt cannot be represented in JSON Schema");
- }
- break;
- }
- case "symbol": {
- if (this.unrepresentable === "throw") {
- throw new Error("Symbols cannot be represented in JSON Schema");
- }
- break;
- }
- case "null": {
- _json.type = "null";
- break;
- }
- case "any": {
- break;
- }
- case "unknown": {
- break;
- }
- case "undefined": {
- if (this.unrepresentable === "throw") {
- throw new Error("Undefined cannot be represented in JSON Schema");
- }
- break;
- }
- case "void": {
- if (this.unrepresentable === "throw") {
- throw new Error("Void cannot be represented in JSON Schema");
- }
- break;
- }
- case "never": {
- _json.not = {};
- break;
- }
- case "date": {
- if (this.unrepresentable === "throw") {
- throw new Error("Date cannot be represented in JSON Schema");
- }
- break;
- }
- case "array": {
- const json = _json;
- const { minimum, maximum } = schema._zod.bag;
- if (typeof minimum === "number")
- json.minItems = minimum;
- if (typeof maximum === "number")
- json.maxItems = maximum;
- json.type = "array";
- json.items = this.process(def2.element, { ...params, path: [...params.path, "items"] });
- break;
- }
- case "object": {
- const json = _json;
- json.type = "object";
- json.properties = {};
- const shape = def2.shape;
- for (const key in shape) {
- json.properties[key] = this.process(shape[key], {
- ...params,
- path: [...params.path, "properties", key]
- });
- }
- const allKeys = new Set(Object.keys(shape));
- const requiredKeys = new Set([...allKeys].filter((key) => {
- const v = def2.shape[key]._zod;
- if (this.io === "input") {
- return v.optin === undefined;
- } else {
- return v.optout === undefined;
- }
- }));
- if (requiredKeys.size > 0) {
- json.required = Array.from(requiredKeys);
- }
- if (def2.catchall?._zod.def.type === "never") {
- json.additionalProperties = false;
- } else if (!def2.catchall) {
- if (this.io === "output")
- json.additionalProperties = false;
- } else if (def2.catchall) {
- json.additionalProperties = this.process(def2.catchall, {
- ...params,
- path: [...params.path, "additionalProperties"]
- });
- }
- break;
- }
- case "union": {
- const json = _json;
- json.anyOf = def2.options.map((x2, i2) => this.process(x2, {
- ...params,
- path: [...params.path, "anyOf", i2]
- }));
- break;
- }
- case "intersection": {
- const json = _json;
- const a2 = this.process(def2.left, {
- ...params,
- path: [...params.path, "allOf", 0]
- });
- const b = this.process(def2.right, {
- ...params,
- path: [...params.path, "allOf", 1]
- });
- const isSimpleIntersection = (val) => ("allOf" in val) && Object.keys(val).length === 1;
- const allOf = [
- ...isSimpleIntersection(a2) ? a2.allOf : [a2],
- ...isSimpleIntersection(b) ? b.allOf : [b]
- ];
- json.allOf = allOf;
- break;
- }
- case "tuple": {
- const json = _json;
- json.type = "array";
- const prefixItems = def2.items.map((x2, i2) => this.process(x2, { ...params, path: [...params.path, "prefixItems", i2] }));
- if (this.target === "draft-2020-12") {
- json.prefixItems = prefixItems;
- } else {
- json.items = prefixItems;
- }
- if (def2.rest) {
- const rest = this.process(def2.rest, {
- ...params,
- path: [...params.path, "items"]
- });
- if (this.target === "draft-2020-12") {
- json.items = rest;
- } else {
- json.additionalItems = rest;
- }
- }
- if (def2.rest) {
- json.items = this.process(def2.rest, {
- ...params,
- path: [...params.path, "items"]
- });
- }
- const { minimum, maximum } = schema._zod.bag;
- if (typeof minimum === "number")
- json.minItems = minimum;
- if (typeof maximum === "number")
- json.maxItems = maximum;
- break;
- }
- case "record": {
- const json = _json;
- json.type = "object";
- json.propertyNames = this.process(def2.keyType, { ...params, path: [...params.path, "propertyNames"] });
- json.additionalProperties = this.process(def2.valueType, {
- ...params,
- path: [...params.path, "additionalProperties"]
- });
- break;
- }
- case "map": {
- if (this.unrepresentable === "throw") {
- throw new Error("Map cannot be represented in JSON Schema");
- }
- break;
- }
- case "set": {
- if (this.unrepresentable === "throw") {
- throw new Error("Set cannot be represented in JSON Schema");
- }
- break;
- }
- case "enum": {
- const json = _json;
- const values = getEnumValues(def2.entries);
- if (values.every((v) => typeof v === "number"))
- json.type = "number";
- if (values.every((v) => typeof v === "string"))
- json.type = "string";
- json.enum = values;
- break;
- }
- case "literal": {
- const json = _json;
- const vals = [];
- for (const val of def2.values) {
- if (val === undefined) {
- if (this.unrepresentable === "throw") {
- throw new Error("Literal `undefined` cannot be represented in JSON Schema");
- } else {}
- } else if (typeof val === "bigint") {
- if (this.unrepresentable === "throw") {
- throw new Error("BigInt literals cannot be represented in JSON Schema");
- } else {
- vals.push(Number(val));
- }
- } else {
- vals.push(val);
- }
- }
- if (vals.length === 0) {} else if (vals.length === 1) {
- const val = vals[0];
- json.type = val === null ? "null" : typeof val;
- json.const = val;
- } else {
- if (vals.every((v) => typeof v === "number"))
- json.type = "number";
- if (vals.every((v) => typeof v === "string"))
- json.type = "string";
- if (vals.every((v) => typeof v === "boolean"))
- json.type = "string";
- if (vals.every((v) => v === null))
- json.type = "null";
- json.enum = vals;
- }
- break;
- }
- case "file": {
- const json = _json;
- const file = {
- type: "string",
- format: "binary",
- contentEncoding: "binary"
- };
- const { minimum, maximum, mime } = schema._zod.bag;
- if (minimum !== undefined)
- file.minLength = minimum;
- if (maximum !== undefined)
- file.maxLength = maximum;
- if (mime) {
- if (mime.length === 1) {
- file.contentMediaType = mime[0];
- Object.assign(json, file);
- } else {
- json.anyOf = mime.map((m) => {
- const mFile = { ...file, contentMediaType: m };
- return mFile;
- });
- }
- } else {
- Object.assign(json, file);
- }
- break;
- }
- case "transform": {
- if (this.unrepresentable === "throw") {
- throw new Error("Transforms cannot be represented in JSON Schema");
- }
- break;
- }
- case "nullable": {
- const inner = this.process(def2.innerType, params);
- _json.anyOf = [inner, { type: "null" }];
- break;
- }
- case "nonoptional": {
- this.process(def2.innerType, params);
- result.ref = def2.innerType;
- break;
- }
- case "success": {
- const json = _json;
- json.type = "boolean";
- break;
- }
- case "default": {
- this.process(def2.innerType, params);
- result.ref = def2.innerType;
- _json.default = JSON.parse(JSON.stringify(def2.defaultValue));
- break;
- }
- case "prefault": {
- this.process(def2.innerType, params);
- result.ref = def2.innerType;
- if (this.io === "input")
- _json._prefault = JSON.parse(JSON.stringify(def2.defaultValue));
- break;
- }
- case "catch": {
- this.process(def2.innerType, params);
- result.ref = def2.innerType;
- let catchValue;
- try {
- catchValue = def2.catchValue(undefined);
- } catch {
- throw new Error("Dynamic catch values are not supported in JSON Schema");
- }
- _json.default = catchValue;
- break;
- }
- case "nan": {
- if (this.unrepresentable === "throw") {
- throw new Error("NaN cannot be represented in JSON Schema");
- }
- break;
- }
- case "template_literal": {
- const json = _json;
- const pattern = schema._zod.pattern;
- if (!pattern)
- throw new Error("Pattern not found in template literal");
- json.type = "string";
- json.pattern = pattern.source;
- break;
- }
- case "pipe": {
- const innerType = this.io === "input" ? def2.in._zod.def.type === "transform" ? def2.out : def2.in : def2.out;
- this.process(innerType, params);
- result.ref = innerType;
- break;
- }
- case "readonly": {
- this.process(def2.innerType, params);
- result.ref = def2.innerType;
- _json.readOnly = true;
- break;
- }
- case "promise": {
- this.process(def2.innerType, params);
- result.ref = def2.innerType;
- break;
- }
- case "optional": {
- this.process(def2.innerType, params);
- result.ref = def2.innerType;
- break;
- }
- case "lazy": {
- const innerType = schema._zod.innerType;
- this.process(innerType, params);
- result.ref = innerType;
- break;
- }
- case "custom": {
- if (this.unrepresentable === "throw") {
- throw new Error("Custom types cannot be represented in JSON Schema");
- }
- break;
- }
- default: {}
- }
- }
- }
- const meta = this.metadataRegistry.get(schema);
- if (meta)
- Object.assign(result.schema, meta);
- if (this.io === "input" && isTransforming(schema)) {
- delete result.schema.examples;
- delete result.schema.default;
- }
- if (this.io === "input" && result.schema._prefault)
- (_a2 = result.schema).default ?? (_a2.default = result.schema._prefault);
- delete result.schema._prefault;
- const _result = this.seen.get(schema);
- return _result.schema;
- }
- emit(schema, _params) {
- const params = {
- cycles: _params?.cycles ?? "ref",
- reused: _params?.reused ?? "inline",
- external: _params?.external ?? undefined
- };
- const root2 = this.seen.get(schema);
- if (!root2)
- throw new Error("Unprocessed schema. This is a bug in Zod.");
- const makeURI = (entry) => {
- const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions";
- if (params.external) {
- const externalId = params.external.registry.get(entry[0])?.id;
- const uriGenerator = params.external.uri ?? ((id2) => id2);
- if (externalId) {
- return { ref: uriGenerator(externalId) };
- }
- const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;
- entry[1].defId = id;
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
- }
- if (entry[1] === root2) {
- return { ref: "#" };
- }
- const uriPrefix = `#`;
- const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
- const defId = entry[1].schema.id ?? `__schema${this.counter++}`;
- return { defId, ref: defUriPrefix + defId };
- };
- const extractToDef = (entry) => {
- if (entry[1].schema.$ref) {
- return;
- }
- const seen = entry[1];
- const { ref, defId } = makeURI(entry);
- seen.def = { ...seen.schema };
- if (defId)
- seen.defId = defId;
- const schema2 = seen.schema;
- for (const key in schema2) {
- delete schema2[key];
- }
- schema2.$ref = ref;
- };
- if (params.cycles === "throw") {
- for (const entry of this.seen.entries()) {
- const seen = entry[1];
- if (seen.cycle) {
- throw new Error("Cycle detected: " + `#/${seen.cycle?.join("/")}/` + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.');
- }
- }
- }
- for (const entry of this.seen.entries()) {
- const seen = entry[1];
- if (schema === entry[0]) {
- extractToDef(entry);
- continue;
- }
- if (params.external) {
- const ext = params.external.registry.get(entry[0])?.id;
- if (schema !== entry[0] && ext) {
- extractToDef(entry);
- continue;
- }
- }
- const id = this.metadataRegistry.get(entry[0])?.id;
- if (id) {
- extractToDef(entry);
- continue;
- }
- if (seen.cycle) {
- extractToDef(entry);
- continue;
- }
- if (seen.count > 1) {
- if (params.reused === "ref") {
- extractToDef(entry);
- continue;
- }
- }
- }
- const flattenRef = (zodSchema, params2) => {
- const seen = this.seen.get(zodSchema);
- const schema2 = seen.def ?? seen.schema;
- const _cached = { ...schema2 };
- if (seen.ref === null) {
- return;
- }
- const ref = seen.ref;
- seen.ref = null;
- if (ref) {
- flattenRef(ref, params2);
- const refSchema = this.seen.get(ref).schema;
- if (refSchema.$ref && params2.target === "draft-7") {
- schema2.allOf = schema2.allOf ?? [];
- schema2.allOf.push(refSchema);
- } else {
- Object.assign(schema2, refSchema);
- Object.assign(schema2, _cached);
- }
- }
- if (!seen.isParent)
- this.override({
- zodSchema,
- jsonSchema: schema2,
- path: seen.path ?? []
- });
- };
- for (const entry of [...this.seen.entries()].reverse()) {
- flattenRef(entry[0], { target: this.target });
- }
- const result = {};
- if (this.target === "draft-2020-12") {
- result.$schema = "https://json-schema.org/draft/2020-12/schema";
- } else if (this.target === "draft-7") {
- result.$schema = "http://json-schema.org/draft-07/schema#";
- } else {
- console.warn(`Invalid target: ${this.target}`);
- }
- if (params.external?.uri) {
- const id = params.external.registry.get(schema)?.id;
- if (!id)
- throw new Error("Schema is missing an `id` property");
- result.$id = params.external.uri(id);
- }
- Object.assign(result, root2.def);
- const defs = params.external?.defs ?? {};
- for (const entry of this.seen.entries()) {
- const seen = entry[1];
- if (seen.def && seen.defId) {
- defs[seen.defId] = seen.def;
- }
- }
- if (params.external) {} else {
- if (Object.keys(defs).length > 0) {
- if (this.target === "draft-2020-12") {
- result.$defs = defs;
- } else {
- result.definitions = defs;
- }
- }
- }
- try {
- return JSON.parse(JSON.stringify(result));
- } catch (_err) {
- throw new Error("Error converting schema to JSON.");
- }
- }
-}
-function toJSONSchema(input, _params) {
- if (input instanceof $ZodRegistry) {
- const gen2 = new JSONSchemaGenerator(_params);
- const defs = {};
- for (const entry of input._idmap.entries()) {
- const [_, schema] = entry;
- gen2.process(schema);
- }
- const schemas = {};
- const external = {
- registry: input,
- uri: _params?.uri,
- defs
- };
- for (const entry of input._idmap.entries()) {
- const [key, schema] = entry;
- schemas[key] = gen2.emit(schema, {
- ..._params,
- external
- });
- }
- if (Object.keys(defs).length > 0) {
- const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions";
- schemas.__shared = {
- [defsSegment]: defs
- };
- }
- return { schemas };
- }
- const gen = new JSONSchemaGenerator(_params);
- gen.process(input);
- return gen.emit(input, _params);
-}
-function isTransforming(_schema, _ctx) {
- const ctx = _ctx ?? { seen: new Set };
- if (ctx.seen.has(_schema))
- return false;
- ctx.seen.add(_schema);
- const schema = _schema;
- const def2 = schema._zod.def;
- switch (def2.type) {
- case "string":
- case "number":
- case "bigint":
- case "boolean":
- case "date":
- case "symbol":
- case "undefined":
- case "null":
- case "any":
- case "unknown":
- case "never":
- case "void":
- case "literal":
- case "enum":
- case "nan":
- case "file":
- case "template_literal":
- return false;
- case "array": {
- return isTransforming(def2.element, ctx);
- }
- case "object": {
- for (const key in def2.shape) {
- if (isTransforming(def2.shape[key], ctx))
- return true;
- }
- return false;
- }
- case "union": {
- for (const option of def2.options) {
- if (isTransforming(option, ctx))
- return true;
- }
- return false;
- }
- case "intersection": {
- return isTransforming(def2.left, ctx) || isTransforming(def2.right, ctx);
- }
- case "tuple": {
- for (const item of def2.items) {
- if (isTransforming(item, ctx))
- return true;
- }
- if (def2.rest && isTransforming(def2.rest, ctx))
- return true;
- return false;
- }
- case "record": {
- return isTransforming(def2.keyType, ctx) || isTransforming(def2.valueType, ctx);
- }
- case "map": {
- return isTransforming(def2.keyType, ctx) || isTransforming(def2.valueType, ctx);
- }
- case "set": {
- return isTransforming(def2.valueType, ctx);
- }
- case "promise":
- case "optional":
- case "nonoptional":
- case "nullable":
- case "readonly":
- return isTransforming(def2.innerType, ctx);
- case "lazy":
- return isTransforming(def2.getter(), ctx);
- case "default": {
- return isTransforming(def2.innerType, ctx);
- }
- case "prefault": {
- return isTransforming(def2.innerType, ctx);
- }
- case "custom": {
- return false;
- }
- case "transform": {
- return true;
- }
- case "pipe": {
- return isTransforming(def2.in, ctx) || isTransforming(def2.out, ctx);
- }
- case "success": {
- return false;
- }
- case "catch": {
- return false;
- }
- default:
- }
- throw new Error(`Unknown schema type: ${def2.type}`);
-}
-var init_to_json_schema = __esm(() => {
- init_registries();
- init_util2();
-});
-
-// node_modules/zod/v4/core/json-schema.js
-var exports_json_schema = {};
-var init_json_schema = () => {};
-
-// node_modules/zod/v4/core/index.js
-var exports_core3 = {};
-__export(exports_core3, {
- version: () => version,
- util: () => exports_util,
- treeifyError: () => treeifyError,
- toJSONSchema: () => toJSONSchema,
- toDotPath: () => toDotPath,
- safeParseAsync: () => safeParseAsync,
- safeParse: () => safeParse,
- registry: () => registry2,
- regexes: () => exports_regexes,
- prettifyError: () => prettifyError,
- parseAsync: () => parseAsync,
- parse: () => parse3,
- locales: () => exports_locales,
- isValidJWT: () => isValidJWT,
- isValidBase64URL: () => isValidBase64URL,
- isValidBase64: () => isValidBase64,
- globalRegistry: () => globalRegistry,
- globalConfig: () => globalConfig,
- function: () => _function,
- formatError: () => formatError,
- flattenError: () => flattenError,
- config: () => config,
- clone: () => clone2,
- _xid: () => _xid,
- _void: () => _void,
- _uuidv7: () => _uuidv7,
- _uuidv6: () => _uuidv6,
- _uuidv4: () => _uuidv4,
- _uuid: () => _uuid,
- _url: () => _url,
- _uppercase: () => _uppercase,
- _unknown: () => _unknown,
- _union: () => _union,
- _undefined: () => _undefined2,
- _ulid: () => _ulid,
- _uint64: () => _uint64,
- _uint32: () => _uint32,
- _tuple: () => _tuple,
- _trim: () => _trim,
- _transform: () => _transform,
- _toUpperCase: () => _toUpperCase,
- _toLowerCase: () => _toLowerCase,
- _templateLiteral: () => _templateLiteral,
- _symbol: () => _symbol,
- _success: () => _success,
- _stringbool: () => _stringbool,
- _stringFormat: () => _stringFormat,
- _string: () => _string,
- _startsWith: () => _startsWith,
- _size: () => _size,
- _set: () => _set,
- _safeParseAsync: () => _safeParseAsync,
- _safeParse: () => _safeParse,
- _regex: () => _regex,
- _refine: () => _refine,
- _record: () => _record,
- _readonly: () => _readonly,
- _property: () => _property,
- _promise: () => _promise,
- _positive: () => _positive,
- _pipe: () => _pipe,
- _parseAsync: () => _parseAsync,
- _parse: () => _parse,
- _overwrite: () => _overwrite,
- _optional: () => _optional,
- _number: () => _number,
- _nullable: () => _nullable,
- _null: () => _null2,
- _normalize: () => _normalize,
- _nonpositive: () => _nonpositive,
- _nonoptional: () => _nonoptional,
- _nonnegative: () => _nonnegative,
- _never: () => _never,
- _negative: () => _negative,
- _nativeEnum: () => _nativeEnum,
- _nanoid: () => _nanoid,
- _nan: () => _nan,
- _multipleOf: () => _multipleOf,
- _minSize: () => _minSize,
- _minLength: () => _minLength,
- _min: () => _gte,
- _mime: () => _mime,
- _maxSize: () => _maxSize,
- _maxLength: () => _maxLength,
- _max: () => _lte,
- _map: () => _map,
- _lte: () => _lte,
- _lt: () => _lt,
- _lowercase: () => _lowercase,
- _literal: () => _literal,
- _length: () => _length,
- _lazy: () => _lazy,
- _ksuid: () => _ksuid,
- _jwt: () => _jwt,
- _isoTime: () => _isoTime,
- _isoDuration: () => _isoDuration,
- _isoDateTime: () => _isoDateTime,
- _isoDate: () => _isoDate,
- _ipv6: () => _ipv6,
- _ipv4: () => _ipv4,
- _intersection: () => _intersection,
- _int64: () => _int64,
- _int32: () => _int32,
- _int: () => _int,
- _includes: () => _includes,
- _guid: () => _guid,
- _gte: () => _gte,
- _gt: () => _gt,
- _float64: () => _float64,
- _float32: () => _float32,
- _file: () => _file,
- _enum: () => _enum,
- _endsWith: () => _endsWith,
- _emoji: () => _emoji2,
- _email: () => _email,
- _e164: () => _e164,
- _discriminatedUnion: () => _discriminatedUnion,
- _default: () => _default,
- _date: () => _date,
- _custom: () => _custom,
- _cuid2: () => _cuid2,
- _cuid: () => _cuid,
- _coercedString: () => _coercedString,
- _coercedNumber: () => _coercedNumber,
- _coercedDate: () => _coercedDate,
- _coercedBoolean: () => _coercedBoolean,
- _coercedBigint: () => _coercedBigint,
- _cidrv6: () => _cidrv6,
- _cidrv4: () => _cidrv4,
- _catch: () => _catch,
- _boolean: () => _boolean,
- _bigint: () => _bigint,
- _base64url: () => _base64url,
- _base64: () => _base64,
- _array: () => _array,
- _any: () => _any,
- TimePrecision: () => TimePrecision,
- NEVER: () => NEVER,
- JSONSchemaGenerator: () => JSONSchemaGenerator,
- JSONSchema: () => exports_json_schema,
- Doc: () => Doc,
- $output: () => $output,
- $input: () => $input,
- $constructor: () => $constructor,
- $brand: () => $brand,
- $ZodXID: () => $ZodXID,
- $ZodVoid: () => $ZodVoid,
- $ZodUnknown: () => $ZodUnknown,
- $ZodUnion: () => $ZodUnion,
- $ZodUndefined: () => $ZodUndefined,
- $ZodUUID: () => $ZodUUID,
- $ZodURL: () => $ZodURL,
- $ZodULID: () => $ZodULID,
- $ZodType: () => $ZodType,
- $ZodTuple: () => $ZodTuple,
- $ZodTransform: () => $ZodTransform,
- $ZodTemplateLiteral: () => $ZodTemplateLiteral,
- $ZodSymbol: () => $ZodSymbol,
- $ZodSuccess: () => $ZodSuccess,
- $ZodStringFormat: () => $ZodStringFormat,
- $ZodString: () => $ZodString,
- $ZodSet: () => $ZodSet,
- $ZodRegistry: () => $ZodRegistry,
- $ZodRecord: () => $ZodRecord,
- $ZodRealError: () => $ZodRealError,
- $ZodReadonly: () => $ZodReadonly,
- $ZodPromise: () => $ZodPromise,
- $ZodPrefault: () => $ZodPrefault,
- $ZodPipe: () => $ZodPipe,
- $ZodOptional: () => $ZodOptional,
- $ZodObject: () => $ZodObject,
- $ZodNumberFormat: () => $ZodNumberFormat,
- $ZodNumber: () => $ZodNumber,
- $ZodNullable: () => $ZodNullable,
- $ZodNull: () => $ZodNull,
- $ZodNonOptional: () => $ZodNonOptional,
- $ZodNever: () => $ZodNever,
- $ZodNanoID: () => $ZodNanoID,
- $ZodNaN: () => $ZodNaN,
- $ZodMap: () => $ZodMap,
- $ZodLiteral: () => $ZodLiteral,
- $ZodLazy: () => $ZodLazy,
- $ZodKSUID: () => $ZodKSUID,
- $ZodJWT: () => $ZodJWT,
- $ZodIntersection: () => $ZodIntersection,
- $ZodISOTime: () => $ZodISOTime,
- $ZodISODuration: () => $ZodISODuration,
- $ZodISODateTime: () => $ZodISODateTime,
- $ZodISODate: () => $ZodISODate,
- $ZodIPv6: () => $ZodIPv6,
- $ZodIPv4: () => $ZodIPv4,
- $ZodGUID: () => $ZodGUID,
- $ZodFunction: () => $ZodFunction,
- $ZodFile: () => $ZodFile,
- $ZodError: () => $ZodError,
- $ZodEnum: () => $ZodEnum,
- $ZodEmoji: () => $ZodEmoji,
- $ZodEmail: () => $ZodEmail,
- $ZodE164: () => $ZodE164,
- $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion,
- $ZodDefault: () => $ZodDefault,
- $ZodDate: () => $ZodDate,
- $ZodCustomStringFormat: () => $ZodCustomStringFormat,
- $ZodCustom: () => $ZodCustom,
- $ZodCheckUpperCase: () => $ZodCheckUpperCase,
- $ZodCheckStringFormat: () => $ZodCheckStringFormat,
- $ZodCheckStartsWith: () => $ZodCheckStartsWith,
- $ZodCheckSizeEquals: () => $ZodCheckSizeEquals,
- $ZodCheckRegex: () => $ZodCheckRegex,
- $ZodCheckProperty: () => $ZodCheckProperty,
- $ZodCheckOverwrite: () => $ZodCheckOverwrite,
- $ZodCheckNumberFormat: () => $ZodCheckNumberFormat,
- $ZodCheckMultipleOf: () => $ZodCheckMultipleOf,
- $ZodCheckMinSize: () => $ZodCheckMinSize,
- $ZodCheckMinLength: () => $ZodCheckMinLength,
- $ZodCheckMimeType: () => $ZodCheckMimeType,
- $ZodCheckMaxSize: () => $ZodCheckMaxSize,
- $ZodCheckMaxLength: () => $ZodCheckMaxLength,
- $ZodCheckLowerCase: () => $ZodCheckLowerCase,
- $ZodCheckLessThan: () => $ZodCheckLessThan,
- $ZodCheckLengthEquals: () => $ZodCheckLengthEquals,
- $ZodCheckIncludes: () => $ZodCheckIncludes,
- $ZodCheckGreaterThan: () => $ZodCheckGreaterThan,
- $ZodCheckEndsWith: () => $ZodCheckEndsWith,
- $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat,
- $ZodCheck: () => $ZodCheck,
- $ZodCatch: () => $ZodCatch,
- $ZodCUID2: () => $ZodCUID2,
- $ZodCUID: () => $ZodCUID,
- $ZodCIDRv6: () => $ZodCIDRv6,
- $ZodCIDRv4: () => $ZodCIDRv4,
- $ZodBoolean: () => $ZodBoolean,
- $ZodBigIntFormat: () => $ZodBigIntFormat,
- $ZodBigInt: () => $ZodBigInt,
- $ZodBase64URL: () => $ZodBase64URL,
- $ZodBase64: () => $ZodBase64,
- $ZodAsyncError: () => $ZodAsyncError,
- $ZodArray: () => $ZodArray,
- $ZodAny: () => $ZodAny
-});
-var init_core5 = __esm(() => {
- init_util2();
- init_regexes();
- init_locales();
- init_json_schema();
- init_core4();
- init_parse();
- init_errors2();
- init_schemas();
- init_checks();
- init_versions();
- init_registries();
- init_function();
- init_api();
- init_to_json_schema();
-});
-
-// node_modules/zod/v4/classic/checks.js
-var init_checks2 = __esm(() => {
- init_core5();
-});
-
-// node_modules/zod/v4/classic/iso.js
-var exports_iso = {};
-__export(exports_iso, {
- time: () => time2,
- duration: () => duration2,
- datetime: () => datetime2,
- date: () => date2,
- ZodISOTime: () => ZodISOTime,
- ZodISODuration: () => ZodISODuration,
- ZodISODateTime: () => ZodISODateTime,
- ZodISODate: () => ZodISODate
-});
-function datetime2(params) {
- return _isoDateTime(ZodISODateTime, params);
-}
-function date2(params) {
- return _isoDate(ZodISODate, params);
-}
-function time2(params) {
- return _isoTime(ZodISOTime, params);
-}
-function duration2(params) {
- return _isoDuration(ZodISODuration, params);
-}
-var ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration;
-var init_iso = __esm(() => {
- init_core5();
- init_schemas2();
- ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def2) => {
- $ZodISODateTime.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def2) => {
- $ZodISODate.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def2) => {
- $ZodISOTime.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def2) => {
- $ZodISODuration.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
-});
-
-// node_modules/zod/v4/classic/errors.js
-var initializer2 = (inst, issues) => {
- $ZodError.init(inst, issues);
- inst.name = "ZodError";
- Object.defineProperties(inst, {
- format: {
- value: (mapper) => formatError(inst, mapper)
- },
- flatten: {
- value: (mapper) => flattenError(inst, mapper)
- },
- addIssue: {
- value: (issue2) => inst.issues.push(issue2)
- },
- addIssues: {
- value: (issues2) => inst.issues.push(...issues2)
- },
- isEmpty: {
- get() {
- return inst.issues.length === 0;
- }
- }
- });
-}, ZodError, ZodRealError;
-var init_errors3 = __esm(() => {
- init_core5();
- init_core5();
- ZodError = $constructor("ZodError", initializer2);
- ZodRealError = $constructor("ZodError", initializer2, {
- Parent: Error
- });
-});
-
-// node_modules/zod/v4/classic/parse.js
-var parse5, parseAsync2, safeParse2, safeParseAsync2;
-var init_parse2 = __esm(() => {
- init_core5();
- init_errors3();
- parse5 = /* @__PURE__ */ _parse(ZodRealError);
- parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
- safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
- safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
-});
-
-// node_modules/zod/v4/classic/schemas.js
-function string2(params) {
- return _string(ZodString, params);
-}
-function email2(params) {
- return _email(ZodEmail, params);
-}
-function guid2(params) {
- return _guid(ZodGUID, params);
-}
-function uuid2(params) {
- return _uuid(ZodUUID, params);
-}
-function uuidv4(params) {
- return _uuidv4(ZodUUID, params);
-}
-function uuidv6(params) {
- return _uuidv6(ZodUUID, params);
-}
-function uuidv7(params) {
- return _uuidv7(ZodUUID, params);
-}
-function url2(params) {
- return _url(ZodURL, params);
-}
-function emoji2(params) {
- return _emoji2(ZodEmoji, params);
-}
-function nanoid2(params) {
- return _nanoid(ZodNanoID, params);
-}
-function cuid3(params) {
- return _cuid(ZodCUID, params);
-}
-function cuid22(params) {
- return _cuid2(ZodCUID2, params);
-}
-function ulid2(params) {
- return _ulid(ZodULID, params);
-}
-function xid2(params) {
- return _xid(ZodXID, params);
-}
-function ksuid2(params) {
- return _ksuid(ZodKSUID, params);
-}
-function ipv42(params) {
- return _ipv4(ZodIPv4, params);
-}
-function ipv62(params) {
- return _ipv6(ZodIPv6, params);
-}
-function cidrv42(params) {
- return _cidrv4(ZodCIDRv4, params);
-}
-function cidrv62(params) {
- return _cidrv6(ZodCIDRv6, params);
-}
-function base642(params) {
- return _base64(ZodBase64, params);
-}
-function base64url2(params) {
- return _base64url(ZodBase64URL, params);
-}
-function e1642(params) {
- return _e164(ZodE164, params);
-}
-function jwt(params) {
- return _jwt(ZodJWT, params);
-}
-function stringFormat(format3, fnOrRegex, _params = {}) {
- return _stringFormat(ZodCustomStringFormat, format3, fnOrRegex, _params);
-}
-function number2(params) {
- return _number(ZodNumber, params);
-}
-function int(params) {
- return _int(ZodNumberFormat, params);
-}
-function float32(params) {
- return _float32(ZodNumberFormat, params);
-}
-function float64(params) {
- return _float64(ZodNumberFormat, params);
-}
-function int32(params) {
- return _int32(ZodNumberFormat, params);
-}
-function uint32(params) {
- return _uint32(ZodNumberFormat, params);
-}
-function boolean2(params) {
- return _boolean(ZodBoolean, params);
-}
-function bigint2(params) {
- return _bigint(ZodBigInt, params);
-}
-function int64(params) {
- return _int64(ZodBigIntFormat, params);
-}
-function uint64(params) {
- return _uint64(ZodBigIntFormat, params);
-}
-function symbol(params) {
- return _symbol(ZodSymbol, params);
-}
-function _undefined3(params) {
- return _undefined2(ZodUndefined, params);
-}
-function _null3(params) {
- return _null2(ZodNull, params);
-}
-function any() {
- return _any(ZodAny);
-}
-function unknown() {
- return _unknown(ZodUnknown);
-}
-function never(params) {
- return _never(ZodNever, params);
-}
-function _void2(params) {
- return _void(ZodVoid, params);
-}
-function date3(params) {
- return _date(ZodDate, params);
-}
-function array(element, params) {
- return _array(ZodArray, element, params);
-}
-function keyof(schema) {
- const shape = schema._zod.def.shape;
- return literal(Object.keys(shape));
-}
-function object(shape, params) {
- const def2 = {
- type: "object",
- get shape() {
- exports_util.assignProp(this, "shape", { ...shape });
- return this.shape;
- },
- ...exports_util.normalizeParams(params)
- };
- return new ZodObject(def2);
-}
-function strictObject(shape, params) {
- return new ZodObject({
- type: "object",
- get shape() {
- exports_util.assignProp(this, "shape", { ...shape });
- return this.shape;
- },
- catchall: never(),
- ...exports_util.normalizeParams(params)
- });
-}
-function looseObject(shape, params) {
- return new ZodObject({
- type: "object",
- get shape() {
- exports_util.assignProp(this, "shape", { ...shape });
- return this.shape;
- },
- catchall: unknown(),
- ...exports_util.normalizeParams(params)
- });
-}
-function union(options2, params) {
- return new ZodUnion({
- type: "union",
- options: options2,
- ...exports_util.normalizeParams(params)
- });
-}
-function discriminatedUnion(discriminator, options2, params) {
- return new ZodDiscriminatedUnion({
- type: "union",
- options: options2,
- discriminator,
- ...exports_util.normalizeParams(params)
- });
-}
-function intersection(left, right) {
- return new ZodIntersection({
- type: "intersection",
- left,
- right
- });
-}
-function tuple(items, _paramsOrRest, _params) {
- const hasRest = _paramsOrRest instanceof $ZodType;
- const params = hasRest ? _params : _paramsOrRest;
- const rest = hasRest ? _paramsOrRest : null;
- return new ZodTuple({
- type: "tuple",
- items,
- rest,
- ...exports_util.normalizeParams(params)
- });
-}
-function record(keyType, valueType, params) {
- return new ZodRecord({
- type: "record",
- keyType,
- valueType,
- ...exports_util.normalizeParams(params)
- });
-}
-function partialRecord(keyType, valueType, params) {
- return new ZodRecord({
- type: "record",
- keyType: union([keyType, never()]),
- valueType,
- ...exports_util.normalizeParams(params)
- });
-}
-function map(keyType, valueType, params) {
- return new ZodMap({
- type: "map",
- keyType,
- valueType,
- ...exports_util.normalizeParams(params)
- });
-}
-function set(valueType, params) {
- return new ZodSet({
- type: "set",
- valueType,
- ...exports_util.normalizeParams(params)
- });
-}
-function _enum2(values, params) {
- const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
- return new ZodEnum({
- type: "enum",
- entries,
- ...exports_util.normalizeParams(params)
- });
-}
-function nativeEnum(entries, params) {
- return new ZodEnum({
- type: "enum",
- entries,
- ...exports_util.normalizeParams(params)
- });
-}
-function literal(value, params) {
- return new ZodLiteral({
- type: "literal",
- values: Array.isArray(value) ? value : [value],
- ...exports_util.normalizeParams(params)
- });
-}
-function file(params) {
- return _file(ZodFile, params);
-}
-function transform(fn) {
- return new ZodTransform({
- type: "transform",
- transform: fn
- });
-}
-function optional(innerType) {
- return new ZodOptional({
- type: "optional",
- innerType
- });
-}
-function nullable(innerType) {
- return new ZodNullable({
- type: "nullable",
- innerType
- });
-}
-function nullish2(innerType) {
- return optional(nullable(innerType));
-}
-function _default2(innerType, defaultValue) {
- return new ZodDefault({
- type: "default",
- innerType,
- get defaultValue() {
- return typeof defaultValue === "function" ? defaultValue() : defaultValue;
- }
- });
-}
-function prefault(innerType, defaultValue) {
- return new ZodPrefault({
- type: "prefault",
- innerType,
- get defaultValue() {
- return typeof defaultValue === "function" ? defaultValue() : defaultValue;
- }
- });
-}
-function nonoptional(innerType, params) {
- return new ZodNonOptional({
- type: "nonoptional",
- innerType,
- ...exports_util.normalizeParams(params)
- });
-}
-function success(innerType) {
- return new ZodSuccess({
- type: "success",
- innerType
- });
-}
-function _catch2(innerType, catchValue) {
- return new ZodCatch({
- type: "catch",
- innerType,
- catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
- });
-}
-function nan(params) {
- return _nan(ZodNaN, params);
-}
-function pipe(in_, out) {
- return new ZodPipe({
- type: "pipe",
- in: in_,
- out
- });
-}
-function readonly(innerType) {
- return new ZodReadonly({
- type: "readonly",
- innerType
- });
-}
-function templateLiteral(parts, params) {
- return new ZodTemplateLiteral({
- type: "template_literal",
- parts,
- ...exports_util.normalizeParams(params)
- });
-}
-function lazy(getter) {
- return new ZodLazy({
- type: "lazy",
- getter
- });
-}
-function promise(innerType) {
- return new ZodPromise({
- type: "promise",
- innerType
- });
-}
-function check2(fn) {
- const ch = new $ZodCheck({
- check: "custom"
- });
- ch._zod.check = fn;
- return ch;
-}
-function custom(fn, _params) {
- return _custom(ZodCustom, fn ?? (() => true), _params);
-}
-function refine(fn, _params = {}) {
- return _refine(ZodCustom, fn, _params);
-}
-function superRefine(fn) {
- const ch = check2((payload) => {
- payload.addIssue = (issue2) => {
- if (typeof issue2 === "string") {
- payload.issues.push(exports_util.issue(issue2, payload.value, ch._zod.def));
- } else {
- const _issue = issue2;
- if (_issue.fatal)
- _issue.continue = false;
- _issue.code ?? (_issue.code = "custom");
- _issue.input ?? (_issue.input = payload.value);
- _issue.inst ?? (_issue.inst = ch);
- _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
- payload.issues.push(exports_util.issue(_issue));
- }
- };
- return fn(payload.value, payload);
- });
- return ch;
-}
-function _instanceof(cls, params = {
- error: `Input not instance of ${cls.name}`
-}) {
- const inst = new ZodCustom({
- type: "custom",
- check: "custom",
- fn: (data) => data instanceof cls,
- abort: true,
- ...exports_util.normalizeParams(params)
- });
- inst._zod.bag.Class = cls;
- return inst;
-}
-function json(params) {
- const jsonSchema = lazy(() => {
- return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]);
- });
- return jsonSchema;
-}
-function preprocess(fn, schema) {
- return pipe(transform(fn), schema);
-}
-var ZodType, _ZodString, ZodString, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber, ZodNumberFormat, ZodBoolean, ZodBigInt, ZodBigIntFormat, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodDate, ZodArray, ZodObject, ZodUnion, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodEnum, ZodLiteral, ZodFile, ZodTransform, ZodOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch, ZodNaN, ZodPipe, ZodReadonly, ZodTemplateLiteral, ZodLazy, ZodPromise, ZodCustom, stringbool = (...args) => _stringbool({
- Pipe: ZodPipe,
- Boolean: ZodBoolean,
- String: ZodString,
- Transform: ZodTransform
-}, ...args);
-var init_schemas2 = __esm(() => {
- init_core5();
- init_core5();
- init_checks2();
- init_iso();
- init_parse2();
- ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def2) => {
- $ZodType.init(inst, def2);
- inst.def = def2;
- Object.defineProperty(inst, "_def", { value: def2 });
- inst.check = (...checks2) => {
- return inst.clone({
- ...def2,
- checks: [
- ...def2.checks ?? [],
- ...checks2.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
- ]
- });
- };
- inst.clone = (def3, params) => clone2(inst, def3, params);
- inst.brand = () => inst;
- inst.register = (reg, meta) => {
- reg.add(inst, meta);
- return inst;
- };
- inst.parse = (data, params) => parse5(inst, data, params, { callee: inst.parse });
- inst.safeParse = (data, params) => safeParse2(inst, data, params);
- inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
- inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
- inst.spa = inst.safeParseAsync;
- inst.refine = (check2, params) => inst.check(refine(check2, params));
- inst.superRefine = (refinement) => inst.check(superRefine(refinement));
- inst.overwrite = (fn) => inst.check(_overwrite(fn));
- inst.optional = () => optional(inst);
- inst.nullable = () => nullable(inst);
- inst.nullish = () => optional(nullable(inst));
- inst.nonoptional = (params) => nonoptional(inst, params);
- inst.array = () => array(inst);
- inst.or = (arg) => union([inst, arg]);
- inst.and = (arg) => intersection(inst, arg);
- inst.transform = (tx) => pipe(inst, transform(tx));
- inst.default = (def3) => _default2(inst, def3);
- inst.prefault = (def3) => prefault(inst, def3);
- inst.catch = (params) => _catch2(inst, params);
- inst.pipe = (target) => pipe(inst, target);
- inst.readonly = () => readonly(inst);
- inst.describe = (description) => {
- const cl = inst.clone();
- globalRegistry.add(cl, { description });
- return cl;
- };
- Object.defineProperty(inst, "description", {
- get() {
- return globalRegistry.get(inst)?.description;
- },
- configurable: true
- });
- inst.meta = (...args) => {
- if (args.length === 0) {
- return globalRegistry.get(inst);
- }
- const cl = inst.clone();
- globalRegistry.add(cl, args[0]);
- return cl;
- };
- inst.isOptional = () => inst.safeParse(undefined).success;
- inst.isNullable = () => inst.safeParse(null).success;
- return inst;
- });
- _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def2) => {
- $ZodString.init(inst, def2);
- ZodType.init(inst, def2);
- const bag = inst._zod.bag;
- inst.format = bag.format ?? null;
- inst.minLength = bag.minimum ?? null;
- inst.maxLength = bag.maximum ?? null;
- inst.regex = (...args) => inst.check(_regex(...args));
- inst.includes = (...args) => inst.check(_includes(...args));
- inst.startsWith = (...args) => inst.check(_startsWith(...args));
- inst.endsWith = (...args) => inst.check(_endsWith(...args));
- inst.min = (...args) => inst.check(_minLength(...args));
- inst.max = (...args) => inst.check(_maxLength(...args));
- inst.length = (...args) => inst.check(_length(...args));
- inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
- inst.lowercase = (params) => inst.check(_lowercase(params));
- inst.uppercase = (params) => inst.check(_uppercase(params));
- inst.trim = () => inst.check(_trim());
- inst.normalize = (...args) => inst.check(_normalize(...args));
- inst.toLowerCase = () => inst.check(_toLowerCase());
- inst.toUpperCase = () => inst.check(_toUpperCase());
- });
- ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def2) => {
- $ZodString.init(inst, def2);
- _ZodString.init(inst, def2);
- inst.email = (params) => inst.check(_email(ZodEmail, params));
- inst.url = (params) => inst.check(_url(ZodURL, params));
- inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
- inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
- inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
- inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
- inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
- inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
- inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
- inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
- inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
- inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
- inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
- inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
- inst.xid = (params) => inst.check(_xid(ZodXID, params));
- inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
- inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
- inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
- inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
- inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
- inst.e164 = (params) => inst.check(_e164(ZodE164, params));
- inst.datetime = (params) => inst.check(datetime2(params));
- inst.date = (params) => inst.check(date2(params));
- inst.time = (params) => inst.check(time2(params));
- inst.duration = (params) => inst.check(duration2(params));
- });
- ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def2) => {
- $ZodStringFormat.init(inst, def2);
- _ZodString.init(inst, def2);
- });
- ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def2) => {
- $ZodEmail.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def2) => {
- $ZodGUID.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def2) => {
- $ZodUUID.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def2) => {
- $ZodURL.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def2) => {
- $ZodEmoji.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def2) => {
- $ZodNanoID.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def2) => {
- $ZodCUID.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def2) => {
- $ZodCUID2.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def2) => {
- $ZodULID.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def2) => {
- $ZodXID.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def2) => {
- $ZodKSUID.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def2) => {
- $ZodIPv4.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def2) => {
- $ZodIPv6.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def2) => {
- $ZodCIDRv4.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def2) => {
- $ZodCIDRv6.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def2) => {
- $ZodBase64.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def2) => {
- $ZodBase64URL.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def2) => {
- $ZodE164.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def2) => {
- $ZodJWT.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def2) => {
- $ZodCustomStringFormat.init(inst, def2);
- ZodStringFormat.init(inst, def2);
- });
- ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def2) => {
- $ZodNumber.init(inst, def2);
- ZodType.init(inst, def2);
- inst.gt = (value, params) => inst.check(_gt(value, params));
- inst.gte = (value, params) => inst.check(_gte(value, params));
- inst.min = (value, params) => inst.check(_gte(value, params));
- inst.lt = (value, params) => inst.check(_lt(value, params));
- inst.lte = (value, params) => inst.check(_lte(value, params));
- inst.max = (value, params) => inst.check(_lte(value, params));
- inst.int = (params) => inst.check(int(params));
- inst.safe = (params) => inst.check(int(params));
- inst.positive = (params) => inst.check(_gt(0, params));
- inst.nonnegative = (params) => inst.check(_gte(0, params));
- inst.negative = (params) => inst.check(_lt(0, params));
- inst.nonpositive = (params) => inst.check(_lte(0, params));
- inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
- inst.step = (value, params) => inst.check(_multipleOf(value, params));
- inst.finite = () => inst;
- const bag = inst._zod.bag;
- inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
- inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
- inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
- inst.isFinite = true;
- inst.format = bag.format ?? null;
- });
- ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def2) => {
- $ZodNumberFormat.init(inst, def2);
- ZodNumber.init(inst, def2);
- });
- ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def2) => {
- $ZodBoolean.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def2) => {
- $ZodBigInt.init(inst, def2);
- ZodType.init(inst, def2);
- inst.gte = (value, params) => inst.check(_gte(value, params));
- inst.min = (value, params) => inst.check(_gte(value, params));
- inst.gt = (value, params) => inst.check(_gt(value, params));
- inst.gte = (value, params) => inst.check(_gte(value, params));
- inst.min = (value, params) => inst.check(_gte(value, params));
- inst.lt = (value, params) => inst.check(_lt(value, params));
- inst.lte = (value, params) => inst.check(_lte(value, params));
- inst.max = (value, params) => inst.check(_lte(value, params));
- inst.positive = (params) => inst.check(_gt(BigInt(0), params));
- inst.negative = (params) => inst.check(_lt(BigInt(0), params));
- inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params));
- inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params));
- inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
- const bag = inst._zod.bag;
- inst.minValue = bag.minimum ?? null;
- inst.maxValue = bag.maximum ?? null;
- inst.format = bag.format ?? null;
- });
- ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def2) => {
- $ZodBigIntFormat.init(inst, def2);
- ZodBigInt.init(inst, def2);
- });
- ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def2) => {
- $ZodSymbol.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def2) => {
- $ZodUndefined.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def2) => {
- $ZodNull.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def2) => {
- $ZodAny.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def2) => {
- $ZodUnknown.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def2) => {
- $ZodNever.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def2) => {
- $ZodVoid.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def2) => {
- $ZodDate.init(inst, def2);
- ZodType.init(inst, def2);
- inst.min = (value, params) => inst.check(_gte(value, params));
- inst.max = (value, params) => inst.check(_lte(value, params));
- const c5 = inst._zod.bag;
- inst.minDate = c5.minimum ? new Date(c5.minimum) : null;
- inst.maxDate = c5.maximum ? new Date(c5.maximum) : null;
- });
- ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def2) => {
- $ZodArray.init(inst, def2);
- ZodType.init(inst, def2);
- inst.element = def2.element;
- inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
- inst.nonempty = (params) => inst.check(_minLength(1, params));
- inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
- inst.length = (len, params) => inst.check(_length(len, params));
- inst.unwrap = () => inst.element;
- });
- ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def2) => {
- $ZodObject.init(inst, def2);
- ZodType.init(inst, def2);
- exports_util.defineLazy(inst, "shape", () => def2.shape);
- inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape));
- inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall });
- inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
- inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
- inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
- inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });
- inst.extend = (incoming) => {
- return exports_util.extend(inst, incoming);
- };
- inst.merge = (other2) => exports_util.merge(inst, other2);
- inst.pick = (mask) => exports_util.pick(inst, mask);
- inst.omit = (mask) => exports_util.omit(inst, mask);
- inst.partial = (...args) => exports_util.partial(ZodOptional, inst, args[0]);
- inst.required = (...args) => exports_util.required(ZodNonOptional, inst, args[0]);
- });
- ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def2) => {
- $ZodUnion.init(inst, def2);
- ZodType.init(inst, def2);
- inst.options = def2.options;
- });
- ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def2) => {
- ZodUnion.init(inst, def2);
- $ZodDiscriminatedUnion.init(inst, def2);
- });
- ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def2) => {
- $ZodIntersection.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def2) => {
- $ZodTuple.init(inst, def2);
- ZodType.init(inst, def2);
- inst.rest = (rest) => inst.clone({
- ...inst._zod.def,
- rest
- });
- });
- ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def2) => {
- $ZodRecord.init(inst, def2);
- ZodType.init(inst, def2);
- inst.keyType = def2.keyType;
- inst.valueType = def2.valueType;
- });
- ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def2) => {
- $ZodMap.init(inst, def2);
- ZodType.init(inst, def2);
- inst.keyType = def2.keyType;
- inst.valueType = def2.valueType;
- });
- ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def2) => {
- $ZodSet.init(inst, def2);
- ZodType.init(inst, def2);
- inst.min = (...args) => inst.check(_minSize(...args));
- inst.nonempty = (params) => inst.check(_minSize(1, params));
- inst.max = (...args) => inst.check(_maxSize(...args));
- inst.size = (...args) => inst.check(_size(...args));
- });
- ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def2) => {
- $ZodEnum.init(inst, def2);
- ZodType.init(inst, def2);
- inst.enum = def2.entries;
- inst.options = Object.values(def2.entries);
- const keys2 = new Set(Object.keys(def2.entries));
- inst.extract = (values, params) => {
- const newEntries = {};
- for (const value of values) {
- if (keys2.has(value)) {
- newEntries[value] = def2.entries[value];
- } else
- throw new Error(`Key ${value} not found in enum`);
- }
- return new ZodEnum({
- ...def2,
- checks: [],
- ...exports_util.normalizeParams(params),
- entries: newEntries
- });
- };
- inst.exclude = (values, params) => {
- const newEntries = { ...def2.entries };
- for (const value of values) {
- if (keys2.has(value)) {
- delete newEntries[value];
- } else
- throw new Error(`Key ${value} not found in enum`);
- }
- return new ZodEnum({
- ...def2,
- checks: [],
- ...exports_util.normalizeParams(params),
- entries: newEntries
- });
- };
- });
- ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def2) => {
- $ZodLiteral.init(inst, def2);
- ZodType.init(inst, def2);
- inst.values = new Set(def2.values);
- Object.defineProperty(inst, "value", {
- get() {
- if (def2.values.length > 1) {
- throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
- }
- return def2.values[0];
- }
- });
- });
- ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def2) => {
- $ZodFile.init(inst, def2);
- ZodType.init(inst, def2);
- inst.min = (size, params) => inst.check(_minSize(size, params));
- inst.max = (size, params) => inst.check(_maxSize(size, params));
- inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params));
- });
- ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def2) => {
- $ZodTransform.init(inst, def2);
- ZodType.init(inst, def2);
- inst._zod.parse = (payload, _ctx) => {
- payload.addIssue = (issue2) => {
- if (typeof issue2 === "string") {
- payload.issues.push(exports_util.issue(issue2, payload.value, def2));
- } else {
- const _issue = issue2;
- if (_issue.fatal)
- _issue.continue = false;
- _issue.code ?? (_issue.code = "custom");
- _issue.input ?? (_issue.input = payload.value);
- _issue.inst ?? (_issue.inst = inst);
- _issue.continue ?? (_issue.continue = true);
- payload.issues.push(exports_util.issue(_issue));
- }
- };
- const output = def2.transform(payload.value, payload);
- if (output instanceof Promise) {
- return output.then((output2) => {
- payload.value = output2;
- return payload;
- });
- }
- payload.value = output;
- return payload;
- };
- });
- ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def2) => {
- $ZodOptional.init(inst, def2);
- ZodType.init(inst, def2);
- inst.unwrap = () => inst._zod.def.innerType;
- });
- ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def2) => {
- $ZodNullable.init(inst, def2);
- ZodType.init(inst, def2);
- inst.unwrap = () => inst._zod.def.innerType;
- });
- ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def2) => {
- $ZodDefault.init(inst, def2);
- ZodType.init(inst, def2);
- inst.unwrap = () => inst._zod.def.innerType;
- inst.removeDefault = inst.unwrap;
- });
- ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def2) => {
- $ZodPrefault.init(inst, def2);
- ZodType.init(inst, def2);
- inst.unwrap = () => inst._zod.def.innerType;
- });
- ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def2) => {
- $ZodNonOptional.init(inst, def2);
- ZodType.init(inst, def2);
- inst.unwrap = () => inst._zod.def.innerType;
- });
- ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def2) => {
- $ZodSuccess.init(inst, def2);
- ZodType.init(inst, def2);
- inst.unwrap = () => inst._zod.def.innerType;
- });
- ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def2) => {
- $ZodCatch.init(inst, def2);
- ZodType.init(inst, def2);
- inst.unwrap = () => inst._zod.def.innerType;
- inst.removeCatch = inst.unwrap;
- });
- ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def2) => {
- $ZodNaN.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def2) => {
- $ZodPipe.init(inst, def2);
- ZodType.init(inst, def2);
- inst.in = def2.in;
- inst.out = def2.out;
- });
- ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def2) => {
- $ZodReadonly.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def2) => {
- $ZodTemplateLiteral.init(inst, def2);
- ZodType.init(inst, def2);
- });
- ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def2) => {
- $ZodLazy.init(inst, def2);
- ZodType.init(inst, def2);
- inst.unwrap = () => inst._zod.def.getter();
- });
- ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def2) => {
- $ZodPromise.init(inst, def2);
- ZodType.init(inst, def2);
- inst.unwrap = () => inst._zod.def.innerType;
- });
- ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def2) => {
- $ZodCustom.init(inst, def2);
- ZodType.init(inst, def2);
- });
-});
-
-// node_modules/zod/v4/classic/compat.js
-function setErrorMap(map2) {
- config({
- customError: map2
- });
-}
-function getErrorMap() {
- return config().customError;
-}
-var ZodIssueCode;
-var init_compat = __esm(() => {
- init_core5();
- ZodIssueCode = {
- invalid_type: "invalid_type",
- too_big: "too_big",
- too_small: "too_small",
- invalid_format: "invalid_format",
- not_multiple_of: "not_multiple_of",
- unrecognized_keys: "unrecognized_keys",
- invalid_union: "invalid_union",
- invalid_key: "invalid_key",
- invalid_element: "invalid_element",
- invalid_value: "invalid_value",
- custom: "custom"
- };
-});
-
-// node_modules/zod/v4/classic/coerce.js
-var exports_coerce = {};
-__export(exports_coerce, {
- string: () => string3,
- number: () => number3,
- date: () => date4,
- boolean: () => boolean3,
- bigint: () => bigint3
-});
-function string3(params) {
- return _coercedString(ZodString, params);
-}
-function number3(params) {
- return _coercedNumber(ZodNumber, params);
-}
-function boolean3(params) {
- return _coercedBoolean(ZodBoolean, params);
-}
-function bigint3(params) {
- return _coercedBigint(ZodBigInt, params);
-}
-function date4(params) {
- return _coercedDate(ZodDate, params);
-}
-var init_coerce = __esm(() => {
- init_core5();
- init_schemas2();
-});
-
-// node_modules/zod/v4/classic/external.js
-var exports_external = {};
-__export(exports_external, {
- xid: () => xid2,
- void: () => _void2,
- uuidv7: () => uuidv7,
- uuidv6: () => uuidv6,
- uuidv4: () => uuidv4,
- uuid: () => uuid2,
- url: () => url2,
- uppercase: () => _uppercase,
- unknown: () => unknown,
- union: () => union,
- undefined: () => _undefined3,
- ulid: () => ulid2,
- uint64: () => uint64,
- uint32: () => uint32,
- tuple: () => tuple,
- trim: () => _trim,
- treeifyError: () => treeifyError,
- transform: () => transform,
- toUpperCase: () => _toUpperCase,
- toLowerCase: () => _toLowerCase,
- toJSONSchema: () => toJSONSchema,
- templateLiteral: () => templateLiteral,
- symbol: () => symbol,
- superRefine: () => superRefine,
- success: () => success,
- stringbool: () => stringbool,
- stringFormat: () => stringFormat,
- string: () => string2,
- strictObject: () => strictObject,
- startsWith: () => _startsWith,
- size: () => _size,
- setErrorMap: () => setErrorMap,
- set: () => set,
- safeParseAsync: () => safeParseAsync2,
- safeParse: () => safeParse2,
- registry: () => registry2,
- regexes: () => exports_regexes,
- regex: () => _regex,
- refine: () => refine,
- record: () => record,
- readonly: () => readonly,
- property: () => _property,
- promise: () => promise,
- prettifyError: () => prettifyError,
- preprocess: () => preprocess,
- prefault: () => prefault,
- positive: () => _positive,
- pipe: () => pipe,
- partialRecord: () => partialRecord,
- parseAsync: () => parseAsync2,
- parse: () => parse5,
- overwrite: () => _overwrite,
- optional: () => optional,
- object: () => object,
- number: () => number2,
- nullish: () => nullish2,
- nullable: () => nullable,
- null: () => _null3,
- normalize: () => _normalize,
- nonpositive: () => _nonpositive,
- nonoptional: () => nonoptional,
- nonnegative: () => _nonnegative,
- never: () => never,
- negative: () => _negative,
- nativeEnum: () => nativeEnum,
- nanoid: () => nanoid2,
- nan: () => nan,
- multipleOf: () => _multipleOf,
- minSize: () => _minSize,
- minLength: () => _minLength,
- mime: () => _mime,
- maxSize: () => _maxSize,
- maxLength: () => _maxLength,
- map: () => map,
- lte: () => _lte,
- lt: () => _lt,
- lowercase: () => _lowercase,
- looseObject: () => looseObject,
- locales: () => exports_locales,
- literal: () => literal,
- length: () => _length,
- lazy: () => lazy,
- ksuid: () => ksuid2,
- keyof: () => keyof,
- jwt: () => jwt,
- json: () => json,
- iso: () => exports_iso,
- ipv6: () => ipv62,
- ipv4: () => ipv42,
- intersection: () => intersection,
- int64: () => int64,
- int32: () => int32,
- int: () => int,
- instanceof: () => _instanceof,
- includes: () => _includes,
- guid: () => guid2,
- gte: () => _gte,
- gt: () => _gt,
- globalRegistry: () => globalRegistry,
- getErrorMap: () => getErrorMap,
- function: () => _function,
- formatError: () => formatError,
- float64: () => float64,
- float32: () => float32,
- flattenError: () => flattenError,
- file: () => file,
- enum: () => _enum2,
- endsWith: () => _endsWith,
- emoji: () => emoji2,
- email: () => email2,
- e164: () => e1642,
- discriminatedUnion: () => discriminatedUnion,
- date: () => date3,
- custom: () => custom,
- cuid2: () => cuid22,
- cuid: () => cuid3,
- core: () => exports_core3,
- config: () => config,
- coerce: () => exports_coerce,
- clone: () => clone2,
- cidrv6: () => cidrv62,
- cidrv4: () => cidrv42,
- check: () => check2,
- catch: () => _catch2,
- boolean: () => boolean2,
- bigint: () => bigint2,
- base64url: () => base64url2,
- base64: () => base642,
- array: () => array,
- any: () => any,
- _default: () => _default2,
- _ZodString: () => _ZodString,
- ZodXID: () => ZodXID,
- ZodVoid: () => ZodVoid,
- ZodUnknown: () => ZodUnknown,
- ZodUnion: () => ZodUnion,
- ZodUndefined: () => ZodUndefined,
- ZodUUID: () => ZodUUID,
- ZodURL: () => ZodURL,
- ZodULID: () => ZodULID,
- ZodType: () => ZodType,
- ZodTuple: () => ZodTuple,
- ZodTransform: () => ZodTransform,
- ZodTemplateLiteral: () => ZodTemplateLiteral,
- ZodSymbol: () => ZodSymbol,
- ZodSuccess: () => ZodSuccess,
- ZodStringFormat: () => ZodStringFormat,
- ZodString: () => ZodString,
- ZodSet: () => ZodSet,
- ZodRecord: () => ZodRecord,
- ZodRealError: () => ZodRealError,
- ZodReadonly: () => ZodReadonly,
- ZodPromise: () => ZodPromise,
- ZodPrefault: () => ZodPrefault,
- ZodPipe: () => ZodPipe,
- ZodOptional: () => ZodOptional,
- ZodObject: () => ZodObject,
- ZodNumberFormat: () => ZodNumberFormat,
- ZodNumber: () => ZodNumber,
- ZodNullable: () => ZodNullable,
- ZodNull: () => ZodNull,
- ZodNonOptional: () => ZodNonOptional,
- ZodNever: () => ZodNever,
- ZodNanoID: () => ZodNanoID,
- ZodNaN: () => ZodNaN,
- ZodMap: () => ZodMap,
- ZodLiteral: () => ZodLiteral,
- ZodLazy: () => ZodLazy,
- ZodKSUID: () => ZodKSUID,
- ZodJWT: () => ZodJWT,
- ZodIssueCode: () => ZodIssueCode,
- ZodIntersection: () => ZodIntersection,
- ZodISOTime: () => ZodISOTime,
- ZodISODuration: () => ZodISODuration,
- ZodISODateTime: () => ZodISODateTime,
- ZodISODate: () => ZodISODate,
- ZodIPv6: () => ZodIPv6,
- ZodIPv4: () => ZodIPv4,
- ZodGUID: () => ZodGUID,
- ZodFile: () => ZodFile,
- ZodError: () => ZodError,
- ZodEnum: () => ZodEnum,
- ZodEmoji: () => ZodEmoji,
- ZodEmail: () => ZodEmail,
- ZodE164: () => ZodE164,
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
- ZodDefault: () => ZodDefault,
- ZodDate: () => ZodDate,
- ZodCustomStringFormat: () => ZodCustomStringFormat,
- ZodCustom: () => ZodCustom,
- ZodCatch: () => ZodCatch,
- ZodCUID2: () => ZodCUID2,
- ZodCUID: () => ZodCUID,
- ZodCIDRv6: () => ZodCIDRv6,
- ZodCIDRv4: () => ZodCIDRv4,
- ZodBoolean: () => ZodBoolean,
- ZodBigIntFormat: () => ZodBigIntFormat,
- ZodBigInt: () => ZodBigInt,
- ZodBase64URL: () => ZodBase64URL,
- ZodBase64: () => ZodBase64,
- ZodArray: () => ZodArray,
- ZodAny: () => ZodAny,
- TimePrecision: () => TimePrecision,
- NEVER: () => NEVER,
- $output: () => $output,
- $input: () => $input,
- $brand: () => $brand
-});
-var init_external = __esm(() => {
- init_core5();
- init_core5();
- init_en();
- init_core5();
- init_locales();
- init_iso();
- init_iso();
- init_coerce();
- init_schemas2();
- init_checks2();
- init_errors3();
- init_parse2();
- init_compat();
- config(en_default());
-});
-
-// node_modules/zod/v4/classic/index.js
-var classic_default;
-var init_classic = __esm(() => {
- init_external();
- init_external();
- classic_default = exports_external;
-});
-
-// node_modules/zod/v4/index.js
-var v4_default;
-var init_v4 = __esm(() => {
- init_classic();
- init_classic();
- v4_default = classic_default;
-});
-
-// src/services/remoteManagedSettings/syncCacheState.ts
-import { join as join17 } from "path";
-function setSessionCache(value) {
- sessionCache = value;
-}
-function resetSyncCache() {
- sessionCache = null;
- eligible = undefined;
-}
-function setEligibility(v) {
- eligible = v;
- return v;
-}
-function getSettingsPath() {
- return join17(getClaudeConfigHomeDir(), SETTINGS_FILENAME);
-}
-function loadSettings() {
- try {
- const content = readFileSync4(getSettingsPath());
- const data = jsonParse(stripBOM2(content));
- if (!data || typeof data !== "object" || Array.isArray(data)) {
- return null;
- }
- return data;
- } catch {
- return null;
- }
-}
-function getRemoteManagedSettingsSyncFromCache() {
- if (eligible !== true)
- return null;
- if (sessionCache)
- return sessionCache;
- const cachedSettings = loadSettings();
- if (cachedSettings) {
- sessionCache = cachedSettings;
- resetSettingsCache();
- return cachedSettings;
- }
- return null;
-}
-var SETTINGS_FILENAME = "remote-settings.json", sessionCache = null, eligible;
-var init_syncCacheState = __esm(() => {
- init_envUtils();
- init_fileRead();
- init_settingsCache();
- init_slowOperations();
-});
-
-// src/utils/array.ts
-function intersperse(as, separator) {
- return as.flatMap((a2, i2) => i2 ? [separator(i2), a2] : [a2]);
-}
-function count2(arr, pred) {
- let n2 = 0;
- for (const x2 of arr)
- n2 += +!!pred(x2);
- return n2;
-}
-function uniq(xs) {
- return [...new Set(xs)];
-}
-
-// src/utils/git/gitignore.ts
-import { appendFile as appendFile2, mkdir as mkdir2, readFile as readFile6, writeFile } from "fs/promises";
-import { homedir as homedir8 } from "os";
-import { dirname as dirname10, join as join18 } from "path";
-async function isPathGitignored(filePath, cwd2) {
- const { code } = await execFileNoThrowWithCwd("git", ["check-ignore", filePath], {
- preserveOutputOnError: false,
- cwd: cwd2
- });
- return code === 0;
-}
-function getGlobalGitignorePath() {
- return join18(homedir8(), ".config", "git", "ignore");
-}
-async function addFileGlobRuleToGitignore(filename, cwd2 = getCwd()) {
- try {
- if (!await dirIsInGitRepo(cwd2)) {
- return;
- }
- const gitignoreEntry = `**/${filename}`;
- const testPath = filename.endsWith("/") ? `${filename}sample-file.txt` : filename;
- if (await isPathGitignored(testPath, cwd2)) {
- return;
- }
- const globalGitignorePath = getGlobalGitignorePath();
- const configGitDir = dirname10(globalGitignorePath);
- await mkdir2(configGitDir, { recursive: true });
- try {
- const content = await readFile6(globalGitignorePath, { encoding: "utf-8" });
- if (content.includes(gitignoreEntry)) {
- return;
- }
- await appendFile2(globalGitignorePath, `
-${gitignoreEntry}
-`);
- } catch (e) {
- const code = getErrnoCode(e);
- if (code === "ENOENT") {
- await writeFile(globalGitignorePath, `${gitignoreEntry}
-`, "utf-8");
- } else {
- throw e;
- }
- }
- } catch (error40) {
- logError2(error40);
- }
-}
-var init_gitignore = __esm(() => {
- init_cwd();
- init_errors();
- init_execFileNoThrow();
- init_git();
- init_log2();
-});
-
-// src/utils/settings/constants.ts
-function getSettingSourceName(source) {
- switch (source) {
- case "userSettings":
- return "user";
- case "projectSettings":
- return "project";
- case "localSettings":
- return "project, gitignored";
- case "flagSettings":
- return "cli flag";
- case "policySettings":
- return "managed";
- }
-}
-function getSourceDisplayName(source) {
- switch (source) {
- case "userSettings":
- return "User";
- case "projectSettings":
- return "Project";
- case "localSettings":
- return "Local";
- case "flagSettings":
- return "Flag";
- case "policySettings":
- return "Managed";
- case "plugin":
- return "Plugin";
- case "built-in":
- return "Built-in";
- }
-}
-function getSettingSourceDisplayNameLowercase(source) {
- switch (source) {
- case "userSettings":
- return "user settings";
- case "projectSettings":
- return "shared project settings";
- case "localSettings":
- return "project local settings";
- case "flagSettings":
- return "command line arguments";
- case "policySettings":
- return "enterprise managed settings";
- case "cliArg":
- return "CLI argument";
- case "command":
- return "command configuration";
- case "session":
- return "current session";
- }
-}
-function getSettingSourceDisplayNameCapitalized(source) {
- switch (source) {
- case "userSettings":
- return "User settings";
- case "projectSettings":
- return "Shared project settings";
- case "localSettings":
- return "Project local settings";
- case "flagSettings":
- return "Command line arguments";
- case "policySettings":
- return "Enterprise managed settings";
- case "cliArg":
- return "CLI argument";
- case "command":
- return "Command configuration";
- case "session":
- return "Current session";
- }
-}
-function parseSettingSourcesFlag(flag) {
- if (flag === "")
- return [];
- const names = flag.split(",").map((s) => s.trim());
- const result = [];
- for (const name of names) {
- switch (name) {
- case "user":
- result.push("userSettings");
- break;
- case "project":
- result.push("projectSettings");
- break;
- case "local":
- result.push("localSettings");
- break;
- default:
- throw new Error(`Invalid setting source: ${name}. Valid options are: user, project, local`);
- }
- }
- return result;
-}
-function getEnabledSettingSources() {
- const allowed = getAllowedSettingSources();
- const result = new Set(allowed);
- result.add("policySettings");
- result.add("flagSettings");
- return Array.from(result);
-}
-function isSettingSourceEnabled(source) {
- const enabled = getEnabledSettingSources();
- return enabled.includes(source);
-}
-var SETTING_SOURCES, SOURCES, CLAUDE_CODE_SETTINGS_SCHEMA_URL = "https://json.schemastore.org/claude-code-settings.json";
-var init_constants2 = __esm(() => {
- init_state();
- SETTING_SOURCES = [
- "userSettings",
- "projectSettings",
- "localSettings",
- "flagSettings",
- "policySettings"
- ];
- SOURCES = [
- "localSettings",
- "projectSettings",
- "userSettings"
- ];
-});
-
-// src/utils/settings/internalWrites.ts
-function markInternalWrite(path8) {
- timestamps.set(path8, Date.now());
-}
-function consumeInternalWrite(path8, windowMs) {
- const ts = timestamps.get(path8);
- if (ts !== undefined && Date.now() - ts < windowMs) {
- timestamps.delete(path8);
- return true;
- }
- return false;
-}
-function clearInternalWrites() {
- timestamps.clear();
-}
-var timestamps;
-var init_internalWrites = __esm(() => {
- timestamps = new Map;
-});
-
-// src/utils/lazySchema.ts
-function lazySchema(factory2) {
- let cached2;
- return () => cached2 ??= factory2();
-}
-
-// src/entrypoints/sandboxTypes.ts
-var SandboxNetworkConfigSchema, SandboxFilesystemConfigSchema, SandboxSettingsSchema;
-var init_sandboxTypes = __esm(() => {
- init_v4();
- SandboxNetworkConfigSchema = lazySchema(() => exports_external.object({
- allowedDomains: exports_external.array(exports_external.string()).optional(),
- allowManagedDomainsOnly: exports_external.boolean().optional().describe("When true (and set in managed settings), only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. " + "User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources."),
- allowUnixSockets: exports_external.array(exports_external.string()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),
- allowAllUnixSockets: exports_external.boolean().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),
- allowLocalBinding: exports_external.boolean().optional(),
- httpProxyPort: exports_external.number().optional(),
- socksProxyPort: exports_external.number().optional()
- }).optional());
- SandboxFilesystemConfigSchema = lazySchema(() => exports_external.object({
- allowWrite: exports_external.array(exports_external.string()).optional().describe("Additional paths to allow writing within the sandbox. " + "Merged with paths from Edit(...) allow permission rules."),
- denyWrite: exports_external.array(exports_external.string()).optional().describe("Additional paths to deny writing within the sandbox. " + "Merged with paths from Edit(...) deny permission rules."),
- denyRead: exports_external.array(exports_external.string()).optional().describe("Additional paths to deny reading within the sandbox. " + "Merged with paths from Read(...) deny permission rules."),
- allowRead: exports_external.array(exports_external.string()).optional().describe("Paths to re-allow reading within denyRead regions. " + "Takes precedence over denyRead for matching paths."),
- allowManagedReadPathsOnly: exports_external.boolean().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used.")
- }).optional());
- SandboxSettingsSchema = lazySchema(() => exports_external.object({
- enabled: exports_external.boolean().optional(),
- failIfUnavailable: exports_external.boolean().optional().describe("Exit with an error at startup if sandbox.enabled is true but the sandbox cannot start " + "(missing dependencies, unsupported platform, or platform not in enabledPlatforms). " + "When false (default), a warning is shown and commands run unsandboxed. " + "Intended for managed-settings deployments that require sandboxing as a hard gate."),
- autoAllowBashIfSandboxed: exports_external.boolean().optional(),
- allowUnsandboxedCommands: exports_external.boolean().optional().describe("Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. " + "When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. " + "Default: true."),
- network: SandboxNetworkConfigSchema(),
- filesystem: SandboxFilesystemConfigSchema(),
- ignoreViolations: exports_external.record(exports_external.string(), exports_external.array(exports_external.string())).optional(),
- enableWeakerNestedSandbox: exports_external.boolean().optional(),
- enableWeakerNetworkIsolation: exports_external.boolean().optional().describe("macOS only: Allow access to com.apple.trustd.agent in the sandbox. " + "Needed for Go-based CLI tools (gh, gcloud, terraform, etc.) to verify TLS certificates " + "when using httpProxyPort with a MITM proxy and custom CA. " + "**Reduces security** \u2014 opens a potential data exfiltration vector through the trustd service. Default: false"),
- excludedCommands: exports_external.array(exports_external.string()).optional(),
- ripgrep: exports_external.object({
- command: exports_external.string(),
- args: exports_external.array(exports_external.string()).optional()
- }).optional().describe("Custom ripgrep configuration for bundled ripgrep support")
- }).passthrough());
-});
-
-// src/constants/figures.ts
-var BLACK_CIRCLE, TEARDROP_ASTERISK = "\u273B", UP_ARROW = "\u2191", DOWN_ARROW = "\u2193", LIGHTNING_BOLT = "\u21AF", EFFORT_LOW = "\u25CB", EFFORT_MEDIUM = "\u25D0", EFFORT_HIGH = "\u25CF", EFFORT_MAX = "\u25C9", PAUSE_ICON = "\u23F8", REFRESH_ARROW = "\u21BB", DIAMOND_OPEN = "\u25C7", DIAMOND_FILLED = "\u25C6", REFERENCE_MARK = "\u203B", BLOCKQUOTE_BAR = "\u258E", BRIDGE_READY_INDICATOR = "\xB7\u2714\uFE0E\xB7", BRIDGE_FAILED_INDICATOR = "\xD7";
-var init_figures2 = __esm(() => {
- init_env();
- BLACK_CIRCLE = env2.platform === "darwin" ? "\u23FA" : "\u25CF";
-});
-
-// src/types/permissions.ts
-var EXTERNAL_PERMISSION_MODES, INTERNAL_PERMISSION_MODES, PERMISSION_MODES;
-var init_permissions = __esm(() => {
- EXTERNAL_PERMISSION_MODES = [
- "acceptEdits",
- "bypassPermissions",
- "default",
- "dontAsk",
- "plan"
- ];
- INTERNAL_PERMISSION_MODES = [
- ...EXTERNAL_PERMISSION_MODES,
- ...[]
- ];
- PERMISSION_MODES = INTERNAL_PERMISSION_MODES;
-});
-
-// src/utils/permissions/PermissionMode.ts
-function isExternalPermissionMode(mode) {
- if (process.env.USER_TYPE !== "ant") {
- return true;
- }
- return mode !== "auto" && mode !== "bubble";
-}
-function getModeConfig(mode) {
- return PERMISSION_MODE_CONFIG[mode] ?? PERMISSION_MODE_CONFIG.default;
-}
-function toExternalPermissionMode(mode) {
- return getModeConfig(mode).external;
-}
-function permissionModeFromString(str) {
- return PERMISSION_MODES.includes(str) ? str : "default";
-}
-function permissionModeTitle(mode) {
- return getModeConfig(mode).title;
-}
-function isDefaultMode(mode) {
- return mode === "default" || mode === undefined;
-}
-function permissionModeSymbol(mode) {
- return getModeConfig(mode).symbol;
-}
-function getModeColor(mode) {
- return getModeConfig(mode).color;
-}
-var permissionModeSchema, externalPermissionModeSchema, PERMISSION_MODE_CONFIG;
-var init_PermissionMode = __esm(() => {
- init_v4();
- init_figures2();
- init_permissions();
- permissionModeSchema = lazySchema(() => v4_default.enum(PERMISSION_MODES));
- externalPermissionModeSchema = lazySchema(() => v4_default.enum(EXTERNAL_PERMISSION_MODES));
- PERMISSION_MODE_CONFIG = {
- default: {
- title: "Default",
- shortTitle: "Default",
- symbol: "",
- color: "text",
- external: "default"
- },
- plan: {
- title: "Plan Mode",
- shortTitle: "Plan",
- symbol: PAUSE_ICON,
- color: "planMode",
- external: "plan"
- },
- acceptEdits: {
- title: "Accept edits",
- shortTitle: "Accept",
- symbol: "\u23F5\u23F5",
- color: "autoAccept",
- external: "acceptEdits"
- },
- bypassPermissions: {
- title: "Bypass Permissions",
- shortTitle: "Bypass",
- symbol: "\u23F5\u23F5",
- color: "error",
- external: "bypassPermissions"
- },
- dontAsk: {
- title: "Don't Ask",
- shortTitle: "DontAsk",
- symbol: "\u23F5\u23F5",
- color: "error",
- external: "dontAsk"
- },
- ...{}
- };
-});
-
-// src/entrypoints/sdk/coreTypes.generated.ts
-var init_coreTypes_generated = () => {};
-
-// src/entrypoints/sdk/coreTypes.ts
-var HOOK_EVENTS;
-var init_coreTypes = __esm(() => {
- init_coreTypes_generated();
- HOOK_EVENTS = [
- "PreToolUse",
- "PostToolUse",
- "PostToolUseFailure",
- "Notification",
- "UserPromptSubmit",
- "SessionStart",
- "SessionEnd",
- "Stop",
- "StopFailure",
- "SubagentStart",
- "SubagentStop",
- "PreCompact",
- "PostCompact",
- "PermissionRequest",
- "PermissionDenied",
- "Setup",
- "TeammateIdle",
- "TaskCreated",
- "TaskCompleted",
- "Elicitation",
- "ElicitationResult",
- "ConfigChange",
- "WorktreeCreate",
- "WorktreeRemove",
- "InstructionsLoaded",
- "CwdChanged",
- "FileChanged"
- ];
-});
-
-// src/entrypoints/sdk/runtimeTypes.ts
-var init_runtimeTypes = () => {};
-
-// src/entrypoints/sdk/toolTypes.ts
-var init_toolTypes = () => {};
-
-// src/entrypoints/agentSdkTypes.ts
-var init_agentSdkTypes = __esm(() => {
- init_coreTypes();
- init_runtimeTypes();
- init_toolTypes();
-});
-
-// src/utils/shell/shellProvider.ts
-var SHELL_TYPES, DEFAULT_HOOK_SHELL = "bash";
-var init_shellProvider = __esm(() => {
- SHELL_TYPES = ["bash", "powershell"];
-});
-
-// src/schemas/hooks.ts
-function buildHookSchemas() {
- const BashCommandHookSchema = exports_external.object({
- type: exports_external.literal("command").describe("Shell command hook type"),
- command: exports_external.string().describe("Shell command to execute"),
- if: IfConditionSchema(),
- shell: exports_external.enum(SHELL_TYPES).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash."),
- timeout: exports_external.number().positive().optional().describe("Timeout in seconds for this specific command"),
- statusMessage: exports_external.string().optional().describe("Custom status message to display in spinner while hook runs"),
- once: exports_external.boolean().optional().describe("If true, hook runs once and is removed after execution"),
- async: exports_external.boolean().optional().describe("If true, hook runs in background without blocking"),
- asyncRewake: exports_external.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async.")
- });
- const PromptHookSchema = exports_external.object({
- type: exports_external.literal("prompt").describe("LLM prompt hook type"),
- prompt: exports_external.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),
- if: IfConditionSchema(),
- timeout: exports_external.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),
- model: exports_external.string().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-4-6"). If not specified, uses the default small fast model.'),
- statusMessage: exports_external.string().optional().describe("Custom status message to display in spinner while hook runs"),
- once: exports_external.boolean().optional().describe("If true, hook runs once and is removed after execution")
- });
- const HttpHookSchema = exports_external.object({
- type: exports_external.literal("http").describe("HTTP hook type"),
- url: exports_external.string().url().describe("URL to POST the hook input JSON to"),
- if: IfConditionSchema(),
- timeout: exports_external.number().positive().optional().describe("Timeout in seconds for this specific request"),
- headers: exports_external.record(exports_external.string(), exports_external.string()).optional().describe('Additional headers to include in the request. Values may reference environment variables using $VAR_NAME or ${VAR_NAME} syntax (e.g., "Authorization": "Bearer $MY_TOKEN"). Only variables listed in allowedEnvVars will be interpolated.'),
- allowedEnvVars: exports_external.array(exports_external.string()).optional().describe("Explicit list of environment variable names that may be interpolated in header values. Only variables listed here will be resolved; all other $VAR references are left as empty strings. Required for env var interpolation to work."),
- statusMessage: exports_external.string().optional().describe("Custom status message to display in spinner while hook runs"),
- once: exports_external.boolean().optional().describe("If true, hook runs once and is removed after execution")
- });
- const AgentHookSchema = exports_external.object({
- type: exports_external.literal("agent").describe("Agentic verifier hook type"),
- prompt: exports_external.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),
- if: IfConditionSchema(),
- timeout: exports_external.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),
- model: exports_external.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-4-6"). If not specified, uses Haiku.'),
- statusMessage: exports_external.string().optional().describe("Custom status message to display in spinner while hook runs"),
- once: exports_external.boolean().optional().describe("If true, hook runs once and is removed after execution")
- });
- return {
- BashCommandHookSchema,
- PromptHookSchema,
- HttpHookSchema,
- AgentHookSchema
- };
-}
-var IfConditionSchema, HookCommandSchema, HookMatcherSchema, HooksSchema;
-var init_hooks = __esm(() => {
- init_agentSdkTypes();
- init_v4();
- init_shellProvider();
- IfConditionSchema = lazySchema(() => exports_external.string().optional().describe('Permission rule syntax to filter when this hook runs (e.g., "Bash(git *)"). ' + "Only runs if the tool call matches the pattern. Avoids spawning hooks for non-matching commands."));
- HookCommandSchema = lazySchema(() => {
- const {
- BashCommandHookSchema,
- PromptHookSchema,
- AgentHookSchema,
- HttpHookSchema
- } = buildHookSchemas();
- return exports_external.discriminatedUnion("type", [
- BashCommandHookSchema,
- PromptHookSchema,
- AgentHookSchema,
- HttpHookSchema
- ]);
- });
- HookMatcherSchema = lazySchema(() => exports_external.object({
- matcher: exports_external.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),
- hooks: exports_external.array(HookCommandSchema()).describe("List of hooks to execute when the matcher matches")
- }));
- HooksSchema = lazySchema(() => exports_external.partialRecord(exports_external.enum(HOOK_EVENTS), exports_external.array(HookMatcherSchema())));
-});
-
-// src/services/mcp/types.ts
-var ConfigScopeSchema, TransportSchema, McpStdioServerConfigSchema, McpXaaConfigSchema, McpOAuthConfigSchema, McpSSEServerConfigSchema, McpSSEIDEServerConfigSchema, McpWebSocketIDEServerConfigSchema, McpHTTPServerConfigSchema, McpWebSocketServerConfigSchema, McpSdkServerConfigSchema, McpClaudeAIProxyServerConfigSchema, McpServerConfigSchema, McpJsonConfigSchema;
-var init_types = __esm(() => {
- init_v4();
- ConfigScopeSchema = lazySchema(() => exports_external.enum([
- "local",
- "user",
- "project",
- "dynamic",
- "enterprise",
- "claudeai",
- "managed"
- ]));
- TransportSchema = lazySchema(() => exports_external.enum(["stdio", "sse", "sse-ide", "http", "ws", "sdk"]));
- McpStdioServerConfigSchema = lazySchema(() => exports_external.object({
- type: exports_external.literal("stdio").optional(),
- command: exports_external.string().min(1, "Command cannot be empty"),
- args: exports_external.array(exports_external.string()).default([]),
- env: exports_external.record(exports_external.string(), exports_external.string()).optional()
- }));
- McpXaaConfigSchema = lazySchema(() => exports_external.boolean());
- McpOAuthConfigSchema = lazySchema(() => exports_external.object({
- clientId: exports_external.string().optional(),
- callbackPort: exports_external.number().int().positive().optional(),
- authServerMetadataUrl: exports_external.string().url().startsWith("https://", {
- message: "authServerMetadataUrl must use https://"
- }).optional(),
- xaa: McpXaaConfigSchema().optional()
- }));
- McpSSEServerConfigSchema = lazySchema(() => exports_external.object({
- type: exports_external.literal("sse"),
- url: exports_external.string(),
- headers: exports_external.record(exports_external.string(), exports_external.string()).optional(),
- headersHelper: exports_external.string().optional(),
- oauth: McpOAuthConfigSchema().optional()
- }));
- McpSSEIDEServerConfigSchema = lazySchema(() => exports_external.object({
- type: exports_external.literal("sse-ide"),
- url: exports_external.string(),
- ideName: exports_external.string(),
- ideRunningInWindows: exports_external.boolean().optional()
- }));
- McpWebSocketIDEServerConfigSchema = lazySchema(() => exports_external.object({
- type: exports_external.literal("ws-ide"),
- url: exports_external.string(),
- ideName: exports_external.string(),
- authToken: exports_external.string().optional(),
- ideRunningInWindows: exports_external.boolean().optional()
- }));
- McpHTTPServerConfigSchema = lazySchema(() => exports_external.object({
- type: exports_external.literal("http"),
- url: exports_external.string(),
- headers: exports_external.record(exports_external.string(), exports_external.string()).optional(),
- headersHelper: exports_external.string().optional(),
- oauth: McpOAuthConfigSchema().optional()
- }));
- McpWebSocketServerConfigSchema = lazySchema(() => exports_external.object({
- type: exports_external.literal("ws"),
- url: exports_external.string(),
- headers: exports_external.record(exports_external.string(), exports_external.string()).optional(),
- headersHelper: exports_external.string().optional()
- }));
- McpSdkServerConfigSchema = lazySchema(() => exports_external.object({
- type: exports_external.literal("sdk"),
- name: exports_external.string()
- }));
- McpClaudeAIProxyServerConfigSchema = lazySchema(() => exports_external.object({
- type: exports_external.literal("claudeai-proxy"),
- url: exports_external.string(),
- id: exports_external.string()
- }));
- McpServerConfigSchema = lazySchema(() => exports_external.union([
- McpStdioServerConfigSchema(),
- McpSSEServerConfigSchema(),
- McpSSEIDEServerConfigSchema(),
- McpWebSocketIDEServerConfigSchema(),
- McpHTTPServerConfigSchema(),
- McpWebSocketServerConfigSchema(),
- McpSdkServerConfigSchema(),
- McpClaudeAIProxyServerConfigSchema()
- ]));
- McpJsonConfigSchema = lazySchema(() => exports_external.object({
- mcpServers: exports_external.record(exports_external.string(), McpServerConfigSchema())
- }));
-});
-
-// src/utils/plugins/schemas.ts
-function isMarketplaceAutoUpdate(marketplaceName, entry) {
- const normalizedName = marketplaceName.toLowerCase();
- return entry.autoUpdate ?? (ALLOWED_OFFICIAL_MARKETPLACE_NAMES.has(normalizedName) && !NO_AUTO_UPDATE_OFFICIAL_MARKETPLACES.has(normalizedName));
-}
-function isBlockedOfficialName(name) {
- if (ALLOWED_OFFICIAL_MARKETPLACE_NAMES.has(name.toLowerCase())) {
- return false;
- }
- if (NON_ASCII_PATTERN.test(name)) {
- return true;
- }
- return BLOCKED_OFFICIAL_NAME_PATTERN.test(name);
-}
-function validateOfficialNameSource(name, source) {
- const normalizedName = name.toLowerCase();
- if (!ALLOWED_OFFICIAL_MARKETPLACE_NAMES.has(normalizedName)) {
- return null;
- }
- if (source.source === "github") {
- const repo = source.repo || "";
- if (!repo.toLowerCase().startsWith(`${OFFICIAL_GITHUB_ORG}/`)) {
- return `The name '${name}' is reserved for official Anthropic marketplaces. Only repositories from 'github.com/${OFFICIAL_GITHUB_ORG}/' can use this name.`;
- }
- return null;
- }
- if (source.source === "git" && source.url) {
- const url3 = source.url.toLowerCase();
- const isHttpsAnthropics = url3.includes("github.com/anthropics/");
- const isSshAnthropics = url3.includes("git@github.com:anthropics/");
- if (isHttpsAnthropics || isSshAnthropics) {
- return null;
- }
- return `The name '${name}' is reserved for official Anthropic marketplaces. Only repositories from 'github.com/${OFFICIAL_GITHUB_ORG}/' can use this name.`;
- }
- return `The name '${name}' is reserved for official Anthropic marketplaces and can only be used with GitHub sources from the '${OFFICIAL_GITHUB_ORG}' organization.`;
-}
-function isLocalPluginSource(source) {
- return typeof source === "string" && source.startsWith("./");
-}
-function isLocalMarketplaceSource(source) {
- return source.source === "file" || source.source === "directory";
-}
-var ALLOWED_OFFICIAL_MARKETPLACE_NAMES, NO_AUTO_UPDATE_OFFICIAL_MARKETPLACES, BLOCKED_OFFICIAL_NAME_PATTERN, NON_ASCII_PATTERN, OFFICIAL_GITHUB_ORG = "anthropics", RelativePath, RelativeJSONPath, McpbPath, RelativeMarkdownPath, RelativeCommandPath, MarketplaceNameSchema, PluginAuthorSchema, PluginManifestMetadataSchema, PluginHooksSchema, PluginManifestHooksSchema, CommandMetadataSchema, PluginManifestCommandsSchema, PluginManifestAgentsSchema, PluginManifestSkillsSchema, PluginManifestOutputStylesSchema, nonEmptyString, fileExtension, PluginManifestMcpServerSchema, PluginUserConfigOptionSchema, PluginManifestUserConfigSchema, PluginManifestChannelsSchema, LspServerConfigSchema, PluginManifestLspServerSchema, NpmPackageNameSchema, PluginManifestSettingsSchema, PluginManifestSchema, MarketplaceSourceSchema, gitSha, PluginSourceSchema, SettingsMarketplacePluginSchema, PluginMarketplaceEntrySchema, PluginMarketplaceSchema, PluginIdSchema, DEP_REF_REGEX, DependencyRefSchema, SettingsPluginEntrySchema, InstalledPluginSchema, InstalledPluginsFileSchemaV1, PluginScopeSchema, PluginInstallationEntrySchema, InstalledPluginsFileSchemaV2, InstalledPluginsFileSchema, KnownMarketplaceSchema, KnownMarketplacesFileSchema;
-var init_schemas3 = __esm(() => {
- init_v4();
- init_hooks();
- init_types();
- ALLOWED_OFFICIAL_MARKETPLACE_NAMES = new Set([
- "claude-code-marketplace",
- "claude-code-plugins",
- "claude-plugins-official",
- "anthropic-marketplace",
- "anthropic-plugins",
- "agent-skills",
- "life-sciences",
- "knowledge-work-plugins"
- ]);
- NO_AUTO_UPDATE_OFFICIAL_MARKETPLACES = new Set(["knowledge-work-plugins"]);
- BLOCKED_OFFICIAL_NAME_PATTERN = /(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i;
- NON_ASCII_PATTERN = /[^\u0020-\u007E]/;
- RelativePath = lazySchema(() => exports_external.string().startsWith("./"));
- RelativeJSONPath = lazySchema(() => RelativePath().endsWith(".json"));
- McpbPath = lazySchema(() => exports_external.union([
- RelativePath().refine((path8) => path8.endsWith(".mcpb") || path8.endsWith(".dxt"), {
- message: "MCPB file path must end with .mcpb or .dxt"
- }).describe("Path to MCPB file relative to plugin root"),
- exports_external.string().url().refine((url3) => url3.endsWith(".mcpb") || url3.endsWith(".dxt"), {
- message: "MCPB URL must end with .mcpb or .dxt"
- }).describe("URL to MCPB file")
- ]));
- RelativeMarkdownPath = lazySchema(() => RelativePath().endsWith(".md"));
- RelativeCommandPath = lazySchema(() => exports_external.union([
- RelativeMarkdownPath(),
- RelativePath()
- ]));
- MarketplaceNameSchema = lazySchema(() => exports_external.string().min(1, "Marketplace must have a name").refine((name) => !name.includes(" "), {
- message: 'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'
- }).refine((name) => !name.includes("/") && !name.includes("\\") && !name.includes("..") && name !== ".", {
- message: 'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'
- }).refine((name) => !isBlockedOfficialName(name), {
- message: "Marketplace name impersonates an official Anthropic/Claude marketplace"
- }).refine((name) => name.toLowerCase() !== "inline", {
- message: 'Marketplace name "inline" is reserved for --plugin-dir session plugins'
- }).refine((name) => name.toLowerCase() !== "builtin", {
- message: 'Marketplace name "builtin" is reserved for built-in plugins'
- }));
- PluginAuthorSchema = lazySchema(() => exports_external.object({
- name: exports_external.string().min(1, "Author name cannot be empty").describe("Display name of the plugin author or organization"),
- email: exports_external.string().optional().describe("Contact email for support or feedback"),
- url: exports_external.string().optional().describe("Website, GitHub profile, or organization URL")
- }));
- PluginManifestMetadataSchema = lazySchema(() => exports_external.object({
- name: exports_external.string().min(1, "Plugin name cannot be empty").refine((name) => !name.includes(" "), {
- message: 'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'
- }).describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),
- version: exports_external.string().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),
- description: exports_external.string().optional().describe("Brief, user-facing explanation of what the plugin provides"),
- author: PluginAuthorSchema().optional().describe("Information about the plugin creator or maintainer"),
- homepage: exports_external.string().url().optional().describe("Plugin homepage or documentation URL"),
- repository: exports_external.string().optional().describe("Source code repository URL"),
- license: exports_external.string().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),
- keywords: exports_external.array(exports_external.string()).optional().describe("Tags for plugin discovery and categorization"),
- dependencies: exports_external.array(DependencyRefSchema()).optional().describe(`Plugins that must be enabled for this plugin to function. Bare names (no "@marketplace") are resolved against the declaring plugin's own marketplace.`)
- }));
- PluginHooksSchema = lazySchema(() => exports_external.object({
- description: exports_external.string().optional().describe("Brief, user-facing explanation of what these hooks provide"),
- hooks: exports_external.lazy(() => HooksSchema()).describe("The hooks provided by the plugin, in the same format as the one used for settings")
- }));
- PluginManifestHooksSchema = lazySchema(() => exports_external.object({
- hooks: exports_external.union([
- RelativeJSONPath().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),
- exports_external.lazy(() => HooksSchema()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),
- exports_external.array(exports_external.union([
- RelativeJSONPath().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),
- exports_external.lazy(() => HooksSchema()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")
- ]))
- ])
- }));
- CommandMetadataSchema = lazySchema(() => exports_external.object({
- source: RelativeCommandPath().optional().describe("Path to command markdown file, relative to plugin root"),
- content: exports_external.string().optional().describe("Inline markdown content for the command"),
- description: exports_external.string().optional().describe("Command description override"),
- argumentHint: exports_external.string().optional().describe('Hint for command arguments (e.g., "[file]")'),
- model: exports_external.string().optional().describe("Default model for this command"),
- allowedTools: exports_external.array(exports_external.string()).optional().describe("Tools allowed when command runs")
- }).refine((data) => data.source && !data.content || !data.source && data.content, {
- message: 'Command must have either "source" (file path) or "content" (inline markdown), but not both'
- }));
- PluginManifestCommandsSchema = lazySchema(() => exports_external.object({
- commands: exports_external.union([
- RelativeCommandPath().describe("Path to additional command file or skill directory (in addition to those in the commands/ directory, if it exists), relative to the plugin root"),
- exports_external.array(RelativeCommandPath().describe("Path to additional command file or skill directory (in addition to those in the commands/ directory, if it exists), relative to the plugin root")).describe("List of paths to additional command files or skill directories"),
- exports_external.record(exports_external.string(), CommandMetadataSchema()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" \u2192 "/plugin:about")')
- ])
- }));
- PluginManifestAgentsSchema = lazySchema(() => exports_external.object({
- agents: exports_external.union([
- RelativeMarkdownPath().describe("Path to additional agent file (in addition to those in the agents/ directory, if it exists), relative to the plugin root"),
- exports_external.array(RelativeMarkdownPath().describe("Path to additional agent file (in addition to those in the agents/ directory, if it exists), relative to the plugin root")).describe("List of paths to additional agent files")
- ])
- }));
- PluginManifestSkillsSchema = lazySchema(() => exports_external.object({
- skills: exports_external.union([
- RelativePath().describe("Path to additional skill directory (in addition to those in the skills/ directory, if it exists), relative to the plugin root"),
- exports_external.array(RelativePath().describe("Path to additional skill directory (in addition to those in the skills/ directory, if it exists), relative to the plugin root")).describe("List of paths to additional skill directories")
- ])
- }));
- PluginManifestOutputStylesSchema = lazySchema(() => exports_external.object({
- outputStyles: exports_external.union([
- RelativePath().describe("Path to additional output styles directory or file (in addition to those in the output-styles/ directory, if it exists), relative to the plugin root"),
- exports_external.array(RelativePath().describe("Path to additional output styles directory or file (in addition to those in the output-styles/ directory, if it exists), relative to the plugin root")).describe("List of paths to additional output styles directories or files")
- ])
- }));
- nonEmptyString = lazySchema(() => exports_external.string().min(1));
- fileExtension = lazySchema(() => exports_external.string().min(2).refine((ext) => ext.startsWith("."), {
- message: 'File extensions must start with dot (e.g., ".ts", not "ts")'
- }));
- PluginManifestMcpServerSchema = lazySchema(() => exports_external.object({
- mcpServers: exports_external.union([
- RelativeJSONPath().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),
- McpbPath().describe("Path or URL to MCPB file containing MCP server configuration"),
- exports_external.record(exports_external.string(), McpServerConfigSchema()).describe("MCP server configurations keyed by server name"),
- exports_external.array(exports_external.union([
- RelativeJSONPath().describe("Path to MCP servers configuration file"),
- McpbPath().describe("Path or URL to MCPB file"),
- exports_external.record(exports_external.string(), McpServerConfigSchema()).describe("Inline MCP server configurations")
- ])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")
- ])
- }));
- PluginUserConfigOptionSchema = lazySchema(() => exports_external.object({
- type: exports_external.enum(["string", "number", "boolean", "directory", "file"]).describe("Type of the configuration value"),
- title: exports_external.string().describe("Human-readable label shown in the config dialog"),
- description: exports_external.string().describe("Help text shown beneath the field in the config dialog"),
- required: exports_external.boolean().optional().describe("If true, validation fails when this field is empty"),
- default: exports_external.union([exports_external.string(), exports_external.number(), exports_external.boolean(), exports_external.array(exports_external.string())]).optional().describe("Default value used when the user provides nothing"),
- multiple: exports_external.boolean().optional().describe("For string type: allow an array of strings"),
- sensitive: exports_external.boolean().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),
- min: exports_external.number().optional().describe("Minimum value (number type only)"),
- max: exports_external.number().optional().describe("Maximum value (number type only)")
- }).strict());
- PluginManifestUserConfigSchema = lazySchema(() => exports_external.object({
- userConfig: exports_external.record(exports_external.string().regex(/^[A-Za-z_]\w*$/, "Option keys must be valid identifiers (letters, digits, underscore; no leading digit) \u2014 they become CLAUDE_PLUGIN_OPTION_ env vars in hooks"), PluginUserConfigOptionSchema()).optional().describe("User-configurable values this plugin needs. Prompted at enable time. " + "Non-sensitive values saved to settings.json; sensitive values to secure storage " + "(macOS keychain or .credentials.json). Available as ${user_config.KEY} in " + "MCP/LSP server config, hook commands, and (non-sensitive only) skill/agent content. " + "Note: sensitive values share a single keychain entry with OAuth tokens \u2014 keep " + "secret counts small to stay under the ~2KB stdin-safe limit (see INC-3028).")
- }));
- PluginManifestChannelsSchema = lazySchema(() => exports_external.object({
- channels: exports_external.array(exports_external.object({
- server: exports_external.string().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),
- displayName: exports_external.string().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),
- userConfig: exports_external.record(exports_external.string(), PluginUserConfigOptionSchema()).optional().describe("Fields to prompt the user for when enabling this plugin in assistant mode. " + "Saved values are substituted into ${user_config.KEY} references in the mcpServers env.")
- }).strict()).describe("Channels this plugin provides. Each entry declares an MCP server as a message channel " + "and optionally specifies user configuration to prompt for at enable time.")
- }));
- LspServerConfigSchema = lazySchema(() => exports_external.strictObject({
- command: exports_external.string().min(1).refine((cmd) => {
- if (cmd.includes(" ") && !cmd.startsWith("/")) {
- return false;
- }
- return true;
- }, {
- message: "Command should not contain spaces. Use args array for arguments."
- }).describe('Command to execute the LSP server (e.g., "typescript-language-server")'),
- args: exports_external.array(nonEmptyString()).optional().describe("Command-line arguments to pass to the server"),
- extensionToLanguage: exports_external.record(fileExtension(), nonEmptyString()).refine((record2) => Object.keys(record2).length > 0, {
- message: "extensionToLanguage must have at least one mapping"
- }).describe("Mapping from file extension to LSP language ID. File extensions and languages are derived from this mapping."),
- transport: exports_external.enum(["stdio", "socket"]).default("stdio").describe("Communication transport mechanism"),
- env: exports_external.record(exports_external.string(), exports_external.string()).optional().describe("Environment variables to set when starting the server"),
- initializationOptions: exports_external.unknown().optional().describe("Initialization options passed to the server during initialization"),
- settings: exports_external.unknown().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),
- workspaceFolder: exports_external.string().optional().describe("Workspace folder path to use for the server"),
- startupTimeout: exports_external.number().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),
- shutdownTimeout: exports_external.number().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),
- restartOnCrash: exports_external.boolean().optional().describe("Whether to restart the server if it crashes"),
- maxRestarts: exports_external.number().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up")
- }));
- PluginManifestLspServerSchema = lazySchema(() => exports_external.object({
- lspServers: exports_external.union([
- RelativeJSONPath().describe("Path to .lsp.json configuration file relative to plugin root"),
- exports_external.record(exports_external.string(), LspServerConfigSchema()).describe("LSP server configurations keyed by server name"),
- exports_external.array(exports_external.union([
- RelativeJSONPath().describe("Path to LSP configuration file"),
- exports_external.record(exports_external.string(), LspServerConfigSchema()).describe("Inline LSP server configurations")
- ])).describe("Array of LSP server configurations (paths or inline definitions)")
- ])
- }));
- NpmPackageNameSchema = lazySchema(() => exports_external.string().refine((name) => !name.includes("..") && !name.includes("//"), "Package name cannot contain path traversal patterns").refine((name) => {
- const scopedPackageRegex = /^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/;
- const regularPackageRegex = /^[a-z0-9][a-z0-9-._]*$/;
- return scopedPackageRegex.test(name) || regularPackageRegex.test(name);
- }, "Invalid npm package name format"));
- PluginManifestSettingsSchema = lazySchema(() => exports_external.object({
- settings: exports_external.record(exports_external.string(), exports_external.unknown()).optional().describe("Settings to merge when plugin is enabled. " + "Only allowlisted keys are kept (currently: agent)")
- }));
- PluginManifestSchema = lazySchema(() => exports_external.object({
- ...PluginManifestMetadataSchema().shape,
- ...PluginManifestHooksSchema().partial().shape,
- ...PluginManifestCommandsSchema().partial().shape,
- ...PluginManifestAgentsSchema().partial().shape,
- ...PluginManifestSkillsSchema().partial().shape,
- ...PluginManifestOutputStylesSchema().partial().shape,
- ...PluginManifestChannelsSchema().partial().shape,
- ...PluginManifestMcpServerSchema().partial().shape,
- ...PluginManifestLspServerSchema().partial().shape,
- ...PluginManifestSettingsSchema().partial().shape,
- ...PluginManifestUserConfigSchema().partial().shape
- }));
- MarketplaceSourceSchema = lazySchema(() => exports_external.discriminatedUnion("source", [
- exports_external.object({
- source: exports_external.literal("url"),
- url: exports_external.string().url().describe("Direct URL to marketplace.json file"),
- headers: exports_external.record(exports_external.string(), exports_external.string()).optional().describe("Custom HTTP headers (e.g., for authentication)")
- }),
- exports_external.object({
- source: exports_external.literal("github"),
- repo: exports_external.string().describe("GitHub repository in owner/repo format"),
- ref: exports_external.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),
- path: exports_external.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),
- sparsePaths: exports_external.array(exports_external.string()).optional().describe("Directories to include via git sparse-checkout (cone mode). " + "Use for monorepos where the marketplace lives in a subdirectory. " + 'Example: [".claude-plugin", "plugins"]. ' + "If omitted, the full repository is cloned.")
- }),
- exports_external.object({
- source: exports_external.literal("git"),
- url: exports_external.string().describe("Full git repository URL"),
- ref: exports_external.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),
- path: exports_external.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),
- sparsePaths: exports_external.array(exports_external.string()).optional().describe("Directories to include via git sparse-checkout (cone mode). " + "Use for monorepos where the marketplace lives in a subdirectory. " + 'Example: [".claude-plugin", "plugins"]. ' + "If omitted, the full repository is cloned.")
- }),
- exports_external.object({
- source: exports_external.literal("npm"),
- package: NpmPackageNameSchema().describe("NPM package containing marketplace.json")
- }),
- exports_external.object({
- source: exports_external.literal("file"),
- path: exports_external.string().describe("Local file path to marketplace.json")
- }),
- exports_external.object({
- source: exports_external.literal("directory"),
- path: exports_external.string().describe("Local directory containing .claude-plugin/marketplace.json")
- }),
- exports_external.object({
- source: exports_external.literal("hostPattern"),
- hostPattern: exports_external.string().describe("Regex pattern to match the host/domain extracted from any marketplace source type. " + 'For github sources, matches against "github.com". For git sources (SSH or HTTPS), ' + "extracts the hostname from the URL. Use in strictKnownMarketplaces to allow all " + 'marketplaces from a specific host (e.g., "^github\\.mycompany\\.com$").')
- }),
- exports_external.object({
- source: exports_external.literal("pathPattern"),
- pathPattern: exports_external.string().describe("Regex pattern matched against the .path field of file and directory sources. " + "Use in strictKnownMarketplaces to allow filesystem-based marketplaces alongside " + 'hostPattern restrictions for network sources. Use ".*" to allow all filesystem ' + 'paths, or a narrower pattern (e.g., "^/opt/approved/") to restrict to specific ' + "directories.")
- }),
- exports_external.object({
- source: exports_external.literal("settings"),
- name: MarketplaceNameSchema().refine((name) => !ALLOWED_OFFICIAL_MARKETPLACE_NAMES.has(name.toLowerCase()), {
- message: "Reserved official marketplace names cannot be used with settings sources. " + "validateOfficialNameSource only accepts github/git sources from anthropics/* " + "for these names; a settings source would be rejected after " + "loadAndCacheMarketplace has already written to disk with cleanupNeeded=false."
- }).describe("Marketplace name. Must match the extraKnownMarketplaces key (enforced); " + "the synthetic manifest is written under this name. Same validation " + "as PluginMarketplaceSchema plus reserved-name rejection \u2014 " + "validateOfficialNameSource runs after the disk write, too late to clean up."),
- plugins: exports_external.array(SettingsMarketplacePluginSchema()).describe("Plugin entries declared inline in settings.json"),
- owner: PluginAuthorSchema().optional()
- }).describe("Inline marketplace manifest defined directly in settings.json. " + "The reconciler writes a synthetic marketplace.json to the cache; " + "diffMarketplaces detects edits via isEqual on the stored source " + "(the plugins array is inside this object, so edits surface as sourceChanged).")
- ]));
- gitSha = lazySchema(() => exports_external.string().length(40).regex(/^[a-f0-9]{40}$/, "Must be a full 40-character lowercase git commit SHA"));
- PluginSourceSchema = lazySchema(() => exports_external.union([
- RelativePath().describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),
- exports_external.object({
- source: exports_external.literal("npm"),
- package: NpmPackageNameSchema().or(exports_external.string()).describe("Package name (or url, or local path, or anything else that can be passed to `npm` as a package)"),
- version: exports_external.string().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),
- registry: exports_external.string().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")
- }).describe("NPM package as plugin source"),
- exports_external.object({
- source: exports_external.literal("pip"),
- package: exports_external.string().describe("Python package name as it appears on PyPI"),
- version: exports_external.string().optional().describe("Version specifier (e.g., ==1.0.0, >=2.0.0, <3.0.0)"),
- registry: exports_external.string().url().optional().describe("Custom PyPI registry URL (defaults to using system default, likely pypi.org)")
- }).describe("Python package as plugin source"),
- exports_external.object({
- source: exports_external.literal("url"),
- url: exports_external.string().describe("Full git repository URL (https:// or git@)"),
- ref: exports_external.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),
- sha: gitSha().optional().describe("Specific commit SHA to use")
- }),
- exports_external.object({
- source: exports_external.literal("github"),
- repo: exports_external.string().describe("GitHub repository in owner/repo format"),
- ref: exports_external.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),
- sha: gitSha().optional().describe("Specific commit SHA to use")
- }),
- exports_external.object({
- source: exports_external.literal("git-subdir"),
- url: exports_external.string().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),
- path: exports_external.string().min(1).describe('Subdirectory within the repo containing the plugin (e.g., "tools/claude-plugin"). ' + "Cloned sparsely using partial clone (--filter=tree:0) to minimize bandwidth for monorepos."),
- ref: exports_external.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),
- sha: gitSha().optional().describe("Specific commit SHA to use")
- }).describe("Plugin located in a subdirectory of a larger repository (monorepo). " + "Only the specified subdirectory is materialized; the rest of the repo is not downloaded.")
- ]));
- SettingsMarketplacePluginSchema = lazySchema(() => exports_external.object({
- name: exports_external.string().min(1, "Plugin name cannot be empty").refine((name) => !name.includes(" "), {
- message: 'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'
- }).describe("Plugin name as it appears in the target repository"),
- source: PluginSourceSchema().describe("Where to fetch the plugin from. Must be a remote source \u2014 relative " + "paths have no marketplace repository to resolve against."),
- description: exports_external.string().optional(),
- version: exports_external.string().optional(),
- strict: exports_external.boolean().optional()
- }).refine((p) => typeof p.source !== "string", {
- message: "Plugins in a settings-sourced marketplace must use remote sources " + '(github, git-subdir, npm, url, pip). Relative-path sources like "./foo" ' + "have no marketplace repository to resolve against."
- }));
- PluginMarketplaceEntrySchema = lazySchema(() => PluginManifestSchema().partial().extend({
- name: exports_external.string().min(1, "Plugin name cannot be empty").refine((name) => !name.includes(" "), {
- message: 'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'
- }).describe("Unique identifier matching the plugin name"),
- source: PluginSourceSchema().describe("Where to fetch the plugin from"),
- category: exports_external.string().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),
- tags: exports_external.array(exports_external.string()).optional().describe("Tags for searchability and discovery"),
- strict: exports_external.boolean().optional().default(true).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest.")
- }));
- PluginMarketplaceSchema = lazySchema(() => exports_external.object({
- name: MarketplaceNameSchema(),
- owner: PluginAuthorSchema().describe("Marketplace maintainer or curator information"),
- plugins: exports_external.array(PluginMarketplaceEntrySchema()).describe("Collection of available plugins in this marketplace"),
- forceRemoveDeletedPlugins: exports_external.boolean().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),
- metadata: exports_external.object({
- pluginRoot: exports_external.string().optional().describe("Base path for relative plugin sources"),
- version: exports_external.string().optional().describe("Marketplace version"),
- description: exports_external.string().optional().describe("Marketplace description")
- }).optional().describe("Optional marketplace metadata"),
- allowCrossMarketplaceDependenciesOn: exports_external.array(exports_external.string()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies \u2014 no transitive trust.")
- }));
- PluginIdSchema = lazySchema(() => exports_external.string().regex(/^[a-z0-9][-a-z0-9._]*@[a-z0-9][-a-z0-9._]*$/i, "Plugin ID must be in format: plugin@marketplace"));
- DEP_REF_REGEX = /^[a-z0-9][-a-z0-9._]*(@[a-z0-9][-a-z0-9._]*)?(@\^[^@]*)?$/i;
- DependencyRefSchema = lazySchema(() => exports_external.union([
- exports_external.string().regex(DEP_REF_REGEX, "Dependency must be a plugin name, optionally qualified with @marketplace").transform((s) => s.replace(/@\^[^@]*$/, "")),
- exports_external.object({
- name: exports_external.string().min(1).regex(/^[a-z0-9][-a-z0-9._]*$/i),
- marketplace: exports_external.string().min(1).regex(/^[a-z0-9][-a-z0-9._]*$/i).optional()
- }).loose().transform((o2) => o2.marketplace ? `${o2.name}@${o2.marketplace}` : o2.name)
- ]));
- SettingsPluginEntrySchema = lazySchema(() => exports_external.union([
- PluginIdSchema(),
- exports_external.object({
- id: PluginIdSchema().describe('Plugin identifier (e.g., "formatter@tools")'),
- version: exports_external.string().optional().describe('Version constraint (e.g., "^2.0.0")'),
- required: exports_external.boolean().optional().describe("If true, cannot be disabled"),
- config: exports_external.record(exports_external.string(), exports_external.unknown()).optional().describe("Plugin-specific configuration")
- })
- ]));
- InstalledPluginSchema = lazySchema(() => exports_external.object({
- version: exports_external.string().describe("Currently installed version"),
- installedAt: exports_external.string().describe("ISO 8601 timestamp of installation"),
- lastUpdated: exports_external.string().optional().describe("ISO 8601 timestamp of last update"),
- installPath: exports_external.string().describe("Absolute path to the installed plugin directory"),
- gitCommitSha: exports_external.string().optional().describe("Git commit SHA for git-based plugins (for version tracking)")
- }));
- InstalledPluginsFileSchemaV1 = lazySchema(() => exports_external.object({
- version: exports_external.literal(1).describe("Schema version 1"),
- plugins: exports_external.record(PluginIdSchema(), InstalledPluginSchema()).describe("Map of plugin IDs to their installation metadata")
- }));
- PluginScopeSchema = lazySchema(() => exports_external.enum(["managed", "user", "project", "local"]));
- PluginInstallationEntrySchema = lazySchema(() => exports_external.object({
- scope: PluginScopeSchema().describe("Installation scope"),
- projectPath: exports_external.string().optional().describe("Project path (required for project/local scopes)"),
- installPath: exports_external.string().describe("Absolute path to the versioned plugin directory"),
- version: exports_external.string().optional().describe("Currently installed version"),
- installedAt: exports_external.string().optional().describe("ISO 8601 timestamp of installation"),
- lastUpdated: exports_external.string().optional().describe("ISO 8601 timestamp of last update"),
- gitCommitSha: exports_external.string().optional().describe("Git commit SHA for git-based plugins")
- }));
- InstalledPluginsFileSchemaV2 = lazySchema(() => exports_external.object({
- version: exports_external.literal(2).describe("Schema version 2"),
- plugins: exports_external.record(PluginIdSchema(), exports_external.array(PluginInstallationEntrySchema())).describe("Map of plugin IDs to arrays of installation entries")
- }));
- InstalledPluginsFileSchema = lazySchema(() => exports_external.union([InstalledPluginsFileSchemaV1(), InstalledPluginsFileSchemaV2()]));
- KnownMarketplaceSchema = lazySchema(() => exports_external.object({
- source: MarketplaceSourceSchema().describe("Where to fetch the marketplace from"),
- installLocation: exports_external.string().describe("Local cache path where marketplace manifest is stored"),
- lastUpdated: exports_external.string().describe("ISO 8601 timestamp of last marketplace refresh"),
- autoUpdate: exports_external.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")
- }));
- KnownMarketplacesFileSchema = lazySchema(() => exports_external.record(exports_external.string(), KnownMarketplaceSchema()));
-});
-
-// src/services/mcp/normalization.ts
-function normalizeNameForMCP(name) {
- let normalized = name.replace(/[^a-zA-Z0-9_-]/g, "_");
- if (name.startsWith(CLAUDEAI_SERVER_PREFIX)) {
- normalized = normalized.replace(/_+/g, "_").replace(/^_|_$/g, "");
- }
- return normalized;
-}
-var CLAUDEAI_SERVER_PREFIX = "claude.ai ";
-
-// src/services/mcp/mcpStringUtils.ts
-function mcpInfoFromString(toolString) {
- const parts = toolString.split("__");
- const [mcpPart, serverName, ...toolNameParts] = parts;
- if (mcpPart !== "mcp" || !serverName) {
- return null;
- }
- const toolName = toolNameParts.length > 0 ? toolNameParts.join("__") : undefined;
- return { serverName, toolName };
-}
-function getMcpPrefix(serverName) {
- return `mcp__${normalizeNameForMCP(serverName)}__`;
-}
-function buildMcpToolName(serverName, toolName) {
- return `${getMcpPrefix(serverName)}${normalizeNameForMCP(toolName)}`;
-}
-function getToolNameForPermissionCheck(tool) {
- return tool.mcpInfo ? buildMcpToolName(tool.mcpInfo.serverName, tool.mcpInfo.toolName) : tool.name;
-}
-function getMcpDisplayName(fullName, serverName) {
- const prefix = `mcp__${normalizeNameForMCP(serverName)}__`;
- return fullName.replace(prefix, "");
-}
-function extractMcpToolDisplayName(userFacingName) {
- let withoutSuffix = userFacingName.replace(/\s*\(MCP\)\s*$/, "");
- withoutSuffix = withoutSuffix.trim();
- const dashIndex = withoutSuffix.indexOf(" - ");
- if (dashIndex !== -1) {
- const displayName = withoutSuffix.substring(dashIndex + 3).trim();
- return displayName;
- }
- return withoutSuffix;
-}
-var init_mcpStringUtils = () => {};
-
-// src/tools/AgentTool/constants.ts
-var AGENT_TOOL_NAME = "Agent", LEGACY_AGENT_TOOL_NAME = "Task", VERIFICATION_AGENT_TYPE = "verification", ONE_SHOT_BUILTIN_AGENT_TYPES;
-var init_constants3 = __esm(() => {
- ONE_SHOT_BUILTIN_AGENT_TYPES = new Set([
- "Explore",
- "Plan"
- ]);
-});
-
-// src/tools/TaskOutputTool/constants.ts
-var TASK_OUTPUT_TOOL_NAME = "TaskOutput";
-
-// src/tools/TaskStopTool/prompt.ts
-var TASK_STOP_TOOL_NAME = "TaskStop", DESCRIPTION = `
-- Stops a running background task by its ID
-- Takes a task_id parameter identifying the task to stop
-- Returns a success or failure status
-- Use this tool when you need to terminate a long-running task
-`;
-
-// src/utils/permissions/permissionRuleParser.ts
-function normalizeLegacyToolName(name) {
- return LEGACY_TOOL_NAME_ALIASES[name] ?? name;
-}
-function getLegacyToolNames(canonicalName) {
- const result = [];
- for (const [legacy, canonical] of Object.entries(LEGACY_TOOL_NAME_ALIASES)) {
- if (canonical === canonicalName)
- result.push(legacy);
- }
- return result;
-}
-function escapeRuleContent(content) {
- return content.replace(/\\/g, "\\\\").replace(/\(/g, "\\(").replace(/\)/g, "\\)");
-}
-function unescapeRuleContent(content) {
- return content.replace(/\\\(/g, "(").replace(/\\\)/g, ")").replace(/\\\\/g, "\\");
-}
-function permissionRuleValueFromString(ruleString) {
- const openParenIndex = findFirstUnescapedChar(ruleString, "(");
- if (openParenIndex === -1) {
- return { toolName: normalizeLegacyToolName(ruleString) };
- }
- const closeParenIndex = findLastUnescapedChar(ruleString, ")");
- if (closeParenIndex === -1 || closeParenIndex <= openParenIndex) {
- return { toolName: normalizeLegacyToolName(ruleString) };
- }
- if (closeParenIndex !== ruleString.length - 1) {
- return { toolName: normalizeLegacyToolName(ruleString) };
- }
- const toolName = ruleString.substring(0, openParenIndex);
- const rawContent = ruleString.substring(openParenIndex + 1, closeParenIndex);
- if (!toolName) {
- return { toolName: normalizeLegacyToolName(ruleString) };
- }
- if (rawContent === "" || rawContent === "*") {
- return { toolName: normalizeLegacyToolName(toolName) };
- }
- const ruleContent = unescapeRuleContent(rawContent);
- return { toolName: normalizeLegacyToolName(toolName), ruleContent };
-}
-function permissionRuleValueToString(ruleValue) {
- if (!ruleValue.ruleContent) {
- return ruleValue.toolName;
- }
- const escapedContent = escapeRuleContent(ruleValue.ruleContent);
- return `${ruleValue.toolName}(${escapedContent})`;
-}
-function findFirstUnescapedChar(str, char) {
- for (let i2 = 0;i2 < str.length; i2++) {
- if (str[i2] === char) {
- let backslashCount = 0;
- let j = i2 - 1;
- while (j >= 0 && str[j] === "\\") {
- backslashCount++;
- j--;
- }
- if (backslashCount % 2 === 0) {
- return i2;
- }
- }
- }
- return -1;
-}
-function findLastUnescapedChar(str, char) {
- for (let i2 = str.length - 1;i2 >= 0; i2--) {
- if (str[i2] === char) {
- let backslashCount = 0;
- let j = i2 - 1;
- while (j >= 0 && str[j] === "\\") {
- backslashCount++;
- j--;
- }
- if (backslashCount % 2 === 0) {
- return i2;
- }
- }
- }
- return -1;
-}
-var LEGACY_TOOL_NAME_ALIASES;
-var init_permissionRuleParser = __esm(() => {
- init_constants3();
- LEGACY_TOOL_NAME_ALIASES = {
- Task: AGENT_TOOL_NAME,
- KillShell: TASK_STOP_TOOL_NAME,
- AgentOutputTool: TASK_OUTPUT_TOOL_NAME,
- BashOutputTool: TASK_OUTPUT_TOOL_NAME,
- ...{}
- };
-});
-
-// src/utils/stringUtils.ts
-function escapeRegExp(str) {
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-}
-function capitalize(str) {
- return str.charAt(0).toUpperCase() + str.slice(1);
-}
-function plural(n2, word, pluralWord = word + "s") {
- return n2 === 1 ? word : pluralWord;
-}
-function firstLineOf(s) {
- const nl = s.indexOf(`
-`);
- return nl === -1 ? s : s.slice(0, nl);
-}
-function countCharInString(str, char, start = 0) {
- let count3 = 0;
- let i2 = str.indexOf(char, start);
- while (i2 !== -1) {
- count3++;
- i2 = str.indexOf(char, i2 + 1);
- }
- return count3;
-}
-function normalizeFullWidthDigits(input) {
- return input.replace(/[\uFF10-\uFF19]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) - 65248));
-}
-function normalizeFullWidthSpace(input) {
- return input.replace(/\u3000/g, " ");
-}
-function safeJoinLines(lines, delimiter = ",", maxSize = MAX_STRING_LENGTH) {
- const truncationMarker = "...[truncated]";
- let result = "";
- for (const line of lines) {
- const delimiterToAdd = result ? delimiter : "";
- const fullAddition = delimiterToAdd + line;
- if (result.length + fullAddition.length <= maxSize) {
- result += fullAddition;
- } else {
- const remainingSpace = maxSize - result.length - delimiterToAdd.length - truncationMarker.length;
- if (remainingSpace > 0) {
- result += delimiterToAdd + line.slice(0, remainingSpace) + truncationMarker;
- } else {
- result += truncationMarker;
- }
- return result;
- }
- }
- return result;
-}
-
-class EndTruncatingAccumulator {
- maxSize;
- content = "";
- isTruncated = false;
- totalBytesReceived = 0;
- constructor(maxSize = MAX_STRING_LENGTH) {
- this.maxSize = maxSize;
- }
- append(data) {
- const str = typeof data === "string" ? data : data.toString();
- this.totalBytesReceived += str.length;
- if (this.isTruncated && this.content.length >= this.maxSize) {
- return;
- }
- if (this.content.length + str.length > this.maxSize) {
- const remainingSpace = this.maxSize - this.content.length;
- if (remainingSpace > 0) {
- this.content += str.slice(0, remainingSpace);
- }
- this.isTruncated = true;
- } else {
- this.content += str;
- }
- }
- toString() {
- if (!this.isTruncated) {
- return this.content;
- }
- const truncatedBytes = this.totalBytesReceived - this.maxSize;
- const truncatedKB = Math.round(truncatedBytes / 1024);
- return this.content + `
-... [output truncated - ${truncatedKB}KB removed]`;
- }
- clear() {
- this.content = "";
- this.isTruncated = false;
- this.totalBytesReceived = 0;
- }
- get length() {
- return this.content.length;
- }
- get truncated() {
- return this.isTruncated;
- }
- get totalBytes() {
- return this.totalBytesReceived;
- }
-}
-function truncateToLines(text, maxLines) {
- const lines = text.split(`
-`);
- if (lines.length <= maxLines) {
- return text;
- }
- return lines.slice(0, maxLines).join(`
-`) + "\u2026";
-}
-var MAX_STRING_LENGTH;
-var init_stringUtils = __esm(() => {
- MAX_STRING_LENGTH = 2 ** 25;
-});
-
-// src/utils/settings/toolValidationConfig.ts
-function isFilePatternTool(toolName) {
- return TOOL_VALIDATION_CONFIG.filePatternTools.includes(toolName);
-}
-function isBashPrefixTool(toolName) {
- return TOOL_VALIDATION_CONFIG.bashPrefixTools.includes(toolName);
-}
-function getCustomValidation(toolName) {
- return TOOL_VALIDATION_CONFIG.customValidation[toolName];
-}
-var TOOL_VALIDATION_CONFIG;
-var init_toolValidationConfig = __esm(() => {
- TOOL_VALIDATION_CONFIG = {
- filePatternTools: [
- "Read",
- "Write",
- "Edit",
- "Glob",
- "NotebookRead",
- "NotebookEdit"
- ],
- bashPrefixTools: ["Bash"],
- customValidation: {
- WebSearch: (content) => {
- if (content.includes("*") || content.includes("?")) {
- return {
- valid: false,
- error: "WebSearch does not support wildcards",
- suggestion: "Use exact search terms without * or ?",
- examples: ["WebSearch(claude ai)", "WebSearch(typescript tutorial)"]
- };
- }
- return { valid: true };
- },
- WebFetch: (content) => {
- if (content.includes("://") || content.startsWith("http")) {
- return {
- valid: false,
- error: "WebFetch permissions use domain format, not URLs",
- suggestion: 'Use "domain:hostname" format',
- examples: [
- "WebFetch(domain:example.com)",
- "WebFetch(domain:github.com)"
- ]
- };
- }
- if (!content.startsWith("domain:")) {
- return {
- valid: false,
- error: 'WebFetch permissions must use "domain:" prefix',
- suggestion: 'Use "domain:hostname" format',
- examples: [
- "WebFetch(domain:example.com)",
- "WebFetch(domain:*.google.com)"
- ]
- };
- }
- return { valid: true };
- }
- }
- };
-});
-
-// src/utils/settings/permissionValidation.ts
-function isEscaped(str, index2) {
- let backslashCount = 0;
- let j = index2 - 1;
- while (j >= 0 && str[j] === "\\") {
- backslashCount++;
- j--;
- }
- return backslashCount % 2 !== 0;
-}
-function countUnescapedChar(str, char) {
- let count3 = 0;
- for (let i2 = 0;i2 < str.length; i2++) {
- if (str[i2] === char && !isEscaped(str, i2)) {
- count3++;
- }
- }
- return count3;
-}
-function hasUnescapedEmptyParens(str) {
- for (let i2 = 0;i2 < str.length - 1; i2++) {
- if (str[i2] === "(" && str[i2 + 1] === ")") {
- if (!isEscaped(str, i2)) {
- return true;
- }
- }
- }
- return false;
-}
-function validatePermissionRule(rule) {
- if (!rule || rule.trim() === "") {
- return { valid: false, error: "Permission rule cannot be empty" };
- }
- const openCount = countUnescapedChar(rule, "(");
- const closeCount = countUnescapedChar(rule, ")");
- if (openCount !== closeCount) {
- return {
- valid: false,
- error: "Mismatched parentheses",
- suggestion: "Ensure all opening parentheses have matching closing parentheses"
- };
- }
- if (hasUnescapedEmptyParens(rule)) {
- const toolName = rule.substring(0, rule.indexOf("("));
- if (!toolName) {
- return {
- valid: false,
- error: "Empty parentheses with no tool name",
- suggestion: "Specify a tool name before the parentheses"
- };
- }
- return {
- valid: false,
- error: "Empty parentheses",
- suggestion: `Either specify a pattern or use just "${toolName}" without parentheses`,
- examples: [`${toolName}`, `${toolName}(some-pattern)`]
- };
- }
- const parsed = permissionRuleValueFromString(rule);
- const mcpInfo = mcpInfoFromString(parsed.toolName);
- if (mcpInfo) {
- if (parsed.ruleContent !== undefined || countUnescapedChar(rule, "(") > 0) {
- return {
- valid: false,
- error: "MCP rules do not support patterns in parentheses",
- suggestion: `Use "${parsed.toolName}" without parentheses, or use "mcp__${mcpInfo.serverName}__*" for all tools`,
- examples: [
- `mcp__${mcpInfo.serverName}`,
- `mcp__${mcpInfo.serverName}__*`,
- mcpInfo.toolName && mcpInfo.toolName !== "*" ? `mcp__${mcpInfo.serverName}__${mcpInfo.toolName}` : undefined
- ].filter(Boolean)
- };
- }
- return { valid: true };
- }
- if (!parsed.toolName || parsed.toolName.length === 0) {
- return { valid: false, error: "Tool name cannot be empty" };
- }
- if (parsed.toolName[0] !== parsed.toolName[0]?.toUpperCase()) {
- return {
- valid: false,
- error: "Tool names must start with uppercase",
- suggestion: `Use "${capitalize(String(parsed.toolName))}"`
- };
- }
- const customValidation = getCustomValidation(parsed.toolName);
- if (customValidation && parsed.ruleContent !== undefined) {
- const customResult = customValidation(parsed.ruleContent);
- if (!customResult.valid) {
- return customResult;
- }
- }
- if (isBashPrefixTool(parsed.toolName) && parsed.ruleContent !== undefined) {
- const content = parsed.ruleContent;
- if (content.includes(":*") && !content.endsWith(":*")) {
- return {
- valid: false,
- error: "The :* pattern must be at the end",
- suggestion: "Move :* to the end for prefix matching, or use * for wildcard matching",
- examples: [
- "Bash(npm run:*) - prefix matching (legacy)",
- "Bash(npm run *) - wildcard matching"
- ]
- };
- }
- if (content === ":*") {
- return {
- valid: false,
- error: "Prefix cannot be empty before :*",
- suggestion: "Specify a command prefix before :*",
- examples: ["Bash(npm:*)", "Bash(git:*)"]
- };
- }
- }
- if (isFilePatternTool(parsed.toolName) && parsed.ruleContent !== undefined) {
- const content = parsed.ruleContent;
- if (content.includes(":*")) {
- return {
- valid: false,
- error: 'The ":*" syntax is only for Bash prefix rules',
- suggestion: 'Use glob patterns like "*" or "**" for file matching',
- examples: [
- `${parsed.toolName}(*.ts) - matches .ts files`,
- `${parsed.toolName}(src/**) - matches all files in src`,
- `${parsed.toolName}(**/*.test.ts) - matches test files`
- ]
- };
- }
- if (content.includes("*") && !content.match(/^\*|\*$|\*\*|\/\*|\*\.|\*\)/) && !content.includes("**")) {
- return {
- valid: false,
- error: "Wildcard placement might be incorrect",
- suggestion: "Wildcards are typically used at path boundaries",
- examples: [
- `${parsed.toolName}(*.js) - all .js files`,
- `${parsed.toolName}(src/*) - all files directly in src`,
- `${parsed.toolName}(src/**) - all files recursively in src`
- ]
- };
- }
- }
- return { valid: true };
-}
-var PermissionRuleSchema;
-var init_permissionValidation = __esm(() => {
- init_v4();
- init_mcpStringUtils();
- init_permissionRuleParser();
- init_stringUtils();
- init_toolValidationConfig();
- PermissionRuleSchema = lazySchema(() => exports_external.string().superRefine((val, ctx) => {
- const result = validatePermissionRule(val);
- if (!result.valid) {
- let message = result.error;
- if (result.suggestion) {
- message += `. ${result.suggestion}`;
- }
- if (result.examples && result.examples.length > 0) {
- message += `. Examples: ${result.examples.join(", ")}`;
- }
- ctx.addIssue({
- code: exports_external.ZodIssueCode.custom,
- message,
- params: { received: val }
- });
- }
- }));
-});
-
-// src/utils/settings/types.ts
-function isMcpServerNameEntry(entry) {
- return "serverName" in entry && entry.serverName !== undefined;
-}
-function isMcpServerCommandEntry(entry) {
- return "serverCommand" in entry && entry.serverCommand !== undefined;
-}
-function isMcpServerUrlEntry(entry) {
- return "serverUrl" in entry && entry.serverUrl !== undefined;
-}
-var EnvironmentVariablesSchema, PermissionsSchema, ExtraKnownMarketplaceSchema, AllowedMcpServerEntrySchema, DeniedMcpServerEntrySchema, CUSTOMIZATION_SURFACES, SettingsSchema;
-var init_types2 = __esm(() => {
- init_v4();
- init_sandboxTypes();
- init_envUtils();
- init_PermissionMode();
- init_schemas3();
- init_constants2();
- init_permissionValidation();
- init_hooks();
- init_hooks();
- EnvironmentVariablesSchema = lazySchema(() => exports_external.record(exports_external.string(), exports_external.coerce.string()));
- PermissionsSchema = lazySchema(() => exports_external.object({
- allow: exports_external.array(PermissionRuleSchema()).optional().describe("List of permission rules for allowed operations"),
- deny: exports_external.array(PermissionRuleSchema()).optional().describe("List of permission rules for denied operations"),
- ask: exports_external.array(PermissionRuleSchema()).optional().describe("List of permission rules that should always prompt for confirmation"),
- defaultMode: exports_external.enum(EXTERNAL_PERMISSION_MODES).optional().describe("Default permission mode when Claude Code needs access"),
- disableBypassPermissionsMode: exports_external.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),
- ...{},
- additionalDirectories: exports_external.array(exports_external.string()).optional().describe("Additional directories to include in the permission scope")
- }).passthrough());
- ExtraKnownMarketplaceSchema = lazySchema(() => exports_external.object({
- source: MarketplaceSourceSchema().describe("Where to fetch the marketplace from"),
- installLocation: exports_external.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),
- autoUpdate: exports_external.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")
- }));
- AllowedMcpServerEntrySchema = lazySchema(() => exports_external.object({
- serverName: exports_external.string().regex(/^[a-zA-Z0-9_-]+$/, "Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),
- serverCommand: exports_external.array(exports_external.string()).min(1, "Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),
- serverUrl: exports_external.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')
- }).refine((data) => {
- const defined = count2([
- data.serverName !== undefined,
- data.serverCommand !== undefined,
- data.serverUrl !== undefined
- ], Boolean);
- return defined === 1;
- }, {
- message: 'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'
- }));
- DeniedMcpServerEntrySchema = lazySchema(() => exports_external.object({
- serverName: exports_external.string().regex(/^[a-zA-Z0-9_-]+$/, "Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that is explicitly blocked"),
- serverCommand: exports_external.array(exports_external.string()).min(1, "Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),
- serverUrl: exports_external.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')
- }).refine((data) => {
- const defined = count2([
- data.serverName !== undefined,
- data.serverCommand !== undefined,
- data.serverUrl !== undefined
- ], Boolean);
- return defined === 1;
- }, {
- message: 'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'
- }));
- CUSTOMIZATION_SURFACES = [
- "skills",
- "agents",
- "hooks",
- "mcp"
- ];
- SettingsSchema = lazySchema(() => exports_external.object({
- $schema: exports_external.literal(CLAUDE_CODE_SETTINGS_SCHEMA_URL).optional().describe("JSON Schema reference for Claude Code settings"),
- apiKeyHelper: exports_external.string().optional().describe("Path to a script that outputs authentication values"),
- awsCredentialExport: exports_external.string().optional().describe("Path to a script that exports AWS credentials"),
- awsAuthRefresh: exports_external.string().optional().describe("Path to a script that refreshes AWS authentication"),
- gcpAuthRefresh: exports_external.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),
- ...isEnvTruthy(process.env.CLAUDE_CODE_ENABLE_XAA) ? {
- xaaIdp: exports_external.object({
- issuer: exports_external.string().url().describe("IdP issuer URL for OIDC discovery"),
- clientId: exports_external.string().describe("Claude Code's client_id registered at the IdP"),
- callbackPort: exports_external.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. " + "Only needed if the IdP does not honor RFC 8252 port-any matching.")
- }).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")
- } : {},
- fileSuggestion: exports_external.object({
- type: exports_external.literal("command"),
- command: exports_external.string()
- }).optional().describe("Custom file suggestion configuration for @ mentions"),
- respectGitignore: exports_external.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). " + "Note: .ignore files are always respected."),
- cleanupPeriodDays: exports_external.number().nonnegative().int().optional().describe("Number of days to retain chat transcripts (default: 30). Setting to 0 disables session persistence entirely: no transcripts are written and existing transcripts are deleted at startup."),
- env: EnvironmentVariablesSchema().optional().describe("Environment variables to set for Claude Code sessions"),
- attribution: exports_external.object({
- commit: exports_external.string().optional().describe("Attribution text for git commits, including any trailers. " + "Empty string hides attribution."),
- pr: exports_external.string().optional().describe("Attribution text for pull request descriptions. " + "Empty string hides attribution.")
- }).optional().describe("Customize attribution text for commits and PRs. " + "Each field defaults to the standard Claude Code attribution if not set."),
- includeCoAuthoredBy: exports_external.boolean().optional().describe("Deprecated: Use attribution instead. " + "Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),
- includeGitInstructions: exports_external.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),
- permissions: PermissionsSchema().optional().describe("Tool usage permissions configuration"),
- model: exports_external.string().optional().describe("Override the default model used by Claude Code"),
- availableModels: exports_external.array(exports_external.string()).optional().describe("Allowlist of models that users can select. " + 'Accepts family aliases ("opus" allows any opus version), ' + 'version prefixes ("opus-4-5" allows only that version), ' + "and full model IDs. " + "If undefined, all models are available. If empty array, only the default model is available. " + "Typically set in managed settings by enterprise administrators."),
- modelOverrides: exports_external.record(exports_external.string(), exports_external.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific ' + "model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by " + "enterprise administrators."),
- enableAllProjectMcpServers: exports_external.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),
- enabledMcpjsonServers: exports_external.array(exports_external.string()).optional().describe("List of approved MCP servers from .mcp.json"),
- disabledMcpjsonServers: exports_external.array(exports_external.string()).optional().describe("List of rejected MCP servers from .mcp.json"),
- allowedMcpServers: exports_external.array(AllowedMcpServerEntrySchema()).optional().describe("Enterprise allowlist of MCP servers that can be used. " + "Applies to all scopes including enterprise servers from managed-mcp.json. " + "If undefined, all servers are allowed. If empty array, no servers are allowed. " + "Denylist takes precedence - if a server is on both lists, it is denied."),
- deniedMcpServers: exports_external.array(DeniedMcpServerEntrySchema()).optional().describe("Enterprise denylist of MCP servers that are explicitly blocked. " + "If a server is on the denylist, it will be blocked across all scopes including enterprise. " + "Denylist takes precedence over allowlist - if a server is on both lists, it is denied."),
- hooks: HooksSchema().optional().describe("Custom commands to run before/after tool executions"),
- worktree: exports_external.object({
- symlinkDirectories: exports_external.array(exports_external.string()).optional().describe("Directories to symlink from main repository to worktrees to avoid disk bloat. " + "Must be explicitly configured - no directories are symlinked by default. " + 'Common examples: "node_modules", ".cache", ".bin"'),
- sparsePaths: exports_external.array(exports_external.string()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). " + "Dramatically faster in large monorepos \u2014 only the listed paths are written to disk.")
- }).optional().describe("Git worktree configuration for --worktree flag."),
- disableAllHooks: exports_external.boolean().optional().describe("Disable all hooks and statusLine execution"),
- defaultShell: exports_external.enum(["bash", "powershell"]).optional().describe("Default shell for input-box ! commands. " + "Defaults to 'bash' on all platforms (no Windows auto-flip)."),
- allowManagedHooksOnly: exports_external.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. " + "User, project, and local hooks are ignored."),
- allowedHttpHookUrls: exports_external.array(exports_external.string()).optional().describe("Allowlist of URL patterns that HTTP hooks may target. " + 'Supports * as a wildcard (e.g. "https://hooks.example.com/*"). ' + "When set, HTTP hooks with non-matching URLs are blocked. " + "If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. " + "Arrays merge across settings sources (same semantics as allowedMcpServers)."),
- httpHookAllowedEnvVars: exports_external.array(exports_external.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. " + "When set, each hook's effective allowedEnvVars is the intersection with this list. " + "If undefined, no restriction is applied. " + "Arrays merge across settings sources (same semantics as allowedMcpServers)."),
- allowManagedPermissionRulesOnly: exports_external.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. " + "User, project, local, and CLI argument permission rules are ignored."),
- allowManagedMcpServersOnly: exports_external.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. " + "deniedMcpServers still merges from all sources, so users can deny servers for themselves. " + "Users can still add their own MCP servers, but only the admin-defined allowlist applies."),
- strictPluginOnlyCustomization: exports_external.preprocess((v) => Array.isArray(v) ? v.filter((x2) => CUSTOMIZATION_SURFACES.includes(x2)) : v, exports_external.union([exports_external.boolean(), exports_external.array(exports_external.enum(CUSTOMIZATION_SURFACES))])).optional().catch(undefined).describe("When set in managed settings, blocks non-plugin customization sources for the listed surfaces. " + 'Array form locks specific surfaces (e.g. ["skills", "hooks"]); `true` locks all four; `false` is an explicit no-op. ' + "Blocked: ~/.claude/{surface}/, .claude/{surface}/ (project), settings.json hooks, .mcp.json. " + "NOT blocked: managed (policySettings) sources, plugin-provided customizations. " + "Composes with strictKnownMarketplaces for end-to-end admin control \u2014 plugins gated by " + "marketplace allowlist, everything else blocked here."),
- statusLine: exports_external.object({
- type: exports_external.literal("command"),
- command: exports_external.string(),
- padding: exports_external.number().optional()
- }).optional().describe("Custom status line display configuration"),
- enabledPlugins: exports_external.record(exports_external.string(), exports_external.union([exports_external.array(exports_external.string()), exports_external.boolean(), exports_external.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints.'),
- extraKnownMarketplaces: exports_external.record(exports_external.string(), ExtraKnownMarketplaceSchema()).check((ctx) => {
- for (const [key, entry] of Object.entries(ctx.value)) {
- if (entry.source.source === "settings" && entry.source.name !== key) {
- ctx.issues.push({
- code: "custom",
- input: entry.source.name,
- path: [key, "source", "name"],
- message: `Settings-sourced marketplace name must match its extraKnownMarketplaces key ` + `(got key "${key}" but source.name "${entry.source.name}")`
- });
- }
- }
- }).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),
- strictKnownMarketplaces: exports_external.array(MarketplaceSourceSchema()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, " + "ONLY these exact sources can be added as marketplaces. The check happens BEFORE " + "downloading, so blocked sources never touch the filesystem. " + "Note: this is a policy gate only \u2014 it does NOT register marketplaces. " + "To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),
- blockedMarketplaces: exports_external.array(MarketplaceSourceSchema()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, " + "these exact sources are blocked from being added as marketplaces. The check happens BEFORE " + "downloading, so blocked sources never touch the filesystem."),
- forceLoginMethod: exports_external.enum(["claudeai", "console"]).optional().describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing'),
- forceLoginOrgUUID: exports_external.string().optional().describe("Organization UUID to use for OAuth login"),
- otelHeadersHelper: exports_external.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),
- outputStyle: exports_external.string().optional().describe("Controls the output style for assistant responses"),
- language: exports_external.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),
- skipWebFetchPreflight: exports_external.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),
- sandbox: SandboxSettingsSchema().optional(),
- feedbackSurveyRate: exports_external.number().min(0).max(1).optional().describe("Probability (0\u20131) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),
- spinnerTipsEnabled: exports_external.boolean().optional().describe("Whether to show tips in the spinner"),
- spinnerVerbs: exports_external.object({
- mode: exports_external.enum(["append", "replace"]),
- verbs: exports_external.array(exports_external.string())
- }).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),
- spinnerTipsOverride: exports_external.object({
- excludeDefault: exports_external.boolean().optional(),
- tips: exports_external.array(exports_external.string())
- }).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),
- syntaxHighlightingDisabled: exports_external.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),
- terminalTitleFromRename: exports_external.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),
- alwaysThinkingEnabled: exports_external.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is " + "enabled automatically for supported models."),
- effortLevel: exports_external.enum(process.env.USER_TYPE === "ant" ? ["low", "medium", "high", "max"] : ["low", "medium", "high"]).optional().catch(undefined).describe("Persisted effort level for supported models."),
- advisorModel: exports_external.string().optional().describe("Advisor model for the server-side advisor tool."),
- fastMode: exports_external.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),
- fastModePerSessionOptIn: exports_external.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),
- promptSuggestionEnabled: exports_external.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, " + "prompt suggestions are enabled."),
- showClearContextOnPlanAccept: exports_external.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),
- agent: exports_external.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. " + "Applies the agent's system prompt, tool restrictions, and model."),
- companyAnnouncements: exports_external.array(exports_external.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),
- pluginConfigs: exports_external.record(exports_external.string(), exports_external.object({
- mcpServers: exports_external.record(exports_external.string(), exports_external.record(exports_external.string(), exports_external.union([
- exports_external.string(),
- exports_external.number(),
- exports_external.boolean(),
- exports_external.array(exports_external.string())
- ]))).optional().describe("User configuration values for MCP servers keyed by server name"),
- options: exports_external.record(exports_external.string(), exports_external.union([
- exports_external.string(),
- exports_external.number(),
- exports_external.boolean(),
- exports_external.array(exports_external.string())
- ])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")
- })).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),
- remote: exports_external.object({
- defaultEnvironmentId: exports_external.string().optional().describe("Default environment ID to use for remote sessions")
- }).optional().describe("Remote session configuration"),
- autoUpdatesChannel: exports_external.enum(["latest", "stable"]).optional().describe("Release channel for auto-updates (latest or stable)"),
- ...{},
- minimumVersion: exports_external.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),
- plansDirectory: exports_external.string().optional().describe("Custom directory for plan files, relative to project root. " + "If not set, defaults to ~/.claude/plans/"),
- ...process.env.USER_TYPE === "ant" ? {
- classifierPermissionsEnabled: exports_external.boolean().optional().describe("Enable AI-based classification for Bash(prompt:...) permission rules")
- } : {},
- ...{},
- ...{},
- ...{},
- channelsEnabled: exports_external.boolean().optional().describe("Teams/Enterprise opt-in for channel notifications (MCP servers with the " + "claude/channel capability pushing inbound messages). Default off. " + "Set true to allow; users then select servers via --channels."),
- allowedChannelPlugins: exports_external.array(exports_external.object({
- marketplace: exports_external.string(),
- plugin: exports_external.string()
- })).optional().describe("Teams/Enterprise allowlist of channel plugins. When set, " + "replaces the default Anthropic allowlist \u2014 admins decide which " + "plugins may push inbound messages. Undefined falls back to the default. " + "Requires channelsEnabled: true."),
- ...{},
- prefersReducedMotion: exports_external.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),
- autoMemoryEnabled: exports_external.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),
- autoMemoryDirectory: exports_external.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .claude/settings.json) for security. When unset, defaults to ~/.claude/projects//memory/."),
- autoDreamEnabled: exports_external.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),
- showThinkingSummaries: exports_external.boolean().optional().describe("Show thinking summaries in the transcript view (ctrl+o). Default: false."),
- skipDangerousModePermissionPrompt: exports_external.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),
- ...{},
- disableAutoMode: exports_external.enum(["disable"]).optional().describe("Disable auto mode"),
- sshConfigs: exports_external.array(exports_external.object({
- id: exports_external.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),
- name: exports_external.string().describe("Display name for the SSH connection"),
- sshHost: exports_external.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),
- sshPort: exports_external.number().int().optional().describe("SSH port (default: 22)"),
- sshIdentityFile: exports_external.string().optional().describe("Path to SSH identity file (private key)"),
- startDirectory: exports_external.string().optional().describe("Default working directory on the remote host. " + "Supports tilde expansion (e.g. ~/projects). " + "If not specified, defaults to the remote user home directory. " + "Can be overridden by the [dir] positional argument in `claude ssh [dir]`.")
- })).optional().describe("SSH connection configurations for remote environments. " + "Typically set in managed settings by enterprise administrators " + "to pre-configure SSH connections for team members."),
- claudeMdExcludes: exports_external.array(exports_external.string()).optional().describe("Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. " + "Patterns are matched against absolute file paths using picomatch. " + "Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). " + 'Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),
- pluginTrustMessage: exports_external.string().optional().describe("Custom message to append to the plugin trust warning shown before installation. " + "Only read from policy settings (managed-settings.json / MDM). " + "Useful for enterprise administrators to add organization-specific context " + '(e.g., "All plugins from our internal marketplace are vetted and approved.").')
- }).passthrough());
-});
-
-// src/utils/settings/schemaOutput.ts
-function generateSettingsJSONSchema() {
- const jsonSchema = toJSONSchema(SettingsSchema(), { unrepresentable: "any" });
- return jsonStringify(jsonSchema, null, 2);
-}
-var init_schemaOutput = __esm(() => {
- init_v4();
- init_slowOperations();
- init_types2();
-});
-
-// src/utils/settings/validationTips.ts
-function getValidationTip(context) {
- const matcher = TIP_MATCHERS.find((m) => m.matches(context));
- if (!matcher)
- return null;
- const tip = { ...matcher.tip };
- if (context.code === "invalid_value" && context.enumValues && !tip.suggestion) {
- tip.suggestion = `Valid values: ${context.enumValues.map((v) => `"${v}"`).join(", ")}`;
- }
- if (!tip.docLink && context.path) {
- const pathPrefix = context.path.split(".")[0];
- if (pathPrefix) {
- tip.docLink = PATH_DOC_LINKS[pathPrefix];
- }
- }
- return tip;
-}
-var DOCUMENTATION_BASE = "https://code.claude.com/docs/en", TIP_MATCHERS, PATH_DOC_LINKS;
-var init_validationTips = __esm(() => {
- TIP_MATCHERS = [
- {
- matches: (ctx) => ctx.path === "permissions.defaultMode" && ctx.code === "invalid_value",
- tip: {
- suggestion: 'Valid modes: "acceptEdits" (ask before file changes), "plan" (analysis only), "bypassPermissions" (auto-accept all), or "default" (standard behavior)',
- docLink: `${DOCUMENTATION_BASE}/iam#permission-modes`
- }
- },
- {
- matches: (ctx) => ctx.path === "apiKeyHelper" && ctx.code === "invalid_type",
- tip: {
- suggestion: 'Provide a shell command that outputs your API key to stdout. The script should output only the API key. Example: "/bin/generate_temp_api_key.sh"'
- }
- },
- {
- matches: (ctx) => ctx.path === "cleanupPeriodDays" && ctx.code === "too_small" && ctx.expected === "0",
- tip: {
- suggestion: "Must be 0 or greater. Set a positive number for days to retain transcripts (default is 30). Setting 0 disables session persistence entirely: no transcripts are written and existing transcripts are deleted at startup."
- }
- },
- {
- matches: (ctx) => ctx.path.startsWith("env.") && ctx.code === "invalid_type",
- tip: {
- suggestion: 'Environment variables must be strings. Wrap numbers and booleans in quotes. Example: "DEBUG": "true", "PORT": "3000"',
- docLink: `${DOCUMENTATION_BASE}/settings#environment-variables`
- }
- },
- {
- matches: (ctx) => (ctx.path === "permissions.allow" || ctx.path === "permissions.deny") && ctx.code === "invalid_type" && ctx.expected === "array",
- tip: {
- suggestion: 'Permission rules must be in an array. Format: ["Tool(specifier)"]. Examples: ["Bash(npm run build)", "Edit(docs/**)", "Read(~/.zshrc)"]. Use * for wildcards.'
- }
- },
- {
- matches: (ctx) => ctx.path.includes("hooks") && ctx.code === "invalid_type",
- tip: {
- suggestion: 'Hooks use a matcher + hooks array. The matcher is a string: a tool name ("Bash"), pipe-separated list ("Edit|Write"), or empty to match all. Example: {"PostToolUse": [{"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "echo Done"}]}]}'
- }
- },
- {
- matches: (ctx) => ctx.code === "invalid_type" && ctx.expected === "boolean",
- tip: {
- suggestion: 'Use true or false without quotes. Example: "includeCoAuthoredBy": true'
- }
- },
- {
- matches: (ctx) => ctx.code === "unrecognized_keys",
- tip: {
- suggestion: "Check for typos or refer to the documentation for valid fields",
- docLink: `${DOCUMENTATION_BASE}/settings`
- }
- },
- {
- matches: (ctx) => ctx.code === "invalid_value" && ctx.enumValues !== undefined,
- tip: {
- suggestion: undefined
- }
- },
- {
- matches: (ctx) => ctx.code === "invalid_type" && ctx.expected === "object" && ctx.received === null && ctx.path === "",
- tip: {
- suggestion: "Check for missing commas, unmatched brackets, or trailing commas. Use a JSON validator to identify the exact syntax error."
- }
- },
- {
- matches: (ctx) => ctx.path === "permissions.additionalDirectories" && ctx.code === "invalid_type",
- tip: {
- suggestion: 'Must be an array of directory paths. Example: ["~/projects", "/tmp/workspace"]. You can also use --add-dir flag or /add-dir command',
- docLink: `${DOCUMENTATION_BASE}/iam#working-directories`
- }
- }
- ];
- PATH_DOC_LINKS = {
- permissions: `${DOCUMENTATION_BASE}/iam#configuring-permissions`,
- env: `${DOCUMENTATION_BASE}/settings#environment-variables`,
- hooks: `${DOCUMENTATION_BASE}/hooks`
- };
-});
-
-// src/utils/settings/validation.ts
-function isInvalidTypeIssue(issue2) {
- return issue2.code === "invalid_type";
-}
-function isInvalidValueIssue(issue2) {
- return issue2.code === "invalid_value";
-}
-function isUnrecognizedKeysIssue(issue2) {
- return issue2.code === "unrecognized_keys";
-}
-function isTooSmallIssue(issue2) {
- return issue2.code === "too_small";
-}
-function getReceivedType(value) {
- if (value === null)
- return "null";
- if (value === undefined)
- return "undefined";
- if (Array.isArray(value))
- return "array";
- return typeof value;
-}
-function extractReceivedFromMessage(msg) {
- const match = msg.match(/received (\w+)/);
- return match ? match[1] : undefined;
-}
-function formatZodError(error40, filePath) {
- return error40.issues.map((issue2) => {
- const path8 = issue2.path.map(String).join(".");
- let message = issue2.message;
- let expected;
- let enumValues;
- let expectedValue;
- let receivedValue;
- let invalidValue;
- if (isInvalidValueIssue(issue2)) {
- enumValues = issue2.values.map((v) => String(v));
- expectedValue = enumValues.join(" | ");
- receivedValue = undefined;
- invalidValue = undefined;
- } else if (isInvalidTypeIssue(issue2)) {
- expectedValue = issue2.expected;
- const receivedType = extractReceivedFromMessage(issue2.message);
- receivedValue = receivedType ?? getReceivedType(issue2.input);
- invalidValue = receivedType ?? getReceivedType(issue2.input);
- } else if (isTooSmallIssue(issue2)) {
- expectedValue = String(issue2.minimum);
- } else if (issue2.code === "custom" && "params" in issue2) {
- const params = issue2.params;
- receivedValue = params.received;
- invalidValue = receivedValue;
- }
- const tip = getValidationTip({
- path: path8,
- code: issue2.code,
- expected: expectedValue,
- received: receivedValue,
- enumValues,
- message: issue2.message,
- value: receivedValue
- });
- if (isInvalidValueIssue(issue2)) {
- expected = enumValues?.map((v) => `"${v}"`).join(", ");
- message = `Invalid value. Expected one of: ${expected}`;
- } else if (isInvalidTypeIssue(issue2)) {
- const receivedType = extractReceivedFromMessage(issue2.message) ?? getReceivedType(issue2.input);
- if (issue2.expected === "object" && receivedType === "null" && path8 === "") {
- message = "Invalid or malformed JSON";
- } else {
- message = `Expected ${issue2.expected}, but received ${receivedType}`;
- }
- } else if (isUnrecognizedKeysIssue(issue2)) {
- const keys2 = issue2.keys.join(", ");
- message = `Unrecognized ${plural(issue2.keys.length, "field")}: ${keys2}`;
- } else if (isTooSmallIssue(issue2)) {
- message = `Number must be greater than or equal to ${issue2.minimum}`;
- expected = String(issue2.minimum);
- }
- return {
- file: filePath,
- path: path8,
- message,
- expected,
- invalidValue,
- suggestion: tip?.suggestion,
- docLink: tip?.docLink
- };
- });
-}
-function validateSettingsFileContent(content) {
- try {
- const jsonData = jsonParse(content);
- const result = SettingsSchema().strict().safeParse(jsonData);
- if (result.success) {
- return { isValid: true };
- }
- const errors3 = formatZodError(result.error, "settings");
- const errorMessage2 = `Settings validation failed:
-` + errors3.map((err) => `- ${err.path}: ${err.message}`).join(`
-`);
- return {
- isValid: false,
- error: errorMessage2,
- fullSchema: generateSettingsJSONSchema()
- };
- } catch (parseError) {
- return {
- isValid: false,
- error: `Invalid JSON: ${parseError instanceof Error ? parseError.message : "Unknown parsing error"}`,
- fullSchema: generateSettingsJSONSchema()
- };
- }
-}
-function filterInvalidPermissionRules(data, filePath) {
- if (!data || typeof data !== "object")
- return [];
- const obj = data;
- if (!obj.permissions || typeof obj.permissions !== "object")
- return [];
- const perms = obj.permissions;
- const warnings = [];
- for (const key of ["allow", "deny", "ask"]) {
- const rules = perms[key];
- if (!Array.isArray(rules))
- continue;
- perms[key] = rules.filter((rule) => {
- if (typeof rule !== "string") {
- warnings.push({
- file: filePath,
- path: `permissions.${key}`,
- message: `Non-string value in ${key} array was removed`,
- invalidValue: rule
- });
- return false;
- }
- const result = validatePermissionRule(rule);
- if (!result.valid) {
- let message = `Invalid permission rule "${rule}" was skipped`;
- if (result.error)
- message += `: ${result.error}`;
- if (result.suggestion)
- message += `. ${result.suggestion}`;
- warnings.push({
- file: filePath,
- path: `permissions.${key}`,
- message,
- invalidValue: rule
- });
- return false;
- }
- return true;
- });
- }
- return warnings;
-}
-var init_validation2 = __esm(() => {
- init_slowOperations();
- init_stringUtils();
- init_permissionValidation();
- init_schemaOutput();
- init_types2();
- init_validationTips();
-});
-
-// src/utils/settings/mdm/settings.ts
-import { join as join19 } from "path";
-function startMdmSettingsLoad() {
- if (mdmLoadPromise)
- return;
- mdmLoadPromise = (async () => {
- profileCheckpoint("mdm_load_start");
- const startTime = Date.now();
- const rawPromise = getMdmRawReadPromise() ?? fireRawRead();
- const { mdm, hkcu } = consumeRawReadResult(await rawPromise);
- mdmCache = mdm;
- hkcuCache = hkcu;
- profileCheckpoint("mdm_load_end");
- const duration3 = Date.now() - startTime;
- logForDebugging(`MDM settings load completed in ${duration3}ms`);
- if (Object.keys(mdm.settings).length > 0) {
- logForDebugging(`MDM settings found: ${Object.keys(mdm.settings).join(", ")}`);
- try {
- logForDiagnosticsNoPII("info", "mdm_settings_loaded", {
- duration_ms: duration3,
- key_count: Object.keys(mdm.settings).length,
- error_count: mdm.errors.length
- });
- } catch {}
- }
- })();
-}
-async function ensureMdmSettingsLoaded() {
- if (!mdmLoadPromise) {
- startMdmSettingsLoad();
- }
- await mdmLoadPromise;
-}
-function getMdmSettings() {
- return mdmCache ?? EMPTY_RESULT;
-}
-function getHkcuSettings() {
- return hkcuCache ?? EMPTY_RESULT;
-}
-function setMdmSettingsCache(mdm, hkcu) {
- mdmCache = mdm;
- hkcuCache = hkcu;
-}
-async function refreshMdmSettings() {
- const raw = await fireRawRead();
- return consumeRawReadResult(raw);
-}
-function parseCommandOutputAsSettings(stdout, sourcePath) {
- const data = safeParseJSON(stdout, false);
- if (!data || typeof data !== "object") {
- return { settings: {}, errors: [] };
- }
- const ruleWarnings = filterInvalidPermissionRules(data, sourcePath);
- const parseResult = SettingsSchema().safeParse(data);
- if (!parseResult.success) {
- const errors3 = formatZodError(parseResult.error, sourcePath);
- return { settings: {}, errors: [...ruleWarnings, ...errors3] };
- }
- return { settings: parseResult.data, errors: ruleWarnings };
-}
-function parseRegQueryStdout(stdout, valueName = "Settings") {
- const lines = stdout.split(/\r?\n/);
- const escaped = valueName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
- const re = new RegExp(`^\\s+${escaped}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`, "i");
- for (const line of lines) {
- const match = line.match(re);
- if (match && match[1]) {
- return match[1].trimEnd();
- }
- }
- return null;
-}
-function consumeRawReadResult(raw) {
- if (raw.plistStdouts && raw.plistStdouts.length > 0) {
- const { stdout, label } = raw.plistStdouts[0];
- const result = parseCommandOutputAsSettings(stdout, label);
- if (Object.keys(result.settings).length > 0) {
- return { mdm: result, hkcu: EMPTY_RESULT };
- }
- }
- if (raw.hklmStdout) {
- const jsonString = parseRegQueryStdout(raw.hklmStdout);
- if (jsonString) {
- const result = parseCommandOutputAsSettings(jsonString, `Registry: ${WINDOWS_REGISTRY_KEY_PATH_HKLM}\\${WINDOWS_REGISTRY_VALUE_NAME}`);
- if (Object.keys(result.settings).length > 0) {
- return { mdm: result, hkcu: EMPTY_RESULT };
- }
- }
- }
- if (hasManagedSettingsFile()) {
- return { mdm: EMPTY_RESULT, hkcu: EMPTY_RESULT };
- }
- if (raw.hkcuStdout) {
- const jsonString = parseRegQueryStdout(raw.hkcuStdout);
- if (jsonString) {
- const result = parseCommandOutputAsSettings(jsonString, `Registry: ${WINDOWS_REGISTRY_KEY_PATH_HKCU}\\${WINDOWS_REGISTRY_VALUE_NAME}`);
- return { mdm: EMPTY_RESULT, hkcu: result };
- }
- }
- return { mdm: EMPTY_RESULT, hkcu: EMPTY_RESULT };
-}
-function hasManagedSettingsFile() {
- try {
- const filePath = join19(getManagedFilePath(), "managed-settings.json");
- const content = readFileSync4(filePath);
- const data = safeParseJSON(content, false);
- if (data && typeof data === "object" && Object.keys(data).length > 0) {
- return true;
- }
- } catch {}
- try {
- const dropInDir = getManagedSettingsDropInDir();
- const entries = getFsImplementation().readdirSync(dropInDir);
- for (const d of entries) {
- if (!(d.isFile() || d.isSymbolicLink()) || !d.name.endsWith(".json") || d.name.startsWith(".")) {
- continue;
- }
- try {
- const content = readFileSync4(join19(dropInDir, d.name));
- const data = safeParseJSON(content, false);
- if (data && typeof data === "object" && Object.keys(data).length > 0) {
- return true;
- }
- } catch {}
- }
- } catch {}
- return false;
-}
-var EMPTY_RESULT, mdmCache = null, hkcuCache = null, mdmLoadPromise = null;
-var init_settings = __esm(() => {
- init_debug();
- init_diagLogs();
- init_fileRead();
- init_fsOperations();
- init_json();
- init_startupProfiler();
- init_managedPath();
- init_types2();
- init_validation2();
- init_constants();
- init_rawRead();
- EMPTY_RESULT = Object.freeze({ settings: {}, errors: [] });
-});
-
-// src/utils/settings/settings.ts
-import { dirname as dirname11, join as join20, resolve as resolve8 } from "path";
-function getManagedSettingsFilePath() {
- return join20(getManagedFilePath(), "managed-settings.json");
-}
-function loadManagedFileSettings() {
- const errors3 = [];
- let merged = {};
- let found = false;
- const { settings, errors: baseErrors } = parseSettingsFile(getManagedSettingsFilePath());
- errors3.push(...baseErrors);
- if (settings && Object.keys(settings).length > 0) {
- merged = mergeWith_default(merged, settings, settingsMergeCustomizer);
- found = true;
- }
- const dropInDir = getManagedSettingsDropInDir();
- try {
- const entries = getFsImplementation().readdirSync(dropInDir).filter((d) => (d.isFile() || d.isSymbolicLink()) && d.name.endsWith(".json") && !d.name.startsWith(".")).map((d) => d.name).sort();
- for (const name of entries) {
- const { settings: settings2, errors: fileErrors } = parseSettingsFile(join20(dropInDir, name));
- errors3.push(...fileErrors);
- if (settings2 && Object.keys(settings2).length > 0) {
- merged = mergeWith_default(merged, settings2, settingsMergeCustomizer);
- found = true;
- }
- }
- } catch (e) {
- const code = getErrnoCode(e);
- if (code !== "ENOENT" && code !== "ENOTDIR") {
- logError2(e);
- }
- }
- return { settings: found ? merged : null, errors: errors3 };
-}
-function getManagedFileSettingsPresence() {
- const { settings: base2 } = parseSettingsFile(getManagedSettingsFilePath());
- const hasBase = !!base2 && Object.keys(base2).length > 0;
- let hasDropIns = false;
- const dropInDir = getManagedSettingsDropInDir();
- try {
- hasDropIns = getFsImplementation().readdirSync(dropInDir).some((d) => (d.isFile() || d.isSymbolicLink()) && d.name.endsWith(".json") && !d.name.startsWith("."));
- } catch {}
- return { hasBase, hasDropIns };
-}
-function handleFileSystemError(error40, path8) {
- if (typeof error40 === "object" && error40 && "code" in error40 && error40.code === "ENOENT") {
- logForDebugging(`Broken symlink or missing file encountered for settings.json at path: ${path8}`);
- } else {
- logError2(error40);
- }
-}
-function parseSettingsFile(path8) {
- const cached2 = getCachedParsedFile(path8);
- if (cached2) {
- return {
- settings: cached2.settings ? clone(cached2.settings) : null,
- errors: cached2.errors
- };
- }
- const result = parseSettingsFileUncached(path8);
- setCachedParsedFile(path8, result);
- return {
- settings: result.settings ? clone(result.settings) : null,
- errors: result.errors
- };
-}
-function parseSettingsFileUncached(path8) {
- try {
- const { resolvedPath } = safeResolvePath(getFsImplementation(), path8);
- const content = readFileSync4(resolvedPath);
- if (content.trim() === "") {
- return { settings: {}, errors: [] };
- }
- const data = safeParseJSON(content, false);
- const ruleWarnings = filterInvalidPermissionRules(data, path8);
- const result = SettingsSchema().safeParse(data);
- if (!result.success) {
- const errors3 = formatZodError(result.error, path8);
- return { settings: null, errors: [...ruleWarnings, ...errors3] };
- }
- return { settings: result.data, errors: ruleWarnings };
- } catch (error40) {
- handleFileSystemError(error40, path8);
- return { settings: null, errors: [] };
- }
-}
-function getSettingsRootPathForSource(source) {
- switch (source) {
- case "userSettings":
- return resolve8(getClaudeConfigHomeDir());
- case "policySettings":
- case "projectSettings":
- case "localSettings": {
- return resolve8(getOriginalCwd());
- }
- case "flagSettings": {
- const path8 = getFlagSettingsPath();
- return path8 ? dirname11(resolve8(path8)) : resolve8(getOriginalCwd());
- }
- }
-}
-function getUserSettingsFilePath() {
- if (getUseCoworkPlugins() || isEnvTruthy(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS)) {
- return "cowork_settings.json";
- }
- return "settings.json";
-}
-function getSettingsFilePathForSource(source) {
- switch (source) {
- case "userSettings":
- return join20(getSettingsRootPathForSource(source), getUserSettingsFilePath());
- case "projectSettings":
- case "localSettings": {
- return join20(getSettingsRootPathForSource(source), getRelativeSettingsFilePathForSource(source));
- }
- case "policySettings":
- return getManagedSettingsFilePath();
- case "flagSettings": {
- return getFlagSettingsPath();
- }
- }
-}
-function getRelativeSettingsFilePathForSource(source) {
- switch (source) {
- case "projectSettings":
- return join20(".claude", "settings.json");
- case "localSettings":
- return join20(".claude", "settings.local.json");
- }
-}
-function getSettingsForSource(source) {
- const cached2 = getCachedSettingsForSource(source);
- if (cached2 !== undefined)
- return cached2;
- const result = getSettingsForSourceUncached(source);
- setCachedSettingsForSource(source, result);
- return result;
-}
-function getSettingsForSourceUncached(source) {
- if (source === "policySettings") {
- const remoteSettings = getRemoteManagedSettingsSyncFromCache();
- if (remoteSettings && Object.keys(remoteSettings).length > 0) {
- return remoteSettings;
- }
- const mdmResult = getMdmSettings();
- if (Object.keys(mdmResult.settings).length > 0) {
- return mdmResult.settings;
- }
- const { settings: fileSettings2 } = loadManagedFileSettings();
- if (fileSettings2) {
- return fileSettings2;
- }
- const hkcu = getHkcuSettings();
- if (Object.keys(hkcu.settings).length > 0) {
- return hkcu.settings;
- }
- return null;
- }
- const settingsFilePath = getSettingsFilePathForSource(source);
- const { settings: fileSettings } = settingsFilePath ? parseSettingsFile(settingsFilePath) : { settings: null };
- if (source === "flagSettings") {
- const inlineSettings = getFlagSettingsInline();
- if (inlineSettings) {
- const parsed = SettingsSchema().safeParse(inlineSettings);
- if (parsed.success) {
- return mergeWith_default(fileSettings || {}, parsed.data, settingsMergeCustomizer);
- }
- }
- }
- return fileSettings;
-}
-function getPolicySettingsOrigin() {
- const remoteSettings = getRemoteManagedSettingsSyncFromCache();
- if (remoteSettings && Object.keys(remoteSettings).length > 0) {
- return "remote";
- }
- const mdmResult = getMdmSettings();
- if (Object.keys(mdmResult.settings).length > 0) {
- return getPlatform() === "macos" ? "plist" : "hklm";
- }
- const { settings: fileSettings } = loadManagedFileSettings();
- if (fileSettings) {
- return "file";
- }
- const hkcu = getHkcuSettings();
- if (Object.keys(hkcu.settings).length > 0) {
- return "hkcu";
- }
- return null;
-}
-function updateSettingsForSource(source, settings) {
- if (source === "policySettings" || source === "flagSettings") {
- return { error: null };
- }
- const filePath = getSettingsFilePathForSource(source);
- if (!filePath) {
- return { error: null };
- }
- try {
- getFsImplementation().mkdirSync(dirname11(filePath));
- let existingSettings = getSettingsForSourceUncached(source);
- if (!existingSettings) {
- let content = null;
- try {
- content = readFileSync4(filePath);
- } catch (e) {
- if (!isENOENT(e)) {
- throw e;
- }
- }
- if (content !== null) {
- const rawData = safeParseJSON(content);
- if (rawData === null) {
- return {
- error: new Error(`Invalid JSON syntax in settings file at ${filePath}`)
- };
- }
- if (rawData && typeof rawData === "object") {
- existingSettings = rawData;
- logForDebugging(`Using raw settings from ${filePath} due to validation failure`);
- }
- }
- }
- const updatedSettings = mergeWith_default(existingSettings || {}, settings, (_objValue, srcValue, key, object2) => {
- if (srcValue === undefined && object2 && typeof key === "string") {
- delete object2[key];
- return;
- }
- if (Array.isArray(srcValue)) {
- return srcValue;
- }
- return;
- });
- markInternalWrite(filePath);
- writeFileSyncAndFlush_DEPRECATED(filePath, jsonStringify(updatedSettings, null, 2) + `
-`);
- resetSettingsCache();
- if (source === "localSettings") {
- addFileGlobRuleToGitignore(getRelativeSettingsFilePathForSource("localSettings"), getOriginalCwd());
- }
- } catch (e) {
- const error40 = new Error(`Failed to read raw settings from ${filePath}: ${e}`);
- logError2(error40);
- return { error: error40 };
- }
- return { error: null };
-}
-function mergeArrays(targetArray, sourceArray) {
- return uniq([...targetArray, ...sourceArray]);
-}
-function settingsMergeCustomizer(objValue, srcValue) {
- if (Array.isArray(objValue) && Array.isArray(srcValue)) {
- return mergeArrays(objValue, srcValue);
- }
- return;
-}
-function getManagedSettingsKeysForLogging(settings) {
- const validSettings = SettingsSchema().strip().parse(settings);
- const keysToExpand = ["permissions", "sandbox", "hooks"];
- const allKeys = [];
- const validNestedKeys = {
- permissions: new Set([
- "allow",
- "deny",
- "ask",
- "defaultMode",
- "disableBypassPermissionsMode",
- ...[],
- "additionalDirectories"
- ]),
- sandbox: new Set([
- "enabled",
- "failIfUnavailable",
- "allowUnsandboxedCommands",
- "network",
- "filesystem",
- "ignoreViolations",
- "excludedCommands",
- "autoAllowBashIfSandboxed",
- "enableWeakerNestedSandbox",
- "enableWeakerNetworkIsolation",
- "ripgrep"
- ]),
- hooks: new Set([
- "PreToolUse",
- "PostToolUse",
- "Notification",
- "UserPromptSubmit",
- "SessionStart",
- "SessionEnd",
- "Stop",
- "SubagentStop",
- "PreCompact",
- "PostCompact",
- "TeammateIdle",
- "TaskCreated",
- "TaskCompleted"
- ])
- };
- for (const key of Object.keys(validSettings)) {
- if (keysToExpand.includes(key) && validSettings[key] && typeof validSettings[key] === "object") {
- const nestedObj = validSettings[key];
- const validKeys = validNestedKeys[key];
- if (validKeys) {
- for (const nestedKey of Object.keys(nestedObj)) {
- if (validKeys.has(nestedKey)) {
- allKeys.push(`${key}.${nestedKey}`);
- }
- }
- }
- } else {
- allKeys.push(key);
- }
- }
- return allKeys.sort();
-}
-function loadSettingsFromDisk() {
- if (isLoadingSettings) {
- return { settings: {}, errors: [] };
- }
- const startTime = Date.now();
- profileCheckpoint("loadSettingsFromDisk_start");
- logForDiagnosticsNoPII("info", "settings_load_started");
- isLoadingSettings = true;
- try {
- const pluginSettings = getPluginSettingsBase();
- let mergedSettings = {};
- if (pluginSettings) {
- mergedSettings = mergeWith_default(mergedSettings, pluginSettings, settingsMergeCustomizer);
- }
- const allErrors = [];
- const seenErrors = new Set;
- const seenFiles = new Set;
- for (const source of getEnabledSettingSources()) {
- if (source === "policySettings") {
- let policySettings = null;
- const policyErrors = [];
- const remoteSettings = getRemoteManagedSettingsSyncFromCache();
- if (remoteSettings && Object.keys(remoteSettings).length > 0) {
- const result = SettingsSchema().safeParse(remoteSettings);
- if (result.success) {
- policySettings = result.data;
- } else {
- policyErrors.push(...formatZodError(result.error, "remote managed settings"));
- }
- }
- if (!policySettings) {
- const mdmResult = getMdmSettings();
- if (Object.keys(mdmResult.settings).length > 0) {
- policySettings = mdmResult.settings;
- }
- policyErrors.push(...mdmResult.errors);
- }
- if (!policySettings) {
- const { settings, errors: errors3 } = loadManagedFileSettings();
- if (settings) {
- policySettings = settings;
- }
- policyErrors.push(...errors3);
- }
- if (!policySettings) {
- const hkcu = getHkcuSettings();
- if (Object.keys(hkcu.settings).length > 0) {
- policySettings = hkcu.settings;
- }
- policyErrors.push(...hkcu.errors);
- }
- if (policySettings) {
- mergedSettings = mergeWith_default(mergedSettings, policySettings, settingsMergeCustomizer);
- }
- for (const error40 of policyErrors) {
- const errorKey = `${error40.file}:${error40.path}:${error40.message}`;
- if (!seenErrors.has(errorKey)) {
- seenErrors.add(errorKey);
- allErrors.push(error40);
- }
- }
- continue;
- }
- const filePath = getSettingsFilePathForSource(source);
- if (filePath) {
- const resolvedPath = resolve8(filePath);
- if (!seenFiles.has(resolvedPath)) {
- seenFiles.add(resolvedPath);
- const { settings, errors: errors3 } = parseSettingsFile(filePath);
- for (const error40 of errors3) {
- const errorKey = `${error40.file}:${error40.path}:${error40.message}`;
- if (!seenErrors.has(errorKey)) {
- seenErrors.add(errorKey);
- allErrors.push(error40);
- }
- }
- if (settings) {
- mergedSettings = mergeWith_default(mergedSettings, settings, settingsMergeCustomizer);
- }
- }
- }
- if (source === "flagSettings") {
- const inlineSettings = getFlagSettingsInline();
- if (inlineSettings) {
- const parsed = SettingsSchema().safeParse(inlineSettings);
- if (parsed.success) {
- mergedSettings = mergeWith_default(mergedSettings, parsed.data, settingsMergeCustomizer);
- }
- }
- }
- }
- logForDiagnosticsNoPII("info", "settings_load_completed", {
- duration_ms: Date.now() - startTime,
- source_count: seenFiles.size,
- error_count: allErrors.length
- });
- return { settings: mergedSettings, errors: allErrors };
- } finally {
- isLoadingSettings = false;
- }
-}
-function getInitialSettings() {
- const { settings } = getSettingsWithErrors();
- return settings || {};
-}
-function getSettingsWithSources() {
- resetSettingsCache();
- const sources = [];
- for (const source of getEnabledSettingSources()) {
- const settings = getSettingsForSource(source);
- if (settings && Object.keys(settings).length > 0) {
- sources.push({ source, settings });
- }
- }
- return { effective: getInitialSettings(), sources };
-}
-function getSettingsWithErrors() {
- const cached2 = getSessionSettingsCache();
- if (cached2 !== null) {
- return cached2;
- }
- const result = loadSettingsFromDisk();
- profileCheckpoint("loadSettingsFromDisk_end");
- setSessionSettingsCache(result);
- return result;
-}
-function hasSkipDangerousModePermissionPrompt() {
- return !!(getSettingsForSource("userSettings")?.skipDangerousModePermissionPrompt || getSettingsForSource("localSettings")?.skipDangerousModePermissionPrompt || getSettingsForSource("flagSettings")?.skipDangerousModePermissionPrompt || getSettingsForSource("policySettings")?.skipDangerousModePermissionPrompt);
-}
-function hasAutoModeOptIn() {
- if (false) {}
- return false;
-}
-function rawSettingsContainsKey(key) {
- for (const source of getEnabledSettingSources()) {
- if (source === "policySettings") {
- continue;
- }
- const filePath = getSettingsFilePathForSource(source);
- if (!filePath) {
- continue;
- }
- try {
- const { resolvedPath } = safeResolvePath(getFsImplementation(), filePath);
- const content = readFileSync4(resolvedPath);
- if (!content.trim()) {
- continue;
- }
- const rawData = safeParseJSON(content, false);
- if (rawData && typeof rawData === "object" && key in rawData) {
- return true;
- }
- } catch (error40) {
- handleFileSystemError(error40, filePath);
- }
- }
- return false;
-}
-var isLoadingSettings = false, getSettings_DEPRECATED;
-var init_settings2 = __esm(() => {
- init_mergeWith();
- init_state();
- init_syncCacheState();
- init_debug();
- init_diagLogs();
- init_envUtils();
- init_errors();
- init_file();
- init_fileRead();
- init_fsOperations();
- init_gitignore();
- init_json();
- init_log2();
- init_platform2();
- init_slowOperations();
- init_startupProfiler();
- init_constants2();
- init_internalWrites();
- init_managedPath();
- init_settings();
- init_settingsCache();
- init_types2();
- init_validation2();
- getSettings_DEPRECATED = getInitialSettings;
-});
-
-// node_modules/agent-base/dist/helpers.js
-var require_helpers = __commonJS((exports) => {
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, 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(o2, k2, desc);
- } : function(o2, m, k, k2) {
- if (k2 === undefined)
- k2 = k;
- o2[k2] = m[k];
- });
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) {
- Object.defineProperty(o2, "default", { enumerable: true, value: v });
- } : function(o2, v) {
- o2["default"] = v;
- });
- var __importStar = exports && exports.__importStar || function(mod2) {
- if (mod2 && mod2.__esModule)
- return mod2;
- var result = {};
- if (mod2 != null) {
- for (var k in mod2)
- if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k))
- __createBinding(result, mod2, k);
- }
- __setModuleDefault(result, mod2);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.req = exports.json = exports.toBuffer = undefined;
- var http3 = __importStar(__require("http"));
- var https2 = __importStar(__require("https"));
- async function toBuffer(stream4) {
- let length = 0;
- const chunks = [];
- for await (const chunk of stream4) {
- length += chunk.length;
- chunks.push(chunk);
- }
- return Buffer.concat(chunks, length);
- }
- exports.toBuffer = toBuffer;
- async function json2(stream4) {
- const buf = await toBuffer(stream4);
- const str = buf.toString("utf8");
- try {
- return JSON.parse(str);
- } catch (_err) {
- const err = _err;
- err.message += ` (input: ${str})`;
- throw err;
- }
- }
- exports.json = json2;
- function req(url3, opts = {}) {
- const href = typeof url3 === "string" ? url3 : url3.href;
- const req2 = (href.startsWith("https:") ? https2 : http3).request(url3, opts);
- const promise2 = new Promise((resolve9, reject) => {
- req2.once("response", resolve9).once("error", reject).end();
- });
- req2.then = promise2.then.bind(promise2);
- return req2;
- }
- exports.req = req;
-});
-
-// node_modules/agent-base/dist/index.js
-var require_dist = __commonJS((exports) => {
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, 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(o2, k2, desc);
- } : function(o2, m, k, k2) {
- if (k2 === undefined)
- k2 = k;
- o2[k2] = m[k];
- });
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) {
- Object.defineProperty(o2, "default", { enumerable: true, value: v });
- } : function(o2, v) {
- o2["default"] = v;
- });
- var __importStar = exports && exports.__importStar || function(mod2) {
- if (mod2 && mod2.__esModule)
- return mod2;
- var result = {};
- if (mod2 != null) {
- for (var k in mod2)
- if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k))
- __createBinding(result, mod2, k);
- }
- __setModuleDefault(result, mod2);
- return result;
- };
- var __exportStar = exports && exports.__exportStar || function(m, exports2) {
- for (var p in m)
- if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
- __createBinding(exports2, m, p);
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Agent = undefined;
- var net = __importStar(__require("net"));
- var http3 = __importStar(__require("http"));
- var https_1 = __require("https");
- __exportStar(require_helpers(), exports);
- var INTERNAL = Symbol("AgentBaseInternalState");
-
- class Agent extends http3.Agent {
- constructor(opts) {
- super(opts);
- this[INTERNAL] = {};
- }
- isSecureEndpoint(options2) {
- if (options2) {
- if (typeof options2.secureEndpoint === "boolean") {
- return options2.secureEndpoint;
- }
- if (typeof options2.protocol === "string") {
- return options2.protocol === "https:";
- }
- }
- const { stack } = new Error;
- if (typeof stack !== "string")
- return false;
- return stack.split(`
-`).some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1);
- }
- incrementSockets(name) {
- if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
- return null;
- }
- if (!this.sockets[name]) {
- this.sockets[name] = [];
- }
- const fakeSocket = new net.Socket({ writable: false });
- this.sockets[name].push(fakeSocket);
- this.totalSocketCount++;
- return fakeSocket;
- }
- decrementSockets(name, socket) {
- if (!this.sockets[name] || socket === null) {
- return;
- }
- const sockets = this.sockets[name];
- const index2 = sockets.indexOf(socket);
- if (index2 !== -1) {
- sockets.splice(index2, 1);
- this.totalSocketCount--;
- if (sockets.length === 0) {
- delete this.sockets[name];
- }
- }
- }
- getName(options2) {
- const secureEndpoint = this.isSecureEndpoint(options2);
- if (secureEndpoint) {
- return https_1.Agent.prototype.getName.call(this, options2);
- }
- return super.getName(options2);
- }
- createSocket(req, options2, cb) {
- const connectOpts = {
- ...options2,
- secureEndpoint: this.isSecureEndpoint(options2)
- };
- 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 http3.Agent) {
- try {
- return socket.addRequest(req, connectOpts);
- } catch (err) {
- return cb(err);
- }
- }
- this[INTERNAL].currentSocket = socket;
- super.createSocket(req, options2, cb);
- }, (err) => {
- this.decrementSockets(name, fakeSocket);
- cb(err);
- });
- }
- createConnection() {
- const socket = this[INTERNAL].currentSocket;
- this[INTERNAL].currentSocket = undefined;
- if (!socket) {
- throw new Error("No socket was returned in the `connect()` function");
- }
- return socket;
- }
- get defaultPort() {
- return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80);
- }
- set defaultPort(v) {
- if (this[INTERNAL]) {
- this[INTERNAL].defaultPort = v;
- }
- }
- get protocol() {
- return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
- }
- set protocol(v) {
- if (this[INTERNAL]) {
- this[INTERNAL].protocol = v;
- }
- }
- }
- exports.Agent = Agent;
-});
-
-// node_modules/https-proxy-agent/dist/parse-proxy-response.js
-var require_parse_proxy_response = __commonJS((exports) => {
- var __importDefault = exports && exports.__importDefault || function(mod2) {
- return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.parseProxyResponse = undefined;
- var debug_1 = __importDefault(require_src());
- var debug2 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
- function parseProxyResponse(socket) {
- return new Promise((resolve9, reject) => {
- 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();
- debug2("onend");
- reject(new Error("Proxy connection ended before receiving CONNECT response"));
- }
- function onerror(err) {
- cleanup();
- debug2("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
-\r
-`);
- if (endOfHeaders === -1) {
- debug2("have not received end of HTTP headers yet...");
- read();
- return;
- }
- const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split(`\r
-`);
- 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;
- }
- }
- debug2("got proxy server response: %o %o", firstLine, headers);
- cleanup();
- resolve9({
- connect: {
- statusCode,
- statusText,
- headers
- },
- buffered
- });
- }
- socket.on("error", onerror);
- socket.on("end", onend);
- read();
- });
- }
- exports.parseProxyResponse = parseProxyResponse;
-});
-
-// node_modules/https-proxy-agent/dist/index.js
-var require_dist2 = __commonJS((exports) => {
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, 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(o2, k2, desc);
- } : function(o2, m, k, k2) {
- if (k2 === undefined)
- k2 = k;
- o2[k2] = m[k];
- });
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) {
- Object.defineProperty(o2, "default", { enumerable: true, value: v });
- } : function(o2, v) {
- o2["default"] = v;
- });
- var __importStar = exports && exports.__importStar || function(mod2) {
- if (mod2 && mod2.__esModule)
- return mod2;
- var result = {};
- if (mod2 != null) {
- for (var k in mod2)
- if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k))
- __createBinding(result, mod2, k);
- }
- __setModuleDefault(result, mod2);
- return result;
- };
- var __importDefault = exports && exports.__importDefault || function(mod2) {
- return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.HttpsProxyAgent = undefined;
- var net = __importStar(__require("net"));
- var tls = __importStar(__require("tls"));
- var assert_1 = __importDefault(__require("assert"));
- var debug_1 = __importDefault(require_src());
- var agent_base_1 = require_dist();
- var url_1 = __require("url");
- var parse_proxy_response_1 = require_parse_proxy_response();
- var debug2 = (0, debug_1.default)("https-proxy-agent");
- var setServernameFromNonIpHost = (options2) => {
- if (options2.servername === undefined && options2.host && !net.isIP(options2.host)) {
- return {
- ...options2,
- servername: options2.host
- };
- }
- return options2;
- };
-
- 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 ?? {};
- debug2("Creating new HttpsProxyAgent instance: %o", this.proxy.href);
- 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 = {
- ALPNProtocols: ["http/1.1"],
- ...opts ? omit2(opts, "headers") : null,
- host,
- port
- };
- }
- async connect(req, opts) {
- const { proxy } = this;
- if (!opts.host) {
- throw new TypeError('No "host" provided');
- }
- let socket;
- if (proxy.protocol === "https:") {
- debug2("Creating `tls.Socket`: %o", this.connectOpts);
- socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
- } else {
- debug2("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
-`;
- 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
-`;
- }
- const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
- socket.write(`${payload}\r
-`);
- 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) {
- debug2("Upgrading socket connection to TLS");
- return tls.connect({
- ...omit2(setServernameFromNonIpHost(opts), "host", "path", "port"),
- socket
- });
- }
- return socket;
- }
- socket.destroy();
- const fakeSocket = new net.Socket({ writable: false });
- fakeSocket.readable = true;
- req.once("socket", (s) => {
- debug2("Replaying proxy buffer for failed request");
- (0, assert_1.default)(s.listenerCount("data") > 0);
- s.push(buffered);
- s.push(null);
- });
- return fakeSocket;
- }
- }
- HttpsProxyAgent.protocols = ["http", "https"];
- exports.HttpsProxyAgent = HttpsProxyAgent;
- function resume(socket) {
- socket.resume();
- }
- function omit2(obj, ...keys2) {
- const ret = {};
- let key;
- for (key in obj) {
- if (!keys2.includes(key)) {
- ret[key] = obj[key];
- }
- }
- return ret;
- }
-});
-
-// src/utils/caCerts.ts
-function clearCACertsCache() {
- getCACertificates.cache.clear?.();
- logForDebugging("Cleared CA certificates cache");
-}
-var getCACertificates;
-var init_caCerts = __esm(() => {
- init_memoize();
- init_debug();
- init_envUtils();
- init_fsOperations();
- getCACertificates = memoize_default(() => {
- const useSystemCA = hasNodeOption("--use-system-ca") || hasNodeOption("--use-openssl-ca");
- const extraCertsPath = process.env.NODE_EXTRA_CA_CERTS;
- logForDebugging(`CA certs: useSystemCA=${useSystemCA}, extraCertsPath=${extraCertsPath}`);
- if (!useSystemCA && !extraCertsPath) {
- return;
- }
- const tls = __require("tls");
- const certs = [];
- if (useSystemCA) {
- const getCACerts = tls.getCACertificates;
- const systemCAs = getCACerts?.("system");
- if (systemCAs && systemCAs.length > 0) {
- certs.push(...systemCAs);
- logForDebugging(`CA certs: Loaded ${certs.length} system CA certificates (--use-system-ca)`);
- } else if (!getCACerts && !extraCertsPath) {
- logForDebugging("CA certs: --use-system-ca set but system CA API unavailable, deferring to runtime");
- return;
- } else {
- certs.push(...tls.rootCertificates);
- logForDebugging(`CA certs: Loaded ${certs.length} bundled root certificates as base (--use-system-ca fallback)`);
- }
- } else {
- certs.push(...tls.rootCertificates);
- logForDebugging(`CA certs: Loaded ${certs.length} bundled root certificates as base`);
- }
- if (extraCertsPath) {
- try {
- const extraCert = getFsImplementation().readFileSync(extraCertsPath, {
- encoding: "utf8"
- });
- certs.push(extraCert);
- logForDebugging(`CA certs: Appended extra certificates from NODE_EXTRA_CA_CERTS (${extraCertsPath})`);
- } catch (error40) {
- logForDebugging(`CA certs: Failed to read NODE_EXTRA_CA_CERTS file (${extraCertsPath}): ${error40}`, { level: "error" });
- }
- }
- return certs.length > 0 ? certs : undefined;
- });
-});
-
-// src/utils/mtls.ts
-import { Agent as HttpsAgent } from "https";
-function getWebSocketTLSOptions() {
- const mtlsConfig = getMTLSConfig();
- const caCerts = getCACertificates();
- if (!mtlsConfig && !caCerts) {
- return;
- }
- return {
- ...mtlsConfig,
- ...caCerts && { ca: caCerts }
- };
-}
-function getTLSFetchOptions() {
- const mtlsConfig = getMTLSConfig();
- const caCerts = getCACertificates();
- if (!mtlsConfig && !caCerts) {
- return {};
- }
- const tlsConfig = {
- ...mtlsConfig,
- ...caCerts && { ca: caCerts }
- };
- if (typeof Bun !== "undefined") {
- return { tls: tlsConfig };
- }
- logForDebugging("TLS: Created undici agent with custom certificates");
- const undiciMod = __require("undici");
- const agent = new undiciMod.Agent({
- connect: {
- cert: tlsConfig.cert,
- key: tlsConfig.key,
- passphrase: tlsConfig.passphrase,
- ...tlsConfig.ca && { ca: tlsConfig.ca }
- },
- pipelining: 1
- });
- return { dispatcher: agent };
-}
-function clearMTLSCache() {
- getMTLSConfig.cache.clear?.();
- getMTLSAgent.cache.clear?.();
- logForDebugging("Cleared mTLS configuration cache");
-}
-function configureGlobalMTLS() {
- const mtlsConfig = getMTLSConfig();
- if (!mtlsConfig) {
- return;
- }
- if (process.env.NODE_EXTRA_CA_CERTS) {
- logForDebugging("NODE_EXTRA_CA_CERTS detected - Node.js will automatically append to built-in CAs");
- }
-}
-var getMTLSConfig, getMTLSAgent;
-var init_mtls = __esm(() => {
- init_memoize();
- init_caCerts();
- init_debug();
- init_fsOperations();
- getMTLSConfig = memoize_default(() => {
- const config2 = {};
- if (process.env.CLAUDE_CODE_CLIENT_CERT) {
- try {
- config2.cert = getFsImplementation().readFileSync(process.env.CLAUDE_CODE_CLIENT_CERT, { encoding: "utf8" });
- logForDebugging("mTLS: Loaded client certificate from CLAUDE_CODE_CLIENT_CERT");
- } catch (error40) {
- logForDebugging(`mTLS: Failed to load client certificate: ${error40}`, {
- level: "error"
- });
- }
- }
- if (process.env.CLAUDE_CODE_CLIENT_KEY) {
- try {
- config2.key = getFsImplementation().readFileSync(process.env.CLAUDE_CODE_CLIENT_KEY, { encoding: "utf8" });
- logForDebugging("mTLS: Loaded client key from CLAUDE_CODE_CLIENT_KEY");
- } catch (error40) {
- logForDebugging(`mTLS: Failed to load client key: ${error40}`, {
- level: "error"
- });
- }
- }
- if (process.env.CLAUDE_CODE_CLIENT_KEY_PASSPHRASE) {
- config2.passphrase = process.env.CLAUDE_CODE_CLIENT_KEY_PASSPHRASE;
- logForDebugging("mTLS: Using client key passphrase");
- }
- if (Object.keys(config2).length === 0) {
- return;
- }
- return config2;
- });
- getMTLSAgent = memoize_default(() => {
- const mtlsConfig = getMTLSConfig();
- const caCerts = getCACertificates();
- if (!mtlsConfig && !caCerts) {
- return;
- }
- const agentOptions = {
- ...mtlsConfig,
- ...caCerts && { ca: caCerts },
- keepAlive: true
- };
- logForDebugging("mTLS: Creating HTTPS agent with custom certificates");
- return new HttpsAgent(agentOptions);
- });
-});
-
-// node_modules/@smithy/node-http-handler/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation) {
- HttpAuthLocation["HEADER"] = "header";
- HttpAuthLocation["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation) {
- HttpApiKeyAuthLocation["HEADER"] = "header";
- HttpApiKeyAuthLocation["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme) {
- EndpointURLScheme["HTTP"] = "http";
- EndpointURLScheme["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId) {
- AlgorithmId["MD5"] = "md5";
- AlgorithmId["CRC32"] = "crc32";
- AlgorithmId["CRC32C"] = "crc32c";
- AlgorithmId["SHA1"] = "sha1";
- AlgorithmId["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration = (runtimeConfig) => {
- return getChecksumConfiguration(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig = (config2) => {
- return resolveChecksumRuntimeConfig(config2);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition) {
- FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER";
- FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType) {
- IniSectionType["PROFILE"] = "profile";
- IniSectionType["SSO_SESSION"] = "sso-session";
- IniSectionType["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol) {
- RequestHandlerProtocol["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig;
-});
-
-// node_modules/@smithy/node-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js
-var require_dist_cjs2 = __commonJS((exports) => {
- var types = require_dist_cjs();
- var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
- };
- var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
- };
-
- class Field {
- name;
- kind;
- values;
- constructor({ name, kind: kind2 = types.FieldPosition.HEADER, values = [] }) {
- this.name = name;
- this.kind = kind2;
- this.values = values;
- }
- add(value) {
- this.values.push(value);
- }
- set(values) {
- this.values = values;
- }
- remove(value) {
- this.values = this.values.filter((v) => v !== value);
- }
- toString() {
- return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
- }
- get() {
- return this.values;
- }
- }
-
- class Fields {
- entries = {};
- encoding;
- constructor({ fields = [], encoding = "utf-8" }) {
- fields.forEach(this.setField.bind(this));
- this.encoding = encoding;
- }
- setField(field) {
- this.entries[field.name.toLowerCase()] = field;
- }
- getField(name) {
- return this.entries[name.toLowerCase()];
- }
- removeField(name) {
- delete this.entries[name.toLowerCase()];
- }
- getByType(kind2) {
- return Object.values(this.entries).filter((field) => field.kind === kind2);
- }
- }
-
- class HttpRequest {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request) {
- const cloned = new HttpRequest({
- ...request,
- headers: { ...request.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery(cloned.query);
- }
- return cloned;
- }
- static isInstance(request) {
- if (!request) {
- return false;
- }
- const req = request;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest.clone(this);
- }
- }
- function cloneQuery(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
- }
-
- class HttpResponse {
- statusCode;
- reason;
- headers;
- body;
- constructor(options2) {
- this.statusCode = options2.statusCode;
- this.reason = options2.reason;
- this.headers = options2.headers || {};
- this.body = options2.body;
- }
- static isInstance(response) {
- if (!response)
- return false;
- const resp = response;
- return typeof resp.statusCode === "number" && typeof resp.headers === "object";
- }
- }
- function isValidHostname(hostname2) {
- const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
- return hostPattern.test(hostname2);
- }
- exports.Field = Field;
- exports.Fields = Fields;
- exports.HttpRequest = HttpRequest;
- exports.HttpResponse = HttpResponse;
- exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
- exports.isValidHostname = isValidHostname;
- exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;
-});
-
-// node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js
-var require_dist_cjs3 = __commonJS((exports) => {
- var escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode);
- var hexEncode = (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`;
- var escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/");
- exports.escapeUri = escapeUri;
- exports.escapeUriPath = escapeUriPath;
-});
-
-// node_modules/@smithy/querystring-builder/dist-cjs/index.js
-var require_dist_cjs4 = __commonJS((exports) => {
- var utilUriEscape = require_dist_cjs3();
- function buildQueryString(query) {
- const parts = [];
- for (let key of Object.keys(query).sort()) {
- const value = query[key];
- key = utilUriEscape.escapeUri(key);
- if (Array.isArray(value)) {
- for (let i2 = 0, iLen = value.length;i2 < iLen; i2++) {
- parts.push(`${key}=${utilUriEscape.escapeUri(value[i2])}`);
- }
- } else {
- let qsEntry = key;
- if (value || typeof value === "string") {
- qsEntry += `=${utilUriEscape.escapeUri(value)}`;
- }
- parts.push(qsEntry);
- }
- }
- return parts.join("&");
- }
- exports.buildQueryString = buildQueryString;
-});
-
-// node_modules/@smithy/node-http-handler/dist-cjs/index.js
-var require_dist_cjs5 = __commonJS((exports) => {
- var protocolHttp = require_dist_cjs2();
- var querystringBuilder = require_dist_cjs4();
- var node_https = __require("https");
- var node_stream = __require("stream");
- var http22 = __require("http2");
- function buildAbortError(abortSignal) {
- const reason = abortSignal && typeof abortSignal === "object" && "reason" in abortSignal ? abortSignal.reason : undefined;
- if (reason) {
- if (reason instanceof Error) {
- const abortError3 = new Error("Request aborted");
- abortError3.name = "AbortError";
- abortError3.cause = reason;
- return abortError3;
- }
- const abortError2 = new Error(String(reason));
- abortError2.name = "AbortError";
- return abortError2;
- }
- const abortError = new Error("Request aborted");
- abortError.name = "AbortError";
- return abortError;
- }
- var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"];
- var getTransformedHeaders = (headers) => {
- const transformedHeaders = {};
- for (const name of Object.keys(headers)) {
- const headerValues = headers[name];
- transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues;
- }
- return transformedHeaders;
- };
- var timing = {
- setTimeout: (cb, ms) => setTimeout(cb, ms),
- clearTimeout: (timeoutId) => clearTimeout(timeoutId)
- };
- var DEFER_EVENT_LISTENER_TIME$2 = 1000;
- var setConnectionTimeout = (request, reject, timeoutInMs = 0) => {
- if (!timeoutInMs) {
- return -1;
- }
- const registerTimeout = (offset) => {
- const timeoutId = timing.setTimeout(() => {
- request.destroy();
- reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), {
- name: "TimeoutError"
- }));
- }, timeoutInMs - offset);
- const doWithSocket = (socket) => {
- if (socket?.connecting) {
- socket.on("connect", () => {
- timing.clearTimeout(timeoutId);
- });
- } else {
- timing.clearTimeout(timeoutId);
- }
- };
- if (request.socket) {
- doWithSocket(request.socket);
- } else {
- request.on("socket", doWithSocket);
- }
- };
- if (timeoutInMs < 2000) {
- registerTimeout(0);
- return 0;
- }
- return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2);
- };
- var setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger) => {
- if (timeoutInMs) {
- return timing.setTimeout(() => {
- let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? "ERROR" : "WARN"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`;
- if (throwOnRequestTimeout) {
- const error40 = Object.assign(new Error(msg), {
- name: "TimeoutError",
- code: "ETIMEDOUT"
- });
- req.destroy(error40);
- reject(error40);
- } else {
- msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`;
- logger?.warn?.(msg);
- }
- }, timeoutInMs);
- }
- return -1;
- };
- var DEFER_EVENT_LISTENER_TIME$1 = 3000;
- var setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => {
- if (keepAlive !== true) {
- return -1;
- }
- const registerListener = () => {
- if (request.socket) {
- request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
- } else {
- request.on("socket", (socket) => {
- socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
- });
- }
- };
- if (deferTimeMs === 0) {
- registerListener();
- return 0;
- }
- return timing.setTimeout(registerListener, deferTimeMs);
- };
- var DEFER_EVENT_LISTENER_TIME = 3000;
- var setSocketTimeout = (request, reject, timeoutInMs = 0) => {
- const registerTimeout = (offset) => {
- const timeout = timeoutInMs - offset;
- const onTimeout = () => {
- request.destroy();
- reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: "TimeoutError" }));
- };
- if (request.socket) {
- request.socket.setTimeout(timeout, onTimeout);
- request.on("close", () => request.socket?.removeListener("timeout", onTimeout));
- } else {
- request.setTimeout(timeout, onTimeout);
- }
- };
- if (0 < timeoutInMs && timeoutInMs < 6000) {
- registerTimeout(0);
- return 0;
- }
- return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);
- };
- var MIN_WAIT_TIME = 6000;
- async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) {
- const headers = request.headers ?? {};
- const expect = headers.Expect || headers.expect;
- let timeoutId = -1;
- let sendBody = true;
- if (!externalAgent && expect === "100-continue") {
- sendBody = await Promise.race([
- new Promise((resolve9) => {
- timeoutId = Number(timing.setTimeout(() => resolve9(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));
- }),
- new Promise((resolve9) => {
- httpRequest.on("continue", () => {
- timing.clearTimeout(timeoutId);
- resolve9(true);
- });
- httpRequest.on("response", () => {
- timing.clearTimeout(timeoutId);
- resolve9(false);
- });
- httpRequest.on("error", () => {
- timing.clearTimeout(timeoutId);
- resolve9(false);
- });
- })
- ]);
- }
- if (sendBody) {
- writeBody(httpRequest, request.body);
- }
- }
- function writeBody(httpRequest, body) {
- if (body instanceof node_stream.Readable) {
- body.pipe(httpRequest);
- return;
- }
- if (body) {
- const isBuffer3 = Buffer.isBuffer(body);
- const isString2 = typeof body === "string";
- if (isBuffer3 || isString2) {
- if (isBuffer3 && body.byteLength === 0) {
- httpRequest.end();
- } else {
- httpRequest.end(body);
- }
- return;
- }
- const uint8 = body;
- if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") {
- httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
- return;
- }
- httpRequest.end(Buffer.from(body));
- return;
- }
- httpRequest.end();
- }
- var DEFAULT_REQUEST_TIMEOUT = 0;
- var hAgent = undefined;
- var hRequest = undefined;
-
- class NodeHttpHandler {
- config;
- configProvider;
- socketWarningTimestamp = 0;
- externalAgent = false;
- metadata = { handlerProtocol: "http/1.1" };
- static create(instanceOrOptions) {
- if (typeof instanceOrOptions?.handle === "function") {
- return instanceOrOptions;
- }
- return new NodeHttpHandler(instanceOrOptions);
- }
- static checkSocketUsage(agent, socketWarningTimestamp, logger = console) {
- const { sockets, requests, maxSockets } = agent;
- if (typeof maxSockets !== "number" || maxSockets === Infinity) {
- return socketWarningTimestamp;
- }
- const interval = 15000;
- if (Date.now() - interval < socketWarningTimestamp) {
- return socketWarningTimestamp;
- }
- if (sockets && requests) {
- for (const origin2 in sockets) {
- const socketsInUse = sockets[origin2]?.length ?? 0;
- const requestsEnqueued = requests[origin2]?.length ?? 0;
- if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {
- logger?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.
-See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
-or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`);
- return Date.now();
- }
- }
- }
- return socketWarningTimestamp;
- }
- constructor(options2) {
- this.configProvider = new Promise((resolve9, reject) => {
- if (typeof options2 === "function") {
- options2().then((_options) => {
- resolve9(this.resolveDefaultConfig(_options));
- }).catch(reject);
- } else {
- resolve9(this.resolveDefaultConfig(options2));
- }
- });
- }
- destroy() {
- this.config?.httpAgent?.destroy();
- this.config?.httpsAgent?.destroy();
- }
- async handle(request, { abortSignal, requestTimeout } = {}) {
- if (!this.config) {
- this.config = await this.configProvider;
- }
- const config2 = this.config;
- const isSSL = request.protocol === "https:";
- if (!isSSL && !this.config.httpAgent) {
- this.config.httpAgent = await this.config.httpAgentProvider();
- }
- return new Promise((_resolve, _reject) => {
- let writeRequestBodyPromise = undefined;
- const timeouts = [];
- const resolve9 = async (arg) => {
- await writeRequestBodyPromise;
- timeouts.forEach(timing.clearTimeout);
- _resolve(arg);
- };
- const reject = async (arg) => {
- await writeRequestBodyPromise;
- timeouts.forEach(timing.clearTimeout);
- _reject(arg);
- };
- if (abortSignal?.aborted) {
- const abortError = buildAbortError(abortSignal);
- reject(abortError);
- return;
- }
- const headers = request.headers ?? {};
- const expectContinue = (headers.Expect ?? headers.expect) === "100-continue";
- let agent = isSSL ? config2.httpsAgent : config2.httpAgent;
- if (expectContinue && !this.externalAgent) {
- agent = new (isSSL ? node_https.Agent : hAgent)({
- keepAlive: false,
- maxSockets: Infinity
- });
- }
- timeouts.push(timing.setTimeout(() => {
- this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, config2.logger);
- }, config2.socketAcquisitionWarningTimeout ?? (config2.requestTimeout ?? 2000) + (config2.connectionTimeout ?? 1000)));
- const queryString = querystringBuilder.buildQueryString(request.query || {});
- let auth = undefined;
- if (request.username != null || request.password != null) {
- const username = request.username ?? "";
- const password = request.password ?? "";
- auth = `${username}:${password}`;
- }
- let path8 = request.path;
- if (queryString) {
- path8 += `?${queryString}`;
- }
- if (request.fragment) {
- path8 += `#${request.fragment}`;
- }
- let hostname2 = request.hostname ?? "";
- if (hostname2[0] === "[" && hostname2.endsWith("]")) {
- hostname2 = request.hostname.slice(1, -1);
- } else {
- hostname2 = request.hostname;
- }
- const nodeHttpsOptions = {
- headers: request.headers,
- host: hostname2,
- method: request.method,
- path: path8,
- port: request.port,
- agent,
- auth
- };
- const requestFunc = isSSL ? node_https.request : hRequest;
- const req = requestFunc(nodeHttpsOptions, (res) => {
- const httpResponse = new protocolHttp.HttpResponse({
- statusCode: res.statusCode || -1,
- reason: res.statusMessage,
- headers: getTransformedHeaders(res.headers),
- body: res
- });
- resolve9({ response: httpResponse });
- });
- req.on("error", (err) => {
- if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) {
- reject(Object.assign(err, { name: "TimeoutError" }));
- } else {
- reject(err);
- }
- });
- if (abortSignal) {
- const onAbort = () => {
- req.destroy();
- const abortError = buildAbortError(abortSignal);
- reject(abortError);
- };
- if (typeof abortSignal.addEventListener === "function") {
- const signal = abortSignal;
- signal.addEventListener("abort", onAbort, { once: true });
- req.once("close", () => signal.removeEventListener("abort", onAbort));
- } else {
- abortSignal.onabort = onAbort;
- }
- }
- const effectiveRequestTimeout = requestTimeout ?? config2.requestTimeout;
- timeouts.push(setConnectionTimeout(req, reject, config2.connectionTimeout));
- timeouts.push(setRequestTimeout(req, reject, effectiveRequestTimeout, config2.throwOnRequestTimeout, config2.logger ?? console));
- timeouts.push(setSocketTimeout(req, reject, config2.socketTimeout));
- const httpAgent = nodeHttpsOptions.agent;
- if (typeof httpAgent === "object" && "keepAlive" in httpAgent) {
- timeouts.push(setSocketKeepAlive(req, {
- keepAlive: httpAgent.keepAlive,
- keepAliveMsecs: httpAgent.keepAliveMsecs
- }));
- }
- writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e) => {
- timeouts.forEach(timing.clearTimeout);
- return _reject(e);
- });
- });
- }
- updateHttpClientConfig(key, value) {
- this.config = undefined;
- this.configProvider = this.configProvider.then((config2) => {
- return {
- ...config2,
- [key]: value
- };
- });
- }
- httpHandlerConfigs() {
- return this.config ?? {};
- }
- resolveDefaultConfig(options2) {
- const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger } = options2 || {};
- const keepAlive = true;
- const maxSockets = 50;
- return {
- connectionTimeout,
- requestTimeout,
- socketTimeout,
- socketAcquisitionWarningTimeout,
- throwOnRequestTimeout,
- httpAgentProvider: async () => {
- const { Agent, request } = await import("http");
- hRequest = request;
- hAgent = Agent;
- if (httpAgent instanceof hAgent || typeof httpAgent?.destroy === "function") {
- this.externalAgent = true;
- return httpAgent;
- }
- return new hAgent({ keepAlive, maxSockets, ...httpAgent });
- },
- httpsAgent: (() => {
- if (httpsAgent instanceof node_https.Agent || typeof httpsAgent?.destroy === "function") {
- this.externalAgent = true;
- return httpsAgent;
- }
- return new node_https.Agent({ keepAlive, maxSockets, ...httpsAgent });
- })(),
- logger
- };
- }
- }
-
- class NodeHttp2ConnectionPool {
- sessions = [];
- constructor(sessions) {
- this.sessions = sessions ?? [];
- }
- poll() {
- if (this.sessions.length > 0) {
- return this.sessions.shift();
- }
- }
- offerLast(session) {
- this.sessions.push(session);
- }
- contains(session) {
- return this.sessions.includes(session);
- }
- remove(session) {
- this.sessions = this.sessions.filter((s) => s !== session);
- }
- [Symbol.iterator]() {
- return this.sessions[Symbol.iterator]();
- }
- destroy(connection) {
- for (const session of this.sessions) {
- if (session === connection) {
- if (!session.destroyed) {
- session.destroy();
- }
- }
- }
- }
- }
-
- class NodeHttp2ConnectionManager {
- constructor(config2) {
- this.config = config2;
- if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) {
- throw new RangeError("maxConcurrency must be greater than zero.");
- }
- }
- config;
- sessionCache = new Map;
- lease(requestContext, connectionConfiguration) {
- const url3 = this.getUrlString(requestContext);
- const existingPool = this.sessionCache.get(url3);
- if (existingPool) {
- const existingSession = existingPool.poll();
- if (existingSession && !this.config.disableConcurrency) {
- return existingSession;
- }
- }
- const session = http22.connect(url3);
- if (this.config.maxConcurrency) {
- session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => {
- if (err) {
- throw new Error("Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString());
- }
- });
- }
- session.unref();
- const destroySessionCb = () => {
- session.destroy();
- this.deleteSession(url3, session);
- };
- session.on("goaway", destroySessionCb);
- session.on("error", destroySessionCb);
- session.on("frameError", destroySessionCb);
- session.on("close", () => this.deleteSession(url3, session));
- if (connectionConfiguration.requestTimeout) {
- session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb);
- }
- const connectionPool = this.sessionCache.get(url3) || new NodeHttp2ConnectionPool;
- connectionPool.offerLast(session);
- this.sessionCache.set(url3, connectionPool);
- return session;
- }
- deleteSession(authority, session) {
- const existingConnectionPool = this.sessionCache.get(authority);
- if (!existingConnectionPool) {
- return;
- }
- if (!existingConnectionPool.contains(session)) {
- return;
- }
- existingConnectionPool.remove(session);
- this.sessionCache.set(authority, existingConnectionPool);
- }
- release(requestContext, session) {
- const cacheKey = this.getUrlString(requestContext);
- this.sessionCache.get(cacheKey)?.offerLast(session);
- }
- destroy() {
- for (const [key, connectionPool] of this.sessionCache) {
- for (const session of connectionPool) {
- if (!session.destroyed) {
- session.destroy();
- }
- connectionPool.remove(session);
- }
- this.sessionCache.delete(key);
- }
- }
- setMaxConcurrentStreams(maxConcurrentStreams) {
- if (maxConcurrentStreams && maxConcurrentStreams <= 0) {
- throw new RangeError("maxConcurrentStreams must be greater than zero.");
- }
- this.config.maxConcurrency = maxConcurrentStreams;
- }
- setDisableConcurrentStreams(disableConcurrentStreams) {
- this.config.disableConcurrency = disableConcurrentStreams;
- }
- getUrlString(request) {
- return request.destination.toString();
- }
- }
-
- class NodeHttp2Handler {
- config;
- configProvider;
- metadata = { handlerProtocol: "h2" };
- connectionManager = new NodeHttp2ConnectionManager({});
- static create(instanceOrOptions) {
- if (typeof instanceOrOptions?.handle === "function") {
- return instanceOrOptions;
- }
- return new NodeHttp2Handler(instanceOrOptions);
- }
- constructor(options2) {
- this.configProvider = new Promise((resolve9, reject) => {
- if (typeof options2 === "function") {
- options2().then((opts) => {
- resolve9(opts || {});
- }).catch(reject);
- } else {
- resolve9(options2 || {});
- }
- });
- }
- destroy() {
- this.connectionManager.destroy();
- }
- async handle(request, { abortSignal, requestTimeout } = {}) {
- if (!this.config) {
- this.config = await this.configProvider;
- this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false);
- if (this.config.maxConcurrentStreams) {
- this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams);
- }
- }
- const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config;
- const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout;
- return new Promise((_resolve, _reject) => {
- let fulfilled = false;
- let writeRequestBodyPromise = undefined;
- const resolve9 = async (arg) => {
- await writeRequestBodyPromise;
- _resolve(arg);
- };
- const reject = async (arg) => {
- await writeRequestBodyPromise;
- _reject(arg);
- };
- if (abortSignal?.aborted) {
- fulfilled = true;
- const abortError = buildAbortError(abortSignal);
- reject(abortError);
- return;
- }
- const { hostname: hostname2, method, port, protocol, query } = request;
- let auth = "";
- if (request.username != null || request.password != null) {
- const username = request.username ?? "";
- const password = request.password ?? "";
- auth = `${username}:${password}@`;
- }
- const authority = `${protocol}//${auth}${hostname2}${port ? `:${port}` : ""}`;
- const requestContext = { destination: new URL(authority) };
- const session = this.connectionManager.lease(requestContext, {
- requestTimeout: this.config?.sessionTimeout,
- disableConcurrentStreams: disableConcurrentStreams || false
- });
- const rejectWithDestroy = (err) => {
- if (disableConcurrentStreams) {
- this.destroySession(session);
- }
- fulfilled = true;
- reject(err);
- };
- const queryString = querystringBuilder.buildQueryString(query || {});
- let path8 = request.path;
- if (queryString) {
- path8 += `?${queryString}`;
- }
- if (request.fragment) {
- path8 += `#${request.fragment}`;
- }
- const req = session.request({
- ...request.headers,
- [http22.constants.HTTP2_HEADER_PATH]: path8,
- [http22.constants.HTTP2_HEADER_METHOD]: method
- });
- session.ref();
- req.on("response", (headers) => {
- const httpResponse = new protocolHttp.HttpResponse({
- statusCode: headers[":status"] || -1,
- headers: getTransformedHeaders(headers),
- body: req
- });
- fulfilled = true;
- resolve9({ response: httpResponse });
- if (disableConcurrentStreams) {
- session.close();
- this.connectionManager.deleteSession(authority, session);
- }
- });
- if (effectiveRequestTimeout) {
- req.setTimeout(effectiveRequestTimeout, () => {
- req.close();
- const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`);
- timeoutError.name = "TimeoutError";
- rejectWithDestroy(timeoutError);
- });
- }
- if (abortSignal) {
- const onAbort = () => {
- req.close();
- const abortError = buildAbortError(abortSignal);
- rejectWithDestroy(abortError);
- };
- if (typeof abortSignal.addEventListener === "function") {
- const signal = abortSignal;
- signal.addEventListener("abort", onAbort, { once: true });
- req.once("close", () => signal.removeEventListener("abort", onAbort));
- } else {
- abortSignal.onabort = onAbort;
- }
- }
- req.on("frameError", (type, code, id) => {
- rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`));
- });
- req.on("error", rejectWithDestroy);
- req.on("aborted", () => {
- rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`));
- });
- req.on("close", () => {
- session.unref();
- if (disableConcurrentStreams) {
- session.destroy();
- }
- if (!fulfilled) {
- rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response"));
- }
- });
- writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout);
- });
- }
- updateHttpClientConfig(key, value) {
- this.config = undefined;
- this.configProvider = this.configProvider.then((config2) => {
- return {
- ...config2,
- [key]: value
- };
- });
- }
- httpHandlerConfigs() {
- return this.config ?? {};
- }
- destroySession(session) {
- if (!session.destroyed) {
- session.destroy();
- }
- }
- }
-
- class Collector extends node_stream.Writable {
- bufferedBytes = [];
- _write(chunk, encoding, callback) {
- this.bufferedBytes.push(chunk);
- callback();
- }
- }
- var streamCollector = (stream4) => {
- if (isReadableStreamInstance(stream4)) {
- return collectReadableStream(stream4);
- }
- return new Promise((resolve9, reject) => {
- const collector = new Collector;
- stream4.pipe(collector);
- stream4.on("error", (err) => {
- collector.end();
- reject(err);
- });
- collector.on("error", reject);
- collector.on("finish", function() {
- const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes));
- resolve9(bytes);
- });
- });
- };
- var isReadableStreamInstance = (stream4) => typeof ReadableStream === "function" && stream4 instanceof ReadableStream;
- async function collectReadableStream(stream4) {
- const chunks = [];
- const reader = stream4.getReader();
- let isDone = false;
- let length = 0;
- while (!isDone) {
- const { done, value } = await reader.read();
- if (value) {
- chunks.push(value);
- length += value.length;
- }
- isDone = done;
- }
- const collected = new Uint8Array(length);
- let offset = 0;
- for (const chunk of chunks) {
- collected.set(chunk, offset);
- offset += chunk.length;
- }
- return collected;
- }
- exports.DEFAULT_REQUEST_TIMEOUT = DEFAULT_REQUEST_TIMEOUT;
- exports.NodeHttp2Handler = NodeHttp2Handler;
- exports.NodeHttpHandler = NodeHttpHandler;
- exports.streamCollector = streamCollector;
-});
-
-// node_modules/@aws-sdk/core/dist-cjs/submodules/client/index.js
-var require_client = __commonJS((exports) => {
- var state = {
- warningEmitted: false
- };
- var emitWarningIfUnsupportedVersion = (version2) => {
- if (version2 && !state.warningEmitted && parseInt(version2.substring(1, version2.indexOf("."))) < 20) {
- state.warningEmitted = true;
- process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will
-no longer support Node.js ${version2} in January 2026.
-
-To continue receiving updates to AWS services, bug fixes, and security
-updates please upgrade to a supported Node.js LTS version.
-
-More information can be found at: https://a.co/c895JFp`);
- }
- };
- function setCredentialFeature(credentials, feature, value) {
- if (!credentials.$source) {
- credentials.$source = {};
- }
- credentials.$source[feature] = value;
- return credentials;
- }
- function setFeature(context, feature, value) {
- if (!context.__aws_sdk_context) {
- context.__aws_sdk_context = {
- features: {}
- };
- } else if (!context.__aws_sdk_context.features) {
- context.__aws_sdk_context.features = {};
- }
- context.__aws_sdk_context.features[feature] = value;
- }
- function setTokenFeature(token, feature, value) {
- if (!token.$source) {
- token.$source = {};
- }
- token.$source[feature] = value;
- return token;
- }
- exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion;
- exports.setCredentialFeature = setCredentialFeature;
- exports.setFeature = setFeature;
- exports.setTokenFeature = setTokenFeature;
- exports.state = state;
-});
-
-// node_modules/@smithy/property-provider/dist-cjs/index.js
-var require_dist_cjs6 = __commonJS((exports) => {
- class ProviderError extends Error {
- name = "ProviderError";
- tryNextLink;
- constructor(message, options2 = true) {
- let logger;
- let tryNextLink = true;
- if (typeof options2 === "boolean") {
- logger = undefined;
- tryNextLink = options2;
- } else if (options2 != null && typeof options2 === "object") {
- logger = options2.logger;
- tryNextLink = options2.tryNextLink ?? true;
- }
- super(message);
- this.tryNextLink = tryNextLink;
- Object.setPrototypeOf(this, ProviderError.prototype);
- logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`);
- }
- static from(error40, options2 = true) {
- return Object.assign(new this(error40.message, options2), error40);
- }
- }
-
- class CredentialsProviderError extends ProviderError {
- name = "CredentialsProviderError";
- constructor(message, options2 = true) {
- super(message, options2);
- Object.setPrototypeOf(this, CredentialsProviderError.prototype);
- }
- }
-
- class TokenProviderError extends ProviderError {
- name = "TokenProviderError";
- constructor(message, options2 = true) {
- super(message, options2);
- Object.setPrototypeOf(this, TokenProviderError.prototype);
- }
- }
- var chain = (...providers) => async () => {
- if (providers.length === 0) {
- throw new ProviderError("No providers in chain");
- }
- let lastProviderError;
- for (const provider of providers) {
- try {
- const credentials = await provider();
- return credentials;
- } catch (err) {
- lastProviderError = err;
- if (err?.tryNextLink) {
- continue;
- }
- throw err;
- }
- }
- throw lastProviderError;
- };
- var fromStatic = (staticValue) => () => Promise.resolve(staticValue);
- var memoize2 = (provider, isExpired, requiresRefresh) => {
- let resolved;
- let pending;
- let hasResult;
- let isConstant = false;
- const coalesceProvider = async () => {
- if (!pending) {
- pending = provider();
- }
- try {
- resolved = await pending;
- hasResult = true;
- isConstant = false;
- } finally {
- pending = undefined;
- }
- return resolved;
- };
- if (isExpired === undefined) {
- return async (options2) => {
- if (!hasResult || options2?.forceRefresh) {
- resolved = await coalesceProvider();
- }
- return resolved;
- };
- }
- return async (options2) => {
- if (!hasResult || options2?.forceRefresh) {
- resolved = await coalesceProvider();
- }
- if (isConstant) {
- return resolved;
- }
- if (requiresRefresh && !requiresRefresh(resolved)) {
- isConstant = true;
- return resolved;
- }
- if (isExpired(resolved)) {
- await coalesceProvider();
- return resolved;
- }
- return resolved;
- };
- };
- exports.CredentialsProviderError = CredentialsProviderError;
- exports.ProviderError = ProviderError;
- exports.TokenProviderError = TokenProviderError;
- exports.chain = chain;
- exports.fromStatic = fromStatic;
- exports.memoize = memoize2;
-});
-
-// node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js
-var import_client, import_property_provider, ENV_KEY = "AWS_ACCESS_KEY_ID", ENV_SECRET = "AWS_SECRET_ACCESS_KEY", ENV_SESSION = "AWS_SESSION_TOKEN", ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION", ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE", ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID", fromEnv = (init) => async () => {
- init?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");
- const accessKeyId = process.env[ENV_KEY];
- const secretAccessKey = process.env[ENV_SECRET];
- const sessionToken = process.env[ENV_SESSION];
- const expiry = process.env[ENV_EXPIRATION];
- const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];
- const accountId = process.env[ENV_ACCOUNT_ID];
- if (accessKeyId && secretAccessKey) {
- const credentials = {
- accessKeyId,
- secretAccessKey,
- ...sessionToken && { sessionToken },
- ...expiry && { expiration: new Date(expiry) },
- ...credentialScope && { credentialScope },
- ...accountId && { accountId }
- };
- import_client.setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS", "g");
- return credentials;
- }
- throw new import_property_provider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init?.logger });
-};
-var init_fromEnv = __esm(() => {
- import_client = __toESM(require_client(), 1);
- import_property_provider = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-env/dist-es/index.js
-var exports_dist_es = {};
-__export(exports_dist_es, {
- fromEnv: () => fromEnv,
- ENV_SESSION: () => ENV_SESSION,
- ENV_SECRET: () => ENV_SECRET,
- ENV_KEY: () => ENV_KEY,
- ENV_EXPIRATION: () => ENV_EXPIRATION,
- ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE,
- ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID
-});
-var init_dist_es = __esm(() => {
- init_fromEnv();
-});
-
-// node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js
-var require_getHomeDir = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getHomeDir = undefined;
- var os_1 = __require("os");
- var path_1 = __require("path");
- var homeDirCache = {};
- var getHomeDirCacheKey = () => {
- if (process && process.geteuid) {
- return `${process.geteuid()}`;
- }
- return "DEFAULT";
- };
- var getHomeDir = () => {
- const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env;
- if (HOME)
- return HOME;
- if (USERPROFILE)
- return USERPROFILE;
- if (HOMEPATH)
- return `${HOMEDRIVE}${HOMEPATH}`;
- const homeDirCacheKey = getHomeDirCacheKey();
- if (!homeDirCache[homeDirCacheKey])
- homeDirCache[homeDirCacheKey] = (0, os_1.homedir)();
- return homeDirCache[homeDirCacheKey];
- };
- exports.getHomeDir = getHomeDir;
-});
-
-// node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js
-var require_getSSOTokenFilepath = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getSSOTokenFilepath = undefined;
- var crypto_1 = __require("crypto");
- var path_1 = __require("path");
- var getHomeDir_1 = require_getHomeDir();
- var getSSOTokenFilepath = (id) => {
- const hasher = (0, crypto_1.createHash)("sha1");
- const cacheName = hasher.update(id).digest("hex");
- return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`);
- };
- exports.getSSOTokenFilepath = getSSOTokenFilepath;
-});
-
-// node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js
-var require_getSSOTokenFromFile = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getSSOTokenFromFile = exports.tokenIntercept = undefined;
- var promises_1 = __require("fs/promises");
- var getSSOTokenFilepath_1 = require_getSSOTokenFilepath();
- exports.tokenIntercept = {};
- var getSSOTokenFromFile = async (id) => {
- if (exports.tokenIntercept[id]) {
- return exports.tokenIntercept[id];
- }
- const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id);
- const ssoTokenText = await (0, promises_1.readFile)(ssoTokenFilepath, "utf8");
- return JSON.parse(ssoTokenText);
- };
- exports.getSSOTokenFromFile = getSSOTokenFromFile;
-});
-
-// node_modules/@smithy/shared-ini-file-loader/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs7 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation) {
- HttpAuthLocation["HEADER"] = "header";
- HttpAuthLocation["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation) {
- HttpApiKeyAuthLocation["HEADER"] = "header";
- HttpApiKeyAuthLocation["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme) {
- EndpointURLScheme["HTTP"] = "http";
- EndpointURLScheme["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId) {
- AlgorithmId["MD5"] = "md5";
- AlgorithmId["CRC32"] = "crc32";
- AlgorithmId["CRC32C"] = "crc32c";
- AlgorithmId["SHA1"] = "sha1";
- AlgorithmId["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration = (runtimeConfig) => {
- return getChecksumConfiguration(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig = (config2) => {
- return resolveChecksumRuntimeConfig(config2);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition) {
- FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER";
- FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType) {
- IniSectionType["PROFILE"] = "profile";
- IniSectionType["SSO_SESSION"] = "sso-session";
- IniSectionType["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol) {
- RequestHandlerProtocol["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig;
-});
-
-// node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js
-var require_readFile = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.readFile = exports.fileIntercept = exports.filePromises = undefined;
- var promises_1 = __require("fs/promises");
- exports.filePromises = {};
- exports.fileIntercept = {};
- var readFile7 = (path8, options2) => {
- if (exports.fileIntercept[path8] !== undefined) {
- return exports.fileIntercept[path8];
- }
- if (!exports.filePromises[path8] || options2?.ignoreCache) {
- exports.filePromises[path8] = (0, promises_1.readFile)(path8, "utf8");
- }
- return exports.filePromises[path8];
- };
- exports.readFile = readFile7;
-});
-
-// node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js
-var require_dist_cjs8 = __commonJS((exports) => {
- var getHomeDir = require_getHomeDir();
- var getSSOTokenFilepath = require_getSSOTokenFilepath();
- var getSSOTokenFromFile = require_getSSOTokenFromFile();
- var path8 = __require("path");
- var types = require_dist_cjs7();
- var readFile7 = require_readFile();
- var ENV_PROFILE = "AWS_PROFILE";
- var DEFAULT_PROFILE = "default";
- var getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE;
- var CONFIG_PREFIX_SEPARATOR = ".";
- var getConfigData = (data) => Object.entries(data).filter(([key]) => {
- const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
- if (indexOfSeparator === -1) {
- return false;
- }
- return Object.values(types.IniSectionType).includes(key.substring(0, indexOfSeparator));
- }).reduce((acc, [key, value]) => {
- const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
- const updatedKey = key.substring(0, indexOfSeparator) === types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key;
- acc[updatedKey] = value;
- return acc;
- }, {
- ...data.default && { default: data.default }
- });
- var ENV_CONFIG_PATH = "AWS_CONFIG_FILE";
- var getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || path8.join(getHomeDir.getHomeDir(), ".aws", "config");
- var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE";
- var getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || path8.join(getHomeDir.getHomeDir(), ".aws", "credentials");
- var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/;
- var profileNameBlockList = ["__proto__", "profile __proto__"];
- var parseIni = (iniData) => {
- const map2 = {};
- let currentSection;
- let currentSubSection;
- for (const iniLine of iniData.split(/\r?\n/)) {
- const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim();
- const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]";
- if (isSection) {
- currentSection = undefined;
- currentSubSection = undefined;
- const sectionName = trimmedLine.substring(1, trimmedLine.length - 1);
- const matches = prefixKeyRegex.exec(sectionName);
- if (matches) {
- const [, prefix, , name] = matches;
- if (Object.values(types.IniSectionType).includes(prefix)) {
- currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR);
- }
- } else {
- currentSection = sectionName;
- }
- if (profileNameBlockList.includes(sectionName)) {
- throw new Error(`Found invalid profile name "${sectionName}"`);
- }
- } else if (currentSection) {
- const indexOfEqualsSign = trimmedLine.indexOf("=");
- if (![0, -1].includes(indexOfEqualsSign)) {
- const [name, value] = [
- trimmedLine.substring(0, indexOfEqualsSign).trim(),
- trimmedLine.substring(indexOfEqualsSign + 1).trim()
- ];
- if (value === "") {
- currentSubSection = name;
- } else {
- if (currentSubSection && iniLine.trimStart() === iniLine) {
- currentSubSection = undefined;
- }
- map2[currentSection] = map2[currentSection] || {};
- const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name;
- map2[currentSection][key] = value;
- }
- }
- }
- }
- return map2;
- };
- var swallowError$1 = () => ({});
- var loadSharedConfigFiles = async (init = {}) => {
- const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init;
- const homeDir = getHomeDir.getHomeDir();
- const relativeHomeDirPrefix = "~/";
- let resolvedFilepath = filepath;
- if (filepath.startsWith(relativeHomeDirPrefix)) {
- resolvedFilepath = path8.join(homeDir, filepath.slice(2));
- }
- let resolvedConfigFilepath = configFilepath;
- if (configFilepath.startsWith(relativeHomeDirPrefix)) {
- resolvedConfigFilepath = path8.join(homeDir, configFilepath.slice(2));
- }
- const parsedFiles = await Promise.all([
- readFile7.readFile(resolvedConfigFilepath, {
- ignoreCache: init.ignoreCache
- }).then(parseIni).then(getConfigData).catch(swallowError$1),
- readFile7.readFile(resolvedFilepath, {
- ignoreCache: init.ignoreCache
- }).then(parseIni).catch(swallowError$1)
- ]);
- return {
- configFile: parsedFiles[0],
- credentialsFile: parsedFiles[1]
- };
- };
- var getSsoSessionData = (data) => Object.entries(data).filter(([key]) => key.startsWith(types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {});
- var swallowError = () => ({});
- var loadSsoSessionData = async (init = {}) => readFile7.readFile(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError);
- var mergeConfigFiles = (...files) => {
- const merged = {};
- for (const file2 of files) {
- for (const [key, values] of Object.entries(file2)) {
- if (merged[key] !== undefined) {
- Object.assign(merged[key], values);
- } else {
- merged[key] = values;
- }
- }
- }
- return merged;
- };
- var parseKnownFiles = async (init) => {
- const parsedFiles = await loadSharedConfigFiles(init);
- return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile);
- };
- var externalDataInterceptor = {
- getFileRecord() {
- return readFile7.fileIntercept;
- },
- interceptFile(path9, contents) {
- readFile7.fileIntercept[path9] = Promise.resolve(contents);
- },
- getTokenRecord() {
- return getSSOTokenFromFile.tokenIntercept;
- },
- interceptToken(id, contents) {
- getSSOTokenFromFile.tokenIntercept[id] = contents;
- }
- };
- exports.getSSOTokenFromFile = getSSOTokenFromFile.getSSOTokenFromFile;
- exports.readFile = readFile7.readFile;
- exports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR;
- exports.DEFAULT_PROFILE = DEFAULT_PROFILE;
- exports.ENV_PROFILE = ENV_PROFILE;
- exports.externalDataInterceptor = externalDataInterceptor;
- exports.getProfileName = getProfileName;
- exports.loadSharedConfigFiles = loadSharedConfigFiles;
- exports.loadSsoSessionData = loadSsoSessionData;
- exports.parseKnownFiles = parseKnownFiles;
- Object.prototype.hasOwnProperty.call(getHomeDir, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: getHomeDir["__proto__"]
- });
- Object.keys(getHomeDir).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = getHomeDir[k];
- });
- Object.prototype.hasOwnProperty.call(getSSOTokenFilepath, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: getSSOTokenFilepath["__proto__"]
- });
- Object.keys(getSSOTokenFilepath).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = getSSOTokenFilepath[k];
- });
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js
-import { Buffer as Buffer7 } from "buffer";
-import { request } from "http";
-function httpRequest(options2) {
- return new Promise((resolve9, reject) => {
- const req = request({
- method: "GET",
- ...options2,
- hostname: options2.hostname?.replace(/^\[(.+)\]$/, "$1")
- });
- req.on("error", (err) => {
- reject(Object.assign(new import_property_provider2.ProviderError("Unable to connect to instance metadata service"), err));
- req.destroy();
- });
- req.on("timeout", () => {
- reject(new import_property_provider2.ProviderError("TimeoutError from instance metadata service"));
- req.destroy();
- });
- req.on("response", (res) => {
- const { statusCode = 400 } = res;
- if (statusCode < 200 || 300 <= statusCode) {
- reject(Object.assign(new import_property_provider2.ProviderError("Error response received from instance metadata service"), { statusCode }));
- req.destroy();
- }
- const chunks = [];
- res.on("data", (chunk) => {
- chunks.push(chunk);
- });
- res.on("end", () => {
- resolve9(Buffer7.concat(chunks));
- req.destroy();
- });
- });
- req.end();
- });
-}
-var import_property_provider2;
-var init_httpRequest = __esm(() => {
- import_property_provider2 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js
-var isImdsCredentials = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string", fromImdsCredentials = (creds) => ({
- accessKeyId: creds.AccessKeyId,
- secretAccessKey: creds.SecretAccessKey,
- sessionToken: creds.Token,
- expiration: new Date(creds.Expiration),
- ...creds.AccountId && { accountId: creds.AccountId }
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js
-var DEFAULT_TIMEOUT = 1000, DEFAULT_MAX_RETRIES = 0, providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT }) => ({ maxRetries, timeout });
-
-// node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js
-var retry = (toRetry, maxRetries) => {
- let promise2 = toRetry();
- for (let i2 = 0;i2 < maxRetries; i2++) {
- promise2 = promise2.catch(toRetry);
- }
- return promise2;
-};
-
-// node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js
-import { parse as parse7 } from "url";
-var import_property_provider3, ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI", ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN", fromContainerMetadata = (init = {}) => {
- const { timeout, maxRetries } = providerConfigFromInit(init);
- return () => retry(async () => {
- const requestOptions = await getCmdsUri({ logger: init.logger });
- const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions));
- if (!isImdsCredentials(credsResponse)) {
- throw new import_property_provider3.CredentialsProviderError("Invalid response received from instance metadata service.", {
- logger: init.logger
- });
- }
- return fromImdsCredentials(credsResponse);
- }, maxRetries);
-}, requestFromEcsImds = async (timeout, options2) => {
- if (process.env[ENV_CMDS_AUTH_TOKEN]) {
- options2.headers = {
- ...options2.headers,
- Authorization: process.env[ENV_CMDS_AUTH_TOKEN]
- };
- }
- const buffer = await httpRequest({
- ...options2,
- timeout
- });
- return buffer.toString();
-}, CMDS_IP = "169.254.170.2", GREENGRASS_HOSTS, GREENGRASS_PROTOCOLS, getCmdsUri = async ({ logger }) => {
- if (process.env[ENV_CMDS_RELATIVE_URI]) {
- return {
- hostname: CMDS_IP,
- path: process.env[ENV_CMDS_RELATIVE_URI]
- };
- }
- if (process.env[ENV_CMDS_FULL_URI]) {
- const parsed = parse7(process.env[ENV_CMDS_FULL_URI]);
- if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) {
- throw new import_property_provider3.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, {
- tryNextLink: false,
- logger
- });
- }
- if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) {
- throw new import_property_provider3.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, {
- tryNextLink: false,
- logger
- });
- }
- return {
- ...parsed,
- port: parsed.port ? parseInt(parsed.port, 10) : undefined
- };
- }
- throw new import_property_provider3.CredentialsProviderError("The container metadata credential provider cannot be used unless" + ` the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment` + " variable is set", {
- tryNextLink: false,
- logger
- });
-};
-var init_fromContainerMetadata = __esm(() => {
- init_httpRequest();
- import_property_provider3 = __toESM(require_dist_cjs6(), 1);
- GREENGRASS_HOSTS = {
- localhost: true,
- "127.0.0.1": true
- };
- GREENGRASS_PROTOCOLS = {
- "http:": true,
- "https:": true
- };
-});
-
-// node_modules/@smithy/node-config-provider/dist-cjs/index.js
-var require_dist_cjs9 = __commonJS((exports) => {
- var propertyProvider = require_dist_cjs6();
- var sharedIniFileLoader = require_dist_cjs8();
- function getSelectorName(functionString) {
- try {
- const constants4 = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? []));
- constants4.delete("CONFIG");
- constants4.delete("CONFIG_PREFIX_SEPARATOR");
- constants4.delete("ENV");
- return [...constants4].join(", ");
- } catch (e) {
- return functionString;
- }
- }
- var fromEnv3 = (envVarSelector, options2) => async () => {
- try {
- const config2 = envVarSelector(process.env, options2);
- if (config2 === undefined) {
- throw new Error;
- }
- return config2;
- } catch (e) {
- throw new propertyProvider.CredentialsProviderError(e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options2?.logger });
- }
- };
- var fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init } = {}) => async () => {
- const profile = sharedIniFileLoader.getProfileName(init);
- const { configFile, credentialsFile } = await sharedIniFileLoader.loadSharedConfigFiles(init);
- const profileFromCredentials = credentialsFile[profile] || {};
- const profileFromConfig = configFile[profile] || {};
- const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials };
- try {
- const cfgFile = preferredFile === "config" ? configFile : credentialsFile;
- const configValue = configSelector(mergedProfile, cfgFile);
- if (configValue === undefined) {
- throw new Error;
- }
- return configValue;
- } catch (e) {
- throw new propertyProvider.CredentialsProviderError(e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init.logger });
- }
- };
- var isFunction4 = (func) => typeof func === "function";
- var fromStatic = (defaultValue) => isFunction4(defaultValue) ? async () => await defaultValue() : propertyProvider.fromStatic(defaultValue);
- var loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => {
- const { signingName, logger } = configuration;
- const envOptions = { signingName, logger };
- return propertyProvider.memoize(propertyProvider.chain(fromEnv3(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue)));
- };
- exports.loadConfig = loadConfig;
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js
-var import_property_provider4, InstanceMetadataV1FallbackError;
-var init_InstanceMetadataV1FallbackError = __esm(() => {
- import_property_provider4 = __toESM(require_dist_cjs6(), 1);
- InstanceMetadataV1FallbackError = class InstanceMetadataV1FallbackError extends import_property_provider4.CredentialsProviderError {
- tryNextLink;
- name = "InstanceMetadataV1FallbackError";
- constructor(message, tryNextLink = true) {
- super(message, tryNextLink);
- this.tryNextLink = tryNextLink;
- Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype);
- }
- };
-});
-
-// node_modules/@smithy/querystring-parser/dist-cjs/index.js
-var require_dist_cjs10 = __commonJS((exports) => {
- function parseQueryString(querystring) {
- const query = {};
- querystring = querystring.replace(/^\?/, "");
- if (querystring) {
- for (const pair of querystring.split("&")) {
- let [key, value = null] = pair.split("=");
- key = decodeURIComponent(key);
- if (value) {
- value = decodeURIComponent(value);
- }
- if (!(key in query)) {
- query[key] = value;
- } else if (Array.isArray(query[key])) {
- query[key].push(value);
- } else {
- query[key] = [query[key], value];
- }
- }
- }
- return query;
- }
- exports.parseQueryString = parseQueryString;
-});
-
-// node_modules/@smithy/url-parser/dist-cjs/index.js
-var require_dist_cjs11 = __commonJS((exports) => {
- var querystringParser = require_dist_cjs10();
- var parseUrl2 = (url3) => {
- if (typeof url3 === "string") {
- return parseUrl2(new URL(url3));
- }
- const { hostname: hostname2, pathname, port, protocol, search } = url3;
- let query;
- if (search) {
- query = querystringParser.parseQueryString(search);
- }
- return {
- hostname: hostname2,
- port: port ? parseInt(port) : undefined,
- protocol,
- path: pathname,
- query
- };
- };
- exports.parseUrl = parseUrl2;
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js
-var Endpoint;
-var init_Endpoint = __esm(() => {
- (function(Endpoint2) {
- Endpoint2["IPv4"] = "http://169.254.169.254";
- Endpoint2["IPv6"] = "http://[fd00:ec2::254]";
- })(Endpoint || (Endpoint = {}));
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js
-var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT", CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint", ENDPOINT_CONFIG_OPTIONS;
-var init_EndpointConfigOptions = __esm(() => {
- ENDPOINT_CONFIG_OPTIONS = {
- environmentVariableSelector: (env4) => env4[ENV_ENDPOINT_NAME],
- configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME],
- default: undefined
- };
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js
-var EndpointMode;
-var init_EndpointMode = __esm(() => {
- (function(EndpointMode2) {
- EndpointMode2["IPv4"] = "IPv4";
- EndpointMode2["IPv6"] = "IPv6";
- })(EndpointMode || (EndpointMode = {}));
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js
-var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE", CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode", ENDPOINT_MODE_CONFIG_OPTIONS;
-var init_EndpointModeConfigOptions = __esm(() => {
- init_EndpointMode();
- ENDPOINT_MODE_CONFIG_OPTIONS = {
- environmentVariableSelector: (env4) => env4[ENV_ENDPOINT_MODE_NAME],
- configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME],
- default: EndpointMode.IPv4
- };
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js
-var import_node_config_provider, import_url_parser, getInstanceMetadataEndpoint = async () => import_url_parser.parseUrl(await getFromEndpointConfig() || await getFromEndpointModeConfig()), getFromEndpointConfig = async () => import_node_config_provider.loadConfig(ENDPOINT_CONFIG_OPTIONS)(), getFromEndpointModeConfig = async () => {
- const endpointMode = await import_node_config_provider.loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)();
- switch (endpointMode) {
- case EndpointMode.IPv4:
- return Endpoint.IPv4;
- case EndpointMode.IPv6:
- return Endpoint.IPv6;
- default:
- throw new Error(`Unsupported endpoint mode: ${endpointMode}.` + ` Select from ${Object.values(EndpointMode)}`);
- }
-};
-var init_getInstanceMetadataEndpoint = __esm(() => {
- init_Endpoint();
- init_EndpointConfigOptions();
- init_EndpointMode();
- init_EndpointModeConfigOptions();
- import_node_config_provider = __toESM(require_dist_cjs9(), 1);
- import_url_parser = __toESM(require_dist_cjs11(), 1);
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js
-var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS, STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS, STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html", getExtendedInstanceMetadataCredentials = (credentials, logger) => {
- const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);
- const newExpiration = new Date(Date.now() + refreshInterval * 1000);
- logger.warn("Attempting credential expiration extension due to a credential service availability issue. A refresh of these " + `credentials will be attempted after ${new Date(newExpiration)}.
-For more information, please visit: ` + STATIC_STABILITY_DOC_URL);
- const originalExpiration = credentials.originalExpiration ?? credentials.expiration;
- return {
- ...credentials,
- ...originalExpiration ? { originalExpiration } : {},
- expiration: newExpiration
- };
-};
-var init_getExtendedInstanceMetadataCredentials = __esm(() => {
- STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;
- STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js
-var staticStabilityProvider = (provider, options2 = {}) => {
- const logger = options2?.logger || console;
- let pastCredentials;
- return async () => {
- let credentials;
- try {
- credentials = await provider();
- if (credentials.expiration && credentials.expiration.getTime() < Date.now()) {
- credentials = getExtendedInstanceMetadataCredentials(credentials, logger);
- }
- } catch (e) {
- if (pastCredentials) {
- logger.warn("Credential renew failed: ", e);
- credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger);
- } else {
- throw e;
- }
- }
- pastCredentials = credentials;
- return credentials;
- };
-};
-var init_staticStabilityProvider = __esm(() => {
- init_getExtendedInstanceMetadataCredentials();
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js
-var import_node_config_provider2, import_property_provider5, IMDS_PATH = "/latest/meta-data/iam/security-credentials/", IMDS_TOKEN_PATH = "/latest/api/token", AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED", PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled", X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token", fromInstanceMetadata = (init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }), getInstanceMetadataProvider = (init = {}) => {
- let disableFetchToken = false;
- const { logger, profile } = init;
- const { timeout, maxRetries } = providerConfigFromInit(init);
- const getCredentials = async (maxRetries2, options2) => {
- const isImdsV1Fallback = disableFetchToken || options2.headers?.[X_AWS_EC2_METADATA_TOKEN] == null;
- if (isImdsV1Fallback) {
- let fallbackBlockedFromProfile = false;
- let fallbackBlockedFromProcessEnv = false;
- const configValue = await import_node_config_provider2.loadConfig({
- environmentVariableSelector: (env4) => {
- const envValue = env4[AWS_EC2_METADATA_V1_DISABLED];
- fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false";
- if (envValue === undefined) {
- throw new import_property_provider5.CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init.logger });
- }
- return fallbackBlockedFromProcessEnv;
- },
- configFileSelector: (profile2) => {
- const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED];
- fallbackBlockedFromProfile = !!profileValue && profileValue !== "false";
- return fallbackBlockedFromProfile;
- },
- default: false
- }, {
- profile
- })();
- if (init.ec2MetadataV1Disabled || configValue) {
- const causes = [];
- if (init.ec2MetadataV1Disabled)
- causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");
- if (fallbackBlockedFromProfile)
- causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`);
- if (fallbackBlockedFromProcessEnv)
- causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`);
- throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`);
- }
- }
- const imdsProfile = (await retry(async () => {
- let profile2;
- try {
- profile2 = await getProfile(options2);
- } catch (err) {
- if (err.statusCode === 401) {
- disableFetchToken = false;
- }
- throw err;
- }
- return profile2;
- }, maxRetries2)).trim();
- return retry(async () => {
- let creds;
- try {
- creds = await getCredentialsFromProfile(imdsProfile, options2, init);
- } catch (err) {
- if (err.statusCode === 401) {
- disableFetchToken = false;
- }
- throw err;
- }
- return creds;
- }, maxRetries2);
- };
- return async () => {
- const endpoint = await getInstanceMetadataEndpoint();
- if (disableFetchToken) {
- logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)");
- return getCredentials(maxRetries, { ...endpoint, timeout });
- } else {
- let token;
- try {
- token = (await getMetadataToken({ ...endpoint, timeout })).toString();
- } catch (error40) {
- if (error40?.statusCode === 400) {
- throw Object.assign(error40, {
- message: "EC2 Metadata token request returned error"
- });
- } else if (error40.message === "TimeoutError" || [403, 404, 405].includes(error40.statusCode)) {
- disableFetchToken = true;
- }
- logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)");
- return getCredentials(maxRetries, { ...endpoint, timeout });
- }
- return getCredentials(maxRetries, {
- ...endpoint,
- headers: {
- [X_AWS_EC2_METADATA_TOKEN]: token
- },
- timeout
- });
- }
- };
-}, getMetadataToken = async (options2) => httpRequest({
- ...options2,
- path: IMDS_TOKEN_PATH,
- method: "PUT",
- headers: {
- "x-aws-ec2-metadata-token-ttl-seconds": "21600"
- }
-}), getProfile = async (options2) => (await httpRequest({ ...options2, path: IMDS_PATH })).toString(), getCredentialsFromProfile = async (profile, options2, init) => {
- const credentialsResponse = JSON.parse((await httpRequest({
- ...options2,
- path: IMDS_PATH + profile
- })).toString());
- if (!isImdsCredentials(credentialsResponse)) {
- throw new import_property_provider5.CredentialsProviderError("Invalid response received from instance metadata service.", {
- logger: init.logger
- });
- }
- return fromImdsCredentials(credentialsResponse);
-};
-var init_fromInstanceMetadata = __esm(() => {
- init_InstanceMetadataV1FallbackError();
- init_httpRequest();
- init_getInstanceMetadataEndpoint();
- init_staticStabilityProvider();
- import_node_config_provider2 = __toESM(require_dist_cjs9(), 1);
- import_property_provider5 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@smithy/credential-provider-imds/dist-es/types.js
-var init_types3 = () => {};
-
-// node_modules/@smithy/credential-provider-imds/dist-es/index.js
-var exports_dist_es2 = {};
-__export(exports_dist_es2, {
- providerConfigFromInit: () => providerConfigFromInit,
- httpRequest: () => httpRequest,
- getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint,
- fromInstanceMetadata: () => fromInstanceMetadata,
- fromContainerMetadata: () => fromContainerMetadata,
- Endpoint: () => Endpoint,
- ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI,
- ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI,
- ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN,
- DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
- DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES
-});
-var init_dist_es2 = __esm(() => {
- init_httpRequest();
- init_getInstanceMetadataEndpoint();
- init_Endpoint();
- init_fromContainerMetadata();
- init_fromInstanceMetadata();
- init_types3();
-});
-
-// node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js
-var import_property_provider6, ECS_CONTAINER_HOST = "169.254.170.2", EKS_CONTAINER_HOST_IPv4 = "169.254.170.23", EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]", checkUrl = (url3, logger) => {
- if (url3.protocol === "https:") {
- return;
- }
- if (url3.hostname === ECS_CONTAINER_HOST || url3.hostname === EKS_CONTAINER_HOST_IPv4 || url3.hostname === EKS_CONTAINER_HOST_IPv6) {
- return;
- }
- if (url3.hostname.includes("[")) {
- if (url3.hostname === "[::1]" || url3.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") {
- return;
- }
- } else {
- if (url3.hostname === "localhost") {
- return;
- }
- const ipComponents = url3.hostname.split(".");
- const inRange2 = (component) => {
- const num = parseInt(component, 10);
- return 0 <= num && num <= 255;
- };
- if (ipComponents[0] === "127" && inRange2(ipComponents[1]) && inRange2(ipComponents[2]) && inRange2(ipComponents[3]) && ipComponents.length === 4) {
- return;
- }
- }
- throw new import_property_provider6.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:
- - loopback CIDR 127.0.0.0/8 or [::1/128]
- - ECS container host 169.254.170.2
- - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger });
-};
-var init_checkUrl = __esm(() => {
- import_property_provider6 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
-var init_extensions = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/abort.js
-var init_abort2 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/auth/auth.js
-var HttpAuthLocation;
-var init_auth = __esm(() => {
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(HttpAuthLocation || (HttpAuthLocation = {}));
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
-var HttpApiKeyAuthLocation;
-var init_HttpApiKeyAuth = __esm(() => {
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {}));
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js
-var init_HttpAuthScheme = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js
-var init_HttpAuthSchemeProvider = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/auth/HttpSigner.js
-var init_HttpSigner = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js
-var init_IdentityProviderConfig = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/auth/index.js
-var init_auth2 = __esm(() => {
- init_auth();
- init_HttpApiKeyAuth();
- init_HttpAuthScheme();
- init_HttpAuthSchemeProvider();
- init_HttpSigner();
- init_IdentityProviderConfig();
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js
-var init_blob_payload_input_types = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/checksum.js
-var init_checksum = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/client.js
-var init_client = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/command.js
-var init_command3 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/connection/config.js
-var init_config2 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/connection/manager.js
-var init_manager = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/connection/pool.js
-var init_pool = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/connection/index.js
-var init_connection = __esm(() => {
- init_config2();
- init_manager();
- init_pool();
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/crypto.js
-var init_crypto2 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/encode.js
-var init_encode = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/endpoint.js
-var EndpointURLScheme;
-var init_endpoint = __esm(() => {
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(EndpointURLScheme || (EndpointURLScheme = {}));
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js
-var init_EndpointRuleObject = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js
-var init_ErrorRuleObject = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js
-var init_RuleSetObject = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/endpoints/shared.js
-var init_shared3 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js
-var init_TreeRuleObject = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/endpoints/index.js
-var init_endpoints = __esm(() => {
- init_EndpointRuleObject();
- init_ErrorRuleObject();
- init_RuleSetObject();
- init_shared3();
- init_TreeRuleObject();
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/eventStream.js
-var init_eventStream = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/extensions/checksum.js
-var AlgorithmId;
-var init_checksum2 = __esm(() => {
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(AlgorithmId || (AlgorithmId = {}));
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js
-var init_defaultClientConfiguration = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js
-var init_defaultExtensionConfiguration = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/extensions/index.js
-var init_extensions2 = __esm(() => {
- init_checksum2();
- init_defaultClientConfiguration();
- init_defaultExtensionConfiguration();
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/feature-ids.js
-var init_feature_ids = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/http.js
-var FieldPosition;
-var init_http2 = __esm(() => {
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(FieldPosition || (FieldPosition = {}));
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js
-var init_httpHandlerInitialization = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js
-var init_apiKeyIdentity = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js
-var init_awsCredentialIdentity = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/identity/identity.js
-var init_identity2 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js
-var init_tokenIdentity = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/identity/index.js
-var init_identity3 = __esm(() => {
- init_apiKeyIdentity();
- init_awsCredentialIdentity();
- init_identity2();
- init_tokenIdentity();
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/logger.js
-var init_logger = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/middleware.js
-var SMITHY_CONTEXT_KEY = "__smithy_context";
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/pagination.js
-var init_pagination2 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/profile.js
-var IniSectionType;
-var init_profile = __esm(() => {
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(IniSectionType || (IniSectionType = {}));
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/response.js
-var init_response = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/retry.js
-var init_retry = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/schema/schema.js
-var init_schema = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/schema/traits.js
-var init_traits = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/schema/schema-deprecated.js
-var init_schema_deprecated = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/schema/sentinels.js
-var init_sentinels = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/schema/static-schemas.js
-var init_static_schemas = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/serde.js
-var init_serde = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/shapes.js
-var init_shapes = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/signature.js
-var init_signature = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/stream.js
-var init_stream2 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js
-var init_streaming_blob_common_types = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js
-var init_streaming_blob_payload_input_types = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js
-var init_streaming_blob_payload_output_types = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/transfer.js
-var RequestHandlerProtocol;
-var init_transfer = __esm(() => {
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(RequestHandlerProtocol || (RequestHandlerProtocol = {}));
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js
-var init_client_payload_blob_type_narrow = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/transform/mutable.js
-var init_mutable = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/transform/no-undefined.js
-var init_no_undefined = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/transform/type-transform.js
-var init_type_transform = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/uri.js
-var init_uri = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/util.js
-var init_util3 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/waiter.js
-var init_waiter = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-es/index.js
-var init_dist_es3 = __esm(() => {
- init_abort2();
- init_auth2();
- init_blob_payload_input_types();
- init_checksum();
- init_client();
- init_command3();
- init_connection();
- init_crypto2();
- init_encode();
- init_endpoint();
- init_endpoints();
- init_eventStream();
- init_extensions2();
- init_feature_ids();
- init_http2();
- init_httpHandlerInitialization();
- init_identity3();
- init_logger();
- init_pagination2();
- init_profile();
- init_response();
- init_retry();
- init_schema();
- init_traits();
- init_schema_deprecated();
- init_sentinels();
- init_static_schemas();
- init_serde();
- init_shapes();
- init_signature();
- init_stream2();
- init_streaming_blob_common_types();
- init_streaming_blob_payload_input_types();
- init_streaming_blob_payload_output_types();
- init_transfer();
- init_client_payload_blob_type_narrow();
- init_mutable();
- init_no_undefined();
- init_type_transform();
- init_uri();
- init_util3();
- init_waiter();
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/Field.js
-var init_Field = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
-var init_httpHandler = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
-class HttpRequest {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest.clone(this);
- }
-}
-function cloneQuery(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
-}
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/types.js
-var init_types4 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/index.js
-var init_dist_es4 = __esm(() => {
- init_extensions();
- init_Field();
- init_httpHandler();
- init_types4();
-});
-
-// node_modules/@smithy/middleware-stack/dist-cjs/index.js
-var require_dist_cjs12 = __commonJS((exports) => {
- var getAllAliases = (name, aliases) => {
- const _aliases = [];
- if (name) {
- _aliases.push(name);
- }
- if (aliases) {
- for (const alias of aliases) {
- _aliases.push(alias);
- }
- }
- return _aliases;
- };
- var getMiddlewareNameWithAliases = (name, aliases) => {
- return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`;
- };
- var constructStack = () => {
- let absoluteEntries = [];
- let relativeEntries = [];
- let identifyOnResolve = false;
- const entriesNameSet = new Set;
- const sort = (entries) => entries.sort((a2, b) => stepWeights[b.step] - stepWeights[a2.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a2.priority || "normal"]);
- const removeByName = (toRemove) => {
- let isRemoved = false;
- const filterCb = (entry) => {
- const aliases = getAllAliases(entry.name, entry.aliases);
- if (aliases.includes(toRemove)) {
- isRemoved = true;
- for (const alias of aliases) {
- entriesNameSet.delete(alias);
- }
- return false;
- }
- return true;
- };
- absoluteEntries = absoluteEntries.filter(filterCb);
- relativeEntries = relativeEntries.filter(filterCb);
- return isRemoved;
- };
- const removeByReference = (toRemove) => {
- let isRemoved = false;
- const filterCb = (entry) => {
- if (entry.middleware === toRemove) {
- isRemoved = true;
- for (const alias of getAllAliases(entry.name, entry.aliases)) {
- entriesNameSet.delete(alias);
- }
- return false;
- }
- return true;
- };
- absoluteEntries = absoluteEntries.filter(filterCb);
- relativeEntries = relativeEntries.filter(filterCb);
- return isRemoved;
- };
- const cloneTo = (toStack) => {
- absoluteEntries.forEach((entry) => {
- toStack.add(entry.middleware, { ...entry });
- });
- relativeEntries.forEach((entry) => {
- toStack.addRelativeTo(entry.middleware, { ...entry });
- });
- toStack.identifyOnResolve?.(stack.identifyOnResolve());
- return toStack;
- };
- const expandRelativeMiddlewareList = (from) => {
- const expandedMiddlewareList = [];
- from.before.forEach((entry) => {
- if (entry.before.length === 0 && entry.after.length === 0) {
- expandedMiddlewareList.push(entry);
- } else {
- expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
- }
- });
- expandedMiddlewareList.push(from);
- from.after.reverse().forEach((entry) => {
- if (entry.before.length === 0 && entry.after.length === 0) {
- expandedMiddlewareList.push(entry);
- } else {
- expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
- }
- });
- return expandedMiddlewareList;
- };
- const getMiddlewareList = (debug2 = false) => {
- const normalizedAbsoluteEntries = [];
- const normalizedRelativeEntries = [];
- const normalizedEntriesNameMap = {};
- absoluteEntries.forEach((entry) => {
- const normalizedEntry = {
- ...entry,
- before: [],
- after: []
- };
- for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
- normalizedEntriesNameMap[alias] = normalizedEntry;
- }
- normalizedAbsoluteEntries.push(normalizedEntry);
- });
- relativeEntries.forEach((entry) => {
- const normalizedEntry = {
- ...entry,
- before: [],
- after: []
- };
- for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
- normalizedEntriesNameMap[alias] = normalizedEntry;
- }
- normalizedRelativeEntries.push(normalizedEntry);
- });
- normalizedRelativeEntries.forEach((entry) => {
- if (entry.toMiddleware) {
- const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware];
- if (toMiddleware === undefined) {
- if (debug2) {
- return;
- }
- throw new Error(`${entry.toMiddleware} is not found when adding ` + `${getMiddlewareNameWithAliases(entry.name, entry.aliases)} ` + `middleware ${entry.relation} ${entry.toMiddleware}`);
- }
- if (entry.relation === "after") {
- toMiddleware.after.push(entry);
- }
- if (entry.relation === "before") {
- toMiddleware.before.push(entry);
- }
- }
- });
- const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => {
- wholeList.push(...expandedMiddlewareList);
- return wholeList;
- }, []);
- return mainChain;
- };
- const stack = {
- add: (middleware2, options2 = {}) => {
- const { name, override, aliases: _aliases } = options2;
- const entry = {
- step: "initialize",
- priority: "normal",
- middleware: middleware2,
- ...options2
- };
- const aliases = getAllAliases(name, _aliases);
- if (aliases.length > 0) {
- if (aliases.some((alias) => entriesNameSet.has(alias))) {
- if (!override)
- throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
- for (const alias of aliases) {
- const toOverrideIndex = absoluteEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a2) => a2 === alias));
- if (toOverrideIndex === -1) {
- continue;
- }
- const toOverride = absoluteEntries[toOverrideIndex];
- if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) {
- throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ` + `${toOverride.priority} priority in ${toOverride.step} step cannot ` + `be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ` + `${entry.priority} priority in ${entry.step} step.`);
- }
- absoluteEntries.splice(toOverrideIndex, 1);
- }
- }
- for (const alias of aliases) {
- entriesNameSet.add(alias);
- }
- }
- absoluteEntries.push(entry);
- },
- addRelativeTo: (middleware2, options2) => {
- const { name, override, aliases: _aliases } = options2;
- const entry = {
- middleware: middleware2,
- ...options2
- };
- const aliases = getAllAliases(name, _aliases);
- if (aliases.length > 0) {
- if (aliases.some((alias) => entriesNameSet.has(alias))) {
- if (!override)
- throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
- for (const alias of aliases) {
- const toOverrideIndex = relativeEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a2) => a2 === alias));
- if (toOverrideIndex === -1) {
- continue;
- }
- const toOverride = relativeEntries[toOverrideIndex];
- if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) {
- throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ` + `${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden ` + `by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} ` + `"${entry.toMiddleware}" middleware.`);
- }
- relativeEntries.splice(toOverrideIndex, 1);
- }
- }
- for (const alias of aliases) {
- entriesNameSet.add(alias);
- }
- }
- relativeEntries.push(entry);
- },
- clone: () => cloneTo(constructStack()),
- use: (plugin) => {
- plugin.applyToStack(stack);
- },
- remove: (toRemove) => {
- if (typeof toRemove === "string")
- return removeByName(toRemove);
- else
- return removeByReference(toRemove);
- },
- removeByTag: (toRemove) => {
- let isRemoved = false;
- const filterCb = (entry) => {
- const { tags, name, aliases: _aliases } = entry;
- if (tags && tags.includes(toRemove)) {
- const aliases = getAllAliases(name, _aliases);
- for (const alias of aliases) {
- entriesNameSet.delete(alias);
- }
- isRemoved = true;
- return false;
- }
- return true;
- };
- absoluteEntries = absoluteEntries.filter(filterCb);
- relativeEntries = relativeEntries.filter(filterCb);
- return isRemoved;
- },
- concat: (from) => {
- const cloned = cloneTo(constructStack());
- cloned.use(from);
- cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false));
- return cloned;
- },
- applyToStack: cloneTo,
- identify: () => {
- return getMiddlewareList(true).map((mw) => {
- const step = mw.step ?? mw.relation + " " + mw.toMiddleware;
- return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step;
- });
- },
- identifyOnResolve(toggle) {
- if (typeof toggle === "boolean")
- identifyOnResolve = toggle;
- return identifyOnResolve;
- },
- resolve: (handler, context) => {
- for (const middleware2 of getMiddlewareList().map((entry) => entry.middleware).reverse()) {
- handler = middleware2(handler, context);
- }
- if (identifyOnResolve) {
- console.log(stack.identify());
- }
- return handler;
- }
- };
- return stack;
- };
- var stepWeights = {
- initialize: 5,
- serialize: 4,
- build: 3,
- finalizeRequest: 2,
- deserialize: 1
- };
- var priorityWeights = {
- high: 3,
- normal: 2,
- low: 1
- };
- exports.constructStack = constructStack;
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/client.js
-class Client {
- config;
- middlewareStack = import_middleware_stack.constructStack();
- initConfig;
- handlers;
- constructor(config3) {
- this.config = config3;
- const { protocol, protocolSettings } = config3;
- if (protocolSettings) {
- if (typeof protocol === "function") {
- config3.protocol = new protocol(protocolSettings);
- }
- }
- }
- send(command2, optionsOrCb, cb) {
- const options2 = typeof optionsOrCb !== "function" ? optionsOrCb : undefined;
- const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
- const useHandlerCache = options2 === undefined && this.config.cacheMiddleware === true;
- let handler;
- if (useHandlerCache) {
- if (!this.handlers) {
- this.handlers = new WeakMap;
- }
- const handlers = this.handlers;
- if (handlers.has(command2.constructor)) {
- handler = handlers.get(command2.constructor);
- } else {
- handler = command2.resolveMiddleware(this.middlewareStack, this.config, options2);
- handlers.set(command2.constructor, handler);
- }
- } else {
- delete this.handlers;
- handler = command2.resolveMiddleware(this.middlewareStack, this.config, options2);
- }
- if (callback) {
- handler(command2).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => {});
- } else {
- return handler(command2).then((result) => result.output);
- }
- }
- destroy() {
- this.config?.requestHandler?.destroy?.();
- delete this.handlers;
- }
-}
-var import_middleware_stack;
-var init_client2 = __esm(() => {
- import_middleware_stack = __toESM(require_dist_cjs12(), 1);
-});
-
-// node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
-var require_dist_cjs13 = __commonJS((exports) => {
- var isArrayBuffer3 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
- exports.isArrayBuffer = isArrayBuffer3;
-});
-
-// node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
-var require_dist_cjs14 = __commonJS((exports) => {
- var isArrayBuffer3 = require_dist_cjs13();
- var buffer = __require("buffer");
- var fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
- if (!isArrayBuffer3.isArrayBuffer(input)) {
- throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
- }
- return buffer.Buffer.from(input, offset, length);
- };
- var fromString = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input);
- };
- exports.fromArrayBuffer = fromArrayBuffer;
- exports.fromString = fromString;
-});
-
-// node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js
-var require_fromBase64 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.fromBase64 = undefined;
- var util_buffer_from_1 = require_dist_cjs14();
- var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
- var fromBase64 = (input) => {
- if (input.length * 3 % 4 !== 0) {
- throw new TypeError(`Incorrect padding on base64 string.`);
- }
- if (!BASE64_REGEX.exec(input)) {
- throw new TypeError(`Invalid base64 string.`);
- }
- const buffer = (0, util_buffer_from_1.fromString)(input, "base64");
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
- };
- exports.fromBase64 = fromBase64;
-});
-
-// node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
-var require_dist_cjs15 = __commonJS((exports) => {
- var isArrayBuffer3 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
- exports.isArrayBuffer = isArrayBuffer3;
-});
-
-// node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
-var require_dist_cjs16 = __commonJS((exports) => {
- var isArrayBuffer3 = require_dist_cjs15();
- var buffer = __require("buffer");
- var fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
- if (!isArrayBuffer3.isArrayBuffer(input)) {
- throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
- }
- return buffer.Buffer.from(input, offset, length);
- };
- var fromString = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input);
- };
- exports.fromArrayBuffer = fromArrayBuffer;
- exports.fromString = fromString;
-});
-
-// node_modules/@smithy/util-utf8/dist-cjs/index.js
-var require_dist_cjs17 = __commonJS((exports) => {
- var utilBufferFrom = require_dist_cjs16();
- var fromUtf8 = (input) => {
- const buf = utilBufferFrom.fromString(input, "utf8");
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
- };
- var toUint8Array = (data) => {
- if (typeof data === "string") {
- return fromUtf8(data);
- }
- if (ArrayBuffer.isView(data)) {
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
- }
- return new Uint8Array(data);
- };
- var toUtf8 = (input) => {
- if (typeof input === "string") {
- return input;
- }
- if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
- throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
- }
- return utilBufferFrom.fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
- };
- exports.fromUtf8 = fromUtf8;
- exports.toUint8Array = toUint8Array;
- exports.toUtf8 = toUtf8;
-});
-
-// node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/toBase64.js
-var require_toBase64 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.toBase64 = undefined;
- var util_buffer_from_1 = require_dist_cjs14();
- var util_utf8_1 = require_dist_cjs17();
- var toBase64 = (_input) => {
- let input;
- if (typeof _input === "string") {
- input = (0, util_utf8_1.fromUtf8)(_input);
- } else {
- input = _input;
- }
- if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
- throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
- }
- return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64");
- };
- exports.toBase64 = toBase64;
-});
-
-// node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/index.js
-var require_dist_cjs18 = __commonJS((exports) => {
- var fromBase64 = require_fromBase64();
- var toBase64 = require_toBase64();
- Object.prototype.hasOwnProperty.call(fromBase64, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: fromBase64["__proto__"]
- });
- Object.keys(fromBase64).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = fromBase64[k];
- });
- Object.prototype.hasOwnProperty.call(toBase64, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: toBase64["__proto__"]
- });
- Object.keys(toBase64).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = toBase64[k];
- });
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js
-var require_ChecksumStream = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ChecksumStream = undefined;
- var util_base64_1 = require_dist_cjs18();
- var stream_1 = __require("stream");
-
- class ChecksumStream extends stream_1.Duplex {
- expectedChecksum;
- checksumSourceLocation;
- checksum;
- source;
- base64Encoder;
- pendingCallback = null;
- constructor({ expectedChecksum, checksum: checksum2, source, checksumSourceLocation, base64Encoder }) {
- super();
- if (typeof source.pipe === "function") {
- this.source = source;
- } else {
- throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`);
- }
- this.base64Encoder = base64Encoder ?? util_base64_1.toBase64;
- this.expectedChecksum = expectedChecksum;
- this.checksum = checksum2;
- this.checksumSourceLocation = checksumSourceLocation;
- this.source.pipe(this);
- }
- _read(size) {
- if (this.pendingCallback) {
- const callback = this.pendingCallback;
- this.pendingCallback = null;
- callback();
- }
- }
- _write(chunk, encoding, callback) {
- try {
- this.checksum.update(chunk);
- const canPushMore = this.push(chunk);
- if (!canPushMore) {
- this.pendingCallback = callback;
- return;
- }
- } catch (e) {
- return callback(e);
- }
- return callback();
- }
- async _final(callback) {
- try {
- const digest = await this.checksum.digest();
- const received = this.base64Encoder(digest);
- if (this.expectedChecksum !== received) {
- return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + ` in response header "${this.checksumSourceLocation}".`));
- }
- } catch (e) {
- return callback(e);
- }
- this.push(null);
- return callback();
- }
- }
- exports.ChecksumStream = ChecksumStream;
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js
-var require_stream_type_check = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isBlob = exports.isReadableStream = undefined;
- var isReadableStream4 = (stream5) => typeof ReadableStream === "function" && (stream5?.constructor?.name === ReadableStream.name || stream5 instanceof ReadableStream);
- exports.isReadableStream = isReadableStream4;
- var isBlob2 = (blob) => {
- return typeof Blob === "function" && (blob?.constructor?.name === Blob.name || blob instanceof Blob);
- };
- exports.isBlob = isBlob2;
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js
-var require_ChecksumStream_browser = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ChecksumStream = undefined;
- var ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function() {};
-
- class ChecksumStream extends ReadableStreamRef {
- }
- exports.ChecksumStream = ChecksumStream;
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js
-var require_createChecksumStream_browser = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.createChecksumStream = undefined;
- var util_base64_1 = require_dist_cjs18();
- var stream_type_check_1 = require_stream_type_check();
- var ChecksumStream_browser_1 = require_ChecksumStream_browser();
- var createChecksumStream = ({ expectedChecksum, checksum: checksum2, source, checksumSourceLocation, base64Encoder }) => {
- if (!(0, stream_type_check_1.isReadableStream)(source)) {
- throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`);
- }
- const encoder = base64Encoder ?? util_base64_1.toBase64;
- if (typeof TransformStream !== "function") {
- throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");
- }
- const transform2 = new TransformStream({
- start() {},
- async transform(chunk, controller) {
- checksum2.update(chunk);
- controller.enqueue(chunk);
- },
- async flush(controller) {
- const digest = await checksum2.digest();
- const received = encoder(digest);
- if (expectedChecksum !== received) {
- const error40 = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + ` in response header "${checksumSourceLocation}".`);
- controller.error(error40);
- } else {
- controller.terminate();
- }
- }
- });
- source.pipeThrough(transform2);
- const readable2 = transform2.readable;
- Object.setPrototypeOf(readable2, ChecksumStream_browser_1.ChecksumStream.prototype);
- return readable2;
- };
- exports.createChecksumStream = createChecksumStream;
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js
-var require_createChecksumStream = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.createChecksumStream = createChecksumStream;
- var stream_type_check_1 = require_stream_type_check();
- var ChecksumStream_1 = require_ChecksumStream();
- var createChecksumStream_browser_1 = require_createChecksumStream_browser();
- function createChecksumStream(init) {
- if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) {
- return (0, createChecksumStream_browser_1.createChecksumStream)(init);
- }
- return new ChecksumStream_1.ChecksumStream(init);
- }
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js
-var require_ByteArrayCollector = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ByteArrayCollector = undefined;
-
- class ByteArrayCollector {
- allocByteArray;
- byteLength = 0;
- byteArrays = [];
- constructor(allocByteArray) {
- this.allocByteArray = allocByteArray;
- }
- push(byteArray) {
- this.byteArrays.push(byteArray);
- this.byteLength += byteArray.byteLength;
- }
- flush() {
- if (this.byteArrays.length === 1) {
- const bytes = this.byteArrays[0];
- this.reset();
- return bytes;
- }
- const aggregation = this.allocByteArray(this.byteLength);
- let cursor = 0;
- for (let i2 = 0;i2 < this.byteArrays.length; ++i2) {
- const bytes = this.byteArrays[i2];
- aggregation.set(bytes, cursor);
- cursor += bytes.byteLength;
- }
- this.reset();
- return aggregation;
- }
- reset() {
- this.byteArrays = [];
- this.byteLength = 0;
- }
- }
- exports.ByteArrayCollector = ByteArrayCollector;
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js
-var require_createBufferedReadableStream = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.createBufferedReadable = undefined;
- exports.createBufferedReadableStream = createBufferedReadableStream;
- exports.merge = merge3;
- exports.flush = flush;
- exports.sizeOf = sizeOf;
- exports.modeOf = modeOf;
- var ByteArrayCollector_1 = require_ByteArrayCollector();
- function createBufferedReadableStream(upstream, size, logger2) {
- const reader = upstream.getReader();
- let streamBufferingLoggedWarning = false;
- let bytesSeen = 0;
- const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size2) => new Uint8Array(size2))];
- let mode = -1;
- const pull = async (controller) => {
- const { value, done } = await reader.read();
- const chunk = value;
- if (done) {
- if (mode !== -1) {
- const remainder = flush(buffers, mode);
- if (sizeOf(remainder) > 0) {
- controller.enqueue(remainder);
- }
- }
- controller.close();
- } else {
- const chunkMode = modeOf(chunk, false);
- if (mode !== chunkMode) {
- if (mode >= 0) {
- controller.enqueue(flush(buffers, mode));
- }
- mode = chunkMode;
- }
- if (mode === -1) {
- controller.enqueue(chunk);
- return;
- }
- const chunkSize = sizeOf(chunk);
- bytesSeen += chunkSize;
- const bufferSize = sizeOf(buffers[mode]);
- if (chunkSize >= size && bufferSize === 0) {
- controller.enqueue(chunk);
- } else {
- const newSize = merge3(buffers, mode, chunk);
- if (!streamBufferingLoggedWarning && bytesSeen > size * 2) {
- streamBufferingLoggedWarning = true;
- logger2?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);
- }
- if (newSize >= size) {
- controller.enqueue(flush(buffers, mode));
- } else {
- await pull(controller);
- }
- }
- }
- };
- return new ReadableStream({
- pull
- });
- }
- exports.createBufferedReadable = createBufferedReadableStream;
- function merge3(buffers, mode, chunk) {
- switch (mode) {
- case 0:
- buffers[0] += chunk;
- return sizeOf(buffers[0]);
- case 1:
- case 2:
- buffers[mode].push(chunk);
- return sizeOf(buffers[mode]);
- }
- }
- function flush(buffers, mode) {
- switch (mode) {
- case 0:
- const s = buffers[0];
- buffers[0] = "";
- return s;
- case 1:
- case 2:
- return buffers[mode].flush();
- }
- throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`);
- }
- function sizeOf(chunk) {
- return chunk?.byteLength ?? chunk?.length ?? 0;
- }
- function modeOf(chunk, allowBuffer = true) {
- if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) {
- return 2;
- }
- if (chunk instanceof Uint8Array) {
- return 1;
- }
- if (typeof chunk === "string") {
- return 0;
- }
- return -1;
- }
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js
-var require_createBufferedReadable = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.createBufferedReadable = createBufferedReadable;
- var node_stream_1 = __require("stream");
- var ByteArrayCollector_1 = require_ByteArrayCollector();
- var createBufferedReadableStream_1 = require_createBufferedReadableStream();
- var stream_type_check_1 = require_stream_type_check();
- function createBufferedReadable(upstream, size, logger2) {
- if ((0, stream_type_check_1.isReadableStream)(upstream)) {
- return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger2);
- }
- const downstream = new node_stream_1.Readable({ read() {} });
- let streamBufferingLoggedWarning = false;
- let bytesSeen = 0;
- const buffers = [
- "",
- new ByteArrayCollector_1.ByteArrayCollector((size2) => new Uint8Array(size2)),
- new ByteArrayCollector_1.ByteArrayCollector((size2) => Buffer.from(new Uint8Array(size2)))
- ];
- let mode = -1;
- upstream.on("data", (chunk) => {
- const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true);
- if (mode !== chunkMode) {
- if (mode >= 0) {
- downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode));
- }
- mode = chunkMode;
- }
- if (mode === -1) {
- downstream.push(chunk);
- return;
- }
- const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk);
- bytesSeen += chunkSize;
- const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]);
- if (chunkSize >= size && bufferSize === 0) {
- downstream.push(chunk);
- } else {
- const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk);
- if (!streamBufferingLoggedWarning && bytesSeen > size * 2) {
- streamBufferingLoggedWarning = true;
- logger2?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);
- }
- if (newSize >= size) {
- downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode));
- }
- }
- });
- upstream.on("end", () => {
- if (mode !== -1) {
- const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode);
- if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) {
- downstream.push(remainder);
- }
- }
- downstream.push(null);
- });
- return downstream;
- }
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.browser.js
-var require_getAwsChunkedEncodingStream_browser = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getAwsChunkedEncodingStream = undefined;
- var getAwsChunkedEncodingStream = (readableStream, options2) => {
- const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options2;
- const checksumRequired = base64Encoder !== undefined && bodyLengthChecker !== undefined && checksumAlgorithmFn !== undefined && checksumLocationName !== undefined && streamHasher !== undefined;
- const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined;
- const reader = readableStream.getReader();
- return new ReadableStream({
- async pull(controller) {
- const { value, done } = await reader.read();
- if (done) {
- controller.enqueue(`0\r
-`);
- if (checksumRequired) {
- const checksum2 = base64Encoder(await digest);
- controller.enqueue(`${checksumLocationName}:${checksum2}\r
-`);
- controller.enqueue(`\r
-`);
- }
- controller.close();
- } else {
- controller.enqueue(`${(bodyLengthChecker(value) || 0).toString(16)}\r
-${value}\r
-`);
- }
- }
- });
- };
- exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream;
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js
-var require_getAwsChunkedEncodingStream = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream;
- var node_stream_1 = __require("stream");
- var getAwsChunkedEncodingStream_browser_1 = require_getAwsChunkedEncodingStream_browser();
- var stream_type_check_1 = require_stream_type_check();
- function getAwsChunkedEncodingStream(stream5, options2) {
- const readable2 = stream5;
- const readableStream = stream5;
- if ((0, stream_type_check_1.isReadableStream)(readableStream)) {
- return (0, getAwsChunkedEncodingStream_browser_1.getAwsChunkedEncodingStream)(readableStream, options2);
- }
- const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options2;
- const checksumRequired = base64Encoder !== undefined && checksumAlgorithmFn !== undefined && checksumLocationName !== undefined && streamHasher !== undefined;
- const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readable2) : undefined;
- const awsChunkedEncodingStream = new node_stream_1.Readable({
- read: () => {}
- });
- readable2.on("data", (data) => {
- const length = bodyLengthChecker(data) || 0;
- if (length === 0) {
- return;
- }
- awsChunkedEncodingStream.push(`${length.toString(16)}\r
-`);
- awsChunkedEncodingStream.push(data);
- awsChunkedEncodingStream.push(`\r
-`);
- });
- readable2.on("end", async () => {
- awsChunkedEncodingStream.push(`0\r
-`);
- if (checksumRequired) {
- const checksum2 = base64Encoder(await digest);
- awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum2}\r
-`);
- awsChunkedEncodingStream.push(`\r
-`);
- }
- awsChunkedEncodingStream.push(null);
- });
- return awsChunkedEncodingStream;
- }
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js
-var require_headStream_browser = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.headStream = headStream;
- async function headStream(stream5, bytes) {
- let byteLengthCounter = 0;
- const chunks = [];
- const reader = stream5.getReader();
- let isDone = false;
- while (!isDone) {
- const { done, value } = await reader.read();
- if (value) {
- chunks.push(value);
- byteLengthCounter += value?.byteLength ?? 0;
- }
- if (byteLengthCounter >= bytes) {
- break;
- }
- isDone = done;
- }
- reader.releaseLock();
- const collected = new Uint8Array(Math.min(bytes, byteLengthCounter));
- let offset = 0;
- for (const chunk of chunks) {
- if (chunk.byteLength > collected.byteLength - offset) {
- collected.set(chunk.subarray(0, collected.byteLength - offset), offset);
- break;
- } else {
- collected.set(chunk, offset);
- }
- offset += chunk.length;
- }
- return collected;
- }
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/headStream.js
-var require_headStream = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.headStream = undefined;
- var stream_1 = __require("stream");
- var headStream_browser_1 = require_headStream_browser();
- var stream_type_check_1 = require_stream_type_check();
- var headStream = (stream5, bytes) => {
- if ((0, stream_type_check_1.isReadableStream)(stream5)) {
- return (0, headStream_browser_1.headStream)(stream5, bytes);
- }
- return new Promise((resolve9, reject) => {
- const collector = new Collector;
- collector.limit = bytes;
- stream5.pipe(collector);
- stream5.on("error", (err) => {
- collector.end();
- reject(err);
- });
- collector.on("error", reject);
- collector.on("finish", function() {
- const bytes2 = new Uint8Array(Buffer.concat(this.buffers));
- resolve9(bytes2);
- });
- });
- };
- exports.headStream = headStream;
-
- class Collector extends stream_1.Writable {
- buffers = [];
- limit = Infinity;
- bytesBuffered = 0;
- _write(chunk, encoding, callback) {
- this.buffers.push(chunk);
- this.bytesBuffered += chunk.byteLength ?? 0;
- if (this.bytesBuffered >= this.limit) {
- const excess = this.bytesBuffered - this.limit;
- const tailBuffer = this.buffers[this.buffers.length - 1];
- this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess);
- this.emit("finish");
- }
- callback();
- }
- }
-});
-
-// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs19 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration = (runtimeConfig) => {
- return getChecksumConfiguration(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig = (config3) => {
- return resolveChecksumRuntimeConfig(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig;
-});
-
-// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js
-var require_dist_cjs20 = __commonJS((exports) => {
- var types3 = require_dist_cjs19();
- var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
- };
- var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
- };
-
- class Field2 {
- name;
- kind;
- values;
- constructor({ name, kind: kind2 = types3.FieldPosition.HEADER, values = [] }) {
- this.name = name;
- this.kind = kind2;
- this.values = values;
- }
- add(value) {
- this.values.push(value);
- }
- set(values) {
- this.values = values;
- }
- remove(value) {
- this.values = this.values.filter((v) => v !== value);
- }
- toString() {
- return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
- }
- get() {
- return this.values;
- }
- }
-
- class Fields2 {
- entries = {};
- encoding;
- constructor({ fields = [], encoding = "utf-8" }) {
- fields.forEach(this.setField.bind(this));
- this.encoding = encoding;
- }
- setField(field) {
- this.entries[field.name.toLowerCase()] = field;
- }
- getField(name) {
- return this.entries[name.toLowerCase()];
- }
- removeField(name) {
- delete this.entries[name.toLowerCase()];
- }
- getByType(kind2) {
- return Object.values(this.entries).filter((field) => field.kind === kind2);
- }
- }
-
- class HttpRequest2 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest2({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery2(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest2.clone(this);
- }
- }
- function cloneQuery2(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
- }
-
- class HttpResponse {
- statusCode;
- reason;
- headers;
- body;
- constructor(options2) {
- this.statusCode = options2.statusCode;
- this.reason = options2.reason;
- this.headers = options2.headers || {};
- this.body = options2.body;
- }
- static isInstance(response2) {
- if (!response2)
- return false;
- const resp = response2;
- return typeof resp.statusCode === "number" && typeof resp.headers === "object";
- }
- }
- function isValidHostname2(hostname2) {
- const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
- return hostPattern.test(hostname2);
- }
- exports.Field = Field2;
- exports.Fields = Fields2;
- exports.HttpRequest = HttpRequest2;
- exports.HttpResponse = HttpResponse;
- exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
- exports.isValidHostname = isValidHostname2;
- exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;
-});
-
-// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
-var require_dist_cjs21 = __commonJS((exports) => {
- var isArrayBuffer3 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
- exports.isArrayBuffer = isArrayBuffer3;
-});
-
-// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
-var require_dist_cjs22 = __commonJS((exports) => {
- var isArrayBuffer3 = require_dist_cjs21();
- var buffer = __require("buffer");
- var fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
- if (!isArrayBuffer3.isArrayBuffer(input)) {
- throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
- }
- return buffer.Buffer.from(input, offset, length);
- };
- var fromString = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input);
- };
- exports.fromArrayBuffer = fromArrayBuffer;
- exports.fromString = fromString;
-});
-
-// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js
-var require_fromBase642 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.fromBase64 = undefined;
- var util_buffer_from_1 = require_dist_cjs22();
- var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
- var fromBase64 = (input) => {
- if (input.length * 3 % 4 !== 0) {
- throw new TypeError(`Incorrect padding on base64 string.`);
- }
- if (!BASE64_REGEX.exec(input)) {
- throw new TypeError(`Invalid base64 string.`);
- }
- const buffer = (0, util_buffer_from_1.fromString)(input, "base64");
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
- };
- exports.fromBase64 = fromBase64;
-});
-
-// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js
-var require_toBase642 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.toBase64 = undefined;
- var util_buffer_from_1 = require_dist_cjs22();
- var util_utf8_1 = require_dist_cjs17();
- var toBase64 = (_input) => {
- let input;
- if (typeof _input === "string") {
- input = (0, util_utf8_1.fromUtf8)(_input);
- } else {
- input = _input;
- }
- if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
- throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
- }
- return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64");
- };
- exports.toBase64 = toBase64;
-});
-
-// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js
-var require_dist_cjs23 = __commonJS((exports) => {
- var fromBase64 = require_fromBase642();
- var toBase64 = require_toBase642();
- Object.prototype.hasOwnProperty.call(fromBase64, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: fromBase64["__proto__"]
- });
- Object.keys(fromBase64).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = fromBase64[k];
- });
- Object.prototype.hasOwnProperty.call(toBase64, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: toBase64["__proto__"]
- });
- Object.keys(toBase64).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = toBase64[k];
- });
-});
-
-// node_modules/@smithy/fetch-http-handler/dist-cjs/index.js
-var require_dist_cjs24 = __commonJS((exports) => {
- var protocolHttp = require_dist_cjs20();
- var querystringBuilder = require_dist_cjs4();
- var utilBase64 = require_dist_cjs23();
- function createRequest(url3, requestOptions) {
- return new Request(url3, requestOptions);
- }
- function requestTimeout(timeoutInMs = 0) {
- return new Promise((resolve9, reject) => {
- if (timeoutInMs) {
- setTimeout(() => {
- const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`);
- timeoutError.name = "TimeoutError";
- reject(timeoutError);
- }, timeoutInMs);
- }
- });
- }
- var keepAliveSupport = {
- supported: undefined
- };
-
- class FetchHttpHandler {
- config;
- configProvider;
- static create(instanceOrOptions) {
- if (typeof instanceOrOptions?.handle === "function") {
- return instanceOrOptions;
- }
- return new FetchHttpHandler(instanceOrOptions);
- }
- constructor(options2) {
- if (typeof options2 === "function") {
- this.configProvider = options2().then((opts) => opts || {});
- } else {
- this.config = options2 ?? {};
- this.configProvider = Promise.resolve(this.config);
- }
- if (keepAliveSupport.supported === undefined) {
- keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]"));
- }
- }
- destroy() {}
- async handle(request2, { abortSignal, requestTimeout: requestTimeout$1 } = {}) {
- if (!this.config) {
- this.config = await this.configProvider;
- }
- const requestTimeoutInMs = requestTimeout$1 ?? this.config.requestTimeout;
- const keepAlive = this.config.keepAlive === true;
- const credentials = this.config.credentials;
- if (abortSignal?.aborted) {
- const abortError = buildAbortError(abortSignal);
- return Promise.reject(abortError);
- }
- let path8 = request2.path;
- const queryString = querystringBuilder.buildQueryString(request2.query || {});
- if (queryString) {
- path8 += `?${queryString}`;
- }
- if (request2.fragment) {
- path8 += `#${request2.fragment}`;
- }
- let auth3 = "";
- if (request2.username != null || request2.password != null) {
- const username = request2.username ?? "";
- const password = request2.password ?? "";
- auth3 = `${username}:${password}@`;
- }
- const { port, method } = request2;
- const url3 = `${request2.protocol}//${auth3}${request2.hostname}${port ? `:${port}` : ""}${path8}`;
- const body = method === "GET" || method === "HEAD" ? undefined : request2.body;
- const requestOptions = {
- body,
- headers: new Headers(request2.headers),
- method,
- credentials
- };
- if (this.config?.cache) {
- requestOptions.cache = this.config.cache;
- }
- if (body) {
- requestOptions.duplex = "half";
- }
- if (typeof AbortController !== "undefined") {
- requestOptions.signal = abortSignal;
- }
- if (keepAliveSupport.supported) {
- requestOptions.keepalive = keepAlive;
- }
- if (typeof this.config.requestInit === "function") {
- Object.assign(requestOptions, this.config.requestInit(request2));
- }
- let removeSignalEventListener = () => {};
- const fetchRequest = createRequest(url3, requestOptions);
- const raceOfPromises = [
- fetch(fetchRequest).then((response2) => {
- const fetchHeaders = response2.headers;
- const transformedHeaders = {};
- for (const pair of fetchHeaders.entries()) {
- transformedHeaders[pair[0]] = pair[1];
- }
- const hasReadableStream = response2.body != null;
- if (!hasReadableStream) {
- return response2.blob().then((body2) => ({
- response: new protocolHttp.HttpResponse({
- headers: transformedHeaders,
- reason: response2.statusText,
- statusCode: response2.status,
- body: body2
- })
- }));
- }
- return {
- response: new protocolHttp.HttpResponse({
- headers: transformedHeaders,
- reason: response2.statusText,
- statusCode: response2.status,
- body: response2.body
- })
- };
- }),
- requestTimeout(requestTimeoutInMs)
- ];
- if (abortSignal) {
- raceOfPromises.push(new Promise((resolve9, reject) => {
- const onAbort = () => {
- const abortError = buildAbortError(abortSignal);
- reject(abortError);
- };
- if (typeof abortSignal.addEventListener === "function") {
- const signal = abortSignal;
- signal.addEventListener("abort", onAbort, { once: true });
- removeSignalEventListener = () => signal.removeEventListener("abort", onAbort);
- } else {
- abortSignal.onabort = onAbort;
- }
- }));
- }
- return Promise.race(raceOfPromises).finally(removeSignalEventListener);
- }
- updateHttpClientConfig(key, value) {
- this.config = undefined;
- this.configProvider = this.configProvider.then((config3) => {
- config3[key] = value;
- return config3;
- });
- }
- httpHandlerConfigs() {
- return this.config ?? {};
- }
- }
- function buildAbortError(abortSignal) {
- const reason = abortSignal && typeof abortSignal === "object" && "reason" in abortSignal ? abortSignal.reason : undefined;
- if (reason) {
- if (reason instanceof Error) {
- const abortError3 = new Error("Request aborted");
- abortError3.name = "AbortError";
- abortError3.cause = reason;
- return abortError3;
- }
- const abortError2 = new Error(String(reason));
- abortError2.name = "AbortError";
- return abortError2;
- }
- const abortError = new Error("Request aborted");
- abortError.name = "AbortError";
- return abortError;
- }
- var streamCollector = async (stream5) => {
- if (typeof Blob === "function" && stream5 instanceof Blob || stream5.constructor?.name === "Blob") {
- if (Blob.prototype.arrayBuffer !== undefined) {
- return new Uint8Array(await stream5.arrayBuffer());
- }
- return collectBlob(stream5);
- }
- return collectStream(stream5);
- };
- async function collectBlob(blob) {
- const base643 = await readToBase64(blob);
- const arrayBuffer = utilBase64.fromBase64(base643);
- return new Uint8Array(arrayBuffer);
- }
- async function collectStream(stream5) {
- const chunks = [];
- const reader = stream5.getReader();
- let isDone = false;
- let length = 0;
- while (!isDone) {
- const { done, value } = await reader.read();
- if (value) {
- chunks.push(value);
- length += value.length;
- }
- isDone = done;
- }
- const collected = new Uint8Array(length);
- let offset = 0;
- for (const chunk of chunks) {
- collected.set(chunk, offset);
- offset += chunk.length;
- }
- return collected;
- }
- function readToBase64(blob) {
- return new Promise((resolve9, reject) => {
- const reader = new FileReader;
- reader.onloadend = () => {
- if (reader.readyState !== 2) {
- return reject(new Error("Reader aborted too early"));
- }
- const result = reader.result ?? "";
- const commaIndex = result.indexOf(",");
- const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;
- resolve9(result.substring(dataOffset));
- };
- reader.onabort = () => reject(new Error("Read aborted"));
- reader.onerror = () => reject(reader.error);
- reader.readAsDataURL(blob);
- });
- }
- exports.FetchHttpHandler = FetchHttpHandler;
- exports.keepAliveSupport = keepAliveSupport;
- exports.streamCollector = streamCollector;
-});
-
-// node_modules/@smithy/util-stream/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js
-var require_dist_cjs25 = __commonJS((exports) => {
- var SHORT_TO_HEX = {};
- var HEX_TO_SHORT = {};
- for (let i2 = 0;i2 < 256; i2++) {
- let encodedByte = i2.toString(16).toLowerCase();
- if (encodedByte.length === 1) {
- encodedByte = `0${encodedByte}`;
- }
- SHORT_TO_HEX[i2] = encodedByte;
- HEX_TO_SHORT[encodedByte] = i2;
- }
- function fromHex(encoded) {
- if (encoded.length % 2 !== 0) {
- throw new Error("Hex encoded strings must have an even number length");
- }
- const out = new Uint8Array(encoded.length / 2);
- for (let i2 = 0;i2 < encoded.length; i2 += 2) {
- const encodedByte = encoded.slice(i2, i2 + 2).toLowerCase();
- if (encodedByte in HEX_TO_SHORT) {
- out[i2 / 2] = HEX_TO_SHORT[encodedByte];
- } else {
- throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
- }
- }
- return out;
- }
- function toHex(bytes) {
- let out = "";
- for (let i2 = 0;i2 < bytes.byteLength; i2++) {
- out += SHORT_TO_HEX[bytes[i2]];
- }
- return out;
- }
- exports.fromHex = fromHex;
- exports.toHex = toHex;
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js
-var require_sdk_stream_mixin_browser = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.sdkStreamMixin = undefined;
- var fetch_http_handler_1 = require_dist_cjs24();
- var util_base64_1 = require_dist_cjs18();
- var util_hex_encoding_1 = require_dist_cjs25();
- var util_utf8_1 = require_dist_cjs17();
- var stream_type_check_1 = require_stream_type_check();
- var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
- var sdkStreamMixin = (stream5) => {
- if (!isBlobInstance(stream5) && !(0, stream_type_check_1.isReadableStream)(stream5)) {
- const name = stream5?.__proto__?.constructor?.name || stream5;
- throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`);
- }
- let transformed = false;
- const transformToByteArray = async () => {
- if (transformed) {
- throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
- }
- transformed = true;
- return await (0, fetch_http_handler_1.streamCollector)(stream5);
- };
- const blobToWebStream = (blob) => {
- if (typeof blob.stream !== "function") {
- throw new Error(`Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.
-` + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");
- }
- return blob.stream();
- };
- return Object.assign(stream5, {
- transformToByteArray,
- transformToString: async (encoding) => {
- const buf = await transformToByteArray();
- if (encoding === "base64") {
- return (0, util_base64_1.toBase64)(buf);
- } else if (encoding === "hex") {
- return (0, util_hex_encoding_1.toHex)(buf);
- } else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") {
- return (0, util_utf8_1.toUtf8)(buf);
- } else if (typeof TextDecoder === "function") {
- return new TextDecoder(encoding).decode(buf);
- } else {
- throw new Error("TextDecoder is not available, please make sure polyfill is provided.");
- }
- },
- transformToWebStream: () => {
- if (transformed) {
- throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
- }
- transformed = true;
- if (isBlobInstance(stream5)) {
- return blobToWebStream(stream5);
- } else if ((0, stream_type_check_1.isReadableStream)(stream5)) {
- return stream5;
- } else {
- throw new Error(`Cannot transform payload to web stream, got ${stream5}`);
- }
- }
- });
- };
- exports.sdkStreamMixin = sdkStreamMixin;
- var isBlobInstance = (stream5) => typeof Blob === "function" && stream5 instanceof Blob;
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js
-var require_sdk_stream_mixin = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.sdkStreamMixin = undefined;
- var node_http_handler_1 = require_dist_cjs5();
- var util_buffer_from_1 = require_dist_cjs14();
- var stream_1 = __require("stream");
- var sdk_stream_mixin_browser_1 = require_sdk_stream_mixin_browser();
- var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
- var sdkStreamMixin = (stream5) => {
- if (!(stream5 instanceof stream_1.Readable)) {
- try {
- return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream5);
- } catch (e) {
- const name = stream5?.__proto__?.constructor?.name || stream5;
- throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`);
- }
- }
- let transformed = false;
- const transformToByteArray = async () => {
- if (transformed) {
- throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
- }
- transformed = true;
- return await (0, node_http_handler_1.streamCollector)(stream5);
- };
- return Object.assign(stream5, {
- transformToByteArray,
- transformToString: async (encoding) => {
- const buf = await transformToByteArray();
- if (encoding === undefined || Buffer.isEncoding(encoding)) {
- return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding);
- } else {
- const decoder = new TextDecoder(encoding);
- return decoder.decode(buf);
- }
- },
- transformToWebStream: () => {
- if (transformed) {
- throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
- }
- if (stream5.readableFlowing !== null) {
- throw new Error("The stream has been consumed by other callbacks.");
- }
- if (typeof stream_1.Readable.toWeb !== "function") {
- throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");
- }
- transformed = true;
- return stream_1.Readable.toWeb(stream5);
- }
- });
- };
- exports.sdkStreamMixin = sdkStreamMixin;
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js
-var require_splitStream_browser = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.splitStream = splitStream;
- async function splitStream(stream5) {
- if (typeof stream5.stream === "function") {
- stream5 = stream5.stream();
- }
- const readableStream = stream5;
- return readableStream.tee();
- }
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/splitStream.js
-var require_splitStream = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.splitStream = splitStream;
- var stream_1 = __require("stream");
- var splitStream_browser_1 = require_splitStream_browser();
- var stream_type_check_1 = require_stream_type_check();
- async function splitStream(stream5) {
- if ((0, stream_type_check_1.isReadableStream)(stream5) || (0, stream_type_check_1.isBlob)(stream5)) {
- return (0, splitStream_browser_1.splitStream)(stream5);
- }
- const stream1 = new stream_1.PassThrough;
- const stream22 = new stream_1.PassThrough;
- stream5.pipe(stream1);
- stream5.pipe(stream22);
- return [stream1, stream22];
- }
-});
-
-// node_modules/@smithy/util-stream/dist-cjs/index.js
-var require_dist_cjs26 = __commonJS((exports) => {
- var utilBase64 = require_dist_cjs18();
- var utilUtf8 = require_dist_cjs17();
- var ChecksumStream = require_ChecksumStream();
- var createChecksumStream = require_createChecksumStream();
- var createBufferedReadable = require_createBufferedReadable();
- var getAwsChunkedEncodingStream = require_getAwsChunkedEncodingStream();
- var headStream = require_headStream();
- var sdkStreamMixin = require_sdk_stream_mixin();
- var splitStream = require_splitStream();
- var streamTypeCheck = require_stream_type_check();
-
- class Uint8ArrayBlobAdapter extends Uint8Array {
- static fromString(source, encoding = "utf-8") {
- if (typeof source === "string") {
- if (encoding === "base64") {
- return Uint8ArrayBlobAdapter.mutate(utilBase64.fromBase64(source));
- }
- return Uint8ArrayBlobAdapter.mutate(utilUtf8.fromUtf8(source));
- }
- throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`);
- }
- static mutate(source) {
- Object.setPrototypeOf(source, Uint8ArrayBlobAdapter.prototype);
- return source;
- }
- transformToString(encoding = "utf-8") {
- if (encoding === "base64") {
- return utilBase64.toBase64(this);
- }
- return utilUtf8.toUtf8(this);
- }
- }
- exports.isBlob = streamTypeCheck.isBlob;
- exports.isReadableStream = streamTypeCheck.isReadableStream;
- exports.Uint8ArrayBlobAdapter = Uint8ArrayBlobAdapter;
- Object.prototype.hasOwnProperty.call(ChecksumStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: ChecksumStream["__proto__"]
- });
- Object.keys(ChecksumStream).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = ChecksumStream[k];
- });
- Object.prototype.hasOwnProperty.call(createChecksumStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: createChecksumStream["__proto__"]
- });
- Object.keys(createChecksumStream).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = createChecksumStream[k];
- });
- Object.prototype.hasOwnProperty.call(createBufferedReadable, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: createBufferedReadable["__proto__"]
- });
- Object.keys(createBufferedReadable).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = createBufferedReadable[k];
- });
- Object.prototype.hasOwnProperty.call(getAwsChunkedEncodingStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: getAwsChunkedEncodingStream["__proto__"]
- });
- Object.keys(getAwsChunkedEncodingStream).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = getAwsChunkedEncodingStream[k];
- });
- Object.prototype.hasOwnProperty.call(headStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: headStream["__proto__"]
- });
- Object.keys(headStream).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = headStream[k];
- });
- Object.prototype.hasOwnProperty.call(sdkStreamMixin, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: sdkStreamMixin["__proto__"]
- });
- Object.keys(sdkStreamMixin).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = sdkStreamMixin[k];
- });
- Object.prototype.hasOwnProperty.call(splitStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: splitStream["__proto__"]
- });
- Object.keys(splitStream).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = splitStream[k];
- });
-});
-
-// node_modules/@smithy/core/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs27 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration = (runtimeConfig) => {
- return getChecksumConfiguration(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig = (config3) => {
- return resolveChecksumRuntimeConfig(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig;
-});
-
-// node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-cjs/index.js
-var require_dist_cjs28 = __commonJS((exports) => {
- var types3 = require_dist_cjs27();
- var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
- };
- var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
- };
-
- class Field2 {
- name;
- kind;
- values;
- constructor({ name, kind: kind2 = types3.FieldPosition.HEADER, values = [] }) {
- this.name = name;
- this.kind = kind2;
- this.values = values;
- }
- add(value) {
- this.values.push(value);
- }
- set(values) {
- this.values = values;
- }
- remove(value) {
- this.values = this.values.filter((v) => v !== value);
- }
- toString() {
- return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
- }
- get() {
- return this.values;
- }
- }
-
- class Fields2 {
- entries = {};
- encoding;
- constructor({ fields = [], encoding = "utf-8" }) {
- fields.forEach(this.setField.bind(this));
- this.encoding = encoding;
- }
- setField(field) {
- this.entries[field.name.toLowerCase()] = field;
- }
- getField(name) {
- return this.entries[name.toLowerCase()];
- }
- removeField(name) {
- delete this.entries[name.toLowerCase()];
- }
- getByType(kind2) {
- return Object.values(this.entries).filter((field) => field.kind === kind2);
- }
- }
-
- class HttpRequest2 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest2({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery2(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest2.clone(this);
- }
- }
- function cloneQuery2(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
- }
-
- class HttpResponse {
- statusCode;
- reason;
- headers;
- body;
- constructor(options2) {
- this.statusCode = options2.statusCode;
- this.reason = options2.reason;
- this.headers = options2.headers || {};
- this.body = options2.body;
- }
- static isInstance(response2) {
- if (!response2)
- return false;
- const resp = response2;
- return typeof resp.statusCode === "number" && typeof resp.headers === "object";
- }
- }
- function isValidHostname2(hostname2) {
- const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
- return hostPattern.test(hostname2);
- }
- exports.Field = Field2;
- exports.Fields = Fields2;
- exports.HttpRequest = HttpRequest2;
- exports.HttpResponse = HttpResponse;
- exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
- exports.isValidHostname = isValidHostname2;
- exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;
-});
-
-// node_modules/@smithy/util-middleware/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs29 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration = (runtimeConfig) => {
- return getChecksumConfiguration(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig = (config3) => {
- return resolveChecksumRuntimeConfig(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig;
-});
-
-// node_modules/@smithy/util-middleware/dist-cjs/index.js
-var require_dist_cjs30 = __commonJS((exports) => {
- var types3 = require_dist_cjs29();
- var getSmithyContext = (context) => context[types3.SMITHY_CONTEXT_KEY] || (context[types3.SMITHY_CONTEXT_KEY] = {});
- var normalizeProvider = (input) => {
- if (typeof input === "function")
- return input;
- const promisified = Promise.resolve(input);
- return () => promisified;
- };
- exports.getSmithyContext = getSmithyContext;
- exports.normalizeProvider = normalizeProvider;
-});
-
-// node_modules/@smithy/core/dist-cjs/submodules/endpoints/index.js
-var require_endpoints = __commonJS((exports) => {
- var urlParser = require_dist_cjs11();
- var toEndpointV1 = (endpoint2) => {
- if (typeof endpoint2 === "object") {
- if ("url" in endpoint2) {
- const v1Endpoint = urlParser.parseUrl(endpoint2.url);
- if (endpoint2.headers) {
- v1Endpoint.headers = {};
- for (const [name, values] of Object.entries(endpoint2.headers)) {
- v1Endpoint.headers[name.toLowerCase()] = values.join(", ");
- }
- }
- return v1Endpoint;
- }
- return endpoint2;
- }
- return urlParser.parseUrl(endpoint2);
- };
- exports.toEndpointV1 = toEndpointV1;
-});
-
-// node_modules/@smithy/core/dist-cjs/submodules/schema/index.js
-var require_schema = __commonJS((exports) => {
- var protocolHttp = require_dist_cjs28();
- var utilMiddleware = require_dist_cjs30();
- var endpoints2 = require_endpoints();
- var deref = (schemaRef) => {
- if (typeof schemaRef === "function") {
- return schemaRef();
- }
- return schemaRef;
- };
- var operation = (namespace, name, traits2, input, output) => ({
- name,
- namespace,
- traits: traits2,
- input,
- output
- });
- var schemaDeserializationMiddleware = (config3) => (next, context) => async (args) => {
- const { response: response2 } = await next(args);
- const { operationSchema } = utilMiddleware.getSmithyContext(context);
- const [, ns, n2, t, i2, o2] = operationSchema ?? [];
- try {
- const parsed = await config3.protocol.deserializeResponse(operation(ns, n2, t, i2, o2), {
- ...config3,
- ...context
- }, response2);
- return {
- response: response2,
- output: parsed
- };
- } catch (error41) {
- Object.defineProperty(error41, "$response", {
- value: response2,
- enumerable: false,
- writable: false,
- configurable: false
- });
- if (!("$metadata" in error41)) {
- const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
- try {
- error41.message += `
- ` + hint;
- } catch (e) {
- if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") {
- console.warn(hint);
- } else {
- context.logger?.warn?.(hint);
- }
- }
- if (typeof error41.$responseBodyText !== "undefined") {
- if (error41.$response) {
- error41.$response.body = error41.$responseBodyText;
- }
- }
- try {
- if (protocolHttp.HttpResponse.isInstance(response2)) {
- const { headers = {} } = response2;
- const headerEntries = Object.entries(headers);
- error41.$metadata = {
- httpStatusCode: response2.statusCode,
- requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries),
- extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries),
- cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries)
- };
- }
- } catch (e) {}
- }
- throw error41;
- }
- };
- var findHeader = (pattern, headers) => {
- return (headers.find(([k]) => {
- return k.match(pattern);
- }) || [undefined, undefined])[1];
- };
- var schemaSerializationMiddleware = (config3) => (next, context) => async (args) => {
- const { operationSchema } = utilMiddleware.getSmithyContext(context);
- const [, ns, n2, t, i2, o2] = operationSchema ?? [];
- const endpoint2 = context.endpointV2 ? async () => endpoints2.toEndpointV1(context.endpointV2) : config3.endpoint;
- const request2 = await config3.protocol.serializeRequest(operation(ns, n2, t, i2, o2), args.input, {
- ...config3,
- ...context,
- endpoint: endpoint2
- });
- return next({
- ...args,
- request: request2
- });
- };
- var deserializerMiddlewareOption = {
- name: "deserializerMiddleware",
- step: "deserialize",
- tags: ["DESERIALIZER"],
- override: true
- };
- var serializerMiddlewareOption = {
- name: "serializerMiddleware",
- step: "serialize",
- tags: ["SERIALIZER"],
- override: true
- };
- function getSchemaSerdePlugin(config3) {
- return {
- applyToStack: (commandStack) => {
- commandStack.add(schemaSerializationMiddleware(config3), serializerMiddlewareOption);
- commandStack.add(schemaDeserializationMiddleware(config3), deserializerMiddlewareOption);
- config3.protocol.setSerdeContext(config3);
- }
- };
- }
-
- class Schema {
- name;
- namespace;
- traits;
- static assign(instance, values) {
- const schema2 = Object.assign(instance, values);
- return schema2;
- }
- static [Symbol.hasInstance](lhs) {
- const isPrototype2 = this.prototype.isPrototypeOf(lhs);
- if (!isPrototype2 && typeof lhs === "object" && lhs !== null) {
- const list3 = lhs;
- return list3.symbol === this.symbol;
- }
- return isPrototype2;
- }
- getName() {
- return this.namespace + "#" + this.name;
- }
- }
-
- class ListSchema extends Schema {
- static symbol = Symbol.for("@smithy/lis");
- name;
- traits;
- valueSchema;
- symbol = ListSchema.symbol;
- }
- var list2 = (namespace, name, traits2, valueSchema) => Schema.assign(new ListSchema, {
- name,
- namespace,
- traits: traits2,
- valueSchema
- });
-
- class MapSchema extends Schema {
- static symbol = Symbol.for("@smithy/map");
- name;
- traits;
- keySchema;
- valueSchema;
- symbol = MapSchema.symbol;
- }
- var map2 = (namespace, name, traits2, keySchema, valueSchema) => Schema.assign(new MapSchema, {
- name,
- namespace,
- traits: traits2,
- keySchema,
- valueSchema
- });
-
- class OperationSchema extends Schema {
- static symbol = Symbol.for("@smithy/ope");
- name;
- traits;
- input;
- output;
- symbol = OperationSchema.symbol;
- }
- var op = (namespace, name, traits2, input, output) => Schema.assign(new OperationSchema, {
- name,
- namespace,
- traits: traits2,
- input,
- output
- });
-
- class StructureSchema extends Schema {
- static symbol = Symbol.for("@smithy/str");
- name;
- traits;
- memberNames;
- memberList;
- symbol = StructureSchema.symbol;
- }
- var struct = (namespace, name, traits2, memberNames, memberList) => Schema.assign(new StructureSchema, {
- name,
- namespace,
- traits: traits2,
- memberNames,
- memberList
- });
-
- class ErrorSchema extends StructureSchema {
- static symbol = Symbol.for("@smithy/err");
- ctor;
- symbol = ErrorSchema.symbol;
- }
- var error40 = (namespace, name, traits2, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema, {
- name,
- namespace,
- traits: traits2,
- memberNames,
- memberList,
- ctor: null
- });
- var traitsCache = [];
- function translateTraits(indicator) {
- if (typeof indicator === "object") {
- return indicator;
- }
- indicator = indicator | 0;
- if (traitsCache[indicator]) {
- return traitsCache[indicator];
- }
- const traits2 = {};
- let i2 = 0;
- for (const trait of [
- "httpLabel",
- "idempotent",
- "idempotencyToken",
- "sensitive",
- "httpPayload",
- "httpResponseCode",
- "httpQueryParams"
- ]) {
- if ((indicator >> i2++ & 1) === 1) {
- traits2[trait] = 1;
- }
- }
- return traitsCache[indicator] = traits2;
- }
- var anno = {
- it: Symbol.for("@smithy/nor-struct-it"),
- ns: Symbol.for("@smithy/ns")
- };
- var simpleSchemaCacheN = [];
- var simpleSchemaCacheS = {};
-
- class NormalizedSchema {
- ref;
- memberName;
- static symbol = Symbol.for("@smithy/nor");
- symbol = NormalizedSchema.symbol;
- name;
- schema;
- _isMemberSchema;
- traits;
- memberTraits;
- normalizedTraits;
- constructor(ref, memberName) {
- this.ref = ref;
- this.memberName = memberName;
- const traitStack = [];
- let _ref = ref;
- let schema2 = ref;
- this._isMemberSchema = false;
- while (isMemberSchema(_ref)) {
- traitStack.push(_ref[1]);
- _ref = _ref[0];
- schema2 = deref(_ref);
- this._isMemberSchema = true;
- }
- if (traitStack.length > 0) {
- this.memberTraits = {};
- for (let i2 = traitStack.length - 1;i2 >= 0; --i2) {
- const traitSet = traitStack[i2];
- Object.assign(this.memberTraits, translateTraits(traitSet));
- }
- } else {
- this.memberTraits = 0;
- }
- if (schema2 instanceof NormalizedSchema) {
- const computedMemberTraits = this.memberTraits;
- Object.assign(this, schema2);
- this.memberTraits = Object.assign({}, computedMemberTraits, schema2.getMemberTraits(), this.getMemberTraits());
- this.normalizedTraits = undefined;
- this.memberName = memberName ?? schema2.memberName;
- return;
- }
- this.schema = deref(schema2);
- if (isStaticSchema(this.schema)) {
- this.name = `${this.schema[1]}#${this.schema[2]}`;
- this.traits = this.schema[3];
- } else {
- this.name = this.memberName ?? String(schema2);
- this.traits = 0;
- }
- if (this._isMemberSchema && !memberName) {
- throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`);
- }
- }
- static [Symbol.hasInstance](lhs) {
- const isPrototype2 = this.prototype.isPrototypeOf(lhs);
- if (!isPrototype2 && typeof lhs === "object" && lhs !== null) {
- const ns = lhs;
- return ns.symbol === this.symbol;
- }
- return isPrototype2;
- }
- static of(ref) {
- const keyAble = typeof ref === "function" || typeof ref === "object" && ref !== null;
- if (typeof ref === "number") {
- if (simpleSchemaCacheN[ref]) {
- return simpleSchemaCacheN[ref];
- }
- } else if (typeof ref === "string") {
- if (simpleSchemaCacheS[ref]) {
- return simpleSchemaCacheS[ref];
- }
- } else if (keyAble) {
- if (ref[anno.ns]) {
- return ref[anno.ns];
- }
- }
- const sc = deref(ref);
- if (sc instanceof NormalizedSchema) {
- return sc;
- }
- if (isMemberSchema(sc)) {
- const [ns2, traits2] = sc;
- if (ns2 instanceof NormalizedSchema) {
- Object.assign(ns2.getMergedTraits(), translateTraits(traits2));
- return ns2;
- }
- throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`);
- }
- const ns = new NormalizedSchema(sc);
- if (keyAble) {
- return ref[anno.ns] = ns;
- }
- if (typeof sc === "string") {
- return simpleSchemaCacheS[sc] = ns;
- }
- if (typeof sc === "number") {
- return simpleSchemaCacheN[sc] = ns;
- }
- return ns;
- }
- getSchema() {
- const sc = this.schema;
- if (Array.isArray(sc) && sc[0] === 0) {
- return sc[4];
- }
- return sc;
- }
- getName(withNamespace = false) {
- const { name } = this;
- const short = !withNamespace && name && name.includes("#");
- return short ? name.split("#")[1] : name || undefined;
- }
- getMemberName() {
- return this.memberName;
- }
- isMemberSchema() {
- return this._isMemberSchema;
- }
- isListSchema() {
- const sc = this.getSchema();
- return typeof sc === "number" ? sc >= 64 && sc < 128 : sc[0] === 1;
- }
- isMapSchema() {
- const sc = this.getSchema();
- return typeof sc === "number" ? sc >= 128 && sc <= 255 : sc[0] === 2;
- }
- isStructSchema() {
- const sc = this.getSchema();
- if (typeof sc !== "object") {
- return false;
- }
- const id = sc[0];
- return id === 3 || id === -3 || id === 4;
- }
- isUnionSchema() {
- const sc = this.getSchema();
- if (typeof sc !== "object") {
- return false;
- }
- return sc[0] === 4;
- }
- isBlobSchema() {
- const sc = this.getSchema();
- return sc === 21 || sc === 42;
- }
- isTimestampSchema() {
- const sc = this.getSchema();
- return typeof sc === "number" && sc >= 4 && sc <= 7;
- }
- isUnitSchema() {
- return this.getSchema() === "unit";
- }
- isDocumentSchema() {
- return this.getSchema() === 15;
- }
- isStringSchema() {
- return this.getSchema() === 0;
- }
- isBooleanSchema() {
- return this.getSchema() === 2;
- }
- isNumericSchema() {
- return this.getSchema() === 1;
- }
- isBigIntegerSchema() {
- return this.getSchema() === 17;
- }
- isBigDecimalSchema() {
- return this.getSchema() === 19;
- }
- isStreaming() {
- const { streaming } = this.getMergedTraits();
- return !!streaming || this.getSchema() === 42;
- }
- isIdempotencyToken() {
- return !!this.getMergedTraits().idempotencyToken;
- }
- getMergedTraits() {
- return this.normalizedTraits ?? (this.normalizedTraits = {
- ...this.getOwnTraits(),
- ...this.getMemberTraits()
- });
- }
- getMemberTraits() {
- return translateTraits(this.memberTraits);
- }
- getOwnTraits() {
- return translateTraits(this.traits);
- }
- getKeySchema() {
- const [isDoc, isMap2] = [this.isDocumentSchema(), this.isMapSchema()];
- if (!isDoc && !isMap2) {
- throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`);
- }
- const schema2 = this.getSchema();
- const memberSchema = isDoc ? 15 : schema2[4] ?? 0;
- return member([memberSchema, 0], "key");
- }
- getValueSchema() {
- const sc = this.getSchema();
- const [isDoc, isMap2, isList] = [this.isDocumentSchema(), this.isMapSchema(), this.isListSchema()];
- const memberSchema = typeof sc === "number" ? 63 & sc : sc && typeof sc === "object" && (isMap2 || isList) ? sc[3 + sc[0]] : isDoc ? 15 : undefined;
- if (memberSchema != null) {
- return member([memberSchema, 0], isMap2 ? "value" : "member");
- }
- throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`);
- }
- getMemberSchema(memberName) {
- const struct2 = this.getSchema();
- if (this.isStructSchema() && struct2[4].includes(memberName)) {
- const i2 = struct2[4].indexOf(memberName);
- const memberSchema = struct2[5][i2];
- return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName);
- }
- if (this.isDocumentSchema()) {
- return member([15, 0], memberName);
- }
- throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${memberName}.`);
- }
- getMemberSchemas() {
- const buffer = {};
- try {
- for (const [k, v] of this.structIterator()) {
- buffer[k] = v;
- }
- } catch (ignored) {}
- return buffer;
- }
- getEventStreamMember() {
- if (this.isStructSchema()) {
- for (const [memberName, memberSchema] of this.structIterator()) {
- if (memberSchema.isStreaming() && memberSchema.isStructSchema()) {
- return memberName;
- }
- }
- }
- return "";
- }
- *structIterator() {
- if (this.isUnitSchema()) {
- return;
- }
- if (!this.isStructSchema()) {
- throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");
- }
- const struct2 = this.getSchema();
- const z2 = struct2[4].length;
- let it = struct2[anno.it];
- if (it && z2 === it.length) {
- yield* it;
- return;
- }
- it = Array(z2);
- for (let i2 = 0;i2 < z2; ++i2) {
- const k = struct2[4][i2];
- const v = member([struct2[5][i2], 0], k);
- yield it[i2] = [k, v];
- }
- struct2[anno.it] = it;
- }
- }
- function member(memberSchema, memberName) {
- if (memberSchema instanceof NormalizedSchema) {
- return Object.assign(memberSchema, {
- memberName,
- _isMemberSchema: true
- });
- }
- const internalCtorAccess = NormalizedSchema;
- return new internalCtorAccess(memberSchema, memberName);
- }
- var isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2;
- var isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5;
-
- class SimpleSchema extends Schema {
- static symbol = Symbol.for("@smithy/sim");
- name;
- schemaRef;
- traits;
- symbol = SimpleSchema.symbol;
- }
- var sim = (namespace, name, schemaRef, traits2) => Schema.assign(new SimpleSchema, {
- name,
- namespace,
- traits: traits2,
- schemaRef
- });
- var simAdapter = (namespace, name, traits2, schemaRef) => Schema.assign(new SimpleSchema, {
- name,
- namespace,
- traits: traits2,
- schemaRef
- });
- var SCHEMA = {
- BLOB: 21,
- STREAMING_BLOB: 42,
- BOOLEAN: 2,
- STRING: 0,
- NUMERIC: 1,
- BIG_INTEGER: 17,
- BIG_DECIMAL: 19,
- DOCUMENT: 15,
- TIMESTAMP_DEFAULT: 4,
- TIMESTAMP_DATE_TIME: 5,
- TIMESTAMP_HTTP_DATE: 6,
- TIMESTAMP_EPOCH_SECONDS: 7,
- LIST_MODIFIER: 64,
- MAP_MODIFIER: 128
- };
-
- class TypeRegistry {
- namespace;
- schemas;
- exceptions;
- static registries = new Map;
- constructor(namespace, schemas3 = new Map, exceptions = new Map) {
- this.namespace = namespace;
- this.schemas = schemas3;
- this.exceptions = exceptions;
- }
- static for(namespace) {
- if (!TypeRegistry.registries.has(namespace)) {
- TypeRegistry.registries.set(namespace, new TypeRegistry(namespace));
- }
- return TypeRegistry.registries.get(namespace);
- }
- copyFrom(other2) {
- const { schemas: schemas3, exceptions } = this;
- for (const [k, v] of other2.schemas) {
- if (!schemas3.has(k)) {
- schemas3.set(k, v);
- }
- }
- for (const [k, v] of other2.exceptions) {
- if (!exceptions.has(k)) {
- exceptions.set(k, v);
- }
- }
- }
- register(shapeId, schema2) {
- const qualifiedName = this.normalizeShapeId(shapeId);
- for (const r of [this, TypeRegistry.for(qualifiedName.split("#")[0])]) {
- r.schemas.set(qualifiedName, schema2);
- }
- }
- getSchema(shapeId) {
- const id = this.normalizeShapeId(shapeId);
- if (!this.schemas.has(id)) {
- throw new Error(`@smithy/core/schema - schema not found for ${id}`);
- }
- return this.schemas.get(id);
- }
- registerError(es, ctor) {
- const $error2 = es;
- const ns = $error2[1];
- for (const r of [this, TypeRegistry.for(ns)]) {
- r.schemas.set(ns + "#" + $error2[2], $error2);
- r.exceptions.set($error2, ctor);
- }
- }
- getErrorCtor(es) {
- const $error2 = es;
- if (this.exceptions.has($error2)) {
- return this.exceptions.get($error2);
- }
- const registry3 = TypeRegistry.for($error2[1]);
- return registry3.exceptions.get($error2);
- }
- getBaseException() {
- for (const exceptionKey of this.exceptions.keys()) {
- if (Array.isArray(exceptionKey)) {
- const [, ns, name] = exceptionKey;
- const id = ns + "#" + name;
- if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) {
- return exceptionKey;
- }
- }
- }
- return;
- }
- find(predicate) {
- return [...this.schemas.values()].find(predicate);
- }
- clear() {
- this.schemas.clear();
- this.exceptions.clear();
- }
- normalizeShapeId(shapeId) {
- if (shapeId.includes("#")) {
- return shapeId;
- }
- return this.namespace + "#" + shapeId;
- }
- }
- exports.ErrorSchema = ErrorSchema;
- exports.ListSchema = ListSchema;
- exports.MapSchema = MapSchema;
- exports.NormalizedSchema = NormalizedSchema;
- exports.OperationSchema = OperationSchema;
- exports.SCHEMA = SCHEMA;
- exports.Schema = Schema;
- exports.SimpleSchema = SimpleSchema;
- exports.StructureSchema = StructureSchema;
- exports.TypeRegistry = TypeRegistry;
- exports.deref = deref;
- exports.deserializerMiddlewareOption = deserializerMiddlewareOption;
- exports.error = error40;
- exports.getSchemaSerdePlugin = getSchemaSerdePlugin;
- exports.isStaticSchema = isStaticSchema;
- exports.list = list2;
- exports.map = map2;
- exports.op = op;
- exports.operation = operation;
- exports.serializerMiddlewareOption = serializerMiddlewareOption;
- exports.sim = sim;
- exports.simAdapter = simAdapter;
- exports.simpleSchemaCacheN = simpleSchemaCacheN;
- exports.simpleSchemaCacheS = simpleSchemaCacheS;
- exports.struct = struct;
- exports.traitsCache = traitsCache;
- exports.translateTraits = translateTraits;
-});
-
-// node_modules/tslib/tslib.js
-var require_tslib = __commonJS((exports, module) => {
- 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 __classPrivateFieldGet5;
- var __classPrivateFieldSet5;
- var __classPrivateFieldIn;
- var __createBinding;
- var __addDisposableResource;
- var __disposeResources;
- var __rewriteRelativeImportExtension;
- (function(factory2) {
- var root2 = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
- if (typeof define === "function" && define.amd) {
- define("tslib", ["exports"], function(exports2) {
- factory2(createExporter(root2, createExporter(exports2)));
- });
- } else if (typeof module === "object" && typeof exports === "object") {
- factory2(createExporter(root2, createExporter(exports)));
- } else {
- factory2(createExporter(root2));
- }
- function createExporter(exports2, previous) {
- if (exports2 !== root2) {
- if (typeof Object.create === "function") {
- Object.defineProperty(exports2, "__esModule", { value: true });
- } else {
- exports2.__esModule = true;
- }
- }
- return function(id, v) {
- return exports2[id] = previous ? previous(id, v) : v;
- };
- }
- })(function(exporter) {
- var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) {
- d.__proto__ = b;
- } || function(d, b) {
- for (var p in b)
- if (Object.prototype.hasOwnProperty.call(b, p))
- d[p] = b[p];
- };
- __extends = function(d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() {
- this.constructor = d;
- }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __);
- };
- __assign = Object.assign || function(t) {
- for (var s, i2 = 1, n2 = arguments.length;i2 < n2; i2++) {
- s = arguments[i2];
- for (var p in s)
- if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- __rest = function(s, e) {
- var t = {};
- for (var p in s)
- if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i2 = 0, p = Object.getOwnPropertySymbols(s);i2 < p.length; i2++) {
- if (e.indexOf(p[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i2]))
- t[p[i2]] = s[p[i2]];
- }
- return t;
- };
- __decorate = function(decorators, target, key, desc) {
- var c5 = arguments.length, r = c5 < 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 i2 = decorators.length - 1;i2 >= 0; i2--)
- if (d = decorators[i2])
- r = (c5 < 3 ? d(r) : c5 > 3 ? d(target, key, r) : d(target, key)) || r;
- return c5 > 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 !== undefined && typeof f !== "function")
- throw new TypeError("Function expected");
- return f;
- }
- var kind2 = contextIn.kind, key = kind2 === "getter" ? "get" : kind2 === "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 i2 = decorators.length - 1;i2 >= 0; i2--) {
- 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[i2])(kind2 === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
- if (kind2 === "accessor") {
- if (result === undefined)
- 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 (kind2 === "field")
- initializers.unshift(_);
- else
- descriptor[key] = _;
- }
- }
- if (target)
- Object.defineProperty(target, contextIn.name, descriptor);
- done = true;
- };
- __runInitializers = function(thisArg, initializers, value) {
- var useValue = arguments.length > 2;
- for (var i2 = 0;i2 < initializers.length; i2++) {
- value = useValue ? initializers[i2].call(thisArg, value) : initializers[i2].call(thisArg);
- }
- return useValue ? value : undefined;
- };
- __propKey = function(x2) {
- return typeof x2 === "symbol" ? x2 : "".concat(x2);
- };
- __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(resolve9) {
- resolve9(value);
- });
- }
- return new (P || (P = Promise))(function(resolve9, 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 ? resolve9(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, y2, 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(n2) {
- return function(v) {
- return step([n2, v]);
- };
- }
- function step(op) {
- if (f)
- throw new TypeError("Generator is already executing.");
- while (g && (g = 0, op[0] && (_ = 0)), _)
- try {
- if (f = 1, y2 && (t = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t = y2["return"]) && t.call(y2), 0) : y2.next) && !(t = t.call(y2, op[1])).done)
- return t;
- if (y2 = 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++;
- y2 = 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];
- y2 = 0;
- } finally {
- f = t = 0;
- }
- if (op[0] & 5)
- throw op[1];
- return { value: op[0] ? op[1] : undefined, done: true };
- }
- };
- __exportStar = function(m, o2) {
- for (var p in m)
- if (p !== "default" && !Object.prototype.hasOwnProperty.call(o2, p))
- __createBinding(o2, m, p);
- };
- __createBinding = Object.create ? function(o2, 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(o2, k2, desc);
- } : function(o2, m, k, k2) {
- if (k2 === undefined)
- k2 = k;
- o2[k2] = m[k];
- };
- __values = function(o2) {
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o2[s], i2 = 0;
- if (m)
- return m.call(o2);
- if (o2 && typeof o2.length === "number")
- return {
- next: function() {
- if (o2 && i2 >= o2.length)
- o2 = undefined;
- return { value: o2 && o2[i2++], done: !o2 };
- }
- };
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
- };
- __read = function(o2, n2) {
- var m = typeof Symbol === "function" && o2[Symbol.iterator];
- if (!m)
- return o2;
- var i2 = m.call(o2), r, ar = [], e;
- try {
- while ((n2 === undefined || n2-- > 0) && !(r = i2.next()).done)
- ar.push(r.value);
- } catch (error40) {
- e = { error: error40 };
- } finally {
- try {
- if (r && !r.done && (m = i2["return"]))
- m.call(i2);
- } finally {
- if (e)
- throw e.error;
- }
- }
- return ar;
- };
- __spread = function() {
- for (var ar = [], i2 = 0;i2 < arguments.length; i2++)
- ar = ar.concat(__read(arguments[i2]));
- return ar;
- };
- __spreadArrays = function() {
- for (var s = 0, i2 = 0, il = arguments.length;i2 < il; i2++)
- s += arguments[i2].length;
- for (var r = Array(s), k = 0, i2 = 0;i2 < il; i2++)
- for (var a2 = arguments[i2], j = 0, jl = a2.length;j < jl; j++, k++)
- r[k] = a2[j];
- return r;
- };
- __spreadArray = function(to, from, pack) {
- if (pack || arguments.length === 2)
- for (var i2 = 0, l = from.length, ar;i2 < l; i2++) {
- if (ar || !(i2 in from)) {
- if (!ar)
- ar = Array.prototype.slice.call(from, 0, i2);
- ar[i2] = from[i2];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
- };
- __await = function(v) {
- return this instanceof __await ? (this.v = v, this) : new __await(v);
- };
- __asyncGenerator = function(thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator)
- throw new TypeError("Symbol.asyncIterator is not defined.");
- var g = generator.apply(thisArg, _arguments || []), i2, q = [];
- return i2 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i2[Symbol.asyncIterator] = function() {
- return this;
- }, i2;
- function awaitReturn(f) {
- return function(v) {
- return Promise.resolve(v).then(f, reject);
- };
- }
- function verb(n2, f) {
- if (g[n2]) {
- i2[n2] = function(v) {
- return new Promise(function(a2, b) {
- q.push([n2, v, a2, b]) > 1 || resume(n2, v);
- });
- };
- if (f)
- i2[n2] = f(i2[n2]);
- }
- }
- function resume(n2, v) {
- try {
- step(g[n2](v));
- } catch (e) {
- settle2(q[0][3], e);
- }
- }
- function step(r) {
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle2(q[0][2], r);
- }
- function fulfill(value) {
- resume("next", value);
- }
- function reject(value) {
- resume("throw", value);
- }
- function settle2(f, v) {
- if (f(v), q.shift(), q.length)
- resume(q[0][0], q[0][1]);
- }
- };
- __asyncDelegator = function(o2) {
- var i2, p;
- return i2 = {}, verb("next"), verb("throw", function(e) {
- throw e;
- }), verb("return"), i2[Symbol.iterator] = function() {
- return this;
- }, i2;
- function verb(n2, f) {
- i2[n2] = o2[n2] ? function(v) {
- return (p = !p) ? { value: __await(o2[n2](v)), done: false } : f ? f(v) : v;
- } : f;
- }
- };
- __asyncValues = function(o2) {
- if (!Symbol.asyncIterator)
- throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o2[Symbol.asyncIterator], i2;
- return m ? m.call(o2) : (o2 = typeof __values === "function" ? __values(o2) : o2[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() {
- return this;
- }, i2);
- function verb(n2) {
- i2[n2] = o2[n2] && function(v) {
- return new Promise(function(resolve9, reject) {
- v = o2[n2](v), settle2(resolve9, reject, v.done, v.value);
- });
- };
- }
- function settle2(resolve9, reject, d, v) {
- Promise.resolve(v).then(function(v2) {
- resolve9({ value: v2, done: d });
- }, reject);
- }
- };
- __makeTemplateObject = function(cooked, raw) {
- if (Object.defineProperty) {
- Object.defineProperty(cooked, "raw", { value: raw });
- } else {
- cooked.raw = raw;
- }
- return cooked;
- };
- var __setModuleDefault = Object.create ? function(o2, v) {
- Object.defineProperty(o2, "default", { enumerable: true, value: v });
- } : function(o2, v) {
- o2["default"] = v;
- };
- var ownKeys = function(o2) {
- ownKeys = Object.getOwnPropertyNames || function(o3) {
- var ar = [];
- for (var k in o3)
- if (Object.prototype.hasOwnProperty.call(o3, k))
- ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o2);
- };
- __importStar = function(mod2) {
- if (mod2 && mod2.__esModule)
- return mod2;
- var result = {};
- if (mod2 != null) {
- for (var k = ownKeys(mod2), i2 = 0;i2 < k.length; i2++)
- if (k[i2] !== "default")
- __createBinding(result, mod2, k[i2]);
- }
- __setModuleDefault(result, mod2);
- return result;
- };
- __importDefault = function(mod2) {
- return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
- };
- __classPrivateFieldGet5 = function(receiver, state, kind2, f) {
- if (kind2 === "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 kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
- };
- __classPrivateFieldSet5 = function(receiver, state, value, kind2, f) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "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 kind2 === "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(env4, value, async) {
- if (value !== null && value !== undefined) {
- 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 === undefined) {
- 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);
- }
- };
- env4.stack.push({ value, dispose, async });
- } else if (async) {
- env4.stack.push({ async: true });
- }
- return value;
- };
- var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error40, suppressed, message) {
- var e = new Error(message);
- return e.name = "SuppressedError", e.error = error40, e.suppressed = suppressed, e;
- };
- __disposeResources = function(env4) {
- function fail(e) {
- env4.error = env4.hasError ? new _SuppressedError(e, env4.error, "An error was suppressed during disposal.") : e;
- env4.hasError = true;
- }
- var r, s = 0;
- function next() {
- while (r = env4.stack.pop()) {
- try {
- if (!r.async && s === 1)
- return s = 0, env4.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 env4.hasError ? Promise.reject(env4.error) : Promise.resolve();
- if (env4.hasError)
- throw env4.error;
- }
- return next();
- };
- __rewriteRelativeImportExtension = function(path8, preserveJsx) {
- if (typeof path8 === "string" && /^\.\.?\//.test(path8)) {
- return path8.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 path8;
- };
- 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", __classPrivateFieldGet5);
- exporter("__classPrivateFieldSet", __classPrivateFieldSet5);
- exporter("__classPrivateFieldIn", __classPrivateFieldIn);
- exporter("__addDisposableResource", __addDisposableResource);
- exporter("__disposeResources", __disposeResources);
- exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension);
- });
-});
-
-// node_modules/@smithy/uuid/dist-cjs/randomUUID.js
-var require_randomUUID = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.randomUUID = undefined;
- var tslib_1 = require_tslib();
- var crypto_1 = tslib_1.__importDefault(__require("crypto"));
- exports.randomUUID = crypto_1.default.randomUUID.bind(crypto_1.default);
-});
-
-// node_modules/@smithy/uuid/dist-cjs/index.js
-var require_dist_cjs31 = __commonJS((exports) => {
- var randomUUID2 = require_randomUUID();
- var decimalToHex = Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0"));
- var v4 = () => {
- if (randomUUID2.randomUUID) {
- return randomUUID2.randomUUID();
- }
- const rnds = new Uint8Array(16);
- crypto.getRandomValues(rnds);
- rnds[6] = rnds[6] & 15 | 64;
- rnds[8] = rnds[8] & 63 | 128;
- return decimalToHex[rnds[0]] + decimalToHex[rnds[1]] + decimalToHex[rnds[2]] + decimalToHex[rnds[3]] + "-" + decimalToHex[rnds[4]] + decimalToHex[rnds[5]] + "-" + decimalToHex[rnds[6]] + decimalToHex[rnds[7]] + "-" + decimalToHex[rnds[8]] + decimalToHex[rnds[9]] + "-" + decimalToHex[rnds[10]] + decimalToHex[rnds[11]] + decimalToHex[rnds[12]] + decimalToHex[rnds[13]] + decimalToHex[rnds[14]] + decimalToHex[rnds[15]];
- };
- exports.v4 = v4;
-});
-
-// node_modules/@smithy/core/dist-cjs/submodules/serde/index.js
-var require_serde = __commonJS((exports) => {
- var uuid3 = require_dist_cjs31();
- var copyDocumentWithTransform = (source, schemaRef, transform2 = (_) => _) => source;
- var parseBoolean = (value) => {
- switch (value) {
- case "true":
- return true;
- case "false":
- return false;
- default:
- throw new Error(`Unable to parse boolean value "${value}"`);
- }
- };
- var expectBoolean = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- if (typeof value === "number") {
- if (value === 0 || value === 1) {
- logger2.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
- }
- if (value === 0) {
- return false;
- }
- if (value === 1) {
- return true;
- }
- }
- if (typeof value === "string") {
- const lower = value.toLowerCase();
- if (lower === "false" || lower === "true") {
- logger2.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
- }
- if (lower === "false") {
- return false;
- }
- if (lower === "true") {
- return true;
- }
- }
- if (typeof value === "boolean") {
- return value;
- }
- throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`);
- };
- var expectNumber = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- if (typeof value === "string") {
- const parsed = parseFloat(value);
- if (!Number.isNaN(parsed)) {
- if (String(parsed) !== String(value)) {
- logger2.warn(stackTraceWarning(`Expected number but observed string: ${value}`));
- }
- return parsed;
- }
- }
- if (typeof value === "number") {
- return value;
- }
- throw new TypeError(`Expected number, got ${typeof value}: ${value}`);
- };
- var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
- var expectFloat32 = (value) => {
- const expected = expectNumber(value);
- if (expected !== undefined && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) {
- if (Math.abs(expected) > MAX_FLOAT) {
- throw new TypeError(`Expected 32-bit float, got ${value}`);
- }
- }
- return expected;
- };
- var expectLong = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- if (Number.isInteger(value) && !Number.isNaN(value)) {
- return value;
- }
- throw new TypeError(`Expected integer, got ${typeof value}: ${value}`);
- };
- var expectInt = expectLong;
- var expectInt32 = (value) => expectSizedInt(value, 32);
- var expectShort = (value) => expectSizedInt(value, 16);
- var expectByte = (value) => expectSizedInt(value, 8);
- var expectSizedInt = (value, size) => {
- const expected = expectLong(value);
- if (expected !== undefined && castInt(expected, size) !== expected) {
- throw new TypeError(`Expected ${size}-bit integer, got ${value}`);
- }
- return expected;
- };
- var castInt = (value, size) => {
- switch (size) {
- case 32:
- return Int32Array.of(value)[0];
- case 16:
- return Int16Array.of(value)[0];
- case 8:
- return Int8Array.of(value)[0];
- }
- };
- var expectNonNull = (value, location) => {
- if (value === null || value === undefined) {
- if (location) {
- throw new TypeError(`Expected a non-null value for ${location}`);
- }
- throw new TypeError("Expected a non-null value");
- }
- return value;
- };
- var expectObject = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- if (typeof value === "object" && !Array.isArray(value)) {
- return value;
- }
- const receivedType = Array.isArray(value) ? "array" : typeof value;
- throw new TypeError(`Expected object, got ${receivedType}: ${value}`);
- };
- var expectString = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- if (typeof value === "string") {
- return value;
- }
- if (["boolean", "number", "bigint"].includes(typeof value)) {
- logger2.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));
- return String(value);
- }
- throw new TypeError(`Expected string, got ${typeof value}: ${value}`);
- };
- var expectUnion = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- const asObject = expectObject(value);
- const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k);
- if (setKeys.length === 0) {
- throw new TypeError(`Unions must have exactly one non-null member. None were found.`);
- }
- if (setKeys.length > 1) {
- throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`);
- }
- return asObject;
- };
- var strictParseDouble = (value) => {
- if (typeof value == "string") {
- return expectNumber(parseNumber2(value));
- }
- return expectNumber(value);
- };
- var strictParseFloat = strictParseDouble;
- var strictParseFloat32 = (value) => {
- if (typeof value == "string") {
- return expectFloat32(parseNumber2(value));
- }
- return expectFloat32(value);
- };
- var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;
- var parseNumber2 = (value) => {
- const matches = value.match(NUMBER_REGEX);
- if (matches === null || matches[0].length !== value.length) {
- throw new TypeError(`Expected real number, got implicit NaN`);
- }
- return parseFloat(value);
- };
- var limitedParseDouble = (value) => {
- if (typeof value == "string") {
- return parseFloatString(value);
- }
- return expectNumber(value);
- };
- var handleFloat = limitedParseDouble;
- var limitedParseFloat = limitedParseDouble;
- var limitedParseFloat32 = (value) => {
- if (typeof value == "string") {
- return parseFloatString(value);
- }
- return expectFloat32(value);
- };
- var parseFloatString = (value) => {
- switch (value) {
- case "NaN":
- return NaN;
- case "Infinity":
- return Infinity;
- case "-Infinity":
- return -Infinity;
- default:
- throw new Error(`Unable to parse float value: ${value}`);
- }
- };
- var strictParseLong = (value) => {
- if (typeof value === "string") {
- return expectLong(parseNumber2(value));
- }
- return expectLong(value);
- };
- var strictParseInt = strictParseLong;
- var strictParseInt32 = (value) => {
- if (typeof value === "string") {
- return expectInt32(parseNumber2(value));
- }
- return expectInt32(value);
- };
- var strictParseShort = (value) => {
- if (typeof value === "string") {
- return expectShort(parseNumber2(value));
- }
- return expectShort(value);
- };
- var strictParseByte = (value) => {
- if (typeof value === "string") {
- return expectByte(parseNumber2(value));
- }
- return expectByte(value);
- };
- var stackTraceWarning = (message) => {
- return String(new TypeError(message).stack || message).split(`
-`).slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join(`
-`);
- };
- var logger2 = {
- warn: console.warn
- };
- var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
- var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
- function dateToUtcString(date6) {
- const year2 = date6.getUTCFullYear();
- const month = date6.getUTCMonth();
- const dayOfWeek = date6.getUTCDay();
- const dayOfMonthInt = date6.getUTCDate();
- const hoursInt = date6.getUTCHours();
- const minutesInt = date6.getUTCMinutes();
- const secondsInt = date6.getUTCSeconds();
- const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`;
- const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`;
- const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`;
- const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`;
- return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year2} ${hoursString}:${minutesString}:${secondsString} GMT`;
- }
- var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);
- var parseRfc3339DateTime = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- if (typeof value !== "string") {
- throw new TypeError("RFC-3339 date-times must be expressed as strings");
- }
- const match = RFC3339.exec(value);
- if (!match) {
- throw new TypeError("Invalid RFC-3339 date-time value");
- }
- const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match;
- const year2 = strictParseShort(stripLeadingZeroes(yearStr));
- const month = parseDateValue(monthStr, "month", 1, 12);
- const day = parseDateValue(dayStr, "day", 1, 31);
- return buildDate(year2, month, day, { hours, minutes, seconds, fractionalMilliseconds });
- };
- var RFC3339_WITH_OFFSET$1 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);
- var parseRfc3339DateTimeWithOffset = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- if (typeof value !== "string") {
- throw new TypeError("RFC-3339 date-times must be expressed as strings");
- }
- const match = RFC3339_WITH_OFFSET$1.exec(value);
- if (!match) {
- throw new TypeError("Invalid RFC-3339 date-time value");
- }
- const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match;
- const year2 = strictParseShort(stripLeadingZeroes(yearStr));
- const month = parseDateValue(monthStr, "month", 1, 12);
- const day = parseDateValue(dayStr, "day", 1, 31);
- const date6 = buildDate(year2, month, day, { hours, minutes, seconds, fractionalMilliseconds });
- if (offsetStr.toUpperCase() != "Z") {
- date6.setTime(date6.getTime() - parseOffsetToMilliseconds(offsetStr));
- }
- return date6;
- };
- var IMF_FIXDATE$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
- var RFC_850_DATE$1 = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
- var ASC_TIME$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);
- var parseRfc7231DateTime = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- if (typeof value !== "string") {
- throw new TypeError("RFC-7231 date-times must be expressed as strings");
- }
- let match = IMF_FIXDATE$1.exec(value);
- if (match) {
- const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match;
- return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds });
- }
- match = RFC_850_DATE$1.exec(value);
- if (match) {
- const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match;
- return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), {
- hours,
- minutes,
- seconds,
- fractionalMilliseconds
- }));
- }
- match = ASC_TIME$1.exec(value);
- if (match) {
- const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match;
- return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds });
- }
- throw new TypeError("Invalid RFC-7231 date-time value");
- };
- var parseEpochTimestamp = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- let valueAsDouble;
- if (typeof value === "number") {
- valueAsDouble = value;
- } else if (typeof value === "string") {
- valueAsDouble = strictParseDouble(value);
- } else if (typeof value === "object" && value.tag === 1) {
- valueAsDouble = value.value;
- } else {
- throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");
- }
- if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) {
- throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");
- }
- return new Date(Math.round(valueAsDouble * 1000));
- };
- var buildDate = (year2, month, day, time4) => {
- const adjustedMonth = month - 1;
- validateDayOfMonth(year2, adjustedMonth, day);
- return new Date(Date.UTC(year2, adjustedMonth, day, parseDateValue(time4.hours, "hour", 0, 23), parseDateValue(time4.minutes, "minute", 0, 59), parseDateValue(time4.seconds, "seconds", 0, 60), parseMilliseconds2(time4.fractionalMilliseconds)));
- };
- var parseTwoDigitYear = (value) => {
- const thisYear = new Date().getUTCFullYear();
- const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value));
- if (valueInThisCentury < thisYear) {
- return valueInThisCentury + 100;
- }
- return valueInThisCentury;
- };
- var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1000;
- var adjustRfc850Year = (input) => {
- if (input.getTime() - new Date().getTime() > FIFTY_YEARS_IN_MILLIS) {
- return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds()));
- }
- return input;
- };
- var parseMonthByShortName = (value) => {
- const monthIdx = MONTHS.indexOf(value);
- if (monthIdx < 0) {
- throw new TypeError(`Invalid month: ${value}`);
- }
- return monthIdx + 1;
- };
- var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
- var validateDayOfMonth = (year2, month, day) => {
- let maxDays = DAYS_IN_MONTH[month];
- if (month === 1 && isLeapYear(year2)) {
- maxDays = 29;
- }
- if (day > maxDays) {
- throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year2}: ${day}`);
- }
- };
- var isLeapYear = (year2) => {
- return year2 % 4 === 0 && (year2 % 100 !== 0 || year2 % 400 === 0);
- };
- var parseDateValue = (value, type, lower, upper) => {
- const dateVal = strictParseByte(stripLeadingZeroes(value));
- if (dateVal < lower || dateVal > upper) {
- throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`);
- }
- return dateVal;
- };
- var parseMilliseconds2 = (value) => {
- if (value === null || value === undefined) {
- return 0;
- }
- return strictParseFloat32("0." + value) * 1000;
- };
- var parseOffsetToMilliseconds = (value) => {
- const directionStr = value[0];
- let direction = 1;
- if (directionStr == "+") {
- direction = 1;
- } else if (directionStr == "-") {
- direction = -1;
- } else {
- throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);
- }
- const hour = Number(value.substring(1, 3));
- const minute = Number(value.substring(4, 6));
- return direction * (hour * 60 + minute) * 60 * 1000;
- };
- var stripLeadingZeroes = (value) => {
- let idx = 0;
- while (idx < value.length - 1 && value.charAt(idx) === "0") {
- idx++;
- }
- if (idx === 0) {
- return value;
- }
- return value.slice(idx);
- };
- var LazyJsonString = function LazyJsonString2(val) {
- const str = Object.assign(new String(val), {
- deserializeJSON() {
- return JSON.parse(String(val));
- },
- toString() {
- return String(val);
- },
- toJSON() {
- return String(val);
- }
- });
- return str;
- };
- LazyJsonString.from = (object2) => {
- if (object2 && typeof object2 === "object" && (object2 instanceof LazyJsonString || ("deserializeJSON" in object2))) {
- return object2;
- } else if (typeof object2 === "string" || Object.getPrototypeOf(object2) === String.prototype) {
- return LazyJsonString(String(object2));
- }
- return LazyJsonString(JSON.stringify(object2));
- };
- LazyJsonString.fromObject = LazyJsonString.from;
- function quoteHeader(part) {
- if (part.includes(",") || part.includes('"')) {
- part = `"${part.replace(/"/g, "\\\"")}"`;
- }
- return part;
- }
- var ddd = `(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`;
- var mmm = `(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`;
- var time3 = `(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`;
- var date5 = `(\\d?\\d)`;
- var year = `(\\d{4})`;
- var RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/);
- var IMF_FIXDATE = new RegExp(`^${ddd}, ${date5} ${mmm} ${year} ${time3} GMT$`);
- var RFC_850_DATE = new RegExp(`^${ddd}, ${date5}-${mmm}-(\\d\\d) ${time3} GMT$`);
- var ASC_TIME = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time3} ${year}$`);
- var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
- var _parseEpochTimestamp = (value) => {
- if (value == null) {
- return;
- }
- let num = NaN;
- if (typeof value === "number") {
- num = value;
- } else if (typeof value === "string") {
- if (!/^-?\d*\.?\d+$/.test(value)) {
- throw new TypeError(`parseEpochTimestamp - numeric string invalid.`);
- }
- num = Number.parseFloat(value);
- } else if (typeof value === "object" && value.tag === 1) {
- num = value.value;
- }
- if (isNaN(num) || Math.abs(num) === Infinity) {
- throw new TypeError("Epoch timestamps must be valid finite numbers.");
- }
- return new Date(Math.round(num * 1000));
- };
- var _parseRfc3339DateTimeWithOffset = (value) => {
- if (value == null) {
- return;
- }
- if (typeof value !== "string") {
- throw new TypeError("RFC3339 timestamps must be strings");
- }
- const matches = RFC3339_WITH_OFFSET.exec(value);
- if (!matches) {
- throw new TypeError(`Invalid RFC3339 timestamp format ${value}`);
- }
- const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms, offsetStr] = matches;
- range(monthStr, 1, 12);
- range(dayStr, 1, 31);
- range(hours, 0, 23);
- range(minutes, 0, 59);
- range(seconds, 0, 60);
- const date6 = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1000) : 0));
- date6.setUTCFullYear(Number(yearStr));
- if (offsetStr.toUpperCase() != "Z") {
- const [, sign, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [undefined, "+", 0, 0];
- const scalar = sign === "-" ? 1 : -1;
- date6.setTime(date6.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1000 + Number(offsetM) * 60 * 1000));
- }
- return date6;
- };
- var _parseRfc7231DateTime = (value) => {
- if (value == null) {
- return;
- }
- if (typeof value !== "string") {
- throw new TypeError("RFC7231 timestamps must be strings.");
- }
- let day;
- let month;
- let year2;
- let hour;
- let minute;
- let second;
- let fraction;
- let matches;
- if (matches = IMF_FIXDATE.exec(value)) {
- [, day, month, year2, hour, minute, second, fraction] = matches;
- } else if (matches = RFC_850_DATE.exec(value)) {
- [, day, month, year2, hour, minute, second, fraction] = matches;
- year2 = (Number(year2) + 1900).toString();
- } else if (matches = ASC_TIME.exec(value)) {
- [, month, day, hour, minute, second, fraction, year2] = matches;
- }
- if (year2 && second) {
- const timestamp = Date.UTC(Number(year2), months.indexOf(month), Number(day), Number(hour), Number(minute), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1000) : 0);
- range(day, 1, 31);
- range(hour, 0, 23);
- range(minute, 0, 59);
- range(second, 0, 60);
- const date6 = new Date(timestamp);
- date6.setUTCFullYear(Number(year2));
- return date6;
- }
- throw new TypeError(`Invalid RFC7231 date-time value ${value}.`);
- };
- function range(v, min, max) {
- const _v = Number(v);
- if (_v < min || _v > max) {
- throw new Error(`Value ${_v} out of range [${min}, ${max}]`);
- }
- }
- function splitEvery(value, delimiter, numDelimiters) {
- if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) {
- throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery.");
- }
- const segments = value.split(delimiter);
- if (numDelimiters === 1) {
- return segments;
- }
- const compoundSegments = [];
- let currentSegment = "";
- for (let i2 = 0;i2 < segments.length; i2++) {
- if (currentSegment === "") {
- currentSegment = segments[i2];
- } else {
- currentSegment += delimiter + segments[i2];
- }
- if ((i2 + 1) % numDelimiters === 0) {
- compoundSegments.push(currentSegment);
- currentSegment = "";
- }
- }
- if (currentSegment !== "") {
- compoundSegments.push(currentSegment);
- }
- return compoundSegments;
- }
- var splitHeader = (value) => {
- const z2 = value.length;
- const values = [];
- let withinQuotes = false;
- let prevChar = undefined;
- let anchor = 0;
- for (let i2 = 0;i2 < z2; ++i2) {
- const char = value[i2];
- switch (char) {
- case `"`:
- if (prevChar !== "\\") {
- withinQuotes = !withinQuotes;
- }
- break;
- case ",":
- if (!withinQuotes) {
- values.push(value.slice(anchor, i2));
- anchor = i2 + 1;
- }
- break;
- }
- prevChar = char;
- }
- values.push(value.slice(anchor));
- return values.map((v) => {
- v = v.trim();
- const z3 = v.length;
- if (z3 < 2) {
- return v;
- }
- if (v[0] === `"` && v[z3 - 1] === `"`) {
- v = v.slice(1, z3 - 1);
- }
- return v.replace(/\\"/g, '"');
- });
- };
- var format3 = /^-?\d*(\.\d+)?$/;
-
- class NumericValue {
- string;
- type;
- constructor(string4, type) {
- this.string = string4;
- this.type = type;
- if (!format3.test(string4)) {
- throw new Error(`@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".`);
- }
- }
- toString() {
- return this.string;
- }
- static [Symbol.hasInstance](object2) {
- if (!object2 || typeof object2 !== "object") {
- return false;
- }
- const _nv = object2;
- return NumericValue.prototype.isPrototypeOf(object2) || _nv.type === "bigDecimal" && format3.test(_nv.string);
- }
- }
- function nv(input) {
- return new NumericValue(String(input), "bigDecimal");
- }
- exports.generateIdempotencyToken = uuid3.v4;
- exports.LazyJsonString = LazyJsonString;
- exports.NumericValue = NumericValue;
- exports._parseEpochTimestamp = _parseEpochTimestamp;
- exports._parseRfc3339DateTimeWithOffset = _parseRfc3339DateTimeWithOffset;
- exports._parseRfc7231DateTime = _parseRfc7231DateTime;
- exports.copyDocumentWithTransform = copyDocumentWithTransform;
- exports.dateToUtcString = dateToUtcString;
- exports.expectBoolean = expectBoolean;
- exports.expectByte = expectByte;
- exports.expectFloat32 = expectFloat32;
- exports.expectInt = expectInt;
- exports.expectInt32 = expectInt32;
- exports.expectLong = expectLong;
- exports.expectNonNull = expectNonNull;
- exports.expectNumber = expectNumber;
- exports.expectObject = expectObject;
- exports.expectShort = expectShort;
- exports.expectString = expectString;
- exports.expectUnion = expectUnion;
- exports.handleFloat = handleFloat;
- exports.limitedParseDouble = limitedParseDouble;
- exports.limitedParseFloat = limitedParseFloat;
- exports.limitedParseFloat32 = limitedParseFloat32;
- exports.logger = logger2;
- exports.nv = nv;
- exports.parseBoolean = parseBoolean;
- exports.parseEpochTimestamp = parseEpochTimestamp;
- exports.parseRfc3339DateTime = parseRfc3339DateTime;
- exports.parseRfc3339DateTimeWithOffset = parseRfc3339DateTimeWithOffset;
- exports.parseRfc7231DateTime = parseRfc7231DateTime;
- exports.quoteHeader = quoteHeader;
- exports.splitEvery = splitEvery;
- exports.splitHeader = splitHeader;
- exports.strictParseByte = strictParseByte;
- exports.strictParseDouble = strictParseDouble;
- exports.strictParseFloat = strictParseFloat;
- exports.strictParseFloat32 = strictParseFloat32;
- exports.strictParseInt = strictParseInt;
- exports.strictParseInt32 = strictParseInt32;
- exports.strictParseLong = strictParseLong;
- exports.strictParseShort = strictParseShort;
-});
-
-// node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
-var require_dist_cjs32 = __commonJS((exports) => {
- var isArrayBuffer3 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
- exports.isArrayBuffer = isArrayBuffer3;
-});
-
-// node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
-var require_dist_cjs33 = __commonJS((exports) => {
- var isArrayBuffer3 = require_dist_cjs32();
- var buffer = __require("buffer");
- var fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
- if (!isArrayBuffer3.isArrayBuffer(input)) {
- throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
- }
- return buffer.Buffer.from(input, offset, length);
- };
- var fromString = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input);
- };
- exports.fromArrayBuffer = fromArrayBuffer;
- exports.fromString = fromString;
-});
-
-// node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js
-var require_fromBase643 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.fromBase64 = undefined;
- var util_buffer_from_1 = require_dist_cjs33();
- var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
- var fromBase64 = (input) => {
- if (input.length * 3 % 4 !== 0) {
- throw new TypeError(`Incorrect padding on base64 string.`);
- }
- if (!BASE64_REGEX.exec(input)) {
- throw new TypeError(`Invalid base64 string.`);
- }
- const buffer = (0, util_buffer_from_1.fromString)(input, "base64");
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
- };
- exports.fromBase64 = fromBase64;
-});
-
-// node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js
-var require_toBase643 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.toBase64 = undefined;
- var util_buffer_from_1 = require_dist_cjs33();
- var util_utf8_1 = require_dist_cjs17();
- var toBase64 = (_input) => {
- let input;
- if (typeof _input === "string") {
- input = (0, util_utf8_1.fromUtf8)(_input);
- } else {
- input = _input;
- }
- if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
- throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
- }
- return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64");
- };
- exports.toBase64 = toBase64;
-});
-
-// node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/index.js
-var require_dist_cjs34 = __commonJS((exports) => {
- var fromBase64 = require_fromBase643();
- var toBase64 = require_toBase643();
- Object.prototype.hasOwnProperty.call(fromBase64, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: fromBase64["__proto__"]
- });
- Object.keys(fromBase64).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = fromBase64[k];
- });
- Object.prototype.hasOwnProperty.call(toBase64, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: toBase64["__proto__"]
- });
- Object.keys(toBase64).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = toBase64[k];
- });
-});
-
-// node_modules/@smithy/core/dist-cjs/submodules/event-streams/index.js
-var require_event_streams = __commonJS((exports) => {
- var utilUtf8 = require_dist_cjs17();
-
- class EventStreamSerde {
- marshaller;
- serializer;
- deserializer;
- serdeContext;
- defaultContentType;
- constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType }) {
- this.marshaller = marshaller;
- this.serializer = serializer;
- this.deserializer = deserializer;
- this.serdeContext = serdeContext;
- this.defaultContentType = defaultContentType;
- }
- async serializeEventStream({ eventStream: eventStream2, requestSchema, initialRequest }) {
- const marshaller = this.marshaller;
- const eventStreamMember = requestSchema.getEventStreamMember();
- const unionSchema = requestSchema.getMemberSchema(eventStreamMember);
- const serializer = this.serializer;
- const defaultContentType = this.defaultContentType;
- const initialRequestMarker = Symbol("initialRequestMarker");
- const eventStreamIterable = {
- async* [Symbol.asyncIterator]() {
- if (initialRequest) {
- const headers = {
- ":event-type": { type: "string", value: "initial-request" },
- ":message-type": { type: "string", value: "event" },
- ":content-type": { type: "string", value: defaultContentType }
- };
- serializer.write(requestSchema, initialRequest);
- const body = serializer.flush();
- yield {
- [initialRequestMarker]: true,
- headers,
- body
- };
- }
- for await (const page of eventStream2) {
- yield page;
- }
- }
- };
- return marshaller.serialize(eventStreamIterable, (event) => {
- if (event[initialRequestMarker]) {
- return {
- headers: event.headers,
- body: event.body
- };
- }
- const unionMember = Object.keys(event).find((key) => {
- return key !== "__type";
- }) ?? "";
- const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event);
- const headers = {
- ":event-type": { type: "string", value: eventType },
- ":message-type": { type: "string", value: "event" },
- ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType },
- ...additionalHeaders
- };
- return {
- headers,
- body
- };
- });
- }
- async deserializeEventStream({ response: response2, responseSchema, initialResponseContainer }) {
- const marshaller = this.marshaller;
- const eventStreamMember = responseSchema.getEventStreamMember();
- const unionSchema = responseSchema.getMemberSchema(eventStreamMember);
- const memberSchemas = unionSchema.getMemberSchemas();
- const initialResponseMarker = Symbol("initialResponseMarker");
- const asyncIterable = marshaller.deserialize(response2.body, async (event) => {
- const unionMember = Object.keys(event).find((key) => {
- return key !== "__type";
- }) ?? "";
- const body = event[unionMember].body;
- if (unionMember === "initial-response") {
- const dataObject = await this.deserializer.read(responseSchema, body);
- delete dataObject[eventStreamMember];
- return {
- [initialResponseMarker]: true,
- ...dataObject
- };
- } else if (unionMember in memberSchemas) {
- const eventStreamSchema = memberSchemas[unionMember];
- if (eventStreamSchema.isStructSchema()) {
- const out = {};
- let hasBindings = false;
- for (const [name, member] of eventStreamSchema.structIterator()) {
- const { eventHeader, eventPayload } = member.getMergedTraits();
- hasBindings = hasBindings || Boolean(eventHeader || eventPayload);
- if (eventPayload) {
- if (member.isBlobSchema()) {
- out[name] = body;
- } else if (member.isStringSchema()) {
- out[name] = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(body);
- } else if (member.isStructSchema()) {
- out[name] = await this.deserializer.read(member, body);
- }
- } else if (eventHeader) {
- const value = event[unionMember].headers[name]?.value;
- if (value != null) {
- if (member.isNumericSchema()) {
- if (value && typeof value === "object" && "bytes" in value) {
- out[name] = BigInt(value.toString());
- } else {
- out[name] = Number(value);
- }
- } else {
- out[name] = value;
- }
- }
- }
- }
- if (hasBindings) {
- return {
- [unionMember]: out
- };
- }
- if (body.byteLength === 0) {
- return {
- [unionMember]: {}
- };
- }
- }
- return {
- [unionMember]: await this.deserializer.read(eventStreamSchema, body)
- };
- } else {
- return {
- $unknown: event
- };
- }
- });
- const asyncIterator2 = asyncIterable[Symbol.asyncIterator]();
- const firstEvent = await asyncIterator2.next();
- if (firstEvent.done) {
- return asyncIterable;
- }
- if (firstEvent.value?.[initialResponseMarker]) {
- if (!responseSchema) {
- throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");
- }
- for (const [key, value] of Object.entries(firstEvent.value)) {
- initialResponseContainer[key] = value;
- }
- }
- return {
- async* [Symbol.asyncIterator]() {
- if (!firstEvent?.value?.[initialResponseMarker]) {
- yield firstEvent.value;
- }
- while (true) {
- const { done, value } = await asyncIterator2.next();
- if (done) {
- break;
- }
- yield value;
- }
- }
- };
- }
- writeEventBody(unionMember, unionSchema, event) {
- const serializer = this.serializer;
- let eventType = unionMember;
- let explicitPayloadMember = null;
- let explicitPayloadContentType;
- const isKnownSchema = (() => {
- const struct = unionSchema.getSchema();
- return struct[4].includes(unionMember);
- })();
- const additionalHeaders = {};
- if (!isKnownSchema) {
- const [type, value] = event[unionMember];
- eventType = type;
- serializer.write(15, value);
- } else {
- const eventSchema = unionSchema.getMemberSchema(unionMember);
- if (eventSchema.isStructSchema()) {
- for (const [memberName, memberSchema] of eventSchema.structIterator()) {
- const { eventHeader, eventPayload } = memberSchema.getMergedTraits();
- if (eventPayload) {
- explicitPayloadMember = memberName;
- } else if (eventHeader) {
- const value = event[unionMember][memberName];
- let type = "binary";
- if (memberSchema.isNumericSchema()) {
- if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) {
- type = "integer";
- } else {
- type = "long";
- }
- } else if (memberSchema.isTimestampSchema()) {
- type = "timestamp";
- } else if (memberSchema.isStringSchema()) {
- type = "string";
- } else if (memberSchema.isBooleanSchema()) {
- type = "boolean";
- }
- if (value != null) {
- additionalHeaders[memberName] = {
- type,
- value
- };
- delete event[unionMember][memberName];
- }
- }
- }
- if (explicitPayloadMember !== null) {
- const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember);
- if (payloadSchema.isBlobSchema()) {
- explicitPayloadContentType = "application/octet-stream";
- } else if (payloadSchema.isStringSchema()) {
- explicitPayloadContentType = "text/plain";
- }
- serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]);
- } else {
- serializer.write(eventSchema, event[unionMember]);
- }
- } else if (eventSchema.isUnitSchema()) {
- serializer.write(eventSchema, {});
- } else {
- throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union.");
- }
- }
- const messageSerialization = serializer.flush() ?? new Uint8Array;
- const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? utilUtf8.fromUtf8)(messageSerialization) : messageSerialization;
- return {
- body,
- eventType,
- explicitPayloadContentType,
- additionalHeaders
- };
- }
- }
- exports.EventStreamSerde = EventStreamSerde;
-});
-
-// node_modules/@smithy/core/dist-cjs/submodules/protocols/index.js
-var require_protocols = __commonJS((exports) => {
- var utilStream = require_dist_cjs26();
- var schema2 = require_schema();
- var serde2 = require_serde();
- var protocolHttp = require_dist_cjs28();
- var utilBase64 = require_dist_cjs34();
- var utilUtf8 = require_dist_cjs17();
- var collectBody = async (streamBody = new Uint8Array, context) => {
- if (streamBody instanceof Uint8Array) {
- return utilStream.Uint8ArrayBlobAdapter.mutate(streamBody);
- }
- if (!streamBody) {
- return utilStream.Uint8ArrayBlobAdapter.mutate(new Uint8Array);
- }
- const fromContext = context.streamCollector(streamBody);
- return utilStream.Uint8ArrayBlobAdapter.mutate(await fromContext);
- };
- function extendedEncodeURIComponent(str) {
- return encodeURIComponent(str).replace(/[!'()*]/g, function(c5) {
- return "%" + c5.charCodeAt(0).toString(16).toUpperCase();
- });
- }
-
- class SerdeContext {
- serdeContext;
- setSerdeContext(serdeContext) {
- this.serdeContext = serdeContext;
- }
- }
-
- class HttpProtocol extends SerdeContext {
- options;
- compositeErrorRegistry;
- constructor(options2) {
- super();
- this.options = options2;
- this.compositeErrorRegistry = schema2.TypeRegistry.for(options2.defaultNamespace);
- for (const etr of options2.errorTypeRegistries ?? []) {
- this.compositeErrorRegistry.copyFrom(etr);
- }
- }
- getRequestType() {
- return protocolHttp.HttpRequest;
- }
- getResponseType() {
- return protocolHttp.HttpResponse;
- }
- setSerdeContext(serdeContext) {
- this.serdeContext = serdeContext;
- this.serializer.setSerdeContext(serdeContext);
- this.deserializer.setSerdeContext(serdeContext);
- if (this.getPayloadCodec()) {
- this.getPayloadCodec().setSerdeContext(serdeContext);
- }
- }
- updateServiceEndpoint(request2, endpoint2) {
- if ("url" in endpoint2) {
- request2.protocol = endpoint2.url.protocol;
- request2.hostname = endpoint2.url.hostname;
- request2.port = endpoint2.url.port ? Number(endpoint2.url.port) : undefined;
- request2.path = endpoint2.url.pathname;
- request2.fragment = endpoint2.url.hash || undefined;
- request2.username = endpoint2.url.username || undefined;
- request2.password = endpoint2.url.password || undefined;
- if (!request2.query) {
- request2.query = {};
- }
- for (const [k, v] of endpoint2.url.searchParams.entries()) {
- request2.query[k] = v;
- }
- if (endpoint2.headers) {
- for (const [name, values] of Object.entries(endpoint2.headers)) {
- request2.headers[name] = values.join(", ");
- }
- }
- return request2;
- } else {
- request2.protocol = endpoint2.protocol;
- request2.hostname = endpoint2.hostname;
- request2.port = endpoint2.port ? Number(endpoint2.port) : undefined;
- request2.path = endpoint2.path;
- request2.query = {
- ...endpoint2.query
- };
- if (endpoint2.headers) {
- for (const [name, value] of Object.entries(endpoint2.headers)) {
- request2.headers[name] = value;
- }
- }
- return request2;
- }
- }
- setHostPrefix(request2, operationSchema, input) {
- if (this.serdeContext?.disableHostPrefix) {
- return;
- }
- const inputNs = schema2.NormalizedSchema.of(operationSchema.input);
- const opTraits = schema2.translateTraits(operationSchema.traits ?? {});
- if (opTraits.endpoint) {
- let hostPrefix = opTraits.endpoint?.[0];
- if (typeof hostPrefix === "string") {
- const hostLabelInputs = [...inputNs.structIterator()].filter(([, member]) => member.getMergedTraits().hostLabel);
- for (const [name] of hostLabelInputs) {
- const replacement = input[name];
- if (typeof replacement !== "string") {
- throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`);
- }
- hostPrefix = hostPrefix.replace(`{${name}}`, replacement);
- }
- request2.hostname = hostPrefix + request2.hostname;
- }
- }
- }
- deserializeMetadata(output) {
- return {
- httpStatusCode: output.statusCode,
- requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
- extendedRequestId: output.headers["x-amz-id-2"],
- cfId: output.headers["x-amz-cf-id"]
- };
- }
- async serializeEventStream({ eventStream: eventStream2, requestSchema, initialRequest }) {
- const eventStreamSerde = await this.loadEventStreamCapability();
- return eventStreamSerde.serializeEventStream({
- eventStream: eventStream2,
- requestSchema,
- initialRequest
- });
- }
- async deserializeEventStream({ response: response2, responseSchema, initialResponseContainer }) {
- const eventStreamSerde = await this.loadEventStreamCapability();
- return eventStreamSerde.deserializeEventStream({
- response: response2,
- responseSchema,
- initialResponseContainer
- });
- }
- async loadEventStreamCapability() {
- const { EventStreamSerde } = await Promise.resolve().then(() => __toESM(require_event_streams()));
- return new EventStreamSerde({
- marshaller: this.getEventStreamMarshaller(),
- serializer: this.serializer,
- deserializer: this.deserializer,
- serdeContext: this.serdeContext,
- defaultContentType: this.getDefaultContentType()
- });
- }
- getDefaultContentType() {
- throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`);
- }
- async deserializeHttpMessage(schema3, context, response2, arg4, arg5) {
- return [];
- }
- getEventStreamMarshaller() {
- const context = this.serdeContext;
- if (!context.eventStreamMarshaller) {
- throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");
- }
- return context.eventStreamMarshaller;
- }
- }
-
- class HttpBindingProtocol extends HttpProtocol {
- async serializeRequest(operationSchema, _input, context) {
- const input = _input && typeof _input === "object" ? _input : {};
- const serializer = this.serializer;
- const query = {};
- const headers = {};
- const endpoint2 = await context.endpoint();
- const ns = schema2.NormalizedSchema.of(operationSchema?.input);
- const payloadMemberNames = [];
- const payloadMemberSchemas = [];
- let hasNonHttpBindingMember = false;
- let payload;
- const request2 = new protocolHttp.HttpRequest({
- protocol: "",
- hostname: "",
- port: undefined,
- path: "",
- fragment: undefined,
- query,
- headers,
- body: undefined
- });
- if (endpoint2) {
- this.updateServiceEndpoint(request2, endpoint2);
- this.setHostPrefix(request2, operationSchema, input);
- const opTraits = schema2.translateTraits(operationSchema.traits);
- if (opTraits.http) {
- request2.method = opTraits.http[0];
- const [path8, search] = opTraits.http[1].split("?");
- if (request2.path == "/") {
- request2.path = path8;
- } else {
- request2.path += path8;
- }
- const traitSearchParams = new URLSearchParams(search ?? "");
- Object.assign(query, Object.fromEntries(traitSearchParams));
- }
- }
- for (const [memberName, memberNs] of ns.structIterator()) {
- const memberTraits = memberNs.getMergedTraits() ?? {};
- const inputMemberValue = input[memberName];
- if (inputMemberValue == null && !memberNs.isIdempotencyToken()) {
- if (memberTraits.httpLabel) {
- if (request2.path.includes(`{${memberName}+}`) || request2.path.includes(`{${memberName}}`)) {
- throw new Error(`No value provided for input HTTP label: ${memberName}.`);
- }
- }
- continue;
- }
- if (memberTraits.httpPayload) {
- const isStreaming = memberNs.isStreaming();
- if (isStreaming) {
- const isEventStream = memberNs.isStructSchema();
- if (isEventStream) {
- if (input[memberName]) {
- payload = await this.serializeEventStream({
- eventStream: input[memberName],
- requestSchema: ns
- });
- }
- } else {
- payload = inputMemberValue;
- }
- } else {
- serializer.write(memberNs, inputMemberValue);
- payload = serializer.flush();
- }
- } else if (memberTraits.httpLabel) {
- serializer.write(memberNs, inputMemberValue);
- const replacement = serializer.flush();
- if (request2.path.includes(`{${memberName}+}`)) {
- request2.path = request2.path.replace(`{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent).join("/"));
- } else if (request2.path.includes(`{${memberName}}`)) {
- request2.path = request2.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement));
- }
- } else if (memberTraits.httpHeader) {
- serializer.write(memberNs, inputMemberValue);
- headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush());
- } else if (typeof memberTraits.httpPrefixHeaders === "string") {
- for (const [key, val] of Object.entries(inputMemberValue)) {
- const amalgam = memberTraits.httpPrefixHeaders + key;
- serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val);
- headers[amalgam.toLowerCase()] = serializer.flush();
- }
- } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) {
- this.serializeQuery(memberNs, inputMemberValue, query);
- } else {
- hasNonHttpBindingMember = true;
- payloadMemberNames.push(memberName);
- payloadMemberSchemas.push(memberNs);
- }
- }
- if (hasNonHttpBindingMember && input) {
- const [namespace, name] = (ns.getName(true) ?? "#Unknown").split("#");
- const requiredMembers = ns.getSchema()[6];
- const payloadSchema = [
- 3,
- namespace,
- name,
- ns.getMergedTraits(),
- payloadMemberNames,
- payloadMemberSchemas,
- undefined
- ];
- if (requiredMembers) {
- payloadSchema[6] = requiredMembers;
- } else {
- payloadSchema.pop();
- }
- serializer.write(payloadSchema, input);
- payload = serializer.flush();
- }
- request2.headers = headers;
- request2.query = query;
- request2.body = payload;
- return request2;
- }
- serializeQuery(ns, data, query) {
- const serializer = this.serializer;
- const traits2 = ns.getMergedTraits();
- if (traits2.httpQueryParams) {
- for (const [key, val] of Object.entries(data)) {
- if (!(key in query)) {
- const valueSchema = ns.getValueSchema();
- Object.assign(valueSchema.getMergedTraits(), {
- ...traits2,
- httpQuery: key,
- httpQueryParams: undefined
- });
- this.serializeQuery(valueSchema, val, query);
- }
- }
- return;
- }
- if (ns.isListSchema()) {
- const sparse = !!ns.getMergedTraits().sparse;
- const buffer = [];
- for (const item of data) {
- serializer.write([ns.getValueSchema(), traits2], item);
- const serializable = serializer.flush();
- if (sparse || serializable !== undefined) {
- buffer.push(serializable);
- }
- }
- query[traits2.httpQuery] = buffer;
- } else {
- serializer.write([ns, traits2], data);
- query[traits2.httpQuery] = serializer.flush();
- }
- }
- async deserializeResponse(operationSchema, context, response2) {
- const deserializer = this.deserializer;
- const ns = schema2.NormalizedSchema.of(operationSchema.output);
- const dataObject = {};
- if (response2.statusCode >= 300) {
- const bytes = await collectBody(response2.body, context);
- if (bytes.byteLength > 0) {
- Object.assign(dataObject, await deserializer.read(15, bytes));
- }
- await this.handleError(operationSchema, context, response2, dataObject, this.deserializeMetadata(response2));
- throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.");
- }
- for (const header in response2.headers) {
- const value = response2.headers[header];
- delete response2.headers[header];
- response2.headers[header.toLowerCase()] = value;
- }
- const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response2, dataObject);
- if (nonHttpBindingMembers.length) {
- const bytes = await collectBody(response2.body, context);
- if (bytes.byteLength > 0) {
- const dataFromBody = await deserializer.read(ns, bytes);
- for (const member of nonHttpBindingMembers) {
- if (dataFromBody[member] != null) {
- dataObject[member] = dataFromBody[member];
- }
- }
- }
- } else if (nonHttpBindingMembers.discardResponseBody) {
- await collectBody(response2.body, context);
- }
- dataObject.$metadata = this.deserializeMetadata(response2);
- return dataObject;
- }
- async deserializeHttpMessage(schema$1, context, response2, arg4, arg5) {
- let dataObject;
- if (arg4 instanceof Set) {
- dataObject = arg5;
- } else {
- dataObject = arg4;
- }
- let discardResponseBody = true;
- const deserializer = this.deserializer;
- const ns = schema2.NormalizedSchema.of(schema$1);
- const nonHttpBindingMembers = [];
- for (const [memberName, memberSchema] of ns.structIterator()) {
- const memberTraits = memberSchema.getMemberTraits();
- if (memberTraits.httpPayload) {
- discardResponseBody = false;
- const isStreaming = memberSchema.isStreaming();
- if (isStreaming) {
- const isEventStream = memberSchema.isStructSchema();
- if (isEventStream) {
- dataObject[memberName] = await this.deserializeEventStream({
- response: response2,
- responseSchema: ns
- });
- } else {
- dataObject[memberName] = utilStream.sdkStreamMixin(response2.body);
- }
- } else if (response2.body) {
- const bytes = await collectBody(response2.body, context);
- if (bytes.byteLength > 0) {
- dataObject[memberName] = await deserializer.read(memberSchema, bytes);
- }
- }
- } else if (memberTraits.httpHeader) {
- const key = String(memberTraits.httpHeader).toLowerCase();
- const value = response2.headers[key];
- if (value != null) {
- if (memberSchema.isListSchema()) {
- const headerListValueSchema = memberSchema.getValueSchema();
- headerListValueSchema.getMergedTraits().httpHeader = key;
- let sections;
- if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === 4) {
- sections = serde2.splitEvery(value, ",", 2);
- } else {
- sections = serde2.splitHeader(value);
- }
- const list2 = [];
- for (const section of sections) {
- list2.push(await deserializer.read(headerListValueSchema, section.trim()));
- }
- dataObject[memberName] = list2;
- } else {
- dataObject[memberName] = await deserializer.read(memberSchema, value);
- }
- }
- } else if (memberTraits.httpPrefixHeaders !== undefined) {
- dataObject[memberName] = {};
- for (const [header, value] of Object.entries(response2.headers)) {
- if (header.startsWith(memberTraits.httpPrefixHeaders)) {
- const valueSchema = memberSchema.getValueSchema();
- valueSchema.getMergedTraits().httpHeader = header;
- dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read(valueSchema, value);
- }
- }
- } else if (memberTraits.httpResponseCode) {
- dataObject[memberName] = response2.statusCode;
- } else {
- nonHttpBindingMembers.push(memberName);
- }
- }
- nonHttpBindingMembers.discardResponseBody = discardResponseBody;
- return nonHttpBindingMembers;
- }
- }
-
- class RpcProtocol extends HttpProtocol {
- async serializeRequest(operationSchema, _input, context) {
- const serializer = this.serializer;
- const query = {};
- const headers = {};
- const endpoint2 = await context.endpoint();
- const ns = schema2.NormalizedSchema.of(operationSchema?.input);
- const schema$1 = ns.getSchema();
- let payload;
- const input = _input && typeof _input === "object" ? _input : {};
- const request2 = new protocolHttp.HttpRequest({
- protocol: "",
- hostname: "",
- port: undefined,
- path: "/",
- fragment: undefined,
- query,
- headers,
- body: undefined
- });
- if (endpoint2) {
- this.updateServiceEndpoint(request2, endpoint2);
- this.setHostPrefix(request2, operationSchema, input);
- }
- if (input) {
- const eventStreamMember = ns.getEventStreamMember();
- if (eventStreamMember) {
- if (input[eventStreamMember]) {
- const initialRequest = {};
- for (const [memberName, memberSchema] of ns.structIterator()) {
- if (memberName !== eventStreamMember && input[memberName]) {
- serializer.write(memberSchema, input[memberName]);
- initialRequest[memberName] = serializer.flush();
- }
- }
- payload = await this.serializeEventStream({
- eventStream: input[eventStreamMember],
- requestSchema: ns,
- initialRequest
- });
- }
- } else {
- serializer.write(schema$1, input);
- payload = serializer.flush();
- }
- }
- request2.headers = Object.assign(request2.headers, headers);
- request2.query = query;
- request2.body = payload;
- request2.method = "POST";
- return request2;
- }
- async deserializeResponse(operationSchema, context, response2) {
- const deserializer = this.deserializer;
- const ns = schema2.NormalizedSchema.of(operationSchema.output);
- const dataObject = {};
- if (response2.statusCode >= 300) {
- const bytes = await collectBody(response2.body, context);
- if (bytes.byteLength > 0) {
- Object.assign(dataObject, await deserializer.read(15, bytes));
- }
- await this.handleError(operationSchema, context, response2, dataObject, this.deserializeMetadata(response2));
- throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.");
- }
- for (const header in response2.headers) {
- const value = response2.headers[header];
- delete response2.headers[header];
- response2.headers[header.toLowerCase()] = value;
- }
- const eventStreamMember = ns.getEventStreamMember();
- if (eventStreamMember) {
- dataObject[eventStreamMember] = await this.deserializeEventStream({
- response: response2,
- responseSchema: ns,
- initialResponseContainer: dataObject
- });
- } else {
- const bytes = await collectBody(response2.body, context);
- if (bytes.byteLength > 0) {
- Object.assign(dataObject, await deserializer.read(ns, bytes));
- }
- }
- dataObject.$metadata = this.deserializeMetadata(response2);
- return dataObject;
- }
- }
- var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => {
- if (input != null && input[memberName] !== undefined) {
- const labelValue = labelValueProvider();
- if (labelValue == null || labelValue.length <= 0) {
- throw new Error("Empty value provided for input HTTP label: " + memberName + ".");
- }
- resolvedPath2 = resolvedPath2.replace(uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue));
- } else {
- throw new Error("No value provided for input HTTP label: " + memberName + ".");
- }
- return resolvedPath2;
- };
- function requestBuilder(input, context) {
- return new RequestBuilder(input, context);
- }
-
- class RequestBuilder {
- input;
- context;
- query = {};
- method = "";
- headers = {};
- path = "";
- body = null;
- hostname = "";
- resolvePathStack = [];
- constructor(input, context) {
- this.input = input;
- this.context = context;
- }
- async build() {
- const { hostname: hostname2, protocol = "https", port, path: basePath } = await this.context.endpoint();
- this.path = basePath;
- for (const resolvePath of this.resolvePathStack) {
- resolvePath(this.path);
- }
- return new protocolHttp.HttpRequest({
- protocol,
- hostname: this.hostname || hostname2,
- port,
- method: this.method,
- path: this.path,
- query: this.query,
- body: this.body,
- headers: this.headers
- });
- }
- hn(hostname2) {
- this.hostname = hostname2;
- return this;
- }
- bp(uriLabel) {
- this.resolvePathStack.push((basePath) => {
- this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel;
- });
- return this;
- }
- p(memberName, labelValueProvider, uriLabel, isGreedyLabel) {
- this.resolvePathStack.push((path8) => {
- this.path = resolvedPath(path8, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel);
- });
- return this;
- }
- h(headers) {
- this.headers = headers;
- return this;
- }
- q(query) {
- this.query = query;
- return this;
- }
- b(body) {
- this.body = body;
- return this;
- }
- m(method) {
- this.method = method;
- return this;
- }
- }
- function determineTimestampFormat(ns, settings) {
- if (settings.timestampFormat.useTrait) {
- if (ns.isTimestampSchema() && (ns.getSchema() === 5 || ns.getSchema() === 6 || ns.getSchema() === 7)) {
- return ns.getSchema();
- }
- }
- const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits();
- const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? 6 : Boolean(httpQuery) || Boolean(httpLabel) ? 5 : undefined : undefined;
- return bindingFormat ?? settings.timestampFormat.default;
- }
-
- class FromStringShapeDeserializer extends SerdeContext {
- settings;
- constructor(settings) {
- super();
- this.settings = settings;
- }
- read(_schema, data) {
- const ns = schema2.NormalizedSchema.of(_schema);
- if (ns.isListSchema()) {
- return serde2.splitHeader(data).map((item) => this.read(ns.getValueSchema(), item));
- }
- if (ns.isBlobSchema()) {
- return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(data);
- }
- if (ns.isTimestampSchema()) {
- const format3 = determineTimestampFormat(ns, this.settings);
- switch (format3) {
- case 5:
- return serde2._parseRfc3339DateTimeWithOffset(data);
- case 6:
- return serde2._parseRfc7231DateTime(data);
- case 7:
- return serde2._parseEpochTimestamp(data);
- default:
- console.warn("Missing timestamp format, parsing value with Date constructor:", data);
- return new Date(data);
- }
- }
- if (ns.isStringSchema()) {
- const mediaType = ns.getMergedTraits().mediaType;
- let intermediateValue = data;
- if (mediaType) {
- if (ns.getMergedTraits().httpHeader) {
- intermediateValue = this.base64ToUtf8(intermediateValue);
- }
- const isJson = mediaType === "application/json" || mediaType.endsWith("+json");
- if (isJson) {
- intermediateValue = serde2.LazyJsonString.from(intermediateValue);
- }
- return intermediateValue;
- }
- }
- if (ns.isNumericSchema()) {
- return Number(data);
- }
- if (ns.isBigIntegerSchema()) {
- return BigInt(data);
- }
- if (ns.isBigDecimalSchema()) {
- return new serde2.NumericValue(data, "bigDecimal");
- }
- if (ns.isBooleanSchema()) {
- return String(data).toLowerCase() === "true";
- }
- return data;
- }
- base64ToUtf8(base64String) {
- return (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)((this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(base64String));
- }
- }
-
- class HttpInterceptingShapeDeserializer extends SerdeContext {
- codecDeserializer;
- stringDeserializer;
- constructor(codecDeserializer, codecSettings) {
- super();
- this.codecDeserializer = codecDeserializer;
- this.stringDeserializer = new FromStringShapeDeserializer(codecSettings);
- }
- setSerdeContext(serdeContext) {
- this.stringDeserializer.setSerdeContext(serdeContext);
- this.codecDeserializer.setSerdeContext(serdeContext);
- this.serdeContext = serdeContext;
- }
- read(schema$1, data) {
- const ns = schema2.NormalizedSchema.of(schema$1);
- const traits2 = ns.getMergedTraits();
- const toString6 = this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8;
- if (traits2.httpHeader || traits2.httpResponseCode) {
- return this.stringDeserializer.read(ns, toString6(data));
- }
- if (traits2.httpPayload) {
- if (ns.isBlobSchema()) {
- const toBytes = this.serdeContext?.utf8Decoder ?? utilUtf8.fromUtf8;
- if (typeof data === "string") {
- return toBytes(data);
- }
- return data;
- } else if (ns.isStringSchema()) {
- if ("byteLength" in data) {
- return toString6(data);
- }
- return data;
- }
- }
- return this.codecDeserializer.read(ns, data);
- }
- }
-
- class ToStringShapeSerializer extends SerdeContext {
- settings;
- stringBuffer = "";
- constructor(settings) {
- super();
- this.settings = settings;
- }
- write(schema$1, value) {
- const ns = schema2.NormalizedSchema.of(schema$1);
- switch (typeof value) {
- case "object":
- if (value === null) {
- this.stringBuffer = "null";
- return;
- }
- if (ns.isTimestampSchema()) {
- if (!(value instanceof Date)) {
- throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`);
- }
- const format3 = determineTimestampFormat(ns, this.settings);
- switch (format3) {
- case 5:
- this.stringBuffer = value.toISOString().replace(".000Z", "Z");
- break;
- case 6:
- this.stringBuffer = serde2.dateToUtcString(value);
- break;
- case 7:
- this.stringBuffer = String(value.getTime() / 1000);
- break;
- default:
- console.warn("Missing timestamp format, using epoch seconds", value);
- this.stringBuffer = String(value.getTime() / 1000);
- }
- return;
- }
- if (ns.isBlobSchema() && "byteLength" in value) {
- this.stringBuffer = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value);
- return;
- }
- if (ns.isListSchema() && Array.isArray(value)) {
- let buffer = "";
- for (const item of value) {
- this.write([ns.getValueSchema(), ns.getMergedTraits()], item);
- const headerItem = this.flush();
- const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : serde2.quoteHeader(headerItem);
- if (buffer !== "") {
- buffer += ", ";
- }
- buffer += serialized;
- }
- this.stringBuffer = buffer;
- return;
- }
- this.stringBuffer = JSON.stringify(value, null, 2);
- break;
- case "string":
- const mediaType = ns.getMergedTraits().mediaType;
- let intermediateValue = value;
- if (mediaType) {
- const isJson = mediaType === "application/json" || mediaType.endsWith("+json");
- if (isJson) {
- intermediateValue = serde2.LazyJsonString.from(intermediateValue);
- }
- if (ns.getMergedTraits().httpHeader) {
- this.stringBuffer = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(intermediateValue.toString());
- return;
- }
- }
- this.stringBuffer = value;
- break;
- default:
- if (ns.isIdempotencyToken()) {
- this.stringBuffer = serde2.generateIdempotencyToken();
- } else {
- this.stringBuffer = String(value);
- }
- }
- }
- flush() {
- const buffer = this.stringBuffer;
- this.stringBuffer = "";
- return buffer;
- }
- }
-
- class HttpInterceptingShapeSerializer {
- codecSerializer;
- stringSerializer;
- buffer;
- constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) {
- this.codecSerializer = codecSerializer;
- this.stringSerializer = stringSerializer;
- }
- setSerdeContext(serdeContext) {
- this.codecSerializer.setSerdeContext(serdeContext);
- this.stringSerializer.setSerdeContext(serdeContext);
- }
- write(schema$1, value) {
- const ns = schema2.NormalizedSchema.of(schema$1);
- const traits2 = ns.getMergedTraits();
- if (traits2.httpHeader || traits2.httpLabel || traits2.httpQuery) {
- this.stringSerializer.write(ns, value);
- this.buffer = this.stringSerializer.flush();
- return;
- }
- return this.codecSerializer.write(ns, value);
- }
- flush() {
- if (this.buffer !== undefined) {
- const buffer = this.buffer;
- this.buffer = undefined;
- return buffer;
- }
- return this.codecSerializer.flush();
- }
- }
- exports.FromStringShapeDeserializer = FromStringShapeDeserializer;
- exports.HttpBindingProtocol = HttpBindingProtocol;
- exports.HttpInterceptingShapeDeserializer = HttpInterceptingShapeDeserializer;
- exports.HttpInterceptingShapeSerializer = HttpInterceptingShapeSerializer;
- exports.HttpProtocol = HttpProtocol;
- exports.RequestBuilder = RequestBuilder;
- exports.RpcProtocol = RpcProtocol;
- exports.SerdeContext = SerdeContext;
- exports.ToStringShapeSerializer = ToStringShapeSerializer;
- exports.collectBody = collectBody;
- exports.determineTimestampFormat = determineTimestampFormat;
- exports.extendedEncodeURIComponent = extendedEncodeURIComponent;
- exports.requestBuilder = requestBuilder;
- exports.resolvedPath = resolvedPath;
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js
-var import_protocols;
-var init_collect_stream_body = __esm(() => {
- import_protocols = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/schemaLogFilter.js
-function schemaLogFilter(schema2, data) {
- if (data == null) {
- return data;
- }
- const ns = import_schema.NormalizedSchema.of(schema2);
- if (ns.getMergedTraits().sensitive) {
- return SENSITIVE_STRING;
- }
- if (ns.isListSchema()) {
- const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING;
- }
- } else if (ns.isMapSchema()) {
- const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING;
- }
- } else if (ns.isStructSchema() && typeof data === "object") {
- const object2 = data;
- const newObject = {};
- for (const [member, memberNs] of ns.structIterator()) {
- if (object2[member] != null) {
- newObject[member] = schemaLogFilter(memberNs, object2[member]);
- }
- }
- return newObject;
- }
- return data;
-}
-var import_schema, SENSITIVE_STRING = "***SensitiveInformation***";
-var init_schemaLogFilter = __esm(() => {
- import_schema = __toESM(require_schema(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/command.js
-class Command2 {
- middlewareStack = import_middleware_stack2.constructStack();
- schema;
- static classBuilder() {
- return new ClassBuilder;
- }
- resolveMiddlewareWithContext(clientStack, configuration, options2, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
- for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options2)) {
- this.middlewareStack.use(mw);
- }
- const stack = clientStack.concat(this.middlewareStack);
- const { logger: logger2 } = configuration;
- const handlerExecutionContext = {
- logger: logger2,
- clientName,
- commandName,
- inputFilterSensitiveLog,
- outputFilterSensitiveLog,
- [SMITHY_CONTEXT_KEY]: {
- commandInstance: this,
- ...smithyContext
- },
- ...additionalContext
- };
- const { requestHandler } = configuration;
- return stack.resolve((request2) => requestHandler.handle(request2.request, options2 || {}), handlerExecutionContext);
- }
-}
-
-class ClassBuilder {
- _init = () => {};
- _ep = {};
- _middlewareFn = () => [];
- _commandName = "";
- _clientName = "";
- _additionalContext = {};
- _smithyContext = {};
- _inputFilterSensitiveLog = undefined;
- _outputFilterSensitiveLog = undefined;
- _serializer = null;
- _deserializer = null;
- _operationSchema;
- init(cb) {
- this._init = cb;
- }
- ep(endpointParameterInstructions) {
- this._ep = endpointParameterInstructions;
- return this;
- }
- m(middlewareSupplier) {
- this._middlewareFn = middlewareSupplier;
- return this;
- }
- s(service, operation, smithyContext = {}) {
- this._smithyContext = {
- service,
- operation,
- ...smithyContext
- };
- return this;
- }
- c(additionalContext = {}) {
- this._additionalContext = additionalContext;
- return this;
- }
- n(clientName, commandName) {
- this._clientName = clientName;
- this._commandName = commandName;
- return this;
- }
- f(inputFilter = (_) => _, outputFilter = (_) => _) {
- this._inputFilterSensitiveLog = inputFilter;
- this._outputFilterSensitiveLog = outputFilter;
- return this;
- }
- ser(serializer) {
- this._serializer = serializer;
- return this;
- }
- de(deserializer) {
- this._deserializer = deserializer;
- return this;
- }
- sc(operation) {
- this._operationSchema = operation;
- this._smithyContext.operationSchema = operation;
- return this;
- }
- build() {
- const closure = this;
- let CommandRef;
- return CommandRef = class extends Command2 {
- input;
- static getEndpointParameterInstructions() {
- return closure._ep;
- }
- constructor(...[input]) {
- super();
- this.input = input ?? {};
- closure._init(this);
- this.schema = closure._operationSchema;
- }
- resolveMiddleware(stack, configuration, options2) {
- const op = closure._operationSchema;
- const input = op?.[4] ?? op?.input;
- const output = op?.[5] ?? op?.output;
- return this.resolveMiddlewareWithContext(stack, configuration, options2, {
- CommandCtor: CommandRef,
- middlewareFn: closure._middlewareFn,
- clientName: closure._clientName,
- commandName: closure._commandName,
- inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _),
- outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _),
- smithyContext: closure._smithyContext,
- additionalContext: closure._additionalContext
- });
- }
- serialize = closure._serializer;
- deserialize = closure._deserializer;
- };
- }
-}
-var import_middleware_stack2;
-var init_command4 = __esm(() => {
- init_dist_es3();
- init_schemaLogFilter();
- import_middleware_stack2 = __toESM(require_dist_cjs12(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/constants.js
-var SENSITIVE_STRING2 = "***SensitiveInformation***";
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js
-var createAggregatedClient = (commands, Client2, options2) => {
- for (const [command2, CommandCtor] of Object.entries(commands)) {
- const methodImpl = async function(args, optionsOrCb, cb) {
- const command3 = new CommandCtor(args);
- if (typeof optionsOrCb === "function") {
- this.send(command3, optionsOrCb);
- } else if (typeof cb === "function") {
- if (typeof optionsOrCb !== "object")
- throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
- this.send(command3, optionsOrCb || {}, cb);
- } else {
- return this.send(command3, optionsOrCb);
- }
- };
- const methodName = (command2[0].toLowerCase() + command2.slice(1)).replace(/Command$/, "");
- Client2.prototype[methodName] = methodImpl;
- }
- const { paginators = {}, waiters = {} } = options2 ?? {};
- for (const [paginatorName, paginatorFn] of Object.entries(paginators)) {
- if (Client2.prototype[paginatorName] === undefined) {
- Client2.prototype[paginatorName] = function(commandInput = {}, paginationConfiguration, ...rest) {
- return paginatorFn({
- ...paginationConfiguration,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
- for (const [waiterName, waiterFn] of Object.entries(waiters)) {
- if (Client2.prototype[waiterName] === undefined) {
- Client2.prototype[waiterName] = async function(commandInput = {}, waiterConfiguration, ...rest) {
- let config3 = waiterConfiguration;
- if (typeof waiterConfiguration === "number") {
- config3 = {
- maxWaitTime: waiterConfiguration
- };
- }
- return waiterFn({
- ...config3,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
-};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/exceptions.js
-var ServiceException, decorateServiceException = (exception, additions = {}) => {
- Object.entries(additions).filter(([, v]) => v !== undefined).forEach(([k, v]) => {
- if (exception[k] == undefined || exception[k] === "") {
- exception[k] = v;
- }
- });
- const message = exception.message || exception.Message || "UnknownError";
- exception.message = message;
- delete exception.Message;
- return exception;
-};
-var init_exceptions = __esm(() => {
- ServiceException = class ServiceException extends Error {
- $fault;
- $response;
- $retryable;
- $metadata;
- constructor(options2) {
- super(options2.message);
- Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
- this.name = options2.name;
- this.$fault = options2.$fault;
- this.$metadata = options2.$metadata;
- }
- static isInstance(value) {
- if (!value)
- return false;
- const candidate = value;
- return ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
- }
- static [Symbol.hasInstance](instance) {
- if (!instance)
- return false;
- const candidate = instance;
- if (this === ServiceException) {
- return ServiceException.isInstance(instance);
- }
- if (ServiceException.isInstance(instance)) {
- if (candidate.name && this.name) {
- return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
- }
- return this.prototype.isPrototypeOf(instance);
- }
- return false;
- }
- };
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js
-var throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => {
- const $metadata = deserializeMetadata(output);
- const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined;
- const response2 = new exceptionCtor({
- name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
- $fault: "client",
- $metadata
- });
- throw decorateServiceException(response2, parsedBody);
-}, withBaseException = (ExceptionCtor) => {
- return ({ output, parsedBody, errorCode }) => {
- throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
- };
-}, deserializeMetadata = (output) => ({
- httpStatusCode: output.statusCode,
- requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
- extendedRequestId: output.headers["x-amz-id-2"],
- cfId: output.headers["x-amz-cf-id"]
-});
-var init_default_error_handler = __esm(() => {
- init_exceptions();
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js
-var loadConfigsForDefaultMode = (mode) => {
- switch (mode) {
- case "standard":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "in-region":
- return {
- retryMode: "standard",
- connectionTimeout: 1100
- };
- case "cross-region":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "mobile":
- return {
- retryMode: "standard",
- connectionTimeout: 30000
- };
- default:
- return {};
- }
-};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js
-var warningEmitted = false, emitWarningIfUnsupportedVersion = (version2) => {
- if (version2 && !warningEmitted && parseInt(version2.substring(1, version2.indexOf("."))) < 16) {
- warningEmitted = true;
- }
-};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js
-var import_protocols2;
-var init_extended_encode_uri_component = __esm(() => {
- import_protocols2 = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js
-var knownAlgorithms, getChecksumConfiguration = (runtimeConfig) => {
- const checksumAlgorithms = [];
- for (const id in AlgorithmId) {
- const algorithmId = AlgorithmId[id];
- if (runtimeConfig[algorithmId] === undefined) {
- continue;
- }
- checksumAlgorithms.push({
- algorithmId: () => algorithmId,
- checksumConstructor: () => runtimeConfig[algorithmId]
- });
- }
- for (const [id, ChecksumCtor] of Object.entries(runtimeConfig.checksumAlgorithms ?? {})) {
- checksumAlgorithms.push({
- algorithmId: () => id,
- checksumConstructor: () => ChecksumCtor
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- runtimeConfig.checksumAlgorithms = runtimeConfig.checksumAlgorithms ?? {};
- const id = algo.algorithmId();
- const ctor = algo.checksumConstructor();
- if (knownAlgorithms.includes(id)) {
- runtimeConfig.checksumAlgorithms[id.toUpperCase()] = ctor;
- } else {
- runtimeConfig.checksumAlgorithms[id] = ctor;
- }
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
-}, resolveChecksumRuntimeConfig = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- const id = checksumAlgorithm.algorithmId();
- if (knownAlgorithms.includes(id)) {
- runtimeConfig[id] = checksumAlgorithm.checksumConstructor();
- }
- });
- return runtimeConfig;
-};
-var init_checksum3 = __esm(() => {
- init_dist_es3();
- knownAlgorithms = Object.values(AlgorithmId);
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js
-var getRetryConfiguration = (runtimeConfig) => {
- return {
- setRetryStrategy(retryStrategy) {
- runtimeConfig.retryStrategy = retryStrategy;
- },
- retryStrategy() {
- return runtimeConfig.retryStrategy;
- }
- };
-}, resolveRetryRuntimeConfig = (retryStrategyConfiguration) => {
- const runtimeConfig = {};
- runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
- return runtimeConfig;
-};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js
-var getDefaultExtensionConfiguration = (runtimeConfig) => {
- return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig));
-}, getDefaultClientConfiguration, resolveDefaultRuntimeConfig = (config3) => {
- return Object.assign(resolveChecksumRuntimeConfig(config3), resolveRetryRuntimeConfig(config3));
-};
-var init_defaultExtensionConfiguration2 = __esm(() => {
- init_checksum3();
- getDefaultClientConfiguration = getDefaultExtensionConfiguration;
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/extensions/index.js
-var init_extensions3 = __esm(() => {
- init_defaultExtensionConfiguration2();
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js
-var getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray];
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js
-var getValueFromTextNode = (obj) => {
- const textNodeName = "#text";
- for (const key in obj) {
- if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) {
- obj[key] = obj[key][textNodeName];
- } else if (typeof obj[key] === "object" && obj[key] !== null) {
- obj[key] = getValueFromTextNode(obj[key]);
- }
- }
- return obj;
-};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js
-var isSerializableHeaderValue = (value) => {
- return value != null;
-};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js
-class NoOpLogger {
- trace() {}
- debug() {}
- info() {}
- warn() {}
- error() {}
-}
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/object-mapping.js
-function map2(arg0, arg1, arg2) {
- let target;
- let filter2;
- let instructions;
- if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
- target = {};
- instructions = arg0;
- } else {
- target = arg0;
- if (typeof arg1 === "function") {
- filter2 = arg1;
- instructions = arg2;
- return mapWithFilter(target, filter2, instructions);
- } else {
- instructions = arg1;
- }
- }
- for (const key of Object.keys(instructions)) {
- if (!Array.isArray(instructions[key])) {
- target[key] = instructions[key];
- continue;
- }
- applyInstruction(target, null, instructions, key);
- }
- return target;
-}
-var convertMap = (target) => {
- const output = {};
- for (const [k, v] of Object.entries(target || {})) {
- output[k] = [, v];
- }
- return output;
-}, take = (source, instructions) => {
- const out = {};
- for (const key in instructions) {
- applyInstruction(out, source, instructions, key);
- }
- return out;
-}, mapWithFilter = (target, filter2, instructions) => {
- return map2(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
- if (Array.isArray(value)) {
- _instructions[key] = value;
- } else {
- if (typeof value === "function") {
- _instructions[key] = [filter2, value()];
- } else {
- _instructions[key] = [filter2, value];
- }
- }
- return _instructions;
- }, {}));
-}, applyInstruction = (target, source, instructions, targetKey) => {
- if (source !== null) {
- let instruction = instructions[targetKey];
- if (typeof instruction === "function") {
- instruction = [, instruction];
- }
- const [filter3 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;
- if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) {
- target[targetKey] = valueFn(source[sourceKey]);
- }
- return;
- }
- let [filter2, value] = instructions[targetKey];
- if (typeof value === "function") {
- let _value;
- const defaultFilterPassed = filter2 === undefined && (_value = value()) != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(undefined) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed) {
- target[targetKey] = _value;
- } else if (customFilterPassed) {
- target[targetKey] = value();
- }
- } else {
- const defaultFilterPassed = filter2 === undefined && value != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed || customFilterPassed) {
- target[targetKey] = value;
- }
- }
-}, nonNullish = (_) => _ != null, pass = (_) => _;
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/resolve-path.js
-var import_protocols3;
-var init_resolve_path = __esm(() => {
- import_protocols3 = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/ser-utils.js
-var serializeFloat = (value) => {
- if (value !== value) {
- return "NaN";
- }
- switch (value) {
- case Infinity:
- return "Infinity";
- case -Infinity:
- return "-Infinity";
- default:
- return value;
- }
-}, serializeDateTime = (date5) => date5.toISOString().replace(".000Z", "Z");
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/serde-json.js
-var _json = (obj) => {
- if (obj == null) {
- return {};
- }
- if (Array.isArray(obj)) {
- return obj.filter((_) => _ != null).map(_json);
- }
- if (typeof obj === "object") {
- const target = {};
- for (const key of Object.keys(obj)) {
- if (obj[key] == null) {
- continue;
- }
- target[key] = _json(obj[key]);
- }
- return target;
- }
- return obj;
-};
-
-// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-es/index.js
-var exports_dist_es3 = {};
-__export(exports_dist_es3, {
- withBaseException: () => withBaseException,
- throwDefaultError: () => throwDefaultError,
- take: () => take,
- serializeFloat: () => serializeFloat,
- serializeDateTime: () => serializeDateTime,
- resolvedPath: () => import_protocols3.resolvedPath,
- resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig,
- map: () => map2,
- loadConfigsForDefaultMode: () => loadConfigsForDefaultMode,
- isSerializableHeaderValue: () => isSerializableHeaderValue,
- getValueFromTextNode: () => getValueFromTextNode,
- getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration,
- getDefaultClientConfiguration: () => getDefaultClientConfiguration,
- getArrayIfSingleItem: () => getArrayIfSingleItem,
- extendedEncodeURIComponent: () => import_protocols2.extendedEncodeURIComponent,
- emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion,
- decorateServiceException: () => decorateServiceException,
- createAggregatedClient: () => createAggregatedClient,
- convertMap: () => convertMap,
- collectBody: () => import_protocols.collectBody,
- _json: () => _json,
- ServiceException: () => ServiceException,
- SENSITIVE_STRING: () => SENSITIVE_STRING2,
- NoOpLogger: () => NoOpLogger,
- Command: () => Command2,
- Client: () => Client
-});
-var init_dist_es5 = __esm(() => {
- init_client2();
- init_collect_stream_body();
- init_command4();
- init_default_error_handler();
- init_exceptions();
- init_extended_encode_uri_component();
- init_extensions3();
- init_resolve_path();
- __reExport(exports_dist_es3, __toESM(require_serde(), 1));
-});
-
-// node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js
-function createGetRequest(url3) {
- return new HttpRequest({
- protocol: url3.protocol,
- hostname: url3.hostname,
- port: Number(url3.port),
- path: url3.pathname,
- query: Array.from(url3.searchParams.entries()).reduce((acc, [k, v]) => {
- acc[k] = v;
- return acc;
- }, {}),
- fragment: url3.hash
- });
-}
-async function getCredentials(response2, logger2) {
- const stream5 = import_util_stream.sdkStreamMixin(response2.body);
- const str = await stream5.transformToString();
- if (response2.statusCode === 200) {
- const parsed = JSON.parse(str);
- if (typeof parsed.AccessKeyId !== "string" || typeof parsed.SecretAccessKey !== "string" || typeof parsed.Token !== "string" || typeof parsed.Expiration !== "string") {
- throw new import_property_provider7.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: " + "{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger: logger2 });
- }
- return {
- accessKeyId: parsed.AccessKeyId,
- secretAccessKey: parsed.SecretAccessKey,
- sessionToken: parsed.Token,
- expiration: exports_dist_es3.parseRfc3339DateTime(parsed.Expiration)
- };
- }
- if (response2.statusCode >= 400 && response2.statusCode < 500) {
- let parsedBody = {};
- try {
- parsedBody = JSON.parse(str);
- } catch (e) {}
- throw Object.assign(new import_property_provider7.CredentialsProviderError(`Server responded with status: ${response2.statusCode}`, { logger: logger2 }), {
- Code: parsedBody.Code,
- Message: parsedBody.Message
- });
- }
- throw new import_property_provider7.CredentialsProviderError(`Server responded with status: ${response2.statusCode}`, { logger: logger2 });
-}
-var import_property_provider7, import_util_stream;
-var init_requestHelpers = __esm(() => {
- init_dist_es4();
- init_dist_es5();
- import_property_provider7 = __toESM(require_dist_cjs6(), 1);
- import_util_stream = __toESM(require_dist_cjs26(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js
-var retryWrapper = (toRetry, maxRetries, delayMs) => {
- return async () => {
- for (let i2 = 0;i2 < maxRetries; ++i2) {
- try {
- return await toRetry();
- } catch (e) {
- await new Promise((resolve9) => setTimeout(resolve9, delayMs));
- }
- }
- return await toRetry();
- };
-};
-
-// node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js
-import fs2 from "fs/promises";
-var import_client2, import_node_http_handler, import_property_provider8, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2", AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI", AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE", AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN", fromHttp = (options2 = {}) => {
- options2.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");
- let host;
- const relative3 = options2.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI];
- const full = options2.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI];
- const token = options2.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN];
- const tokenFile = options2.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE];
- const warn = options2.logger?.constructor?.name === "NoOpLogger" || !options2.logger?.warn ? console.warn : options2.logger.warn.bind(options2.logger);
- if (relative3 && full) {
- warn("@aws-sdk/credential-provider-http: " + "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.");
- warn("awsContainerCredentialsFullUri will take precedence.");
- }
- if (token && tokenFile) {
- warn("@aws-sdk/credential-provider-http: " + "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.");
- warn("awsContainerAuthorizationToken will take precedence.");
- }
- if (full) {
- host = full;
- } else if (relative3) {
- host = `${DEFAULT_LINK_LOCAL_HOST}${relative3}`;
- } else {
- throw new import_property_provider8.CredentialsProviderError(`No HTTP credential provider host provided.
-Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options2.logger });
- }
- const url3 = new URL(host);
- checkUrl(url3, options2.logger);
- const requestHandler = import_node_http_handler.NodeHttpHandler.create({
- requestTimeout: options2.timeout ?? 1000,
- connectionTimeout: options2.timeout ?? 1000
- });
- return retryWrapper(async () => {
- const request2 = createGetRequest(url3);
- if (token) {
- request2.headers.Authorization = token;
- } else if (tokenFile) {
- request2.headers.Authorization = (await fs2.readFile(tokenFile)).toString();
- }
- try {
- const result = await requestHandler.handle(request2);
- return getCredentials(result.response).then((creds) => import_client2.setCredentialFeature(creds, "CREDENTIALS_HTTP", "z"));
- } catch (e) {
- throw new import_property_provider8.CredentialsProviderError(String(e), { logger: options2.logger });
- }
- }, options2.maxRetries ?? 3, options2.timeout ?? 1000);
-};
-var init_fromHttp = __esm(() => {
- init_checkUrl();
- init_requestHelpers();
- import_client2 = __toESM(require_client(), 1);
- import_node_http_handler = __toESM(require_dist_cjs5(), 1);
- import_property_provider8 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-http/dist-es/index.js
-var exports_dist_es4 = {};
-__export(exports_dist_es4, {
- fromHttp: () => fromHttp
-});
-var init_dist_es6 = __esm(() => {
- init_fromHttp();
-});
-
-// node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js
-var import_property_provider9, ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED", remoteProvider = async (init) => {
- const { ENV_CMDS_FULL_URI: ENV_CMDS_FULL_URI2, ENV_CMDS_RELATIVE_URI: ENV_CMDS_RELATIVE_URI2, fromContainerMetadata: fromContainerMetadata3, fromInstanceMetadata: fromInstanceMetadata3 } = await Promise.resolve().then(() => (init_dist_es2(), exports_dist_es2));
- if (process.env[ENV_CMDS_RELATIVE_URI2] || process.env[ENV_CMDS_FULL_URI2]) {
- init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata");
- const { fromHttp: fromHttp2 } = await Promise.resolve().then(() => (init_dist_es6(), exports_dist_es4));
- return import_property_provider9.chain(fromHttp2(init), fromContainerMetadata3(init));
- }
- if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") {
- return async () => {
- throw new import_property_provider9.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init.logger });
- };
- }
- init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata");
- return fromInstanceMetadata3(init);
-};
-var init_remoteProvider = __esm(() => {
- import_property_provider9 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-node/dist-es/runtime/memoize-chain.js
-function memoizeChain(providers, treatAsExpired) {
- const chain2 = internalCreateChain(providers);
- let activeLock;
- let passiveLock;
- let credentials;
- const provider = async (options2) => {
- if (options2?.forceRefresh) {
- return await chain2(options2);
- }
- if (credentials?.expiration) {
- if (credentials?.expiration?.getTime() < Date.now()) {
- credentials = undefined;
- }
- }
- if (activeLock) {
- await activeLock;
- } else if (!credentials || treatAsExpired?.(credentials)) {
- if (credentials) {
- if (!passiveLock) {
- passiveLock = chain2(options2).then((c5) => {
- credentials = c5;
- }).finally(() => {
- passiveLock = undefined;
- });
- }
- } else {
- activeLock = chain2(options2).then((c5) => {
- credentials = c5;
- }).finally(() => {
- activeLock = undefined;
- });
- return provider(options2);
- }
- }
- return credentials;
- };
- return provider;
-}
-var internalCreateChain = (providers) => async (awsIdentityProperties) => {
- let lastProviderError;
- for (const provider of providers) {
- try {
- return await provider(awsIdentityProperties);
- } catch (err) {
- lastProviderError = err;
- if (err?.tryNextLink) {
- continue;
- }
- throw err;
- }
- }
- throw lastProviderError;
-};
-
-// node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js
-var isSsoProfile = (arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string");
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs35 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration2 = (runtimeConfig) => {
- return getChecksumConfiguration2(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return resolveChecksumRuntimeConfig2(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
-});
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-cjs/index.js
-var require_dist_cjs36 = __commonJS((exports) => {
- var types3 = require_dist_cjs35();
- var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
- };
- var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
- };
-
- class Field2 {
- name;
- kind;
- values;
- constructor({ name, kind: kind2 = types3.FieldPosition.HEADER, values = [] }) {
- this.name = name;
- this.kind = kind2;
- this.values = values;
- }
- add(value) {
- this.values.push(value);
- }
- set(values) {
- this.values = values;
- }
- remove(value) {
- this.values = this.values.filter((v) => v !== value);
- }
- toString() {
- return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
- }
- get() {
- return this.values;
- }
- }
-
- class Fields2 {
- entries = {};
- encoding;
- constructor({ fields = [], encoding = "utf-8" }) {
- fields.forEach(this.setField.bind(this));
- this.encoding = encoding;
- }
- setField(field) {
- this.entries[field.name.toLowerCase()] = field;
- }
- getField(name) {
- return this.entries[name.toLowerCase()];
- }
- removeField(name) {
- delete this.entries[name.toLowerCase()];
- }
- getByType(kind2) {
- return Object.values(this.entries).filter((field) => field.kind === kind2);
- }
- }
-
- class HttpRequest2 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest2({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery2(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest2.clone(this);
- }
- }
- function cloneQuery2(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
- }
-
- class HttpResponse {
- statusCode;
- reason;
- headers;
- body;
- constructor(options2) {
- this.statusCode = options2.statusCode;
- this.reason = options2.reason;
- this.headers = options2.headers || {};
- this.body = options2.body;
- }
- static isInstance(response2) {
- if (!response2)
- return false;
- const resp = response2;
- return typeof resp.statusCode === "number" && typeof resp.headers === "object";
- }
- }
- function isValidHostname2(hostname2) {
- const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
- return hostPattern.test(hostname2);
- }
- exports.Field = Field2;
- exports.Fields = Fields2;
- exports.HttpRequest = HttpRequest2;
- exports.HttpResponse = HttpResponse;
- exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
- exports.isValidHostname = isValidHostname2;
- exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;
-});
-
-// node_modules/@smithy/core/dist-cjs/index.js
-var require_dist_cjs37 = __commonJS((exports) => {
- var types3 = require_dist_cjs27();
- var utilMiddleware = require_dist_cjs30();
- var protocolHttp = require_dist_cjs28();
- var protocols = require_protocols();
- var getSmithyContext = (context) => context[types3.SMITHY_CONTEXT_KEY] || (context[types3.SMITHY_CONTEXT_KEY] = {});
- var resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => {
- if (!authSchemePreference || authSchemePreference.length === 0) {
- return candidateAuthOptions;
- }
- const preferredAuthOptions = [];
- for (const preferredSchemeName of authSchemePreference) {
- for (const candidateAuthOption of candidateAuthOptions) {
- const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1];
- if (candidateAuthSchemeName === preferredSchemeName) {
- preferredAuthOptions.push(candidateAuthOption);
- }
- }
- }
- for (const candidateAuthOption of candidateAuthOptions) {
- if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) {
- preferredAuthOptions.push(candidateAuthOption);
- }
- }
- return preferredAuthOptions;
- };
- function convertHttpAuthSchemesToMap(httpAuthSchemes) {
- const map3 = new Map;
- for (const scheme of httpAuthSchemes) {
- map3.set(scheme.schemeId, scheme);
- }
- return map3;
- }
- var httpAuthSchemeMiddleware = (config3, mwOptions) => (next, context) => async (args) => {
- const options2 = config3.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config3, context, args.input));
- const authSchemePreference = config3.authSchemePreference ? await config3.authSchemePreference() : [];
- const resolvedOptions = resolveAuthOptions(options2, authSchemePreference);
- const authSchemes = convertHttpAuthSchemesToMap(config3.httpAuthSchemes);
- const smithyContext = utilMiddleware.getSmithyContext(context);
- const failureReasons = [];
- for (const option of resolvedOptions) {
- const scheme = authSchemes.get(option.schemeId);
- if (!scheme) {
- failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);
- continue;
- }
- const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config3));
- if (!identityProvider) {
- failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);
- continue;
- }
- const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config3, context) || {};
- option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties);
- option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties);
- smithyContext.selectedHttpAuthScheme = {
- httpAuthOption: option,
- identity: await identityProvider(option.identityProperties),
- signer: scheme.signer
- };
- break;
- }
- if (!smithyContext.selectedHttpAuthScheme) {
- throw new Error(failureReasons.join(`
-`));
- }
- return next(args);
- };
- var httpAuthSchemeEndpointRuleSetMiddlewareOptions = {
- step: "serialize",
- tags: ["HTTP_AUTH_SCHEME"],
- name: "httpAuthSchemeMiddleware",
- override: true,
- relation: "before",
- toMiddleware: "endpointV2Middleware"
- };
- var getHttpAuthSchemeEndpointRuleSetPlugin = (config3, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({
- applyToStack: (clientStack) => {
- clientStack.addRelativeTo(httpAuthSchemeMiddleware(config3, {
- httpAuthSchemeParametersProvider,
- identityProviderConfigProvider
- }), httpAuthSchemeEndpointRuleSetMiddlewareOptions);
- }
- });
- var httpAuthSchemeMiddlewareOptions = {
- step: "serialize",
- tags: ["HTTP_AUTH_SCHEME"],
- name: "httpAuthSchemeMiddleware",
- override: true,
- relation: "before",
- toMiddleware: "serializerMiddleware"
- };
- var getHttpAuthSchemePlugin = (config3, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({
- applyToStack: (clientStack) => {
- clientStack.addRelativeTo(httpAuthSchemeMiddleware(config3, {
- httpAuthSchemeParametersProvider,
- identityProviderConfigProvider
- }), httpAuthSchemeMiddlewareOptions);
- }
- });
- var defaultErrorHandler = (signingProperties) => (error40) => {
- throw error40;
- };
- var defaultSuccessHandler = (httpResponse2, signingProperties) => {};
- var httpSigningMiddleware = (config3) => (next, context) => async (args) => {
- if (!protocolHttp.HttpRequest.isInstance(args.request)) {
- return next(args);
- }
- const smithyContext = utilMiddleware.getSmithyContext(context);
- const scheme = smithyContext.selectedHttpAuthScheme;
- if (!scheme) {
- throw new Error(`No HttpAuthScheme was selected: unable to sign request`);
- }
- const { httpAuthOption: { signingProperties = {} }, identity: identity6, signer } = scheme;
- const output = await next({
- ...args,
- request: await signer.sign(args.request, identity6, signingProperties)
- }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties));
- (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties);
- return output;
- };
- var httpSigningMiddlewareOptions = {
- step: "finalizeRequest",
- tags: ["HTTP_SIGNING"],
- name: "httpSigningMiddleware",
- aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"],
- override: true,
- relation: "after",
- toMiddleware: "retryMiddleware"
- };
- var getHttpSigningPlugin = (config3) => ({
- applyToStack: (clientStack) => {
- clientStack.addRelativeTo(httpSigningMiddleware(), httpSigningMiddlewareOptions);
- }
- });
- var normalizeProvider = (input) => {
- if (typeof input === "function")
- return input;
- const promisified = Promise.resolve(input);
- return () => promisified;
- };
- var makePagedClientRequest = async (CommandCtor, client3, input, withCommand = (_) => _, ...args) => {
- let command3 = new CommandCtor(input);
- command3 = withCommand(command3) ?? command3;
- return await client3.send(command3, ...args);
- };
- function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) {
- return async function* paginateOperation(config3, input, ...additionalArguments) {
- const _input = input;
- let token = config3.startingToken ?? _input[inputTokenName];
- let hasNext = true;
- let page;
- while (hasNext) {
- _input[inputTokenName] = token;
- if (pageSizeTokenName) {
- _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config3.pageSize;
- }
- if (config3.client instanceof ClientCtor) {
- page = await makePagedClientRequest(CommandCtor, config3.client, input, config3.withCommand, ...additionalArguments);
- } else {
- throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`);
- }
- yield page;
- const prevToken = token;
- token = get2(page, outputTokenName);
- hasNext = !!(token && (!config3.stopOnSameToken || token !== prevToken));
- }
- return;
- };
- }
- var get2 = (fromObject, path8) => {
- let cursor = fromObject;
- const pathComponents = path8.split(".");
- for (const step of pathComponents) {
- if (!cursor || typeof cursor !== "object") {
- return;
- }
- cursor = cursor[step];
- }
- return cursor;
- };
- function setFeature(context, feature, value) {
- if (!context.__smithy_context) {
- context.__smithy_context = {
- features: {}
- };
- } else if (!context.__smithy_context.features) {
- context.__smithy_context.features = {};
- }
- context.__smithy_context.features[feature] = value;
- }
-
- class DefaultIdentityProviderConfig {
- authSchemes = new Map;
- constructor(config3) {
- for (const [key, value] of Object.entries(config3)) {
- if (value !== undefined) {
- this.authSchemes.set(key, value);
- }
- }
- }
- getIdentityProvider(schemeId) {
- return this.authSchemes.get(schemeId);
- }
- }
-
- class HttpApiKeyAuthSigner {
- async sign(httpRequest3, identity6, signingProperties) {
- if (!signingProperties) {
- throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");
- }
- if (!signingProperties.name) {
- throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing");
- }
- if (!signingProperties.in) {
- throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing");
- }
- if (!identity6.apiKey) {
- throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined");
- }
- const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest3);
- if (signingProperties.in === types3.HttpApiKeyAuthLocation.QUERY) {
- clonedRequest.query[signingProperties.name] = identity6.apiKey;
- } else if (signingProperties.in === types3.HttpApiKeyAuthLocation.HEADER) {
- clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity6.apiKey}` : identity6.apiKey;
- } else {
- throw new Error("request can only be signed with `apiKey` locations `query` or `header`, " + "but found: `" + signingProperties.in + "`");
- }
- return clonedRequest;
- }
- }
-
- class HttpBearerAuthSigner {
- async sign(httpRequest3, identity6, signingProperties) {
- const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest3);
- if (!identity6.token) {
- throw new Error("request could not be signed with `token` since the `token` is not defined");
- }
- clonedRequest.headers["Authorization"] = `Bearer ${identity6.token}`;
- return clonedRequest;
- }
- }
-
- class NoAuthSigner {
- async sign(httpRequest3, identity6, signingProperties) {
- return httpRequest3;
- }
- }
- var createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired2(identity6) {
- return doesIdentityRequireRefresh(identity6) && identity6.expiration.getTime() - Date.now() < expirationMs;
- };
- var EXPIRATION_MS = 300000;
- var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS);
- var doesIdentityRequireRefresh = (identity6) => identity6.expiration !== undefined;
- var memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => {
- if (provider === undefined) {
- return;
- }
- const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider;
- let resolved;
- let pending;
- let hasResult;
- let isConstant = false;
- const coalesceProvider = async (options2) => {
- if (!pending) {
- pending = normalizedProvider(options2);
- }
- try {
- resolved = await pending;
- hasResult = true;
- isConstant = false;
- } finally {
- pending = undefined;
- }
- return resolved;
- };
- if (isExpired === undefined) {
- return async (options2) => {
- if (!hasResult || options2?.forceRefresh) {
- resolved = await coalesceProvider(options2);
- }
- return resolved;
- };
- }
- return async (options2) => {
- if (!hasResult || options2?.forceRefresh) {
- resolved = await coalesceProvider(options2);
- }
- if (isConstant) {
- return resolved;
- }
- if (!requiresRefresh(resolved)) {
- isConstant = true;
- return resolved;
- }
- if (isExpired(resolved)) {
- await coalesceProvider(options2);
- return resolved;
- }
- return resolved;
- };
- };
- exports.requestBuilder = protocols.requestBuilder;
- exports.DefaultIdentityProviderConfig = DefaultIdentityProviderConfig;
- exports.EXPIRATION_MS = EXPIRATION_MS;
- exports.HttpApiKeyAuthSigner = HttpApiKeyAuthSigner;
- exports.HttpBearerAuthSigner = HttpBearerAuthSigner;
- exports.NoAuthSigner = NoAuthSigner;
- exports.createIsIdentityExpiredFunction = createIsIdentityExpiredFunction;
- exports.createPaginator = createPaginator;
- exports.doesIdentityRequireRefresh = doesIdentityRequireRefresh;
- exports.getHttpAuthSchemeEndpointRuleSetPlugin = getHttpAuthSchemeEndpointRuleSetPlugin;
- exports.getHttpAuthSchemePlugin = getHttpAuthSchemePlugin;
- exports.getHttpSigningPlugin = getHttpSigningPlugin;
- exports.getSmithyContext = getSmithyContext;
- exports.httpAuthSchemeEndpointRuleSetMiddlewareOptions = httpAuthSchemeEndpointRuleSetMiddlewareOptions;
- exports.httpAuthSchemeMiddleware = httpAuthSchemeMiddleware;
- exports.httpAuthSchemeMiddlewareOptions = httpAuthSchemeMiddlewareOptions;
- exports.httpSigningMiddleware = httpSigningMiddleware;
- exports.httpSigningMiddlewareOptions = httpSigningMiddlewareOptions;
- exports.isIdentityExpired = isIdentityExpired;
- exports.memoizeIdentityProvider = memoizeIdentityProvider;
- exports.normalizeProvider = normalizeProvider;
- exports.setFeature = setFeature;
-});
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js
-var require_dist_cjs38 = __commonJS((exports) => {
- var SHORT_TO_HEX = {};
- var HEX_TO_SHORT = {};
- for (let i2 = 0;i2 < 256; i2++) {
- let encodedByte = i2.toString(16).toLowerCase();
- if (encodedByte.length === 1) {
- encodedByte = `0${encodedByte}`;
- }
- SHORT_TO_HEX[i2] = encodedByte;
- HEX_TO_SHORT[encodedByte] = i2;
- }
- function fromHex(encoded) {
- if (encoded.length % 2 !== 0) {
- throw new Error("Hex encoded strings must have an even number length");
- }
- const out = new Uint8Array(encoded.length / 2);
- for (let i2 = 0;i2 < encoded.length; i2 += 2) {
- const encodedByte = encoded.slice(i2, i2 + 2).toLowerCase();
- if (encodedByte in HEX_TO_SHORT) {
- out[i2 / 2] = HEX_TO_SHORT[encodedByte];
- } else {
- throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
- }
- }
- return out;
- }
- function toHex(bytes) {
- let out = "";
- for (let i2 = 0;i2 < bytes.byteLength; i2++) {
- out += SHORT_TO_HEX[bytes[i2]];
- }
- return out;
- }
- exports.fromHex = fromHex;
- exports.toHex = toHex;
-});
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
-var require_dist_cjs39 = __commonJS((exports) => {
- var isArrayBuffer3 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
- exports.isArrayBuffer = isArrayBuffer3;
-});
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/index.js
-var require_dist_cjs40 = __commonJS((exports) => {
- var escapeUri = (uri2) => encodeURIComponent(uri2).replace(/[!'()*]/g, hexEncode);
- var hexEncode = (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`;
- var escapeUriPath = (uri2) => uri2.split("/").map(escapeUri).join("/");
- exports.escapeUri = escapeUri;
- exports.escapeUriPath = escapeUriPath;
-});
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-cjs/index.js
-var require_dist_cjs41 = __commonJS((exports) => {
- var utilHexEncoding = require_dist_cjs38();
- var utilUtf8 = require_dist_cjs17();
- var isArrayBuffer3 = require_dist_cjs39();
- var protocolHttp = require_dist_cjs36();
- var utilMiddleware = require_dist_cjs30();
- var utilUriEscape = require_dist_cjs40();
- var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm";
- var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential";
- var AMZ_DATE_QUERY_PARAM = "X-Amz-Date";
- var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders";
- var EXPIRES_QUERY_PARAM = "X-Amz-Expires";
- var SIGNATURE_QUERY_PARAM = "X-Amz-Signature";
- var TOKEN_QUERY_PARAM = "X-Amz-Security-Token";
- var REGION_SET_PARAM = "X-Amz-Region-Set";
- var AUTH_HEADER = "authorization";
- var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();
- var DATE_HEADER = "date";
- var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER];
- var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();
- var SHA256_HEADER = "x-amz-content-sha256";
- var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();
- var HOST_HEADER = "host";
- var ALWAYS_UNSIGNABLE_HEADERS = {
- authorization: true,
- "cache-control": true,
- connection: true,
- expect: true,
- from: true,
- "keep-alive": true,
- "max-forwards": true,
- pragma: true,
- referer: true,
- te: true,
- trailer: true,
- "transfer-encoding": true,
- upgrade: true,
- "user-agent": true,
- "x-amzn-trace-id": true
- };
- var PROXY_HEADER_PATTERN = /^proxy-/;
- var SEC_HEADER_PATTERN = /^sec-/;
- var UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i];
- var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256";
- var ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256";
- var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD";
- var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
- var MAX_CACHE_SIZE = 50;
- var KEY_TYPE_IDENTIFIER = "aws4_request";
- var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;
- var signingKeyCache = {};
- var cacheQueue = [];
- var createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;
- var getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => {
- const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId);
- const cacheKey = `${shortDate}:${region}:${service}:${utilHexEncoding.toHex(credsHash)}:${credentials.sessionToken}`;
- if (cacheKey in signingKeyCache) {
- return signingKeyCache[cacheKey];
- }
- cacheQueue.push(cacheKey);
- while (cacheQueue.length > MAX_CACHE_SIZE) {
- delete signingKeyCache[cacheQueue.shift()];
- }
- let key = `AWS4${credentials.secretAccessKey}`;
- for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) {
- key = await hmac(sha256Constructor, key, signable);
- }
- return signingKeyCache[cacheKey] = key;
- };
- var clearCredentialCache = () => {
- cacheQueue.length = 0;
- Object.keys(signingKeyCache).forEach((cacheKey) => {
- delete signingKeyCache[cacheKey];
- });
- };
- var hmac = (ctor, secret, data) => {
- const hash2 = new ctor(secret);
- hash2.update(utilUtf8.toUint8Array(data));
- return hash2.digest();
- };
- var getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => {
- const canonical = {};
- for (const headerName of Object.keys(headers).sort()) {
- if (headers[headerName] == undefined) {
- continue;
- }
- const canonicalHeaderName = headerName.toLowerCase();
- if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) {
- if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) {
- continue;
- }
- }
- canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " ");
- }
- return canonical;
- };
- var getPayloadHash = async ({ headers, body }, hashConstructor) => {
- for (const headerName of Object.keys(headers)) {
- if (headerName.toLowerCase() === SHA256_HEADER) {
- return headers[headerName];
- }
- }
- if (body == undefined) {
- return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
- } else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer3.isArrayBuffer(body)) {
- const hashCtor = new hashConstructor;
- hashCtor.update(utilUtf8.toUint8Array(body));
- return utilHexEncoding.toHex(await hashCtor.digest());
- }
- return UNSIGNED_PAYLOAD;
- };
-
- class HeaderFormatter {
- format(headers) {
- const chunks = [];
- for (const headerName of Object.keys(headers)) {
- const bytes = utilUtf8.fromUtf8(headerName);
- chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
- }
- const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
- let position2 = 0;
- for (const chunk of chunks) {
- out.set(chunk, position2);
- position2 += chunk.byteLength;
- }
- return out;
- }
- formatHeaderValue(header) {
- switch (header.type) {
- case "boolean":
- return Uint8Array.from([header.value ? 0 : 1]);
- case "byte":
- return Uint8Array.from([2, header.value]);
- case "short":
- const shortView = new DataView(new ArrayBuffer(3));
- shortView.setUint8(0, 3);
- shortView.setInt16(1, header.value, false);
- return new Uint8Array(shortView.buffer);
- case "integer":
- const intView = new DataView(new ArrayBuffer(5));
- intView.setUint8(0, 4);
- intView.setInt32(1, header.value, false);
- return new Uint8Array(intView.buffer);
- case "long":
- const longBytes = new Uint8Array(9);
- longBytes[0] = 5;
- longBytes.set(header.value.bytes, 1);
- return longBytes;
- case "binary":
- const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
- binView.setUint8(0, 6);
- binView.setUint16(1, header.value.byteLength, false);
- const binBytes = new Uint8Array(binView.buffer);
- binBytes.set(header.value, 3);
- return binBytes;
- case "string":
- const utf8Bytes = utilUtf8.fromUtf8(header.value);
- const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
- strView.setUint8(0, 7);
- strView.setUint16(1, utf8Bytes.byteLength, false);
- const strBytes = new Uint8Array(strView.buffer);
- strBytes.set(utf8Bytes, 3);
- return strBytes;
- case "timestamp":
- const tsBytes = new Uint8Array(9);
- tsBytes[0] = 8;
- tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1);
- return tsBytes;
- case "uuid":
- if (!UUID_PATTERN.test(header.value)) {
- throw new Error(`Invalid UUID received: ${header.value}`);
- }
- const uuidBytes = new Uint8Array(17);
- uuidBytes[0] = 9;
- uuidBytes.set(utilHexEncoding.fromHex(header.value.replace(/\-/g, "")), 1);
- return uuidBytes;
- }
- }
- }
- var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
-
- class Int64 {
- bytes;
- constructor(bytes) {
- this.bytes = bytes;
- if (bytes.byteLength !== 8) {
- throw new Error("Int64 buffers must be exactly 8 bytes");
- }
- }
- static fromNumber(number4) {
- if (number4 > 9223372036854776000 || number4 < -9223372036854776000) {
- throw new Error(`${number4} is too large (or, if negative, too small) to represent as an Int64`);
- }
- const bytes = new Uint8Array(8);
- for (let i2 = 7, remaining = Math.abs(Math.round(number4));i2 > -1 && remaining > 0; i2--, remaining /= 256) {
- bytes[i2] = remaining;
- }
- if (number4 < 0) {
- negate(bytes);
- }
- return new Int64(bytes);
- }
- valueOf() {
- const bytes = this.bytes.slice(0);
- const negative = bytes[0] & 128;
- if (negative) {
- negate(bytes);
- }
- return parseInt(utilHexEncoding.toHex(bytes), 16) * (negative ? -1 : 1);
- }
- toString() {
- return String(this.valueOf());
- }
- }
- function negate(bytes) {
- for (let i2 = 0;i2 < 8; i2++) {
- bytes[i2] ^= 255;
- }
- for (let i2 = 7;i2 > -1; i2--) {
- bytes[i2]++;
- if (bytes[i2] !== 0)
- break;
- }
- }
- var hasHeader = (soughtHeader, headers) => {
- soughtHeader = soughtHeader.toLowerCase();
- for (const headerName of Object.keys(headers)) {
- if (soughtHeader === headerName.toLowerCase()) {
- return true;
- }
- }
- return false;
- };
- var moveHeadersToQuery = (request2, options2 = {}) => {
- const { headers, query = {} } = protocolHttp.HttpRequest.clone(request2);
- for (const name of Object.keys(headers)) {
- const lname = name.toLowerCase();
- if (lname.slice(0, 6) === "x-amz-" && !options2.unhoistableHeaders?.has(lname) || options2.hoistableHeaders?.has(lname)) {
- query[name] = headers[name];
- delete headers[name];
- }
- }
- return {
- ...request2,
- headers,
- query
- };
- };
- var prepareRequest = (request2) => {
- request2 = protocolHttp.HttpRequest.clone(request2);
- for (const headerName of Object.keys(request2.headers)) {
- if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {
- delete request2.headers[headerName];
- }
- }
- return request2;
- };
- var getCanonicalQuery = ({ query = {} }) => {
- const keys2 = [];
- const serialized = {};
- for (const key of Object.keys(query)) {
- if (key.toLowerCase() === SIGNATURE_HEADER) {
- continue;
- }
- const encodedKey = utilUriEscape.escapeUri(key);
- keys2.push(encodedKey);
- const value = query[key];
- if (typeof value === "string") {
- serialized[encodedKey] = `${encodedKey}=${utilUriEscape.escapeUri(value)}`;
- } else if (Array.isArray(value)) {
- serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${utilUriEscape.escapeUri(value2)}`]), []).sort().join("&");
- }
- }
- return keys2.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&");
- };
- var iso8601 = (time3) => toDate(time3).toISOString().replace(/\.\d{3}Z$/, "Z");
- var toDate = (time3) => {
- if (typeof time3 === "number") {
- return new Date(time3 * 1000);
- }
- if (typeof time3 === "string") {
- if (Number(time3)) {
- return new Date(Number(time3) * 1000);
- }
- return new Date(time3);
- }
- return time3;
- };
-
- class SignatureV4Base {
- service;
- regionProvider;
- credentialProvider;
- sha256;
- uriEscapePath;
- applyChecksum;
- constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true }) {
- this.service = service;
- this.sha256 = sha256;
- this.uriEscapePath = uriEscapePath;
- this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
- this.regionProvider = utilMiddleware.normalizeProvider(region);
- this.credentialProvider = utilMiddleware.normalizeProvider(credentials);
- }
- createCanonicalRequest(request2, canonicalHeaders, payloadHash) {
- const sortedHeaders = Object.keys(canonicalHeaders).sort();
- return `${request2.method}
-${this.getCanonicalPath(request2)}
-${getCanonicalQuery(request2)}
-${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join(`
-`)}
-
-${sortedHeaders.join(";")}
-${payloadHash}`;
- }
- async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) {
- const hash2 = new this.sha256;
- hash2.update(utilUtf8.toUint8Array(canonicalRequest));
- const hashedRequest = await hash2.digest();
- return `${algorithmIdentifier}
-${longDate}
-${credentialScope}
-${utilHexEncoding.toHex(hashedRequest)}`;
- }
- getCanonicalPath({ path: path8 }) {
- if (this.uriEscapePath) {
- const normalizedPathSegments = [];
- for (const pathSegment of path8.split("/")) {
- if (pathSegment?.length === 0)
- continue;
- if (pathSegment === ".")
- continue;
- if (pathSegment === "..") {
- normalizedPathSegments.pop();
- } else {
- normalizedPathSegments.push(pathSegment);
- }
- }
- const normalizedPath = `${path8?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path8?.endsWith("/") ? "/" : ""}`;
- const doubleEncoded = utilUriEscape.escapeUri(normalizedPath);
- return doubleEncoded.replace(/%2F/g, "/");
- }
- return path8;
- }
- validateResolvedCredentials(credentials) {
- if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") {
- throw new Error("Resolved credential object is not valid");
- }
- }
- formatDate(now) {
- const longDate = iso8601(now).replace(/[\-:]/g, "");
- return {
- longDate,
- shortDate: longDate.slice(0, 8)
- };
- }
- getCanonicalHeaderList(headers) {
- return Object.keys(headers).sort().join(";");
- }
- }
-
- class SignatureV4 extends SignatureV4Base {
- headerFormatter = new HeaderFormatter;
- constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true }) {
- super({
- applyChecksum,
- credentials,
- region,
- service,
- sha256,
- uriEscapePath
- });
- }
- async presign(originalRequest, options2 = {}) {
- const { signingDate = new Date, expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService } = options2;
- const credentials = await this.credentialProvider();
- this.validateResolvedCredentials(credentials);
- const region = signingRegion ?? await this.regionProvider();
- const { longDate, shortDate } = this.formatDate(signingDate);
- if (expiresIn > MAX_PRESIGNED_TTL) {
- return Promise.reject("Signature version 4 presigned URLs" + " must have an expiration date less than one week in" + " the future");
- }
- const scope = createScope(shortDate, region, signingService ?? this.service);
- const request2 = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders });
- if (credentials.sessionToken) {
- request2.query[TOKEN_QUERY_PARAM] = credentials.sessionToken;
- }
- request2.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
- request2.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`;
- request2.query[AMZ_DATE_QUERY_PARAM] = longDate;
- request2.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
- const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders);
- request2.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders);
- request2.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)));
- return request2;
- }
- async sign(toSign, options2) {
- if (typeof toSign === "string") {
- return this.signString(toSign, options2);
- } else if (toSign.headers && toSign.payload) {
- return this.signEvent(toSign, options2);
- } else if (toSign.message) {
- return this.signMessage(toSign, options2);
- } else {
- return this.signRequest(toSign, options2);
- }
- }
- async signEvent({ headers, payload }, { signingDate = new Date, priorSignature, signingRegion, signingService }) {
- const region = signingRegion ?? await this.regionProvider();
- const { shortDate, longDate } = this.formatDate(signingDate);
- const scope = createScope(shortDate, region, signingService ?? this.service);
- const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256);
- const hash2 = new this.sha256;
- hash2.update(headers);
- const hashedHeaders = utilHexEncoding.toHex(await hash2.digest());
- const stringToSign = [
- EVENT_ALGORITHM_IDENTIFIER,
- longDate,
- scope,
- priorSignature,
- hashedHeaders,
- hashedPayload
- ].join(`
-`);
- return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
- }
- async signMessage(signableMessage, { signingDate = new Date, signingRegion, signingService }) {
- const promise2 = this.signEvent({
- headers: this.headerFormatter.format(signableMessage.message.headers),
- payload: signableMessage.message.body
- }, {
- signingDate,
- signingRegion,
- signingService,
- priorSignature: signableMessage.priorSignature
- });
- return promise2.then((signature2) => {
- return { message: signableMessage.message, signature: signature2 };
- });
- }
- async signString(stringToSign, { signingDate = new Date, signingRegion, signingService } = {}) {
- const credentials = await this.credentialProvider();
- this.validateResolvedCredentials(credentials);
- const region = signingRegion ?? await this.regionProvider();
- const { shortDate } = this.formatDate(signingDate);
- const hash2 = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService));
- hash2.update(utilUtf8.toUint8Array(stringToSign));
- return utilHexEncoding.toHex(await hash2.digest());
- }
- async signRequest(requestToSign, { signingDate = new Date, signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) {
- const credentials = await this.credentialProvider();
- this.validateResolvedCredentials(credentials);
- const region = signingRegion ?? await this.regionProvider();
- const request2 = prepareRequest(requestToSign);
- const { longDate, shortDate } = this.formatDate(signingDate);
- const scope = createScope(shortDate, region, signingService ?? this.service);
- request2.headers[AMZ_DATE_HEADER] = longDate;
- if (credentials.sessionToken) {
- request2.headers[TOKEN_HEADER] = credentials.sessionToken;
- }
- const payloadHash = await getPayloadHash(request2, this.sha256);
- if (!hasHeader(SHA256_HEADER, request2.headers) && this.applyChecksum) {
- request2.headers[SHA256_HEADER] = payloadHash;
- }
- const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders);
- const signature2 = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, payloadHash));
- request2.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} ` + `Credential=${credentials.accessKeyId}/${scope}, ` + `SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, ` + `Signature=${signature2}`;
- return request2;
- }
- async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {
- const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER);
- const hash2 = new this.sha256(await keyPromise);
- hash2.update(utilUtf8.toUint8Array(stringToSign));
- return utilHexEncoding.toHex(await hash2.digest());
- }
- getSigningKey(credentials, region, shortDate, service) {
- return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service);
- }
- }
- var signatureV4aContainer = {
- SignatureV4a: null
- };
- exports.ALGORITHM_IDENTIFIER = ALGORITHM_IDENTIFIER;
- exports.ALGORITHM_IDENTIFIER_V4A = ALGORITHM_IDENTIFIER_V4A;
- exports.ALGORITHM_QUERY_PARAM = ALGORITHM_QUERY_PARAM;
- exports.ALWAYS_UNSIGNABLE_HEADERS = ALWAYS_UNSIGNABLE_HEADERS;
- exports.AMZ_DATE_HEADER = AMZ_DATE_HEADER;
- exports.AMZ_DATE_QUERY_PARAM = AMZ_DATE_QUERY_PARAM;
- exports.AUTH_HEADER = AUTH_HEADER;
- exports.CREDENTIAL_QUERY_PARAM = CREDENTIAL_QUERY_PARAM;
- exports.DATE_HEADER = DATE_HEADER;
- exports.EVENT_ALGORITHM_IDENTIFIER = EVENT_ALGORITHM_IDENTIFIER;
- exports.EXPIRES_QUERY_PARAM = EXPIRES_QUERY_PARAM;
- exports.GENERATED_HEADERS = GENERATED_HEADERS;
- exports.HOST_HEADER = HOST_HEADER;
- exports.KEY_TYPE_IDENTIFIER = KEY_TYPE_IDENTIFIER;
- exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE;
- exports.MAX_PRESIGNED_TTL = MAX_PRESIGNED_TTL;
- exports.PROXY_HEADER_PATTERN = PROXY_HEADER_PATTERN;
- exports.REGION_SET_PARAM = REGION_SET_PARAM;
- exports.SEC_HEADER_PATTERN = SEC_HEADER_PATTERN;
- exports.SHA256_HEADER = SHA256_HEADER;
- exports.SIGNATURE_HEADER = SIGNATURE_HEADER;
- exports.SIGNATURE_QUERY_PARAM = SIGNATURE_QUERY_PARAM;
- exports.SIGNED_HEADERS_QUERY_PARAM = SIGNED_HEADERS_QUERY_PARAM;
- exports.SignatureV4 = SignatureV4;
- exports.SignatureV4Base = SignatureV4Base;
- exports.TOKEN_HEADER = TOKEN_HEADER;
- exports.TOKEN_QUERY_PARAM = TOKEN_QUERY_PARAM;
- exports.UNSIGNABLE_PATTERNS = UNSIGNABLE_PATTERNS;
- exports.UNSIGNED_PAYLOAD = UNSIGNED_PAYLOAD;
- exports.clearCredentialCache = clearCredentialCache;
- exports.createScope = createScope;
- exports.getCanonicalHeaders = getCanonicalHeaders;
- exports.getCanonicalQuery = getCanonicalQuery;
- exports.getPayloadHash = getPayloadHash;
- exports.getSigningKey = getSigningKey;
- exports.hasHeader = hasHeader;
- exports.moveHeadersToQuery = moveHeadersToQuery;
- exports.prepareRequest = prepareRequest;
- exports.signatureV4aContainer = signatureV4aContainer;
-});
-
-// node_modules/@aws-sdk/core/dist-cjs/submodules/httpAuthSchemes/index.js
-var require_httpAuthSchemes = __commonJS((exports) => {
- var protocolHttp = require_dist_cjs36();
- var core2 = require_dist_cjs37();
- var propertyProvider = require_dist_cjs6();
- var client3 = require_client();
- var signatureV4 = require_dist_cjs41();
- var getDateHeader = (response2) => protocolHttp.HttpResponse.isInstance(response2) ? response2.headers?.date ?? response2.headers?.Date : undefined;
- var getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset);
- var isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 300000;
- var getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => {
- const clockTimeInMs = Date.parse(clockTime);
- if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) {
- return clockTimeInMs - Date.now();
- }
- return currentSystemClockOffset;
- };
- var throwSigningPropertyError = (name, property2) => {
- if (!property2) {
- throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);
- }
- return property2;
- };
- var validateSigningProperties = async (signingProperties) => {
- const context = throwSigningPropertyError("context", signingProperties.context);
- const config3 = throwSigningPropertyError("config", signingProperties.config);
- const authScheme = context.endpointV2?.properties?.authSchemes?.[0];
- const signerFunction = throwSigningPropertyError("signer", config3.signer);
- const signer = await signerFunction(authScheme);
- const signingRegion = signingProperties?.signingRegion;
- const signingRegionSet = signingProperties?.signingRegionSet;
- const signingName = signingProperties?.signingName;
- return {
- config: config3,
- signer,
- signingRegion,
- signingRegionSet,
- signingName
- };
- };
-
- class AwsSdkSigV4Signer {
- async sign(httpRequest3, identity6, signingProperties) {
- if (!protocolHttp.HttpRequest.isInstance(httpRequest3)) {
- throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
- }
- const validatedProps = await validateSigningProperties(signingProperties);
- const { config: config3, signer } = validatedProps;
- let { signingRegion, signingName } = validatedProps;
- const handlerExecutionContext = signingProperties.context;
- if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) {
- const [first, second] = handlerExecutionContext.authSchemes;
- if (first?.name === "sigv4a" && second?.name === "sigv4") {
- signingRegion = second?.signingRegion ?? signingRegion;
- signingName = second?.signingName ?? signingName;
- }
- }
- const signedRequest = await signer.sign(httpRequest3, {
- signingDate: getSkewCorrectedDate(config3.systemClockOffset),
- signingRegion,
- signingService: signingName
- });
- return signedRequest;
- }
- errorHandler(signingProperties) {
- return (error40) => {
- const serverTime = error40.ServerTime ?? getDateHeader(error40.$response);
- if (serverTime) {
- const config3 = throwSigningPropertyError("config", signingProperties.config);
- const initialSystemClockOffset = config3.systemClockOffset;
- config3.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config3.systemClockOffset);
- const clockSkewCorrected = config3.systemClockOffset !== initialSystemClockOffset;
- if (clockSkewCorrected && error40.$metadata) {
- error40.$metadata.clockSkewCorrected = true;
- }
- }
- throw error40;
- };
- }
- successHandler(httpResponse2, signingProperties) {
- const dateHeader = getDateHeader(httpResponse2);
- if (dateHeader) {
- const config3 = throwSigningPropertyError("config", signingProperties.config);
- config3.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config3.systemClockOffset);
- }
- }
- }
- var AWSSDKSigV4Signer = AwsSdkSigV4Signer;
-
- class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer {
- async sign(httpRequest3, identity6, signingProperties) {
- if (!protocolHttp.HttpRequest.isInstance(httpRequest3)) {
- throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
- }
- const { config: config3, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties);
- const configResolvedSigningRegionSet = await config3.sigv4aSigningRegionSet?.();
- const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(",");
- const signedRequest = await signer.sign(httpRequest3, {
- signingDate: getSkewCorrectedDate(config3.systemClockOffset),
- signingRegion: multiRegionOverride,
- signingService: signingName
- });
- return signedRequest;
- }
- }
- var getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [];
- var getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`;
- var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE";
- var NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference";
- var NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = {
- environmentVariableSelector: (env4, options2) => {
- if (options2?.signingName) {
- const bearerTokenKey = getBearerTokenEnvKey(options2.signingName);
- if (bearerTokenKey in env4)
- return ["httpBearerAuth"];
- }
- if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env4))
- return;
- return getArrayForCommaSeparatedString(env4[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]);
- },
- configFileSelector: (profile2) => {
- if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile2))
- return;
- return getArrayForCommaSeparatedString(profile2[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]);
- },
- default: []
- };
- var resolveAwsSdkSigV4AConfig = (config3) => {
- config3.sigv4aSigningRegionSet = core2.normalizeProvider(config3.sigv4aSigningRegionSet);
- return config3;
- };
- var NODE_SIGV4A_CONFIG_OPTIONS = {
- environmentVariableSelector(env4) {
- if (env4.AWS_SIGV4A_SIGNING_REGION_SET) {
- return env4.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim());
- }
- throw new propertyProvider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", {
- tryNextLink: true
- });
- },
- configFileSelector(profile2) {
- if (profile2.sigv4a_signing_region_set) {
- return (profile2.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim());
- }
- throw new propertyProvider.ProviderError("sigv4a_signing_region_set not set in profile.", {
- tryNextLink: true
- });
- },
- default: undefined
- };
- var resolveAwsSdkSigV4Config = (config3) => {
- let inputCredentials = config3.credentials;
- let isUserSupplied = !!config3.credentials;
- let resolvedCredentials = undefined;
- Object.defineProperty(config3, "credentials", {
- set(credentials) {
- if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) {
- isUserSupplied = true;
- }
- inputCredentials = credentials;
- const memoizedProvider = normalizeCredentialProvider(config3, {
- credentials: inputCredentials,
- credentialDefaultProvider: config3.credentialDefaultProvider
- });
- const boundProvider = bindCallerConfig(config3, memoizedProvider);
- if (isUserSupplied && !boundProvider.attributed) {
- const isCredentialObject = typeof inputCredentials === "object" && inputCredentials !== null;
- resolvedCredentials = async (options2) => {
- const creds = await boundProvider(options2);
- const attributedCreds = creds;
- if (isCredentialObject && (!attributedCreds.$source || Object.keys(attributedCreds.$source).length === 0)) {
- return client3.setCredentialFeature(attributedCreds, "CREDENTIALS_CODE", "e");
- }
- return attributedCreds;
- };
- resolvedCredentials.memoized = boundProvider.memoized;
- resolvedCredentials.configBound = boundProvider.configBound;
- resolvedCredentials.attributed = true;
- } else {
- resolvedCredentials = boundProvider;
- }
- },
- get() {
- return resolvedCredentials;
- },
- enumerable: true,
- configurable: true
- });
- config3.credentials = inputCredentials;
- const { signingEscapePath = true, systemClockOffset = config3.systemClockOffset || 0, sha256 } = config3;
- let signer;
- if (config3.signer) {
- signer = core2.normalizeProvider(config3.signer);
- } else if (config3.regionInfoProvider) {
- signer = () => core2.normalizeProvider(config3.region)().then(async (region) => [
- await config3.regionInfoProvider(region, {
- useFipsEndpoint: await config3.useFipsEndpoint(),
- useDualstackEndpoint: await config3.useDualstackEndpoint()
- }) || {},
- region
- ]).then(([regionInfo, region]) => {
- const { signingRegion, signingService } = regionInfo;
- config3.signingRegion = config3.signingRegion || signingRegion || region;
- config3.signingName = config3.signingName || signingService || config3.serviceId;
- const params = {
- ...config3,
- credentials: config3.credentials,
- region: config3.signingRegion,
- service: config3.signingName,
- sha256,
- uriEscapePath: signingEscapePath
- };
- const SignerCtor = config3.signerConstructor || signatureV4.SignatureV4;
- return new SignerCtor(params);
- });
- } else {
- signer = async (authScheme) => {
- authScheme = Object.assign({}, {
- name: "sigv4",
- signingName: config3.signingName || config3.defaultSigningName,
- signingRegion: await core2.normalizeProvider(config3.region)(),
- properties: {}
- }, authScheme);
- const signingRegion = authScheme.signingRegion;
- const signingService = authScheme.signingName;
- config3.signingRegion = config3.signingRegion || signingRegion;
- config3.signingName = config3.signingName || signingService || config3.serviceId;
- const params = {
- ...config3,
- credentials: config3.credentials,
- region: config3.signingRegion,
- service: config3.signingName,
- sha256,
- uriEscapePath: signingEscapePath
- };
- const SignerCtor = config3.signerConstructor || signatureV4.SignatureV4;
- return new SignerCtor(params);
- };
- }
- const resolvedConfig = Object.assign(config3, {
- systemClockOffset,
- signingEscapePath,
- signer
- });
- return resolvedConfig;
- };
- var resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config;
- function normalizeCredentialProvider(config3, { credentials, credentialDefaultProvider }) {
- let credentialsProvider;
- if (credentials) {
- if (!credentials?.memoized) {
- credentialsProvider = core2.memoizeIdentityProvider(credentials, core2.isIdentityExpired, core2.doesIdentityRequireRefresh);
- } else {
- credentialsProvider = credentials;
- }
- } else {
- if (credentialDefaultProvider) {
- credentialsProvider = core2.normalizeProvider(credentialDefaultProvider(Object.assign({}, config3, {
- parentClientConfig: config3
- })));
- } else {
- credentialsProvider = async () => {
- throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.");
- };
- }
- }
- credentialsProvider.memoized = true;
- return credentialsProvider;
- }
- function bindCallerConfig(config3, credentialsProvider) {
- if (credentialsProvider.configBound) {
- return credentialsProvider;
- }
- const fn = async (options2) => credentialsProvider({ ...options2, callerClientConfig: config3 });
- fn.memoized = credentialsProvider.memoized;
- fn.configBound = true;
- return fn;
- }
- exports.AWSSDKSigV4Signer = AWSSDKSigV4Signer;
- exports.AwsSdkSigV4ASigner = AwsSdkSigV4ASigner;
- exports.AwsSdkSigV4Signer = AwsSdkSigV4Signer;
- exports.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = NODE_AUTH_SCHEME_PREFERENCE_OPTIONS;
- exports.NODE_SIGV4A_CONFIG_OPTIONS = NODE_SIGV4A_CONFIG_OPTIONS;
- exports.getBearerTokenEnvKey = getBearerTokenEnvKey;
- exports.resolveAWSSDKSigV4Config = resolveAWSSDKSigV4Config;
- exports.resolveAwsSdkSigV4AConfig = resolveAwsSdkSigV4AConfig;
- exports.resolveAwsSdkSigV4Config = resolveAwsSdkSigV4Config;
- exports.validateSigningProperties = validateSigningProperties;
-});
-
-// node_modules/@aws-sdk/token-providers/dist-es/fromEnvSigningName.js
-var import_client3, import_httpAuthSchemes, import_property_provider10, fromEnvSigningName = ({ logger: logger2, signingName } = {}) => async () => {
- logger2?.debug?.("@aws-sdk/token-providers - fromEnvSigningName");
- if (!signingName) {
- throw new import_property_provider10.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger: logger2 });
- }
- const bearerTokenKey = import_httpAuthSchemes.getBearerTokenEnvKey(signingName);
- if (!(bearerTokenKey in process.env)) {
- throw new import_property_provider10.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger: logger2 });
- }
- const token = { token: process.env[bearerTokenKey] };
- import_client3.setTokenFeature(token, "BEARER_SERVICE_ENV_VARS", "3");
- return token;
-};
-var init_fromEnvSigningName = __esm(() => {
- import_client3 = __toESM(require_client(), 1);
- import_httpAuthSchemes = __toESM(require_httpAuthSchemes(), 1);
- import_property_provider10 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/token-providers/dist-es/constants.js
-var EXPIRE_WINDOW_MS, REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;
-var init_constants4 = __esm(() => {
- EXPIRE_WINDOW_MS = 5 * 60 * 1000;
-});
-
-// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs42 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration2 = (runtimeConfig) => {
- return getChecksumConfiguration2(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return resolveChecksumRuntimeConfig2(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
-});
-
-// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-cjs/index.js
-var require_dist_cjs43 = __commonJS((exports) => {
- var types3 = require_dist_cjs42();
- var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
- };
- var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
- };
-
- class Field2 {
- name;
- kind;
- values;
- constructor({ name, kind: kind2 = types3.FieldPosition.HEADER, values = [] }) {
- this.name = name;
- this.kind = kind2;
- this.values = values;
- }
- add(value) {
- this.values.push(value);
- }
- set(values) {
- this.values = values;
- }
- remove(value) {
- this.values = this.values.filter((v) => v !== value);
- }
- toString() {
- return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
- }
- get() {
- return this.values;
- }
- }
-
- class Fields2 {
- entries = {};
- encoding;
- constructor({ fields = [], encoding = "utf-8" }) {
- fields.forEach(this.setField.bind(this));
- this.encoding = encoding;
- }
- setField(field) {
- this.entries[field.name.toLowerCase()] = field;
- }
- getField(name) {
- return this.entries[name.toLowerCase()];
- }
- removeField(name) {
- delete this.entries[name.toLowerCase()];
- }
- getByType(kind2) {
- return Object.values(this.entries).filter((field) => field.kind === kind2);
- }
- }
-
- class HttpRequest2 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest2({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery2(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest2.clone(this);
- }
- }
- function cloneQuery2(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
- }
-
- class HttpResponse {
- statusCode;
- reason;
- headers;
- body;
- constructor(options2) {
- this.statusCode = options2.statusCode;
- this.reason = options2.reason;
- this.headers = options2.headers || {};
- this.body = options2.body;
- }
- static isInstance(response2) {
- if (!response2)
- return false;
- const resp = response2;
- return typeof resp.statusCode === "number" && typeof resp.headers === "object";
- }
- }
- function isValidHostname2(hostname2) {
- const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
- return hostPattern.test(hostname2);
- }
- exports.Field = Field2;
- exports.Fields = Fields2;
- exports.HttpRequest = HttpRequest2;
- exports.HttpResponse = HttpResponse;
- exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
- exports.isValidHostname = isValidHostname2;
- exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js
-var require_dist_cjs44 = __commonJS((exports) => {
- var protocolHttp = require_dist_cjs43();
- function resolveHostHeaderConfig(input) {
- return input;
- }
- var hostHeaderMiddleware = (options2) => (next) => async (args) => {
- if (!protocolHttp.HttpRequest.isInstance(args.request))
- return next(args);
- const { request: request2 } = args;
- const { handlerProtocol = "" } = options2.requestHandler.metadata || {};
- if (handlerProtocol.indexOf("h2") >= 0 && !request2.headers[":authority"]) {
- delete request2.headers["host"];
- request2.headers[":authority"] = request2.hostname + (request2.port ? ":" + request2.port : "");
- } else if (!request2.headers["host"]) {
- let host = request2.hostname;
- if (request2.port != null)
- host += `:${request2.port}`;
- request2.headers["host"] = host;
- }
- return next(args);
- };
- var hostHeaderMiddlewareOptions = {
- name: "hostHeaderMiddleware",
- step: "build",
- priority: "low",
- tags: ["HOST"],
- override: true
- };
- var getHostHeaderPlugin = (options2) => ({
- applyToStack: (clientStack) => {
- clientStack.add(hostHeaderMiddleware(options2), hostHeaderMiddlewareOptions);
- }
- });
- exports.getHostHeaderPlugin = getHostHeaderPlugin;
- exports.hostHeaderMiddleware = hostHeaderMiddleware;
- exports.hostHeaderMiddlewareOptions = hostHeaderMiddlewareOptions;
- exports.resolveHostHeaderConfig = resolveHostHeaderConfig;
-});
-
-// node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js
-var require_dist_cjs45 = __commonJS((exports) => {
- var loggerMiddleware = () => (next, context) => async (args) => {
- try {
- const response2 = await next(args);
- const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context;
- const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
- const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
- const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog;
- const { $metadata, ...outputWithoutMetadata } = response2.output;
- logger2?.info?.({
- clientName,
- commandName,
- input: inputFilterSensitiveLog(args.input),
- output: outputFilterSensitiveLog(outputWithoutMetadata),
- metadata: $metadata
- });
- return response2;
- } catch (error40) {
- const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context;
- const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
- const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
- logger2?.error?.({
- clientName,
- commandName,
- input: inputFilterSensitiveLog(args.input),
- error: error40,
- metadata: error40.$metadata
- });
- throw error40;
- }
- };
- var loggerMiddlewareOptions = {
- name: "loggerMiddleware",
- tags: ["LOGGER"],
- step: "initialize",
- override: true
- };
- var getLoggerPlugin = (options2) => ({
- applyToStack: (clientStack) => {
- clientStack.add(loggerMiddleware(), loggerMiddlewareOptions);
- }
- });
- exports.getLoggerPlugin = getLoggerPlugin;
- exports.loggerMiddleware = loggerMiddleware;
- exports.loggerMiddlewareOptions = loggerMiddlewareOptions;
-});
-
-// node_modules/@aws/lambda-invoke-store/dist-cjs/invoke-store.js
-var require_invoke_store = __commonJS((exports) => {
- var PROTECTED_KEYS = {
- REQUEST_ID: Symbol.for("_AWS_LAMBDA_REQUEST_ID"),
- X_RAY_TRACE_ID: Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),
- TENANT_ID: Symbol.for("_AWS_LAMBDA_TENANT_ID")
- };
- var NO_GLOBAL_AWS_LAMBDA = ["true", "1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? "");
- if (!NO_GLOBAL_AWS_LAMBDA) {
- globalThis.awslambda = globalThis.awslambda || {};
- }
-
- class InvokeStoreBase {
- static PROTECTED_KEYS = PROTECTED_KEYS;
- isProtectedKey(key) {
- return Object.values(PROTECTED_KEYS).includes(key);
- }
- getRequestId() {
- return this.get(PROTECTED_KEYS.REQUEST_ID) ?? "-";
- }
- getXRayTraceId() {
- return this.get(PROTECTED_KEYS.X_RAY_TRACE_ID);
- }
- getTenantId() {
- return this.get(PROTECTED_KEYS.TENANT_ID);
- }
- }
-
- class InvokeStoreSingle extends InvokeStoreBase {
- currentContext;
- getContext() {
- return this.currentContext;
- }
- hasContext() {
- return this.currentContext !== undefined;
- }
- get(key) {
- return this.currentContext?.[key];
- }
- set(key, value) {
- if (this.isProtectedKey(key)) {
- throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);
- }
- this.currentContext = this.currentContext || {};
- this.currentContext[key] = value;
- }
- run(context, fn) {
- this.currentContext = context;
- return fn();
- }
- }
-
- class InvokeStoreMulti extends InvokeStoreBase {
- als;
- static async create() {
- const instance = new InvokeStoreMulti;
- const asyncHooks = await import("async_hooks");
- instance.als = new asyncHooks.AsyncLocalStorage;
- return instance;
- }
- getContext() {
- return this.als.getStore();
- }
- hasContext() {
- return this.als.getStore() !== undefined;
- }
- get(key) {
- return this.als.getStore()?.[key];
- }
- set(key, value) {
- if (this.isProtectedKey(key)) {
- throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);
- }
- const store = this.als.getStore();
- if (!store) {
- throw new Error("No context available");
- }
- store[key] = value;
- }
- run(context, fn) {
- return this.als.run(context, fn);
- }
- }
- exports.InvokeStore = undefined;
- (function(InvokeStore) {
- let instance = null;
- async function getInstanceAsync(forceInvokeStoreMulti) {
- if (!instance) {
- instance = (async () => {
- const isMulti = forceInvokeStoreMulti === true || "AWS_LAMBDA_MAX_CONCURRENCY" in process.env;
- const newInstance = isMulti ? await InvokeStoreMulti.create() : new InvokeStoreSingle;
- if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda?.InvokeStore) {
- return globalThis.awslambda.InvokeStore;
- } else if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda) {
- globalThis.awslambda.InvokeStore = newInstance;
- return newInstance;
- } else {
- return newInstance;
- }
- })();
- }
- return instance;
- }
- InvokeStore.getInstanceAsync = getInstanceAsync;
- InvokeStore._testing = process.env.AWS_LAMBDA_BENCHMARK_MODE === "1" ? {
- reset: () => {
- instance = null;
- if (globalThis.awslambda?.InvokeStore) {
- delete globalThis.awslambda.InvokeStore;
- }
- globalThis.awslambda = { InvokeStore: undefined };
- }
- } : undefined;
- })(exports.InvokeStore || (exports.InvokeStore = {}));
- exports.InvokeStoreBase = InvokeStoreBase;
-});
-
-// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs46 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration2 = (runtimeConfig) => {
- return getChecksumConfiguration2(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return resolveChecksumRuntimeConfig2(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
-});
-
-// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-cjs/index.js
-var require_dist_cjs47 = __commonJS((exports) => {
- var types3 = require_dist_cjs46();
- var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
- };
- var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
- };
-
- class Field2 {
- name;
- kind;
- values;
- constructor({ name, kind: kind2 = types3.FieldPosition.HEADER, values = [] }) {
- this.name = name;
- this.kind = kind2;
- this.values = values;
- }
- add(value) {
- this.values.push(value);
- }
- set(values) {
- this.values = values;
- }
- remove(value) {
- this.values = this.values.filter((v) => v !== value);
- }
- toString() {
- return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
- }
- get() {
- return this.values;
- }
- }
-
- class Fields2 {
- entries = {};
- encoding;
- constructor({ fields = [], encoding = "utf-8" }) {
- fields.forEach(this.setField.bind(this));
- this.encoding = encoding;
- }
- setField(field) {
- this.entries[field.name.toLowerCase()] = field;
- }
- getField(name) {
- return this.entries[name.toLowerCase()];
- }
- removeField(name) {
- delete this.entries[name.toLowerCase()];
- }
- getByType(kind2) {
- return Object.values(this.entries).filter((field) => field.kind === kind2);
- }
- }
-
- class HttpRequest2 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest2({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery2(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest2.clone(this);
- }
- }
- function cloneQuery2(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
- }
-
- class HttpResponse {
- statusCode;
- reason;
- headers;
- body;
- constructor(options2) {
- this.statusCode = options2.statusCode;
- this.reason = options2.reason;
- this.headers = options2.headers || {};
- this.body = options2.body;
- }
- static isInstance(response2) {
- if (!response2)
- return false;
- const resp = response2;
- return typeof resp.statusCode === "number" && typeof resp.headers === "object";
- }
- }
- function isValidHostname2(hostname2) {
- const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
- return hostPattern.test(hostname2);
- }
- exports.Field = Field2;
- exports.Fields = Fields2;
- exports.HttpRequest = HttpRequest2;
- exports.HttpResponse = HttpResponse;
- exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
- exports.isValidHostname = isValidHostname2;
- exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js
-var require_recursionDetectionMiddleware = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.recursionDetectionMiddleware = undefined;
- var lambda_invoke_store_1 = require_invoke_store();
- var protocol_http_1 = require_dist_cjs47();
- var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
- var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
- var ENV_TRACE_ID = "_X_AMZN_TRACE_ID";
- var recursionDetectionMiddleware = () => (next) => async (args) => {
- const { request: request2 } = args;
- if (!protocol_http_1.HttpRequest.isInstance(request2)) {
- return next(args);
- }
- const traceIdHeader = Object.keys(request2.headers ?? {}).find((h2) => h2.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME;
- if (request2.headers.hasOwnProperty(traceIdHeader)) {
- return next(args);
- }
- const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME];
- const traceIdFromEnv = process.env[ENV_TRACE_ID];
- const invokeStore = await lambda_invoke_store_1.InvokeStore.getInstanceAsync();
- const traceIdFromInvokeStore = invokeStore?.getXRayTraceId();
- const traceId = traceIdFromInvokeStore ?? traceIdFromEnv;
- const nonEmptyString2 = (str) => typeof str === "string" && str.length > 0;
- if (nonEmptyString2(functionName) && nonEmptyString2(traceId)) {
- request2.headers[TRACE_ID_HEADER_NAME] = traceId;
- }
- return next({
- ...args,
- request: request2
- });
- };
- exports.recursionDetectionMiddleware = recursionDetectionMiddleware;
-});
-
-// node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js
-var require_dist_cjs48 = __commonJS((exports) => {
- var recursionDetectionMiddleware = require_recursionDetectionMiddleware();
- var recursionDetectionMiddlewareOptions = {
- step: "build",
- tags: ["RECURSION_DETECTION"],
- name: "recursionDetectionMiddleware",
- override: true,
- priority: "low"
- };
- var getRecursionDetectionPlugin = (options2) => ({
- applyToStack: (clientStack) => {
- clientStack.add(recursionDetectionMiddleware.recursionDetectionMiddleware(), recursionDetectionMiddlewareOptions);
- }
- });
- exports.getRecursionDetectionPlugin = getRecursionDetectionPlugin;
- Object.prototype.hasOwnProperty.call(recursionDetectionMiddleware, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: recursionDetectionMiddleware["__proto__"]
- });
- Object.keys(recursionDetectionMiddleware).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = recursionDetectionMiddleware[k];
- });
-});
-
-// node_modules/@smithy/util-endpoints/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs49 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration2 = (runtimeConfig) => {
- return getChecksumConfiguration2(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return resolveChecksumRuntimeConfig2(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
-});
-
-// node_modules/@smithy/util-endpoints/dist-cjs/index.js
-var require_dist_cjs50 = __commonJS((exports) => {
- var types3 = require_dist_cjs49();
-
- class EndpointCache {
- capacity;
- data = new Map;
- parameters = [];
- constructor({ size, params }) {
- this.capacity = size ?? 50;
- if (params) {
- this.parameters = params;
- }
- }
- get(endpointParams, resolver) {
- const key = this.hash(endpointParams);
- if (key === false) {
- return resolver();
- }
- if (!this.data.has(key)) {
- if (this.data.size > this.capacity + 10) {
- const keys2 = this.data.keys();
- let i2 = 0;
- while (true) {
- const { value, done } = keys2.next();
- this.data.delete(value);
- if (done || ++i2 > 10) {
- break;
- }
- }
- }
- this.data.set(key, resolver());
- }
- return this.data.get(key);
- }
- size() {
- return this.data.size;
- }
- hash(endpointParams) {
- let buffer = "";
- const { parameters } = this;
- if (parameters.length === 0) {
- return false;
- }
- for (const param of parameters) {
- const val = String(endpointParams[param] ?? "");
- if (val.includes("|;")) {
- return false;
- }
- buffer += val + "|;";
- }
- return buffer;
- }
- }
- var IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`);
- var isIpAddress = (value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]");
- var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);
- var isValidHostLabel = (value, allowSubDomains = false) => {
- if (!allowSubDomains) {
- return VALID_HOST_LABEL_REGEX.test(value);
- }
- const labels = value.split(".");
- for (const label of labels) {
- if (!isValidHostLabel(label)) {
- return false;
- }
- }
- return true;
- };
- var customEndpointFunctions = {};
- var debugId = "endpoints";
- function toDebugString(input) {
- if (typeof input !== "object" || input == null) {
- return input;
- }
- if ("ref" in input) {
- return `$${toDebugString(input.ref)}`;
- }
- if ("fn" in input) {
- return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`;
- }
- return JSON.stringify(input, null, 2);
- }
-
- class EndpointError extends Error {
- constructor(message) {
- super(message);
- this.name = "EndpointError";
- }
- }
- var booleanEquals = (value1, value2) => value1 === value2;
- var getAttrPathList = (path8) => {
- const parts = path8.split(".");
- const pathList = [];
- for (const part of parts) {
- const squareBracketIndex = part.indexOf("[");
- if (squareBracketIndex !== -1) {
- if (part.indexOf("]") !== part.length - 1) {
- throw new EndpointError(`Path: '${path8}' does not end with ']'`);
- }
- const arrayIndex = part.slice(squareBracketIndex + 1, -1);
- if (Number.isNaN(parseInt(arrayIndex))) {
- throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path8}'`);
- }
- if (squareBracketIndex !== 0) {
- pathList.push(part.slice(0, squareBracketIndex));
- }
- pathList.push(arrayIndex);
- } else {
- pathList.push(part);
- }
- }
- return pathList;
- };
- var getAttr = (value, path8) => getAttrPathList(path8).reduce((acc, index2) => {
- if (typeof acc !== "object") {
- throw new EndpointError(`Index '${index2}' in '${path8}' not found in '${JSON.stringify(value)}'`);
- } else if (Array.isArray(acc)) {
- return acc[parseInt(index2)];
- }
- return acc[index2];
- }, value);
- var isSet2 = (value) => value != null;
- var not = (value) => !value;
- var DEFAULT_PORTS2 = {
- [types3.EndpointURLScheme.HTTP]: 80,
- [types3.EndpointURLScheme.HTTPS]: 443
- };
- var parseURL = (value) => {
- const whatwgURL = (() => {
- try {
- if (value instanceof URL) {
- return value;
- }
- if (typeof value === "object" && "hostname" in value) {
- const { hostname: hostname3, port, protocol: protocol2 = "", path: path8 = "", query = {} } = value;
- const url3 = new URL(`${protocol2}//${hostname3}${port ? `:${port}` : ""}${path8}`);
- url3.search = Object.entries(query).map(([k, v]) => `${k}=${v}`).join("&");
- return url3;
- }
- return new URL(value);
- } catch (error40) {
- return null;
- }
- })();
- if (!whatwgURL) {
- console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);
- return null;
- }
- const urlString = whatwgURL.href;
- const { host, hostname: hostname2, pathname, protocol, search } = whatwgURL;
- if (search) {
- return null;
- }
- const scheme = protocol.slice(0, -1);
- if (!Object.values(types3.EndpointURLScheme).includes(scheme)) {
- return null;
- }
- const isIp = isIpAddress(hostname2);
- const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS2[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS2[scheme]}`);
- const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS2[scheme]}` : ``}`;
- return {
- scheme,
- authority,
- path: pathname,
- normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`,
- isIp
- };
- };
- var stringEquals = (value1, value2) => value1 === value2;
- var substring = (input, start, stop, reverse) => {
- if (start >= stop || input.length < stop || /[^\u0000-\u007f]/.test(input)) {
- return null;
- }
- if (!reverse) {
- return input.substring(start, stop);
- }
- return input.substring(input.length - stop, input.length - start);
- };
- var uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`);
- var endpointFunctions = {
- booleanEquals,
- getAttr,
- isSet: isSet2,
- isValidHostLabel,
- not,
- parseURL,
- stringEquals,
- substring,
- uriEncode
- };
- var evaluateTemplate = (template, options2) => {
- const evaluatedTemplateArr = [];
- const templateContext = {
- ...options2.endpointParams,
- ...options2.referenceRecord
- };
- let currentIndex = 0;
- while (currentIndex < template.length) {
- const openingBraceIndex = template.indexOf("{", currentIndex);
- if (openingBraceIndex === -1) {
- evaluatedTemplateArr.push(template.slice(currentIndex));
- break;
- }
- evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex));
- const closingBraceIndex = template.indexOf("}", openingBraceIndex);
- if (closingBraceIndex === -1) {
- evaluatedTemplateArr.push(template.slice(openingBraceIndex));
- break;
- }
- if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") {
- evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex));
- currentIndex = closingBraceIndex + 2;
- }
- const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex);
- if (parameterName.includes("#")) {
- const [refName, attrName] = parameterName.split("#");
- evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName));
- } else {
- evaluatedTemplateArr.push(templateContext[parameterName]);
- }
- currentIndex = closingBraceIndex + 1;
- }
- return evaluatedTemplateArr.join("");
- };
- var getReferenceValue = ({ ref }, options2) => {
- const referenceRecord = {
- ...options2.endpointParams,
- ...options2.referenceRecord
- };
- return referenceRecord[ref];
- };
- var evaluateExpression = (obj, keyName, options2) => {
- if (typeof obj === "string") {
- return evaluateTemplate(obj, options2);
- } else if (obj["fn"]) {
- return group$2.callFunction(obj, options2);
- } else if (obj["ref"]) {
- return getReferenceValue(obj, options2);
- }
- throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`);
- };
- var callFunction = ({ fn, argv }, options2) => {
- const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : group$2.evaluateExpression(arg, "arg", options2));
- const fnSegments = fn.split(".");
- if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) {
- return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs);
- }
- return endpointFunctions[fn](...evaluatedArgs);
- };
- var group$2 = {
- evaluateExpression,
- callFunction
- };
- var evaluateCondition = ({ assign, ...fnArgs }, options2) => {
- if (assign && assign in options2.referenceRecord) {
- throw new EndpointError(`'${assign}' is already defined in Reference Record.`);
- }
- const value = callFunction(fnArgs, options2);
- options2.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);
- return {
- result: value === "" ? true : !!value,
- ...assign != null && { toAssign: { name: assign, value } }
- };
- };
- var evaluateConditions = (conditions = [], options2) => {
- const conditionsReferenceRecord = {};
- for (const condition of conditions) {
- const { result, toAssign } = evaluateCondition(condition, {
- ...options2,
- referenceRecord: {
- ...options2.referenceRecord,
- ...conditionsReferenceRecord
- }
- });
- if (!result) {
- return { result };
- }
- if (toAssign) {
- conditionsReferenceRecord[toAssign.name] = toAssign.value;
- options2.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`);
- }
- }
- return { result: true, referenceRecord: conditionsReferenceRecord };
- };
- var getEndpointHeaders = (headers, options2) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({
- ...acc,
- [headerKey]: headerVal.map((headerValEntry) => {
- const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options2);
- if (typeof processedExpr !== "string") {
- throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`);
- }
- return processedExpr;
- })
- }), {});
- var getEndpointProperties = (properties, options2) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({
- ...acc,
- [propertyKey]: group$1.getEndpointProperty(propertyVal, options2)
- }), {});
- var getEndpointProperty = (property2, options2) => {
- if (Array.isArray(property2)) {
- return property2.map((propertyEntry) => getEndpointProperty(propertyEntry, options2));
- }
- switch (typeof property2) {
- case "string":
- return evaluateTemplate(property2, options2);
- case "object":
- if (property2 === null) {
- throw new EndpointError(`Unexpected endpoint property: ${property2}`);
- }
- return group$1.getEndpointProperties(property2, options2);
- case "boolean":
- return property2;
- default:
- throw new EndpointError(`Unexpected endpoint property type: ${typeof property2}`);
- }
- };
- var group$1 = {
- getEndpointProperty,
- getEndpointProperties
- };
- var getEndpointUrl = (endpointUrl, options2) => {
- const expression = evaluateExpression(endpointUrl, "Endpoint URL", options2);
- if (typeof expression === "string") {
- try {
- return new URL(expression);
- } catch (error40) {
- console.error(`Failed to construct URL with ${expression}`, error40);
- throw error40;
- }
- }
- throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`);
- };
- var evaluateEndpointRule = (endpointRule, options2) => {
- const { conditions, endpoint: endpoint2 } = endpointRule;
- const { result, referenceRecord } = evaluateConditions(conditions, options2);
- if (!result) {
- return;
- }
- const endpointRuleOptions = {
- ...options2,
- referenceRecord: { ...options2.referenceRecord, ...referenceRecord }
- };
- const { url: url3, properties, headers } = endpoint2;
- options2.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint2)}`);
- return {
- ...headers != null && {
- headers: getEndpointHeaders(headers, endpointRuleOptions)
- },
- ...properties != null && {
- properties: getEndpointProperties(properties, endpointRuleOptions)
- },
- url: getEndpointUrl(url3, endpointRuleOptions)
- };
- };
- var evaluateErrorRule = (errorRule, options2) => {
- const { conditions, error: error40 } = errorRule;
- const { result, referenceRecord } = evaluateConditions(conditions, options2);
- if (!result) {
- return;
- }
- throw new EndpointError(evaluateExpression(error40, "Error", {
- ...options2,
- referenceRecord: { ...options2.referenceRecord, ...referenceRecord }
- }));
- };
- var evaluateRules = (rules, options2) => {
- for (const rule of rules) {
- if (rule.type === "endpoint") {
- const endpointOrUndefined = evaluateEndpointRule(rule, options2);
- if (endpointOrUndefined) {
- return endpointOrUndefined;
- }
- } else if (rule.type === "error") {
- evaluateErrorRule(rule, options2);
- } else if (rule.type === "tree") {
- const endpointOrUndefined = group.evaluateTreeRule(rule, options2);
- if (endpointOrUndefined) {
- return endpointOrUndefined;
- }
- } else {
- throw new EndpointError(`Unknown endpoint rule: ${rule}`);
- }
- }
- throw new EndpointError(`Rules evaluation failed`);
- };
- var evaluateTreeRule = (treeRule, options2) => {
- const { conditions, rules } = treeRule;
- const { result, referenceRecord } = evaluateConditions(conditions, options2);
- if (!result) {
- return;
- }
- return group.evaluateRules(rules, {
- ...options2,
- referenceRecord: { ...options2.referenceRecord, ...referenceRecord }
- });
- };
- var group = {
- evaluateRules,
- evaluateTreeRule
- };
- var resolveEndpoint = (ruleSetObject, options2) => {
- const { endpointParams, logger: logger2 } = options2;
- const { parameters, rules } = ruleSetObject;
- options2.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);
- const paramsWithDefault = Object.entries(parameters).filter(([, v]) => v.default != null).map(([k, v]) => [k, v.default]);
- if (paramsWithDefault.length > 0) {
- for (const [paramKey, paramDefaultValue] of paramsWithDefault) {
- endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue;
- }
- }
- const requiredParams = Object.entries(parameters).filter(([, v]) => v.required).map(([k]) => k);
- for (const requiredParam of requiredParams) {
- if (endpointParams[requiredParam] == null) {
- throw new EndpointError(`Missing required parameter: '${requiredParam}'`);
- }
- }
- const endpoint2 = evaluateRules(rules, { endpointParams, logger: logger2, referenceRecord: {} });
- options2.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint2)}`);
- return endpoint2;
- };
- exports.EndpointCache = EndpointCache;
- exports.EndpointError = EndpointError;
- exports.customEndpointFunctions = customEndpointFunctions;
- exports.isIpAddress = isIpAddress;
- exports.isValidHostLabel = isValidHostLabel;
- exports.resolveEndpoint = resolveEndpoint;
-});
-
-// node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js
-var require_dist_cjs51 = __commonJS((exports) => {
- var utilEndpoints = require_dist_cjs50();
- var urlParser = require_dist_cjs11();
- var isVirtualHostableS3Bucket = (value, allowSubDomains = false) => {
- if (allowSubDomains) {
- for (const label of value.split(".")) {
- if (!isVirtualHostableS3Bucket(label)) {
- return false;
- }
- }
- return true;
- }
- if (!utilEndpoints.isValidHostLabel(value)) {
- return false;
- }
- if (value.length < 3 || value.length > 63) {
- return false;
- }
- if (value !== value.toLowerCase()) {
- return false;
- }
- if (utilEndpoints.isIpAddress(value)) {
- return false;
- }
- return true;
- };
- var ARN_DELIMITER = ":";
- var RESOURCE_DELIMITER = "/";
- var parseArn = (value) => {
- const segments = value.split(ARN_DELIMITER);
- if (segments.length < 6)
- return null;
- const [arn, partition3, service, region, accountId, ...resourcePath] = segments;
- if (arn !== "arn" || partition3 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "")
- return null;
- const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat();
- return {
- partition: partition3,
- service,
- region,
- accountId,
- resourceId
- };
- };
- var partitions = [
- {
- id: "aws",
- outputs: {
- dnsSuffix: "amazonaws.com",
- dualStackDnsSuffix: "api.aws",
- implicitGlobalRegion: "us-east-1",
- name: "aws",
- supportsDualStack: true,
- supportsFIPS: true
- },
- regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",
- regions: {
- "af-south-1": {
- description: "Africa (Cape Town)"
- },
- "ap-east-1": {
- description: "Asia Pacific (Hong Kong)"
- },
- "ap-east-2": {
- description: "Asia Pacific (Taipei)"
- },
- "ap-northeast-1": {
- description: "Asia Pacific (Tokyo)"
- },
- "ap-northeast-2": {
- description: "Asia Pacific (Seoul)"
- },
- "ap-northeast-3": {
- description: "Asia Pacific (Osaka)"
- },
- "ap-south-1": {
- description: "Asia Pacific (Mumbai)"
- },
- "ap-south-2": {
- description: "Asia Pacific (Hyderabad)"
- },
- "ap-southeast-1": {
- description: "Asia Pacific (Singapore)"
- },
- "ap-southeast-2": {
- description: "Asia Pacific (Sydney)"
- },
- "ap-southeast-3": {
- description: "Asia Pacific (Jakarta)"
- },
- "ap-southeast-4": {
- description: "Asia Pacific (Melbourne)"
- },
- "ap-southeast-5": {
- description: "Asia Pacific (Malaysia)"
- },
- "ap-southeast-6": {
- description: "Asia Pacific (New Zealand)"
- },
- "ap-southeast-7": {
- description: "Asia Pacific (Thailand)"
- },
- "aws-global": {
- description: "aws global region"
- },
- "ca-central-1": {
- description: "Canada (Central)"
- },
- "ca-west-1": {
- description: "Canada West (Calgary)"
- },
- "eu-central-1": {
- description: "Europe (Frankfurt)"
- },
- "eu-central-2": {
- description: "Europe (Zurich)"
- },
- "eu-north-1": {
- description: "Europe (Stockholm)"
- },
- "eu-south-1": {
- description: "Europe (Milan)"
- },
- "eu-south-2": {
- description: "Europe (Spain)"
- },
- "eu-west-1": {
- description: "Europe (Ireland)"
- },
- "eu-west-2": {
- description: "Europe (London)"
- },
- "eu-west-3": {
- description: "Europe (Paris)"
- },
- "il-central-1": {
- description: "Israel (Tel Aviv)"
- },
- "me-central-1": {
- description: "Middle East (UAE)"
- },
- "me-south-1": {
- description: "Middle East (Bahrain)"
- },
- "mx-central-1": {
- description: "Mexico (Central)"
- },
- "sa-east-1": {
- description: "South America (Sao Paulo)"
- },
- "us-east-1": {
- description: "US East (N. Virginia)"
- },
- "us-east-2": {
- description: "US East (Ohio)"
- },
- "us-west-1": {
- description: "US West (N. California)"
- },
- "us-west-2": {
- description: "US West (Oregon)"
- }
- }
- },
- {
- id: "aws-cn",
- outputs: {
- dnsSuffix: "amazonaws.com.cn",
- dualStackDnsSuffix: "api.amazonwebservices.com.cn",
- implicitGlobalRegion: "cn-northwest-1",
- name: "aws-cn",
- supportsDualStack: true,
- supportsFIPS: true
- },
- regionRegex: "^cn\\-\\w+\\-\\d+$",
- regions: {
- "aws-cn-global": {
- description: "aws-cn global region"
- },
- "cn-north-1": {
- description: "China (Beijing)"
- },
- "cn-northwest-1": {
- description: "China (Ningxia)"
- }
- }
- },
- {
- id: "aws-eusc",
- outputs: {
- dnsSuffix: "amazonaws.eu",
- dualStackDnsSuffix: "api.amazonwebservices.eu",
- implicitGlobalRegion: "eusc-de-east-1",
- name: "aws-eusc",
- supportsDualStack: true,
- supportsFIPS: true
- },
- regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$",
- regions: {
- "eusc-de-east-1": {
- description: "AWS European Sovereign Cloud (Germany)"
- }
- }
- },
- {
- id: "aws-iso",
- outputs: {
- dnsSuffix: "c2s.ic.gov",
- dualStackDnsSuffix: "api.aws.ic.gov",
- implicitGlobalRegion: "us-iso-east-1",
- name: "aws-iso",
- supportsDualStack: true,
- supportsFIPS: true
- },
- regionRegex: "^us\\-iso\\-\\w+\\-\\d+$",
- regions: {
- "aws-iso-global": {
- description: "aws-iso global region"
- },
- "us-iso-east-1": {
- description: "US ISO East"
- },
- "us-iso-west-1": {
- description: "US ISO WEST"
- }
- }
- },
- {
- id: "aws-iso-b",
- outputs: {
- dnsSuffix: "sc2s.sgov.gov",
- dualStackDnsSuffix: "api.aws.scloud",
- implicitGlobalRegion: "us-isob-east-1",
- name: "aws-iso-b",
- supportsDualStack: true,
- supportsFIPS: true
- },
- regionRegex: "^us\\-isob\\-\\w+\\-\\d+$",
- regions: {
- "aws-iso-b-global": {
- description: "aws-iso-b global region"
- },
- "us-isob-east-1": {
- description: "US ISOB East (Ohio)"
- },
- "us-isob-west-1": {
- description: "US ISOB West"
- }
- }
- },
- {
- id: "aws-iso-e",
- outputs: {
- dnsSuffix: "cloud.adc-e.uk",
- dualStackDnsSuffix: "api.cloud-aws.adc-e.uk",
- implicitGlobalRegion: "eu-isoe-west-1",
- name: "aws-iso-e",
- supportsDualStack: true,
- supportsFIPS: true
- },
- regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$",
- regions: {
- "aws-iso-e-global": {
- description: "aws-iso-e global region"
- },
- "eu-isoe-west-1": {
- description: "EU ISOE West"
- }
- }
- },
- {
- id: "aws-iso-f",
- outputs: {
- dnsSuffix: "csp.hci.ic.gov",
- dualStackDnsSuffix: "api.aws.hci.ic.gov",
- implicitGlobalRegion: "us-isof-south-1",
- name: "aws-iso-f",
- supportsDualStack: true,
- supportsFIPS: true
- },
- regionRegex: "^us\\-isof\\-\\w+\\-\\d+$",
- regions: {
- "aws-iso-f-global": {
- description: "aws-iso-f global region"
- },
- "us-isof-east-1": {
- description: "US ISOF EAST"
- },
- "us-isof-south-1": {
- description: "US ISOF SOUTH"
- }
- }
- },
- {
- id: "aws-us-gov",
- outputs: {
- dnsSuffix: "amazonaws.com",
- dualStackDnsSuffix: "api.aws",
- implicitGlobalRegion: "us-gov-west-1",
- name: "aws-us-gov",
- supportsDualStack: true,
- supportsFIPS: true
- },
- regionRegex: "^us\\-gov\\-\\w+\\-\\d+$",
- regions: {
- "aws-us-gov-global": {
- description: "aws-us-gov global region"
- },
- "us-gov-east-1": {
- description: "AWS GovCloud (US-East)"
- },
- "us-gov-west-1": {
- description: "AWS GovCloud (US-West)"
- }
- }
- }
- ];
- var version2 = "1.1";
- var partitionsInfo = {
- partitions,
- version: version2
- };
- var selectedPartitionsInfo = partitionsInfo;
- var selectedUserAgentPrefix = "";
- var partition2 = (value) => {
- const { partitions: partitions2 } = selectedPartitionsInfo;
- for (const partition3 of partitions2) {
- const { regions, outputs } = partition3;
- for (const [region, regionData] of Object.entries(regions)) {
- if (region === value) {
- return {
- ...outputs,
- ...regionData
- };
- }
- }
- }
- for (const partition3 of partitions2) {
- const { regionRegex, outputs } = partition3;
- if (new RegExp(regionRegex).test(value)) {
- return {
- ...outputs
- };
- }
- }
- const DEFAULT_PARTITION = partitions2.find((partition3) => partition3.id === "aws");
- if (!DEFAULT_PARTITION) {
- throw new Error("Provided region was not found in the partition array or regex," + " and default partition with id 'aws' doesn't exist.");
- }
- return {
- ...DEFAULT_PARTITION.outputs
- };
- };
- var setPartitionInfo = (partitionsInfo2, userAgentPrefix = "") => {
- selectedPartitionsInfo = partitionsInfo2;
- selectedUserAgentPrefix = userAgentPrefix;
- };
- var useDefaultPartitionInfo = () => {
- setPartitionInfo(partitionsInfo, "");
- };
- var getUserAgentPrefix = () => selectedUserAgentPrefix;
- var awsEndpointFunctions = {
- isVirtualHostableS3Bucket,
- parseArn,
- partition: partition2
- };
- utilEndpoints.customEndpointFunctions.aws = awsEndpointFunctions;
- var resolveDefaultAwsRegionalEndpointsConfig = (input) => {
- if (typeof input.endpointProvider !== "function") {
- throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");
- }
- const { endpoint: endpoint2 } = input;
- if (endpoint2 === undefined) {
- input.endpoint = async () => {
- return toEndpointV1(input.endpointProvider({
- Region: typeof input.region === "function" ? await input.region() : input.region,
- UseDualStack: typeof input.useDualstackEndpoint === "function" ? await input.useDualstackEndpoint() : input.useDualstackEndpoint,
- UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint,
- Endpoint: undefined
- }, { logger: input.logger }));
- };
- }
- return input;
- };
- var toEndpointV1 = (endpoint2) => urlParser.parseUrl(endpoint2.url);
- exports.EndpointError = utilEndpoints.EndpointError;
- exports.isIpAddress = utilEndpoints.isIpAddress;
- exports.resolveEndpoint = utilEndpoints.resolveEndpoint;
- exports.awsEndpointFunctions = awsEndpointFunctions;
- exports.getUserAgentPrefix = getUserAgentPrefix;
- exports.partition = partition2;
- exports.resolveDefaultAwsRegionalEndpointsConfig = resolveDefaultAwsRegionalEndpointsConfig;
- exports.setPartitionInfo = setPartitionInfo;
- exports.toEndpointV1 = toEndpointV1;
- exports.useDefaultPartitionInfo = useDefaultPartitionInfo;
-});
-
-// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs52 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration2 = (runtimeConfig) => {
- return getChecksumConfiguration2(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return resolveChecksumRuntimeConfig2(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
-});
-
-// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-cjs/index.js
-var require_dist_cjs53 = __commonJS((exports) => {
- var types3 = require_dist_cjs52();
- var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
- };
- var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
- };
-
- class Field2 {
- name;
- kind;
- values;
- constructor({ name, kind: kind2 = types3.FieldPosition.HEADER, values = [] }) {
- this.name = name;
- this.kind = kind2;
- this.values = values;
- }
- add(value) {
- this.values.push(value);
- }
- set(values) {
- this.values = values;
- }
- remove(value) {
- this.values = this.values.filter((v) => v !== value);
- }
- toString() {
- return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
- }
- get() {
- return this.values;
- }
- }
-
- class Fields2 {
- entries = {};
- encoding;
- constructor({ fields = [], encoding = "utf-8" }) {
- fields.forEach(this.setField.bind(this));
- this.encoding = encoding;
- }
- setField(field) {
- this.entries[field.name.toLowerCase()] = field;
- }
- getField(name) {
- return this.entries[name.toLowerCase()];
- }
- removeField(name) {
- delete this.entries[name.toLowerCase()];
- }
- getByType(kind2) {
- return Object.values(this.entries).filter((field) => field.kind === kind2);
- }
- }
-
- class HttpRequest2 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest2({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery2(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest2.clone(this);
- }
- }
- function cloneQuery2(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
- }
-
- class HttpResponse {
- statusCode;
- reason;
- headers;
- body;
- constructor(options2) {
- this.statusCode = options2.statusCode;
- this.reason = options2.reason;
- this.headers = options2.headers || {};
- this.body = options2.body;
- }
- static isInstance(response2) {
- if (!response2)
- return false;
- const resp = response2;
- return typeof resp.statusCode === "number" && typeof resp.headers === "object";
- }
- }
- function isValidHostname2(hostname2) {
- const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
- return hostPattern.test(hostname2);
- }
- exports.Field = Field2;
- exports.Fields = Fields2;
- exports.HttpRequest = HttpRequest2;
- exports.HttpResponse = HttpResponse;
- exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
- exports.isValidHostname = isValidHostname2;
- exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;
-});
-
-// node_modules/@smithy/service-error-classification/dist-cjs/index.js
-var require_dist_cjs54 = __commonJS((exports) => {
- var CLOCK_SKEW_ERROR_CODES = [
- "AuthFailure",
- "InvalidSignatureException",
- "RequestExpired",
- "RequestInTheFuture",
- "RequestTimeTooSkewed",
- "SignatureDoesNotMatch"
- ];
- var THROTTLING_ERROR_CODES = [
- "BandwidthLimitExceeded",
- "EC2ThrottledException",
- "LimitExceededException",
- "PriorRequestNotComplete",
- "ProvisionedThroughputExceededException",
- "RequestLimitExceeded",
- "RequestThrottled",
- "RequestThrottledException",
- "SlowDown",
- "ThrottledException",
- "Throttling",
- "ThrottlingException",
- "TooManyRequestsException",
- "TransactionInProgressException"
- ];
- var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"];
- var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];
- var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"];
- var NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND"];
- var isRetryableByTrait = (error40) => error40?.$retryable !== undefined;
- var isClockSkewError = (error40) => CLOCK_SKEW_ERROR_CODES.includes(error40.name);
- var isClockSkewCorrectedError = (error40) => error40.$metadata?.clockSkewCorrected;
- var isBrowserNetworkError = (error40) => {
- const errorMessages = new Set([
- "Failed to fetch",
- "NetworkError when attempting to fetch resource",
- "The Internet connection appears to be offline",
- "Load failed",
- "Network request failed"
- ]);
- const isValid = error40 && error40 instanceof TypeError;
- if (!isValid) {
- return false;
- }
- return errorMessages.has(error40.message);
- };
- var isThrottlingError = (error40) => error40.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error40.name) || error40.$retryable?.throttling == true;
- var isTransientError = (error40, depth = 0) => isRetryableByTrait(error40) || isClockSkewCorrectedError(error40) || TRANSIENT_ERROR_CODES.includes(error40.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error40?.code || "") || NODEJS_NETWORK_ERROR_CODES.includes(error40?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error40.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error40) || error40.cause !== undefined && depth <= 10 && isTransientError(error40.cause, depth + 1);
- var isServerError = (error40) => {
- if (error40.$metadata?.httpStatusCode !== undefined) {
- const statusCode = error40.$metadata.httpStatusCode;
- if (500 <= statusCode && statusCode <= 599 && !isTransientError(error40)) {
- return true;
- }
- return false;
- }
- return false;
- };
- exports.isBrowserNetworkError = isBrowserNetworkError;
- exports.isClockSkewCorrectedError = isClockSkewCorrectedError;
- exports.isClockSkewError = isClockSkewError;
- exports.isRetryableByTrait = isRetryableByTrait;
- exports.isServerError = isServerError;
- exports.isThrottlingError = isThrottlingError;
- exports.isTransientError = isTransientError;
-});
-
-// node_modules/@smithy/util-retry/dist-cjs/index.js
-var require_dist_cjs55 = __commonJS((exports) => {
- var serviceErrorClassification = require_dist_cjs54();
- exports.RETRY_MODES = undefined;
- (function(RETRY_MODES) {
- RETRY_MODES["STANDARD"] = "standard";
- RETRY_MODES["ADAPTIVE"] = "adaptive";
- })(exports.RETRY_MODES || (exports.RETRY_MODES = {}));
- var DEFAULT_MAX_ATTEMPTS = 3;
- var DEFAULT_RETRY_MODE = exports.RETRY_MODES.STANDARD;
-
- class DefaultRateLimiter {
- static setTimeoutFn = setTimeout;
- beta;
- minCapacity;
- minFillRate;
- scaleConstant;
- smooth;
- currentCapacity = 0;
- enabled = false;
- lastMaxRate = 0;
- measuredTxRate = 0;
- requestCount = 0;
- fillRate;
- lastThrottleTime;
- lastTimestamp = 0;
- lastTxRateBucket;
- maxCapacity;
- timeWindow = 0;
- constructor(options2) {
- this.beta = options2?.beta ?? 0.7;
- this.minCapacity = options2?.minCapacity ?? 1;
- this.minFillRate = options2?.minFillRate ?? 0.5;
- this.scaleConstant = options2?.scaleConstant ?? 0.4;
- this.smooth = options2?.smooth ?? 0.8;
- const currentTimeInSeconds = this.getCurrentTimeInSeconds();
- this.lastThrottleTime = currentTimeInSeconds;
- this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());
- this.fillRate = this.minFillRate;
- this.maxCapacity = this.minCapacity;
- }
- getCurrentTimeInSeconds() {
- return Date.now() / 1000;
- }
- async getSendToken() {
- return this.acquireTokenBucket(1);
- }
- async acquireTokenBucket(amount) {
- if (!this.enabled) {
- return;
- }
- this.refillTokenBucket();
- if (amount > this.currentCapacity) {
- const delay = (amount - this.currentCapacity) / this.fillRate * 1000;
- await new Promise((resolve9) => DefaultRateLimiter.setTimeoutFn(resolve9, delay));
- }
- this.currentCapacity = this.currentCapacity - amount;
- }
- refillTokenBucket() {
- const timestamp = this.getCurrentTimeInSeconds();
- if (!this.lastTimestamp) {
- this.lastTimestamp = timestamp;
- return;
- }
- const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate;
- this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount);
- this.lastTimestamp = timestamp;
- }
- updateClientSendingRate(response2) {
- let calculatedRate;
- this.updateMeasuredRate();
- if (serviceErrorClassification.isThrottlingError(response2)) {
- const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate);
- this.lastMaxRate = rateToUse;
- this.calculateTimeWindow();
- this.lastThrottleTime = this.getCurrentTimeInSeconds();
- calculatedRate = this.cubicThrottle(rateToUse);
- this.enableTokenBucket();
- } else {
- this.calculateTimeWindow();
- calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds());
- }
- const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate);
- this.updateTokenBucketRate(newRate);
- }
- calculateTimeWindow() {
- this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3));
- }
- cubicThrottle(rateToUse) {
- return this.getPrecise(rateToUse * this.beta);
- }
- cubicSuccess(timestamp) {
- return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate);
- }
- enableTokenBucket() {
- this.enabled = true;
- }
- updateTokenBucketRate(newRate) {
- this.refillTokenBucket();
- this.fillRate = Math.max(newRate, this.minFillRate);
- this.maxCapacity = Math.max(newRate, this.minCapacity);
- this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity);
- }
- updateMeasuredRate() {
- const t = this.getCurrentTimeInSeconds();
- const timeBucket = Math.floor(t * 2) / 2;
- this.requestCount++;
- if (timeBucket > this.lastTxRateBucket) {
- const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket);
- this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth));
- this.requestCount = 0;
- this.lastTxRateBucket = timeBucket;
- }
- }
- getPrecise(num) {
- return parseFloat(num.toFixed(8));
- }
- }
- var DEFAULT_RETRY_DELAY_BASE = 100;
- var MAXIMUM_RETRY_DELAY = 20 * 1000;
- var THROTTLING_RETRY_DELAY_BASE = 500;
- var INITIAL_RETRY_TOKENS = 500;
- var RETRY_COST = 5;
- var TIMEOUT_RETRY_COST = 10;
- var NO_RETRY_INCREMENT = 1;
- var INVOCATION_ID_HEADER = "amz-sdk-invocation-id";
- var REQUEST_HEADER = "amz-sdk-request";
- var getDefaultRetryBackoffStrategy = () => {
- let delayBase = DEFAULT_RETRY_DELAY_BASE;
- const computeNextBackoffDelay = (attempts) => {
- return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
- };
- const setDelayBase = (delay) => {
- delayBase = delay;
- };
- return {
- computeNextBackoffDelay,
- setDelayBase
- };
- };
- var createDefaultRetryToken = ({ retryDelay, retryCount, retryCost }) => {
- const getRetryCount = () => retryCount;
- const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay);
- const getRetryCost = () => retryCost;
- return {
- getRetryCount,
- getRetryDelay,
- getRetryCost
- };
- };
-
- class StandardRetryStrategy {
- maxAttempts;
- mode = exports.RETRY_MODES.STANDARD;
- capacity = INITIAL_RETRY_TOKENS;
- retryBackoffStrategy = getDefaultRetryBackoffStrategy();
- maxAttemptsProvider;
- constructor(maxAttempts) {
- this.maxAttempts = maxAttempts;
- this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts;
- }
- async acquireInitialRetryToken(retryTokenScope) {
- return createDefaultRetryToken({
- retryDelay: DEFAULT_RETRY_DELAY_BASE,
- retryCount: 0
- });
- }
- async refreshRetryTokenForRetry(token, errorInfo) {
- const maxAttempts = await this.getMaxAttempts();
- if (this.shouldRetry(token, errorInfo, maxAttempts)) {
- const errorType = errorInfo.errorType;
- this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE);
- const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());
- const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType;
- const capacityCost = this.getCapacityCost(errorType);
- this.capacity -= capacityCost;
- return createDefaultRetryToken({
- retryDelay,
- retryCount: token.getRetryCount() + 1,
- retryCost: capacityCost
- });
- }
- throw new Error("No retry token available");
- }
- recordSuccess(token) {
- this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT));
- }
- getCapacity() {
- return this.capacity;
- }
- async getMaxAttempts() {
- try {
- return await this.maxAttemptsProvider();
- } catch (error40) {
- console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);
- return DEFAULT_MAX_ATTEMPTS;
- }
- }
- shouldRetry(tokenToRenew, errorInfo, maxAttempts) {
- const attempts = tokenToRenew.getRetryCount() + 1;
- return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType);
- }
- getCapacityCost(errorType) {
- return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST;
- }
- isRetryableError(errorType) {
- return errorType === "THROTTLING" || errorType === "TRANSIENT";
- }
- }
-
- class AdaptiveRetryStrategy {
- maxAttemptsProvider;
- rateLimiter;
- standardRetryStrategy;
- mode = exports.RETRY_MODES.ADAPTIVE;
- constructor(maxAttemptsProvider, options2) {
- this.maxAttemptsProvider = maxAttemptsProvider;
- const { rateLimiter } = options2 ?? {};
- this.rateLimiter = rateLimiter ?? new DefaultRateLimiter;
- this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider);
- }
- async acquireInitialRetryToken(retryTokenScope) {
- await this.rateLimiter.getSendToken();
- return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);
- }
- async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
- this.rateLimiter.updateClientSendingRate(errorInfo);
- return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
- }
- recordSuccess(token) {
- this.rateLimiter.updateClientSendingRate({});
- this.standardRetryStrategy.recordSuccess(token);
- }
- }
-
- class ConfiguredRetryStrategy extends StandardRetryStrategy {
- computeNextBackoffDelay;
- constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) {
- super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts);
- if (typeof computeNextBackoffDelay === "number") {
- this.computeNextBackoffDelay = () => computeNextBackoffDelay;
- } else {
- this.computeNextBackoffDelay = computeNextBackoffDelay;
- }
- }
- async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
- const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
- token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount());
- return token;
- }
- }
- exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy;
- exports.ConfiguredRetryStrategy = ConfiguredRetryStrategy;
- exports.DEFAULT_MAX_ATTEMPTS = DEFAULT_MAX_ATTEMPTS;
- exports.DEFAULT_RETRY_DELAY_BASE = DEFAULT_RETRY_DELAY_BASE;
- exports.DEFAULT_RETRY_MODE = DEFAULT_RETRY_MODE;
- exports.DefaultRateLimiter = DefaultRateLimiter;
- exports.INITIAL_RETRY_TOKENS = INITIAL_RETRY_TOKENS;
- exports.INVOCATION_ID_HEADER = INVOCATION_ID_HEADER;
- exports.MAXIMUM_RETRY_DELAY = MAXIMUM_RETRY_DELAY;
- exports.NO_RETRY_INCREMENT = NO_RETRY_INCREMENT;
- exports.REQUEST_HEADER = REQUEST_HEADER;
- exports.RETRY_COST = RETRY_COST;
- exports.StandardRetryStrategy = StandardRetryStrategy;
- exports.THROTTLING_RETRY_DELAY_BASE = THROTTLING_RETRY_DELAY_BASE;
- exports.TIMEOUT_RETRY_COST = TIMEOUT_RETRY_COST;
-});
-
-// node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js
-var require_dist_cjs56 = __commonJS((exports) => {
- var core2 = require_dist_cjs37();
- var utilEndpoints = require_dist_cjs51();
- var protocolHttp = require_dist_cjs53();
- var client3 = require_client();
- var utilRetry = require_dist_cjs55();
- var DEFAULT_UA_APP_ID = undefined;
- function isValidUserAgentAppId(appId) {
- if (appId === undefined) {
- return true;
- }
- return typeof appId === "string" && appId.length <= 50;
- }
- function resolveUserAgentConfig(input) {
- const normalizedAppIdProvider = core2.normalizeProvider(input.userAgentAppId ?? DEFAULT_UA_APP_ID);
- const { customUserAgent } = input;
- return Object.assign(input, {
- customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent,
- userAgentAppId: async () => {
- const appId = await normalizedAppIdProvider();
- if (!isValidUserAgentAppId(appId)) {
- const logger2 = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger;
- if (typeof appId !== "string") {
- logger2?.warn("userAgentAppId must be a string or undefined.");
- } else if (appId.length > 50) {
- logger2?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.");
- }
- }
- return appId;
- }
- });
- }
- var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/;
- async function checkFeatures(context, config3, args) {
- const request2 = args.request;
- if (request2?.headers?.["smithy-protocol"] === "rpc-v2-cbor") {
- client3.setFeature(context, "PROTOCOL_RPC_V2_CBOR", "M");
- }
- if (typeof config3.retryStrategy === "function") {
- const retryStrategy = await config3.retryStrategy();
- if (typeof retryStrategy.mode === "string") {
- switch (retryStrategy.mode) {
- case utilRetry.RETRY_MODES.ADAPTIVE:
- client3.setFeature(context, "RETRY_MODE_ADAPTIVE", "F");
- break;
- case utilRetry.RETRY_MODES.STANDARD:
- client3.setFeature(context, "RETRY_MODE_STANDARD", "E");
- break;
- }
- }
- }
- if (typeof config3.accountIdEndpointMode === "function") {
- const endpointV2 = context.endpointV2;
- if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) {
- client3.setFeature(context, "ACCOUNT_ID_ENDPOINT", "O");
- }
- switch (await config3.accountIdEndpointMode?.()) {
- case "disabled":
- client3.setFeature(context, "ACCOUNT_ID_MODE_DISABLED", "Q");
- break;
- case "preferred":
- client3.setFeature(context, "ACCOUNT_ID_MODE_PREFERRED", "P");
- break;
- case "required":
- client3.setFeature(context, "ACCOUNT_ID_MODE_REQUIRED", "R");
- break;
- }
- }
- const identity6 = context.__smithy_context?.selectedHttpAuthScheme?.identity;
- if (identity6?.$source) {
- const credentials = identity6;
- if (credentials.accountId) {
- client3.setFeature(context, "RESOLVED_ACCOUNT_ID", "T");
- }
- for (const [key, value] of Object.entries(credentials.$source ?? {})) {
- client3.setFeature(context, key, value);
- }
- }
- }
- var USER_AGENT = "user-agent";
- var X_AMZ_USER_AGENT = "x-amz-user-agent";
- var SPACE = " ";
- var UA_NAME_SEPARATOR = "/";
- var UA_NAME_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w]/g;
- var UA_VALUE_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w#]/g;
- var UA_ESCAPE_CHAR = "-";
- var BYTE_LIMIT = 1024;
- function encodeFeatures(features) {
- let buffer = "";
- for (const key in features) {
- const val = features[key];
- if (buffer.length + val.length + 1 <= BYTE_LIMIT) {
- if (buffer.length) {
- buffer += "," + val;
- } else {
- buffer += val;
- }
- continue;
- }
- break;
- }
- return buffer;
- }
- var userAgentMiddleware = (options2) => (next, context) => async (args) => {
- const { request: request2 } = args;
- if (!protocolHttp.HttpRequest.isInstance(request2)) {
- return next(args);
- }
- const { headers } = request2;
- const userAgent = context?.userAgent?.map(escapeUserAgent) || [];
- const defaultUserAgent = (await options2.defaultUserAgentProvider()).map(escapeUserAgent);
- await checkFeatures(context, options2, args);
- const awsContext = context;
- defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`);
- const customUserAgent = options2?.customUserAgent?.map(escapeUserAgent) || [];
- const appId = await options2.userAgentAppId();
- if (appId) {
- defaultUserAgent.push(escapeUserAgent([`app`, `${appId}`]));
- }
- const prefix = utilEndpoints.getUserAgentPrefix();
- const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE);
- const normalUAValue = [
- ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")),
- ...customUserAgent
- ].join(SPACE);
- if (options2.runtime !== "browser") {
- if (normalUAValue) {
- headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue;
- }
- headers[USER_AGENT] = sdkUserAgentValue;
- } else {
- headers[X_AMZ_USER_AGENT] = sdkUserAgentValue;
- }
- return next({
- ...args,
- request: request2
- });
- };
- var escapeUserAgent = (userAgentPair) => {
- const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR);
- const version2 = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR);
- const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR);
- const prefix = name.substring(0, prefixSeparatorIndex);
- let uaName = name.substring(prefixSeparatorIndex + 1);
- if (prefix === "api") {
- uaName = uaName.toLowerCase();
- }
- return [prefix, uaName, version2].filter((item) => item && item.length > 0).reduce((acc, item, index2) => {
- switch (index2) {
- case 0:
- return item;
- case 1:
- return `${acc}/${item}`;
- default:
- return `${acc}#${item}`;
- }
- }, "");
- };
- var getUserAgentMiddlewareOptions = {
- name: "getUserAgentMiddleware",
- step: "build",
- priority: "low",
- tags: ["SET_USER_AGENT", "USER_AGENT"],
- override: true
- };
- var getUserAgentPlugin = (config3) => ({
- applyToStack: (clientStack) => {
- clientStack.add(userAgentMiddleware(config3), getUserAgentMiddlewareOptions);
- }
- });
- exports.DEFAULT_UA_APP_ID = DEFAULT_UA_APP_ID;
- exports.getUserAgentMiddlewareOptions = getUserAgentMiddlewareOptions;
- exports.getUserAgentPlugin = getUserAgentPlugin;
- exports.resolveUserAgentConfig = resolveUserAgentConfig;
- exports.userAgentMiddleware = userAgentMiddleware;
-});
-
-// node_modules/@smithy/util-config-provider/dist-cjs/index.js
-var require_dist_cjs57 = __commonJS((exports) => {
- var booleanSelector = (obj, key, type) => {
- if (!(key in obj))
- return;
- if (obj[key] === "true")
- return true;
- if (obj[key] === "false")
- return false;
- throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`);
- };
- var numberSelector = (obj, key, type) => {
- if (!(key in obj))
- return;
- const numberValue = parseInt(obj[key], 10);
- if (Number.isNaN(numberValue)) {
- throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`);
- }
- return numberValue;
- };
- exports.SelectorType = undefined;
- (function(SelectorType) {
- SelectorType["ENV"] = "env";
- SelectorType["CONFIG"] = "shared config entry";
- })(exports.SelectorType || (exports.SelectorType = {}));
- exports.booleanSelector = booleanSelector;
- exports.numberSelector = numberSelector;
-});
-
-// node_modules/@smithy/config-resolver/dist-cjs/index.js
-var require_dist_cjs58 = __commonJS((exports) => {
- var utilConfigProvider = require_dist_cjs57();
- var utilMiddleware = require_dist_cjs30();
- var utilEndpoints = require_dist_cjs50();
- var ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
- var CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
- var DEFAULT_USE_DUALSTACK_ENDPOINT = false;
- var NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = {
- environmentVariableSelector: (env4) => utilConfigProvider.booleanSelector(env4, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV),
- configFileSelector: (profile2) => utilConfigProvider.booleanSelector(profile2, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG),
- default: false
- };
- var nodeDualstackConfigSelectors = {
- environmentVariableSelector: (env4) => utilConfigProvider.booleanSelector(env4, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV),
- configFileSelector: (profile2) => utilConfigProvider.booleanSelector(profile2, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG),
- default: undefined
- };
- var ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
- var CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint";
- var DEFAULT_USE_FIPS_ENDPOINT = false;
- var NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = {
- environmentVariableSelector: (env4) => utilConfigProvider.booleanSelector(env4, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV),
- configFileSelector: (profile2) => utilConfigProvider.booleanSelector(profile2, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG),
- default: false
- };
- var nodeFipsConfigSelectors = {
- environmentVariableSelector: (env4) => utilConfigProvider.booleanSelector(env4, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV),
- configFileSelector: (profile2) => utilConfigProvider.booleanSelector(profile2, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG),
- default: undefined
- };
- var resolveCustomEndpointsConfig = (input) => {
- const { tls, endpoint: endpoint2, urlParser, useDualstackEndpoint } = input;
- return Object.assign(input, {
- tls: tls ?? true,
- endpoint: utilMiddleware.normalizeProvider(typeof endpoint2 === "string" ? urlParser(endpoint2) : endpoint2),
- isCustomEndpoint: true,
- useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false)
- });
- };
- var getEndpointFromRegion = async (input) => {
- const { tls = true } = input;
- const region = await input.region();
- const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/);
- if (!dnsHostRegex.test(region)) {
- throw new Error("Invalid region in client config");
- }
- const useDualstackEndpoint = await input.useDualstackEndpoint();
- const useFipsEndpoint = await input.useFipsEndpoint();
- const { hostname: hostname2 } = await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }) ?? {};
- if (!hostname2) {
- throw new Error("Cannot resolve hostname from client config");
- }
- return input.urlParser(`${tls ? "https:" : "http:"}//${hostname2}`);
- };
- var resolveEndpointsConfig = (input) => {
- const useDualstackEndpoint = utilMiddleware.normalizeProvider(input.useDualstackEndpoint ?? false);
- const { endpoint: endpoint2, useFipsEndpoint, urlParser, tls } = input;
- return Object.assign(input, {
- tls: tls ?? true,
- endpoint: endpoint2 ? utilMiddleware.normalizeProvider(typeof endpoint2 === "string" ? urlParser(endpoint2) : endpoint2) : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }),
- isCustomEndpoint: !!endpoint2,
- useDualstackEndpoint
- });
- };
- var REGION_ENV_NAME = "AWS_REGION";
- var REGION_INI_NAME = "region";
- var NODE_REGION_CONFIG_OPTIONS = {
- environmentVariableSelector: (env4) => env4[REGION_ENV_NAME],
- configFileSelector: (profile2) => profile2[REGION_INI_NAME],
- default: () => {
- throw new Error("Region is missing");
- }
- };
- var NODE_REGION_CONFIG_FILE_OPTIONS = {
- preferredFile: "credentials"
- };
- var validRegions = new Set;
- var checkRegion = (region, check3 = utilEndpoints.isValidHostLabel) => {
- if (!validRegions.has(region) && !check3(region)) {
- if (region === "*") {
- console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`);
- } else {
- throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`);
- }
- } else {
- validRegions.add(region);
- }
- };
- var isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips"));
- var getRealRegion = (region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region;
- var resolveRegionConfig = (input) => {
- const { region, useFipsEndpoint } = input;
- if (!region) {
- throw new Error("Region is missing");
- }
- return Object.assign(input, {
- region: async () => {
- const providedRegion = typeof region === "function" ? await region() : region;
- const realRegion = getRealRegion(providedRegion);
- checkRegion(realRegion);
- return realRegion;
- },
- useFipsEndpoint: async () => {
- const providedRegion = typeof region === "string" ? region : await region();
- if (isFipsRegion(providedRegion)) {
- return true;
- }
- return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
- }
- });
- };
- var getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname;
- var getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : undefined;
- var getResolvedPartition = (region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws";
- var getResolvedSigningRegion = (hostname2, { signingRegion, regionRegex, useFipsEndpoint }) => {
- if (signingRegion) {
- return signingRegion;
- } else if (useFipsEndpoint) {
- const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\.");
- const regionRegexmatchArray = hostname2.match(regionRegexJs);
- if (regionRegexmatchArray) {
- return regionRegexmatchArray[0].slice(1, -1);
- }
- }
- };
- var getRegionInfo = (region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash }) => {
- const partition2 = getResolvedPartition(region, { partitionHash });
- const resolvedRegion = region in regionHash ? region : partitionHash[partition2]?.endpoint ?? region;
- const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint };
- const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions);
- const partitionHostname = getHostnameFromVariants(partitionHash[partition2]?.variants, hostnameOptions);
- const hostname2 = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname });
- if (hostname2 === undefined) {
- throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`);
- }
- const signingRegion = getResolvedSigningRegion(hostname2, {
- signingRegion: regionHash[resolvedRegion]?.signingRegion,
- regionRegex: partitionHash[partition2].regionRegex,
- useFipsEndpoint
- });
- return {
- partition: partition2,
- signingService,
- hostname: hostname2,
- ...signingRegion && { signingRegion },
- ...regionHash[resolvedRegion]?.signingService && {
- signingService: regionHash[resolvedRegion].signingService
- }
- };
- };
- exports.CONFIG_USE_DUALSTACK_ENDPOINT = CONFIG_USE_DUALSTACK_ENDPOINT;
- exports.CONFIG_USE_FIPS_ENDPOINT = CONFIG_USE_FIPS_ENDPOINT;
- exports.DEFAULT_USE_DUALSTACK_ENDPOINT = DEFAULT_USE_DUALSTACK_ENDPOINT;
- exports.DEFAULT_USE_FIPS_ENDPOINT = DEFAULT_USE_FIPS_ENDPOINT;
- exports.ENV_USE_DUALSTACK_ENDPOINT = ENV_USE_DUALSTACK_ENDPOINT;
- exports.ENV_USE_FIPS_ENDPOINT = ENV_USE_FIPS_ENDPOINT;
- exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS;
- exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS;
- exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS;
- exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS;
- exports.REGION_ENV_NAME = REGION_ENV_NAME;
- exports.REGION_INI_NAME = REGION_INI_NAME;
- exports.getRegionInfo = getRegionInfo;
- exports.nodeDualstackConfigSelectors = nodeDualstackConfigSelectors;
- exports.nodeFipsConfigSelectors = nodeFipsConfigSelectors;
- exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig;
- exports.resolveEndpointsConfig = resolveEndpointsConfig;
- exports.resolveRegionConfig = resolveRegionConfig;
-});
-
-// node_modules/@smithy/middleware-content-length/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs59 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration2 = (runtimeConfig) => {
- return getChecksumConfiguration2(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return resolveChecksumRuntimeConfig2(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
-});
-
-// node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-cjs/index.js
-var require_dist_cjs60 = __commonJS((exports) => {
- var types3 = require_dist_cjs59();
- var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
- };
- var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
- };
-
- class Field2 {
- name;
- kind;
- values;
- constructor({ name, kind: kind2 = types3.FieldPosition.HEADER, values = [] }) {
- this.name = name;
- this.kind = kind2;
- this.values = values;
- }
- add(value) {
- this.values.push(value);
- }
- set(values) {
- this.values = values;
- }
- remove(value) {
- this.values = this.values.filter((v) => v !== value);
- }
- toString() {
- return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
- }
- get() {
- return this.values;
- }
- }
-
- class Fields2 {
- entries = {};
- encoding;
- constructor({ fields = [], encoding = "utf-8" }) {
- fields.forEach(this.setField.bind(this));
- this.encoding = encoding;
- }
- setField(field) {
- this.entries[field.name.toLowerCase()] = field;
- }
- getField(name) {
- return this.entries[name.toLowerCase()];
- }
- removeField(name) {
- delete this.entries[name.toLowerCase()];
- }
- getByType(kind2) {
- return Object.values(this.entries).filter((field) => field.kind === kind2);
- }
- }
-
- class HttpRequest2 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest2({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery2(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest2.clone(this);
- }
- }
- function cloneQuery2(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
- }
-
- class HttpResponse {
- statusCode;
- reason;
- headers;
- body;
- constructor(options2) {
- this.statusCode = options2.statusCode;
- this.reason = options2.reason;
- this.headers = options2.headers || {};
- this.body = options2.body;
- }
- static isInstance(response2) {
- if (!response2)
- return false;
- const resp = response2;
- return typeof resp.statusCode === "number" && typeof resp.headers === "object";
- }
- }
- function isValidHostname2(hostname2) {
- const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
- return hostPattern.test(hostname2);
- }
- exports.Field = Field2;
- exports.Fields = Fields2;
- exports.HttpRequest = HttpRequest2;
- exports.HttpResponse = HttpResponse;
- exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
- exports.isValidHostname = isValidHostname2;
- exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;
-});
-
-// node_modules/@smithy/middleware-content-length/dist-cjs/index.js
-var require_dist_cjs61 = __commonJS((exports) => {
- var protocolHttp = require_dist_cjs60();
- var CONTENT_LENGTH_HEADER = "content-length";
- function contentLengthMiddleware(bodyLengthChecker) {
- return (next) => async (args) => {
- const request2 = args.request;
- if (protocolHttp.HttpRequest.isInstance(request2)) {
- const { body, headers } = request2;
- if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) {
- try {
- const length = bodyLengthChecker(body);
- request2.headers = {
- ...request2.headers,
- [CONTENT_LENGTH_HEADER]: String(length)
- };
- } catch (error40) {}
- }
- }
- return next({
- ...args,
- request: request2
- });
- };
- }
- var contentLengthMiddlewareOptions = {
- step: "build",
- tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"],
- name: "contentLengthMiddleware",
- override: true
- };
- var getContentLengthPlugin = (options2) => ({
- applyToStack: (clientStack) => {
- clientStack.add(contentLengthMiddleware(options2.bodyLengthChecker), contentLengthMiddlewareOptions);
- }
- });
- exports.contentLengthMiddleware = contentLengthMiddleware;
- exports.contentLengthMiddlewareOptions = contentLengthMiddlewareOptions;
- exports.getContentLengthPlugin = getContentLengthPlugin;
-});
-
-// node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js
-var require_getEndpointUrlConfig = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getEndpointUrlConfig = undefined;
- var shared_ini_file_loader_1 = require_dist_cjs8();
- var ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL";
- var CONFIG_ENDPOINT_URL = "endpoint_url";
- var getEndpointUrlConfig = (serviceId) => ({
- environmentVariableSelector: (env4) => {
- const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase());
- const serviceEndpointUrl = env4[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")];
- if (serviceEndpointUrl)
- return serviceEndpointUrl;
- const endpointUrl = env4[ENV_ENDPOINT_URL];
- if (endpointUrl)
- return endpointUrl;
- return;
- },
- configFileSelector: (profile2, config3) => {
- if (config3 && profile2.services) {
- const servicesSection = config3[["services", profile2.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)];
- if (servicesSection) {
- const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase());
- const endpointUrl2 = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)];
- if (endpointUrl2)
- return endpointUrl2;
- }
- }
- const endpointUrl = profile2[CONFIG_ENDPOINT_URL];
- if (endpointUrl)
- return endpointUrl;
- return;
- },
- default: undefined
- });
- exports.getEndpointUrlConfig = getEndpointUrlConfig;
-});
-
-// node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js
-var require_getEndpointFromConfig = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getEndpointFromConfig = undefined;
- var node_config_provider_1 = require_dist_cjs9();
- var getEndpointUrlConfig_1 = require_getEndpointUrlConfig();
- var getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId ?? ""))();
- exports.getEndpointFromConfig = getEndpointFromConfig;
-});
-
-// node_modules/@smithy/middleware-serde/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs62 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration2 = (runtimeConfig) => {
- return getChecksumConfiguration2(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return resolveChecksumRuntimeConfig2(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
-});
-
-// node_modules/@smithy/middleware-serde/node_modules/@smithy/protocol-http/dist-cjs/index.js
-var require_dist_cjs63 = __commonJS((exports) => {
- var types3 = require_dist_cjs62();
- var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
- };
- var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
- };
-
- class Field2 {
- name;
- kind;
- values;
- constructor({ name, kind: kind2 = types3.FieldPosition.HEADER, values = [] }) {
- this.name = name;
- this.kind = kind2;
- this.values = values;
- }
- add(value) {
- this.values.push(value);
- }
- set(values) {
- this.values = values;
- }
- remove(value) {
- this.values = this.values.filter((v) => v !== value);
- }
- toString() {
- return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
- }
- get() {
- return this.values;
- }
- }
-
- class Fields2 {
- entries = {};
- encoding;
- constructor({ fields = [], encoding = "utf-8" }) {
- fields.forEach(this.setField.bind(this));
- this.encoding = encoding;
- }
- setField(field) {
- this.entries[field.name.toLowerCase()] = field;
- }
- getField(name) {
- return this.entries[name.toLowerCase()];
- }
- removeField(name) {
- delete this.entries[name.toLowerCase()];
- }
- getByType(kind2) {
- return Object.values(this.entries).filter((field) => field.kind === kind2);
- }
- }
-
- class HttpRequest2 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest2({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery2(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest2.clone(this);
- }
- }
- function cloneQuery2(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
- }
-
- class HttpResponse {
- statusCode;
- reason;
- headers;
- body;
- constructor(options2) {
- this.statusCode = options2.statusCode;
- this.reason = options2.reason;
- this.headers = options2.headers || {};
- this.body = options2.body;
- }
- static isInstance(response2) {
- if (!response2)
- return false;
- const resp = response2;
- return typeof resp.statusCode === "number" && typeof resp.headers === "object";
- }
- }
- function isValidHostname2(hostname2) {
- const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
- return hostPattern.test(hostname2);
- }
- exports.Field = Field2;
- exports.Fields = Fields2;
- exports.HttpRequest = HttpRequest2;
- exports.HttpResponse = HttpResponse;
- exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
- exports.isValidHostname = isValidHostname2;
- exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;
-});
-
-// node_modules/@smithy/middleware-serde/dist-cjs/index.js
-var require_dist_cjs64 = __commonJS((exports) => {
- var protocolHttp = require_dist_cjs63();
- var endpoints2 = require_endpoints();
- var deserializerMiddleware = (options2, deserializer) => (next, context) => async (args) => {
- const { response: response2 } = await next(args);
- try {
- const parsed = await deserializer(response2, options2);
- return {
- response: response2,
- output: parsed
- };
- } catch (error40) {
- Object.defineProperty(error40, "$response", {
- value: response2,
- enumerable: false,
- writable: false,
- configurable: false
- });
- if (!("$metadata" in error40)) {
- const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
- try {
- error40.message += `
- ` + hint;
- } catch (e) {
- if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") {
- console.warn(hint);
- } else {
- context.logger?.warn?.(hint);
- }
- }
- if (typeof error40.$responseBodyText !== "undefined") {
- if (error40.$response) {
- error40.$response.body = error40.$responseBodyText;
- }
- }
- try {
- if (protocolHttp.HttpResponse.isInstance(response2)) {
- const { headers = {} } = response2;
- const headerEntries = Object.entries(headers);
- error40.$metadata = {
- httpStatusCode: response2.statusCode,
- requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries),
- extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries),
- cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries)
- };
- }
- } catch (e) {}
- }
- throw error40;
- }
- };
- var findHeader = (pattern, headers) => {
- return (headers.find(([k]) => {
- return k.match(pattern);
- }) || [undefined, undefined])[1];
- };
- var serializerMiddleware = (options2, serializer) => (next, context) => async (args) => {
- const endpointConfig = options2;
- const endpoint2 = context.endpointV2 ? async () => endpoints2.toEndpointV1(context.endpointV2) : endpointConfig.endpoint;
- if (!endpoint2) {
- throw new Error("No valid endpoint provider available.");
- }
- const request2 = await serializer(args.input, { ...options2, endpoint: endpoint2 });
- return next({
- ...args,
- request: request2
- });
- };
- var deserializerMiddlewareOption = {
- name: "deserializerMiddleware",
- step: "deserialize",
- tags: ["DESERIALIZER"],
- override: true
- };
- var serializerMiddlewareOption = {
- name: "serializerMiddleware",
- step: "serialize",
- tags: ["SERIALIZER"],
- override: true
- };
- function getSerdePlugin(config3, serializer, deserializer) {
- return {
- applyToStack: (commandStack) => {
- commandStack.add(deserializerMiddleware(config3, deserializer), deserializerMiddlewareOption);
- commandStack.add(serializerMiddleware(config3, serializer), serializerMiddlewareOption);
- }
- };
- }
- exports.deserializerMiddleware = deserializerMiddleware;
- exports.deserializerMiddlewareOption = deserializerMiddlewareOption;
- exports.getSerdePlugin = getSerdePlugin;
- exports.serializerMiddleware = serializerMiddleware;
- exports.serializerMiddlewareOption = serializerMiddlewareOption;
-});
-
-// node_modules/@smithy/middleware-endpoint/dist-cjs/index.js
-var require_dist_cjs65 = __commonJS((exports) => {
- var getEndpointFromConfig = require_getEndpointFromConfig();
- var urlParser = require_dist_cjs11();
- var core2 = require_dist_cjs37();
- var utilMiddleware = require_dist_cjs30();
- var middlewareSerde = require_dist_cjs64();
- var resolveParamsForS3 = async (endpointParams) => {
- const bucket = endpointParams?.Bucket || "";
- if (typeof endpointParams.Bucket === "string") {
- endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?"));
- }
- if (isArnBucketName(bucket)) {
- if (endpointParams.ForcePathStyle === true) {
- throw new Error("Path-style addressing cannot be used with ARN buckets");
- }
- } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) {
- endpointParams.ForcePathStyle = true;
- }
- if (endpointParams.DisableMultiRegionAccessPoints) {
- endpointParams.disableMultiRegionAccessPoints = true;
- endpointParams.DisableMRAP = true;
- }
- return endpointParams;
- };
- var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;
- var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/;
- var DOTS_PATTERN = /\.\./;
- var isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName);
- var isArnBucketName = (bucketName) => {
- const [arn, partition2, service, , , bucket] = bucketName.split(":");
- const isArn = arn === "arn" && bucketName.split(":").length >= 6;
- const isValidArn = Boolean(isArn && partition2 && service && bucket);
- if (isArn && !isValidArn) {
- throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);
- }
- return isValidArn;
- };
- var createConfigValueProvider = (configKey, canonicalEndpointParamKey, config3, isClientContextParam = false) => {
- const configProvider = async () => {
- let configValue;
- if (isClientContextParam) {
- const clientContextParams = config3.clientContextParams;
- const nestedValue = clientContextParams?.[configKey];
- configValue = nestedValue ?? config3[configKey] ?? config3[canonicalEndpointParamKey];
- } else {
- configValue = config3[configKey] ?? config3[canonicalEndpointParamKey];
- }
- if (typeof configValue === "function") {
- return configValue();
- }
- return configValue;
- };
- if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") {
- return async () => {
- const credentials = typeof config3.credentials === "function" ? await config3.credentials() : config3.credentials;
- const configValue = credentials?.credentialScope ?? credentials?.CredentialScope;
- return configValue;
- };
- }
- if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") {
- return async () => {
- const credentials = typeof config3.credentials === "function" ? await config3.credentials() : config3.credentials;
- const configValue = credentials?.accountId ?? credentials?.AccountId;
- return configValue;
- };
- }
- if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") {
- return async () => {
- if (config3.isCustomEndpoint === false) {
- return;
- }
- const endpoint2 = await configProvider();
- if (endpoint2 && typeof endpoint2 === "object") {
- if ("url" in endpoint2) {
- return endpoint2.url.href;
- }
- if ("hostname" in endpoint2) {
- const { protocol, hostname: hostname2, port, path: path8 } = endpoint2;
- return `${protocol}//${hostname2}${port ? ":" + port : ""}${path8}`;
- }
- }
- return endpoint2;
- };
- }
- return configProvider;
- };
- var toEndpointV1 = (endpoint2) => {
- if (typeof endpoint2 === "object") {
- if ("url" in endpoint2) {
- const v1Endpoint = urlParser.parseUrl(endpoint2.url);
- if (endpoint2.headers) {
- v1Endpoint.headers = {};
- for (const [name, values] of Object.entries(endpoint2.headers)) {
- v1Endpoint.headers[name.toLowerCase()] = values.join(", ");
- }
- }
- return v1Endpoint;
- }
- return endpoint2;
- }
- return urlParser.parseUrl(endpoint2);
- };
- var getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => {
- if (!clientConfig.isCustomEndpoint) {
- let endpointFromConfig;
- if (clientConfig.serviceConfiguredEndpoint) {
- endpointFromConfig = await clientConfig.serviceConfiguredEndpoint();
- } else {
- endpointFromConfig = await getEndpointFromConfig.getEndpointFromConfig(clientConfig.serviceId);
- }
- if (endpointFromConfig) {
- clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig));
- clientConfig.isCustomEndpoint = true;
- }
- }
- const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig);
- if (typeof clientConfig.endpointProvider !== "function") {
- throw new Error("config.endpointProvider is not set.");
- }
- const endpoint2 = clientConfig.endpointProvider(endpointParams, context);
- if (clientConfig.isCustomEndpoint && clientConfig.endpoint) {
- const customEndpoint = await clientConfig.endpoint();
- if (customEndpoint?.headers) {
- endpoint2.headers ??= {};
- for (const [name, value] of Object.entries(customEndpoint.headers)) {
- endpoint2.headers[name] = Array.isArray(value) ? value : [value];
- }
- }
- }
- return endpoint2;
- };
- var resolveParams = async (commandInput, instructionsSupplier, clientConfig) => {
- const endpointParams = {};
- const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {};
- for (const [name, instruction] of Object.entries(instructions)) {
- switch (instruction.type) {
- case "staticContextParams":
- endpointParams[name] = instruction.value;
- break;
- case "contextParams":
- endpointParams[name] = commandInput[instruction.name];
- break;
- case "clientContextParams":
- case "builtInParams":
- endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig, instruction.type !== "builtInParams")();
- break;
- case "operationContextParams":
- endpointParams[name] = instruction.get(commandInput);
- break;
- default:
- throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction));
- }
- }
- if (Object.keys(instructions).length === 0) {
- Object.assign(endpointParams, clientConfig);
- }
- if (String(clientConfig.serviceId).toLowerCase() === "s3") {
- await resolveParamsForS3(endpointParams);
- }
- return endpointParams;
- };
- var endpointMiddleware = ({ config: config3, instructions }) => {
- return (next, context) => async (args) => {
- if (config3.isCustomEndpoint) {
- core2.setFeature(context, "ENDPOINT_OVERRIDE", "N");
- }
- const endpoint2 = await getEndpointFromInstructions(args.input, {
- getEndpointParameterInstructions() {
- return instructions;
- }
- }, { ...config3 }, context);
- context.endpointV2 = endpoint2;
- context.authSchemes = endpoint2.properties?.authSchemes;
- const authScheme = context.authSchemes?.[0];
- if (authScheme) {
- context["signing_region"] = authScheme.signingRegion;
- context["signing_service"] = authScheme.signingName;
- const smithyContext = utilMiddleware.getSmithyContext(context);
- const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption;
- if (httpAuthOption) {
- httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, {
- signing_region: authScheme.signingRegion,
- signingRegion: authScheme.signingRegion,
- signing_service: authScheme.signingName,
- signingName: authScheme.signingName,
- signingRegionSet: authScheme.signingRegionSet
- }, authScheme.properties);
- }
- }
- return next({
- ...args
- });
- };
- };
- var endpointMiddlewareOptions = {
- step: "serialize",
- tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"],
- name: "endpointV2Middleware",
- override: true,
- relation: "before",
- toMiddleware: middlewareSerde.serializerMiddlewareOption.name
- };
- var getEndpointPlugin = (config3, instructions) => ({
- applyToStack: (clientStack) => {
- clientStack.addRelativeTo(endpointMiddleware({
- config: config3,
- instructions
- }), endpointMiddlewareOptions);
- }
- });
- var resolveEndpointConfig = (input) => {
- const tls = input.tls ?? true;
- const { endpoint: endpoint2, useDualstackEndpoint, useFipsEndpoint } = input;
- const customEndpointProvider = endpoint2 != null ? async () => toEndpointV1(await utilMiddleware.normalizeProvider(endpoint2)()) : undefined;
- const isCustomEndpoint = !!endpoint2;
- const resolvedConfig = Object.assign(input, {
- endpoint: customEndpointProvider,
- tls,
- isCustomEndpoint,
- useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false),
- useFipsEndpoint: utilMiddleware.normalizeProvider(useFipsEndpoint ?? false)
- });
- let configuredEndpointPromise = undefined;
- resolvedConfig.serviceConfiguredEndpoint = async () => {
- if (input.serviceId && !configuredEndpointPromise) {
- configuredEndpointPromise = getEndpointFromConfig.getEndpointFromConfig(input.serviceId);
- }
- return configuredEndpointPromise;
- };
- return resolvedConfig;
- };
- var resolveEndpointRequiredConfig = (input) => {
- const { endpoint: endpoint2 } = input;
- if (endpoint2 === undefined) {
- input.endpoint = async () => {
- throw new Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.");
- };
- }
- return input;
- };
- exports.endpointMiddleware = endpointMiddleware;
- exports.endpointMiddlewareOptions = endpointMiddlewareOptions;
- exports.getEndpointFromInstructions = getEndpointFromInstructions;
- exports.getEndpointPlugin = getEndpointPlugin;
- exports.resolveEndpointConfig = resolveEndpointConfig;
- exports.resolveEndpointRequiredConfig = resolveEndpointRequiredConfig;
- exports.resolveParams = resolveParams;
- exports.toEndpointV1 = toEndpointV1;
-});
-
-// node_modules/@smithy/middleware-retry/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs66 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration2 = (runtimeConfig) => {
- return getChecksumConfiguration2(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return resolveChecksumRuntimeConfig2(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
-});
-
-// node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-cjs/index.js
-var require_dist_cjs67 = __commonJS((exports) => {
- var types3 = require_dist_cjs66();
- var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
- };
- var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
- };
-
- class Field2 {
- name;
- kind;
- values;
- constructor({ name, kind: kind2 = types3.FieldPosition.HEADER, values = [] }) {
- this.name = name;
- this.kind = kind2;
- this.values = values;
- }
- add(value) {
- this.values.push(value);
- }
- set(values) {
- this.values = values;
- }
- remove(value) {
- this.values = this.values.filter((v) => v !== value);
- }
- toString() {
- return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
- }
- get() {
- return this.values;
- }
- }
-
- class Fields2 {
- entries = {};
- encoding;
- constructor({ fields = [], encoding = "utf-8" }) {
- fields.forEach(this.setField.bind(this));
- this.encoding = encoding;
- }
- setField(field) {
- this.entries[field.name.toLowerCase()] = field;
- }
- getField(name) {
- return this.entries[name.toLowerCase()];
- }
- removeField(name) {
- delete this.entries[name.toLowerCase()];
- }
- getByType(kind2) {
- return Object.values(this.entries).filter((field) => field.kind === kind2);
- }
- }
-
- class HttpRequest2 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest2({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery2(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest2.clone(this);
- }
- }
- function cloneQuery2(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
- }
-
- class HttpResponse {
- statusCode;
- reason;
- headers;
- body;
- constructor(options2) {
- this.statusCode = options2.statusCode;
- this.reason = options2.reason;
- this.headers = options2.headers || {};
- this.body = options2.body;
- }
- static isInstance(response2) {
- if (!response2)
- return false;
- const resp = response2;
- return typeof resp.statusCode === "number" && typeof resp.headers === "object";
- }
- }
- function isValidHostname2(hostname2) {
- const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
- return hostPattern.test(hostname2);
- }
- exports.Field = Field2;
- exports.Fields = Fields2;
- exports.HttpRequest = HttpRequest2;
- exports.HttpResponse = HttpResponse;
- exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
- exports.isValidHostname = isValidHostname2;
- exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;
-});
-
-// node_modules/@smithy/middleware-retry/node_modules/@smithy/smithy-client/dist-cjs/index.js
-var require_dist_cjs68 = __commonJS((exports) => {
- var middlewareStack = require_dist_cjs12();
- var protocols = require_protocols();
- var types3 = require_dist_cjs66();
- var schema2 = require_schema();
- var serde3 = require_serde();
-
- class Client2 {
- config;
- middlewareStack = middlewareStack.constructStack();
- initConfig;
- handlers;
- constructor(config3) {
- this.config = config3;
- const { protocol, protocolSettings } = config3;
- if (protocolSettings) {
- if (typeof protocol === "function") {
- config3.protocol = new protocol(protocolSettings);
- }
- }
- }
- send(command3, optionsOrCb, cb) {
- const options2 = typeof optionsOrCb !== "function" ? optionsOrCb : undefined;
- const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
- const useHandlerCache = options2 === undefined && this.config.cacheMiddleware === true;
- let handler;
- if (useHandlerCache) {
- if (!this.handlers) {
- this.handlers = new WeakMap;
- }
- const handlers = this.handlers;
- if (handlers.has(command3.constructor)) {
- handler = handlers.get(command3.constructor);
- } else {
- handler = command3.resolveMiddleware(this.middlewareStack, this.config, options2);
- handlers.set(command3.constructor, handler);
- }
- } else {
- delete this.handlers;
- handler = command3.resolveMiddleware(this.middlewareStack, this.config, options2);
- }
- if (callback) {
- handler(command3).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => {});
- } else {
- return handler(command3).then((result) => result.output);
- }
- }
- destroy() {
- this.config?.requestHandler?.destroy?.();
- delete this.handlers;
- }
- }
- var SENSITIVE_STRING$1 = "***SensitiveInformation***";
- function schemaLogFilter2(schema$1, data) {
- if (data == null) {
- return data;
- }
- const ns = schema2.NormalizedSchema.of(schema$1);
- if (ns.getMergedTraits().sensitive) {
- return SENSITIVE_STRING$1;
- }
- if (ns.isListSchema()) {
- const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING$1;
- }
- } else if (ns.isMapSchema()) {
- const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING$1;
- }
- } else if (ns.isStructSchema() && typeof data === "object") {
- const object2 = data;
- const newObject = {};
- for (const [member, memberNs] of ns.structIterator()) {
- if (object2[member] != null) {
- newObject[member] = schemaLogFilter2(memberNs, object2[member]);
- }
- }
- return newObject;
- }
- return data;
- }
-
- class Command3 {
- middlewareStack = middlewareStack.constructStack();
- schema;
- static classBuilder() {
- return new ClassBuilder2;
- }
- resolveMiddlewareWithContext(clientStack, configuration, options2, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
- for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options2)) {
- this.middlewareStack.use(mw);
- }
- const stack = clientStack.concat(this.middlewareStack);
- const { logger: logger2 } = configuration;
- const handlerExecutionContext = {
- logger: logger2,
- clientName,
- commandName,
- inputFilterSensitiveLog,
- outputFilterSensitiveLog,
- [types3.SMITHY_CONTEXT_KEY]: {
- commandInstance: this,
- ...smithyContext
- },
- ...additionalContext
- };
- const { requestHandler } = configuration;
- return stack.resolve((request2) => requestHandler.handle(request2.request, options2 || {}), handlerExecutionContext);
- }
- }
-
- class ClassBuilder2 {
- _init = () => {};
- _ep = {};
- _middlewareFn = () => [];
- _commandName = "";
- _clientName = "";
- _additionalContext = {};
- _smithyContext = {};
- _inputFilterSensitiveLog = undefined;
- _outputFilterSensitiveLog = undefined;
- _serializer = null;
- _deserializer = null;
- _operationSchema;
- init(cb) {
- this._init = cb;
- }
- ep(endpointParameterInstructions) {
- this._ep = endpointParameterInstructions;
- return this;
- }
- m(middlewareSupplier) {
- this._middlewareFn = middlewareSupplier;
- return this;
- }
- s(service, operation, smithyContext = {}) {
- this._smithyContext = {
- service,
- operation,
- ...smithyContext
- };
- return this;
- }
- c(additionalContext = {}) {
- this._additionalContext = additionalContext;
- return this;
- }
- n(clientName, commandName) {
- this._clientName = clientName;
- this._commandName = commandName;
- return this;
- }
- f(inputFilter = (_) => _, outputFilter = (_) => _) {
- this._inputFilterSensitiveLog = inputFilter;
- this._outputFilterSensitiveLog = outputFilter;
- return this;
- }
- ser(serializer) {
- this._serializer = serializer;
- return this;
- }
- de(deserializer) {
- this._deserializer = deserializer;
- return this;
- }
- sc(operation) {
- this._operationSchema = operation;
- this._smithyContext.operationSchema = operation;
- return this;
- }
- build() {
- const closure = this;
- let CommandRef;
- return CommandRef = class extends Command3 {
- input;
- static getEndpointParameterInstructions() {
- return closure._ep;
- }
- constructor(...[input]) {
- super();
- this.input = input ?? {};
- closure._init(this);
- this.schema = closure._operationSchema;
- }
- resolveMiddleware(stack, configuration, options2) {
- const op = closure._operationSchema;
- const input = op?.[4] ?? op?.input;
- const output = op?.[5] ?? op?.output;
- return this.resolveMiddlewareWithContext(stack, configuration, options2, {
- CommandCtor: CommandRef,
- middlewareFn: closure._middlewareFn,
- clientName: closure._clientName,
- commandName: closure._commandName,
- inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter2.bind(null, input) : (_) => _),
- outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter2.bind(null, output) : (_) => _),
- smithyContext: closure._smithyContext,
- additionalContext: closure._additionalContext
- });
- }
- serialize = closure._serializer;
- deserialize = closure._deserializer;
- };
- }
- }
- var SENSITIVE_STRING3 = "***SensitiveInformation***";
- var createAggregatedClient2 = (commands, Client3, options2) => {
- for (const [command3, CommandCtor] of Object.entries(commands)) {
- const methodImpl = async function(args, optionsOrCb, cb) {
- const command4 = new CommandCtor(args);
- if (typeof optionsOrCb === "function") {
- this.send(command4, optionsOrCb);
- } else if (typeof cb === "function") {
- if (typeof optionsOrCb !== "object")
- throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
- this.send(command4, optionsOrCb || {}, cb);
- } else {
- return this.send(command4, optionsOrCb);
- }
- };
- const methodName = (command3[0].toLowerCase() + command3.slice(1)).replace(/Command$/, "");
- Client3.prototype[methodName] = methodImpl;
- }
- const { paginators = {}, waiters = {} } = options2 ?? {};
- for (const [paginatorName, paginatorFn] of Object.entries(paginators)) {
- if (Client3.prototype[paginatorName] === undefined) {
- Client3.prototype[paginatorName] = function(commandInput = {}, paginationConfiguration, ...rest) {
- return paginatorFn({
- ...paginationConfiguration,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
- for (const [waiterName, waiterFn] of Object.entries(waiters)) {
- if (Client3.prototype[waiterName] === undefined) {
- Client3.prototype[waiterName] = async function(commandInput = {}, waiterConfiguration, ...rest) {
- let config3 = waiterConfiguration;
- if (typeof waiterConfiguration === "number") {
- config3 = {
- maxWaitTime: waiterConfiguration
- };
- }
- return waiterFn({
- ...config3,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
- };
-
- class ServiceException2 extends Error {
- $fault;
- $response;
- $retryable;
- $metadata;
- constructor(options2) {
- super(options2.message);
- Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
- this.name = options2.name;
- this.$fault = options2.$fault;
- this.$metadata = options2.$metadata;
- }
- static isInstance(value) {
- if (!value)
- return false;
- const candidate = value;
- return ServiceException2.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
- }
- static [Symbol.hasInstance](instance) {
- if (!instance)
- return false;
- const candidate = instance;
- if (this === ServiceException2) {
- return ServiceException2.isInstance(instance);
- }
- if (ServiceException2.isInstance(instance)) {
- if (candidate.name && this.name) {
- return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
- }
- return this.prototype.isPrototypeOf(instance);
- }
- return false;
- }
- }
- var decorateServiceException2 = (exception, additions = {}) => {
- Object.entries(additions).filter(([, v]) => v !== undefined).forEach(([k, v]) => {
- if (exception[k] == undefined || exception[k] === "") {
- exception[k] = v;
- }
- });
- const message = exception.message || exception.Message || "UnknownError";
- exception.message = message;
- delete exception.Message;
- return exception;
- };
- var throwDefaultError2 = ({ output, parsedBody, exceptionCtor, errorCode }) => {
- const $metadata = deserializeMetadata2(output);
- const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined;
- const response2 = new exceptionCtor({
- name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
- $fault: "client",
- $metadata
- });
- throw decorateServiceException2(response2, parsedBody);
- };
- var withBaseException2 = (ExceptionCtor) => {
- return ({ output, parsedBody, errorCode }) => {
- throwDefaultError2({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
- };
- };
- var deserializeMetadata2 = (output) => ({
- httpStatusCode: output.statusCode,
- requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
- extendedRequestId: output.headers["x-amz-id-2"],
- cfId: output.headers["x-amz-cf-id"]
- });
- var loadConfigsForDefaultMode2 = (mode) => {
- switch (mode) {
- case "standard":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "in-region":
- return {
- retryMode: "standard",
- connectionTimeout: 1100
- };
- case "cross-region":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "mobile":
- return {
- retryMode: "standard",
- connectionTimeout: 30000
- };
- default:
- return {};
- }
- };
- var warningEmitted2 = false;
- var emitWarningIfUnsupportedVersion3 = (version2) => {
- if (version2 && !warningEmitted2 && parseInt(version2.substring(1, version2.indexOf("."))) < 16) {
- warningEmitted2 = true;
- }
- };
- var knownAlgorithms2 = Object.values(types3.AlgorithmId);
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- for (const id in types3.AlgorithmId) {
- const algorithmId = types3.AlgorithmId[id];
- if (runtimeConfig[algorithmId] === undefined) {
- continue;
- }
- checksumAlgorithms.push({
- algorithmId: () => algorithmId,
- checksumConstructor: () => runtimeConfig[algorithmId]
- });
- }
- for (const [id, ChecksumCtor] of Object.entries(runtimeConfig.checksumAlgorithms ?? {})) {
- checksumAlgorithms.push({
- algorithmId: () => id,
- checksumConstructor: () => ChecksumCtor
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- runtimeConfig.checksumAlgorithms = runtimeConfig.checksumAlgorithms ?? {};
- const id = algo.algorithmId();
- const ctor = algo.checksumConstructor();
- if (knownAlgorithms2.includes(id)) {
- runtimeConfig.checksumAlgorithms[id.toUpperCase()] = ctor;
- } else {
- runtimeConfig.checksumAlgorithms[id] = ctor;
- }
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- const id = checksumAlgorithm.algorithmId();
- if (knownAlgorithms2.includes(id)) {
- runtimeConfig[id] = checksumAlgorithm.checksumConstructor();
- }
- });
- return runtimeConfig;
- };
- var getRetryConfiguration2 = (runtimeConfig) => {
- return {
- setRetryStrategy(retryStrategy) {
- runtimeConfig.retryStrategy = retryStrategy;
- },
- retryStrategy() {
- return runtimeConfig.retryStrategy;
- }
- };
- };
- var resolveRetryRuntimeConfig2 = (retryStrategyConfiguration) => {
- const runtimeConfig = {};
- runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
- return runtimeConfig;
- };
- var getDefaultExtensionConfiguration2 = (runtimeConfig) => {
- return Object.assign(getChecksumConfiguration2(runtimeConfig), getRetryConfiguration2(runtimeConfig));
- };
- var getDefaultClientConfiguration2 = getDefaultExtensionConfiguration2;
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return Object.assign(resolveChecksumRuntimeConfig2(config3), resolveRetryRuntimeConfig2(config3));
- };
- var getArrayIfSingleItem2 = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray];
- var getValueFromTextNode2 = (obj) => {
- const textNodeName = "#text";
- for (const key in obj) {
- if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) {
- obj[key] = obj[key][textNodeName];
- } else if (typeof obj[key] === "object" && obj[key] !== null) {
- obj[key] = getValueFromTextNode2(obj[key]);
- }
- }
- return obj;
- };
- var isSerializableHeaderValue2 = (value) => {
- return value != null;
- };
-
- class NoOpLogger3 {
- trace() {}
- debug() {}
- info() {}
- warn() {}
- error() {}
- }
- function map3(arg0, arg1, arg2) {
- let target;
- let filter2;
- let instructions;
- if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
- target = {};
- instructions = arg0;
- } else {
- target = arg0;
- if (typeof arg1 === "function") {
- filter2 = arg1;
- instructions = arg2;
- return mapWithFilter2(target, filter2, instructions);
- } else {
- instructions = arg1;
- }
- }
- for (const key of Object.keys(instructions)) {
- if (!Array.isArray(instructions[key])) {
- target[key] = instructions[key];
- continue;
- }
- applyInstruction2(target, null, instructions, key);
- }
- return target;
- }
- var convertMap2 = (target) => {
- const output = {};
- for (const [k, v] of Object.entries(target || {})) {
- output[k] = [, v];
- }
- return output;
- };
- var take2 = (source, instructions) => {
- const out = {};
- for (const key in instructions) {
- applyInstruction2(out, source, instructions, key);
- }
- return out;
- };
- var mapWithFilter2 = (target, filter2, instructions) => {
- return map3(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
- if (Array.isArray(value)) {
- _instructions[key] = value;
- } else {
- if (typeof value === "function") {
- _instructions[key] = [filter2, value()];
- } else {
- _instructions[key] = [filter2, value];
- }
- }
- return _instructions;
- }, {}));
- };
- var applyInstruction2 = (target, source, instructions, targetKey) => {
- if (source !== null) {
- let instruction = instructions[targetKey];
- if (typeof instruction === "function") {
- instruction = [, instruction];
- }
- const [filter3 = nonNullish2, valueFn = pass2, sourceKey = targetKey] = instruction;
- if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) {
- target[targetKey] = valueFn(source[sourceKey]);
- }
- return;
- }
- let [filter2, value] = instructions[targetKey];
- if (typeof value === "function") {
- let _value;
- const defaultFilterPassed = filter2 === undefined && (_value = value()) != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(undefined) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed) {
- target[targetKey] = _value;
- } else if (customFilterPassed) {
- target[targetKey] = value();
- }
- } else {
- const defaultFilterPassed = filter2 === undefined && value != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed || customFilterPassed) {
- target[targetKey] = value;
- }
- }
- };
- var nonNullish2 = (_) => _ != null;
- var pass2 = (_) => _;
- var serializeFloat2 = (value) => {
- if (value !== value) {
- return "NaN";
- }
- switch (value) {
- case Infinity:
- return "Infinity";
- case -Infinity:
- return "-Infinity";
- default:
- return value;
- }
- };
- var serializeDateTime2 = (date5) => date5.toISOString().replace(".000Z", "Z");
- var _json2 = (obj) => {
- if (obj == null) {
- return {};
- }
- if (Array.isArray(obj)) {
- return obj.filter((_) => _ != null).map(_json2);
- }
- if (typeof obj === "object") {
- const target = {};
- for (const key of Object.keys(obj)) {
- if (obj[key] == null) {
- continue;
- }
- target[key] = _json2(obj[key]);
- }
- return target;
- }
- return obj;
- };
- exports.collectBody = protocols.collectBody;
- exports.extendedEncodeURIComponent = protocols.extendedEncodeURIComponent;
- exports.resolvedPath = protocols.resolvedPath;
- exports.Client = Client2;
- exports.Command = Command3;
- exports.NoOpLogger = NoOpLogger3;
- exports.SENSITIVE_STRING = SENSITIVE_STRING3;
- exports.ServiceException = ServiceException2;
- exports._json = _json2;
- exports.convertMap = convertMap2;
- exports.createAggregatedClient = createAggregatedClient2;
- exports.decorateServiceException = decorateServiceException2;
- exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion3;
- exports.getArrayIfSingleItem = getArrayIfSingleItem2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration2;
- exports.getValueFromTextNode = getValueFromTextNode2;
- exports.isSerializableHeaderValue = isSerializableHeaderValue2;
- exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode2;
- exports.map = map3;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
- exports.serializeDateTime = serializeDateTime2;
- exports.serializeFloat = serializeFloat2;
- exports.take = take2;
- exports.throwDefaultError = throwDefaultError2;
- exports.withBaseException = withBaseException2;
- Object.prototype.hasOwnProperty.call(serde3, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: serde3["__proto__"]
- });
- Object.keys(serde3).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = serde3[k];
- });
-});
-
-// node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js
-var require_isStreamingPayload = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isStreamingPayload = undefined;
- var stream_1 = __require("stream");
- var isStreamingPayload = (request2) => request2?.body instanceof stream_1.Readable || typeof ReadableStream !== "undefined" && request2?.body instanceof ReadableStream;
- exports.isStreamingPayload = isStreamingPayload;
-});
-
-// node_modules/@smithy/middleware-retry/dist-cjs/index.js
-var require_dist_cjs69 = __commonJS((exports) => {
- var utilRetry = require_dist_cjs55();
- var protocolHttp = require_dist_cjs67();
- var serviceErrorClassification = require_dist_cjs54();
- var uuid3 = require_dist_cjs31();
- var utilMiddleware = require_dist_cjs30();
- var smithyClient = require_dist_cjs68();
- var isStreamingPayload = require_isStreamingPayload();
- var getDefaultRetryQuota = (initialRetryTokens, options2) => {
- const MAX_CAPACITY = initialRetryTokens;
- const noRetryIncrement = utilRetry.NO_RETRY_INCREMENT;
- const retryCost = utilRetry.RETRY_COST;
- const timeoutRetryCost = utilRetry.TIMEOUT_RETRY_COST;
- let availableCapacity = initialRetryTokens;
- const getCapacityAmount = (error40) => error40.name === "TimeoutError" ? timeoutRetryCost : retryCost;
- const hasRetryTokens = (error40) => getCapacityAmount(error40) <= availableCapacity;
- const retrieveRetryTokens = (error40) => {
- if (!hasRetryTokens(error40)) {
- throw new Error("No retry token available");
- }
- const capacityAmount = getCapacityAmount(error40);
- availableCapacity -= capacityAmount;
- return capacityAmount;
- };
- const releaseRetryTokens = (capacityReleaseAmount) => {
- availableCapacity += capacityReleaseAmount ?? noRetryIncrement;
- availableCapacity = Math.min(availableCapacity, MAX_CAPACITY);
- };
- return Object.freeze({
- hasRetryTokens,
- retrieveRetryTokens,
- releaseRetryTokens
- });
- };
- var defaultDelayDecider = (delayBase, attempts) => Math.floor(Math.min(utilRetry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
- var defaultRetryDecider = (error40) => {
- if (!error40) {
- return false;
- }
- return serviceErrorClassification.isRetryableByTrait(error40) || serviceErrorClassification.isClockSkewError(error40) || serviceErrorClassification.isThrottlingError(error40) || serviceErrorClassification.isTransientError(error40);
- };
- var asSdkError = (error40) => {
- if (error40 instanceof Error)
- return error40;
- if (error40 instanceof Object)
- return Object.assign(new Error, error40);
- if (typeof error40 === "string")
- return new Error(error40);
- return new Error(`AWS SDK error wrapper for ${error40}`);
- };
-
- class StandardRetryStrategy {
- maxAttemptsProvider;
- retryDecider;
- delayDecider;
- retryQuota;
- mode = utilRetry.RETRY_MODES.STANDARD;
- constructor(maxAttemptsProvider, options2) {
- this.maxAttemptsProvider = maxAttemptsProvider;
- this.retryDecider = options2?.retryDecider ?? defaultRetryDecider;
- this.delayDecider = options2?.delayDecider ?? defaultDelayDecider;
- this.retryQuota = options2?.retryQuota ?? getDefaultRetryQuota(utilRetry.INITIAL_RETRY_TOKENS);
- }
- shouldRetry(error40, attempts, maxAttempts) {
- return attempts < maxAttempts && this.retryDecider(error40) && this.retryQuota.hasRetryTokens(error40);
- }
- async getMaxAttempts() {
- let maxAttempts;
- try {
- maxAttempts = await this.maxAttemptsProvider();
- } catch (error40) {
- maxAttempts = utilRetry.DEFAULT_MAX_ATTEMPTS;
- }
- return maxAttempts;
- }
- async retry(next, args, options2) {
- let retryTokenAmount;
- let attempts = 0;
- let totalDelay = 0;
- const maxAttempts = await this.getMaxAttempts();
- const { request: request2 } = args;
- if (protocolHttp.HttpRequest.isInstance(request2)) {
- request2.headers[utilRetry.INVOCATION_ID_HEADER] = uuid3.v4();
- }
- while (true) {
- try {
- if (protocolHttp.HttpRequest.isInstance(request2)) {
- request2.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
- }
- if (options2?.beforeRequest) {
- await options2.beforeRequest();
- }
- const { response: response2, output } = await next(args);
- if (options2?.afterRequest) {
- options2.afterRequest(response2);
- }
- this.retryQuota.releaseRetryTokens(retryTokenAmount);
- output.$metadata.attempts = attempts + 1;
- output.$metadata.totalRetryDelay = totalDelay;
- return { response: response2, output };
- } catch (e) {
- const err = asSdkError(e);
- attempts++;
- if (this.shouldRetry(err, attempts, maxAttempts)) {
- retryTokenAmount = this.retryQuota.retrieveRetryTokens(err);
- const delayFromDecider = this.delayDecider(serviceErrorClassification.isThrottlingError(err) ? utilRetry.THROTTLING_RETRY_DELAY_BASE : utilRetry.DEFAULT_RETRY_DELAY_BASE, attempts);
- const delayFromResponse = getDelayFromRetryAfterHeader(err.$response);
- const delay = Math.max(delayFromResponse || 0, delayFromDecider);
- totalDelay += delay;
- await new Promise((resolve9) => setTimeout(resolve9, delay));
- continue;
- }
- if (!err.$metadata) {
- err.$metadata = {};
- }
- err.$metadata.attempts = attempts;
- err.$metadata.totalRetryDelay = totalDelay;
- throw err;
- }
- }
- }
- }
- var getDelayFromRetryAfterHeader = (response2) => {
- if (!protocolHttp.HttpResponse.isInstance(response2))
- return;
- const retryAfterHeaderName = Object.keys(response2.headers).find((key) => key.toLowerCase() === "retry-after");
- if (!retryAfterHeaderName)
- return;
- const retryAfter = response2.headers[retryAfterHeaderName];
- const retryAfterSeconds = Number(retryAfter);
- if (!Number.isNaN(retryAfterSeconds))
- return retryAfterSeconds * 1000;
- const retryAfterDate = new Date(retryAfter);
- return retryAfterDate.getTime() - Date.now();
- };
-
- class AdaptiveRetryStrategy extends StandardRetryStrategy {
- rateLimiter;
- constructor(maxAttemptsProvider, options2) {
- const { rateLimiter, ...superOptions } = options2 ?? {};
- super(maxAttemptsProvider, superOptions);
- this.rateLimiter = rateLimiter ?? new utilRetry.DefaultRateLimiter;
- this.mode = utilRetry.RETRY_MODES.ADAPTIVE;
- }
- async retry(next, args) {
- return super.retry(next, args, {
- beforeRequest: async () => {
- return this.rateLimiter.getSendToken();
- },
- afterRequest: (response2) => {
- this.rateLimiter.updateClientSendingRate(response2);
- }
- });
- }
- }
- var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS";
- var CONFIG_MAX_ATTEMPTS = "max_attempts";
- var NODE_MAX_ATTEMPT_CONFIG_OPTIONS = {
- environmentVariableSelector: (env4) => {
- const value = env4[ENV_MAX_ATTEMPTS];
- if (!value)
- return;
- const maxAttempt = parseInt(value);
- if (Number.isNaN(maxAttempt)) {
- throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`);
- }
- return maxAttempt;
- },
- configFileSelector: (profile2) => {
- const value = profile2[CONFIG_MAX_ATTEMPTS];
- if (!value)
- return;
- const maxAttempt = parseInt(value);
- if (Number.isNaN(maxAttempt)) {
- throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`);
- }
- return maxAttempt;
- },
- default: utilRetry.DEFAULT_MAX_ATTEMPTS
- };
- var resolveRetryConfig = (input) => {
- const { retryStrategy, retryMode } = input;
- const maxAttempts = utilMiddleware.normalizeProvider(input.maxAttempts ?? utilRetry.DEFAULT_MAX_ATTEMPTS);
- let controller = retryStrategy ? Promise.resolve(retryStrategy) : undefined;
- const getDefault = async () => await utilMiddleware.normalizeProvider(retryMode)() === utilRetry.RETRY_MODES.ADAPTIVE ? new utilRetry.AdaptiveRetryStrategy(maxAttempts) : new utilRetry.StandardRetryStrategy(maxAttempts);
- return Object.assign(input, {
- maxAttempts,
- retryStrategy: () => controller ??= getDefault()
- });
- };
- var ENV_RETRY_MODE = "AWS_RETRY_MODE";
- var CONFIG_RETRY_MODE = "retry_mode";
- var NODE_RETRY_MODE_CONFIG_OPTIONS = {
- environmentVariableSelector: (env4) => env4[ENV_RETRY_MODE],
- configFileSelector: (profile2) => profile2[CONFIG_RETRY_MODE],
- default: utilRetry.DEFAULT_RETRY_MODE
- };
- var omitRetryHeadersMiddleware = () => (next) => async (args) => {
- const { request: request2 } = args;
- if (protocolHttp.HttpRequest.isInstance(request2)) {
- delete request2.headers[utilRetry.INVOCATION_ID_HEADER];
- delete request2.headers[utilRetry.REQUEST_HEADER];
- }
- return next(args);
- };
- var omitRetryHeadersMiddlewareOptions = {
- name: "omitRetryHeadersMiddleware",
- tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"],
- relation: "before",
- toMiddleware: "awsAuthMiddleware",
- override: true
- };
- var getOmitRetryHeadersPlugin = (options2) => ({
- applyToStack: (clientStack) => {
- clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions);
- }
- });
- var retryMiddleware = (options2) => (next, context) => async (args) => {
- let retryStrategy = await options2.retryStrategy();
- const maxAttempts = await options2.maxAttempts();
- if (isRetryStrategyV2(retryStrategy)) {
- retryStrategy = retryStrategy;
- let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]);
- let lastError = new Error;
- let attempts = 0;
- let totalRetryDelay = 0;
- const { request: request2 } = args;
- const isRequest2 = protocolHttp.HttpRequest.isInstance(request2);
- if (isRequest2) {
- request2.headers[utilRetry.INVOCATION_ID_HEADER] = uuid3.v4();
- }
- while (true) {
- try {
- if (isRequest2) {
- request2.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
- }
- const { response: response2, output } = await next(args);
- retryStrategy.recordSuccess(retryToken);
- output.$metadata.attempts = attempts + 1;
- output.$metadata.totalRetryDelay = totalRetryDelay;
- return { response: response2, output };
- } catch (e) {
- const retryErrorInfo = getRetryErrorInfo(e);
- lastError = asSdkError(e);
- if (isRequest2 && isStreamingPayload.isStreamingPayload(request2)) {
- (context.logger instanceof smithyClient.NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request.");
- throw lastError;
- }
- try {
- retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo);
- } catch (refreshError) {
- if (!lastError.$metadata) {
- lastError.$metadata = {};
- }
- lastError.$metadata.attempts = attempts + 1;
- lastError.$metadata.totalRetryDelay = totalRetryDelay;
- throw lastError;
- }
- attempts = retryToken.getRetryCount();
- const delay = retryToken.getRetryDelay();
- totalRetryDelay += delay;
- await new Promise((resolve9) => setTimeout(resolve9, delay));
- }
- }
- } else {
- retryStrategy = retryStrategy;
- if (retryStrategy?.mode)
- context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]];
- return retryStrategy.retry(next, args);
- }
- };
- var isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined";
- var getRetryErrorInfo = (error40) => {
- const errorInfo = {
- error: error40,
- errorType: getRetryErrorType(error40)
- };
- const retryAfterHint = getRetryAfterHint(error40.$response);
- if (retryAfterHint) {
- errorInfo.retryAfterHint = retryAfterHint;
- }
- return errorInfo;
- };
- var getRetryErrorType = (error40) => {
- if (serviceErrorClassification.isThrottlingError(error40))
- return "THROTTLING";
- if (serviceErrorClassification.isTransientError(error40))
- return "TRANSIENT";
- if (serviceErrorClassification.isServerError(error40))
- return "SERVER_ERROR";
- return "CLIENT_ERROR";
- };
- var retryMiddlewareOptions = {
- name: "retryMiddleware",
- tags: ["RETRY"],
- step: "finalizeRequest",
- priority: "high",
- override: true
- };
- var getRetryPlugin = (options2) => ({
- applyToStack: (clientStack) => {
- clientStack.add(retryMiddleware(options2), retryMiddlewareOptions);
- }
- });
- var getRetryAfterHint = (response2) => {
- if (!protocolHttp.HttpResponse.isInstance(response2))
- return;
- const retryAfterHeaderName = Object.keys(response2.headers).find((key) => key.toLowerCase() === "retry-after");
- if (!retryAfterHeaderName)
- return;
- const retryAfter = response2.headers[retryAfterHeaderName];
- const retryAfterSeconds = Number(retryAfter);
- if (!Number.isNaN(retryAfterSeconds))
- return new Date(retryAfterSeconds * 1000);
- const retryAfterDate = new Date(retryAfter);
- return retryAfterDate;
- };
- exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy;
- exports.CONFIG_MAX_ATTEMPTS = CONFIG_MAX_ATTEMPTS;
- exports.CONFIG_RETRY_MODE = CONFIG_RETRY_MODE;
- exports.ENV_MAX_ATTEMPTS = ENV_MAX_ATTEMPTS;
- exports.ENV_RETRY_MODE = ENV_RETRY_MODE;
- exports.NODE_MAX_ATTEMPT_CONFIG_OPTIONS = NODE_MAX_ATTEMPT_CONFIG_OPTIONS;
- exports.NODE_RETRY_MODE_CONFIG_OPTIONS = NODE_RETRY_MODE_CONFIG_OPTIONS;
- exports.StandardRetryStrategy = StandardRetryStrategy;
- exports.defaultDelayDecider = defaultDelayDecider;
- exports.defaultRetryDecider = defaultRetryDecider;
- exports.getOmitRetryHeadersPlugin = getOmitRetryHeadersPlugin;
- exports.getRetryAfterHint = getRetryAfterHint;
- exports.getRetryPlugin = getRetryPlugin;
- exports.omitRetryHeadersMiddleware = omitRetryHeadersMiddleware;
- exports.omitRetryHeadersMiddlewareOptions = omitRetryHeadersMiddlewareOptions;
- exports.resolveRetryConfig = resolveRetryConfig;
- exports.retryMiddleware = retryMiddleware;
- exports.retryMiddlewareOptions = retryMiddlewareOptions;
-});
-
-// node_modules/@aws-sdk/nested-clients/node_modules/@smithy/types/dist-cjs/index.js
-var require_dist_cjs70 = __commonJS((exports) => {
- exports.HttpAuthLocation = undefined;
- (function(HttpAuthLocation2) {
- HttpAuthLocation2["HEADER"] = "header";
- HttpAuthLocation2["QUERY"] = "query";
- })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
- exports.HttpApiKeyAuthLocation = undefined;
- (function(HttpApiKeyAuthLocation2) {
- HttpApiKeyAuthLocation2["HEADER"] = "header";
- HttpApiKeyAuthLocation2["QUERY"] = "query";
- })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
- exports.EndpointURLScheme = undefined;
- (function(EndpointURLScheme2) {
- EndpointURLScheme2["HTTP"] = "http";
- EndpointURLScheme2["HTTPS"] = "https";
- })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
- exports.AlgorithmId = undefined;
- (function(AlgorithmId2) {
- AlgorithmId2["MD5"] = "md5";
- AlgorithmId2["CRC32"] = "crc32";
- AlgorithmId2["CRC32C"] = "crc32c";
- AlgorithmId2["SHA1"] = "sha1";
- AlgorithmId2["SHA256"] = "sha256";
- })(exports.AlgorithmId || (exports.AlgorithmId = {}));
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- if (runtimeConfig.sha256 !== undefined) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.SHA256,
- checksumConstructor: () => runtimeConfig.sha256
- });
- }
- if (runtimeConfig.md5 != null) {
- checksumAlgorithms.push({
- algorithmId: () => exports.AlgorithmId.MD5,
- checksumConstructor: () => runtimeConfig.md5
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
- });
- return runtimeConfig;
- };
- var getDefaultClientConfiguration2 = (runtimeConfig) => {
- return getChecksumConfiguration2(runtimeConfig);
- };
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return resolveChecksumRuntimeConfig2(config3);
- };
- exports.FieldPosition = undefined;
- (function(FieldPosition2) {
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
- })(exports.FieldPosition || (exports.FieldPosition = {}));
- var SMITHY_CONTEXT_KEY2 = "__smithy_context";
- exports.IniSectionType = undefined;
- (function(IniSectionType2) {
- IniSectionType2["PROFILE"] = "profile";
- IniSectionType2["SSO_SESSION"] = "sso-session";
- IniSectionType2["SERVICES"] = "services";
- })(exports.IniSectionType || (exports.IniSectionType = {}));
- exports.RequestHandlerProtocol = undefined;
- (function(RequestHandlerProtocol2) {
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
- })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
- exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
-});
-
-// node_modules/@aws-sdk/nested-clients/node_modules/@smithy/smithy-client/dist-cjs/index.js
-var require_dist_cjs71 = __commonJS((exports) => {
- var middlewareStack = require_dist_cjs12();
- var protocols = require_protocols();
- var types3 = require_dist_cjs70();
- var schema2 = require_schema();
- var serde3 = require_serde();
-
- class Client2 {
- config;
- middlewareStack = middlewareStack.constructStack();
- initConfig;
- handlers;
- constructor(config3) {
- this.config = config3;
- const { protocol, protocolSettings } = config3;
- if (protocolSettings) {
- if (typeof protocol === "function") {
- config3.protocol = new protocol(protocolSettings);
- }
- }
- }
- send(command3, optionsOrCb, cb) {
- const options2 = typeof optionsOrCb !== "function" ? optionsOrCb : undefined;
- const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
- const useHandlerCache = options2 === undefined && this.config.cacheMiddleware === true;
- let handler;
- if (useHandlerCache) {
- if (!this.handlers) {
- this.handlers = new WeakMap;
- }
- const handlers = this.handlers;
- if (handlers.has(command3.constructor)) {
- handler = handlers.get(command3.constructor);
- } else {
- handler = command3.resolveMiddleware(this.middlewareStack, this.config, options2);
- handlers.set(command3.constructor, handler);
- }
- } else {
- delete this.handlers;
- handler = command3.resolveMiddleware(this.middlewareStack, this.config, options2);
- }
- if (callback) {
- handler(command3).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => {});
- } else {
- return handler(command3).then((result) => result.output);
- }
- }
- destroy() {
- this.config?.requestHandler?.destroy?.();
- delete this.handlers;
- }
- }
- var SENSITIVE_STRING$1 = "***SensitiveInformation***";
- function schemaLogFilter2(schema$1, data) {
- if (data == null) {
- return data;
- }
- const ns = schema2.NormalizedSchema.of(schema$1);
- if (ns.getMergedTraits().sensitive) {
- return SENSITIVE_STRING$1;
- }
- if (ns.isListSchema()) {
- const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING$1;
- }
- } else if (ns.isMapSchema()) {
- const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING$1;
- }
- } else if (ns.isStructSchema() && typeof data === "object") {
- const object2 = data;
- const newObject = {};
- for (const [member, memberNs] of ns.structIterator()) {
- if (object2[member] != null) {
- newObject[member] = schemaLogFilter2(memberNs, object2[member]);
- }
- }
- return newObject;
- }
- return data;
- }
-
- class Command3 {
- middlewareStack = middlewareStack.constructStack();
- schema;
- static classBuilder() {
- return new ClassBuilder2;
- }
- resolveMiddlewareWithContext(clientStack, configuration, options2, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
- for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options2)) {
- this.middlewareStack.use(mw);
- }
- const stack = clientStack.concat(this.middlewareStack);
- const { logger: logger2 } = configuration;
- const handlerExecutionContext = {
- logger: logger2,
- clientName,
- commandName,
- inputFilterSensitiveLog,
- outputFilterSensitiveLog,
- [types3.SMITHY_CONTEXT_KEY]: {
- commandInstance: this,
- ...smithyContext
- },
- ...additionalContext
- };
- const { requestHandler } = configuration;
- return stack.resolve((request2) => requestHandler.handle(request2.request, options2 || {}), handlerExecutionContext);
- }
- }
-
- class ClassBuilder2 {
- _init = () => {};
- _ep = {};
- _middlewareFn = () => [];
- _commandName = "";
- _clientName = "";
- _additionalContext = {};
- _smithyContext = {};
- _inputFilterSensitiveLog = undefined;
- _outputFilterSensitiveLog = undefined;
- _serializer = null;
- _deserializer = null;
- _operationSchema;
- init(cb) {
- this._init = cb;
- }
- ep(endpointParameterInstructions) {
- this._ep = endpointParameterInstructions;
- return this;
- }
- m(middlewareSupplier) {
- this._middlewareFn = middlewareSupplier;
- return this;
- }
- s(service, operation, smithyContext = {}) {
- this._smithyContext = {
- service,
- operation,
- ...smithyContext
- };
- return this;
- }
- c(additionalContext = {}) {
- this._additionalContext = additionalContext;
- return this;
- }
- n(clientName, commandName) {
- this._clientName = clientName;
- this._commandName = commandName;
- return this;
- }
- f(inputFilter = (_) => _, outputFilter = (_) => _) {
- this._inputFilterSensitiveLog = inputFilter;
- this._outputFilterSensitiveLog = outputFilter;
- return this;
- }
- ser(serializer) {
- this._serializer = serializer;
- return this;
- }
- de(deserializer) {
- this._deserializer = deserializer;
- return this;
- }
- sc(operation) {
- this._operationSchema = operation;
- this._smithyContext.operationSchema = operation;
- return this;
- }
- build() {
- const closure = this;
- let CommandRef;
- return CommandRef = class extends Command3 {
- input;
- static getEndpointParameterInstructions() {
- return closure._ep;
- }
- constructor(...[input]) {
- super();
- this.input = input ?? {};
- closure._init(this);
- this.schema = closure._operationSchema;
- }
- resolveMiddleware(stack, configuration, options2) {
- const op = closure._operationSchema;
- const input = op?.[4] ?? op?.input;
- const output = op?.[5] ?? op?.output;
- return this.resolveMiddlewareWithContext(stack, configuration, options2, {
- CommandCtor: CommandRef,
- middlewareFn: closure._middlewareFn,
- clientName: closure._clientName,
- commandName: closure._commandName,
- inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter2.bind(null, input) : (_) => _),
- outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter2.bind(null, output) : (_) => _),
- smithyContext: closure._smithyContext,
- additionalContext: closure._additionalContext
- });
- }
- serialize = closure._serializer;
- deserialize = closure._deserializer;
- };
- }
- }
- var SENSITIVE_STRING3 = "***SensitiveInformation***";
- var createAggregatedClient2 = (commands, Client3, options2) => {
- for (const [command3, CommandCtor] of Object.entries(commands)) {
- const methodImpl = async function(args, optionsOrCb, cb) {
- const command4 = new CommandCtor(args);
- if (typeof optionsOrCb === "function") {
- this.send(command4, optionsOrCb);
- } else if (typeof cb === "function") {
- if (typeof optionsOrCb !== "object")
- throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
- this.send(command4, optionsOrCb || {}, cb);
- } else {
- return this.send(command4, optionsOrCb);
- }
- };
- const methodName = (command3[0].toLowerCase() + command3.slice(1)).replace(/Command$/, "");
- Client3.prototype[methodName] = methodImpl;
- }
- const { paginators = {}, waiters = {} } = options2 ?? {};
- for (const [paginatorName, paginatorFn] of Object.entries(paginators)) {
- if (Client3.prototype[paginatorName] === undefined) {
- Client3.prototype[paginatorName] = function(commandInput = {}, paginationConfiguration, ...rest) {
- return paginatorFn({
- ...paginationConfiguration,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
- for (const [waiterName, waiterFn] of Object.entries(waiters)) {
- if (Client3.prototype[waiterName] === undefined) {
- Client3.prototype[waiterName] = async function(commandInput = {}, waiterConfiguration, ...rest) {
- let config3 = waiterConfiguration;
- if (typeof waiterConfiguration === "number") {
- config3 = {
- maxWaitTime: waiterConfiguration
- };
- }
- return waiterFn({
- ...config3,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
- };
-
- class ServiceException2 extends Error {
- $fault;
- $response;
- $retryable;
- $metadata;
- constructor(options2) {
- super(options2.message);
- Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
- this.name = options2.name;
- this.$fault = options2.$fault;
- this.$metadata = options2.$metadata;
- }
- static isInstance(value) {
- if (!value)
- return false;
- const candidate = value;
- return ServiceException2.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
- }
- static [Symbol.hasInstance](instance) {
- if (!instance)
- return false;
- const candidate = instance;
- if (this === ServiceException2) {
- return ServiceException2.isInstance(instance);
- }
- if (ServiceException2.isInstance(instance)) {
- if (candidate.name && this.name) {
- return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
- }
- return this.prototype.isPrototypeOf(instance);
- }
- return false;
- }
- }
- var decorateServiceException2 = (exception, additions = {}) => {
- Object.entries(additions).filter(([, v]) => v !== undefined).forEach(([k, v]) => {
- if (exception[k] == undefined || exception[k] === "") {
- exception[k] = v;
- }
- });
- const message = exception.message || exception.Message || "UnknownError";
- exception.message = message;
- delete exception.Message;
- return exception;
- };
- var throwDefaultError2 = ({ output, parsedBody, exceptionCtor, errorCode }) => {
- const $metadata = deserializeMetadata2(output);
- const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined;
- const response2 = new exceptionCtor({
- name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
- $fault: "client",
- $metadata
- });
- throw decorateServiceException2(response2, parsedBody);
- };
- var withBaseException2 = (ExceptionCtor) => {
- return ({ output, parsedBody, errorCode }) => {
- throwDefaultError2({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
- };
- };
- var deserializeMetadata2 = (output) => ({
- httpStatusCode: output.statusCode,
- requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
- extendedRequestId: output.headers["x-amz-id-2"],
- cfId: output.headers["x-amz-cf-id"]
- });
- var loadConfigsForDefaultMode2 = (mode) => {
- switch (mode) {
- case "standard":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "in-region":
- return {
- retryMode: "standard",
- connectionTimeout: 1100
- };
- case "cross-region":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "mobile":
- return {
- retryMode: "standard",
- connectionTimeout: 30000
- };
- default:
- return {};
- }
- };
- var warningEmitted2 = false;
- var emitWarningIfUnsupportedVersion3 = (version2) => {
- if (version2 && !warningEmitted2 && parseInt(version2.substring(1, version2.indexOf("."))) < 16) {
- warningEmitted2 = true;
- }
- };
- var knownAlgorithms2 = Object.values(types3.AlgorithmId);
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- for (const id in types3.AlgorithmId) {
- const algorithmId = types3.AlgorithmId[id];
- if (runtimeConfig[algorithmId] === undefined) {
- continue;
- }
- checksumAlgorithms.push({
- algorithmId: () => algorithmId,
- checksumConstructor: () => runtimeConfig[algorithmId]
- });
- }
- for (const [id, ChecksumCtor] of Object.entries(runtimeConfig.checksumAlgorithms ?? {})) {
- checksumAlgorithms.push({
- algorithmId: () => id,
- checksumConstructor: () => ChecksumCtor
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- runtimeConfig.checksumAlgorithms = runtimeConfig.checksumAlgorithms ?? {};
- const id = algo.algorithmId();
- const ctor = algo.checksumConstructor();
- if (knownAlgorithms2.includes(id)) {
- runtimeConfig.checksumAlgorithms[id.toUpperCase()] = ctor;
- } else {
- runtimeConfig.checksumAlgorithms[id] = ctor;
- }
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- const id = checksumAlgorithm.algorithmId();
- if (knownAlgorithms2.includes(id)) {
- runtimeConfig[id] = checksumAlgorithm.checksumConstructor();
- }
- });
- return runtimeConfig;
- };
- var getRetryConfiguration2 = (runtimeConfig) => {
- return {
- setRetryStrategy(retryStrategy) {
- runtimeConfig.retryStrategy = retryStrategy;
- },
- retryStrategy() {
- return runtimeConfig.retryStrategy;
- }
- };
- };
- var resolveRetryRuntimeConfig2 = (retryStrategyConfiguration) => {
- const runtimeConfig = {};
- runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
- return runtimeConfig;
- };
- var getDefaultExtensionConfiguration2 = (runtimeConfig) => {
- return Object.assign(getChecksumConfiguration2(runtimeConfig), getRetryConfiguration2(runtimeConfig));
- };
- var getDefaultClientConfiguration2 = getDefaultExtensionConfiguration2;
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return Object.assign(resolveChecksumRuntimeConfig2(config3), resolveRetryRuntimeConfig2(config3));
- };
- var getArrayIfSingleItem2 = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray];
- var getValueFromTextNode2 = (obj) => {
- const textNodeName = "#text";
- for (const key in obj) {
- if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) {
- obj[key] = obj[key][textNodeName];
- } else if (typeof obj[key] === "object" && obj[key] !== null) {
- obj[key] = getValueFromTextNode2(obj[key]);
- }
- }
- return obj;
- };
- var isSerializableHeaderValue2 = (value) => {
- return value != null;
- };
-
- class NoOpLogger3 {
- trace() {}
- debug() {}
- info() {}
- warn() {}
- error() {}
- }
- function map3(arg0, arg1, arg2) {
- let target;
- let filter2;
- let instructions;
- if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
- target = {};
- instructions = arg0;
- } else {
- target = arg0;
- if (typeof arg1 === "function") {
- filter2 = arg1;
- instructions = arg2;
- return mapWithFilter2(target, filter2, instructions);
- } else {
- instructions = arg1;
- }
- }
- for (const key of Object.keys(instructions)) {
- if (!Array.isArray(instructions[key])) {
- target[key] = instructions[key];
- continue;
- }
- applyInstruction2(target, null, instructions, key);
- }
- return target;
- }
- var convertMap2 = (target) => {
- const output = {};
- for (const [k, v] of Object.entries(target || {})) {
- output[k] = [, v];
- }
- return output;
- };
- var take2 = (source, instructions) => {
- const out = {};
- for (const key in instructions) {
- applyInstruction2(out, source, instructions, key);
- }
- return out;
- };
- var mapWithFilter2 = (target, filter2, instructions) => {
- return map3(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
- if (Array.isArray(value)) {
- _instructions[key] = value;
- } else {
- if (typeof value === "function") {
- _instructions[key] = [filter2, value()];
- } else {
- _instructions[key] = [filter2, value];
- }
- }
- return _instructions;
- }, {}));
- };
- var applyInstruction2 = (target, source, instructions, targetKey) => {
- if (source !== null) {
- let instruction = instructions[targetKey];
- if (typeof instruction === "function") {
- instruction = [, instruction];
- }
- const [filter3 = nonNullish2, valueFn = pass2, sourceKey = targetKey] = instruction;
- if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) {
- target[targetKey] = valueFn(source[sourceKey]);
- }
- return;
- }
- let [filter2, value] = instructions[targetKey];
- if (typeof value === "function") {
- let _value;
- const defaultFilterPassed = filter2 === undefined && (_value = value()) != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(undefined) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed) {
- target[targetKey] = _value;
- } else if (customFilterPassed) {
- target[targetKey] = value();
- }
- } else {
- const defaultFilterPassed = filter2 === undefined && value != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed || customFilterPassed) {
- target[targetKey] = value;
- }
- }
- };
- var nonNullish2 = (_) => _ != null;
- var pass2 = (_) => _;
- var serializeFloat2 = (value) => {
- if (value !== value) {
- return "NaN";
- }
- switch (value) {
- case Infinity:
- return "Infinity";
- case -Infinity:
- return "-Infinity";
- default:
- return value;
- }
- };
- var serializeDateTime2 = (date5) => date5.toISOString().replace(".000Z", "Z");
- var _json2 = (obj) => {
- if (obj == null) {
- return {};
- }
- if (Array.isArray(obj)) {
- return obj.filter((_) => _ != null).map(_json2);
- }
- if (typeof obj === "object") {
- const target = {};
- for (const key of Object.keys(obj)) {
- if (obj[key] == null) {
- continue;
- }
- target[key] = _json2(obj[key]);
- }
- return target;
- }
- return obj;
- };
- exports.collectBody = protocols.collectBody;
- exports.extendedEncodeURIComponent = protocols.extendedEncodeURIComponent;
- exports.resolvedPath = protocols.resolvedPath;
- exports.Client = Client2;
- exports.Command = Command3;
- exports.NoOpLogger = NoOpLogger3;
- exports.SENSITIVE_STRING = SENSITIVE_STRING3;
- exports.ServiceException = ServiceException2;
- exports._json = _json2;
- exports.convertMap = convertMap2;
- exports.createAggregatedClient = createAggregatedClient2;
- exports.decorateServiceException = decorateServiceException2;
- exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion3;
- exports.getArrayIfSingleItem = getArrayIfSingleItem2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration2;
- exports.getValueFromTextNode = getValueFromTextNode2;
- exports.isSerializableHeaderValue = isSerializableHeaderValue2;
- exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode2;
- exports.map = map3;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
- exports.serializeDateTime = serializeDateTime2;
- exports.serializeFloat = serializeFloat2;
- exports.take = take2;
- exports.throwDefaultError = throwDefaultError2;
- exports.withBaseException = withBaseException2;
- Object.prototype.hasOwnProperty.call(serde3, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: serde3["__proto__"]
- });
- Object.keys(serde3).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = serde3[k];
- });
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/auth/httpAuthSchemeProvider.js
-var require_httpAuthSchemeProvider = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = undefined;
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var util_middleware_1 = require_dist_cjs30();
- var defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config3, context, input) => {
- return {
- operation: (0, util_middleware_1.getSmithyContext)(context).operation,
- region: await (0, util_middleware_1.normalizeProvider)(config3.region)() || (() => {
- throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
- })()
- };
- };
- exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider;
- function createAwsAuthSigv4HttpAuthOption(authParameters) {
- return {
- schemeId: "aws.auth#sigv4",
- signingProperties: {
- name: "sso-oauth",
- region: authParameters.region
- },
- propertiesExtractor: (config3, context) => ({
- signingProperties: {
- config: config3,
- context
- }
- })
- };
- }
- function createSmithyApiNoAuthHttpAuthOption(authParameters) {
- return {
- schemeId: "smithy.api#noAuth"
- };
- }
- var defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {
- const options2 = [];
- switch (authParameters.operation) {
- case "CreateToken": {
- options2.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
- break;
- }
- default: {
- options2.push(createAwsAuthSigv4HttpAuthOption(authParameters));
- }
- }
- return options2;
- };
- exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider;
- var resolveHttpAuthSchemeConfig = (config3) => {
- const config_0 = (0, httpAuthSchemes_1.resolveAwsSdkSigV4Config)(config3);
- return Object.assign(config_0, {
- authSchemePreference: (0, util_middleware_1.normalizeProvider)(config3.authSchemePreference ?? [])
- });
- };
- exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/package.json
-var require_package = __commonJS((exports, module) => {
- module.exports = {
- name: "@aws-sdk/nested-clients",
- version: "3.996.17",
- description: "Nested clients for AWS SDK packages.",
- main: "./dist-cjs/index.js",
- module: "./dist-es/index.js",
- types: "./dist-types/index.d.ts",
- scripts: {
- build: "yarn lint && concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs",
- "build:cjs": "node ../../scripts/compilation/inline nested-clients",
- "build:es": "tsc -p tsconfig.es.json",
- "build:include:deps": 'yarn g:turbo run build -F="$npm_package_name"',
- "build:types": "tsc -p tsconfig.types.json",
- "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
- clean: "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",
- lint: "node ../../scripts/validation/submodules-linter.js --pkg nested-clients",
- test: "yarn g:vitest run",
- "test:watch": "yarn g:vitest watch"
- },
- engines: {
- node: ">=20.0.0"
- },
- sideEffects: false,
- author: {
- name: "AWS SDK for JavaScript Team",
- url: "https://aws.amazon.com/javascript/"
- },
- license: "Apache-2.0",
- dependencies: {
- "@aws-crypto/sha256-browser": "5.2.0",
- "@aws-crypto/sha256-js": "5.2.0",
- "@aws-sdk/core": "^3.973.26",
- "@aws-sdk/middleware-host-header": "^3.972.8",
- "@aws-sdk/middleware-logger": "^3.972.8",
- "@aws-sdk/middleware-recursion-detection": "^3.972.9",
- "@aws-sdk/middleware-user-agent": "^3.972.27",
- "@aws-sdk/region-config-resolver": "^3.972.10",
- "@aws-sdk/types": "^3.973.6",
- "@aws-sdk/util-endpoints": "^3.996.5",
- "@aws-sdk/util-user-agent-browser": "^3.972.8",
- "@aws-sdk/util-user-agent-node": "^3.973.13",
- "@smithy/config-resolver": "^4.4.13",
- "@smithy/core": "^3.23.13",
- "@smithy/fetch-http-handler": "^5.3.15",
- "@smithy/hash-node": "^4.2.12",
- "@smithy/invalid-dependency": "^4.2.12",
- "@smithy/middleware-content-length": "^4.2.12",
- "@smithy/middleware-endpoint": "^4.4.28",
- "@smithy/middleware-retry": "^4.4.45",
- "@smithy/middleware-serde": "^4.2.16",
- "@smithy/middleware-stack": "^4.2.12",
- "@smithy/node-config-provider": "^4.3.12",
- "@smithy/node-http-handler": "^4.5.1",
- "@smithy/protocol-http": "^5.3.12",
- "@smithy/smithy-client": "^4.12.8",
- "@smithy/types": "^4.13.1",
- "@smithy/url-parser": "^4.2.12",
- "@smithy/util-base64": "^4.3.2",
- "@smithy/util-body-length-browser": "^4.2.2",
- "@smithy/util-body-length-node": "^4.2.3",
- "@smithy/util-defaults-mode-browser": "^4.3.44",
- "@smithy/util-defaults-mode-node": "^4.2.48",
- "@smithy/util-endpoints": "^3.3.3",
- "@smithy/util-middleware": "^4.2.12",
- "@smithy/util-retry": "^4.2.12",
- "@smithy/util-utf8": "^4.2.2",
- tslib: "^2.6.2"
- },
- devDependencies: {
- concurrently: "7.0.0",
- "downlevel-dts": "0.10.1",
- premove: "4.0.0",
- typescript: "~5.8.3"
- },
- typesVersions: {
- "<4.5": {
- "dist-types/*": [
- "dist-types/ts3.4/*"
- ]
- }
- },
- files: [
- "./cognito-identity.d.ts",
- "./cognito-identity.js",
- "./signin.d.ts",
- "./signin.js",
- "./sso-oidc.d.ts",
- "./sso-oidc.js",
- "./sso.d.ts",
- "./sso.js",
- "./sts.d.ts",
- "./sts.js",
- "dist-*/**"
- ],
- browser: {
- "./dist-es/submodules/cognito-identity/runtimeConfig": "./dist-es/submodules/cognito-identity/runtimeConfig.browser",
- "./dist-es/submodules/signin/runtimeConfig": "./dist-es/submodules/signin/runtimeConfig.browser",
- "./dist-es/submodules/sso-oidc/runtimeConfig": "./dist-es/submodules/sso-oidc/runtimeConfig.browser",
- "./dist-es/submodules/sso/runtimeConfig": "./dist-es/submodules/sso/runtimeConfig.browser",
- "./dist-es/submodules/sts/runtimeConfig": "./dist-es/submodules/sts/runtimeConfig.browser"
- },
- "react-native": {},
- homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients",
- repository: {
- type: "git",
- url: "https://github.com/aws/aws-sdk-js-v3.git",
- directory: "packages/nested-clients"
- },
- exports: {
- "./package.json": "./package.json",
- "./sso-oidc": {
- types: "./dist-types/submodules/sso-oidc/index.d.ts",
- module: "./dist-es/submodules/sso-oidc/index.js",
- node: "./dist-cjs/submodules/sso-oidc/index.js",
- import: "./dist-es/submodules/sso-oidc/index.js",
- require: "./dist-cjs/submodules/sso-oidc/index.js"
- },
- "./sts": {
- types: "./dist-types/submodules/sts/index.d.ts",
- module: "./dist-es/submodules/sts/index.js",
- node: "./dist-cjs/submodules/sts/index.js",
- import: "./dist-es/submodules/sts/index.js",
- require: "./dist-cjs/submodules/sts/index.js"
- },
- "./signin": {
- types: "./dist-types/submodules/signin/index.d.ts",
- module: "./dist-es/submodules/signin/index.js",
- node: "./dist-cjs/submodules/signin/index.js",
- import: "./dist-es/submodules/signin/index.js",
- require: "./dist-cjs/submodules/signin/index.js"
- },
- "./cognito-identity": {
- types: "./dist-types/submodules/cognito-identity/index.d.ts",
- module: "./dist-es/submodules/cognito-identity/index.js",
- node: "./dist-cjs/submodules/cognito-identity/index.js",
- import: "./dist-es/submodules/cognito-identity/index.js",
- require: "./dist-cjs/submodules/cognito-identity/index.js"
- },
- "./sso": {
- types: "./dist-types/submodules/sso/index.d.ts",
- module: "./dist-es/submodules/sso/index.js",
- node: "./dist-cjs/submodules/sso/index.js",
- import: "./dist-es/submodules/sso/index.js",
- require: "./dist-cjs/submodules/sso/index.js"
- }
- }
- };
-});
-
-// node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js
-var require_dist_cjs72 = __commonJS((exports) => {
- var __dirname = "/home/roger/.openclaw/workspace/claude-code/node_modules/@aws-sdk/util-user-agent-node/dist-cjs";
- var node_os = __require("os");
- var node_process = __require("process");
- var utilConfigProvider = require_dist_cjs57();
- var promises = __require("fs/promises");
- var node_path = __require("path");
- var middlewareUserAgent = require_dist_cjs56();
- var getRuntimeUserAgentPair = () => {
- const runtimesToCheck = ["deno", "bun", "llrt"];
- for (const runtime of runtimesToCheck) {
- if (node_process.versions[runtime]) {
- return [`md/${runtime}`, node_process.versions[runtime]];
- }
- }
- return ["md/nodejs", node_process.versions.node];
- };
- var getNodeModulesParentDirs = (dirname12) => {
- const cwd2 = process.cwd();
- if (!dirname12) {
- return [cwd2];
- }
- const normalizedPath = node_path.normalize(dirname12);
- const parts = normalizedPath.split(node_path.sep);
- const nodeModulesIndex = parts.indexOf("node_modules");
- const parentDir = nodeModulesIndex !== -1 ? parts.slice(0, nodeModulesIndex).join(node_path.sep) : normalizedPath;
- if (cwd2 === parentDir) {
- return [cwd2];
- }
- return [parentDir, cwd2];
- };
- var SEMVER_REGEX = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;
- var getSanitizedTypeScriptVersion = (version2 = "") => {
- const match = version2.match(SEMVER_REGEX);
- if (!match) {
- return;
- }
- const [major, minor, patch, prerelease] = [match[1], match[2], match[3], match[4]];
- return prerelease ? `${major}.${minor}.${patch}-${prerelease}` : `${major}.${minor}.${patch}`;
- };
- var ALLOWED_PREFIXES = ["^", "~", ">=", "<=", ">", "<"];
- var ALLOWED_DIST_TAGS = ["latest", "beta", "dev", "rc", "insiders", "next"];
- var getSanitizedDevTypeScriptVersion = (version2 = "") => {
- if (ALLOWED_DIST_TAGS.includes(version2)) {
- return version2;
- }
- const prefix = ALLOWED_PREFIXES.find((p) => version2.startsWith(p)) ?? "";
- const sanitizedTypeScriptVersion = getSanitizedTypeScriptVersion(version2.slice(prefix.length));
- if (!sanitizedTypeScriptVersion) {
- return;
- }
- return `${prefix}${sanitizedTypeScriptVersion}`;
- };
- var tscVersion;
- var TS_PACKAGE_JSON = node_path.join("node_modules", "typescript", "package.json");
- var getTypeScriptUserAgentPair = async () => {
- if (tscVersion === null) {
- return;
- } else if (typeof tscVersion === "string") {
- return ["md/tsc", tscVersion];
- }
- let isTypeScriptDetectionDisabled = false;
- try {
- isTypeScriptDetectionDisabled = utilConfigProvider.booleanSelector(process.env, "AWS_SDK_JS_TYPESCRIPT_DETECTION_DISABLED", utilConfigProvider.SelectorType.ENV) || false;
- } catch {}
- if (isTypeScriptDetectionDisabled) {
- tscVersion = null;
- return;
- }
- const dirname12 = typeof __dirname !== "undefined" ? __dirname : undefined;
- const nodeModulesParentDirs = getNodeModulesParentDirs(dirname12);
- let versionFromApp;
- for (const nodeModulesParentDir of nodeModulesParentDirs) {
- try {
- const appPackageJsonPath = node_path.join(nodeModulesParentDir, "package.json");
- const packageJson = await promises.readFile(appPackageJsonPath, "utf-8");
- const { dependencies, devDependencies } = JSON.parse(packageJson);
- const version2 = devDependencies?.typescript ?? dependencies?.typescript;
- if (typeof version2 !== "string") {
- continue;
- }
- versionFromApp = version2;
- break;
- } catch {}
- }
- if (!versionFromApp) {
- tscVersion = null;
- return;
- }
- let versionFromNodeModules;
- for (const nodeModulesParentDir of nodeModulesParentDirs) {
- try {
- const tsPackageJsonPath = node_path.join(nodeModulesParentDir, TS_PACKAGE_JSON);
- const packageJson = await promises.readFile(tsPackageJsonPath, "utf-8");
- const { version: version2 } = JSON.parse(packageJson);
- const sanitizedVersion2 = getSanitizedTypeScriptVersion(version2);
- if (typeof sanitizedVersion2 !== "string") {
- continue;
- }
- versionFromNodeModules = sanitizedVersion2;
- break;
- } catch {}
- }
- if (versionFromNodeModules) {
- tscVersion = versionFromNodeModules;
- return ["md/tsc", tscVersion];
- }
- const sanitizedVersion = getSanitizedDevTypeScriptVersion(versionFromApp);
- if (typeof sanitizedVersion !== "string") {
- tscVersion = null;
- return;
- }
- tscVersion = `dev_${sanitizedVersion}`;
- return ["md/tsc", tscVersion];
- };
- var crtAvailability = {
- isCrtAvailable: false
- };
- var isCrtAvailable = () => {
- if (crtAvailability.isCrtAvailable) {
- return ["md/crt-avail"];
- }
- return null;
- };
- var createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => {
- const runtimeUserAgentPair = getRuntimeUserAgentPair();
- return async (config3) => {
- const sections = [
- ["aws-sdk-js", clientVersion],
- ["ua", "2.1"],
- [`os/${node_os.platform()}`, node_os.release()],
- ["lang/js"],
- runtimeUserAgentPair
- ];
- const typescriptUserAgentPair = await getTypeScriptUserAgentPair();
- if (typescriptUserAgentPair) {
- sections.push(typescriptUserAgentPair);
- }
- const crtAvailable = isCrtAvailable();
- if (crtAvailable) {
- sections.push(crtAvailable);
- }
- if (serviceId) {
- sections.push([`api/${serviceId}`, clientVersion]);
- }
- if (node_process.env.AWS_EXECUTION_ENV) {
- sections.push([`exec-env/${node_process.env.AWS_EXECUTION_ENV}`]);
- }
- const appId = await config3?.userAgentAppId?.();
- const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections];
- return resolvedUserAgent;
- };
- };
- var defaultUserAgent = createDefaultUserAgentProvider;
- var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID";
- var UA_APP_ID_INI_NAME = "sdk_ua_app_id";
- var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id";
- var NODE_APP_ID_CONFIG_OPTIONS = {
- environmentVariableSelector: (env4) => env4[UA_APP_ID_ENV_NAME],
- configFileSelector: (profile2) => profile2[UA_APP_ID_INI_NAME] ?? profile2[UA_APP_ID_INI_NAME_DEPRECATED],
- default: middlewareUserAgent.DEFAULT_UA_APP_ID
- };
- exports.NODE_APP_ID_CONFIG_OPTIONS = NODE_APP_ID_CONFIG_OPTIONS;
- exports.UA_APP_ID_ENV_NAME = UA_APP_ID_ENV_NAME;
- exports.UA_APP_ID_INI_NAME = UA_APP_ID_INI_NAME;
- exports.createDefaultUserAgentProvider = createDefaultUserAgentProvider;
- exports.crtAvailability = crtAvailability;
- exports.defaultUserAgent = defaultUserAgent;
-});
-
-// node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
-var require_dist_cjs73 = __commonJS((exports) => {
- var isArrayBuffer3 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
- exports.isArrayBuffer = isArrayBuffer3;
-});
-
-// node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
-var require_dist_cjs74 = __commonJS((exports) => {
- var isArrayBuffer3 = require_dist_cjs73();
- var buffer = __require("buffer");
- var fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
- if (!isArrayBuffer3.isArrayBuffer(input)) {
- throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
- }
- return buffer.Buffer.from(input, offset, length);
- };
- var fromString = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input);
- };
- exports.fromArrayBuffer = fromArrayBuffer;
- exports.fromString = fromString;
-});
-
-// node_modules/@smithy/hash-node/dist-cjs/index.js
-var require_dist_cjs75 = __commonJS((exports) => {
- var utilBufferFrom = require_dist_cjs74();
- var utilUtf8 = require_dist_cjs17();
- var buffer = __require("buffer");
- var crypto4 = __require("crypto");
-
- class Hash2 {
- algorithmIdentifier;
- secret;
- hash;
- constructor(algorithmIdentifier, secret) {
- this.algorithmIdentifier = algorithmIdentifier;
- this.secret = secret;
- this.reset();
- }
- update(toHash, encoding) {
- this.hash.update(utilUtf8.toUint8Array(castSourceData(toHash, encoding)));
- }
- digest() {
- return Promise.resolve(this.hash.digest());
- }
- reset() {
- this.hash = this.secret ? crypto4.createHmac(this.algorithmIdentifier, castSourceData(this.secret)) : crypto4.createHash(this.algorithmIdentifier);
- }
- }
- function castSourceData(toCast, encoding) {
- if (buffer.Buffer.isBuffer(toCast)) {
- return toCast;
- }
- if (typeof toCast === "string") {
- return utilBufferFrom.fromString(toCast, encoding);
- }
- if (ArrayBuffer.isView(toCast)) {
- return utilBufferFrom.fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength);
- }
- return utilBufferFrom.fromArrayBuffer(toCast);
- }
- exports.Hash = Hash2;
-});
-
-// node_modules/@smithy/util-body-length-node/dist-cjs/index.js
-var require_dist_cjs76 = __commonJS((exports) => {
- var node_fs = __require("fs");
- var calculateBodyLength = (body) => {
- if (!body) {
- return 0;
- }
- if (typeof body === "string") {
- return Buffer.byteLength(body);
- } else if (typeof body.byteLength === "number") {
- return body.byteLength;
- } else if (typeof body.size === "number") {
- return body.size;
- } else if (typeof body.start === "number" && typeof body.end === "number") {
- return body.end + 1 - body.start;
- } else if (body instanceof node_fs.ReadStream) {
- if (body.path != null) {
- return node_fs.lstatSync(body.path).size;
- } else if (typeof body.fd === "number") {
- return node_fs.fstatSync(body.fd).size;
- }
- }
- throw new Error(`Body Length computation failed for ${body}`);
- };
- exports.calculateBodyLength = calculateBodyLength;
-});
-
-// node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js
-var require_dist_cjs77 = __commonJS((exports) => {
- var configResolver = require_dist_cjs58();
- var nodeConfigProvider = require_dist_cjs9();
- var propertyProvider = require_dist_cjs6();
- var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV";
- var AWS_REGION_ENV = "AWS_REGION";
- var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION";
- var ENV_IMDS_DISABLED2 = "AWS_EC2_METADATA_DISABLED";
- var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"];
- var IMDS_REGION_PATH = "/latest/meta-data/placement/region";
- var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE";
- var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode";
- var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = {
- environmentVariableSelector: (env4) => {
- return env4[AWS_DEFAULTS_MODE_ENV];
- },
- configFileSelector: (profile2) => {
- return profile2[AWS_DEFAULTS_MODE_CONFIG];
- },
- default: "legacy"
- };
- var resolveDefaultsModeConfig = ({ region = nodeConfigProvider.loadConfig(configResolver.NODE_REGION_CONFIG_OPTIONS), defaultsMode = nodeConfigProvider.loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) } = {}) => propertyProvider.memoize(async () => {
- const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode;
- switch (mode?.toLowerCase()) {
- case "auto":
- return resolveNodeDefaultsModeAuto(region);
- case "in-region":
- case "cross-region":
- case "mobile":
- case "standard":
- case "legacy":
- return Promise.resolve(mode?.toLocaleLowerCase());
- case undefined:
- return Promise.resolve("legacy");
- default:
- throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`);
- }
- });
- var resolveNodeDefaultsModeAuto = async (clientRegion) => {
- if (clientRegion) {
- const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion;
- const inferredRegion = await inferPhysicalRegion();
- if (!inferredRegion) {
- return "standard";
- }
- if (resolvedRegion === inferredRegion) {
- return "in-region";
- } else {
- return "cross-region";
- }
- }
- return "standard";
- };
- var inferPhysicalRegion = async () => {
- if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) {
- return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV];
- }
- if (!process.env[ENV_IMDS_DISABLED2]) {
- try {
- const { getInstanceMetadataEndpoint: getInstanceMetadataEndpoint2, httpRequest: httpRequest3 } = await Promise.resolve().then(() => (init_dist_es2(), exports_dist_es2));
- const endpoint2 = await getInstanceMetadataEndpoint2();
- return (await httpRequest3({ ...endpoint2, path: IMDS_REGION_PATH })).toString();
- } catch (e) {}
- }
- };
- exports.resolveDefaultsModeConfig = resolveDefaultsModeConfig;
-});
-
-// node_modules/@smithy/util-body-length-browser/dist-cjs/index.js
-var require_dist_cjs78 = __commonJS((exports) => {
- var TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder : null;
- var calculateBodyLength = (body) => {
- if (typeof body === "string") {
- if (TEXT_ENCODER) {
- return TEXT_ENCODER.encode(body).byteLength;
- }
- let len = body.length;
- for (let i2 = len - 1;i2 >= 0; i2--) {
- const code = body.charCodeAt(i2);
- if (code > 127 && code <= 2047)
- len++;
- else if (code > 2047 && code <= 65535)
- len += 2;
- if (code >= 56320 && code <= 57343)
- i2--;
- }
- return len;
- } else if (typeof body.byteLength === "number") {
- return body.byteLength;
- } else if (typeof body.size === "number") {
- return body.size;
- }
- throw new Error(`Body Length computation failed for ${body}`);
- };
- exports.calculateBodyLength = calculateBodyLength;
-});
-
-// node_modules/@smithy/core/dist-cjs/submodules/cbor/index.js
-var require_cbor = __commonJS((exports) => {
- var serde3 = require_serde();
- var utilUtf8 = require_dist_cjs17();
- var protocols = require_protocols();
- var protocolHttp = require_dist_cjs28();
- var utilBodyLengthBrowser = require_dist_cjs78();
- var schema2 = require_schema();
- var utilMiddleware = require_dist_cjs30();
- var utilBase64 = require_dist_cjs34();
- var majorUint64 = 0;
- var majorNegativeInt64 = 1;
- var majorUnstructuredByteString = 2;
- var majorUtf8String = 3;
- var majorList = 4;
- var majorMap = 5;
- var majorTag = 6;
- var majorSpecial = 7;
- var specialFalse = 20;
- var specialTrue = 21;
- var specialNull = 22;
- var specialUndefined = 23;
- var extendedOneByte = 24;
- var extendedFloat16 = 25;
- var extendedFloat32 = 26;
- var extendedFloat64 = 27;
- var minorIndefinite = 31;
- function alloc(size) {
- return typeof Buffer !== "undefined" ? Buffer.alloc(size) : new Uint8Array(size);
- }
- var tagSymbol = Symbol("@smithy/core/cbor::tagSymbol");
- function tag2(data2) {
- data2[tagSymbol] = true;
- return data2;
- }
- var USE_TEXT_DECODER = typeof TextDecoder !== "undefined";
- var USE_BUFFER$1 = typeof Buffer !== "undefined";
- var payload = alloc(0);
- var dataView$1 = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
- var textDecoder2 = USE_TEXT_DECODER ? new TextDecoder : null;
- var _offset = 0;
- function setPayload(bytes) {
- payload = bytes;
- dataView$1 = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
- }
- function decode(at, to) {
- if (at >= to) {
- throw new Error("unexpected end of (decode) payload.");
- }
- const major = (payload[at] & 224) >> 5;
- const minor = payload[at] & 31;
- switch (major) {
- case majorUint64:
- case majorNegativeInt64:
- case majorTag:
- let unsignedInt;
- let offset;
- if (minor < 24) {
- unsignedInt = minor;
- offset = 1;
- } else {
- switch (minor) {
- case extendedOneByte:
- case extendedFloat16:
- case extendedFloat32:
- case extendedFloat64:
- const countLength = minorValueToArgumentLength[minor];
- const countOffset = countLength + 1;
- offset = countOffset;
- if (to - at < countOffset) {
- throw new Error(`countLength ${countLength} greater than remaining buf len.`);
- }
- const countIndex = at + 1;
- if (countLength === 1) {
- unsignedInt = payload[countIndex];
- } else if (countLength === 2) {
- unsignedInt = dataView$1.getUint16(countIndex);
- } else if (countLength === 4) {
- unsignedInt = dataView$1.getUint32(countIndex);
- } else {
- unsignedInt = dataView$1.getBigUint64(countIndex);
- }
- break;
- default:
- throw new Error(`unexpected minor value ${minor}.`);
- }
- }
- if (major === majorUint64) {
- _offset = offset;
- return castBigInt(unsignedInt);
- } else if (major === majorNegativeInt64) {
- let negativeInt;
- if (typeof unsignedInt === "bigint") {
- negativeInt = BigInt(-1) - unsignedInt;
- } else {
- negativeInt = -1 - unsignedInt;
- }
- _offset = offset;
- return castBigInt(negativeInt);
- } else {
- if (minor === 2 || minor === 3) {
- const length = decodeCount(at + offset, to);
- let b = BigInt(0);
- const start = at + offset + _offset;
- for (let i2 = start;i2 < start + length; ++i2) {
- b = b << BigInt(8) | BigInt(payload[i2]);
- }
- _offset = offset + _offset + length;
- return minor === 3 ? -b - BigInt(1) : b;
- } else if (minor === 4) {
- const decimalFraction = decode(at + offset, to);
- const [exponent, mantissa] = decimalFraction;
- const normalizer = mantissa < 0 ? -1 : 1;
- const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + String(BigInt(normalizer) * BigInt(mantissa));
- let numericString;
- const sign = mantissa < 0 ? "-" : "";
- numericString = exponent === 0 ? mantissaStr : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent);
- numericString = numericString.replace(/^0+/g, "");
- if (numericString === "") {
- numericString = "0";
- }
- if (numericString[0] === ".") {
- numericString = "0" + numericString;
- }
- numericString = sign + numericString;
- _offset = offset + _offset;
- return serde3.nv(numericString);
- } else {
- const value = decode(at + offset, to);
- const valueOffset = _offset;
- _offset = offset + valueOffset;
- return tag2({ tag: castBigInt(unsignedInt), value });
- }
- }
- case majorUtf8String:
- case majorMap:
- case majorList:
- case majorUnstructuredByteString:
- if (minor === minorIndefinite) {
- switch (major) {
- case majorUtf8String:
- return decodeUtf8StringIndefinite(at, to);
- case majorMap:
- return decodeMapIndefinite(at, to);
- case majorList:
- return decodeListIndefinite(at, to);
- case majorUnstructuredByteString:
- return decodeUnstructuredByteStringIndefinite(at, to);
- }
- } else {
- switch (major) {
- case majorUtf8String:
- return decodeUtf8String(at, to);
- case majorMap:
- return decodeMap(at, to);
- case majorList:
- return decodeList(at, to);
- case majorUnstructuredByteString:
- return decodeUnstructuredByteString(at, to);
- }
- }
- default:
- return decodeSpecial(at, to);
- }
- }
- function bytesToUtf8(bytes, at, to) {
- if (USE_BUFFER$1 && bytes.constructor?.name === "Buffer") {
- return bytes.toString("utf-8", at, to);
- }
- if (textDecoder2) {
- return textDecoder2.decode(bytes.subarray(at, to));
- }
- return utilUtf8.toUtf8(bytes.subarray(at, to));
- }
- function demote(bigInteger) {
- const num = Number(bigInteger);
- if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) {
- console.warn(new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`));
- }
- return num;
- }
- var minorValueToArgumentLength = {
- [extendedOneByte]: 1,
- [extendedFloat16]: 2,
- [extendedFloat32]: 4,
- [extendedFloat64]: 8
- };
- function bytesToFloat16(a2, b) {
- const sign = a2 >> 7;
- const exponent = (a2 & 124) >> 2;
- const fraction = (a2 & 3) << 8 | b;
- const scalar = sign === 0 ? 1 : -1;
- let exponentComponent;
- let summation;
- if (exponent === 0) {
- if (fraction === 0) {
- return 0;
- } else {
- exponentComponent = Math.pow(2, 1 - 15);
- summation = 0;
- }
- } else if (exponent === 31) {
- if (fraction === 0) {
- return scalar * Infinity;
- } else {
- return NaN;
- }
- } else {
- exponentComponent = Math.pow(2, exponent - 15);
- summation = 1;
- }
- summation += fraction / 1024;
- return scalar * (exponentComponent * summation);
- }
- function decodeCount(at, to) {
- const minor = payload[at] & 31;
- if (minor < 24) {
- _offset = 1;
- return minor;
- }
- if (minor === extendedOneByte || minor === extendedFloat16 || minor === extendedFloat32 || minor === extendedFloat64) {
- const countLength = minorValueToArgumentLength[minor];
- _offset = countLength + 1;
- if (to - at < _offset) {
- throw new Error(`countLength ${countLength} greater than remaining buf len.`);
- }
- const countIndex = at + 1;
- if (countLength === 1) {
- return payload[countIndex];
- } else if (countLength === 2) {
- return dataView$1.getUint16(countIndex);
- } else if (countLength === 4) {
- return dataView$1.getUint32(countIndex);
- }
- return demote(dataView$1.getBigUint64(countIndex));
- }
- throw new Error(`unexpected minor value ${minor}.`);
- }
- function decodeUtf8String(at, to) {
- const length = decodeCount(at, to);
- const offset = _offset;
- at += offset;
- if (to - at < length) {
- throw new Error(`string len ${length} greater than remaining buf len.`);
- }
- const value = bytesToUtf8(payload, at, at + length);
- _offset = offset + length;
- return value;
- }
- function decodeUtf8StringIndefinite(at, to) {
- at += 1;
- const vector = [];
- for (const base2 = at;at < to; ) {
- if (payload[at] === 255) {
- const data2 = alloc(vector.length);
- data2.set(vector, 0);
- _offset = at - base2 + 2;
- return bytesToUtf8(data2, 0, data2.length);
- }
- const major = (payload[at] & 224) >> 5;
- const minor = payload[at] & 31;
- if (major !== majorUtf8String) {
- throw new Error(`unexpected major type ${major} in indefinite string.`);
- }
- if (minor === minorIndefinite) {
- throw new Error("nested indefinite string.");
- }
- const bytes = decodeUnstructuredByteString(at, to);
- const length = _offset;
- at += length;
- for (let i2 = 0;i2 < bytes.length; ++i2) {
- vector.push(bytes[i2]);
- }
- }
- throw new Error("expected break marker.");
- }
- function decodeUnstructuredByteString(at, to) {
- const length = decodeCount(at, to);
- const offset = _offset;
- at += offset;
- if (to - at < length) {
- throw new Error(`unstructured byte string len ${length} greater than remaining buf len.`);
- }
- const value = payload.subarray(at, at + length);
- _offset = offset + length;
- return value;
- }
- function decodeUnstructuredByteStringIndefinite(at, to) {
- at += 1;
- const vector = [];
- for (const base2 = at;at < to; ) {
- if (payload[at] === 255) {
- const data2 = alloc(vector.length);
- data2.set(vector, 0);
- _offset = at - base2 + 2;
- return data2;
- }
- const major = (payload[at] & 224) >> 5;
- const minor = payload[at] & 31;
- if (major !== majorUnstructuredByteString) {
- throw new Error(`unexpected major type ${major} in indefinite string.`);
- }
- if (minor === minorIndefinite) {
- throw new Error("nested indefinite string.");
- }
- const bytes = decodeUnstructuredByteString(at, to);
- const length = _offset;
- at += length;
- for (let i2 = 0;i2 < bytes.length; ++i2) {
- vector.push(bytes[i2]);
- }
- }
- throw new Error("expected break marker.");
- }
- function decodeList(at, to) {
- const listDataLength = decodeCount(at, to);
- const offset = _offset;
- at += offset;
- const base2 = at;
- const list2 = Array(listDataLength);
- for (let i2 = 0;i2 < listDataLength; ++i2) {
- const item = decode(at, to);
- const itemOffset = _offset;
- list2[i2] = item;
- at += itemOffset;
- }
- _offset = offset + (at - base2);
- return list2;
- }
- function decodeListIndefinite(at, to) {
- at += 1;
- const list2 = [];
- for (const base2 = at;at < to; ) {
- if (payload[at] === 255) {
- _offset = at - base2 + 2;
- return list2;
- }
- const item = decode(at, to);
- const n2 = _offset;
- at += n2;
- list2.push(item);
- }
- throw new Error("expected break marker.");
- }
- function decodeMap(at, to) {
- const mapDataLength = decodeCount(at, to);
- const offset = _offset;
- at += offset;
- const base2 = at;
- const map3 = {};
- for (let i2 = 0;i2 < mapDataLength; ++i2) {
- if (at >= to) {
- throw new Error("unexpected end of map payload.");
- }
- const major = (payload[at] & 224) >> 5;
- if (major !== majorUtf8String) {
- throw new Error(`unexpected major type ${major} for map key at index ${at}.`);
- }
- const key = decode(at, to);
- at += _offset;
- const value = decode(at, to);
- at += _offset;
- map3[key] = value;
- }
- _offset = offset + (at - base2);
- return map3;
- }
- function decodeMapIndefinite(at, to) {
- at += 1;
- const base2 = at;
- const map3 = {};
- for (;at < to; ) {
- if (at >= to) {
- throw new Error("unexpected end of map payload.");
- }
- if (payload[at] === 255) {
- _offset = at - base2 + 2;
- return map3;
- }
- const major = (payload[at] & 224) >> 5;
- if (major !== majorUtf8String) {
- throw new Error(`unexpected major type ${major} for map key.`);
- }
- const key = decode(at, to);
- at += _offset;
- const value = decode(at, to);
- at += _offset;
- map3[key] = value;
- }
- throw new Error("expected break marker.");
- }
- function decodeSpecial(at, to) {
- const minor = payload[at] & 31;
- switch (minor) {
- case specialTrue:
- case specialFalse:
- _offset = 1;
- return minor === specialTrue;
- case specialNull:
- _offset = 1;
- return null;
- case specialUndefined:
- _offset = 1;
- return null;
- case extendedFloat16:
- if (to - at < 3) {
- throw new Error("incomplete float16 at end of buf.");
- }
- _offset = 3;
- return bytesToFloat16(payload[at + 1], payload[at + 2]);
- case extendedFloat32:
- if (to - at < 5) {
- throw new Error("incomplete float32 at end of buf.");
- }
- _offset = 5;
- return dataView$1.getFloat32(at + 1);
- case extendedFloat64:
- if (to - at < 9) {
- throw new Error("incomplete float64 at end of buf.");
- }
- _offset = 9;
- return dataView$1.getFloat64(at + 1);
- default:
- throw new Error(`unexpected minor value ${minor}.`);
- }
- }
- function castBigInt(bigInt) {
- if (typeof bigInt === "number") {
- return bigInt;
- }
- const num = Number(bigInt);
- if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) {
- return num;
- }
- return bigInt;
- }
- var USE_BUFFER = typeof Buffer !== "undefined";
- var initialSize = 2048;
- var data = alloc(initialSize);
- var dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
- var cursor = 0;
- function ensureSpace(bytes) {
- const remaining = data.byteLength - cursor;
- if (remaining < bytes) {
- if (cursor < 16000000) {
- resize(Math.max(data.byteLength * 4, data.byteLength + bytes));
- } else {
- resize(data.byteLength + bytes + 16000000);
- }
- }
- }
- function toUint8Array() {
- const out = alloc(cursor);
- out.set(data.subarray(0, cursor), 0);
- cursor = 0;
- return out;
- }
- function resize(size) {
- const old = data;
- data = alloc(size);
- if (old) {
- if (old.copy) {
- old.copy(data, 0, 0, old.byteLength);
- } else {
- data.set(old, 0);
- }
- }
- dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
- }
- function encodeHeader(major, value) {
- if (value < 24) {
- data[cursor++] = major << 5 | value;
- } else if (value < 1 << 8) {
- data[cursor++] = major << 5 | 24;
- data[cursor++] = value;
- } else if (value < 1 << 16) {
- data[cursor++] = major << 5 | extendedFloat16;
- dataView.setUint16(cursor, value);
- cursor += 2;
- } else if (value < 2 ** 32) {
- data[cursor++] = major << 5 | extendedFloat32;
- dataView.setUint32(cursor, value);
- cursor += 4;
- } else {
- data[cursor++] = major << 5 | extendedFloat64;
- dataView.setBigUint64(cursor, typeof value === "bigint" ? value : BigInt(value));
- cursor += 8;
- }
- }
- function encode4(_input) {
- const encodeStack = [_input];
- while (encodeStack.length) {
- const input = encodeStack.pop();
- ensureSpace(typeof input === "string" ? input.length * 4 : 64);
- if (typeof input === "string") {
- if (USE_BUFFER) {
- encodeHeader(majorUtf8String, Buffer.byteLength(input));
- cursor += data.write(input, cursor);
- } else {
- const bytes = utilUtf8.fromUtf8(input);
- encodeHeader(majorUtf8String, bytes.byteLength);
- data.set(bytes, cursor);
- cursor += bytes.byteLength;
- }
- continue;
- } else if (typeof input === "number") {
- if (Number.isInteger(input)) {
- const nonNegative = input >= 0;
- const major = nonNegative ? majorUint64 : majorNegativeInt64;
- const value = nonNegative ? input : -input - 1;
- if (value < 24) {
- data[cursor++] = major << 5 | value;
- } else if (value < 256) {
- data[cursor++] = major << 5 | 24;
- data[cursor++] = value;
- } else if (value < 65536) {
- data[cursor++] = major << 5 | extendedFloat16;
- data[cursor++] = value >> 8;
- data[cursor++] = value;
- } else if (value < 4294967296) {
- data[cursor++] = major << 5 | extendedFloat32;
- dataView.setUint32(cursor, value);
- cursor += 4;
- } else {
- data[cursor++] = major << 5 | extendedFloat64;
- dataView.setBigUint64(cursor, BigInt(value));
- cursor += 8;
- }
- continue;
- }
- data[cursor++] = majorSpecial << 5 | extendedFloat64;
- dataView.setFloat64(cursor, input);
- cursor += 8;
- continue;
- } else if (typeof input === "bigint") {
- const nonNegative = input >= 0;
- const major = nonNegative ? majorUint64 : majorNegativeInt64;
- const value = nonNegative ? input : -input - BigInt(1);
- const n2 = Number(value);
- if (n2 < 24) {
- data[cursor++] = major << 5 | n2;
- } else if (n2 < 256) {
- data[cursor++] = major << 5 | 24;
- data[cursor++] = n2;
- } else if (n2 < 65536) {
- data[cursor++] = major << 5 | extendedFloat16;
- data[cursor++] = n2 >> 8;
- data[cursor++] = n2 & 255;
- } else if (n2 < 4294967296) {
- data[cursor++] = major << 5 | extendedFloat32;
- dataView.setUint32(cursor, n2);
- cursor += 4;
- } else if (value < BigInt("18446744073709551616")) {
- data[cursor++] = major << 5 | extendedFloat64;
- dataView.setBigUint64(cursor, value);
- cursor += 8;
- } else {
- const binaryBigInt = value.toString(2);
- const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8));
- let b = value;
- let i2 = 0;
- while (bigIntBytes.byteLength - ++i2 >= 0) {
- bigIntBytes[bigIntBytes.byteLength - i2] = Number(b & BigInt(255));
- b >>= BigInt(8);
- }
- ensureSpace(bigIntBytes.byteLength * 2);
- data[cursor++] = nonNegative ? 194 : 195;
- if (USE_BUFFER) {
- encodeHeader(majorUnstructuredByteString, Buffer.byteLength(bigIntBytes));
- } else {
- encodeHeader(majorUnstructuredByteString, bigIntBytes.byteLength);
- }
- data.set(bigIntBytes, cursor);
- cursor += bigIntBytes.byteLength;
- }
- continue;
- } else if (input === null) {
- data[cursor++] = majorSpecial << 5 | specialNull;
- continue;
- } else if (typeof input === "boolean") {
- data[cursor++] = majorSpecial << 5 | (input ? specialTrue : specialFalse);
- continue;
- } else if (typeof input === "undefined") {
- throw new Error("@smithy/core/cbor: client may not serialize undefined value.");
- } else if (Array.isArray(input)) {
- for (let i2 = input.length - 1;i2 >= 0; --i2) {
- encodeStack.push(input[i2]);
- }
- encodeHeader(majorList, input.length);
- continue;
- } else if (typeof input.byteLength === "number") {
- ensureSpace(input.length * 2);
- encodeHeader(majorUnstructuredByteString, input.length);
- data.set(input, cursor);
- cursor += input.byteLength;
- continue;
- } else if (typeof input === "object") {
- if (input instanceof serde3.NumericValue) {
- const decimalIndex = input.string.indexOf(".");
- const exponent = decimalIndex === -1 ? 0 : decimalIndex - input.string.length + 1;
- const mantissa = BigInt(input.string.replace(".", ""));
- data[cursor++] = 196;
- encodeStack.push(mantissa);
- encodeStack.push(exponent);
- encodeHeader(majorList, 2);
- continue;
- }
- if (input[tagSymbol]) {
- if ("tag" in input && "value" in input) {
- encodeStack.push(input.value);
- encodeHeader(majorTag, input.tag);
- continue;
- } else {
- throw new Error("tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input));
- }
- }
- const keys2 = Object.keys(input);
- for (let i2 = keys2.length - 1;i2 >= 0; --i2) {
- const key = keys2[i2];
- encodeStack.push(input[key]);
- encodeStack.push(key);
- }
- encodeHeader(majorMap, keys2.length);
- continue;
- }
- throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`);
- }
- }
- var cbor = {
- deserialize(payload2) {
- setPayload(payload2);
- return decode(0, payload2.length);
- },
- serialize(input) {
- try {
- encode4(input);
- return toUint8Array();
- } catch (e) {
- toUint8Array();
- throw e;
- }
- },
- resizeEncodingBuffer(size) {
- resize(size);
- }
- };
- var parseCborBody = (streamBody, context) => {
- return protocols.collectBody(streamBody, context).then(async (bytes) => {
- if (bytes.length) {
- try {
- return cbor.deserialize(bytes);
- } catch (e) {
- Object.defineProperty(e, "$responseBodyText", {
- value: context.utf8Encoder(bytes)
- });
- throw e;
- }
- }
- return {};
- });
- };
- var dateToTag = (date5) => {
- return tag2({
- tag: 1,
- value: date5.getTime() / 1000
- });
- };
- var parseCborErrorBody = async (errorBody, context) => {
- const value = await parseCborBody(errorBody, context);
- value.message = value.message ?? value.Message;
- return value;
- };
- var loadSmithyRpcV2CborErrorCode = (output, data2) => {
- const sanitizeErrorCode = (rawValue) => {
- let cleanValue = rawValue;
- if (typeof cleanValue === "number") {
- cleanValue = cleanValue.toString();
- }
- if (cleanValue.indexOf(",") >= 0) {
- cleanValue = cleanValue.split(",")[0];
- }
- if (cleanValue.indexOf(":") >= 0) {
- cleanValue = cleanValue.split(":")[0];
- }
- if (cleanValue.indexOf("#") >= 0) {
- cleanValue = cleanValue.split("#")[1];
- }
- return cleanValue;
- };
- if (data2["__type"] !== undefined) {
- return sanitizeErrorCode(data2["__type"]);
- }
- const codeKey = Object.keys(data2).find((key) => key.toLowerCase() === "code");
- if (codeKey && data2[codeKey] !== undefined) {
- return sanitizeErrorCode(data2[codeKey]);
- }
- };
- var checkCborResponse = (response2) => {
- if (String(response2.headers["smithy-protocol"]).toLowerCase() !== "rpc-v2-cbor") {
- throw new Error("Malformed RPCv2 CBOR response, status: " + response2.statusCode);
- }
- };
- var buildHttpRpcRequest = async (context, headers, path8, resolvedHostname, body) => {
- const endpoint2 = await context.endpoint();
- const { hostname: hostname2, protocol = "https", port, path: basePath } = endpoint2;
- const contents = {
- protocol,
- hostname: hostname2,
- port,
- method: "POST",
- path: basePath.endsWith("/") ? basePath.slice(0, -1) + path8 : basePath + path8,
- headers: {
- ...headers
- }
- };
- if (resolvedHostname !== undefined) {
- contents.hostname = resolvedHostname;
- }
- if (endpoint2.headers) {
- for (const [name, value] of Object.entries(endpoint2.headers)) {
- contents.headers[name] = value;
- }
- }
- if (body !== undefined) {
- contents.body = body;
- try {
- contents.headers["content-length"] = String(utilBodyLengthBrowser.calculateBodyLength(body));
- } catch (e) {}
- }
- return new protocolHttp.HttpRequest(contents);
- };
-
- class CborCodec extends protocols.SerdeContext {
- createSerializer() {
- const serializer = new CborShapeSerializer;
- serializer.setSerdeContext(this.serdeContext);
- return serializer;
- }
- createDeserializer() {
- const deserializer = new CborShapeDeserializer;
- deserializer.setSerdeContext(this.serdeContext);
- return deserializer;
- }
- }
-
- class CborShapeSerializer extends protocols.SerdeContext {
- value;
- write(schema3, value) {
- this.value = this.serialize(schema3, value);
- }
- serialize(schema$1, source) {
- const ns = schema2.NormalizedSchema.of(schema$1);
- if (source == null) {
- if (ns.isIdempotencyToken()) {
- return serde3.generateIdempotencyToken();
- }
- return source;
- }
- if (ns.isBlobSchema()) {
- if (typeof source === "string") {
- return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(source);
- }
- return source;
- }
- if (ns.isTimestampSchema()) {
- if (typeof source === "number" || typeof source === "bigint") {
- return dateToTag(new Date(Number(source) / 1000 | 0));
- }
- return dateToTag(source);
- }
- if (typeof source === "function" || typeof source === "object") {
- const sourceObject = source;
- if (ns.isListSchema() && Array.isArray(sourceObject)) {
- const sparse = !!ns.getMergedTraits().sparse;
- const newArray = [];
- let i2 = 0;
- for (const item of sourceObject) {
- const value = this.serialize(ns.getValueSchema(), item);
- if (value != null || sparse) {
- newArray[i2++] = value;
- }
- }
- return newArray;
- }
- if (sourceObject instanceof Date) {
- return dateToTag(sourceObject);
- }
- const newObject = {};
- if (ns.isMapSchema()) {
- const sparse = !!ns.getMergedTraits().sparse;
- for (const key of Object.keys(sourceObject)) {
- const value = this.serialize(ns.getValueSchema(), sourceObject[key]);
- if (value != null || sparse) {
- newObject[key] = value;
- }
- }
- } else if (ns.isStructSchema()) {
- for (const [key, memberSchema] of ns.structIterator()) {
- const value = this.serialize(memberSchema, sourceObject[key]);
- if (value != null) {
- newObject[key] = value;
- }
- }
- const isUnion = ns.isUnionSchema();
- if (isUnion && Array.isArray(sourceObject.$unknown)) {
- const [k, v] = sourceObject.$unknown;
- newObject[k] = v;
- } else if (typeof sourceObject.__type === "string") {
- for (const [k, v] of Object.entries(sourceObject)) {
- if (!(k in newObject)) {
- newObject[k] = this.serialize(15, v);
- }
- }
- }
- } else if (ns.isDocumentSchema()) {
- for (const key of Object.keys(sourceObject)) {
- newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]);
- }
- } else if (ns.isBigDecimalSchema()) {
- return sourceObject;
- }
- return newObject;
- }
- return source;
- }
- flush() {
- const buffer = cbor.serialize(this.value);
- this.value = undefined;
- return buffer;
- }
- }
-
- class CborShapeDeserializer extends protocols.SerdeContext {
- read(schema3, bytes) {
- const data2 = cbor.deserialize(bytes);
- return this.readValue(schema3, data2);
- }
- readValue(_schema, value) {
- const ns = schema2.NormalizedSchema.of(_schema);
- if (ns.isTimestampSchema()) {
- if (typeof value === "number") {
- return serde3._parseEpochTimestamp(value);
- }
- if (typeof value === "object") {
- if (value.tag === 1 && "value" in value) {
- return serde3._parseEpochTimestamp(value.value);
- }
- }
- }
- if (ns.isBlobSchema()) {
- if (typeof value === "string") {
- return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(value);
- }
- return value;
- }
- if (typeof value === "undefined" || typeof value === "boolean" || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || typeof value === "symbol") {
- return value;
- } else if (typeof value === "object") {
- if (value === null) {
- return null;
- }
- if ("byteLength" in value) {
- return value;
- }
- if (value instanceof Date) {
- return value;
- }
- if (ns.isDocumentSchema()) {
- return value;
- }
- if (ns.isListSchema()) {
- const newArray = [];
- const memberSchema = ns.getValueSchema();
- for (const item of value) {
- const itemValue = this.readValue(memberSchema, item);
- newArray.push(itemValue);
- }
- return newArray;
- }
- const newObject = {};
- if (ns.isMapSchema()) {
- const targetSchema = ns.getValueSchema();
- for (const key of Object.keys(value)) {
- const itemValue = this.readValue(targetSchema, value[key]);
- newObject[key] = itemValue;
- }
- } else if (ns.isStructSchema()) {
- const isUnion = ns.isUnionSchema();
- let keys2;
- if (isUnion) {
- keys2 = new Set(Object.keys(value).filter((k) => k !== "__type"));
- }
- for (const [key, memberSchema] of ns.structIterator()) {
- if (isUnion) {
- keys2.delete(key);
- }
- if (value[key] != null) {
- newObject[key] = this.readValue(memberSchema, value[key]);
- }
- }
- if (isUnion && keys2?.size === 1 && Object.keys(newObject).length === 0) {
- const k = keys2.values().next().value;
- newObject.$unknown = [k, value[k]];
- } else if (typeof value.__type === "string") {
- for (const [k, v] of Object.entries(value)) {
- if (!(k in newObject)) {
- newObject[k] = v;
- }
- }
- }
- } else if (value instanceof serde3.NumericValue) {
- return value;
- }
- return newObject;
- } else {
- return value;
- }
- }
- }
-
- class SmithyRpcV2CborProtocol extends protocols.RpcProtocol {
- codec = new CborCodec;
- serializer = this.codec.createSerializer();
- deserializer = this.codec.createDeserializer();
- constructor({ defaultNamespace, errorTypeRegistries }) {
- super({ defaultNamespace, errorTypeRegistries });
- }
- getShapeId() {
- return "smithy.protocols#rpcv2Cbor";
- }
- getPayloadCodec() {
- return this.codec;
- }
- async serializeRequest(operationSchema, input, context) {
- const request2 = await super.serializeRequest(operationSchema, input, context);
- Object.assign(request2.headers, {
- "content-type": this.getDefaultContentType(),
- "smithy-protocol": "rpc-v2-cbor",
- accept: this.getDefaultContentType()
- });
- if (schema2.deref(operationSchema.input) === "unit") {
- delete request2.body;
- delete request2.headers["content-type"];
- } else {
- if (!request2.body) {
- this.serializer.write(15, {});
- request2.body = this.serializer.flush();
- }
- try {
- request2.headers["content-length"] = String(request2.body.byteLength);
- } catch (e) {}
- }
- const { service, operation } = utilMiddleware.getSmithyContext(context);
- const path8 = `/service/${service}/operation/${operation}`;
- if (request2.path.endsWith("/")) {
- request2.path += path8.slice(1);
- } else {
- request2.path += path8;
- }
- return request2;
- }
- async deserializeResponse(operationSchema, context, response2) {
- return super.deserializeResponse(operationSchema, context, response2);
- }
- async handleError(operationSchema, context, response2, dataObject, metadata) {
- const errorName = loadSmithyRpcV2CborErrorCode(response2, dataObject) ?? "Unknown";
- const errorMetadata = {
- $metadata: metadata,
- $fault: response2.statusCode <= 500 ? "client" : "server"
- };
- let namespace = this.options.defaultNamespace;
- if (errorName.includes("#")) {
- [namespace] = errorName.split("#");
- }
- const registry3 = this.compositeErrorRegistry;
- const nsRegistry = schema2.TypeRegistry.for(namespace);
- registry3.copyFrom(nsRegistry);
- let errorSchema;
- try {
- errorSchema = registry3.getSchema(errorName);
- } catch (e) {
- if (dataObject.Message) {
- dataObject.message = dataObject.Message;
- }
- const syntheticRegistry = schema2.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace);
- registry3.copyFrom(syntheticRegistry);
- const baseExceptionSchema = registry3.getBaseException();
- if (baseExceptionSchema) {
- const ErrorCtor2 = registry3.getErrorCtor(baseExceptionSchema);
- throw Object.assign(new ErrorCtor2({ name: errorName }), errorMetadata, dataObject);
- }
- throw Object.assign(new Error(errorName), errorMetadata, dataObject);
- }
- const ns = schema2.NormalizedSchema.of(errorSchema);
- const ErrorCtor = registry3.getErrorCtor(errorSchema);
- const message = dataObject.message ?? dataObject.Message ?? "Unknown";
- const exception = new ErrorCtor(message);
- const output = {};
- for (const [name, member] of ns.structIterator()) {
- output[name] = this.deserializer.readValue(member, dataObject[name]);
- }
- throw Object.assign(exception, errorMetadata, {
- $fault: ns.getMergedTraits().error,
- message
- }, output);
- }
- getDefaultContentType() {
- return "application/cbor";
- }
- }
- exports.CborCodec = CborCodec;
- exports.CborShapeDeserializer = CborShapeDeserializer;
- exports.CborShapeSerializer = CborShapeSerializer;
- exports.SmithyRpcV2CborProtocol = SmithyRpcV2CborProtocol;
- exports.buildHttpRpcRequest = buildHttpRpcRequest;
- exports.cbor = cbor;
- exports.checkCborResponse = checkCborResponse;
- exports.dateToTag = dateToTag;
- exports.loadSmithyRpcV2CborErrorCode = loadSmithyRpcV2CborErrorCode;
- exports.parseCborBody = parseCborBody;
- exports.parseCborErrorBody = parseCborErrorBody;
- exports.tag = tag2;
- exports.tagSymbol = tagSymbol;
-});
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/smithy-client/dist-cjs/index.js
-var require_dist_cjs79 = __commonJS((exports) => {
- var middlewareStack = require_dist_cjs12();
- var protocols = require_protocols();
- var types3 = require_dist_cjs35();
- var schema2 = require_schema();
- var serde3 = require_serde();
-
- class Client2 {
- config;
- middlewareStack = middlewareStack.constructStack();
- initConfig;
- handlers;
- constructor(config3) {
- this.config = config3;
- const { protocol, protocolSettings } = config3;
- if (protocolSettings) {
- if (typeof protocol === "function") {
- config3.protocol = new protocol(protocolSettings);
- }
- }
- }
- send(command3, optionsOrCb, cb) {
- const options2 = typeof optionsOrCb !== "function" ? optionsOrCb : undefined;
- const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
- const useHandlerCache = options2 === undefined && this.config.cacheMiddleware === true;
- let handler;
- if (useHandlerCache) {
- if (!this.handlers) {
- this.handlers = new WeakMap;
- }
- const handlers = this.handlers;
- if (handlers.has(command3.constructor)) {
- handler = handlers.get(command3.constructor);
- } else {
- handler = command3.resolveMiddleware(this.middlewareStack, this.config, options2);
- handlers.set(command3.constructor, handler);
- }
- } else {
- delete this.handlers;
- handler = command3.resolveMiddleware(this.middlewareStack, this.config, options2);
- }
- if (callback) {
- handler(command3).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => {});
- } else {
- return handler(command3).then((result) => result.output);
- }
- }
- destroy() {
- this.config?.requestHandler?.destroy?.();
- delete this.handlers;
- }
- }
- var SENSITIVE_STRING$1 = "***SensitiveInformation***";
- function schemaLogFilter2(schema$1, data) {
- if (data == null) {
- return data;
- }
- const ns = schema2.NormalizedSchema.of(schema$1);
- if (ns.getMergedTraits().sensitive) {
- return SENSITIVE_STRING$1;
- }
- if (ns.isListSchema()) {
- const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING$1;
- }
- } else if (ns.isMapSchema()) {
- const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING$1;
- }
- } else if (ns.isStructSchema() && typeof data === "object") {
- const object2 = data;
- const newObject = {};
- for (const [member, memberNs] of ns.structIterator()) {
- if (object2[member] != null) {
- newObject[member] = schemaLogFilter2(memberNs, object2[member]);
- }
- }
- return newObject;
- }
- return data;
- }
-
- class Command3 {
- middlewareStack = middlewareStack.constructStack();
- schema;
- static classBuilder() {
- return new ClassBuilder2;
- }
- resolveMiddlewareWithContext(clientStack, configuration, options2, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
- for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options2)) {
- this.middlewareStack.use(mw);
- }
- const stack = clientStack.concat(this.middlewareStack);
- const { logger: logger2 } = configuration;
- const handlerExecutionContext = {
- logger: logger2,
- clientName,
- commandName,
- inputFilterSensitiveLog,
- outputFilterSensitiveLog,
- [types3.SMITHY_CONTEXT_KEY]: {
- commandInstance: this,
- ...smithyContext
- },
- ...additionalContext
- };
- const { requestHandler } = configuration;
- return stack.resolve((request2) => requestHandler.handle(request2.request, options2 || {}), handlerExecutionContext);
- }
- }
-
- class ClassBuilder2 {
- _init = () => {};
- _ep = {};
- _middlewareFn = () => [];
- _commandName = "";
- _clientName = "";
- _additionalContext = {};
- _smithyContext = {};
- _inputFilterSensitiveLog = undefined;
- _outputFilterSensitiveLog = undefined;
- _serializer = null;
- _deserializer = null;
- _operationSchema;
- init(cb) {
- this._init = cb;
- }
- ep(endpointParameterInstructions) {
- this._ep = endpointParameterInstructions;
- return this;
- }
- m(middlewareSupplier) {
- this._middlewareFn = middlewareSupplier;
- return this;
- }
- s(service, operation, smithyContext = {}) {
- this._smithyContext = {
- service,
- operation,
- ...smithyContext
- };
- return this;
- }
- c(additionalContext = {}) {
- this._additionalContext = additionalContext;
- return this;
- }
- n(clientName, commandName) {
- this._clientName = clientName;
- this._commandName = commandName;
- return this;
- }
- f(inputFilter = (_) => _, outputFilter = (_) => _) {
- this._inputFilterSensitiveLog = inputFilter;
- this._outputFilterSensitiveLog = outputFilter;
- return this;
- }
- ser(serializer) {
- this._serializer = serializer;
- return this;
- }
- de(deserializer) {
- this._deserializer = deserializer;
- return this;
- }
- sc(operation) {
- this._operationSchema = operation;
- this._smithyContext.operationSchema = operation;
- return this;
- }
- build() {
- const closure = this;
- let CommandRef;
- return CommandRef = class extends Command3 {
- input;
- static getEndpointParameterInstructions() {
- return closure._ep;
- }
- constructor(...[input]) {
- super();
- this.input = input ?? {};
- closure._init(this);
- this.schema = closure._operationSchema;
- }
- resolveMiddleware(stack, configuration, options2) {
- const op = closure._operationSchema;
- const input = op?.[4] ?? op?.input;
- const output = op?.[5] ?? op?.output;
- return this.resolveMiddlewareWithContext(stack, configuration, options2, {
- CommandCtor: CommandRef,
- middlewareFn: closure._middlewareFn,
- clientName: closure._clientName,
- commandName: closure._commandName,
- inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter2.bind(null, input) : (_) => _),
- outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter2.bind(null, output) : (_) => _),
- smithyContext: closure._smithyContext,
- additionalContext: closure._additionalContext
- });
- }
- serialize = closure._serializer;
- deserialize = closure._deserializer;
- };
- }
- }
- var SENSITIVE_STRING3 = "***SensitiveInformation***";
- var createAggregatedClient2 = (commands, Client3, options2) => {
- for (const [command3, CommandCtor] of Object.entries(commands)) {
- const methodImpl = async function(args, optionsOrCb, cb) {
- const command4 = new CommandCtor(args);
- if (typeof optionsOrCb === "function") {
- this.send(command4, optionsOrCb);
- } else if (typeof cb === "function") {
- if (typeof optionsOrCb !== "object")
- throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
- this.send(command4, optionsOrCb || {}, cb);
- } else {
- return this.send(command4, optionsOrCb);
- }
- };
- const methodName = (command3[0].toLowerCase() + command3.slice(1)).replace(/Command$/, "");
- Client3.prototype[methodName] = methodImpl;
- }
- const { paginators = {}, waiters = {} } = options2 ?? {};
- for (const [paginatorName, paginatorFn] of Object.entries(paginators)) {
- if (Client3.prototype[paginatorName] === undefined) {
- Client3.prototype[paginatorName] = function(commandInput = {}, paginationConfiguration, ...rest) {
- return paginatorFn({
- ...paginationConfiguration,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
- for (const [waiterName, waiterFn] of Object.entries(waiters)) {
- if (Client3.prototype[waiterName] === undefined) {
- Client3.prototype[waiterName] = async function(commandInput = {}, waiterConfiguration, ...rest) {
- let config3 = waiterConfiguration;
- if (typeof waiterConfiguration === "number") {
- config3 = {
- maxWaitTime: waiterConfiguration
- };
- }
- return waiterFn({
- ...config3,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
- };
-
- class ServiceException2 extends Error {
- $fault;
- $response;
- $retryable;
- $metadata;
- constructor(options2) {
- super(options2.message);
- Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
- this.name = options2.name;
- this.$fault = options2.$fault;
- this.$metadata = options2.$metadata;
- }
- static isInstance(value) {
- if (!value)
- return false;
- const candidate = value;
- return ServiceException2.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
- }
- static [Symbol.hasInstance](instance) {
- if (!instance)
- return false;
- const candidate = instance;
- if (this === ServiceException2) {
- return ServiceException2.isInstance(instance);
- }
- if (ServiceException2.isInstance(instance)) {
- if (candidate.name && this.name) {
- return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
- }
- return this.prototype.isPrototypeOf(instance);
- }
- return false;
- }
- }
- var decorateServiceException2 = (exception, additions = {}) => {
- Object.entries(additions).filter(([, v]) => v !== undefined).forEach(([k, v]) => {
- if (exception[k] == undefined || exception[k] === "") {
- exception[k] = v;
- }
- });
- const message = exception.message || exception.Message || "UnknownError";
- exception.message = message;
- delete exception.Message;
- return exception;
- };
- var throwDefaultError2 = ({ output, parsedBody, exceptionCtor, errorCode }) => {
- const $metadata = deserializeMetadata2(output);
- const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined;
- const response2 = new exceptionCtor({
- name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
- $fault: "client",
- $metadata
- });
- throw decorateServiceException2(response2, parsedBody);
- };
- var withBaseException2 = (ExceptionCtor) => {
- return ({ output, parsedBody, errorCode }) => {
- throwDefaultError2({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
- };
- };
- var deserializeMetadata2 = (output) => ({
- httpStatusCode: output.statusCode,
- requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
- extendedRequestId: output.headers["x-amz-id-2"],
- cfId: output.headers["x-amz-cf-id"]
- });
- var loadConfigsForDefaultMode2 = (mode) => {
- switch (mode) {
- case "standard":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "in-region":
- return {
- retryMode: "standard",
- connectionTimeout: 1100
- };
- case "cross-region":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "mobile":
- return {
- retryMode: "standard",
- connectionTimeout: 30000
- };
- default:
- return {};
- }
- };
- var warningEmitted2 = false;
- var emitWarningIfUnsupportedVersion3 = (version2) => {
- if (version2 && !warningEmitted2 && parseInt(version2.substring(1, version2.indexOf("."))) < 16) {
- warningEmitted2 = true;
- }
- };
- var knownAlgorithms2 = Object.values(types3.AlgorithmId);
- var getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- for (const id in types3.AlgorithmId) {
- const algorithmId = types3.AlgorithmId[id];
- if (runtimeConfig[algorithmId] === undefined) {
- continue;
- }
- checksumAlgorithms.push({
- algorithmId: () => algorithmId,
- checksumConstructor: () => runtimeConfig[algorithmId]
- });
- }
- for (const [id, ChecksumCtor] of Object.entries(runtimeConfig.checksumAlgorithms ?? {})) {
- checksumAlgorithms.push({
- algorithmId: () => id,
- checksumConstructor: () => ChecksumCtor
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- runtimeConfig.checksumAlgorithms = runtimeConfig.checksumAlgorithms ?? {};
- const id = algo.algorithmId();
- const ctor = algo.checksumConstructor();
- if (knownAlgorithms2.includes(id)) {
- runtimeConfig.checksumAlgorithms[id.toUpperCase()] = ctor;
- } else {
- runtimeConfig.checksumAlgorithms[id] = ctor;
- }
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
- };
- var resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- const id = checksumAlgorithm.algorithmId();
- if (knownAlgorithms2.includes(id)) {
- runtimeConfig[id] = checksumAlgorithm.checksumConstructor();
- }
- });
- return runtimeConfig;
- };
- var getRetryConfiguration2 = (runtimeConfig) => {
- return {
- setRetryStrategy(retryStrategy) {
- runtimeConfig.retryStrategy = retryStrategy;
- },
- retryStrategy() {
- return runtimeConfig.retryStrategy;
- }
- };
- };
- var resolveRetryRuntimeConfig2 = (retryStrategyConfiguration) => {
- const runtimeConfig = {};
- runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
- return runtimeConfig;
- };
- var getDefaultExtensionConfiguration2 = (runtimeConfig) => {
- return Object.assign(getChecksumConfiguration2(runtimeConfig), getRetryConfiguration2(runtimeConfig));
- };
- var getDefaultClientConfiguration2 = getDefaultExtensionConfiguration2;
- var resolveDefaultRuntimeConfig2 = (config3) => {
- return Object.assign(resolveChecksumRuntimeConfig2(config3), resolveRetryRuntimeConfig2(config3));
- };
- var getArrayIfSingleItem2 = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray];
- var getValueFromTextNode2 = (obj) => {
- const textNodeName = "#text";
- for (const key in obj) {
- if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) {
- obj[key] = obj[key][textNodeName];
- } else if (typeof obj[key] === "object" && obj[key] !== null) {
- obj[key] = getValueFromTextNode2(obj[key]);
- }
- }
- return obj;
- };
- var isSerializableHeaderValue2 = (value) => {
- return value != null;
- };
-
- class NoOpLogger3 {
- trace() {}
- debug() {}
- info() {}
- warn() {}
- error() {}
- }
- function map3(arg0, arg1, arg2) {
- let target;
- let filter2;
- let instructions;
- if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
- target = {};
- instructions = arg0;
- } else {
- target = arg0;
- if (typeof arg1 === "function") {
- filter2 = arg1;
- instructions = arg2;
- return mapWithFilter2(target, filter2, instructions);
- } else {
- instructions = arg1;
- }
- }
- for (const key of Object.keys(instructions)) {
- if (!Array.isArray(instructions[key])) {
- target[key] = instructions[key];
- continue;
- }
- applyInstruction2(target, null, instructions, key);
- }
- return target;
- }
- var convertMap2 = (target) => {
- const output = {};
- for (const [k, v] of Object.entries(target || {})) {
- output[k] = [, v];
- }
- return output;
- };
- var take2 = (source, instructions) => {
- const out = {};
- for (const key in instructions) {
- applyInstruction2(out, source, instructions, key);
- }
- return out;
- };
- var mapWithFilter2 = (target, filter2, instructions) => {
- return map3(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
- if (Array.isArray(value)) {
- _instructions[key] = value;
- } else {
- if (typeof value === "function") {
- _instructions[key] = [filter2, value()];
- } else {
- _instructions[key] = [filter2, value];
- }
- }
- return _instructions;
- }, {}));
- };
- var applyInstruction2 = (target, source, instructions, targetKey) => {
- if (source !== null) {
- let instruction = instructions[targetKey];
- if (typeof instruction === "function") {
- instruction = [, instruction];
- }
- const [filter3 = nonNullish2, valueFn = pass2, sourceKey = targetKey] = instruction;
- if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) {
- target[targetKey] = valueFn(source[sourceKey]);
- }
- return;
- }
- let [filter2, value] = instructions[targetKey];
- if (typeof value === "function") {
- let _value;
- const defaultFilterPassed = filter2 === undefined && (_value = value()) != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(undefined) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed) {
- target[targetKey] = _value;
- } else if (customFilterPassed) {
- target[targetKey] = value();
- }
- } else {
- const defaultFilterPassed = filter2 === undefined && value != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed || customFilterPassed) {
- target[targetKey] = value;
- }
- }
- };
- var nonNullish2 = (_) => _ != null;
- var pass2 = (_) => _;
- var serializeFloat2 = (value) => {
- if (value !== value) {
- return "NaN";
- }
- switch (value) {
- case Infinity:
- return "Infinity";
- case -Infinity:
- return "-Infinity";
- default:
- return value;
- }
- };
- var serializeDateTime2 = (date5) => date5.toISOString().replace(".000Z", "Z");
- var _json2 = (obj) => {
- if (obj == null) {
- return {};
- }
- if (Array.isArray(obj)) {
- return obj.filter((_) => _ != null).map(_json2);
- }
- if (typeof obj === "object") {
- const target = {};
- for (const key of Object.keys(obj)) {
- if (obj[key] == null) {
- continue;
- }
- target[key] = _json2(obj[key]);
- }
- return target;
- }
- return obj;
- };
- exports.collectBody = protocols.collectBody;
- exports.extendedEncodeURIComponent = protocols.extendedEncodeURIComponent;
- exports.resolvedPath = protocols.resolvedPath;
- exports.Client = Client2;
- exports.Command = Command3;
- exports.NoOpLogger = NoOpLogger3;
- exports.SENSITIVE_STRING = SENSITIVE_STRING3;
- exports.ServiceException = ServiceException2;
- exports._json = _json2;
- exports.convertMap = convertMap2;
- exports.createAggregatedClient = createAggregatedClient2;
- exports.decorateServiceException = decorateServiceException2;
- exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion3;
- exports.getArrayIfSingleItem = getArrayIfSingleItem2;
- exports.getDefaultClientConfiguration = getDefaultClientConfiguration2;
- exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration2;
- exports.getValueFromTextNode = getValueFromTextNode2;
- exports.isSerializableHeaderValue = isSerializableHeaderValue2;
- exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode2;
- exports.map = map3;
- exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig2;
- exports.serializeDateTime = serializeDateTime2;
- exports.serializeFloat = serializeFloat2;
- exports.take = take2;
- exports.throwDefaultError = throwDefaultError2;
- exports.withBaseException = withBaseException2;
- Object.prototype.hasOwnProperty.call(serde3, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: serde3["__proto__"]
- });
- Object.keys(serde3).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = serde3[k];
- });
-});
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
-var require_dist_cjs80 = __commonJS((exports) => {
- var isArrayBuffer3 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
- exports.isArrayBuffer = isArrayBuffer3;
-});
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
-var require_dist_cjs81 = __commonJS((exports) => {
- var isArrayBuffer3 = require_dist_cjs80();
- var buffer = __require("buffer");
- var fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
- if (!isArrayBuffer3.isArrayBuffer(input)) {
- throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
- }
- return buffer.Buffer.from(input, offset, length);
- };
- var fromString = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input);
- };
- exports.fromArrayBuffer = fromArrayBuffer;
- exports.fromString = fromString;
-});
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js
-var require_fromBase644 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.fromBase64 = undefined;
- var util_buffer_from_1 = require_dist_cjs81();
- var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
- var fromBase64 = (input) => {
- if (input.length * 3 % 4 !== 0) {
- throw new TypeError(`Incorrect padding on base64 string.`);
- }
- if (!BASE64_REGEX.exec(input)) {
- throw new TypeError(`Invalid base64 string.`);
- }
- const buffer = (0, util_buffer_from_1.fromString)(input, "base64");
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
- };
- exports.fromBase64 = fromBase64;
-});
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js
-var require_toBase644 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.toBase64 = undefined;
- var util_buffer_from_1 = require_dist_cjs81();
- var util_utf8_1 = require_dist_cjs17();
- var toBase64 = (_input) => {
- let input;
- if (typeof _input === "string") {
- input = (0, util_utf8_1.fromUtf8)(_input);
- } else {
- input = _input;
- }
- if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
- throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
- }
- return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64");
- };
- exports.toBase64 = toBase64;
-});
-
-// node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/index.js
-var require_dist_cjs82 = __commonJS((exports) => {
- var fromBase64 = require_fromBase644();
- var toBase64 = require_toBase644();
- Object.prototype.hasOwnProperty.call(fromBase64, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: fromBase64["__proto__"]
- });
- Object.keys(fromBase64).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = fromBase64[k];
- });
- Object.prototype.hasOwnProperty.call(toBase64, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: toBase64["__proto__"]
- });
- Object.keys(toBase64).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = toBase64[k];
- });
-});
-
-// node_modules/fast-xml-parser/lib/fxp.cjs
-var require_fxp = __commonJS((exports, module) => {
- (() => {
- var t = { d: (e2, i3) => {
- for (var n3 in i3)
- t.o(i3, n3) && !t.o(e2, n3) && Object.defineProperty(e2, n3, { enumerable: true, get: i3[n3] });
- }, o: (t2, e2) => Object.prototype.hasOwnProperty.call(t2, e2), r: (t2) => {
- typeof Symbol != "undefined" && Symbol.toStringTag && Object.defineProperty(t2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t2, "__esModule", { value: true });
- } }, e = {};
- t.r(e), t.d(e, { XMLBuilder: () => $t, XMLParser: () => gt, XMLValidator: () => It });
- const i2 = ":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", n2 = new RegExp("^[" + i2 + "][" + i2 + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");
- function s(t2, e2) {
- const i3 = [];
- let n3 = e2.exec(t2);
- for (;n3; ) {
- const s2 = [];
- s2.startIndex = e2.lastIndex - n3[0].length;
- const r2 = n3.length;
- for (let t3 = 0;t3 < r2; t3++)
- s2.push(n3[t3]);
- i3.push(s2), n3 = e2.exec(t2);
- }
- return i3;
- }
- const r = function(t2) {
- return !(n2.exec(t2) == null);
- }, o2 = ["hasOwnProperty", "toString", "valueOf", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"], a2 = ["__proto__", "constructor", "prototype"], h2 = { allowBooleanAttributes: false, unpairedTags: [] };
- function l(t2, e2) {
- e2 = Object.assign({}, h2, e2);
- const i3 = [];
- let n3 = false, s2 = false;
- t2[0] === "\uFEFF" && (t2 = t2.substr(1));
- for (let r2 = 0;r2 < t2.length; r2++)
- if (t2[r2] === "<" && t2[r2 + 1] === "?") {
- if (r2 += 2, r2 = u2(t2, r2), r2.err)
- return r2;
- } else {
- if (t2[r2] !== "<") {
- if (p(t2[r2]))
- continue;
- return b("InvalidChar", "char '" + t2[r2] + "' is not expected.", w(t2, r2));
- }
- {
- let o3 = r2;
- if (r2++, t2[r2] === "!") {
- r2 = c5(t2, r2);
- continue;
- }
- {
- let a3 = false;
- t2[r2] === "/" && (a3 = true, r2++);
- let h3 = "";
- for (;r2 < t2.length && t2[r2] !== ">" && t2[r2] !== " " && t2[r2] !== "\t" && t2[r2] !== `
-` && t2[r2] !== "\r"; r2++)
- h3 += t2[r2];
- if (h3 = h3.trim(), h3[h3.length - 1] === "/" && (h3 = h3.substring(0, h3.length - 1), r2--), !y2(h3)) {
- let e3;
- return e3 = h3.trim().length === 0 ? "Invalid space after '<'." : "Tag '" + h3 + "' is an invalid name.", b("InvalidTag", e3, w(t2, r2));
- }
- const l2 = g(t2, r2);
- if (l2 === false)
- return b("InvalidAttr", "Attributes for '" + h3 + "' have open quote.", w(t2, r2));
- let d2 = l2.value;
- if (r2 = l2.index, d2[d2.length - 1] === "/") {
- const i4 = r2 - d2.length;
- d2 = d2.substring(0, d2.length - 1);
- const s3 = x2(d2, e2);
- if (s3 !== true)
- return b(s3.err.code, s3.err.msg, w(t2, i4 + s3.err.line));
- n3 = true;
- } else if (a3) {
- if (!l2.tagClosed)
- return b("InvalidTag", "Closing tag '" + h3 + "' doesn't have proper closing.", w(t2, r2));
- if (d2.trim().length > 0)
- return b("InvalidTag", "Closing tag '" + h3 + "' can't have attributes or invalid starting.", w(t2, o3));
- if (i3.length === 0)
- return b("InvalidTag", "Closing tag '" + h3 + "' has not been opened.", w(t2, o3));
- {
- const e3 = i3.pop();
- if (h3 !== e3.tagName) {
- let i4 = w(t2, e3.tagStartPos);
- return b("InvalidTag", "Expected closing tag '" + e3.tagName + "' (opened in line " + i4.line + ", col " + i4.col + ") instead of closing tag '" + h3 + "'.", w(t2, o3));
- }
- i3.length == 0 && (s2 = true);
- }
- } else {
- const a4 = x2(d2, e2);
- if (a4 !== true)
- return b(a4.err.code, a4.err.msg, w(t2, r2 - d2.length + a4.err.line));
- if (s2 === true)
- return b("InvalidXml", "Multiple possible root nodes found.", w(t2, r2));
- e2.unpairedTags.indexOf(h3) !== -1 || i3.push({ tagName: h3, tagStartPos: o3 }), n3 = true;
- }
- for (r2++;r2 < t2.length; r2++)
- if (t2[r2] === "<") {
- if (t2[r2 + 1] === "!") {
- r2++, r2 = c5(t2, r2);
- continue;
- }
- if (t2[r2 + 1] !== "?")
- break;
- if (r2 = u2(t2, ++r2), r2.err)
- return r2;
- } else if (t2[r2] === "&") {
- const e3 = N(t2, r2);
- if (e3 == -1)
- return b("InvalidChar", "char '&' is not expected.", w(t2, r2));
- r2 = e3;
- } else if (s2 === true && !p(t2[r2]))
- return b("InvalidXml", "Extra text at the end", w(t2, r2));
- t2[r2] === "<" && r2--;
- }
- }
- }
- return n3 ? i3.length == 1 ? b("InvalidTag", "Unclosed tag '" + i3[0].tagName + "'.", w(t2, i3[0].tagStartPos)) : !(i3.length > 0) || b("InvalidXml", "Invalid '" + JSON.stringify(i3.map((t3) => t3.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }) : b("InvalidXml", "Start tag expected.", 1);
- }
- function p(t2) {
- return t2 === " " || t2 === "\t" || t2 === `
-` || t2 === "\r";
- }
- function u2(t2, e2) {
- const i3 = e2;
- for (;e2 < t2.length; e2++)
- if (t2[e2] == "?" || t2[e2] == " ") {
- const n3 = t2.substr(i3, e2 - i3);
- if (e2 > 5 && n3 === "xml")
- return b("InvalidXml", "XML declaration allowed only at the start of the document.", w(t2, e2));
- if (t2[e2] == "?" && t2[e2 + 1] == ">") {
- e2++;
- break;
- }
- continue;
- }
- return e2;
- }
- function c5(t2, e2) {
- if (t2.length > e2 + 5 && t2[e2 + 1] === "-" && t2[e2 + 2] === "-") {
- for (e2 += 3;e2 < t2.length; e2++)
- if (t2[e2] === "-" && t2[e2 + 1] === "-" && t2[e2 + 2] === ">") {
- e2 += 2;
- break;
- }
- } else if (t2.length > e2 + 8 && t2[e2 + 1] === "D" && t2[e2 + 2] === "O" && t2[e2 + 3] === "C" && t2[e2 + 4] === "T" && t2[e2 + 5] === "Y" && t2[e2 + 6] === "P" && t2[e2 + 7] === "E") {
- let i3 = 1;
- for (e2 += 8;e2 < t2.length; e2++)
- if (t2[e2] === "<")
- i3++;
- else if (t2[e2] === ">" && (i3--, i3 === 0))
- break;
- } else if (t2.length > e2 + 9 && t2[e2 + 1] === "[" && t2[e2 + 2] === "C" && t2[e2 + 3] === "D" && t2[e2 + 4] === "A" && t2[e2 + 5] === "T" && t2[e2 + 6] === "A" && t2[e2 + 7] === "[") {
- for (e2 += 8;e2 < t2.length; e2++)
- if (t2[e2] === "]" && t2[e2 + 1] === "]" && t2[e2 + 2] === ">") {
- e2 += 2;
- break;
- }
- }
- return e2;
- }
- const d = '"', f = "'";
- function g(t2, e2) {
- let i3 = "", n3 = "", s2 = false;
- for (;e2 < t2.length; e2++) {
- if (t2[e2] === d || t2[e2] === f)
- n3 === "" ? n3 = t2[e2] : n3 !== t2[e2] || (n3 = "");
- else if (t2[e2] === ">" && n3 === "") {
- s2 = true;
- break;
- }
- i3 += t2[e2];
- }
- return n3 === "" && { value: i3, index: e2, tagClosed: s2 };
- }
- const m = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g");
- function x2(t2, e2) {
- const i3 = s(t2, m), n3 = {};
- for (let t3 = 0;t3 < i3.length; t3++) {
- if (i3[t3][1].length === 0)
- return b("InvalidAttr", "Attribute '" + i3[t3][2] + "' has no space in starting.", v(i3[t3]));
- if (i3[t3][3] !== undefined && i3[t3][4] === undefined)
- return b("InvalidAttr", "Attribute '" + i3[t3][2] + "' is without value.", v(i3[t3]));
- if (i3[t3][3] === undefined && !e2.allowBooleanAttributes)
- return b("InvalidAttr", "boolean attribute '" + i3[t3][2] + "' is not allowed.", v(i3[t3]));
- const s2 = i3[t3][2];
- if (!E(s2))
- return b("InvalidAttr", "Attribute '" + s2 + "' is an invalid name.", v(i3[t3]));
- if (Object.prototype.hasOwnProperty.call(n3, s2))
- return b("InvalidAttr", "Attribute '" + s2 + "' is repeated.", v(i3[t3]));
- n3[s2] = 1;
- }
- return true;
- }
- function N(t2, e2) {
- if (t2[++e2] === ";")
- return -1;
- if (t2[e2] === "#")
- return function(t3, e3) {
- let i4 = /\d/;
- for (t3[e3] === "x" && (e3++, i4 = /[\da-fA-F]/);e3 < t3.length; e3++) {
- if (t3[e3] === ";")
- return e3;
- if (!t3[e3].match(i4))
- break;
- }
- return -1;
- }(t2, ++e2);
- let i3 = 0;
- for (;e2 < t2.length; e2++, i3++)
- if (!(t2[e2].match(/\w/) && i3 < 20)) {
- if (t2[e2] === ";")
- break;
- return -1;
- }
- return e2;
- }
- function b(t2, e2, i3) {
- return { err: { code: t2, msg: e2, line: i3.line || i3, col: i3.col } };
- }
- function E(t2) {
- return r(t2);
- }
- function y2(t2) {
- return r(t2);
- }
- function w(t2, e2) {
- const i3 = t2.substring(0, e2).split(/\r?\n/);
- return { line: i3.length, col: i3[i3.length - 1].length + 1 };
- }
- function v(t2) {
- return t2.startIndex + t2[1].length;
- }
- const T = (t2) => o2.includes(t2) ? "__" + t2 : t2, P = { preserveOrder: false, attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, removeNSPrefix: false, allowBooleanAttributes: false, parseTagValue: true, parseAttributeValue: false, trimValues: true, cdataPropName: false, numberParseOptions: { hex: true, leadingZeros: true, eNotation: true }, tagValueProcessor: function(t2, e2) {
- return e2;
- }, attributeValueProcessor: function(t2, e2) {
- return e2;
- }, stopNodes: [], alwaysCreateTextNode: false, isArray: () => false, commentPropName: false, unpairedTags: [], processEntities: true, htmlEntities: false, ignoreDeclaration: false, ignorePiTags: false, transformTagName: false, transformAttributeName: false, updateTag: function(t2, e2, i3) {
- return t2;
- }, captureMetaData: false, maxNestedTags: 100, strictReservedNames: true, jPath: true, onDangerousProperty: T };
- function S(t2, e2) {
- if (typeof t2 != "string")
- return;
- const i3 = t2.toLowerCase();
- if (o2.some((t3) => i3 === t3.toLowerCase()))
- throw new Error(`[SECURITY] Invalid ${e2}: "${t2}" is a reserved JavaScript keyword that could cause prototype pollution`);
- if (a2.some((t3) => i3 === t3.toLowerCase()))
- throw new Error(`[SECURITY] Invalid ${e2}: "${t2}" is a reserved JavaScript keyword that could cause prototype pollution`);
- }
- function A(t2) {
- return typeof t2 == "boolean" ? { enabled: t2, maxEntitySize: 1e4, maxExpansionDepth: 10, maxTotalExpansions: 1000, maxExpandedLength: 1e5, maxEntityCount: 100, allowedTags: null, tagFilter: null } : typeof t2 == "object" && t2 !== null ? { enabled: t2.enabled !== false, maxEntitySize: Math.max(1, t2.maxEntitySize ?? 1e4), maxExpansionDepth: Math.max(1, t2.maxExpansionDepth ?? 10), maxTotalExpansions: Math.max(1, t2.maxTotalExpansions ?? 1000), maxExpandedLength: Math.max(1, t2.maxExpandedLength ?? 1e5), maxEntityCount: Math.max(1, t2.maxEntityCount ?? 100), allowedTags: t2.allowedTags ?? null, tagFilter: t2.tagFilter ?? null } : A(true);
- }
- const O = function(t2) {
- const e2 = Object.assign({}, P, t2), i3 = [{ value: e2.attributeNamePrefix, name: "attributeNamePrefix" }, { value: e2.attributesGroupName, name: "attributesGroupName" }, { value: e2.textNodeName, name: "textNodeName" }, { value: e2.cdataPropName, name: "cdataPropName" }, { value: e2.commentPropName, name: "commentPropName" }];
- for (const { value: t3, name: e3 } of i3)
- t3 && S(t3, e3);
- return e2.onDangerousProperty === null && (e2.onDangerousProperty = T), e2.processEntities = A(e2.processEntities), e2.stopNodes && Array.isArray(e2.stopNodes) && (e2.stopNodes = e2.stopNodes.map((t3) => typeof t3 == "string" && t3.startsWith("*.") ? ".." + t3.substring(2) : t3)), e2;
- };
- let C2;
- C2 = typeof Symbol != "function" ? "@@xmlMetadata" : Symbol("XML Node Metadata");
-
- class $2 {
- constructor(t2) {
- this.tagname = t2, this.child = [], this[":@"] = Object.create(null);
- }
- add(t2, e2) {
- t2 === "__proto__" && (t2 = "#__proto__"), this.child.push({ [t2]: e2 });
- }
- addChild(t2, e2) {
- t2.tagname === "__proto__" && (t2.tagname = "#__proto__"), t2[":@"] && Object.keys(t2[":@"]).length > 0 ? this.child.push({ [t2.tagname]: t2.child, ":@": t2[":@"] }) : this.child.push({ [t2.tagname]: t2.child }), e2 !== undefined && (this.child[this.child.length - 1][C2] = { startIndex: e2 });
- }
- static getMetaDataSymbol() {
- return C2;
- }
- }
-
- class I2 {
- constructor(t2) {
- this.suppressValidationErr = !t2, this.options = t2;
- }
- readDocType(t2, e2) {
- const i3 = Object.create(null);
- let n3 = 0;
- if (t2[e2 + 3] !== "O" || t2[e2 + 4] !== "C" || t2[e2 + 5] !== "T" || t2[e2 + 6] !== "Y" || t2[e2 + 7] !== "P" || t2[e2 + 8] !== "E")
- throw new Error("Invalid Tag instead of DOCTYPE");
- {
- e2 += 9;
- let s2 = 1, r2 = false, o3 = false, a3 = "";
- for (;e2 < t2.length; e2++)
- if (t2[e2] !== "<" || o3)
- if (t2[e2] === ">") {
- if (o3 ? t2[e2 - 1] === "-" && t2[e2 - 2] === "-" && (o3 = false, s2--) : s2--, s2 === 0)
- break;
- } else
- t2[e2] === "[" ? r2 = true : a3 += t2[e2];
- else {
- if (r2 && M2(t2, "!ENTITY", e2)) {
- let s3, r3;
- if (e2 += 7, [s3, r3, e2] = this.readEntityExp(t2, e2 + 1, this.suppressValidationErr), r3.indexOf("&") === -1) {
- if (this.options.enabled !== false && this.options.maxEntityCount != null && n3 >= this.options.maxEntityCount)
- throw new Error(`Entity count (${n3 + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`);
- const t3 = s3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
- i3[s3] = { regx: RegExp(`&${t3};`, "g"), val: r3 }, n3++;
- }
- } else if (r2 && M2(t2, "!ELEMENT", e2)) {
- e2 += 8;
- const { index: i4 } = this.readElementExp(t2, e2 + 1);
- e2 = i4;
- } else if (r2 && M2(t2, "!ATTLIST", e2))
- e2 += 8;
- else if (r2 && M2(t2, "!NOTATION", e2)) {
- e2 += 9;
- const { index: i4 } = this.readNotationExp(t2, e2 + 1, this.suppressValidationErr);
- e2 = i4;
- } else {
- if (!M2(t2, "!--", e2))
- throw new Error("Invalid DOCTYPE");
- o3 = true;
- }
- s2++, a3 = "";
- }
- if (s2 !== 0)
- throw new Error("Unclosed DOCTYPE");
- }
- return { entities: i3, i: e2 };
- }
- readEntityExp(t2, e2) {
- const i3 = e2 = j(t2, e2);
- for (;e2 < t2.length && !/\s/.test(t2[e2]) && t2[e2] !== '"' && t2[e2] !== "'"; )
- e2++;
- let n3 = t2.substring(i3, e2);
- if (_(n3), e2 = j(t2, e2), !this.suppressValidationErr) {
- if (t2.substring(e2, e2 + 6).toUpperCase() === "SYSTEM")
- throw new Error("External entities are not supported");
- if (t2[e2] === "%")
- throw new Error("Parameter entities are not supported");
- }
- let s2 = "";
- if ([e2, s2] = this.readIdentifierVal(t2, e2, "entity"), this.options.enabled !== false && this.options.maxEntitySize != null && s2.length > this.options.maxEntitySize)
- throw new Error(`Entity "${n3}" size (${s2.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);
- return [n3, s2, --e2];
- }
- readNotationExp(t2, e2) {
- const i3 = e2 = j(t2, e2);
- for (;e2 < t2.length && !/\s/.test(t2[e2]); )
- e2++;
- let n3 = t2.substring(i3, e2);
- !this.suppressValidationErr && _(n3), e2 = j(t2, e2);
- const s2 = t2.substring(e2, e2 + 6).toUpperCase();
- if (!this.suppressValidationErr && s2 !== "SYSTEM" && s2 !== "PUBLIC")
- throw new Error(`Expected SYSTEM or PUBLIC, found "${s2}"`);
- e2 += s2.length, e2 = j(t2, e2);
- let r2 = null, o3 = null;
- if (s2 === "PUBLIC")
- [e2, r2] = this.readIdentifierVal(t2, e2, "publicIdentifier"), t2[e2 = j(t2, e2)] !== '"' && t2[e2] !== "'" || ([e2, o3] = this.readIdentifierVal(t2, e2, "systemIdentifier"));
- else if (s2 === "SYSTEM" && ([e2, o3] = this.readIdentifierVal(t2, e2, "systemIdentifier"), !this.suppressValidationErr && !o3))
- throw new Error("Missing mandatory system identifier for SYSTEM notation");
- return { notationName: n3, publicIdentifier: r2, systemIdentifier: o3, index: --e2 };
- }
- readIdentifierVal(t2, e2, i3) {
- let n3 = "";
- const s2 = t2[e2];
- if (s2 !== '"' && s2 !== "'")
- throw new Error(`Expected quoted string, found "${s2}"`);
- const r2 = ++e2;
- for (;e2 < t2.length && t2[e2] !== s2; )
- e2++;
- if (n3 = t2.substring(r2, e2), t2[e2] !== s2)
- throw new Error(`Unterminated ${i3} value`);
- return [++e2, n3];
- }
- readElementExp(t2, e2) {
- const i3 = e2 = j(t2, e2);
- for (;e2 < t2.length && !/\s/.test(t2[e2]); )
- e2++;
- let n3 = t2.substring(i3, e2);
- if (!this.suppressValidationErr && !r(n3))
- throw new Error(`Invalid element name: "${n3}"`);
- let s2 = "";
- if (t2[e2 = j(t2, e2)] === "E" && M2(t2, "MPTY", e2))
- e2 += 4;
- else if (t2[e2] === "A" && M2(t2, "NY", e2))
- e2 += 2;
- else if (t2[e2] === "(") {
- const i4 = ++e2;
- for (;e2 < t2.length && t2[e2] !== ")"; )
- e2++;
- if (s2 = t2.substring(i4, e2), t2[e2] !== ")")
- throw new Error("Unterminated content model");
- } else if (!this.suppressValidationErr)
- throw new Error(`Invalid Element Expression, found "${t2[e2]}"`);
- return { elementName: n3, contentModel: s2.trim(), index: e2 };
- }
- readAttlistExp(t2, e2) {
- let i3 = e2 = j(t2, e2);
- for (;e2 < t2.length && !/\s/.test(t2[e2]); )
- e2++;
- let n3 = t2.substring(i3, e2);
- for (_(n3), i3 = e2 = j(t2, e2);e2 < t2.length && !/\s/.test(t2[e2]); )
- e2++;
- let s2 = t2.substring(i3, e2);
- if (!_(s2))
- throw new Error(`Invalid attribute name: "${s2}"`);
- e2 = j(t2, e2);
- let r2 = "";
- if (t2.substring(e2, e2 + 8).toUpperCase() === "NOTATION") {
- if (r2 = "NOTATION", t2[e2 = j(t2, e2 += 8)] !== "(")
- throw new Error(`Expected '(', found "${t2[e2]}"`);
- e2++;
- let i4 = [];
- for (;e2 < t2.length && t2[e2] !== ")"; ) {
- const n4 = e2;
- for (;e2 < t2.length && t2[e2] !== "|" && t2[e2] !== ")"; )
- e2++;
- let s3 = t2.substring(n4, e2);
- if (s3 = s3.trim(), !_(s3))
- throw new Error(`Invalid notation name: "${s3}"`);
- i4.push(s3), t2[e2] === "|" && (e2++, e2 = j(t2, e2));
- }
- if (t2[e2] !== ")")
- throw new Error("Unterminated list of notations");
- e2++, r2 += " (" + i4.join("|") + ")";
- } else {
- const i4 = e2;
- for (;e2 < t2.length && !/\s/.test(t2[e2]); )
- e2++;
- r2 += t2.substring(i4, e2);
- const n4 = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"];
- if (!this.suppressValidationErr && !n4.includes(r2.toUpperCase()))
- throw new Error(`Invalid attribute type: "${r2}"`);
- }
- e2 = j(t2, e2);
- let o3 = "";
- return t2.substring(e2, e2 + 8).toUpperCase() === "#REQUIRED" ? (o3 = "#REQUIRED", e2 += 8) : t2.substring(e2, e2 + 7).toUpperCase() === "#IMPLIED" ? (o3 = "#IMPLIED", e2 += 7) : [e2, o3] = this.readIdentifierVal(t2, e2, "ATTLIST"), { elementName: n3, attributeName: s2, attributeType: r2, defaultValue: o3, index: e2 };
- }
- }
- const j = (t2, e2) => {
- for (;e2 < t2.length && /\s/.test(t2[e2]); )
- e2++;
- return e2;
- };
- function M2(t2, e2, i3) {
- for (let n3 = 0;n3 < e2.length; n3++)
- if (e2[n3] !== t2[i3 + n3 + 1])
- return false;
- return true;
- }
- function _(t2) {
- if (r(t2))
- return t2;
- throw new Error(`Invalid entity name ${t2}`);
- }
- const D2 = /^[-+]?0x[a-fA-F0-9]+$/, V = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/, k = { hex: true, leadingZeros: true, decimalPoint: ".", eNotation: true, infinity: "original" };
- const F = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/, L2 = new Set(["push", "pop", "reset", "updateCurrent", "restore"]);
-
- class G3 {
- constructor(t2 = {}) {
- this.separator = t2.separator || ".", this.path = [], this.siblingStacks = [];
- }
- push(t2, e2 = null, i3 = null) {
- this.path.length > 0 && (this.path[this.path.length - 1].values = undefined);
- const n3 = this.path.length;
- this.siblingStacks[n3] || (this.siblingStacks[n3] = new Map);
- const s2 = this.siblingStacks[n3], r2 = i3 ? `${i3}:${t2}` : t2, o3 = s2.get(r2) || 0;
- let a3 = 0;
- for (const t3 of s2.values())
- a3 += t3;
- s2.set(r2, o3 + 1);
- const h3 = { tag: t2, position: a3, counter: o3 };
- i3 != null && (h3.namespace = i3), e2 != null && (h3.values = e2), this.path.push(h3);
- }
- pop() {
- if (this.path.length === 0)
- return;
- const t2 = this.path.pop();
- return this.siblingStacks.length > this.path.length + 1 && (this.siblingStacks.length = this.path.length + 1), t2;
- }
- updateCurrent(t2) {
- if (this.path.length > 0) {
- const e2 = this.path[this.path.length - 1];
- t2 != null && (e2.values = t2);
- }
- }
- getCurrentTag() {
- return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined;
- }
- getCurrentNamespace() {
- return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined;
- }
- getAttrValue(t2) {
- if (this.path.length === 0)
- return;
- const e2 = this.path[this.path.length - 1];
- return e2.values?.[t2];
- }
- hasAttr(t2) {
- if (this.path.length === 0)
- return false;
- const e2 = this.path[this.path.length - 1];
- return e2.values !== undefined && t2 in e2.values;
- }
- getPosition() {
- return this.path.length === 0 ? -1 : this.path[this.path.length - 1].position ?? 0;
- }
- getCounter() {
- return this.path.length === 0 ? -1 : this.path[this.path.length - 1].counter ?? 0;
- }
- getIndex() {
- return this.getPosition();
- }
- getDepth() {
- return this.path.length;
- }
- toString(t2, e2 = true) {
- const i3 = t2 || this.separator;
- return this.path.map((t3) => e2 && t3.namespace ? `${t3.namespace}:${t3.tag}` : t3.tag).join(i3);
- }
- toArray() {
- return this.path.map((t2) => t2.tag);
- }
- reset() {
- this.path = [], this.siblingStacks = [];
- }
- matches(t2) {
- const e2 = t2.segments;
- return e2.length !== 0 && (t2.hasDeepWildcard() ? this._matchWithDeepWildcard(e2) : this._matchSimple(e2));
- }
- _matchSimple(t2) {
- if (this.path.length !== t2.length)
- return false;
- for (let e2 = 0;e2 < t2.length; e2++) {
- const i3 = t2[e2], n3 = this.path[e2], s2 = e2 === this.path.length - 1;
- if (!this._matchSegment(i3, n3, s2))
- return false;
- }
- return true;
- }
- _matchWithDeepWildcard(t2) {
- let e2 = this.path.length - 1, i3 = t2.length - 1;
- for (;i3 >= 0 && e2 >= 0; ) {
- const n3 = t2[i3];
- if (n3.type === "deep-wildcard") {
- if (i3--, i3 < 0)
- return true;
- const n4 = t2[i3];
- let s2 = false;
- for (let t3 = e2;t3 >= 0; t3--) {
- const r2 = t3 === this.path.length - 1;
- if (this._matchSegment(n4, this.path[t3], r2)) {
- e2 = t3 - 1, i3--, s2 = true;
- break;
- }
- }
- if (!s2)
- return false;
- } else {
- const t3 = e2 === this.path.length - 1;
- if (!this._matchSegment(n3, this.path[e2], t3))
- return false;
- e2--, i3--;
- }
- }
- return i3 < 0;
- }
- _matchSegment(t2, e2, i3) {
- if (t2.tag !== "*" && t2.tag !== e2.tag)
- return false;
- if (t2.namespace !== undefined && t2.namespace !== "*" && t2.namespace !== e2.namespace)
- return false;
- if (t2.attrName !== undefined) {
- if (!i3)
- return false;
- if (!e2.values || !(t2.attrName in e2.values))
- return false;
- if (t2.attrValue !== undefined) {
- const i4 = e2.values[t2.attrName];
- if (String(i4) !== String(t2.attrValue))
- return false;
- }
- }
- if (t2.position !== undefined) {
- if (!i3)
- return false;
- const n3 = e2.counter ?? 0;
- if (t2.position === "first" && n3 !== 0)
- return false;
- if (t2.position === "odd" && n3 % 2 != 1)
- return false;
- if (t2.position === "even" && n3 % 2 != 0)
- return false;
- if (t2.position === "nth" && n3 !== t2.positionValue)
- return false;
- }
- return true;
- }
- snapshot() {
- return { path: this.path.map((t2) => ({ ...t2 })), siblingStacks: this.siblingStacks.map((t2) => new Map(t2)) };
- }
- restore(t2) {
- this.path = t2.path.map((t3) => ({ ...t3 })), this.siblingStacks = t2.siblingStacks.map((t3) => new Map(t3));
- }
- readOnly() {
- return new Proxy(this, { get(t2, e2, i3) {
- if (L2.has(e2))
- return () => {
- throw new TypeError(`Cannot call '${e2}' on a read-only Matcher. Obtain a writable instance to mutate state.`);
- };
- const n3 = Reflect.get(t2, e2, i3);
- return e2 === "path" || e2 === "siblingStacks" ? Object.freeze(Array.isArray(n3) ? n3.map((t3) => t3 instanceof Map ? Object.freeze(new Map(t3)) : Object.freeze({ ...t3 })) : n3) : typeof n3 == "function" ? n3.bind(t2) : n3;
- }, set(t2, e2) {
- throw new TypeError(`Cannot set property '${String(e2)}' on a read-only Matcher.`);
- }, deleteProperty(t2, e2) {
- throw new TypeError(`Cannot delete property '${String(e2)}' from a read-only Matcher.`);
- } });
- }
- }
-
- class R2 {
- constructor(t2, e2 = {}) {
- this.pattern = t2, this.separator = e2.separator || ".", this.segments = this._parse(t2), this._hasDeepWildcard = this.segments.some((t3) => t3.type === "deep-wildcard"), this._hasAttributeCondition = this.segments.some((t3) => t3.attrName !== undefined), this._hasPositionSelector = this.segments.some((t3) => t3.position !== undefined);
- }
- _parse(t2) {
- const e2 = [];
- let i3 = 0, n3 = "";
- for (;i3 < t2.length; )
- t2[i3] === this.separator ? i3 + 1 < t2.length && t2[i3 + 1] === this.separator ? (n3.trim() && (e2.push(this._parseSegment(n3.trim())), n3 = ""), e2.push({ type: "deep-wildcard" }), i3 += 2) : (n3.trim() && e2.push(this._parseSegment(n3.trim())), n3 = "", i3++) : (n3 += t2[i3], i3++);
- return n3.trim() && e2.push(this._parseSegment(n3.trim())), e2;
- }
- _parseSegment(t2) {
- const e2 = { type: "tag" };
- let i3 = null, n3 = t2;
- const s2 = t2.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);
- if (s2 && (n3 = s2[1] + s2[3], s2[2])) {
- const t3 = s2[2].slice(1, -1);
- t3 && (i3 = t3);
- }
- let r2, o3, a3 = n3;
- if (n3.includes("::")) {
- const e3 = n3.indexOf("::");
- if (r2 = n3.substring(0, e3).trim(), a3 = n3.substring(e3 + 2).trim(), !r2)
- throw new Error(`Invalid namespace in pattern: ${t2}`);
- }
- let h3 = null;
- if (a3.includes(":")) {
- const t3 = a3.lastIndexOf(":"), e3 = a3.substring(0, t3).trim(), i4 = a3.substring(t3 + 1).trim();
- ["first", "last", "odd", "even"].includes(i4) || /^nth\(\d+\)$/.test(i4) ? (o3 = e3, h3 = i4) : o3 = a3;
- } else
- o3 = a3;
- if (!o3)
- throw new Error(`Invalid segment pattern: ${t2}`);
- if (e2.tag = o3, r2 && (e2.namespace = r2), i3)
- if (i3.includes("=")) {
- const t3 = i3.indexOf("=");
- e2.attrName = i3.substring(0, t3).trim(), e2.attrValue = i3.substring(t3 + 1).trim();
- } else
- e2.attrName = i3.trim();
- if (h3) {
- const t3 = h3.match(/^nth\((\d+)\)$/);
- t3 ? (e2.position = "nth", e2.positionValue = parseInt(t3[1], 10)) : e2.position = h3;
- }
- return e2;
- }
- get length() {
- return this.segments.length;
- }
- hasDeepWildcard() {
- return this._hasDeepWildcard;
- }
- hasAttributeCondition() {
- return this._hasAttributeCondition;
- }
- hasPositionSelector() {
- return this._hasPositionSelector;
- }
- toString() {
- return this.pattern;
- }
- }
- function U2(t2, e2) {
- if (!t2)
- return {};
- const i3 = e2.attributesGroupName ? t2[e2.attributesGroupName] : t2;
- if (!i3)
- return {};
- const n3 = {};
- for (const t3 in i3)
- t3.startsWith(e2.attributeNamePrefix) ? n3[t3.substring(e2.attributeNamePrefix.length)] = i3[t3] : n3[t3] = i3[t3];
- return n3;
- }
- function B(t2) {
- if (!t2 || typeof t2 != "string")
- return;
- const e2 = t2.indexOf(":");
- if (e2 !== -1 && e2 > 0) {
- const i3 = t2.substring(0, e2);
- if (i3 !== "xmlns")
- return i3;
- }
- }
-
- class W2 {
- constructor(t2) {
- var e2;
- if (this.options = t2, this.currentNode = null, this.tagsNodeStack = [], this.docTypeEntities = {}, this.lastEntities = { apos: { regex: /&(apos|#39|#x27);/g, val: "'" }, gt: { regex: /&(gt|#62|#x3E);/g, val: ">" }, lt: { regex: /&(lt|#60|#x3C);/g, val: "<" }, quot: { regex: /&(quot|#34|#x22);/g, val: '"' } }, this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }, this.htmlEntities = { space: { regex: /&(nbsp|#160);/g, val: " " }, cent: { regex: /&(cent|#162);/g, val: "\xA2" }, pound: { regex: /&(pound|#163);/g, val: "\xA3" }, yen: { regex: /&(yen|#165);/g, val: "\xA5" }, euro: { regex: /&(euro|#8364);/g, val: "\u20AC" }, copyright: { regex: /&(copy|#169);/g, val: "\xA9" }, reg: { regex: /&(reg|#174);/g, val: "\xAE" }, inr: { regex: /&(inr|#8377);/g, val: "\u20B9" }, num_dec: { regex: /([0-9]{1,7});/g, val: (t3, e3) => rt(e3, 10, "") }, num_hex: { regex: /([0-9a-fA-F]{1,6});/g, val: (t3, e3) => rt(e3, 16, "") } }, this.addExternalEntities = Y, this.parseXml = J, this.parseTextData = z2, this.resolveNameSpace = X, this.buildAttributesMap = Z, this.isItStopNode = tt, this.replaceEntitiesValue = Q, this.readStopNodeData = nt, this.saveTextToParentTag = H2, this.addChild = K, this.ignoreAttributesFn = typeof (e2 = this.options.ignoreAttributes) == "function" ? e2 : Array.isArray(e2) ? (t3) => {
- for (const i3 of e2) {
- if (typeof i3 == "string" && t3 === i3)
- return true;
- if (i3 instanceof RegExp && i3.test(t3))
- return true;
- }
- } : () => false, this.entityExpansionCount = 0, this.currentExpandedLength = 0, this.matcher = new G3, this.readonlyMatcher = this.matcher.readOnly(), this.isCurrentNodeStopNode = false, this.options.stopNodes && this.options.stopNodes.length > 0) {
- this.stopNodeExpressions = [];
- for (let t3 = 0;t3 < this.options.stopNodes.length; t3++) {
- const e3 = this.options.stopNodes[t3];
- typeof e3 == "string" ? this.stopNodeExpressions.push(new R2(e3)) : e3 instanceof R2 && this.stopNodeExpressions.push(e3);
- }
- }
- }
- }
- function Y(t2) {
- const e2 = Object.keys(t2);
- for (let i3 = 0;i3 < e2.length; i3++) {
- const n3 = e2[i3], s2 = n3.replace(/[.\-+*:]/g, "\\.");
- this.lastEntities[n3] = { regex: new RegExp("&" + s2 + ";", "g"), val: t2[n3] };
- }
- }
- function z2(t2, e2, i3, n3, s2, r2, o3) {
- if (t2 !== undefined && (this.options.trimValues && !n3 && (t2 = t2.trim()), t2.length > 0)) {
- o3 || (t2 = this.replaceEntitiesValue(t2, e2, i3));
- const n4 = this.options.jPath ? i3.toString() : i3, a3 = this.options.tagValueProcessor(e2, t2, n4, s2, r2);
- return a3 == null ? t2 : typeof a3 != typeof t2 || a3 !== t2 ? a3 : this.options.trimValues || t2.trim() === t2 ? st(t2, this.options.parseTagValue, this.options.numberParseOptions) : t2;
- }
- }
- function X(t2) {
- if (this.options.removeNSPrefix) {
- const e2 = t2.split(":"), i3 = t2.charAt(0) === "/" ? "/" : "";
- if (e2[0] === "xmlns")
- return "";
- e2.length === 2 && (t2 = i3 + e2[1]);
- }
- return t2;
- }
- const q = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm");
- function Z(t2, e2, i3) {
- if (this.options.ignoreAttributes !== true && typeof t2 == "string") {
- const n3 = s(t2, q), r2 = n3.length, o3 = {}, a3 = {};
- for (let t3 = 0;t3 < r2; t3++) {
- const e3 = this.resolveNameSpace(n3[t3][1]), s2 = n3[t3][4];
- if (e3.length && s2 !== undefined) {
- let t4 = s2;
- this.options.trimValues && (t4 = t4.trim()), t4 = this.replaceEntitiesValue(t4, i3, this.readonlyMatcher), a3[e3] = t4;
- }
- }
- Object.keys(a3).length > 0 && typeof e2 == "object" && e2.updateCurrent && e2.updateCurrent(a3);
- for (let t3 = 0;t3 < r2; t3++) {
- const s2 = this.resolveNameSpace(n3[t3][1]), r3 = this.options.jPath ? e2.toString() : this.readonlyMatcher;
- if (this.ignoreAttributesFn(s2, r3))
- continue;
- let a4 = n3[t3][4], h3 = this.options.attributeNamePrefix + s2;
- if (s2.length)
- if (this.options.transformAttributeName && (h3 = this.options.transformAttributeName(h3)), h3 = at(h3, this.options), a4 !== undefined) {
- this.options.trimValues && (a4 = a4.trim()), a4 = this.replaceEntitiesValue(a4, i3, this.readonlyMatcher);
- const t4 = this.options.jPath ? e2.toString() : this.readonlyMatcher, n4 = this.options.attributeValueProcessor(s2, a4, t4);
- o3[h3] = n4 == null ? a4 : typeof n4 != typeof a4 || n4 !== a4 ? n4 : st(a4, this.options.parseAttributeValue, this.options.numberParseOptions);
- } else
- this.options.allowBooleanAttributes && (o3[h3] = true);
- }
- if (!Object.keys(o3).length)
- return;
- if (this.options.attributesGroupName) {
- const t3 = {};
- return t3[this.options.attributesGroupName] = o3, t3;
- }
- return o3;
- }
- }
- const J = function(t2) {
- t2 = t2.replace(/\r\n?/g, `
-`);
- const e2 = new $2("!xml");
- let i3 = e2, n3 = "";
- this.matcher.reset(), this.entityExpansionCount = 0, this.currentExpandedLength = 0;
- const s2 = new I2(this.options.processEntities);
- for (let r2 = 0;r2 < t2.length; r2++)
- if (t2[r2] === "<")
- if (t2[r2 + 1] === "/") {
- const e3 = et(t2, ">", r2, "Closing Tag is not closed.");
- let s3 = t2.substring(r2 + 2, e3).trim();
- if (this.options.removeNSPrefix) {
- const t3 = s3.indexOf(":");
- t3 !== -1 && (s3 = s3.substr(t3 + 1));
- }
- s3 = ot(this.options.transformTagName, s3, "", this.options).tagName, i3 && (n3 = this.saveTextToParentTag(n3, i3, this.readonlyMatcher));
- const o3 = this.matcher.getCurrentTag();
- if (s3 && this.options.unpairedTags.indexOf(s3) !== -1)
- throw new Error(`Unpaired tag can not be used as closing tag: ${s3}>`);
- o3 && this.options.unpairedTags.indexOf(o3) !== -1 && (this.matcher.pop(), this.tagsNodeStack.pop()), this.matcher.pop(), this.isCurrentNodeStopNode = false, i3 = this.tagsNodeStack.pop(), n3 = "", r2 = e3;
- } else if (t2[r2 + 1] === "?") {
- let e3 = it(t2, r2, false, "?>");
- if (!e3)
- throw new Error("Pi Tag is not closed.");
- if (n3 = this.saveTextToParentTag(n3, i3, this.readonlyMatcher), this.options.ignoreDeclaration && e3.tagName === "?xml" || this.options.ignorePiTags)
- ;
- else {
- const t3 = new $2(e3.tagName);
- t3.add(this.options.textNodeName, ""), e3.tagName !== e3.tagExp && e3.attrExpPresent && (t3[":@"] = this.buildAttributesMap(e3.tagExp, this.matcher, e3.tagName)), this.addChild(i3, t3, this.readonlyMatcher, r2);
- }
- r2 = e3.closeIndex + 1;
- } else if (t2.substr(r2 + 1, 3) === "!--") {
- const e3 = et(t2, "-->", r2 + 4, "Comment is not closed.");
- if (this.options.commentPropName) {
- const s3 = t2.substring(r2 + 4, e3 - 2);
- n3 = this.saveTextToParentTag(n3, i3, this.readonlyMatcher), i3.add(this.options.commentPropName, [{ [this.options.textNodeName]: s3 }]);
- }
- r2 = e3;
- } else if (t2.substr(r2 + 1, 2) === "!D") {
- const e3 = s2.readDocType(t2, r2);
- this.docTypeEntities = e3.entities, r2 = e3.i;
- } else if (t2.substr(r2 + 1, 2) === "![") {
- const e3 = et(t2, "]]>", r2, "CDATA is not closed.") - 2, s3 = t2.substring(r2 + 9, e3);
- n3 = this.saveTextToParentTag(n3, i3, this.readonlyMatcher);
- let o3 = this.parseTextData(s3, i3.tagname, this.readonlyMatcher, true, false, true, true);
- o3 == null && (o3 = ""), this.options.cdataPropName ? i3.add(this.options.cdataPropName, [{ [this.options.textNodeName]: s3 }]) : i3.add(this.options.textNodeName, o3), r2 = e3 + 2;
- } else {
- let s3 = it(t2, r2, this.options.removeNSPrefix);
- if (!s3) {
- const e3 = t2.substring(Math.max(0, r2 - 50), Math.min(t2.length, r2 + 50));
- throw new Error(`readTagExp returned undefined at position ${r2}. Context: "${e3}"`);
- }
- let o3 = s3.tagName;
- const a3 = s3.rawTagName;
- let { tagExp: h3, attrExpPresent: l2, closeIndex: p2 } = s3;
- if ({ tagName: o3, tagExp: h3 } = ot(this.options.transformTagName, o3, h3, this.options), this.options.strictReservedNames && (o3 === this.options.commentPropName || o3 === this.options.cdataPropName || o3 === this.options.textNodeName || o3 === this.options.attributesGroupName))
- throw new Error(`Invalid tag name: ${o3}`);
- i3 && n3 && i3.tagname !== "!xml" && (n3 = this.saveTextToParentTag(n3, i3, this.readonlyMatcher, false));
- const u3 = i3;
- u3 && this.options.unpairedTags.indexOf(u3.tagname) !== -1 && (i3 = this.tagsNodeStack.pop(), this.matcher.pop());
- let c6 = false;
- h3.length > 0 && h3.lastIndexOf("/") === h3.length - 1 && (c6 = true, o3[o3.length - 1] === "/" ? (o3 = o3.substr(0, o3.length - 1), h3 = o3) : h3 = h3.substr(0, h3.length - 1), l2 = o3 !== h3);
- let d2, f2 = null, g2 = {};
- d2 = B(a3), o3 !== e2.tagname && this.matcher.push(o3, {}, d2), o3 !== h3 && l2 && (f2 = this.buildAttributesMap(h3, this.matcher, o3), f2 && (g2 = U2(f2, this.options))), o3 !== e2.tagname && (this.isCurrentNodeStopNode = this.isItStopNode(this.stopNodeExpressions, this.matcher));
- const m2 = r2;
- if (this.isCurrentNodeStopNode) {
- let e3 = "";
- if (c6)
- r2 = s3.closeIndex;
- else if (this.options.unpairedTags.indexOf(o3) !== -1)
- r2 = s3.closeIndex;
- else {
- const i4 = this.readStopNodeData(t2, a3, p2 + 1);
- if (!i4)
- throw new Error(`Unexpected end of ${a3}`);
- r2 = i4.i, e3 = i4.tagContent;
- }
- const n4 = new $2(o3);
- f2 && (n4[":@"] = f2), n4.add(this.options.textNodeName, e3), this.matcher.pop(), this.isCurrentNodeStopNode = false, this.addChild(i3, n4, this.readonlyMatcher, m2);
- } else {
- if (c6) {
- ({ tagName: o3, tagExp: h3 } = ot(this.options.transformTagName, o3, h3, this.options));
- const t3 = new $2(o3);
- f2 && (t3[":@"] = f2), this.addChild(i3, t3, this.readonlyMatcher, m2), this.matcher.pop(), this.isCurrentNodeStopNode = false;
- } else {
- if (this.options.unpairedTags.indexOf(o3) !== -1) {
- const t3 = new $2(o3);
- f2 && (t3[":@"] = f2), this.addChild(i3, t3, this.readonlyMatcher, m2), this.matcher.pop(), this.isCurrentNodeStopNode = false, r2 = s3.closeIndex;
- continue;
- }
- {
- const t3 = new $2(o3);
- if (this.tagsNodeStack.length > this.options.maxNestedTags)
- throw new Error("Maximum nested tags exceeded");
- this.tagsNodeStack.push(i3), f2 && (t3[":@"] = f2), this.addChild(i3, t3, this.readonlyMatcher, m2), i3 = t3;
- }
- }
- n3 = "", r2 = p2;
- }
- }
- else
- n3 += t2[r2];
- return e2.child;
- };
- function K(t2, e2, i3, n3) {
- this.options.captureMetaData || (n3 = undefined);
- const s2 = this.options.jPath ? i3.toString() : i3, r2 = this.options.updateTag(e2.tagname, s2, e2[":@"]);
- r2 === false || (typeof r2 == "string" ? (e2.tagname = r2, t2.addChild(e2, n3)) : t2.addChild(e2, n3));
- }
- function Q(t2, e2, i3) {
- const n3 = this.options.processEntities;
- if (!n3 || !n3.enabled)
- return t2;
- if (n3.allowedTags) {
- const s2 = this.options.jPath ? i3.toString() : i3;
- if (!(Array.isArray(n3.allowedTags) ? n3.allowedTags.includes(e2) : n3.allowedTags(e2, s2)))
- return t2;
- }
- if (n3.tagFilter) {
- const s2 = this.options.jPath ? i3.toString() : i3;
- if (!n3.tagFilter(e2, s2))
- return t2;
- }
- for (const e3 of Object.keys(this.docTypeEntities)) {
- const i4 = this.docTypeEntities[e3], s2 = t2.match(i4.regx);
- if (s2) {
- if (this.entityExpansionCount += s2.length, n3.maxTotalExpansions && this.entityExpansionCount > n3.maxTotalExpansions)
- throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n3.maxTotalExpansions}`);
- const e4 = t2.length;
- if (t2 = t2.replace(i4.regx, i4.val), n3.maxExpandedLength && (this.currentExpandedLength += t2.length - e4, this.currentExpandedLength > n3.maxExpandedLength))
- throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${n3.maxExpandedLength}`);
- }
- }
- for (const e3 of Object.keys(this.lastEntities)) {
- const i4 = this.lastEntities[e3], s2 = t2.match(i4.regex);
- if (s2 && (this.entityExpansionCount += s2.length, n3.maxTotalExpansions && this.entityExpansionCount > n3.maxTotalExpansions))
- throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n3.maxTotalExpansions}`);
- t2 = t2.replace(i4.regex, i4.val);
- }
- if (t2.indexOf("&") === -1)
- return t2;
- if (this.options.htmlEntities)
- for (const e3 of Object.keys(this.htmlEntities)) {
- const i4 = this.htmlEntities[e3], s2 = t2.match(i4.regex);
- if (s2 && (this.entityExpansionCount += s2.length, n3.maxTotalExpansions && this.entityExpansionCount > n3.maxTotalExpansions))
- throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n3.maxTotalExpansions}`);
- t2 = t2.replace(i4.regex, i4.val);
- }
- return t2.replace(this.ampEntity.regex, this.ampEntity.val);
- }
- function H2(t2, e2, i3, n3) {
- return t2 && (n3 === undefined && (n3 = e2.child.length === 0), (t2 = this.parseTextData(t2, e2.tagname, i3, false, !!e2[":@"] && Object.keys(e2[":@"]).length !== 0, n3)) !== undefined && t2 !== "" && e2.add(this.options.textNodeName, t2), t2 = ""), t2;
- }
- function tt(t2, e2) {
- if (!t2 || t2.length === 0)
- return false;
- for (let i3 = 0;i3 < t2.length; i3++)
- if (e2.matches(t2[i3]))
- return true;
- return false;
- }
- function et(t2, e2, i3, n3) {
- const s2 = t2.indexOf(e2, i3);
- if (s2 === -1)
- throw new Error(n3);
- return s2 + e2.length - 1;
- }
- function it(t2, e2, i3, n3 = ">") {
- const s2 = function(t3, e3, i4 = ">") {
- let n4, s3 = "";
- for (let r3 = e3;r3 < t3.length; r3++) {
- let e4 = t3[r3];
- if (n4)
- e4 === n4 && (n4 = "");
- else if (e4 === '"' || e4 === "'")
- n4 = e4;
- else if (e4 === i4[0]) {
- if (!i4[1])
- return { data: s3, index: r3 };
- if (t3[r3 + 1] === i4[1])
- return { data: s3, index: r3 };
- } else
- e4 === "\t" && (e4 = " ");
- s3 += e4;
- }
- }(t2, e2 + 1, n3);
- if (!s2)
- return;
- let r2 = s2.data;
- const o3 = s2.index, a3 = r2.search(/\s/);
- let h3 = r2, l2 = true;
- a3 !== -1 && (h3 = r2.substring(0, a3), r2 = r2.substring(a3 + 1).trimStart());
- const p2 = h3;
- if (i3) {
- const t3 = h3.indexOf(":");
- t3 !== -1 && (h3 = h3.substr(t3 + 1), l2 = h3 !== s2.data.substr(t3 + 1));
- }
- return { tagName: h3, tagExp: r2, closeIndex: o3, attrExpPresent: l2, rawTagName: p2 };
- }
- function nt(t2, e2, i3) {
- const n3 = i3;
- let s2 = 1;
- for (;i3 < t2.length; i3++)
- if (t2[i3] === "<")
- if (t2[i3 + 1] === "/") {
- const r2 = et(t2, ">", i3, `${e2} is not closed`);
- if (t2.substring(i3 + 2, r2).trim() === e2 && (s2--, s2 === 0))
- return { tagContent: t2.substring(n3, i3), i: r2 };
- i3 = r2;
- } else if (t2[i3 + 1] === "?")
- i3 = et(t2, "?>", i3 + 1, "StopNode is not closed.");
- else if (t2.substr(i3 + 1, 3) === "!--")
- i3 = et(t2, "-->", i3 + 3, "StopNode is not closed.");
- else if (t2.substr(i3 + 1, 2) === "![")
- i3 = et(t2, "]]>", i3, "StopNode is not closed.") - 2;
- else {
- const n4 = it(t2, i3, ">");
- n4 && ((n4 && n4.tagName) === e2 && n4.tagExp[n4.tagExp.length - 1] !== "/" && s2++, i3 = n4.closeIndex);
- }
- }
- function st(t2, e2, i3) {
- if (e2 && typeof t2 == "string") {
- const e3 = t2.trim();
- return e3 === "true" || e3 !== "false" && function(t3, e4 = {}) {
- if (e4 = Object.assign({}, k, e4), !t3 || typeof t3 != "string")
- return t3;
- let i4 = t3.trim();
- if (e4.skipLike !== undefined && e4.skipLike.test(i4))
- return t3;
- if (t3 === "0")
- return 0;
- if (e4.hex && D2.test(i4))
- return function(t4) {
- if (parseInt)
- return parseInt(t4, 16);
- if (Number.parseInt)
- return Number.parseInt(t4, 16);
- if (window && window.parseInt)
- return window.parseInt(t4, 16);
- throw new Error("parseInt, Number.parseInt, window.parseInt are not supported");
- }(i4);
- if (isFinite(i4)) {
- if (i4.includes("e") || i4.includes("E"))
- return function(t4, e5, i5) {
- if (!i5.eNotation)
- return t4;
- const n4 = e5.match(F);
- if (n4) {
- let s2 = n4[1] || "";
- const r2 = n4[3].indexOf("e") === -1 ? "E" : "e", o3 = n4[2], a3 = s2 ? t4[o3.length + 1] === r2 : t4[o3.length] === r2;
- return o3.length > 1 && a3 ? t4 : (o3.length !== 1 || !n4[3].startsWith(`.${r2}`) && n4[3][0] !== r2) && o3.length > 0 ? i5.leadingZeros && !a3 ? (e5 = (n4[1] || "") + n4[3], Number(e5)) : t4 : Number(e5);
- }
- return t4;
- }(t3, i4, e4);
- {
- const s2 = V.exec(i4);
- if (s2) {
- const r2 = s2[1] || "", o3 = s2[2];
- let a3 = (n3 = s2[3]) && n3.indexOf(".") !== -1 ? ((n3 = n3.replace(/0+$/, "")) === "." ? n3 = "0" : n3[0] === "." ? n3 = "0" + n3 : n3[n3.length - 1] === "." && (n3 = n3.substring(0, n3.length - 1)), n3) : n3;
- const h3 = r2 ? t3[o3.length + 1] === "." : t3[o3.length] === ".";
- if (!e4.leadingZeros && (o3.length > 1 || o3.length === 1 && !h3))
- return t3;
- {
- const n4 = Number(i4), s3 = String(n4);
- if (n4 === 0)
- return n4;
- if (s3.search(/[eE]/) !== -1)
- return e4.eNotation ? n4 : t3;
- if (i4.indexOf(".") !== -1)
- return s3 === "0" || s3 === a3 || s3 === `${r2}${a3}` ? n4 : t3;
- let h4 = o3 ? a3 : i4;
- return o3 ? h4 === s3 || r2 + h4 === s3 ? n4 : t3 : h4 === s3 || h4 === r2 + s3 ? n4 : t3;
- }
- }
- return t3;
- }
- }
- var n3;
- return function(t4, e5, i5) {
- const n4 = e5 === 1 / 0;
- switch (i5.infinity.toLowerCase()) {
- case "null":
- return null;
- case "infinity":
- return e5;
- case "string":
- return n4 ? "Infinity" : "-Infinity";
- default:
- return t4;
- }
- }(t3, Number(i4), e4);
- }(t2, i3);
- }
- return t2 !== undefined ? t2 : "";
- }
- function rt(t2, e2, i3) {
- const n3 = Number.parseInt(t2, e2);
- return n3 >= 0 && n3 <= 1114111 ? String.fromCodePoint(n3) : i3 + t2 + ";";
- }
- function ot(t2, e2, i3, n3) {
- if (t2) {
- const n4 = t2(e2);
- i3 === e2 && (i3 = n4), e2 = n4;
- }
- return { tagName: e2 = at(e2, n3), tagExp: i3 };
- }
- function at(t2, e2) {
- if (a2.includes(t2))
- throw new Error(`[SECURITY] Invalid name: "${t2}" is a reserved JavaScript keyword that could cause prototype pollution`);
- return o2.includes(t2) ? e2.onDangerousProperty(t2) : t2;
- }
- const ht = $2.getMetaDataSymbol();
- function lt(t2, e2) {
- if (!t2 || typeof t2 != "object")
- return {};
- if (!e2)
- return t2;
- const i3 = {};
- for (const n3 in t2)
- n3.startsWith(e2) ? i3[n3.substring(e2.length)] = t2[n3] : i3[n3] = t2[n3];
- return i3;
- }
- function pt(t2, e2, i3, n3) {
- return ut(t2, e2, i3, n3);
- }
- function ut(t2, e2, i3, n3) {
- let s2;
- const r2 = {};
- for (let o3 = 0;o3 < t2.length; o3++) {
- const a3 = t2[o3], h3 = ct(a3);
- if (h3 !== undefined && h3 !== e2.textNodeName) {
- const t3 = lt(a3[":@"] || {}, e2.attributeNamePrefix);
- i3.push(h3, t3);
- }
- if (h3 === e2.textNodeName)
- s2 === undefined ? s2 = a3[h3] : s2 += "" + a3[h3];
- else {
- if (h3 === undefined)
- continue;
- if (a3[h3]) {
- let t3 = ut(a3[h3], e2, i3, n3);
- const s3 = ft(t3, e2);
- if (a3[":@"] ? dt(t3, a3[":@"], n3, e2) : Object.keys(t3).length !== 1 || t3[e2.textNodeName] === undefined || e2.alwaysCreateTextNode ? Object.keys(t3).length === 0 && (e2.alwaysCreateTextNode ? t3[e2.textNodeName] = "" : t3 = "") : t3 = t3[e2.textNodeName], a3[ht] !== undefined && typeof t3 == "object" && t3 !== null && (t3[ht] = a3[ht]), r2[h3] !== undefined && Object.prototype.hasOwnProperty.call(r2, h3))
- Array.isArray(r2[h3]) || (r2[h3] = [r2[h3]]), r2[h3].push(t3);
- else {
- const i4 = e2.jPath ? n3.toString() : n3;
- e2.isArray(h3, i4, s3) ? r2[h3] = [t3] : r2[h3] = t3;
- }
- h3 !== undefined && h3 !== e2.textNodeName && i3.pop();
- }
- }
- }
- return typeof s2 == "string" ? s2.length > 0 && (r2[e2.textNodeName] = s2) : s2 !== undefined && (r2[e2.textNodeName] = s2), r2;
- }
- function ct(t2) {
- const e2 = Object.keys(t2);
- for (let t3 = 0;t3 < e2.length; t3++) {
- const i3 = e2[t3];
- if (i3 !== ":@")
- return i3;
- }
- }
- function dt(t2, e2, i3, n3) {
- if (e2) {
- const s2 = Object.keys(e2), r2 = s2.length;
- for (let o3 = 0;o3 < r2; o3++) {
- const r3 = s2[o3], a3 = r3.startsWith(n3.attributeNamePrefix) ? r3.substring(n3.attributeNamePrefix.length) : r3, h3 = n3.jPath ? i3.toString() + "." + a3 : i3;
- n3.isArray(r3, h3, true, true) ? t2[r3] = [e2[r3]] : t2[r3] = e2[r3];
- }
- }
- }
- function ft(t2, e2) {
- const { textNodeName: i3 } = e2, n3 = Object.keys(t2).length;
- return n3 === 0 || !(n3 !== 1 || !t2[i3] && typeof t2[i3] != "boolean" && t2[i3] !== 0);
- }
-
- class gt {
- constructor(t2) {
- this.externalEntities = {}, this.options = O(t2);
- }
- parse(t2, e2) {
- if (typeof t2 != "string" && t2.toString)
- t2 = t2.toString();
- else if (typeof t2 != "string")
- throw new Error("XML data is accepted in String or Bytes[] form.");
- if (e2) {
- e2 === true && (e2 = {});
- const i4 = l(t2, e2);
- if (i4 !== true)
- throw Error(`${i4.err.msg}:${i4.err.line}:${i4.err.col}`);
- }
- const i3 = new W2(this.options);
- i3.addExternalEntities(this.externalEntities);
- const n3 = i3.parseXml(t2);
- return this.options.preserveOrder || n3 === undefined ? n3 : pt(n3, this.options, i3.matcher, i3.readonlyMatcher);
- }
- addEntity(t2, e2) {
- if (e2.indexOf("&") !== -1)
- throw new Error("Entity value can't have '&'");
- if (t2.indexOf("&") !== -1 || t2.indexOf(";") !== -1)
- throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");
- if (e2 === "&")
- throw new Error("An entity with value '&' is not permitted");
- this.externalEntities[t2] = e2;
- }
- static getMetaDataSymbol() {
- return $2.getMetaDataSymbol();
- }
- }
- function mt(t2, e2) {
- let i3 = "";
- e2.format && e2.indentBy.length > 0 && (i3 = `
-`);
- const n3 = [];
- if (e2.stopNodes && Array.isArray(e2.stopNodes))
- for (let t3 = 0;t3 < e2.stopNodes.length; t3++) {
- const i4 = e2.stopNodes[t3];
- typeof i4 == "string" ? n3.push(new R2(i4)) : i4 instanceof R2 && n3.push(i4);
- }
- return xt(t2, e2, i3, new G3, n3);
- }
- function xt(t2, e2, i3, n3, s2) {
- let r2 = "", o3 = false;
- if (e2.maxNestedTags && n3.getDepth() > e2.maxNestedTags)
- throw new Error("Maximum nested tags exceeded");
- if (!Array.isArray(t2)) {
- if (t2 != null) {
- let i4 = t2.toString();
- return i4 = Tt(i4, e2), i4;
- }
- return "";
- }
- for (let a3 = 0;a3 < t2.length; a3++) {
- const h3 = t2[a3], l2 = yt(h3);
- if (l2 === undefined)
- continue;
- const p2 = Nt(h3[":@"], e2);
- n3.push(l2, p2);
- const u3 = vt(n3, s2);
- if (l2 === e2.textNodeName) {
- let t3 = h3[l2];
- u3 || (t3 = e2.tagValueProcessor(l2, t3), t3 = Tt(t3, e2)), o3 && (r2 += i3), r2 += t3, o3 = false, n3.pop();
- continue;
- }
- if (l2 === e2.cdataPropName) {
- o3 && (r2 += i3), r2 += ``, o3 = false, n3.pop();
- continue;
- }
- if (l2 === e2.commentPropName) {
- r2 += i3 + ``, o3 = true, n3.pop();
- continue;
- }
- if (l2[0] === "?") {
- const t3 = wt(h3[":@"], e2, u3), s3 = l2 === "?xml" ? "" : i3;
- let a4 = h3[l2][0][e2.textNodeName];
- a4 = a4.length !== 0 ? " " + a4 : "", r2 += s3 + `<${l2}${a4}${t3}?>`, o3 = true, n3.pop();
- continue;
- }
- let c6 = i3;
- c6 !== "" && (c6 += e2.indentBy);
- const d2 = i3 + `<${l2}${wt(h3[":@"], e2, u3)}`;
- let f2;
- f2 = u3 ? bt(h3[l2], e2) : xt(h3[l2], e2, c6, n3, s2), e2.unpairedTags.indexOf(l2) !== -1 ? e2.suppressUnpairedNode ? r2 += d2 + ">" : r2 += d2 + "/>" : f2 && f2.length !== 0 || !e2.suppressEmptyNode ? f2 && f2.endsWith(">") ? r2 += d2 + `>${f2}${i3}${l2}>` : (r2 += d2 + ">", f2 && i3 !== "" && (f2.includes("/>") || f2.includes("")) ? r2 += i3 + e2.indentBy + f2 + i3 : r2 += f2, r2 += `${l2}>`) : r2 += d2 + "/>", o3 = true, n3.pop();
- }
- return r2;
- }
- function Nt(t2, e2) {
- if (!t2 || e2.ignoreAttributes)
- return null;
- const i3 = {};
- let n3 = false;
- for (let s2 in t2)
- Object.prototype.hasOwnProperty.call(t2, s2) && (i3[s2.startsWith(e2.attributeNamePrefix) ? s2.substr(e2.attributeNamePrefix.length) : s2] = t2[s2], n3 = true);
- return n3 ? i3 : null;
- }
- function bt(t2, e2) {
- if (!Array.isArray(t2))
- return t2 != null ? t2.toString() : "";
- let i3 = "";
- for (let n3 = 0;n3 < t2.length; n3++) {
- const s2 = t2[n3], r2 = yt(s2);
- if (r2 === e2.textNodeName)
- i3 += s2[r2];
- else if (r2 === e2.cdataPropName)
- i3 += s2[r2][0][e2.textNodeName];
- else if (r2 === e2.commentPropName)
- i3 += s2[r2][0][e2.textNodeName];
- else {
- if (r2 && r2[0] === "?")
- continue;
- if (r2) {
- const t3 = Et(s2[":@"], e2), n4 = bt(s2[r2], e2);
- n4 && n4.length !== 0 ? i3 += `<${r2}${t3}>${n4}${r2}>` : i3 += `<${r2}${t3}/>`;
- }
- }
- }
- return i3;
- }
- function Et(t2, e2) {
- let i3 = "";
- if (t2 && !e2.ignoreAttributes)
- for (let n3 in t2) {
- if (!Object.prototype.hasOwnProperty.call(t2, n3))
- continue;
- let s2 = t2[n3];
- s2 === true && e2.suppressBooleanAttributes ? i3 += ` ${n3.substr(e2.attributeNamePrefix.length)}` : i3 += ` ${n3.substr(e2.attributeNamePrefix.length)}="${s2}"`;
- }
- return i3;
- }
- function yt(t2) {
- const e2 = Object.keys(t2);
- for (let i3 = 0;i3 < e2.length; i3++) {
- const n3 = e2[i3];
- if (Object.prototype.hasOwnProperty.call(t2, n3) && n3 !== ":@")
- return n3;
- }
- }
- function wt(t2, e2, i3) {
- let n3 = "";
- if (t2 && !e2.ignoreAttributes)
- for (let s2 in t2) {
- if (!Object.prototype.hasOwnProperty.call(t2, s2))
- continue;
- let r2;
- i3 ? r2 = t2[s2] : (r2 = e2.attributeValueProcessor(s2, t2[s2]), r2 = Tt(r2, e2)), r2 === true && e2.suppressBooleanAttributes ? n3 += ` ${s2.substr(e2.attributeNamePrefix.length)}` : n3 += ` ${s2.substr(e2.attributeNamePrefix.length)}="${r2}"`;
- }
- return n3;
- }
- function vt(t2, e2) {
- if (!e2 || e2.length === 0)
- return false;
- for (let i3 = 0;i3 < e2.length; i3++)
- if (t2.matches(e2[i3]))
- return true;
- return false;
- }
- function Tt(t2, e2) {
- if (t2 && t2.length > 0 && e2.processEntities)
- for (let i3 = 0;i3 < e2.entities.length; i3++) {
- const n3 = e2.entities[i3];
- t2 = t2.replace(n3.regex, n3.val);
- }
- return t2;
- }
- const Pt = { attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, cdataPropName: false, format: false, indentBy: " ", suppressEmptyNode: false, suppressUnpairedNode: true, suppressBooleanAttributes: true, tagValueProcessor: function(t2, e2) {
- return e2;
- }, attributeValueProcessor: function(t2, e2) {
- return e2;
- }, preserveOrder: false, commentPropName: false, unpairedTags: [], entities: [{ regex: new RegExp("&", "g"), val: "&" }, { regex: new RegExp(">", "g"), val: ">" }, { regex: new RegExp("<", "g"), val: "<" }, { regex: new RegExp("'", "g"), val: "'" }, { regex: new RegExp('"', "g"), val: """ }], processEntities: true, stopNodes: [], oneListGroup: false, maxNestedTags: 100, jPath: true };
- function St(t2) {
- if (this.options = Object.assign({}, Pt, t2), this.options.stopNodes && Array.isArray(this.options.stopNodes) && (this.options.stopNodes = this.options.stopNodes.map((t3) => typeof t3 == "string" && t3.startsWith("*.") ? ".." + t3.substring(2) : t3)), this.stopNodeExpressions = [], this.options.stopNodes && Array.isArray(this.options.stopNodes))
- for (let t3 = 0;t3 < this.options.stopNodes.length; t3++) {
- const e3 = this.options.stopNodes[t3];
- typeof e3 == "string" ? this.stopNodeExpressions.push(new R2(e3)) : e3 instanceof R2 && this.stopNodeExpressions.push(e3);
- }
- var e2;
- this.options.ignoreAttributes === true || this.options.attributesGroupName ? this.isAttribute = function() {
- return false;
- } : (this.ignoreAttributesFn = typeof (e2 = this.options.ignoreAttributes) == "function" ? e2 : Array.isArray(e2) ? (t3) => {
- for (const i3 of e2) {
- if (typeof i3 == "string" && t3 === i3)
- return true;
- if (i3 instanceof RegExp && i3.test(t3))
- return true;
- }
- } : () => false, this.attrPrefixLen = this.options.attributeNamePrefix.length, this.isAttribute = Ct), this.processTextOrObjNode = At, this.options.format ? (this.indentate = Ot, this.tagEndChar = `>
-`, this.newLine = `
-`) : (this.indentate = function() {
- return "";
- }, this.tagEndChar = ">", this.newLine = "");
- }
- function At(t2, e2, i3, n3) {
- const s2 = this.extractAttributes(t2);
- if (n3.push(e2, s2), this.checkStopNode(n3)) {
- const s3 = this.buildRawContent(t2), r3 = this.buildAttributesForStopNode(t2);
- return n3.pop(), this.buildObjectNode(s3, e2, r3, i3);
- }
- const r2 = this.j2x(t2, i3 + 1, n3);
- return n3.pop(), t2[this.options.textNodeName] !== undefined && Object.keys(t2).length === 1 ? this.buildTextValNode(t2[this.options.textNodeName], e2, r2.attrStr, i3, n3) : this.buildObjectNode(r2.val, e2, r2.attrStr, i3);
- }
- function Ot(t2) {
- return this.options.indentBy.repeat(t2);
- }
- function Ct(t2) {
- return !(!t2.startsWith(this.options.attributeNamePrefix) || t2 === this.options.textNodeName) && t2.substr(this.attrPrefixLen);
- }
- St.prototype.build = function(t2) {
- if (this.options.preserveOrder)
- return mt(t2, this.options);
- {
- Array.isArray(t2) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1 && (t2 = { [this.options.arrayNodeName]: t2 });
- const e2 = new G3;
- return this.j2x(t2, 0, e2).val;
- }
- }, St.prototype.j2x = function(t2, e2, i3) {
- let n3 = "", s2 = "";
- if (this.options.maxNestedTags && i3.getDepth() >= this.options.maxNestedTags)
- throw new Error("Maximum nested tags exceeded");
- const r2 = this.options.jPath ? i3.toString() : i3, o3 = this.checkStopNode(i3);
- for (let a3 in t2)
- if (Object.prototype.hasOwnProperty.call(t2, a3))
- if (t2[a3] === undefined)
- this.isAttribute(a3) && (s2 += "");
- else if (t2[a3] === null)
- this.isAttribute(a3) || a3 === this.options.cdataPropName ? s2 += "" : a3[0] === "?" ? s2 += this.indentate(e2) + "<" + a3 + "?" + this.tagEndChar : s2 += this.indentate(e2) + "<" + a3 + "/" + this.tagEndChar;
- else if (t2[a3] instanceof Date)
- s2 += this.buildTextValNode(t2[a3], a3, "", e2, i3);
- else if (typeof t2[a3] != "object") {
- const h3 = this.isAttribute(a3);
- if (h3 && !this.ignoreAttributesFn(h3, r2))
- n3 += this.buildAttrPairStr(h3, "" + t2[a3], o3);
- else if (!h3)
- if (a3 === this.options.textNodeName) {
- let e3 = this.options.tagValueProcessor(a3, "" + t2[a3]);
- s2 += this.replaceEntitiesValue(e3);
- } else {
- i3.push(a3);
- const n4 = this.checkStopNode(i3);
- if (i3.pop(), n4) {
- const i4 = "" + t2[a3];
- s2 += i4 === "" ? this.indentate(e2) + "<" + a3 + this.closeTag(a3) + this.tagEndChar : this.indentate(e2) + "<" + a3 + ">" + i4 + "" + a3 + this.tagEndChar;
- } else
- s2 += this.buildTextValNode(t2[a3], a3, "", e2, i3);
- }
- } else if (Array.isArray(t2[a3])) {
- const n4 = t2[a3].length;
- let r3 = "", o4 = "";
- for (let h3 = 0;h3 < n4; h3++) {
- const n5 = t2[a3][h3];
- if (n5 === undefined)
- ;
- else if (n5 === null)
- a3[0] === "?" ? s2 += this.indentate(e2) + "<" + a3 + "?" + this.tagEndChar : s2 += this.indentate(e2) + "<" + a3 + "/" + this.tagEndChar;
- else if (typeof n5 == "object")
- if (this.options.oneListGroup) {
- i3.push(a3);
- const t3 = this.j2x(n5, e2 + 1, i3);
- i3.pop(), r3 += t3.val, this.options.attributesGroupName && n5.hasOwnProperty(this.options.attributesGroupName) && (o4 += t3.attrStr);
- } else
- r3 += this.processTextOrObjNode(n5, a3, e2, i3);
- else if (this.options.oneListGroup) {
- let t3 = this.options.tagValueProcessor(a3, n5);
- t3 = this.replaceEntitiesValue(t3), r3 += t3;
- } else {
- i3.push(a3);
- const t3 = this.checkStopNode(i3);
- if (i3.pop(), t3) {
- const t4 = "" + n5;
- r3 += t4 === "" ? this.indentate(e2) + "<" + a3 + this.closeTag(a3) + this.tagEndChar : this.indentate(e2) + "<" + a3 + ">" + t4 + "" + a3 + this.tagEndChar;
- } else
- r3 += this.buildTextValNode(n5, a3, "", e2, i3);
- }
- }
- this.options.oneListGroup && (r3 = this.buildObjectNode(r3, a3, o4, e2)), s2 += r3;
- } else if (this.options.attributesGroupName && a3 === this.options.attributesGroupName) {
- const e3 = Object.keys(t2[a3]), i4 = e3.length;
- for (let s3 = 0;s3 < i4; s3++)
- n3 += this.buildAttrPairStr(e3[s3], "" + t2[a3][e3[s3]], o3);
- } else
- s2 += this.processTextOrObjNode(t2[a3], a3, e2, i3);
- return { attrStr: n3, val: s2 };
- }, St.prototype.buildAttrPairStr = function(t2, e2, i3) {
- return i3 || (e2 = this.options.attributeValueProcessor(t2, "" + e2), e2 = this.replaceEntitiesValue(e2)), this.options.suppressBooleanAttributes && e2 === "true" ? " " + t2 : " " + t2 + '="' + e2 + '"';
- }, St.prototype.extractAttributes = function(t2) {
- if (!t2 || typeof t2 != "object")
- return null;
- const e2 = {};
- let i3 = false;
- if (this.options.attributesGroupName && t2[this.options.attributesGroupName]) {
- const n3 = t2[this.options.attributesGroupName];
- for (let t3 in n3)
- Object.prototype.hasOwnProperty.call(n3, t3) && (e2[t3.startsWith(this.options.attributeNamePrefix) ? t3.substring(this.options.attributeNamePrefix.length) : t3] = n3[t3], i3 = true);
- } else
- for (let n3 in t2) {
- if (!Object.prototype.hasOwnProperty.call(t2, n3))
- continue;
- const s2 = this.isAttribute(n3);
- s2 && (e2[s2] = t2[n3], i3 = true);
- }
- return i3 ? e2 : null;
- }, St.prototype.buildRawContent = function(t2) {
- if (typeof t2 == "string")
- return t2;
- if (typeof t2 != "object" || t2 === null)
- return String(t2);
- if (t2[this.options.textNodeName] !== undefined)
- return t2[this.options.textNodeName];
- let e2 = "";
- for (let i3 in t2) {
- if (!Object.prototype.hasOwnProperty.call(t2, i3))
- continue;
- if (this.isAttribute(i3))
- continue;
- if (this.options.attributesGroupName && i3 === this.options.attributesGroupName)
- continue;
- const n3 = t2[i3];
- if (i3 === this.options.textNodeName)
- e2 += n3;
- else if (Array.isArray(n3)) {
- for (let t3 of n3)
- if (typeof t3 == "string" || typeof t3 == "number")
- e2 += `<${i3}>${t3}${i3}>`;
- else if (typeof t3 == "object" && t3 !== null) {
- const n4 = this.buildRawContent(t3), s2 = this.buildAttributesForStopNode(t3);
- e2 += n4 === "" ? `<${i3}${s2}/>` : `<${i3}${s2}>${n4}${i3}>`;
- }
- } else if (typeof n3 == "object" && n3 !== null) {
- const t3 = this.buildRawContent(n3), s2 = this.buildAttributesForStopNode(n3);
- e2 += t3 === "" ? `<${i3}${s2}/>` : `<${i3}${s2}>${t3}${i3}>`;
- } else
- e2 += `<${i3}>${n3}${i3}>`;
- }
- return e2;
- }, St.prototype.buildAttributesForStopNode = function(t2) {
- if (!t2 || typeof t2 != "object")
- return "";
- let e2 = "";
- if (this.options.attributesGroupName && t2[this.options.attributesGroupName]) {
- const i3 = t2[this.options.attributesGroupName];
- for (let t3 in i3) {
- if (!Object.prototype.hasOwnProperty.call(i3, t3))
- continue;
- const n3 = t3.startsWith(this.options.attributeNamePrefix) ? t3.substring(this.options.attributeNamePrefix.length) : t3, s2 = i3[t3];
- s2 === true && this.options.suppressBooleanAttributes ? e2 += " " + n3 : e2 += " " + n3 + '="' + s2 + '"';
- }
- } else
- for (let i3 in t2) {
- if (!Object.prototype.hasOwnProperty.call(t2, i3))
- continue;
- const n3 = this.isAttribute(i3);
- if (n3) {
- const s2 = t2[i3];
- s2 === true && this.options.suppressBooleanAttributes ? e2 += " " + n3 : e2 += " " + n3 + '="' + s2 + '"';
- }
- }
- return e2;
- }, St.prototype.buildObjectNode = function(t2, e2, i3, n3) {
- if (t2 === "")
- return e2[0] === "?" ? this.indentate(n3) + "<" + e2 + i3 + "?" + this.tagEndChar : this.indentate(n3) + "<" + e2 + i3 + this.closeTag(e2) + this.tagEndChar;
- {
- let s2 = "" + e2 + this.tagEndChar, r2 = "";
- return e2[0] === "?" && (r2 = "?", s2 = ""), !i3 && i3 !== "" || t2.indexOf("<") !== -1 ? this.options.commentPropName !== false && e2 === this.options.commentPropName && r2.length === 0 ? this.indentate(n3) + `` + this.newLine : this.indentate(n3) + "<" + e2 + i3 + r2 + this.tagEndChar + t2 + this.indentate(n3) + s2 : this.indentate(n3) + "<" + e2 + i3 + r2 + ">" + t2 + s2;
- }
- }, St.prototype.closeTag = function(t2) {
- let e2 = "";
- return this.options.unpairedTags.indexOf(t2) !== -1 ? this.options.suppressUnpairedNode || (e2 = "/") : e2 = this.options.suppressEmptyNode ? "/" : `>${t2}`, e2;
- }, St.prototype.checkStopNode = function(t2) {
- if (!this.stopNodeExpressions || this.stopNodeExpressions.length === 0)
- return false;
- for (let e2 = 0;e2 < this.stopNodeExpressions.length; e2++)
- if (t2.matches(this.stopNodeExpressions[e2]))
- return true;
- return false;
- }, St.prototype.buildTextValNode = function(t2, e2, i3, n3, s2) {
- if (this.options.cdataPropName !== false && e2 === this.options.cdataPropName)
- return this.indentate(n3) + `` + this.newLine;
- if (this.options.commentPropName !== false && e2 === this.options.commentPropName)
- return this.indentate(n3) + `` + this.newLine;
- if (e2[0] === "?")
- return this.indentate(n3) + "<" + e2 + i3 + "?" + this.tagEndChar;
- {
- let s3 = this.options.tagValueProcessor(e2, t2);
- return s3 = this.replaceEntitiesValue(s3), s3 === "" ? this.indentate(n3) + "<" + e2 + i3 + this.closeTag(e2) + this.tagEndChar : this.indentate(n3) + "<" + e2 + i3 + ">" + s3 + "" + e2 + this.tagEndChar;
- }
- }, St.prototype.replaceEntitiesValue = function(t2) {
- if (t2 && t2.length > 0 && this.options.processEntities)
- for (let e2 = 0;e2 < this.options.entities.length; e2++) {
- const i3 = this.options.entities[e2];
- t2 = t2.replace(i3.regex, i3.val);
- }
- return t2;
- };
- const $t = St, It = { validate: l };
- module.exports = e;
- })();
-});
-
-// node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js
-var require_xml_parser = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.parseXML = parseXML;
- var fast_xml_parser_1 = require_fxp();
- var parser2 = new fast_xml_parser_1.XMLParser({
- attributeNamePrefix: "",
- processEntities: {
- enabled: true,
- maxTotalExpansions: Infinity
- },
- htmlEntities: true,
- ignoreAttributes: false,
- ignoreDeclaration: true,
- parseTagValue: false,
- trimValues: false,
- tagValueProcessor: (_, val) => val.trim() === "" && val.includes(`
-`) ? "" : undefined,
- maxNestedTags: Infinity
- });
- parser2.addEntity("#xD", "\r");
- parser2.addEntity("#10", `
-`);
- function parseXML(xmlString) {
- return parser2.parse(xmlString, true);
- }
-});
-
-// node_modules/@aws-sdk/xml-builder/dist-cjs/index.js
-var require_dist_cjs83 = __commonJS((exports) => {
- var xmlParser = require_xml_parser();
- var ATTR_ESCAPE_RE = /[&<>"]/g;
- var ATTR_ESCAPE_MAP = {
- "&": "&",
- "<": "<",
- ">": ">",
- '"': """
- };
- function escapeAttribute(value) {
- return value.replace(ATTR_ESCAPE_RE, (ch) => ATTR_ESCAPE_MAP[ch]);
- }
- var ELEMENT_ESCAPE_RE = /[&"'<>\r\n\u0085\u2028]/g;
- var ELEMENT_ESCAPE_MAP = {
- "&": "&",
- '"': """,
- "'": "'",
- "<": "<",
- ">": ">",
- "\r": "
",
- "\n": "
",
- "\x85": "
",
- "\u2028": "
"
- };
- function escapeElement(value) {
- return value.replace(ELEMENT_ESCAPE_RE, (ch) => ELEMENT_ESCAPE_MAP[ch]);
- }
-
- class XmlText {
- value;
- constructor(value) {
- this.value = value;
- }
- toString() {
- return escapeElement("" + this.value);
- }
- }
-
- class XmlNode {
- name;
- children;
- attributes = {};
- static of(name, childText, withName) {
- const node = new XmlNode(name);
- if (childText !== undefined) {
- node.addChildNode(new XmlText(childText));
- }
- if (withName !== undefined) {
- node.withName(withName);
- }
- return node;
- }
- constructor(name, children = []) {
- this.name = name;
- this.children = children;
- }
- withName(name) {
- this.name = name;
- return this;
- }
- addAttribute(name, value) {
- this.attributes[name] = value;
- return this;
- }
- addChildNode(child) {
- this.children.push(child);
- return this;
- }
- removeAttribute(name) {
- delete this.attributes[name];
- return this;
- }
- n(name) {
- this.name = name;
- return this;
- }
- c(child) {
- this.children.push(child);
- return this;
- }
- a(name, value) {
- if (value != null) {
- this.attributes[name] = value;
- }
- return this;
- }
- cc(input, field, withName = field) {
- if (input[field] != null) {
- const node = XmlNode.of(field, input[field]).withName(withName);
- this.c(node);
- }
- }
- l(input, listName, memberName, valueProvider) {
- if (input[listName] != null) {
- const nodes = valueProvider();
- nodes.map((node) => {
- node.withName(memberName);
- this.c(node);
- });
- }
- }
- lc(input, listName, memberName, valueProvider) {
- if (input[listName] != null) {
- const nodes = valueProvider();
- const containerNode = new XmlNode(memberName);
- nodes.map((node) => {
- containerNode.c(node);
- });
- this.c(containerNode);
- }
- }
- toString() {
- const hasChildren = Boolean(this.children.length);
- let xmlText = `<${this.name}`;
- const attributes = this.attributes;
- for (const attributeName of Object.keys(attributes)) {
- const attribute2 = attributes[attributeName];
- if (attribute2 != null) {
- xmlText += ` ${attributeName}="${escapeAttribute("" + attribute2)}"`;
- }
- }
- return xmlText += !hasChildren ? "/>" : `>${this.children.map((c5) => c5.toString()).join("")}${this.name}>`;
- }
- }
- exports.parseXML = xmlParser.parseXML;
- exports.XmlNode = XmlNode;
- exports.XmlText = XmlText;
-});
-
-// node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js
-var require_protocols2 = __commonJS((exports) => {
- var cbor = require_cbor();
- var schema2 = require_schema();
- var smithyClient = require_dist_cjs79();
- var protocols = require_protocols();
- var serde3 = require_serde();
- var utilBase64 = require_dist_cjs82();
- var utilUtf8 = require_dist_cjs17();
- var xmlBuilder = require_dist_cjs83();
-
- class ProtocolLib {
- queryCompat;
- errorRegistry;
- constructor(queryCompat = false) {
- this.queryCompat = queryCompat;
- }
- resolveRestContentType(defaultContentType, inputSchema) {
- const members = inputSchema.getMemberSchemas();
- const httpPayloadMember = Object.values(members).find((m) => {
- return !!m.getMergedTraits().httpPayload;
- });
- if (httpPayloadMember) {
- const mediaType = httpPayloadMember.getMergedTraits().mediaType;
- if (mediaType) {
- return mediaType;
- } else if (httpPayloadMember.isStringSchema()) {
- return "text/plain";
- } else if (httpPayloadMember.isBlobSchema()) {
- return "application/octet-stream";
- } else {
- return defaultContentType;
- }
- } else if (!inputSchema.isUnitSchema()) {
- const hasBody = Object.values(members).find((m) => {
- const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits();
- const noPrefixHeaders = httpPrefixHeaders === undefined;
- return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders;
- });
- if (hasBody) {
- return defaultContentType;
- }
- }
- }
- async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response2, dataObject, metadata, getErrorSchema) {
- let errorName = errorIdentifier;
- if (errorIdentifier.includes("#")) {
- [, errorName] = errorIdentifier.split("#");
- }
- const errorMetadata = {
- $metadata: metadata,
- $fault: response2.statusCode < 500 ? "client" : "server"
- };
- if (!this.errorRegistry) {
- throw new Error("@aws-sdk/core/protocols - error handler not initialized.");
- }
- try {
- const errorSchema = getErrorSchema?.(this.errorRegistry, errorName) ?? this.errorRegistry.getSchema(errorIdentifier);
- return { errorSchema, errorMetadata };
- } catch (e) {
- dataObject.message = dataObject.message ?? dataObject.Message ?? "UnknownError";
- const synthetic = this.errorRegistry;
- const baseExceptionSchema = synthetic.getBaseException();
- if (baseExceptionSchema) {
- const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error;
- throw this.decorateServiceException(Object.assign(new ErrorCtor({ name: errorName }), errorMetadata), dataObject);
- }
- const d = dataObject;
- const message = d?.message ?? d?.Message ?? d?.Error?.Message ?? d?.Error?.message;
- throw this.decorateServiceException(Object.assign(new Error(message), {
- name: errorName
- }, errorMetadata), dataObject);
- }
- }
- compose(composite, errorIdentifier, defaultNamespace) {
- let namespace = defaultNamespace;
- if (errorIdentifier.includes("#")) {
- [namespace] = errorIdentifier.split("#");
- }
- const staticRegistry = schema2.TypeRegistry.for(namespace);
- const defaultSyntheticRegistry = schema2.TypeRegistry.for("smithy.ts.sdk.synthetic." + defaultNamespace);
- composite.copyFrom(staticRegistry);
- composite.copyFrom(defaultSyntheticRegistry);
- this.errorRegistry = composite;
- }
- decorateServiceException(exception, additions = {}) {
- if (this.queryCompat) {
- const msg = exception.Message ?? additions.Message;
- const error40 = smithyClient.decorateServiceException(exception, additions);
- if (msg) {
- error40.message = msg;
- }
- error40.Error = {
- ...error40.Error,
- Type: error40.Error?.Type,
- Code: error40.Error?.Code,
- Message: error40.Error?.message ?? error40.Error?.Message ?? msg
- };
- const reqId = error40.$metadata.requestId;
- if (reqId) {
- error40.RequestId = reqId;
- }
- return error40;
- }
- return smithyClient.decorateServiceException(exception, additions);
- }
- setQueryCompatError(output, response2) {
- const queryErrorHeader = response2.headers?.["x-amzn-query-error"];
- if (output !== undefined && queryErrorHeader != null) {
- const [Code, Type] = queryErrorHeader.split(";");
- const entries = Object.entries(output);
- const Error2 = {
- Code,
- Type
- };
- Object.assign(output, Error2);
- for (const [k, v] of entries) {
- Error2[k === "message" ? "Message" : k] = v;
- }
- delete Error2.__type;
- output.Error = Error2;
- }
- }
- queryCompatOutput(queryCompatErrorData, errorData) {
- if (queryCompatErrorData.Error) {
- errorData.Error = queryCompatErrorData.Error;
- }
- if (queryCompatErrorData.Type) {
- errorData.Type = queryCompatErrorData.Type;
- }
- if (queryCompatErrorData.Code) {
- errorData.Code = queryCompatErrorData.Code;
- }
- }
- findQueryCompatibleError(registry3, errorName) {
- try {
- return registry3.getSchema(errorName);
- } catch (e) {
- return registry3.find((schema$1) => schema2.NormalizedSchema.of(schema$1).getMergedTraits().awsQueryError?.[0] === errorName);
- }
- }
- }
-
- class AwsSmithyRpcV2CborProtocol extends cbor.SmithyRpcV2CborProtocol {
- awsQueryCompatible;
- mixin;
- constructor({ defaultNamespace, errorTypeRegistries, awsQueryCompatible }) {
- super({ defaultNamespace, errorTypeRegistries });
- this.awsQueryCompatible = !!awsQueryCompatible;
- this.mixin = new ProtocolLib(this.awsQueryCompatible);
- }
- async serializeRequest(operationSchema, input, context) {
- const request2 = await super.serializeRequest(operationSchema, input, context);
- if (this.awsQueryCompatible) {
- request2.headers["x-amzn-query-mode"] = "true";
- }
- return request2;
- }
- async handleError(operationSchema, context, response2, dataObject, metadata) {
- if (this.awsQueryCompatible) {
- this.mixin.setQueryCompatError(dataObject, response2);
- }
- const errorName = (() => {
- const compatHeader = response2.headers["x-amzn-query-error"];
- if (compatHeader && this.awsQueryCompatible) {
- return compatHeader.split(";")[0];
- }
- return cbor.loadSmithyRpcV2CborErrorCode(response2, dataObject) ?? "Unknown";
- })();
- this.mixin.compose(this.compositeErrorRegistry, errorName, this.options.defaultNamespace);
- const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response2, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : undefined);
- const ns = schema2.NormalizedSchema.of(errorSchema);
- const message = dataObject.message ?? dataObject.Message ?? "UnknownError";
- const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error;
- const exception = new ErrorCtor(message);
- const output = {};
- for (const [name, member] of ns.structIterator()) {
- if (dataObject[name] != null) {
- output[name] = this.deserializer.readValue(member, dataObject[name]);
- }
- }
- if (this.awsQueryCompatible) {
- this.mixin.queryCompatOutput(dataObject, output);
- }
- throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {
- $fault: ns.getMergedTraits().error,
- message
- }, output), dataObject);
- }
- }
- var _toStr = (val) => {
- if (val == null) {
- return val;
- }
- if (typeof val === "number" || typeof val === "bigint") {
- const warning = new Error(`Received number ${val} where a string was expected.`);
- warning.name = "Warning";
- console.warn(warning);
- return String(val);
- }
- if (typeof val === "boolean") {
- const warning = new Error(`Received boolean ${val} where a string was expected.`);
- warning.name = "Warning";
- console.warn(warning);
- return String(val);
- }
- return val;
- };
- var _toBool = (val) => {
- if (val == null) {
- return val;
- }
- if (typeof val === "string") {
- const lowercase2 = val.toLowerCase();
- if (val !== "" && lowercase2 !== "false" && lowercase2 !== "true") {
- const warning = new Error(`Received string "${val}" where a boolean was expected.`);
- warning.name = "Warning";
- console.warn(warning);
- }
- return val !== "" && lowercase2 !== "false";
- }
- return val;
- };
- var _toNum = (val) => {
- if (val == null) {
- return val;
- }
- if (typeof val === "string") {
- const num = Number(val);
- if (num.toString() !== val) {
- const warning = new Error(`Received string "${val}" where a number was expected.`);
- warning.name = "Warning";
- console.warn(warning);
- return val;
- }
- return num;
- }
- return val;
- };
-
- class SerdeContextConfig {
- serdeContext;
- setSerdeContext(serdeContext) {
- this.serdeContext = serdeContext;
- }
- }
-
- class UnionSerde {
- from;
- to;
- keys;
- constructor(from, to) {
- this.from = from;
- this.to = to;
- this.keys = new Set(Object.keys(this.from).filter((k) => k !== "__type"));
- }
- mark(key) {
- this.keys.delete(key);
- }
- hasUnknown() {
- return this.keys.size === 1 && Object.keys(this.to).length === 0;
- }
- writeUnknown() {
- if (this.hasUnknown()) {
- const k = this.keys.values().next().value;
- const v = this.from[k];
- this.to.$unknown = [k, v];
- }
- }
- }
- function jsonReviver(key, value, context) {
- if (context?.source) {
- const numericString = context.source;
- if (typeof value === "number") {
- if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) {
- const isFractional = numericString.includes(".");
- if (isFractional) {
- return new serde3.NumericValue(numericString, "bigDecimal");
- } else {
- return BigInt(numericString);
- }
- }
- }
- }
- return value;
- }
- var collectBodyString = (streamBody, context) => smithyClient.collectBody(streamBody, context).then((body) => (context?.utf8Encoder ?? utilUtf8.toUtf8)(body));
- var parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
- if (encoded.length) {
- try {
- return JSON.parse(encoded);
- } catch (e) {
- if (e?.name === "SyntaxError") {
- Object.defineProperty(e, "$responseBodyText", {
- value: encoded
- });
- }
- throw e;
- }
- }
- return {};
- });
- var parseJsonErrorBody = async (errorBody, context) => {
- const value = await parseJsonBody(errorBody, context);
- value.message = value.message ?? value.Message;
- return value;
- };
- var loadRestJsonErrorCode = (output, data) => {
- const findKey2 = (object2, key) => Object.keys(object2).find((k) => k.toLowerCase() === key.toLowerCase());
- const sanitizeErrorCode = (rawValue) => {
- let cleanValue = rawValue;
- if (typeof cleanValue === "number") {
- cleanValue = cleanValue.toString();
- }
- if (cleanValue.indexOf(",") >= 0) {
- cleanValue = cleanValue.split(",")[0];
- }
- if (cleanValue.indexOf(":") >= 0) {
- cleanValue = cleanValue.split(":")[0];
- }
- if (cleanValue.indexOf("#") >= 0) {
- cleanValue = cleanValue.split("#")[1];
- }
- return cleanValue;
- };
- const headerKey = findKey2(output.headers, "x-amzn-errortype");
- if (headerKey !== undefined) {
- return sanitizeErrorCode(output.headers[headerKey]);
- }
- if (data && typeof data === "object") {
- const codeKey = findKey2(data, "code");
- if (codeKey && data[codeKey] !== undefined) {
- return sanitizeErrorCode(data[codeKey]);
- }
- if (data["__type"] !== undefined) {
- return sanitizeErrorCode(data["__type"]);
- }
- }
- };
-
- class JsonShapeDeserializer extends SerdeContextConfig {
- settings;
- constructor(settings) {
- super();
- this.settings = settings;
- }
- async read(schema3, data) {
- return this._read(schema3, typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext));
- }
- readObject(schema3, data) {
- return this._read(schema3, data);
- }
- _read(schema$1, value) {
- const isObject5 = value !== null && typeof value === "object";
- const ns = schema2.NormalizedSchema.of(schema$1);
- if (isObject5) {
- if (ns.isStructSchema()) {
- const record2 = value;
- const union2 = ns.isUnionSchema();
- const out = {};
- let nameMap = undefined;
- const { jsonName } = this.settings;
- if (jsonName) {
- nameMap = {};
- }
- let unionSerde;
- if (union2) {
- unionSerde = new UnionSerde(record2, out);
- }
- for (const [memberName, memberSchema] of ns.structIterator()) {
- let fromKey = memberName;
- if (jsonName) {
- fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey;
- nameMap[fromKey] = memberName;
- }
- if (union2) {
- unionSerde.mark(fromKey);
- }
- if (record2[fromKey] != null) {
- out[memberName] = this._read(memberSchema, record2[fromKey]);
- }
- }
- if (union2) {
- unionSerde.writeUnknown();
- } else if (typeof record2.__type === "string") {
- for (const [k, v] of Object.entries(record2)) {
- const t = jsonName ? nameMap[k] ?? k : k;
- if (!(t in out)) {
- out[t] = v;
- }
- }
- }
- return out;
- }
- if (Array.isArray(value) && ns.isListSchema()) {
- const listMember = ns.getValueSchema();
- const out = [];
- for (const item of value) {
- out.push(this._read(listMember, item));
- }
- return out;
- }
- if (ns.isMapSchema()) {
- const mapMember = ns.getValueSchema();
- const out = {};
- for (const [_k, _v] of Object.entries(value)) {
- out[_k] = this._read(mapMember, _v);
- }
- return out;
- }
- }
- if (ns.isBlobSchema() && typeof value === "string") {
- return utilBase64.fromBase64(value);
- }
- const mediaType = ns.getMergedTraits().mediaType;
- if (ns.isStringSchema() && typeof value === "string" && mediaType) {
- const isJson = mediaType === "application/json" || mediaType.endsWith("+json");
- if (isJson) {
- return serde3.LazyJsonString.from(value);
- }
- return value;
- }
- if (ns.isTimestampSchema() && value != null) {
- const format3 = protocols.determineTimestampFormat(ns, this.settings);
- switch (format3) {
- case 5:
- return serde3.parseRfc3339DateTimeWithOffset(value);
- case 6:
- return serde3.parseRfc7231DateTime(value);
- case 7:
- return serde3.parseEpochTimestamp(value);
- default:
- console.warn("Missing timestamp format, parsing value with Date constructor:", value);
- return new Date(value);
- }
- }
- if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) {
- return BigInt(value);
- }
- if (ns.isBigDecimalSchema() && value != null) {
- if (value instanceof serde3.NumericValue) {
- return value;
- }
- const untyped = value;
- if (untyped.type === "bigDecimal" && "string" in untyped) {
- return new serde3.NumericValue(untyped.string, untyped.type);
- }
- return new serde3.NumericValue(String(value), "bigDecimal");
- }
- if (ns.isNumericSchema() && typeof value === "string") {
- switch (value) {
- case "Infinity":
- return Infinity;
- case "-Infinity":
- return -Infinity;
- case "NaN":
- return NaN;
- }
- return value;
- }
- if (ns.isDocumentSchema()) {
- if (isObject5) {
- const out = Array.isArray(value) ? [] : {};
- for (const [k, v] of Object.entries(value)) {
- if (v instanceof serde3.NumericValue) {
- out[k] = v;
- } else {
- out[k] = this._read(ns, v);
- }
- }
- return out;
- } else {
- return structuredClone(value);
- }
- }
- return value;
- }
- }
- var NUMERIC_CONTROL_CHAR = String.fromCharCode(925);
-
- class JsonReplacer {
- values = new Map;
- counter = 0;
- stage = 0;
- createReplacer() {
- if (this.stage === 1) {
- throw new Error("@aws-sdk/core/protocols - JsonReplacer already created.");
- }
- if (this.stage === 2) {
- throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");
- }
- this.stage = 1;
- return (key, value) => {
- if (value instanceof serde3.NumericValue) {
- const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string;
- this.values.set(`"${v}"`, value.string);
- return v;
- }
- if (typeof value === "bigint") {
- const s = value.toString();
- const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s;
- this.values.set(`"${v}"`, s);
- return v;
- }
- return value;
- };
- }
- replaceInJson(json2) {
- if (this.stage === 0) {
- throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");
- }
- if (this.stage === 2) {
- throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");
- }
- this.stage = 2;
- if (this.counter === 0) {
- return json2;
- }
- for (const [key, value] of this.values) {
- json2 = json2.replace(key, value);
- }
- return json2;
- }
- }
-
- class JsonShapeSerializer extends SerdeContextConfig {
- settings;
- buffer;
- useReplacer = false;
- rootSchema;
- constructor(settings) {
- super();
- this.settings = settings;
- }
- write(schema$1, value) {
- this.rootSchema = schema2.NormalizedSchema.of(schema$1);
- this.buffer = this._write(this.rootSchema, value);
- }
- writeDiscriminatedDocument(schema$1, value) {
- this.write(schema$1, value);
- if (typeof this.buffer === "object") {
- this.buffer.__type = schema2.NormalizedSchema.of(schema$1).getName(true);
- }
- }
- flush() {
- const { rootSchema, useReplacer } = this;
- this.rootSchema = undefined;
- this.useReplacer = false;
- if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) {
- if (!useReplacer) {
- return JSON.stringify(this.buffer);
- }
- const replacer = new JsonReplacer;
- return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0));
- }
- return this.buffer;
- }
- _write(schema$1, value, container) {
- const isObject5 = value !== null && typeof value === "object";
- const ns = schema2.NormalizedSchema.of(schema$1);
- if (isObject5) {
- if (ns.isStructSchema()) {
- const record2 = value;
- const out = {};
- const { jsonName } = this.settings;
- let nameMap = undefined;
- if (jsonName) {
- nameMap = {};
- }
- for (const [memberName, memberSchema] of ns.structIterator()) {
- const serializableValue = this._write(memberSchema, record2[memberName], ns);
- if (serializableValue !== undefined) {
- let targetKey = memberName;
- if (jsonName) {
- targetKey = memberSchema.getMergedTraits().jsonName ?? memberName;
- nameMap[memberName] = targetKey;
- }
- out[targetKey] = serializableValue;
- }
- }
- if (ns.isUnionSchema() && Object.keys(out).length === 0) {
- const { $unknown } = record2;
- if (Array.isArray($unknown)) {
- const [k, v] = $unknown;
- out[k] = this._write(15, v);
- }
- } else if (typeof record2.__type === "string") {
- for (const [k, v] of Object.entries(record2)) {
- const targetKey = jsonName ? nameMap[k] ?? k : k;
- if (!(targetKey in out)) {
- out[targetKey] = this._write(15, v);
- }
- }
- }
- return out;
- }
- if (Array.isArray(value) && ns.isListSchema()) {
- const listMember = ns.getValueSchema();
- const out = [];
- const sparse = !!ns.getMergedTraits().sparse;
- for (const item of value) {
- if (sparse || item != null) {
- out.push(this._write(listMember, item));
- }
- }
- return out;
- }
- if (ns.isMapSchema()) {
- const mapMember = ns.getValueSchema();
- const out = {};
- const sparse = !!ns.getMergedTraits().sparse;
- for (const [_k, _v] of Object.entries(value)) {
- if (sparse || _v != null) {
- out[_k] = this._write(mapMember, _v);
- }
- }
- return out;
- }
- if (value instanceof Uint8Array && (ns.isBlobSchema() || ns.isDocumentSchema())) {
- if (ns === this.rootSchema) {
- return value;
- }
- return (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value);
- }
- if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) {
- const format3 = protocols.determineTimestampFormat(ns, this.settings);
- switch (format3) {
- case 5:
- return value.toISOString().replace(".000Z", "Z");
- case 6:
- return serde3.dateToUtcString(value);
- case 7:
- return value.getTime() / 1000;
- default:
- console.warn("Missing timestamp format, using epoch seconds", value);
- return value.getTime() / 1000;
- }
- }
- if (value instanceof serde3.NumericValue) {
- this.useReplacer = true;
- }
- }
- if (value === null && container?.isStructSchema()) {
- return;
- }
- if (ns.isStringSchema()) {
- if (typeof value === "undefined" && ns.isIdempotencyToken()) {
- return serde3.generateIdempotencyToken();
- }
- const mediaType = ns.getMergedTraits().mediaType;
- if (value != null && mediaType) {
- const isJson = mediaType === "application/json" || mediaType.endsWith("+json");
- if (isJson) {
- return serde3.LazyJsonString.from(value);
- }
- }
- return value;
- }
- if (typeof value === "number" && ns.isNumericSchema()) {
- if (Math.abs(value) === Infinity || isNaN(value)) {
- return String(value);
- }
- return value;
- }
- if (typeof value === "string" && ns.isBlobSchema()) {
- if (ns === this.rootSchema) {
- return value;
- }
- return (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value);
- }
- if (typeof value === "bigint") {
- this.useReplacer = true;
- }
- if (ns.isDocumentSchema()) {
- if (isObject5) {
- const out = Array.isArray(value) ? [] : {};
- for (const [k, v] of Object.entries(value)) {
- if (v instanceof serde3.NumericValue) {
- this.useReplacer = true;
- out[k] = v;
- } else {
- out[k] = this._write(ns, v);
- }
- }
- return out;
- } else {
- return structuredClone(value);
- }
- }
- return value;
- }
- }
-
- class JsonCodec extends SerdeContextConfig {
- settings;
- constructor(settings) {
- super();
- this.settings = settings;
- }
- createSerializer() {
- const serializer = new JsonShapeSerializer(this.settings);
- serializer.setSerdeContext(this.serdeContext);
- return serializer;
- }
- createDeserializer() {
- const deserializer = new JsonShapeDeserializer(this.settings);
- deserializer.setSerdeContext(this.serdeContext);
- return deserializer;
- }
- }
-
- class AwsJsonRpcProtocol extends protocols.RpcProtocol {
- serializer;
- deserializer;
- serviceTarget;
- codec;
- mixin;
- awsQueryCompatible;
- constructor({ defaultNamespace, errorTypeRegistries, serviceTarget, awsQueryCompatible, jsonCodec }) {
- super({
- defaultNamespace,
- errorTypeRegistries
- });
- this.serviceTarget = serviceTarget;
- this.codec = jsonCodec ?? new JsonCodec({
- timestampFormat: {
- useTrait: true,
- default: 7
- },
- jsonName: false
- });
- this.serializer = this.codec.createSerializer();
- this.deserializer = this.codec.createDeserializer();
- this.awsQueryCompatible = !!awsQueryCompatible;
- this.mixin = new ProtocolLib(this.awsQueryCompatible);
- }
- async serializeRequest(operationSchema, input, context) {
- const request2 = await super.serializeRequest(operationSchema, input, context);
- if (!request2.path.endsWith("/")) {
- request2.path += "/";
- }
- Object.assign(request2.headers, {
- "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`,
- "x-amz-target": `${this.serviceTarget}.${operationSchema.name}`
- });
- if (this.awsQueryCompatible) {
- request2.headers["x-amzn-query-mode"] = "true";
- }
- if (schema2.deref(operationSchema.input) === "unit" || !request2.body) {
- request2.body = "{}";
- }
- return request2;
- }
- getPayloadCodec() {
- return this.codec;
- }
- async handleError(operationSchema, context, response2, dataObject, metadata) {
- if (this.awsQueryCompatible) {
- this.mixin.setQueryCompatError(dataObject, response2);
- }
- const errorIdentifier = loadRestJsonErrorCode(response2, dataObject) ?? "Unknown";
- this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace);
- const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response2, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : undefined);
- const ns = schema2.NormalizedSchema.of(errorSchema);
- const message = dataObject.message ?? dataObject.Message ?? "UnknownError";
- const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error;
- const exception = new ErrorCtor(message);
- const output = {};
- for (const [name, member] of ns.structIterator()) {
- if (dataObject[name] != null) {
- output[name] = this.codec.createDeserializer().readObject(member, dataObject[name]);
- }
- }
- if (this.awsQueryCompatible) {
- this.mixin.queryCompatOutput(dataObject, output);
- }
- throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {
- $fault: ns.getMergedTraits().error,
- message
- }, output), dataObject);
- }
- }
-
- class AwsJson1_0Protocol extends AwsJsonRpcProtocol {
- constructor({ defaultNamespace, errorTypeRegistries, serviceTarget, awsQueryCompatible, jsonCodec }) {
- super({
- defaultNamespace,
- errorTypeRegistries,
- serviceTarget,
- awsQueryCompatible,
- jsonCodec
- });
- }
- getShapeId() {
- return "aws.protocols#awsJson1_0";
- }
- getJsonRpcVersion() {
- return "1.0";
- }
- getDefaultContentType() {
- return "application/x-amz-json-1.0";
- }
- }
-
- class AwsJson1_1Protocol extends AwsJsonRpcProtocol {
- constructor({ defaultNamespace, errorTypeRegistries, serviceTarget, awsQueryCompatible, jsonCodec }) {
- super({
- defaultNamespace,
- errorTypeRegistries,
- serviceTarget,
- awsQueryCompatible,
- jsonCodec
- });
- }
- getShapeId() {
- return "aws.protocols#awsJson1_1";
- }
- getJsonRpcVersion() {
- return "1.1";
- }
- getDefaultContentType() {
- return "application/x-amz-json-1.1";
- }
- }
-
- class AwsRestJsonProtocol extends protocols.HttpBindingProtocol {
- serializer;
- deserializer;
- codec;
- mixin = new ProtocolLib;
- constructor({ defaultNamespace, errorTypeRegistries }) {
- super({
- defaultNamespace,
- errorTypeRegistries
- });
- const settings = {
- timestampFormat: {
- useTrait: true,
- default: 7
- },
- httpBindings: true,
- jsonName: true
- };
- this.codec = new JsonCodec(settings);
- this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings);
- this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings);
- }
- getShapeId() {
- return "aws.protocols#restJson1";
- }
- getPayloadCodec() {
- return this.codec;
- }
- setSerdeContext(serdeContext) {
- this.codec.setSerdeContext(serdeContext);
- super.setSerdeContext(serdeContext);
- }
- async serializeRequest(operationSchema, input, context) {
- const request2 = await super.serializeRequest(operationSchema, input, context);
- const inputSchema = schema2.NormalizedSchema.of(operationSchema.input);
- if (!request2.headers["content-type"]) {
- const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema);
- if (contentType) {
- request2.headers["content-type"] = contentType;
- }
- }
- if (request2.body == null && request2.headers["content-type"] === this.getDefaultContentType()) {
- request2.body = "{}";
- }
- return request2;
- }
- async deserializeResponse(operationSchema, context, response2) {
- const output = await super.deserializeResponse(operationSchema, context, response2);
- const outputSchema = schema2.NormalizedSchema.of(operationSchema.output);
- for (const [name, member] of outputSchema.structIterator()) {
- if (member.getMemberTraits().httpPayload && !(name in output)) {
- output[name] = null;
- }
- }
- return output;
- }
- async handleError(operationSchema, context, response2, dataObject, metadata) {
- const errorIdentifier = loadRestJsonErrorCode(response2, dataObject) ?? "Unknown";
- this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace);
- const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response2, dataObject, metadata);
- const ns = schema2.NormalizedSchema.of(errorSchema);
- const message = dataObject.message ?? dataObject.Message ?? "UnknownError";
- const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error;
- const exception = new ErrorCtor(message);
- await this.deserializeHttpMessage(errorSchema, context, response2, dataObject);
- const output = {};
- for (const [name, member] of ns.structIterator()) {
- const target = member.getMergedTraits().jsonName ?? name;
- output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]);
- }
- throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {
- $fault: ns.getMergedTraits().error,
- message
- }, output), dataObject);
- }
- getDefaultContentType() {
- return "application/json";
- }
- }
- var awsExpectUnion = (value) => {
- if (value == null) {
- return;
- }
- if (typeof value === "object" && "__type" in value) {
- delete value.__type;
- }
- return smithyClient.expectUnion(value);
- };
-
- class XmlShapeDeserializer extends SerdeContextConfig {
- settings;
- stringDeserializer;
- constructor(settings) {
- super();
- this.settings = settings;
- this.stringDeserializer = new protocols.FromStringShapeDeserializer(settings);
- }
- setSerdeContext(serdeContext) {
- this.serdeContext = serdeContext;
- this.stringDeserializer.setSerdeContext(serdeContext);
- }
- read(schema$1, bytes, key) {
- const ns = schema2.NormalizedSchema.of(schema$1);
- const memberSchemas = ns.getMemberSchemas();
- const isEventPayload = ns.isStructSchema() && ns.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => {
- return !!memberNs.getMemberTraits().eventPayload;
- });
- if (isEventPayload) {
- const output = {};
- const memberName = Object.keys(memberSchemas)[0];
- const eventMemberSchema = memberSchemas[memberName];
- if (eventMemberSchema.isBlobSchema()) {
- output[memberName] = bytes;
- } else {
- output[memberName] = this.read(memberSchemas[memberName], bytes);
- }
- return output;
- }
- const xmlString = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(bytes);
- const parsedObject = this.parseXml(xmlString);
- return this.readSchema(schema$1, key ? parsedObject[key] : parsedObject);
- }
- readSchema(_schema, value) {
- const ns = schema2.NormalizedSchema.of(_schema);
- if (ns.isUnitSchema()) {
- return;
- }
- const traits2 = ns.getMergedTraits();
- if (ns.isListSchema() && !Array.isArray(value)) {
- return this.readSchema(ns, [value]);
- }
- if (value == null) {
- return value;
- }
- if (typeof value === "object") {
- const flat = !!traits2.xmlFlattened;
- if (ns.isListSchema()) {
- const listValue = ns.getValueSchema();
- const buffer2 = [];
- const sourceKey = listValue.getMergedTraits().xmlName ?? "member";
- const source = flat ? value : (value[0] ?? value)[sourceKey];
- if (source == null) {
- return buffer2;
- }
- const sourceArray = Array.isArray(source) ? source : [source];
- for (const v of sourceArray) {
- buffer2.push(this.readSchema(listValue, v));
- }
- return buffer2;
- }
- const buffer = {};
- if (ns.isMapSchema()) {
- const keyNs = ns.getKeySchema();
- const memberNs = ns.getValueSchema();
- let entries;
- if (flat) {
- entries = Array.isArray(value) ? value : [value];
- } else {
- entries = Array.isArray(value.entry) ? value.entry : [value.entry];
- }
- const keyProperty = keyNs.getMergedTraits().xmlName ?? "key";
- const valueProperty = memberNs.getMergedTraits().xmlName ?? "value";
- for (const entry of entries) {
- const key = entry[keyProperty];
- const value2 = entry[valueProperty];
- buffer[key] = this.readSchema(memberNs, value2);
- }
- return buffer;
- }
- if (ns.isStructSchema()) {
- const union2 = ns.isUnionSchema();
- let unionSerde;
- if (union2) {
- unionSerde = new UnionSerde(value, buffer);
- }
- for (const [memberName, memberSchema] of ns.structIterator()) {
- const memberTraits = memberSchema.getMergedTraits();
- const xmlObjectKey = !memberTraits.httpPayload ? memberSchema.getMemberTraits().xmlName ?? memberName : memberTraits.xmlName ?? memberSchema.getName();
- if (union2) {
- unionSerde.mark(xmlObjectKey);
- }
- if (value[xmlObjectKey] != null) {
- buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]);
- }
- }
- if (union2) {
- unionSerde.writeUnknown();
- }
- return buffer;
- }
- if (ns.isDocumentSchema()) {
- return value;
- }
- throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`);
- }
- if (ns.isListSchema()) {
- return [];
- }
- if (ns.isMapSchema() || ns.isStructSchema()) {
- return {};
- }
- return this.stringDeserializer.read(ns, value);
- }
- parseXml(xml) {
- if (xml.length) {
- let parsedObj;
- try {
- parsedObj = xmlBuilder.parseXML(xml);
- } catch (e) {
- if (e && typeof e === "object") {
- Object.defineProperty(e, "$responseBodyText", {
- value: xml
- });
- }
- throw e;
- }
- const textNodeName = "#text";
- const key = Object.keys(parsedObj)[0];
- const parsedObjToReturn = parsedObj[key];
- if (parsedObjToReturn[textNodeName]) {
- parsedObjToReturn[key] = parsedObjToReturn[textNodeName];
- delete parsedObjToReturn[textNodeName];
- }
- return smithyClient.getValueFromTextNode(parsedObjToReturn);
- }
- return {};
- }
- }
-
- class QueryShapeSerializer extends SerdeContextConfig {
- settings;
- buffer;
- constructor(settings) {
- super();
- this.settings = settings;
- }
- write(schema$1, value, prefix = "") {
- if (this.buffer === undefined) {
- this.buffer = "";
- }
- const ns = schema2.NormalizedSchema.of(schema$1);
- if (prefix && !prefix.endsWith(".")) {
- prefix += ".";
- }
- if (ns.isBlobSchema()) {
- if (typeof value === "string" || value instanceof Uint8Array) {
- this.writeKey(prefix);
- this.writeValue((this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value));
- }
- } else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) {
- if (value != null) {
- this.writeKey(prefix);
- this.writeValue(String(value));
- } else if (ns.isIdempotencyToken()) {
- this.writeKey(prefix);
- this.writeValue(serde3.generateIdempotencyToken());
- }
- } else if (ns.isBigIntegerSchema()) {
- if (value != null) {
- this.writeKey(prefix);
- this.writeValue(String(value));
- }
- } else if (ns.isBigDecimalSchema()) {
- if (value != null) {
- this.writeKey(prefix);
- this.writeValue(value instanceof serde3.NumericValue ? value.string : String(value));
- }
- } else if (ns.isTimestampSchema()) {
- if (value instanceof Date) {
- this.writeKey(prefix);
- const format3 = protocols.determineTimestampFormat(ns, this.settings);
- switch (format3) {
- case 5:
- this.writeValue(value.toISOString().replace(".000Z", "Z"));
- break;
- case 6:
- this.writeValue(smithyClient.dateToUtcString(value));
- break;
- case 7:
- this.writeValue(String(value.getTime() / 1000));
- break;
- }
- }
- } else if (ns.isDocumentSchema()) {
- if (Array.isArray(value)) {
- this.write(64 | 15, value, prefix);
- } else if (value instanceof Date) {
- this.write(4, value, prefix);
- } else if (value instanceof Uint8Array) {
- this.write(21, value, prefix);
- } else if (value && typeof value === "object") {
- this.write(128 | 15, value, prefix);
- } else {
- this.writeKey(prefix);
- this.writeValue(String(value));
- }
- } else if (ns.isListSchema()) {
- if (Array.isArray(value)) {
- if (value.length === 0) {
- if (this.settings.serializeEmptyLists) {
- this.writeKey(prefix);
- this.writeValue("");
- }
- } else {
- const member = ns.getValueSchema();
- const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened;
- let i2 = 1;
- for (const item of value) {
- if (item == null) {
- continue;
- }
- const traits2 = member.getMergedTraits();
- const suffix = this.getKey("member", traits2.xmlName, traits2.ec2QueryName);
- const key = flat ? `${prefix}${i2}` : `${prefix}${suffix}.${i2}`;
- this.write(member, item, key);
- ++i2;
- }
- }
- }
- } else if (ns.isMapSchema()) {
- if (value && typeof value === "object") {
- const keySchema = ns.getKeySchema();
- const memberSchema = ns.getValueSchema();
- const flat = ns.getMergedTraits().xmlFlattened;
- let i2 = 1;
- for (const [k, v] of Object.entries(value)) {
- if (v == null) {
- continue;
- }
- const keyTraits = keySchema.getMergedTraits();
- const keySuffix = this.getKey("key", keyTraits.xmlName, keyTraits.ec2QueryName);
- const key = flat ? `${prefix}${i2}.${keySuffix}` : `${prefix}entry.${i2}.${keySuffix}`;
- const valTraits = memberSchema.getMergedTraits();
- const valueSuffix = this.getKey("value", valTraits.xmlName, valTraits.ec2QueryName);
- const valueKey = flat ? `${prefix}${i2}.${valueSuffix}` : `${prefix}entry.${i2}.${valueSuffix}`;
- this.write(keySchema, k, key);
- this.write(memberSchema, v, valueKey);
- ++i2;
- }
- }
- } else if (ns.isStructSchema()) {
- if (value && typeof value === "object") {
- let didWriteMember = false;
- for (const [memberName, member] of ns.structIterator()) {
- if (value[memberName] == null && !member.isIdempotencyToken()) {
- continue;
- }
- const traits2 = member.getMergedTraits();
- const suffix = this.getKey(memberName, traits2.xmlName, traits2.ec2QueryName, "struct");
- const key = `${prefix}${suffix}`;
- this.write(member, value[memberName], key);
- didWriteMember = true;
- }
- if (!didWriteMember && ns.isUnionSchema()) {
- const { $unknown } = value;
- if (Array.isArray($unknown)) {
- const [k, v] = $unknown;
- const key = `${prefix}${k}`;
- this.write(15, v, key);
- }
- }
- }
- } else if (ns.isUnitSchema())
- ;
- else {
- throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`);
- }
- }
- flush() {
- if (this.buffer === undefined) {
- throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");
- }
- const str = this.buffer;
- delete this.buffer;
- return str;
- }
- getKey(memberName, xmlName, ec2QueryName, keySource) {
- const { ec2, capitalizeKeys } = this.settings;
- if (ec2 && ec2QueryName) {
- return ec2QueryName;
- }
- const key = xmlName ?? memberName;
- if (capitalizeKeys && keySource === "struct") {
- return key[0].toUpperCase() + key.slice(1);
- }
- return key;
- }
- writeKey(key) {
- if (key.endsWith(".")) {
- key = key.slice(0, key.length - 1);
- }
- this.buffer += `&${protocols.extendedEncodeURIComponent(key)}=`;
- }
- writeValue(value) {
- this.buffer += protocols.extendedEncodeURIComponent(value);
- }
- }
-
- class AwsQueryProtocol extends protocols.RpcProtocol {
- options;
- serializer;
- deserializer;
- mixin = new ProtocolLib;
- constructor(options2) {
- super({
- defaultNamespace: options2.defaultNamespace,
- errorTypeRegistries: options2.errorTypeRegistries
- });
- this.options = options2;
- const settings = {
- timestampFormat: {
- useTrait: true,
- default: 5
- },
- httpBindings: false,
- xmlNamespace: options2.xmlNamespace,
- serviceNamespace: options2.defaultNamespace,
- serializeEmptyLists: true
- };
- this.serializer = new QueryShapeSerializer(settings);
- this.deserializer = new XmlShapeDeserializer(settings);
- }
- getShapeId() {
- return "aws.protocols#awsQuery";
- }
- setSerdeContext(serdeContext) {
- this.serializer.setSerdeContext(serdeContext);
- this.deserializer.setSerdeContext(serdeContext);
- }
- getPayloadCodec() {
- throw new Error("AWSQuery protocol has no payload codec.");
- }
- async serializeRequest(operationSchema, input, context) {
- const request2 = await super.serializeRequest(operationSchema, input, context);
- if (!request2.path.endsWith("/")) {
- request2.path += "/";
- }
- Object.assign(request2.headers, {
- "content-type": `application/x-www-form-urlencoded`
- });
- if (schema2.deref(operationSchema.input) === "unit" || !request2.body) {
- request2.body = "";
- }
- const action = operationSchema.name.split("#")[1] ?? operationSchema.name;
- request2.body = `Action=${action}&Version=${this.options.version}` + request2.body;
- if (request2.body.endsWith("&")) {
- request2.body = request2.body.slice(-1);
- }
- return request2;
- }
- async deserializeResponse(operationSchema, context, response2) {
- const deserializer = this.deserializer;
- const ns = schema2.NormalizedSchema.of(operationSchema.output);
- const dataObject = {};
- if (response2.statusCode >= 300) {
- const bytes2 = await protocols.collectBody(response2.body, context);
- if (bytes2.byteLength > 0) {
- Object.assign(dataObject, await deserializer.read(15, bytes2));
- }
- await this.handleError(operationSchema, context, response2, dataObject, this.deserializeMetadata(response2));
- }
- for (const header in response2.headers) {
- const value = response2.headers[header];
- delete response2.headers[header];
- response2.headers[header.toLowerCase()] = value;
- }
- const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name;
- const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : undefined;
- const bytes = await protocols.collectBody(response2.body, context);
- if (bytes.byteLength > 0) {
- Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey));
- }
- const output = {
- $metadata: this.deserializeMetadata(response2),
- ...dataObject
- };
- return output;
- }
- useNestedResult() {
- return true;
- }
- async handleError(operationSchema, context, response2, dataObject, metadata) {
- const errorIdentifier = this.loadQueryErrorCode(response2, dataObject) ?? "Unknown";
- this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace);
- const errorData = this.loadQueryError(dataObject) ?? {};
- const message = this.loadQueryErrorMessage(dataObject);
- errorData.message = message;
- errorData.Error = {
- Type: errorData.Type,
- Code: errorData.Code,
- Message: message
- };
- const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response2, errorData, metadata, this.mixin.findQueryCompatibleError);
- const ns = schema2.NormalizedSchema.of(errorSchema);
- const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error;
- const exception = new ErrorCtor(message);
- const output = {
- Type: errorData.Error.Type,
- Code: errorData.Error.Code,
- Error: errorData.Error
- };
- for (const [name, member] of ns.structIterator()) {
- const target = member.getMergedTraits().xmlName ?? name;
- const value = errorData[target] ?? dataObject[target];
- output[name] = this.deserializer.readSchema(member, value);
- }
- throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {
- $fault: ns.getMergedTraits().error,
- message
- }, output), dataObject);
- }
- loadQueryErrorCode(output, data) {
- const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code;
- if (code !== undefined) {
- return code;
- }
- if (output.statusCode == 404) {
- return "NotFound";
- }
- }
- loadQueryError(data) {
- return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error;
- }
- loadQueryErrorMessage(data) {
- const errorData = this.loadQueryError(data);
- return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown";
- }
- getDefaultContentType() {
- return "application/x-www-form-urlencoded";
- }
- }
-
- class AwsEc2QueryProtocol extends AwsQueryProtocol {
- options;
- constructor(options2) {
- super(options2);
- this.options = options2;
- const ec2Settings = {
- capitalizeKeys: true,
- flattenLists: true,
- serializeEmptyLists: false,
- ec2: true
- };
- Object.assign(this.serializer.settings, ec2Settings);
- }
- getShapeId() {
- return "aws.protocols#ec2Query";
- }
- useNestedResult() {
- return false;
- }
- }
- var parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
- if (encoded.length) {
- let parsedObj;
- try {
- parsedObj = xmlBuilder.parseXML(encoded);
- } catch (e) {
- if (e && typeof e === "object") {
- Object.defineProperty(e, "$responseBodyText", {
- value: encoded
- });
- }
- throw e;
- }
- const textNodeName = "#text";
- const key = Object.keys(parsedObj)[0];
- const parsedObjToReturn = parsedObj[key];
- if (parsedObjToReturn[textNodeName]) {
- parsedObjToReturn[key] = parsedObjToReturn[textNodeName];
- delete parsedObjToReturn[textNodeName];
- }
- return smithyClient.getValueFromTextNode(parsedObjToReturn);
- }
- return {};
- });
- var parseXmlErrorBody = async (errorBody, context) => {
- const value = await parseXmlBody(errorBody, context);
- if (value.Error) {
- value.Error.message = value.Error.message ?? value.Error.Message;
- }
- return value;
- };
- var loadRestXmlErrorCode = (output, data) => {
- if (data?.Error?.Code !== undefined) {
- return data.Error.Code;
- }
- if (data?.Code !== undefined) {
- return data.Code;
- }
- if (output.statusCode == 404) {
- return "NotFound";
- }
- };
-
- class XmlShapeSerializer extends SerdeContextConfig {
- settings;
- stringBuffer;
- byteBuffer;
- buffer;
- constructor(settings) {
- super();
- this.settings = settings;
- }
- write(schema$1, value) {
- const ns = schema2.NormalizedSchema.of(schema$1);
- if (ns.isStringSchema() && typeof value === "string") {
- this.stringBuffer = value;
- } else if (ns.isBlobSchema()) {
- this.byteBuffer = "byteLength" in value ? value : (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(value);
- } else {
- this.buffer = this.writeStruct(ns, value, undefined);
- const traits2 = ns.getMergedTraits();
- if (traits2.httpPayload && !traits2.xmlName) {
- this.buffer.withName(ns.getName());
- }
- }
- }
- flush() {
- if (this.byteBuffer !== undefined) {
- const bytes = this.byteBuffer;
- delete this.byteBuffer;
- return bytes;
- }
- if (this.stringBuffer !== undefined) {
- const str = this.stringBuffer;
- delete this.stringBuffer;
- return str;
- }
- const buffer = this.buffer;
- if (this.settings.xmlNamespace) {
- if (!buffer?.attributes?.["xmlns"]) {
- buffer.addAttribute("xmlns", this.settings.xmlNamespace);
- }
- }
- delete this.buffer;
- return buffer.toString();
- }
- writeStruct(ns, value, parentXmlns) {
- const traits2 = ns.getMergedTraits();
- const name = ns.isMemberSchema() && !traits2.httpPayload ? ns.getMemberTraits().xmlName ?? ns.getMemberName() : traits2.xmlName ?? ns.getName();
- if (!name || !ns.isStructSchema()) {
- throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`);
- }
- const structXmlNode = xmlBuilder.XmlNode.of(name);
- const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns);
- for (const [memberName, memberSchema] of ns.structIterator()) {
- const val = value[memberName];
- if (val != null || memberSchema.isIdempotencyToken()) {
- if (memberSchema.getMergedTraits().xmlAttribute) {
- structXmlNode.addAttribute(memberSchema.getMergedTraits().xmlName ?? memberName, this.writeSimple(memberSchema, val));
- continue;
- }
- if (memberSchema.isListSchema()) {
- this.writeList(memberSchema, val, structXmlNode, xmlns);
- } else if (memberSchema.isMapSchema()) {
- this.writeMap(memberSchema, val, structXmlNode, xmlns);
- } else if (memberSchema.isStructSchema()) {
- structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns));
- } else {
- const memberNode = xmlBuilder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName());
- this.writeSimpleInto(memberSchema, val, memberNode, xmlns);
- structXmlNode.addChildNode(memberNode);
- }
- }
- }
- const { $unknown } = value;
- if ($unknown && ns.isUnionSchema() && Array.isArray($unknown) && Object.keys(value).length === 1) {
- const [k, v] = $unknown;
- const node = xmlBuilder.XmlNode.of(k);
- if (typeof v !== "string") {
- if (value instanceof xmlBuilder.XmlNode || value instanceof xmlBuilder.XmlText) {
- structXmlNode.addChildNode(value);
- } else {
- throw new Error(`@aws-sdk - $unknown union member in XML requires ` + `value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.`);
- }
- }
- this.writeSimpleInto(0, v, node, xmlns);
- structXmlNode.addChildNode(node);
- }
- if (xmlns) {
- structXmlNode.addAttribute(xmlnsAttr, xmlns);
- }
- return structXmlNode;
- }
- writeList(listMember, array2, container, parentXmlns) {
- if (!listMember.isMemberSchema()) {
- throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}`);
- }
- const listTraits = listMember.getMergedTraits();
- const listValueSchema = listMember.getValueSchema();
- const listValueTraits = listValueSchema.getMergedTraits();
- const sparse = !!listValueTraits.sparse;
- const flat = !!listTraits.xmlFlattened;
- const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns);
- const writeItem = (container2, value) => {
- if (listValueSchema.isListSchema()) {
- this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container2, xmlns);
- } else if (listValueSchema.isMapSchema()) {
- this.writeMap(listValueSchema, value, container2, xmlns);
- } else if (listValueSchema.isStructSchema()) {
- const struct = this.writeStruct(listValueSchema, value, xmlns);
- container2.addChildNode(struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member"));
- } else {
- const listItemNode = xmlBuilder.XmlNode.of(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member");
- this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns);
- container2.addChildNode(listItemNode);
- }
- };
- if (flat) {
- for (const value of array2) {
- if (sparse || value != null) {
- writeItem(container, value);
- }
- }
- } else {
- const listNode = xmlBuilder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName());
- if (xmlns) {
- listNode.addAttribute(xmlnsAttr, xmlns);
- }
- for (const value of array2) {
- if (sparse || value != null) {
- writeItem(listNode, value);
- }
- }
- container.addChildNode(listNode);
- }
- }
- writeMap(mapMember, map3, container, parentXmlns, containerIsMap = false) {
- if (!mapMember.isMemberSchema()) {
- throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}`);
- }
- const mapTraits = mapMember.getMergedTraits();
- const mapKeySchema = mapMember.getKeySchema();
- const mapKeyTraits = mapKeySchema.getMergedTraits();
- const keyTag = mapKeyTraits.xmlName ?? "key";
- const mapValueSchema = mapMember.getValueSchema();
- const mapValueTraits = mapValueSchema.getMergedTraits();
- const valueTag = mapValueTraits.xmlName ?? "value";
- const sparse = !!mapValueTraits.sparse;
- const flat = !!mapTraits.xmlFlattened;
- const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns);
- const addKeyValue = (entry, key, val) => {
- const keyNode = xmlBuilder.XmlNode.of(keyTag, key);
- const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns);
- if (keyXmlns) {
- keyNode.addAttribute(keyXmlnsAttr, keyXmlns);
- }
- entry.addChildNode(keyNode);
- let valueNode = xmlBuilder.XmlNode.of(valueTag);
- if (mapValueSchema.isListSchema()) {
- this.writeList(mapValueSchema, val, valueNode, xmlns);
- } else if (mapValueSchema.isMapSchema()) {
- this.writeMap(mapValueSchema, val, valueNode, xmlns, true);
- } else if (mapValueSchema.isStructSchema()) {
- valueNode = this.writeStruct(mapValueSchema, val, xmlns);
- } else {
- this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns);
- }
- entry.addChildNode(valueNode);
- };
- if (flat) {
- for (const [key, val] of Object.entries(map3)) {
- if (sparse || val != null) {
- const entry = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName());
- addKeyValue(entry, key, val);
- container.addChildNode(entry);
- }
- }
- } else {
- let mapNode2;
- if (!containerIsMap) {
- mapNode2 = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName());
- if (xmlns) {
- mapNode2.addAttribute(xmlnsAttr, xmlns);
- }
- container.addChildNode(mapNode2);
- }
- for (const [key, val] of Object.entries(map3)) {
- if (sparse || val != null) {
- const entry = xmlBuilder.XmlNode.of("entry");
- addKeyValue(entry, key, val);
- (containerIsMap ? container : mapNode2).addChildNode(entry);
- }
- }
- }
- }
- writeSimple(_schema, value) {
- if (value === null) {
- throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");
- }
- const ns = schema2.NormalizedSchema.of(_schema);
- let nodeContents = null;
- if (value && typeof value === "object") {
- if (ns.isBlobSchema()) {
- nodeContents = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value);
- } else if (ns.isTimestampSchema() && value instanceof Date) {
- const format3 = protocols.determineTimestampFormat(ns, this.settings);
- switch (format3) {
- case 5:
- nodeContents = value.toISOString().replace(".000Z", "Z");
- break;
- case 6:
- nodeContents = smithyClient.dateToUtcString(value);
- break;
- case 7:
- nodeContents = String(value.getTime() / 1000);
- break;
- default:
- console.warn("Missing timestamp format, using http date", value);
- nodeContents = smithyClient.dateToUtcString(value);
- break;
- }
- } else if (ns.isBigDecimalSchema() && value) {
- if (value instanceof serde3.NumericValue) {
- return value.string;
- }
- return String(value);
- } else if (ns.isMapSchema() || ns.isListSchema()) {
- throw new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead.");
- } else {
- throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`);
- }
- }
- if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) {
- nodeContents = String(value);
- }
- if (ns.isStringSchema()) {
- if (value === undefined && ns.isIdempotencyToken()) {
- nodeContents = serde3.generateIdempotencyToken();
- } else {
- nodeContents = String(value);
- }
- }
- if (nodeContents === null) {
- throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`);
- }
- return nodeContents;
- }
- writeSimpleInto(_schema, value, into, parentXmlns) {
- const nodeContents = this.writeSimple(_schema, value);
- const ns = schema2.NormalizedSchema.of(_schema);
- const content = new xmlBuilder.XmlText(nodeContents);
- const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns);
- if (xmlns) {
- into.addAttribute(xmlnsAttr, xmlns);
- }
- into.addChildNode(content);
- }
- getXmlnsAttribute(ns, parentXmlns) {
- const traits2 = ns.getMergedTraits();
- const [prefix, xmlns] = traits2.xmlNamespace ?? [];
- if (xmlns && xmlns !== parentXmlns) {
- return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns];
- }
- return [undefined, undefined];
- }
- }
-
- class XmlCodec extends SerdeContextConfig {
- settings;
- constructor(settings) {
- super();
- this.settings = settings;
- }
- createSerializer() {
- const serializer = new XmlShapeSerializer(this.settings);
- serializer.setSerdeContext(this.serdeContext);
- return serializer;
- }
- createDeserializer() {
- const deserializer = new XmlShapeDeserializer(this.settings);
- deserializer.setSerdeContext(this.serdeContext);
- return deserializer;
- }
- }
-
- class AwsRestXmlProtocol extends protocols.HttpBindingProtocol {
- codec;
- serializer;
- deserializer;
- mixin = new ProtocolLib;
- constructor(options2) {
- super(options2);
- const settings = {
- timestampFormat: {
- useTrait: true,
- default: 5
- },
- httpBindings: true,
- xmlNamespace: options2.xmlNamespace,
- serviceNamespace: options2.defaultNamespace
- };
- this.codec = new XmlCodec(settings);
- this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings);
- this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings);
- this.compositeErrorRegistry;
- }
- getPayloadCodec() {
- return this.codec;
- }
- getShapeId() {
- return "aws.protocols#restXml";
- }
- async serializeRequest(operationSchema, input, context) {
- const request2 = await super.serializeRequest(operationSchema, input, context);
- const inputSchema = schema2.NormalizedSchema.of(operationSchema.input);
- if (!request2.headers["content-type"]) {
- const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema);
- if (contentType) {
- request2.headers["content-type"] = contentType;
- }
- }
- if (typeof request2.body === "string" && request2.headers["content-type"] === this.getDefaultContentType() && !request2.body.startsWith("' + request2.body;
- }
- return request2;
- }
- async deserializeResponse(operationSchema, context, response2) {
- return super.deserializeResponse(operationSchema, context, response2);
- }
- async handleError(operationSchema, context, response2, dataObject, metadata) {
- const errorIdentifier = loadRestXmlErrorCode(response2, dataObject) ?? "Unknown";
- this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace);
- if (dataObject.Error && typeof dataObject.Error === "object") {
- for (const key of Object.keys(dataObject.Error)) {
- dataObject[key] = dataObject.Error[key];
- if (key.toLowerCase() === "message") {
- dataObject.message = dataObject.Error[key];
- }
- }
- }
- if (dataObject.RequestId && !metadata.requestId) {
- metadata.requestId = dataObject.RequestId;
- }
- const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response2, dataObject, metadata);
- const ns = schema2.NormalizedSchema.of(errorSchema);
- const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "UnknownError";
- const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error;
- const exception = new ErrorCtor(message);
- await this.deserializeHttpMessage(errorSchema, context, response2, dataObject);
- const output = {};
- for (const [name, member] of ns.structIterator()) {
- const target = member.getMergedTraits().xmlName ?? name;
- const value = dataObject.Error?.[target] ?? dataObject[target];
- output[name] = this.codec.createDeserializer().readSchema(member, value);
- }
- throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {
- $fault: ns.getMergedTraits().error,
- message
- }, output), dataObject);
- }
- getDefaultContentType() {
- return "application/xml";
- }
- hasUnstructuredPayloadBinding(ns) {
- for (const [, member] of ns.structIterator()) {
- if (member.getMergedTraits().httpPayload) {
- return !(member.isStructSchema() || member.isMapSchema() || member.isListSchema());
- }
- }
- return false;
- }
- }
- exports.AwsEc2QueryProtocol = AwsEc2QueryProtocol;
- exports.AwsJson1_0Protocol = AwsJson1_0Protocol;
- exports.AwsJson1_1Protocol = AwsJson1_1Protocol;
- exports.AwsJsonRpcProtocol = AwsJsonRpcProtocol;
- exports.AwsQueryProtocol = AwsQueryProtocol;
- exports.AwsRestJsonProtocol = AwsRestJsonProtocol;
- exports.AwsRestXmlProtocol = AwsRestXmlProtocol;
- exports.AwsSmithyRpcV2CborProtocol = AwsSmithyRpcV2CborProtocol;
- exports.JsonCodec = JsonCodec;
- exports.JsonShapeDeserializer = JsonShapeDeserializer;
- exports.JsonShapeSerializer = JsonShapeSerializer;
- exports.QueryShapeSerializer = QueryShapeSerializer;
- exports.XmlCodec = XmlCodec;
- exports.XmlShapeDeserializer = XmlShapeDeserializer;
- exports.XmlShapeSerializer = XmlShapeSerializer;
- exports._toBool = _toBool;
- exports._toNum = _toNum;
- exports._toStr = _toStr;
- exports.awsExpectUnion = awsExpectUnion;
- exports.loadRestJsonErrorCode = loadRestJsonErrorCode;
- exports.loadRestXmlErrorCode = loadRestXmlErrorCode;
- exports.parseJsonBody = parseJsonBody;
- exports.parseJsonErrorBody = parseJsonErrorBody;
- exports.parseXmlBody = parseXmlBody;
- exports.parseXmlErrorBody = parseXmlErrorBody;
-});
-
-// node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
-var require_dist_cjs84 = __commonJS((exports) => {
- var isArrayBuffer3 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
- exports.isArrayBuffer = isArrayBuffer3;
-});
-
-// node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
-var require_dist_cjs85 = __commonJS((exports) => {
- var isArrayBuffer3 = require_dist_cjs84();
- var buffer = __require("buffer");
- var fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
- if (!isArrayBuffer3.isArrayBuffer(input)) {
- throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
- }
- return buffer.Buffer.from(input, offset, length);
- };
- var fromString = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input);
- };
- exports.fromArrayBuffer = fromArrayBuffer;
- exports.fromString = fromString;
-});
-
-// node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js
-var require_fromBase645 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.fromBase64 = undefined;
- var util_buffer_from_1 = require_dist_cjs85();
- var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
- var fromBase64 = (input) => {
- if (input.length * 3 % 4 !== 0) {
- throw new TypeError(`Incorrect padding on base64 string.`);
- }
- if (!BASE64_REGEX.exec(input)) {
- throw new TypeError(`Invalid base64 string.`);
- }
- const buffer = (0, util_buffer_from_1.fromString)(input, "base64");
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
- };
- exports.fromBase64 = fromBase64;
-});
-
-// node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/toBase64.js
-var require_toBase645 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.toBase64 = undefined;
- var util_buffer_from_1 = require_dist_cjs85();
- var util_utf8_1 = require_dist_cjs17();
- var toBase64 = (_input) => {
- let input;
- if (typeof _input === "string") {
- input = (0, util_utf8_1.fromUtf8)(_input);
- } else {
- input = _input;
- }
- if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
- throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
- }
- return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64");
- };
- exports.toBase64 = toBase64;
-});
-
-// node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/index.js
-var require_dist_cjs86 = __commonJS((exports) => {
- var fromBase64 = require_fromBase645();
- var toBase64 = require_toBase645();
- Object.prototype.hasOwnProperty.call(fromBase64, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: fromBase64["__proto__"]
- });
- Object.keys(fromBase64).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = fromBase64[k];
- });
- Object.prototype.hasOwnProperty.call(toBase64, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: toBase64["__proto__"]
- });
- Object.keys(toBase64).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = toBase64[k];
- });
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/ruleset.js
-var require_ruleset = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ruleSet = undefined;
- var u2 = "required";
- var v = "fn";
- var w = "argv";
- var x2 = "ref";
- var a2 = true;
- var b = "isSet";
- var c5 = "booleanEquals";
- var d = "error";
- var e = "endpoint";
- var f = "tree";
- var g = "PartitionResult";
- var h2 = "getAttr";
- var i2 = { [u2]: false, type: "string" };
- var j = { [u2]: true, default: false, type: "boolean" };
- var k = { [x2]: "Endpoint" };
- var l = { [v]: c5, [w]: [{ [x2]: "UseFIPS" }, true] };
- var m = { [v]: c5, [w]: [{ [x2]: "UseDualStack" }, true] };
- var n2 = {};
- var o2 = { [v]: h2, [w]: [{ [x2]: g }, "supportsFIPS"] };
- var p = { [x2]: g };
- var q = { [v]: c5, [w]: [true, { [v]: h2, [w]: [p, "supportsDualStack"] }] };
- var r = [l];
- var s = [m];
- var t = [{ [x2]: "Region" }];
- var _data = {
- version: "1.0",
- parameters: { Region: i2, UseDualStack: j, UseFIPS: j, Endpoint: i2 },
- rules: [
- {
- conditions: [{ [v]: b, [w]: [k] }],
- rules: [
- { conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d },
- { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d },
- { endpoint: { url: k, properties: n2, headers: n2 }, type: e }
- ],
- type: f
- },
- {
- conditions: [{ [v]: b, [w]: t }],
- rules: [
- {
- conditions: [{ [v]: "aws.partition", [w]: t, assign: g }],
- rules: [
- {
- conditions: [l, m],
- rules: [
- {
- conditions: [{ [v]: c5, [w]: [a2, o2] }, q],
- rules: [
- {
- endpoint: {
- url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",
- properties: n2,
- headers: n2
- },
- type: e
- }
- ],
- type: f
- },
- { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }
- ],
- type: f
- },
- {
- conditions: r,
- rules: [
- {
- conditions: [{ [v]: c5, [w]: [o2, a2] }],
- rules: [
- {
- conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h2, [w]: [p, "name"] }, "aws-us-gov"] }],
- endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n2, headers: n2 },
- type: e
- },
- {
- endpoint: {
- url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",
- properties: n2,
- headers: n2
- },
- type: e
- }
- ],
- type: f
- },
- { error: "FIPS is enabled but this partition does not support FIPS", type: d }
- ],
- type: f
- },
- {
- conditions: s,
- rules: [
- {
- conditions: [q],
- rules: [
- {
- endpoint: {
- url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",
- properties: n2,
- headers: n2
- },
- type: e
- }
- ],
- type: f
- },
- { error: "DualStack is enabled but this partition does not support DualStack", type: d }
- ],
- type: f
- },
- {
- endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n2, headers: n2 },
- type: e
- }
- ],
- type: f
- }
- ],
- type: f
- },
- { error: "Invalid Configuration: Missing Region", type: d }
- ]
- };
- exports.ruleSet = _data;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/endpointResolver.js
-var require_endpointResolver = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.defaultEndpointResolver = undefined;
- var util_endpoints_1 = require_dist_cjs51();
- var util_endpoints_2 = require_dist_cjs50();
- var ruleset_1 = require_ruleset();
- var cache2 = new util_endpoints_2.EndpointCache({
- size: 50,
- params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
- });
- var defaultEndpointResolver = (endpointParams, context = {}) => {
- return cache2.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
- endpointParams,
- logger: context.logger
- }));
- };
- exports.defaultEndpointResolver = defaultEndpointResolver;
- util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/models/SSOOIDCServiceException.js
-var require_SSOOIDCServiceException = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.SSOOIDCServiceException = exports.__ServiceException = undefined;
- var smithy_client_1 = require_dist_cjs71();
- Object.defineProperty(exports, "__ServiceException", { enumerable: true, get: function() {
- return smithy_client_1.ServiceException;
- } });
-
- class SSOOIDCServiceException extends smithy_client_1.ServiceException {
- constructor(options2) {
- super(options2);
- Object.setPrototypeOf(this, SSOOIDCServiceException.prototype);
- }
- }
- exports.SSOOIDCServiceException = SSOOIDCServiceException;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/models/errors.js
-var require_errors = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.UnsupportedGrantTypeException = exports.UnauthorizedClientException = exports.SlowDownException = exports.InvalidScopeException = exports.InvalidRequestException = exports.InvalidGrantException = exports.InvalidClientException = exports.InternalServerException = exports.ExpiredTokenException = exports.AuthorizationPendingException = exports.AccessDeniedException = undefined;
- var SSOOIDCServiceException_1 = require_SSOOIDCServiceException();
-
- class AccessDeniedException extends SSOOIDCServiceException_1.SSOOIDCServiceException {
- name = "AccessDeniedException";
- $fault = "client";
- error;
- reason;
- error_description;
- constructor(opts) {
- super({
- name: "AccessDeniedException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, AccessDeniedException.prototype);
- this.error = opts.error;
- this.reason = opts.reason;
- this.error_description = opts.error_description;
- }
- }
- exports.AccessDeniedException = AccessDeniedException;
-
- class AuthorizationPendingException extends SSOOIDCServiceException_1.SSOOIDCServiceException {
- name = "AuthorizationPendingException";
- $fault = "client";
- error;
- error_description;
- constructor(opts) {
- super({
- name: "AuthorizationPendingException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, AuthorizationPendingException.prototype);
- this.error = opts.error;
- this.error_description = opts.error_description;
- }
- }
- exports.AuthorizationPendingException = AuthorizationPendingException;
-
- class ExpiredTokenException extends SSOOIDCServiceException_1.SSOOIDCServiceException {
- name = "ExpiredTokenException";
- $fault = "client";
- error;
- error_description;
- constructor(opts) {
- super({
- name: "ExpiredTokenException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ExpiredTokenException.prototype);
- this.error = opts.error;
- this.error_description = opts.error_description;
- }
- }
- exports.ExpiredTokenException = ExpiredTokenException;
-
- class InternalServerException extends SSOOIDCServiceException_1.SSOOIDCServiceException {
- name = "InternalServerException";
- $fault = "server";
- error;
- error_description;
- constructor(opts) {
- super({
- name: "InternalServerException",
- $fault: "server",
- ...opts
- });
- Object.setPrototypeOf(this, InternalServerException.prototype);
- this.error = opts.error;
- this.error_description = opts.error_description;
- }
- }
- exports.InternalServerException = InternalServerException;
-
- class InvalidClientException extends SSOOIDCServiceException_1.SSOOIDCServiceException {
- name = "InvalidClientException";
- $fault = "client";
- error;
- error_description;
- constructor(opts) {
- super({
- name: "InvalidClientException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, InvalidClientException.prototype);
- this.error = opts.error;
- this.error_description = opts.error_description;
- }
- }
- exports.InvalidClientException = InvalidClientException;
-
- class InvalidGrantException extends SSOOIDCServiceException_1.SSOOIDCServiceException {
- name = "InvalidGrantException";
- $fault = "client";
- error;
- error_description;
- constructor(opts) {
- super({
- name: "InvalidGrantException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, InvalidGrantException.prototype);
- this.error = opts.error;
- this.error_description = opts.error_description;
- }
- }
- exports.InvalidGrantException = InvalidGrantException;
-
- class InvalidRequestException extends SSOOIDCServiceException_1.SSOOIDCServiceException {
- name = "InvalidRequestException";
- $fault = "client";
- error;
- reason;
- error_description;
- constructor(opts) {
- super({
- name: "InvalidRequestException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, InvalidRequestException.prototype);
- this.error = opts.error;
- this.reason = opts.reason;
- this.error_description = opts.error_description;
- }
- }
- exports.InvalidRequestException = InvalidRequestException;
-
- class InvalidScopeException extends SSOOIDCServiceException_1.SSOOIDCServiceException {
- name = "InvalidScopeException";
- $fault = "client";
- error;
- error_description;
- constructor(opts) {
- super({
- name: "InvalidScopeException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, InvalidScopeException.prototype);
- this.error = opts.error;
- this.error_description = opts.error_description;
- }
- }
- exports.InvalidScopeException = InvalidScopeException;
-
- class SlowDownException extends SSOOIDCServiceException_1.SSOOIDCServiceException {
- name = "SlowDownException";
- $fault = "client";
- error;
- error_description;
- constructor(opts) {
- super({
- name: "SlowDownException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, SlowDownException.prototype);
- this.error = opts.error;
- this.error_description = opts.error_description;
- }
- }
- exports.SlowDownException = SlowDownException;
-
- class UnauthorizedClientException extends SSOOIDCServiceException_1.SSOOIDCServiceException {
- name = "UnauthorizedClientException";
- $fault = "client";
- error;
- error_description;
- constructor(opts) {
- super({
- name: "UnauthorizedClientException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, UnauthorizedClientException.prototype);
- this.error = opts.error;
- this.error_description = opts.error_description;
- }
- }
- exports.UnauthorizedClientException = UnauthorizedClientException;
-
- class UnsupportedGrantTypeException extends SSOOIDCServiceException_1.SSOOIDCServiceException {
- name = "UnsupportedGrantTypeException";
- $fault = "client";
- error;
- error_description;
- constructor(opts) {
- super({
- name: "UnsupportedGrantTypeException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, UnsupportedGrantTypeException.prototype);
- this.error = opts.error;
- this.error_description = opts.error_description;
- }
- }
- exports.UnsupportedGrantTypeException = UnsupportedGrantTypeException;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/schemas/schemas_0.js
-var require_schemas_0 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.CreateToken$ = exports.CreateTokenResponse$ = exports.CreateTokenRequest$ = exports.errorTypeRegistries = exports.UnsupportedGrantTypeException$ = exports.UnauthorizedClientException$ = exports.SlowDownException$ = exports.InvalidScopeException$ = exports.InvalidRequestException$ = exports.InvalidGrantException$ = exports.InvalidClientException$ = exports.InternalServerException$ = exports.ExpiredTokenException$ = exports.AuthorizationPendingException$ = exports.AccessDeniedException$ = exports.SSOOIDCServiceException$ = undefined;
- var _ADE = "AccessDeniedException";
- var _APE = "AuthorizationPendingException";
- var _AT = "AccessToken";
- var _CS = "ClientSecret";
- var _CT = "CreateToken";
- var _CTR = "CreateTokenRequest";
- var _CTRr = "CreateTokenResponse";
- var _CV = "CodeVerifier";
- var _ETE = "ExpiredTokenException";
- var _ICE = "InvalidClientException";
- var _IGE = "InvalidGrantException";
- var _IRE = "InvalidRequestException";
- var _ISE = "InternalServerException";
- var _ISEn = "InvalidScopeException";
- var _IT = "IdToken";
- var _RT = "RefreshToken";
- var _SDE = "SlowDownException";
- var _UCE = "UnauthorizedClientException";
- var _UGTE = "UnsupportedGrantTypeException";
- var _aT = "accessToken";
- var _c = "client";
- var _cI = "clientId";
- var _cS = "clientSecret";
- var _cV = "codeVerifier";
- var _co = "code";
- var _dC = "deviceCode";
- var _e = "error";
- var _eI = "expiresIn";
- var _ed = "error_description";
- var _gT = "grantType";
- var _h = "http";
- var _hE = "httpError";
- var _iT = "idToken";
- var _r = "reason";
- var _rT = "refreshToken";
- var _rU = "redirectUri";
- var _s = "smithy.ts.sdk.synthetic.com.amazonaws.ssooidc";
- var _sc = "scope";
- var _se = "server";
- var _tT = "tokenType";
- var n0 = "com.amazonaws.ssooidc";
- var schema_1 = require_schema();
- var errors_1 = require_errors();
- var SSOOIDCServiceException_1 = require_SSOOIDCServiceException();
- var _s_registry = schema_1.TypeRegistry.for(_s);
- exports.SSOOIDCServiceException$ = [-3, _s, "SSOOIDCServiceException", 0, [], []];
- _s_registry.registerError(exports.SSOOIDCServiceException$, SSOOIDCServiceException_1.SSOOIDCServiceException);
- var n0_registry = schema_1.TypeRegistry.for(n0);
- exports.AccessDeniedException$ = [
- -3,
- n0,
- _ADE,
- { [_e]: _c, [_hE]: 400 },
- [_e, _r, _ed],
- [0, 0, 0]
- ];
- n0_registry.registerError(exports.AccessDeniedException$, errors_1.AccessDeniedException);
- exports.AuthorizationPendingException$ = [
- -3,
- n0,
- _APE,
- { [_e]: _c, [_hE]: 400 },
- [_e, _ed],
- [0, 0]
- ];
- n0_registry.registerError(exports.AuthorizationPendingException$, errors_1.AuthorizationPendingException);
- exports.ExpiredTokenException$ = [-3, n0, _ETE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]];
- n0_registry.registerError(exports.ExpiredTokenException$, errors_1.ExpiredTokenException);
- exports.InternalServerException$ = [-3, n0, _ISE, { [_e]: _se, [_hE]: 500 }, [_e, _ed], [0, 0]];
- n0_registry.registerError(exports.InternalServerException$, errors_1.InternalServerException);
- exports.InvalidClientException$ = [-3, n0, _ICE, { [_e]: _c, [_hE]: 401 }, [_e, _ed], [0, 0]];
- n0_registry.registerError(exports.InvalidClientException$, errors_1.InvalidClientException);
- exports.InvalidGrantException$ = [-3, n0, _IGE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]];
- n0_registry.registerError(exports.InvalidGrantException$, errors_1.InvalidGrantException);
- exports.InvalidRequestException$ = [
- -3,
- n0,
- _IRE,
- { [_e]: _c, [_hE]: 400 },
- [_e, _r, _ed],
- [0, 0, 0]
- ];
- n0_registry.registerError(exports.InvalidRequestException$, errors_1.InvalidRequestException);
- exports.InvalidScopeException$ = [-3, n0, _ISEn, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]];
- n0_registry.registerError(exports.InvalidScopeException$, errors_1.InvalidScopeException);
- exports.SlowDownException$ = [-3, n0, _SDE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]];
- n0_registry.registerError(exports.SlowDownException$, errors_1.SlowDownException);
- exports.UnauthorizedClientException$ = [
- -3,
- n0,
- _UCE,
- { [_e]: _c, [_hE]: 400 },
- [_e, _ed],
- [0, 0]
- ];
- n0_registry.registerError(exports.UnauthorizedClientException$, errors_1.UnauthorizedClientException);
- exports.UnsupportedGrantTypeException$ = [
- -3,
- n0,
- _UGTE,
- { [_e]: _c, [_hE]: 400 },
- [_e, _ed],
- [0, 0]
- ];
- n0_registry.registerError(exports.UnsupportedGrantTypeException$, errors_1.UnsupportedGrantTypeException);
- exports.errorTypeRegistries = [_s_registry, n0_registry];
- var AccessToken = [0, n0, _AT, 8, 0];
- var ClientSecret = [0, n0, _CS, 8, 0];
- var CodeVerifier = [0, n0, _CV, 8, 0];
- var IdToken = [0, n0, _IT, 8, 0];
- var RefreshToken = [0, n0, _RT, 8, 0];
- exports.CreateTokenRequest$ = [
- 3,
- n0,
- _CTR,
- 0,
- [_cI, _cS, _gT, _dC, _co, _rT, _sc, _rU, _cV],
- [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]],
- 3
- ];
- exports.CreateTokenResponse$ = [
- 3,
- n0,
- _CTRr,
- 0,
- [_aT, _tT, _eI, _rT, _iT],
- [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]]
- ];
- var Scopes = 64 | 0;
- exports.CreateToken$ = [
- 9,
- n0,
- _CT,
- { [_h]: ["POST", "/token", 200] },
- () => exports.CreateTokenRequest$,
- () => exports.CreateTokenResponse$
- ];
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.shared.js
-var require_runtimeConfig_shared = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRuntimeConfig = undefined;
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var protocols_1 = require_protocols2();
- var core_1 = require_dist_cjs37();
- var smithy_client_1 = require_dist_cjs71();
- var url_parser_1 = require_dist_cjs11();
- var util_base64_1 = require_dist_cjs86();
- var util_utf8_1 = require_dist_cjs17();
- var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider();
- var endpointResolver_1 = require_endpointResolver();
- var schemas_0_1 = require_schemas_0();
- var getRuntimeConfig = (config3) => {
- return {
- apiVersion: "2019-06-10",
- base64Decoder: config3?.base64Decoder ?? util_base64_1.fromBase64,
- base64Encoder: config3?.base64Encoder ?? util_base64_1.toBase64,
- disableHostPrefix: config3?.disableHostPrefix ?? false,
- endpointProvider: config3?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver,
- extensions: config3?.extensions ?? [],
- httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider,
- httpAuthSchemes: config3?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
- signer: new httpAuthSchemes_1.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#noAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
- signer: new core_1.NoAuthSigner
- }
- ],
- logger: config3?.logger ?? new smithy_client_1.NoOpLogger,
- protocol: config3?.protocol ?? protocols_1.AwsRestJsonProtocol,
- protocolSettings: config3?.protocolSettings ?? {
- defaultNamespace: "com.amazonaws.ssooidc",
- errorTypeRegistries: schemas_0_1.errorTypeRegistries,
- version: "2019-06-10",
- serviceTarget: "AWSSSOOIDCService"
- },
- serviceId: config3?.serviceId ?? "SSO OIDC",
- urlParser: config3?.urlParser ?? url_parser_1.parseUrl,
- utf8Decoder: config3?.utf8Decoder ?? util_utf8_1.fromUtf8,
- utf8Encoder: config3?.utf8Encoder ?? util_utf8_1.toUtf8
- };
- };
- exports.getRuntimeConfig = getRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.js
-var require_runtimeConfig = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRuntimeConfig = undefined;
- var tslib_1 = require_tslib();
- var package_json_1 = tslib_1.__importDefault(require_package());
- var client_1 = require_client();
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var util_user_agent_node_1 = require_dist_cjs72();
- var config_resolver_1 = require_dist_cjs58();
- var hash_node_1 = require_dist_cjs75();
- var middleware_retry_1 = require_dist_cjs69();
- var node_config_provider_1 = require_dist_cjs9();
- var node_http_handler_1 = require_dist_cjs5();
- var smithy_client_1 = require_dist_cjs71();
- var util_body_length_node_1 = require_dist_cjs76();
- var util_defaults_mode_node_1 = require_dist_cjs77();
- var util_retry_1 = require_dist_cjs55();
- var runtimeConfig_shared_1 = require_runtimeConfig_shared();
- var getRuntimeConfig = (config3) => {
- (0, smithy_client_1.emitWarningIfUnsupportedVersion)(process.version);
- const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config3);
- const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
- const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config3);
- (0, client_1.emitWarningIfUnsupportedVersion)(process.version);
- const loaderConfig = {
- profile: config3?.profile,
- logger: clientSharedValues.logger
- };
- return {
- ...clientSharedValues,
- ...config3,
- runtime: "node",
- defaultsMode,
- authSchemePreference: config3?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(httpAuthSchemes_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
- bodyLengthChecker: config3?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength,
- defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
- maxAttempts: config3?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3),
- region: config3?.region ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
- requestHandler: node_http_handler_1.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider),
- retryMode: config3?.retryMode ?? (0, node_config_provider_1.loadConfig)({
- ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
- default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
- }, config3),
- sha256: config3?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"),
- streamCollector: config3?.streamCollector ?? node_http_handler_1.streamCollector,
- useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- useFipsEndpoint: config3?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- userAgentAppId: config3?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
- };
- };
- exports.getRuntimeConfig = getRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js
-var require_stsRegionDefaultResolver = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.warning = undefined;
- exports.stsRegionDefaultResolver = stsRegionDefaultResolver;
- var config_resolver_1 = require_dist_cjs58();
- var node_config_provider_1 = require_dist_cjs9();
- function stsRegionDefaultResolver(loaderConfig = {}) {
- return (0, node_config_provider_1.loadConfig)({
- ...config_resolver_1.NODE_REGION_CONFIG_OPTIONS,
- async default() {
- if (!exports.warning.silence) {
- console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly.");
- }
- return "us-east-1";
- }
- }, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig });
- }
- exports.warning = {
- silence: false
- };
-});
-
-// node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js
-var require_dist_cjs87 = __commonJS((exports) => {
- var stsRegionDefaultResolver = require_stsRegionDefaultResolver();
- var configResolver = require_dist_cjs58();
- var getAwsRegionExtensionConfiguration = (runtimeConfig) => {
- return {
- setRegion(region) {
- runtimeConfig.region = region;
- },
- region() {
- return runtimeConfig.region;
- }
- };
- };
- var resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => {
- return {
- region: awsRegionExtensionConfiguration.region()
- };
- };
- exports.NODE_REGION_CONFIG_FILE_OPTIONS = configResolver.NODE_REGION_CONFIG_FILE_OPTIONS;
- exports.NODE_REGION_CONFIG_OPTIONS = configResolver.NODE_REGION_CONFIG_OPTIONS;
- exports.REGION_ENV_NAME = configResolver.REGION_ENV_NAME;
- exports.REGION_INI_NAME = configResolver.REGION_INI_NAME;
- exports.resolveRegionConfig = configResolver.resolveRegionConfig;
- exports.getAwsRegionExtensionConfiguration = getAwsRegionExtensionConfiguration;
- exports.resolveAwsRegionExtensionConfiguration = resolveAwsRegionExtensionConfiguration;
- Object.prototype.hasOwnProperty.call(stsRegionDefaultResolver, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: stsRegionDefaultResolver["__proto__"]
- });
- Object.keys(stsRegionDefaultResolver).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = stsRegionDefaultResolver[k];
- });
-});
-
-// node_modules/@aws-sdk/nested-clients/node_modules/@smithy/protocol-http/dist-cjs/index.js
-var require_dist_cjs88 = __commonJS((exports) => {
- var types3 = require_dist_cjs70();
- var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
- };
- var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
- };
-
- class Field2 {
- name;
- kind;
- values;
- constructor({ name, kind: kind2 = types3.FieldPosition.HEADER, values = [] }) {
- this.name = name;
- this.kind = kind2;
- this.values = values;
- }
- add(value) {
- this.values.push(value);
- }
- set(values) {
- this.values = values;
- }
- remove(value) {
- this.values = this.values.filter((v) => v !== value);
- }
- toString() {
- return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
- }
- get() {
- return this.values;
- }
- }
-
- class Fields2 {
- entries = {};
- encoding;
- constructor({ fields = [], encoding = "utf-8" }) {
- fields.forEach(this.setField.bind(this));
- this.encoding = encoding;
- }
- setField(field) {
- this.entries[field.name.toLowerCase()] = field;
- }
- getField(name) {
- return this.entries[name.toLowerCase()];
- }
- removeField(name) {
- delete this.entries[name.toLowerCase()];
- }
- getByType(kind2) {
- return Object.values(this.entries).filter((field) => field.kind === kind2);
- }
- }
-
- class HttpRequest2 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest2({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery2(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest2.clone(this);
- }
- }
- function cloneQuery2(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
- }
-
- class HttpResponse {
- statusCode;
- reason;
- headers;
- body;
- constructor(options2) {
- this.statusCode = options2.statusCode;
- this.reason = options2.reason;
- this.headers = options2.headers || {};
- this.body = options2.body;
- }
- static isInstance(response2) {
- if (!response2)
- return false;
- const resp = response2;
- return typeof resp.statusCode === "number" && typeof resp.headers === "object";
- }
- }
- function isValidHostname2(hostname2) {
- const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
- return hostPattern.test(hostname2);
- }
- exports.Field = Field2;
- exports.Fields = Fields2;
- exports.HttpRequest = HttpRequest2;
- exports.HttpResponse = HttpResponse;
- exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
- exports.isValidHostname = isValidHostname2;
- exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js
-var require_sso_oidc = __commonJS((exports) => {
- var middlewareHostHeader = require_dist_cjs44();
- var middlewareLogger = require_dist_cjs45();
- var middlewareRecursionDetection = require_dist_cjs48();
- var middlewareUserAgent = require_dist_cjs56();
- var configResolver = require_dist_cjs58();
- var core2 = require_dist_cjs37();
- var schema2 = require_schema();
- var middlewareContentLength = require_dist_cjs61();
- var middlewareEndpoint = require_dist_cjs65();
- var middlewareRetry = require_dist_cjs69();
- var smithyClient = require_dist_cjs71();
- var httpAuthSchemeProvider = require_httpAuthSchemeProvider();
- var runtimeConfig = require_runtimeConfig();
- var regionConfigResolver = require_dist_cjs87();
- var protocolHttp = require_dist_cjs88();
- var schemas_0 = require_schemas_0();
- var errors3 = require_errors();
- var SSOOIDCServiceException = require_SSOOIDCServiceException();
- var resolveClientEndpointParameters = (options2) => {
- return Object.assign(options2, {
- useDualstackEndpoint: options2.useDualstackEndpoint ?? false,
- useFipsEndpoint: options2.useFipsEndpoint ?? false,
- defaultSigningName: "sso-oauth"
- });
- };
- var commonParams = {
- UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
- Endpoint: { type: "builtInParams", name: "endpoint" },
- Region: { type: "builtInParams", name: "region" },
- UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
- };
- var getHttpAuthExtensionConfiguration = (runtimeConfig2) => {
- const _httpAuthSchemes = runtimeConfig2.httpAuthSchemes;
- let _httpAuthSchemeProvider = runtimeConfig2.httpAuthSchemeProvider;
- let _credentials = runtimeConfig2.credentials;
- return {
- setHttpAuthScheme(httpAuthScheme) {
- const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
- if (index2 === -1) {
- _httpAuthSchemes.push(httpAuthScheme);
- } else {
- _httpAuthSchemes.splice(index2, 1, httpAuthScheme);
- }
- },
- httpAuthSchemes() {
- return _httpAuthSchemes;
- },
- setHttpAuthSchemeProvider(httpAuthSchemeProvider2) {
- _httpAuthSchemeProvider = httpAuthSchemeProvider2;
- },
- httpAuthSchemeProvider() {
- return _httpAuthSchemeProvider;
- },
- setCredentials(credentials) {
- _credentials = credentials;
- },
- credentials() {
- return _credentials;
- }
- };
- };
- var resolveHttpAuthRuntimeConfig = (config3) => {
- return {
- httpAuthSchemes: config3.httpAuthSchemes(),
- httpAuthSchemeProvider: config3.httpAuthSchemeProvider(),
- credentials: config3.credentials()
- };
- };
- var resolveRuntimeExtensions = (runtimeConfig2, extensions4) => {
- const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig2), smithyClient.getDefaultExtensionConfiguration(runtimeConfig2), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig2), getHttpAuthExtensionConfiguration(runtimeConfig2));
- extensions4.forEach((extension) => extension.configure(extensionConfiguration));
- return Object.assign(runtimeConfig2, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));
- };
-
- class SSOOIDCClient extends smithyClient.Client {
- config;
- constructor(...[configuration]) {
- const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {});
- super(_config_0);
- this.initConfig = _config_0;
- const _config_1 = resolveClientEndpointParameters(_config_0);
- const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1);
- const _config_3 = middlewareRetry.resolveRetryConfig(_config_2);
- const _config_4 = configResolver.resolveRegionConfig(_config_3);
- const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4);
- const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5);
- const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6);
- const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);
- this.config = _config_8;
- this.middlewareStack.use(schema2.getSchemaSerdePlugin(this.config));
- this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config));
- this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config));
- this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config));
- this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config));
- this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config));
- this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config));
- this.middlewareStack.use(core2.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
- httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider,
- identityProviderConfigProvider: async (config3) => new core2.DefaultIdentityProviderConfig({
- "aws.auth#sigv4": config3.credentials
- })
- }));
- this.middlewareStack.use(core2.getHttpSigningPlugin(this.config));
- }
- destroy() {
- super.destroy();
- }
- }
-
- class CreateTokenCommand extends smithyClient.Command.classBuilder().ep(commonParams).m(function(Command3, cs, config3, o2) {
- return [middlewareEndpoint.getEndpointPlugin(config3, Command3.getEndpointParameterInstructions())];
- }).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").sc(schemas_0.CreateToken$).build() {
- }
- var commands = {
- CreateTokenCommand
- };
-
- class SSOOIDC extends SSOOIDCClient {
- }
- smithyClient.createAggregatedClient(commands, SSOOIDC);
- var AccessDeniedExceptionReason = {
- KMS_ACCESS_DENIED: "KMS_AccessDeniedException"
- };
- var InvalidRequestExceptionReason = {
- KMS_DISABLED_KEY: "KMS_DisabledException",
- KMS_INVALID_KEY_USAGE: "KMS_InvalidKeyUsageException",
- KMS_INVALID_STATE: "KMS_InvalidStateException",
- KMS_KEY_NOT_FOUND: "KMS_NotFoundException"
- };
- exports.$Command = smithyClient.Command;
- exports.__Client = smithyClient.Client;
- exports.SSOOIDCServiceException = SSOOIDCServiceException.SSOOIDCServiceException;
- exports.AccessDeniedExceptionReason = AccessDeniedExceptionReason;
- exports.CreateTokenCommand = CreateTokenCommand;
- exports.InvalidRequestExceptionReason = InvalidRequestExceptionReason;
- exports.SSOOIDC = SSOOIDC;
- exports.SSOOIDCClient = SSOOIDCClient;
- Object.prototype.hasOwnProperty.call(schemas_0, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: schemas_0["__proto__"]
- });
- Object.keys(schemas_0).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = schemas_0[k];
- });
- Object.prototype.hasOwnProperty.call(errors3, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: errors3["__proto__"]
- });
- Object.keys(errors3).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = errors3[k];
- });
-});
-
-// node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js
-var getSsoOidcClient = async (ssoRegion, init = {}, callerClientConfig) => {
- const { SSOOIDCClient } = await Promise.resolve().then(() => __toESM(require_sso_oidc(), 1));
- const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop] ?? callerClientConfig?.[prop];
- const ssoOidcClient = new SSOOIDCClient(Object.assign({}, init.clientConfig ?? {}, {
- region: ssoRegion ?? init.clientConfig?.region,
- logger: coalesce("logger"),
- userAgentAppId: coalesce("userAgentAppId")
- }));
- return ssoOidcClient;
-};
-
-// node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js
-var getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}, callerClientConfig) => {
- const { CreateTokenCommand } = await Promise.resolve().then(() => __toESM(require_sso_oidc(), 1));
- const ssoOidcClient = await getSsoOidcClient(ssoRegion, init, callerClientConfig);
- return ssoOidcClient.send(new CreateTokenCommand({
- clientId: ssoToken.clientId,
- clientSecret: ssoToken.clientSecret,
- refreshToken: ssoToken.refreshToken,
- grantType: "refresh_token"
- }));
-};
-var init_getNewSsoOidcToken = () => {};
-
-// node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js
-var import_property_provider11, validateTokenExpiry = (token) => {
- if (token.expiration && token.expiration.getTime() < Date.now()) {
- throw new import_property_provider11.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);
- }
-};
-var init_validateTokenExpiry = __esm(() => {
- init_constants4();
- import_property_provider11 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js
-var import_property_provider12, validateTokenKey = (key, value, forRefresh = false) => {
- if (typeof value === "undefined") {
- throw new import_property_provider12.TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false);
- }
-};
-var init_validateTokenKey = __esm(() => {
- init_constants4();
- import_property_provider12 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js
-import { promises as fsPromises } from "fs";
-var import_shared_ini_file_loader, writeFile2, writeSSOTokenToFile = (id, ssoToken) => {
- const tokenFilepath = import_shared_ini_file_loader.getSSOTokenFilepath(id);
- const tokenString = JSON.stringify(ssoToken, null, 2);
- return writeFile2(tokenFilepath, tokenString);
-};
-var init_writeSSOTokenToFile = __esm(() => {
- import_shared_ini_file_loader = __toESM(require_dist_cjs8(), 1);
- ({ writeFile: writeFile2 } = fsPromises);
-});
-
-// node_modules/@aws-sdk/token-providers/dist-es/fromSso.js
-var import_property_provider13, import_shared_ini_file_loader2, lastRefreshAttemptTime, fromSso = (init = {}) => async ({ callerClientConfig } = {}) => {
- init.logger?.debug("@aws-sdk/token-providers - fromSso");
- const profiles = await import_shared_ini_file_loader2.parseKnownFiles(init);
- const profileName = import_shared_ini_file_loader2.getProfileName({
- profile: init.profile ?? callerClientConfig?.profile
- });
- const profile2 = profiles[profileName];
- if (!profile2) {
- throw new import_property_provider13.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);
- } else if (!profile2["sso_session"]) {
- throw new import_property_provider13.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);
- }
- const ssoSessionName = profile2["sso_session"];
- const ssoSessions = await import_shared_ini_file_loader2.loadSsoSessionData(init);
- const ssoSession = ssoSessions[ssoSessionName];
- if (!ssoSession) {
- throw new import_property_provider13.TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false);
- }
- for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) {
- if (!ssoSession[ssoSessionRequiredKey]) {
- throw new import_property_provider13.TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false);
- }
- }
- const ssoStartUrl = ssoSession["sso_start_url"];
- const ssoRegion = ssoSession["sso_region"];
- let ssoToken;
- try {
- ssoToken = await import_shared_ini_file_loader2.getSSOTokenFromFile(ssoSessionName);
- } catch (e) {
- throw new import_property_provider13.TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false);
- }
- validateTokenKey("accessToken", ssoToken.accessToken);
- validateTokenKey("expiresAt", ssoToken.expiresAt);
- const { accessToken, expiresAt } = ssoToken;
- const existingToken = { token: accessToken, expiration: new Date(expiresAt) };
- if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {
- return existingToken;
- }
- if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1000) {
- validateTokenExpiry(existingToken);
- return existingToken;
- }
- validateTokenKey("clientId", ssoToken.clientId, true);
- validateTokenKey("clientSecret", ssoToken.clientSecret, true);
- validateTokenKey("refreshToken", ssoToken.refreshToken, true);
- try {
- lastRefreshAttemptTime.setTime(Date.now());
- const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init, callerClientConfig);
- validateTokenKey("accessToken", newSsoOidcToken.accessToken);
- validateTokenKey("expiresIn", newSsoOidcToken.expiresIn);
- const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000);
- try {
- await writeSSOTokenToFile(ssoSessionName, {
- ...ssoToken,
- accessToken: newSsoOidcToken.accessToken,
- expiresAt: newTokenExpiration.toISOString(),
- refreshToken: newSsoOidcToken.refreshToken
- });
- } catch (error40) {}
- return {
- token: newSsoOidcToken.accessToken,
- expiration: newTokenExpiration
- };
- } catch (error40) {
- validateTokenExpiry(existingToken);
- return existingToken;
- }
-};
-var init_fromSso = __esm(() => {
- init_constants4();
- init_getNewSsoOidcToken();
- init_validateTokenExpiry();
- init_validateTokenKey();
- init_writeSSOTokenToFile();
- import_property_provider13 = __toESM(require_dist_cjs6(), 1);
- import_shared_ini_file_loader2 = __toESM(require_dist_cjs8(), 1);
- lastRefreshAttemptTime = new Date(0);
-});
-
-// node_modules/@aws-sdk/token-providers/dist-es/fromStatic.js
-var init_fromStatic = () => {};
-
-// node_modules/@aws-sdk/token-providers/dist-es/nodeProvider.js
-var import_property_provider14, nodeProvider = (init = {}) => import_property_provider14.memoize(import_property_provider14.chain(fromSso(init), async () => {
- throw new import_property_provider14.TokenProviderError("Could not load token from any providers", false);
-}), (token) => token.expiration !== undefined && token.expiration.getTime() - Date.now() < 300000, (token) => token.expiration !== undefined);
-var init_nodeProvider = __esm(() => {
- init_fromSso();
- import_property_provider14 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/token-providers/dist-es/index.js
-var init_dist_es7 = __esm(() => {
- init_fromEnvSigningName();
- init_fromSso();
- init_fromStatic();
- init_nodeProvider();
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/auth/httpAuthSchemeProvider.js
-var require_httpAuthSchemeProvider2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.resolveHttpAuthSchemeConfig = exports.defaultSSOHttpAuthSchemeProvider = exports.defaultSSOHttpAuthSchemeParametersProvider = undefined;
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var util_middleware_1 = require_dist_cjs30();
- var defaultSSOHttpAuthSchemeParametersProvider = async (config3, context, input) => {
- return {
- operation: (0, util_middleware_1.getSmithyContext)(context).operation,
- region: await (0, util_middleware_1.normalizeProvider)(config3.region)() || (() => {
- throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
- })()
- };
- };
- exports.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider;
- function createAwsAuthSigv4HttpAuthOption(authParameters) {
- return {
- schemeId: "aws.auth#sigv4",
- signingProperties: {
- name: "awsssoportal",
- region: authParameters.region
- },
- propertiesExtractor: (config3, context) => ({
- signingProperties: {
- config: config3,
- context
- }
- })
- };
- }
- function createSmithyApiNoAuthHttpAuthOption(authParameters) {
- return {
- schemeId: "smithy.api#noAuth"
- };
- }
- var defaultSSOHttpAuthSchemeProvider = (authParameters) => {
- const options2 = [];
- switch (authParameters.operation) {
- case "GetRoleCredentials": {
- options2.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
- break;
- }
- default: {
- options2.push(createAwsAuthSigv4HttpAuthOption(authParameters));
- }
- }
- return options2;
- };
- exports.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider;
- var resolveHttpAuthSchemeConfig = (config3) => {
- const config_0 = (0, httpAuthSchemes_1.resolveAwsSdkSigV4Config)(config3);
- return Object.assign(config_0, {
- authSchemePreference: (0, util_middleware_1.normalizeProvider)(config3.authSchemePreference ?? [])
- });
- };
- exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/endpoint/ruleset.js
-var require_ruleset2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ruleSet = undefined;
- var u2 = "required";
- var v = "fn";
- var w = "argv";
- var x2 = "ref";
- var a2 = true;
- var b = "isSet";
- var c5 = "booleanEquals";
- var d = "error";
- var e = "endpoint";
- var f = "tree";
- var g = "PartitionResult";
- var h2 = "getAttr";
- var i2 = { [u2]: false, type: "string" };
- var j = { [u2]: true, default: false, type: "boolean" };
- var k = { [x2]: "Endpoint" };
- var l = { [v]: c5, [w]: [{ [x2]: "UseFIPS" }, true] };
- var m = { [v]: c5, [w]: [{ [x2]: "UseDualStack" }, true] };
- var n2 = {};
- var o2 = { [v]: h2, [w]: [{ [x2]: g }, "supportsFIPS"] };
- var p = { [x2]: g };
- var q = { [v]: c5, [w]: [true, { [v]: h2, [w]: [p, "supportsDualStack"] }] };
- var r = [l];
- var s = [m];
- var t = [{ [x2]: "Region" }];
- var _data = {
- version: "1.0",
- parameters: { Region: i2, UseDualStack: j, UseFIPS: j, Endpoint: i2 },
- rules: [
- {
- conditions: [{ [v]: b, [w]: [k] }],
- rules: [
- { conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d },
- { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d },
- { endpoint: { url: k, properties: n2, headers: n2 }, type: e }
- ],
- type: f
- },
- {
- conditions: [{ [v]: b, [w]: t }],
- rules: [
- {
- conditions: [{ [v]: "aws.partition", [w]: t, assign: g }],
- rules: [
- {
- conditions: [l, m],
- rules: [
- {
- conditions: [{ [v]: c5, [w]: [a2, o2] }, q],
- rules: [
- {
- endpoint: {
- url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",
- properties: n2,
- headers: n2
- },
- type: e
- }
- ],
- type: f
- },
- { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }
- ],
- type: f
- },
- {
- conditions: r,
- rules: [
- {
- conditions: [{ [v]: c5, [w]: [o2, a2] }],
- rules: [
- {
- conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h2, [w]: [p, "name"] }, "aws-us-gov"] }],
- endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n2, headers: n2 },
- type: e
- },
- {
- endpoint: {
- url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}",
- properties: n2,
- headers: n2
- },
- type: e
- }
- ],
- type: f
- },
- { error: "FIPS is enabled but this partition does not support FIPS", type: d }
- ],
- type: f
- },
- {
- conditions: s,
- rules: [
- {
- conditions: [q],
- rules: [
- {
- endpoint: {
- url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}",
- properties: n2,
- headers: n2
- },
- type: e
- }
- ],
- type: f
- },
- { error: "DualStack is enabled but this partition does not support DualStack", type: d }
- ],
- type: f
- },
- {
- endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n2, headers: n2 },
- type: e
- }
- ],
- type: f
- }
- ],
- type: f
- },
- { error: "Invalid Configuration: Missing Region", type: d }
- ]
- };
- exports.ruleSet = _data;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/endpoint/endpointResolver.js
-var require_endpointResolver2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.defaultEndpointResolver = undefined;
- var util_endpoints_1 = require_dist_cjs51();
- var util_endpoints_2 = require_dist_cjs50();
- var ruleset_1 = require_ruleset2();
- var cache2 = new util_endpoints_2.EndpointCache({
- size: 50,
- params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
- });
- var defaultEndpointResolver = (endpointParams, context = {}) => {
- return cache2.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
- endpointParams,
- logger: context.logger
- }));
- };
- exports.defaultEndpointResolver = defaultEndpointResolver;
- util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/models/SSOServiceException.js
-var require_SSOServiceException = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.SSOServiceException = exports.__ServiceException = undefined;
- var smithy_client_1 = require_dist_cjs71();
- Object.defineProperty(exports, "__ServiceException", { enumerable: true, get: function() {
- return smithy_client_1.ServiceException;
- } });
-
- class SSOServiceException extends smithy_client_1.ServiceException {
- constructor(options2) {
- super(options2);
- Object.setPrototypeOf(this, SSOServiceException.prototype);
- }
- }
- exports.SSOServiceException = SSOServiceException;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/models/errors.js
-var require_errors2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.UnauthorizedException = exports.TooManyRequestsException = exports.ResourceNotFoundException = exports.InvalidRequestException = undefined;
- var SSOServiceException_1 = require_SSOServiceException();
-
- class InvalidRequestException extends SSOServiceException_1.SSOServiceException {
- name = "InvalidRequestException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "InvalidRequestException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, InvalidRequestException.prototype);
- }
- }
- exports.InvalidRequestException = InvalidRequestException;
-
- class ResourceNotFoundException extends SSOServiceException_1.SSOServiceException {
- name = "ResourceNotFoundException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ResourceNotFoundException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ResourceNotFoundException.prototype);
- }
- }
- exports.ResourceNotFoundException = ResourceNotFoundException;
-
- class TooManyRequestsException extends SSOServiceException_1.SSOServiceException {
- name = "TooManyRequestsException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "TooManyRequestsException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, TooManyRequestsException.prototype);
- }
- }
- exports.TooManyRequestsException = TooManyRequestsException;
-
- class UnauthorizedException extends SSOServiceException_1.SSOServiceException {
- name = "UnauthorizedException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "UnauthorizedException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, UnauthorizedException.prototype);
- }
- }
- exports.UnauthorizedException = UnauthorizedException;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/schemas/schemas_0.js
-var require_schemas_02 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.GetRoleCredentials$ = exports.RoleCredentials$ = exports.GetRoleCredentialsResponse$ = exports.GetRoleCredentialsRequest$ = exports.errorTypeRegistries = exports.UnauthorizedException$ = exports.TooManyRequestsException$ = exports.ResourceNotFoundException$ = exports.InvalidRequestException$ = exports.SSOServiceException$ = undefined;
- var _ATT = "AccessTokenType";
- var _GRC = "GetRoleCredentials";
- var _GRCR = "GetRoleCredentialsRequest";
- var _GRCRe = "GetRoleCredentialsResponse";
- var _IRE = "InvalidRequestException";
- var _RC = "RoleCredentials";
- var _RNFE = "ResourceNotFoundException";
- var _SAKT = "SecretAccessKeyType";
- var _STT = "SessionTokenType";
- var _TMRE = "TooManyRequestsException";
- var _UE = "UnauthorizedException";
- var _aI = "accountId";
- var _aKI = "accessKeyId";
- var _aT = "accessToken";
- var _ai = "account_id";
- var _c = "client";
- var _e = "error";
- var _ex = "expiration";
- var _h = "http";
- var _hE = "httpError";
- var _hH = "httpHeader";
- var _hQ = "httpQuery";
- var _m = "message";
- var _rC = "roleCredentials";
- var _rN = "roleName";
- var _rn = "role_name";
- var _s = "smithy.ts.sdk.synthetic.com.amazonaws.sso";
- var _sAK = "secretAccessKey";
- var _sT = "sessionToken";
- var _xasbt = "x-amz-sso_bearer_token";
- var n0 = "com.amazonaws.sso";
- var schema_1 = require_schema();
- var errors_1 = require_errors2();
- var SSOServiceException_1 = require_SSOServiceException();
- var _s_registry = schema_1.TypeRegistry.for(_s);
- exports.SSOServiceException$ = [-3, _s, "SSOServiceException", 0, [], []];
- _s_registry.registerError(exports.SSOServiceException$, SSOServiceException_1.SSOServiceException);
- var n0_registry = schema_1.TypeRegistry.for(n0);
- exports.InvalidRequestException$ = [-3, n0, _IRE, { [_e]: _c, [_hE]: 400 }, [_m], [0]];
- n0_registry.registerError(exports.InvalidRequestException$, errors_1.InvalidRequestException);
- exports.ResourceNotFoundException$ = [-3, n0, _RNFE, { [_e]: _c, [_hE]: 404 }, [_m], [0]];
- n0_registry.registerError(exports.ResourceNotFoundException$, errors_1.ResourceNotFoundException);
- exports.TooManyRequestsException$ = [-3, n0, _TMRE, { [_e]: _c, [_hE]: 429 }, [_m], [0]];
- n0_registry.registerError(exports.TooManyRequestsException$, errors_1.TooManyRequestsException);
- exports.UnauthorizedException$ = [-3, n0, _UE, { [_e]: _c, [_hE]: 401 }, [_m], [0]];
- n0_registry.registerError(exports.UnauthorizedException$, errors_1.UnauthorizedException);
- exports.errorTypeRegistries = [_s_registry, n0_registry];
- var AccessTokenType = [0, n0, _ATT, 8, 0];
- var SecretAccessKeyType = [0, n0, _SAKT, 8, 0];
- var SessionTokenType = [0, n0, _STT, 8, 0];
- exports.GetRoleCredentialsRequest$ = [
- 3,
- n0,
- _GRCR,
- 0,
- [_rN, _aI, _aT],
- [
- [0, { [_hQ]: _rn }],
- [0, { [_hQ]: _ai }],
- [() => AccessTokenType, { [_hH]: _xasbt }]
- ],
- 3
- ];
- exports.GetRoleCredentialsResponse$ = [
- 3,
- n0,
- _GRCRe,
- 0,
- [_rC],
- [[() => exports.RoleCredentials$, 0]]
- ];
- exports.RoleCredentials$ = [
- 3,
- n0,
- _RC,
- 0,
- [_aKI, _sAK, _sT, _ex],
- [0, [() => SecretAccessKeyType, 0], [() => SessionTokenType, 0], 1]
- ];
- exports.GetRoleCredentials$ = [
- 9,
- n0,
- _GRC,
- { [_h]: ["GET", "/federation/credentials", 200] },
- () => exports.GetRoleCredentialsRequest$,
- () => exports.GetRoleCredentialsResponse$
- ];
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/runtimeConfig.shared.js
-var require_runtimeConfig_shared2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRuntimeConfig = undefined;
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var protocols_1 = require_protocols2();
- var core_1 = require_dist_cjs37();
- var smithy_client_1 = require_dist_cjs71();
- var url_parser_1 = require_dist_cjs11();
- var util_base64_1 = require_dist_cjs86();
- var util_utf8_1 = require_dist_cjs17();
- var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider2();
- var endpointResolver_1 = require_endpointResolver2();
- var schemas_0_1 = require_schemas_02();
- var getRuntimeConfig = (config3) => {
- return {
- apiVersion: "2019-06-10",
- base64Decoder: config3?.base64Decoder ?? util_base64_1.fromBase64,
- base64Encoder: config3?.base64Encoder ?? util_base64_1.toBase64,
- disableHostPrefix: config3?.disableHostPrefix ?? false,
- endpointProvider: config3?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver,
- extensions: config3?.extensions ?? [],
- httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider,
- httpAuthSchemes: config3?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
- signer: new httpAuthSchemes_1.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#noAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
- signer: new core_1.NoAuthSigner
- }
- ],
- logger: config3?.logger ?? new smithy_client_1.NoOpLogger,
- protocol: config3?.protocol ?? protocols_1.AwsRestJsonProtocol,
- protocolSettings: config3?.protocolSettings ?? {
- defaultNamespace: "com.amazonaws.sso",
- errorTypeRegistries: schemas_0_1.errorTypeRegistries,
- version: "2019-06-10",
- serviceTarget: "SWBPortalService"
- },
- serviceId: config3?.serviceId ?? "SSO",
- urlParser: config3?.urlParser ?? url_parser_1.parseUrl,
- utf8Decoder: config3?.utf8Decoder ?? util_utf8_1.fromUtf8,
- utf8Encoder: config3?.utf8Encoder ?? util_utf8_1.toUtf8
- };
- };
- exports.getRuntimeConfig = getRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/runtimeConfig.js
-var require_runtimeConfig2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRuntimeConfig = undefined;
- var tslib_1 = require_tslib();
- var package_json_1 = tslib_1.__importDefault(require_package());
- var client_1 = require_client();
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var util_user_agent_node_1 = require_dist_cjs72();
- var config_resolver_1 = require_dist_cjs58();
- var hash_node_1 = require_dist_cjs75();
- var middleware_retry_1 = require_dist_cjs69();
- var node_config_provider_1 = require_dist_cjs9();
- var node_http_handler_1 = require_dist_cjs5();
- var smithy_client_1 = require_dist_cjs71();
- var util_body_length_node_1 = require_dist_cjs76();
- var util_defaults_mode_node_1 = require_dist_cjs77();
- var util_retry_1 = require_dist_cjs55();
- var runtimeConfig_shared_1 = require_runtimeConfig_shared2();
- var getRuntimeConfig = (config3) => {
- (0, smithy_client_1.emitWarningIfUnsupportedVersion)(process.version);
- const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config3);
- const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
- const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config3);
- (0, client_1.emitWarningIfUnsupportedVersion)(process.version);
- const loaderConfig = {
- profile: config3?.profile,
- logger: clientSharedValues.logger
- };
- return {
- ...clientSharedValues,
- ...config3,
- runtime: "node",
- defaultsMode,
- authSchemePreference: config3?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(httpAuthSchemes_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
- bodyLengthChecker: config3?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength,
- defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
- maxAttempts: config3?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3),
- region: config3?.region ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
- requestHandler: node_http_handler_1.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider),
- retryMode: config3?.retryMode ?? (0, node_config_provider_1.loadConfig)({
- ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
- default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
- }, config3),
- sha256: config3?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"),
- streamCollector: config3?.streamCollector ?? node_http_handler_1.streamCollector,
- useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- useFipsEndpoint: config3?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- userAgentAppId: config3?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
- };
- };
- exports.getRuntimeConfig = getRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/index.js
-var require_sso = __commonJS((exports) => {
- var middlewareHostHeader = require_dist_cjs44();
- var middlewareLogger = require_dist_cjs45();
- var middlewareRecursionDetection = require_dist_cjs48();
- var middlewareUserAgent = require_dist_cjs56();
- var configResolver = require_dist_cjs58();
- var core2 = require_dist_cjs37();
- var schema2 = require_schema();
- var middlewareContentLength = require_dist_cjs61();
- var middlewareEndpoint = require_dist_cjs65();
- var middlewareRetry = require_dist_cjs69();
- var smithyClient = require_dist_cjs71();
- var httpAuthSchemeProvider = require_httpAuthSchemeProvider2();
- var runtimeConfig = require_runtimeConfig2();
- var regionConfigResolver = require_dist_cjs87();
- var protocolHttp = require_dist_cjs88();
- var schemas_0 = require_schemas_02();
- var errors3 = require_errors2();
- var SSOServiceException = require_SSOServiceException();
- var resolveClientEndpointParameters = (options2) => {
- return Object.assign(options2, {
- useDualstackEndpoint: options2.useDualstackEndpoint ?? false,
- useFipsEndpoint: options2.useFipsEndpoint ?? false,
- defaultSigningName: "awsssoportal"
- });
- };
- var commonParams = {
- UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
- Endpoint: { type: "builtInParams", name: "endpoint" },
- Region: { type: "builtInParams", name: "region" },
- UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
- };
- var getHttpAuthExtensionConfiguration = (runtimeConfig2) => {
- const _httpAuthSchemes = runtimeConfig2.httpAuthSchemes;
- let _httpAuthSchemeProvider = runtimeConfig2.httpAuthSchemeProvider;
- let _credentials = runtimeConfig2.credentials;
- return {
- setHttpAuthScheme(httpAuthScheme) {
- const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
- if (index2 === -1) {
- _httpAuthSchemes.push(httpAuthScheme);
- } else {
- _httpAuthSchemes.splice(index2, 1, httpAuthScheme);
- }
- },
- httpAuthSchemes() {
- return _httpAuthSchemes;
- },
- setHttpAuthSchemeProvider(httpAuthSchemeProvider2) {
- _httpAuthSchemeProvider = httpAuthSchemeProvider2;
- },
- httpAuthSchemeProvider() {
- return _httpAuthSchemeProvider;
- },
- setCredentials(credentials) {
- _credentials = credentials;
- },
- credentials() {
- return _credentials;
- }
- };
- };
- var resolveHttpAuthRuntimeConfig = (config3) => {
- return {
- httpAuthSchemes: config3.httpAuthSchemes(),
- httpAuthSchemeProvider: config3.httpAuthSchemeProvider(),
- credentials: config3.credentials()
- };
- };
- var resolveRuntimeExtensions = (runtimeConfig2, extensions4) => {
- const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig2), smithyClient.getDefaultExtensionConfiguration(runtimeConfig2), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig2), getHttpAuthExtensionConfiguration(runtimeConfig2));
- extensions4.forEach((extension) => extension.configure(extensionConfiguration));
- return Object.assign(runtimeConfig2, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));
- };
-
- class SSOClient extends smithyClient.Client {
- config;
- constructor(...[configuration]) {
- const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {});
- super(_config_0);
- this.initConfig = _config_0;
- const _config_1 = resolveClientEndpointParameters(_config_0);
- const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1);
- const _config_3 = middlewareRetry.resolveRetryConfig(_config_2);
- const _config_4 = configResolver.resolveRegionConfig(_config_3);
- const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4);
- const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5);
- const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6);
- const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);
- this.config = _config_8;
- this.middlewareStack.use(schema2.getSchemaSerdePlugin(this.config));
- this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config));
- this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config));
- this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config));
- this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config));
- this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config));
- this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config));
- this.middlewareStack.use(core2.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
- httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultSSOHttpAuthSchemeParametersProvider,
- identityProviderConfigProvider: async (config3) => new core2.DefaultIdentityProviderConfig({
- "aws.auth#sigv4": config3.credentials
- })
- }));
- this.middlewareStack.use(core2.getHttpSigningPlugin(this.config));
- }
- destroy() {
- super.destroy();
- }
- }
-
- class GetRoleCredentialsCommand extends smithyClient.Command.classBuilder().ep(commonParams).m(function(Command3, cs, config3, o2) {
- return [middlewareEndpoint.getEndpointPlugin(config3, Command3.getEndpointParameterInstructions())];
- }).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").sc(schemas_0.GetRoleCredentials$).build() {
- }
- var commands = {
- GetRoleCredentialsCommand
- };
-
- class SSO extends SSOClient {
- }
- smithyClient.createAggregatedClient(commands, SSO);
- exports.$Command = smithyClient.Command;
- exports.__Client = smithyClient.Client;
- exports.SSOServiceException = SSOServiceException.SSOServiceException;
- exports.GetRoleCredentialsCommand = GetRoleCredentialsCommand;
- exports.SSO = SSO;
- exports.SSOClient = SSOClient;
- Object.prototype.hasOwnProperty.call(schemas_0, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: schemas_0["__proto__"]
- });
- Object.keys(schemas_0).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = schemas_0[k];
- });
- Object.prototype.hasOwnProperty.call(errors3, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: errors3["__proto__"]
- });
- Object.keys(errors3).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = errors3[k];
- });
-});
-
-// node_modules/@aws-sdk/credential-provider-sso/dist-es/loadSso.js
-var exports_loadSso = {};
-__export(exports_loadSso, {
- SSOClient: () => import_sso.SSOClient,
- GetRoleCredentialsCommand: () => import_sso.GetRoleCredentialsCommand
-});
-var import_sso;
-var init_loadSso = __esm(() => {
- import_sso = __toESM(require_sso(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js
-var import_client4, import_property_provider15, import_shared_ini_file_loader3, SHOULD_FAIL_CREDENTIAL_CHAIN = false, resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, callerClientConfig, profile: profile2, filepath, configFilepath, ignoreCache, logger: logger2 }) => {
- let token;
- const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;
- if (ssoSession) {
- try {
- const _token = await fromSso({
- profile: profile2,
- filepath,
- configFilepath,
- ignoreCache
- })();
- token = {
- accessToken: _token.token,
- expiresAt: new Date(_token.expiration).toISOString()
- };
- } catch (e) {
- throw new import_property_provider15.CredentialsProviderError(e.message, {
- tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
- logger: logger2
- });
- }
- } else {
- try {
- token = await import_shared_ini_file_loader3.getSSOTokenFromFile(ssoStartUrl);
- } catch (e) {
- throw new import_property_provider15.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {
- tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
- logger: logger2
- });
- }
- }
- if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {
- throw new import_property_provider15.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, {
- tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
- logger: logger2
- });
- }
- const { accessToken } = token;
- const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), exports_loadSso));
- const sso = ssoClient || new SSOClient2(Object.assign({}, clientConfig ?? {}, {
- logger: clientConfig?.logger ?? callerClientConfig?.logger ?? parentClientConfig?.logger,
- region: clientConfig?.region ?? ssoRegion,
- userAgentAppId: clientConfig?.userAgentAppId ?? callerClientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId
- }));
- let ssoResp;
- try {
- ssoResp = await sso.send(new GetRoleCredentialsCommand2({
- accountId: ssoAccountId,
- roleName: ssoRoleName,
- accessToken
- }));
- } catch (e) {
- throw new import_property_provider15.CredentialsProviderError(e, {
- tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
- logger: logger2
- });
- }
- const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} } = ssoResp;
- if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {
- throw new import_property_provider15.CredentialsProviderError("SSO returns an invalid temporary credential.", {
- tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
- logger: logger2
- });
- }
- const credentials = {
- accessKeyId,
- secretAccessKey,
- sessionToken,
- expiration: new Date(expiration),
- ...credentialScope && { credentialScope },
- ...accountId && { accountId }
- };
- if (ssoSession) {
- import_client4.setCredentialFeature(credentials, "CREDENTIALS_SSO", "s");
- } else {
- import_client4.setCredentialFeature(credentials, "CREDENTIALS_SSO_LEGACY", "u");
- }
- return credentials;
-};
-var init_resolveSSOCredentials = __esm(() => {
- init_dist_es7();
- import_client4 = __toESM(require_client(), 1);
- import_property_provider15 = __toESM(require_dist_cjs6(), 1);
- import_shared_ini_file_loader3 = __toESM(require_dist_cjs8(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js
-var import_property_provider16, validateSsoProfile = (profile2, logger2) => {
- const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile2;
- if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {
- throw new import_property_provider16.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", ` + `"sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile2).join(", ")}
-Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger: logger2 });
- }
- return profile2;
-};
-var init_validateSsoProfile = __esm(() => {
- import_property_provider16 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js
-var import_property_provider17, import_shared_ini_file_loader4, fromSSO = (init = {}) => async ({ callerClientConfig } = {}) => {
- init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");
- const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;
- const { ssoClient } = init;
- const profileName = import_shared_ini_file_loader4.getProfileName({
- profile: init.profile ?? callerClientConfig?.profile
- });
- if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
- const profiles = await import_shared_ini_file_loader4.parseKnownFiles(init);
- const profile2 = profiles[profileName];
- if (!profile2) {
- throw new import_property_provider17.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger });
- }
- if (!isSsoProfile(profile2)) {
- throw new import_property_provider17.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, {
- logger: init.logger
- });
- }
- if (profile2?.sso_session) {
- const ssoSessions = await import_shared_ini_file_loader4.loadSsoSessionData(init);
- const session = ssoSessions[profile2.sso_session];
- const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile2.sso_session}`;
- if (ssoRegion && ssoRegion !== session.sso_region) {
- throw new import_property_provider17.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, {
- tryNextLink: false,
- logger: init.logger
- });
- }
- if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {
- throw new import_property_provider17.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, {
- tryNextLink: false,
- logger: init.logger
- });
- }
- profile2.sso_region = session.sso_region;
- profile2.sso_start_url = session.sso_start_url;
- }
- const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile2, init.logger);
- return resolveSSOCredentials({
- ssoStartUrl: sso_start_url,
- ssoSession: sso_session,
- ssoAccountId: sso_account_id,
- ssoRegion: sso_region,
- ssoRoleName: sso_role_name,
- ssoClient,
- clientConfig: init.clientConfig,
- parentClientConfig: init.parentClientConfig,
- callerClientConfig: init.callerClientConfig,
- profile: profileName,
- filepath: init.filepath,
- configFilepath: init.configFilepath,
- ignoreCache: init.ignoreCache,
- logger: init.logger
- });
- } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {
- throw new import_property_provider17.CredentialsProviderError("Incomplete configuration. The fromSSO() argument hash must include " + '"ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', { tryNextLink: false, logger: init.logger });
- } else {
- return resolveSSOCredentials({
- ssoStartUrl,
- ssoSession,
- ssoAccountId,
- ssoRegion,
- ssoRoleName,
- ssoClient,
- clientConfig: init.clientConfig,
- parentClientConfig: init.parentClientConfig,
- callerClientConfig: init.callerClientConfig,
- profile: profileName,
- filepath: init.filepath,
- configFilepath: init.configFilepath,
- ignoreCache: init.ignoreCache,
- logger: init.logger
- });
- }
-};
-var init_fromSSO = __esm(() => {
- init_resolveSSOCredentials();
- init_validateSsoProfile();
- import_property_provider17 = __toESM(require_dist_cjs6(), 1);
- import_shared_ini_file_loader4 = __toESM(require_dist_cjs8(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-sso/dist-es/types.js
-var init_types5 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-sso/dist-es/index.js
-var exports_dist_es5 = {};
-__export(exports_dist_es5, {
- validateSsoProfile: () => validateSsoProfile,
- isSsoProfile: () => isSsoProfile,
- fromSSO: () => fromSSO
-});
-var init_dist_es8 = __esm(() => {
- init_fromSSO();
- init_types5();
- init_validateSsoProfile();
-});
-
-// node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js
-var import_client5, import_property_provider18, resolveCredentialSource = (credentialSource, profileName, logger2) => {
- const sourceProvidersMap = {
- EcsContainer: async (options2) => {
- const { fromHttp: fromHttp2 } = await Promise.resolve().then(() => (init_dist_es6(), exports_dist_es4));
- const { fromContainerMetadata: fromContainerMetadata3 } = await Promise.resolve().then(() => (init_dist_es2(), exports_dist_es2));
- logger2?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer");
- return async () => import_property_provider18.chain(fromHttp2(options2 ?? {}), fromContainerMetadata3(options2))().then(setNamedProvider);
- },
- Ec2InstanceMetadata: async (options2) => {
- logger2?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");
- const { fromInstanceMetadata: fromInstanceMetadata3 } = await Promise.resolve().then(() => (init_dist_es2(), exports_dist_es2));
- return async () => fromInstanceMetadata3(options2)().then(setNamedProvider);
- },
- Environment: async (options2) => {
- logger2?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");
- const { fromEnv: fromEnv3 } = await Promise.resolve().then(() => (init_dist_es(), exports_dist_es));
- return async () => fromEnv3(options2)().then(setNamedProvider);
- }
- };
- if (credentialSource in sourceProvidersMap) {
- return sourceProvidersMap[credentialSource];
- } else {
- throw new import_property_provider18.CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger: logger2 });
- }
-}, setNamedProvider = (creds) => import_client5.setCredentialFeature(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p");
-var init_resolveCredentialSource = __esm(() => {
- import_client5 = __toESM(require_client(), 1);
- import_property_provider18 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthSchemeProvider.js
-var require_httpAuthSchemeProvider3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = undefined;
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var util_middleware_1 = require_dist_cjs30();
- var STSClient_1 = require_STSClient();
- var defaultSTSHttpAuthSchemeParametersProvider = async (config3, context, input) => {
- return {
- operation: (0, util_middleware_1.getSmithyContext)(context).operation,
- region: await (0, util_middleware_1.normalizeProvider)(config3.region)() || (() => {
- throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
- })()
- };
- };
- exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider;
- function createAwsAuthSigv4HttpAuthOption(authParameters) {
- return {
- schemeId: "aws.auth#sigv4",
- signingProperties: {
- name: "sts",
- region: authParameters.region
- },
- propertiesExtractor: (config3, context) => ({
- signingProperties: {
- config: config3,
- context
- }
- })
- };
- }
- function createSmithyApiNoAuthHttpAuthOption(authParameters) {
- return {
- schemeId: "smithy.api#noAuth"
- };
- }
- var defaultSTSHttpAuthSchemeProvider = (authParameters) => {
- const options2 = [];
- switch (authParameters.operation) {
- case "AssumeRoleWithWebIdentity": {
- options2.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
- break;
- }
- default: {
- options2.push(createAwsAuthSigv4HttpAuthOption(authParameters));
- }
- }
- return options2;
- };
- exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider;
- var resolveStsAuthConfig = (input) => Object.assign(input, {
- stsClientCtor: STSClient_1.STSClient
- });
- exports.resolveStsAuthConfig = resolveStsAuthConfig;
- var resolveHttpAuthSchemeConfig = (config3) => {
- const config_0 = (0, exports.resolveStsAuthConfig)(config3);
- const config_1 = (0, httpAuthSchemes_1.resolveAwsSdkSigV4Config)(config_0);
- return Object.assign(config_1, {
- authSchemePreference: (0, util_middleware_1.normalizeProvider)(config3.authSchemePreference ?? [])
- });
- };
- exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/EndpointParameters.js
-var require_EndpointParameters = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.commonParams = exports.resolveClientEndpointParameters = undefined;
- var resolveClientEndpointParameters = (options2) => {
- return Object.assign(options2, {
- useDualstackEndpoint: options2.useDualstackEndpoint ?? false,
- useFipsEndpoint: options2.useFipsEndpoint ?? false,
- useGlobalEndpoint: options2.useGlobalEndpoint ?? false,
- defaultSigningName: "sts"
- });
- };
- exports.resolveClientEndpointParameters = resolveClientEndpointParameters;
- exports.commonParams = {
- UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" },
- UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
- Endpoint: { type: "builtInParams", name: "endpoint" },
- Region: { type: "builtInParams", name: "region" },
- UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
- };
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/ruleset.js
-var require_ruleset3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ruleSet = undefined;
- var F = "required";
- var G3 = "type";
- var H2 = "fn";
- var I2 = "argv";
- var J = "ref";
- var a2 = false;
- var b = true;
- var c5 = "booleanEquals";
- var d = "stringEquals";
- var e = "sigv4";
- var f = "sts";
- var g = "us-east-1";
- var h2 = "endpoint";
- var i2 = "https://sts.{Region}.{PartitionResult#dnsSuffix}";
- var j = "tree";
- var k = "error";
- var l = "getAttr";
- var m = { [F]: false, [G3]: "string" };
- var n2 = { [F]: true, default: false, [G3]: "boolean" };
- var o2 = { [J]: "Endpoint" };
- var p = { [H2]: "isSet", [I2]: [{ [J]: "Region" }] };
- var q = { [J]: "Region" };
- var r = { [H2]: "aws.partition", [I2]: [q], assign: "PartitionResult" };
- var s = { [J]: "UseFIPS" };
- var t = { [J]: "UseDualStack" };
- var u2 = {
- url: "https://sts.amazonaws.com",
- properties: { authSchemes: [{ name: e, signingName: f, signingRegion: g }] },
- headers: {}
- };
- var v = {};
- var w = { conditions: [{ [H2]: d, [I2]: [q, "aws-global"] }], [h2]: u2, [G3]: h2 };
- var x2 = { [H2]: c5, [I2]: [s, true] };
- var y2 = { [H2]: c5, [I2]: [t, true] };
- var z2 = { [H2]: l, [I2]: [{ [J]: "PartitionResult" }, "supportsFIPS"] };
- var A = { [J]: "PartitionResult" };
- var B = { [H2]: c5, [I2]: [true, { [H2]: l, [I2]: [A, "supportsDualStack"] }] };
- var C2 = [{ [H2]: "isSet", [I2]: [o2] }];
- var D2 = [x2];
- var E = [y2];
- var _data = {
- version: "1.0",
- parameters: { Region: m, UseDualStack: n2, UseFIPS: n2, Endpoint: m, UseGlobalEndpoint: n2 },
- rules: [
- {
- conditions: [
- { [H2]: c5, [I2]: [{ [J]: "UseGlobalEndpoint" }, b] },
- { [H2]: "not", [I2]: C2 },
- p,
- r,
- { [H2]: c5, [I2]: [s, a2] },
- { [H2]: c5, [I2]: [t, a2] }
- ],
- rules: [
- { conditions: [{ [H2]: d, [I2]: [q, "ap-northeast-1"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "ap-south-1"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "ap-southeast-1"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "ap-southeast-2"] }], endpoint: u2, [G3]: h2 },
- w,
- { conditions: [{ [H2]: d, [I2]: [q, "ca-central-1"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "eu-central-1"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "eu-north-1"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "eu-west-1"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "eu-west-2"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "eu-west-3"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "sa-east-1"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, g] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "us-east-2"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "us-west-1"] }], endpoint: u2, [G3]: h2 },
- { conditions: [{ [H2]: d, [I2]: [q, "us-west-2"] }], endpoint: u2, [G3]: h2 },
- {
- endpoint: {
- url: i2,
- properties: { authSchemes: [{ name: e, signingName: f, signingRegion: "{Region}" }] },
- headers: v
- },
- [G3]: h2
- }
- ],
- [G3]: j
- },
- {
- conditions: C2,
- rules: [
- { conditions: D2, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G3]: k },
- { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G3]: k },
- { endpoint: { url: o2, properties: v, headers: v }, [G3]: h2 }
- ],
- [G3]: j
- },
- {
- conditions: [p],
- rules: [
- {
- conditions: [r],
- rules: [
- {
- conditions: [x2, y2],
- rules: [
- {
- conditions: [{ [H2]: c5, [I2]: [b, z2] }, B],
- rules: [
- {
- endpoint: {
- url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",
- properties: v,
- headers: v
- },
- [G3]: h2
- }
- ],
- [G3]: j
- },
- { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G3]: k }
- ],
- [G3]: j
- },
- {
- conditions: D2,
- rules: [
- {
- conditions: [{ [H2]: c5, [I2]: [z2, b] }],
- rules: [
- {
- conditions: [{ [H2]: d, [I2]: [{ [H2]: l, [I2]: [A, "name"] }, "aws-us-gov"] }],
- endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v, headers: v },
- [G3]: h2
- },
- {
- endpoint: {
- url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}",
- properties: v,
- headers: v
- },
- [G3]: h2
- }
- ],
- [G3]: j
- },
- { error: "FIPS is enabled but this partition does not support FIPS", [G3]: k }
- ],
- [G3]: j
- },
- {
- conditions: E,
- rules: [
- {
- conditions: [B],
- rules: [
- {
- endpoint: {
- url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}",
- properties: v,
- headers: v
- },
- [G3]: h2
- }
- ],
- [G3]: j
- },
- { error: "DualStack is enabled but this partition does not support DualStack", [G3]: k }
- ],
- [G3]: j
- },
- w,
- { endpoint: { url: i2, properties: v, headers: v }, [G3]: h2 }
- ],
- [G3]: j
- }
- ],
- [G3]: j
- },
- { error: "Invalid Configuration: Missing Region", [G3]: k }
- ]
- };
- exports.ruleSet = _data;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/endpointResolver.js
-var require_endpointResolver3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.defaultEndpointResolver = undefined;
- var util_endpoints_1 = require_dist_cjs51();
- var util_endpoints_2 = require_dist_cjs50();
- var ruleset_1 = require_ruleset3();
- var cache2 = new util_endpoints_2.EndpointCache({
- size: 50,
- params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"]
- });
- var defaultEndpointResolver = (endpointParams, context = {}) => {
- return cache2.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
- endpointParams,
- logger: context.logger
- }));
- };
- exports.defaultEndpointResolver = defaultEndpointResolver;
- util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/models/STSServiceException.js
-var require_STSServiceException = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.STSServiceException = exports.__ServiceException = undefined;
- var smithy_client_1 = require_dist_cjs71();
- Object.defineProperty(exports, "__ServiceException", { enumerable: true, get: function() {
- return smithy_client_1.ServiceException;
- } });
-
- class STSServiceException extends smithy_client_1.ServiceException {
- constructor(options2) {
- super(options2);
- Object.setPrototypeOf(this, STSServiceException.prototype);
- }
- }
- exports.STSServiceException = STSServiceException;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/models/errors.js
-var require_errors3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.IDPCommunicationErrorException = exports.InvalidIdentityTokenException = exports.IDPRejectedClaimException = exports.RegionDisabledException = exports.PackedPolicyTooLargeException = exports.MalformedPolicyDocumentException = exports.ExpiredTokenException = undefined;
- var STSServiceException_1 = require_STSServiceException();
-
- class ExpiredTokenException extends STSServiceException_1.STSServiceException {
- name = "ExpiredTokenException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ExpiredTokenException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ExpiredTokenException.prototype);
- }
- }
- exports.ExpiredTokenException = ExpiredTokenException;
-
- class MalformedPolicyDocumentException extends STSServiceException_1.STSServiceException {
- name = "MalformedPolicyDocumentException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "MalformedPolicyDocumentException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype);
- }
- }
- exports.MalformedPolicyDocumentException = MalformedPolicyDocumentException;
-
- class PackedPolicyTooLargeException extends STSServiceException_1.STSServiceException {
- name = "PackedPolicyTooLargeException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "PackedPolicyTooLargeException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, PackedPolicyTooLargeException.prototype);
- }
- }
- exports.PackedPolicyTooLargeException = PackedPolicyTooLargeException;
-
- class RegionDisabledException extends STSServiceException_1.STSServiceException {
- name = "RegionDisabledException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "RegionDisabledException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, RegionDisabledException.prototype);
- }
- }
- exports.RegionDisabledException = RegionDisabledException;
-
- class IDPRejectedClaimException extends STSServiceException_1.STSServiceException {
- name = "IDPRejectedClaimException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "IDPRejectedClaimException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, IDPRejectedClaimException.prototype);
- }
- }
- exports.IDPRejectedClaimException = IDPRejectedClaimException;
-
- class InvalidIdentityTokenException extends STSServiceException_1.STSServiceException {
- name = "InvalidIdentityTokenException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "InvalidIdentityTokenException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, InvalidIdentityTokenException.prototype);
- }
- }
- exports.InvalidIdentityTokenException = InvalidIdentityTokenException;
-
- class IDPCommunicationErrorException extends STSServiceException_1.STSServiceException {
- name = "IDPCommunicationErrorException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "IDPCommunicationErrorException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, IDPCommunicationErrorException.prototype);
- }
- }
- exports.IDPCommunicationErrorException = IDPCommunicationErrorException;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/schemas/schemas_0.js
-var require_schemas_03 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AssumeRoleWithWebIdentity$ = exports.AssumeRole$ = exports.Tag$ = exports.ProvidedContext$ = exports.PolicyDescriptorType$ = exports.Credentials$ = exports.AssumeRoleWithWebIdentityResponse$ = exports.AssumeRoleWithWebIdentityRequest$ = exports.AssumeRoleResponse$ = exports.AssumeRoleRequest$ = exports.AssumedRoleUser$ = exports.errorTypeRegistries = exports.RegionDisabledException$ = exports.PackedPolicyTooLargeException$ = exports.MalformedPolicyDocumentException$ = exports.InvalidIdentityTokenException$ = exports.IDPRejectedClaimException$ = exports.IDPCommunicationErrorException$ = exports.ExpiredTokenException$ = exports.STSServiceException$ = undefined;
- var _A = "Arn";
- var _AKI = "AccessKeyId";
- var _AR = "AssumeRole";
- var _ARI = "AssumedRoleId";
- var _ARR = "AssumeRoleRequest";
- var _ARRs = "AssumeRoleResponse";
- var _ARU = "AssumedRoleUser";
- var _ARWWI = "AssumeRoleWithWebIdentity";
- var _ARWWIR = "AssumeRoleWithWebIdentityRequest";
- var _ARWWIRs = "AssumeRoleWithWebIdentityResponse";
- var _Au = "Audience";
- var _C = "Credentials";
- var _CA = "ContextAssertion";
- var _DS = "DurationSeconds";
- var _E = "Expiration";
- var _EI = "ExternalId";
- var _ETE = "ExpiredTokenException";
- var _IDPCEE = "IDPCommunicationErrorException";
- var _IDPRCE = "IDPRejectedClaimException";
- var _IITE = "InvalidIdentityTokenException";
- var _K = "Key";
- var _MPDE = "MalformedPolicyDocumentException";
- var _P = "Policy";
- var _PA = "PolicyArns";
- var _PAr = "ProviderArn";
- var _PC = "ProvidedContexts";
- var _PCLT = "ProvidedContextsListType";
- var _PCr = "ProvidedContext";
- var _PDT = "PolicyDescriptorType";
- var _PI = "ProviderId";
- var _PPS = "PackedPolicySize";
- var _PPTLE = "PackedPolicyTooLargeException";
- var _Pr = "Provider";
- var _RA = "RoleArn";
- var _RDE = "RegionDisabledException";
- var _RSN = "RoleSessionName";
- var _SAK = "SecretAccessKey";
- var _SFWIT = "SubjectFromWebIdentityToken";
- var _SI = "SourceIdentity";
- var _SN = "SerialNumber";
- var _ST = "SessionToken";
- var _T = "Tags";
- var _TC = "TokenCode";
- var _TTK = "TransitiveTagKeys";
- var _Ta = "Tag";
- var _V = "Value";
- var _WIT = "WebIdentityToken";
- var _a2 = "arn";
- var _aKST = "accessKeySecretType";
- var _aQE = "awsQueryError";
- var _c = "client";
- var _cTT = "clientTokenType";
- var _e = "error";
- var _hE = "httpError";
- var _m = "message";
- var _pDLT = "policyDescriptorListType";
- var _s = "smithy.ts.sdk.synthetic.com.amazonaws.sts";
- var _tLT = "tagListType";
- var n0 = "com.amazonaws.sts";
- var schema_1 = require_schema();
- var errors_1 = require_errors3();
- var STSServiceException_1 = require_STSServiceException();
- var _s_registry = schema_1.TypeRegistry.for(_s);
- exports.STSServiceException$ = [-3, _s, "STSServiceException", 0, [], []];
- _s_registry.registerError(exports.STSServiceException$, STSServiceException_1.STSServiceException);
- var n0_registry = schema_1.TypeRegistry.for(n0);
- exports.ExpiredTokenException$ = [
- -3,
- n0,
- _ETE,
- { [_aQE]: [`ExpiredTokenException`, 400], [_e]: _c, [_hE]: 400 },
- [_m],
- [0]
- ];
- n0_registry.registerError(exports.ExpiredTokenException$, errors_1.ExpiredTokenException);
- exports.IDPCommunicationErrorException$ = [
- -3,
- n0,
- _IDPCEE,
- { [_aQE]: [`IDPCommunicationError`, 400], [_e]: _c, [_hE]: 400 },
- [_m],
- [0]
- ];
- n0_registry.registerError(exports.IDPCommunicationErrorException$, errors_1.IDPCommunicationErrorException);
- exports.IDPRejectedClaimException$ = [
- -3,
- n0,
- _IDPRCE,
- { [_aQE]: [`IDPRejectedClaim`, 403], [_e]: _c, [_hE]: 403 },
- [_m],
- [0]
- ];
- n0_registry.registerError(exports.IDPRejectedClaimException$, errors_1.IDPRejectedClaimException);
- exports.InvalidIdentityTokenException$ = [
- -3,
- n0,
- _IITE,
- { [_aQE]: [`InvalidIdentityToken`, 400], [_e]: _c, [_hE]: 400 },
- [_m],
- [0]
- ];
- n0_registry.registerError(exports.InvalidIdentityTokenException$, errors_1.InvalidIdentityTokenException);
- exports.MalformedPolicyDocumentException$ = [
- -3,
- n0,
- _MPDE,
- { [_aQE]: [`MalformedPolicyDocument`, 400], [_e]: _c, [_hE]: 400 },
- [_m],
- [0]
- ];
- n0_registry.registerError(exports.MalformedPolicyDocumentException$, errors_1.MalformedPolicyDocumentException);
- exports.PackedPolicyTooLargeException$ = [
- -3,
- n0,
- _PPTLE,
- { [_aQE]: [`PackedPolicyTooLarge`, 400], [_e]: _c, [_hE]: 400 },
- [_m],
- [0]
- ];
- n0_registry.registerError(exports.PackedPolicyTooLargeException$, errors_1.PackedPolicyTooLargeException);
- exports.RegionDisabledException$ = [
- -3,
- n0,
- _RDE,
- { [_aQE]: [`RegionDisabledException`, 403], [_e]: _c, [_hE]: 403 },
- [_m],
- [0]
- ];
- n0_registry.registerError(exports.RegionDisabledException$, errors_1.RegionDisabledException);
- exports.errorTypeRegistries = [_s_registry, n0_registry];
- var accessKeySecretType = [0, n0, _aKST, 8, 0];
- var clientTokenType = [0, n0, _cTT, 8, 0];
- exports.AssumedRoleUser$ = [3, n0, _ARU, 0, [_ARI, _A], [0, 0], 2];
- exports.AssumeRoleRequest$ = [
- 3,
- n0,
- _ARR,
- 0,
- [_RA, _RSN, _PA, _P, _DS, _T, _TTK, _EI, _SN, _TC, _SI, _PC],
- [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType],
- 2
- ];
- exports.AssumeRoleResponse$ = [
- 3,
- n0,
- _ARRs,
- 0,
- [_C, _ARU, _PPS, _SI],
- [[() => exports.Credentials$, 0], () => exports.AssumedRoleUser$, 1, 0]
- ];
- exports.AssumeRoleWithWebIdentityRequest$ = [
- 3,
- n0,
- _ARWWIR,
- 0,
- [_RA, _RSN, _WIT, _PI, _PA, _P, _DS],
- [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1],
- 3
- ];
- exports.AssumeRoleWithWebIdentityResponse$ = [
- 3,
- n0,
- _ARWWIRs,
- 0,
- [_C, _SFWIT, _ARU, _PPS, _Pr, _Au, _SI],
- [[() => exports.Credentials$, 0], 0, () => exports.AssumedRoleUser$, 1, 0, 0, 0]
- ];
- exports.Credentials$ = [
- 3,
- n0,
- _C,
- 0,
- [_AKI, _SAK, _ST, _E],
- [0, [() => accessKeySecretType, 0], 0, 4],
- 4
- ];
- exports.PolicyDescriptorType$ = [3, n0, _PDT, 0, [_a2], [0]];
- exports.ProvidedContext$ = [3, n0, _PCr, 0, [_PAr, _CA], [0, 0]];
- exports.Tag$ = [3, n0, _Ta, 0, [_K, _V], [0, 0], 2];
- var policyDescriptorListType = [1, n0, _pDLT, 0, () => exports.PolicyDescriptorType$];
- var ProvidedContextsListType = [1, n0, _PCLT, 0, () => exports.ProvidedContext$];
- var tagKeyListType = 64 | 0;
- var tagListType = [1, n0, _tLT, 0, () => exports.Tag$];
- exports.AssumeRole$ = [9, n0, _AR, 0, () => exports.AssumeRoleRequest$, () => exports.AssumeRoleResponse$];
- exports.AssumeRoleWithWebIdentity$ = [
- 9,
- n0,
- _ARWWI,
- 0,
- () => exports.AssumeRoleWithWebIdentityRequest$,
- () => exports.AssumeRoleWithWebIdentityResponse$
- ];
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.shared.js
-var require_runtimeConfig_shared3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRuntimeConfig = undefined;
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var protocols_1 = require_protocols2();
- var core_1 = require_dist_cjs37();
- var smithy_client_1 = require_dist_cjs71();
- var url_parser_1 = require_dist_cjs11();
- var util_base64_1 = require_dist_cjs86();
- var util_utf8_1 = require_dist_cjs17();
- var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider3();
- var endpointResolver_1 = require_endpointResolver3();
- var schemas_0_1 = require_schemas_03();
- var getRuntimeConfig = (config3) => {
- return {
- apiVersion: "2011-06-15",
- base64Decoder: config3?.base64Decoder ?? util_base64_1.fromBase64,
- base64Encoder: config3?.base64Encoder ?? util_base64_1.toBase64,
- disableHostPrefix: config3?.disableHostPrefix ?? false,
- endpointProvider: config3?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver,
- extensions: config3?.extensions ?? [],
- httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider,
- httpAuthSchemes: config3?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
- signer: new httpAuthSchemes_1.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#noAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
- signer: new core_1.NoAuthSigner
- }
- ],
- logger: config3?.logger ?? new smithy_client_1.NoOpLogger,
- protocol: config3?.protocol ?? protocols_1.AwsQueryProtocol,
- protocolSettings: config3?.protocolSettings ?? {
- defaultNamespace: "com.amazonaws.sts",
- errorTypeRegistries: schemas_0_1.errorTypeRegistries,
- xmlNamespace: "https://sts.amazonaws.com/doc/2011-06-15/",
- version: "2011-06-15",
- serviceTarget: "AWSSecurityTokenServiceV20110615"
- },
- serviceId: config3?.serviceId ?? "STS",
- urlParser: config3?.urlParser ?? url_parser_1.parseUrl,
- utf8Decoder: config3?.utf8Decoder ?? util_utf8_1.fromUtf8,
- utf8Encoder: config3?.utf8Encoder ?? util_utf8_1.toUtf8
- };
- };
- exports.getRuntimeConfig = getRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.js
-var require_runtimeConfig3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRuntimeConfig = undefined;
- var tslib_1 = require_tslib();
- var package_json_1 = tslib_1.__importDefault(require_package());
- var client_1 = require_client();
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var util_user_agent_node_1 = require_dist_cjs72();
- var config_resolver_1 = require_dist_cjs58();
- var core_1 = require_dist_cjs37();
- var hash_node_1 = require_dist_cjs75();
- var middleware_retry_1 = require_dist_cjs69();
- var node_config_provider_1 = require_dist_cjs9();
- var node_http_handler_1 = require_dist_cjs5();
- var smithy_client_1 = require_dist_cjs71();
- var util_body_length_node_1 = require_dist_cjs76();
- var util_defaults_mode_node_1 = require_dist_cjs77();
- var util_retry_1 = require_dist_cjs55();
- var runtimeConfig_shared_1 = require_runtimeConfig_shared3();
- var getRuntimeConfig = (config3) => {
- (0, smithy_client_1.emitWarningIfUnsupportedVersion)(process.version);
- const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config3);
- const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
- const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config3);
- (0, client_1.emitWarningIfUnsupportedVersion)(process.version);
- const loaderConfig = {
- profile: config3?.profile,
- logger: clientSharedValues.logger
- };
- return {
- ...clientSharedValues,
- ...config3,
- runtime: "node",
- defaultsMode,
- authSchemePreference: config3?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(httpAuthSchemes_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
- bodyLengthChecker: config3?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength,
- defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
- httpAuthSchemes: config3?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || (async (idProps) => await config3.credentialDefaultProvider(idProps?.__config || {})()),
- signer: new httpAuthSchemes_1.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#noAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
- signer: new core_1.NoAuthSigner
- }
- ],
- maxAttempts: config3?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3),
- region: config3?.region ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
- requestHandler: node_http_handler_1.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider),
- retryMode: config3?.retryMode ?? (0, node_config_provider_1.loadConfig)({
- ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
- default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
- }, config3),
- sha256: config3?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"),
- streamCollector: config3?.streamCollector ?? node_http_handler_1.streamCollector,
- useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- useFipsEndpoint: config3?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- userAgentAppId: config3?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
- };
- };
- exports.getRuntimeConfig = getRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthExtensionConfiguration.js
-var require_httpAuthExtensionConfiguration = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = undefined;
- var getHttpAuthExtensionConfiguration = (runtimeConfig) => {
- const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
- let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
- let _credentials = runtimeConfig.credentials;
- return {
- setHttpAuthScheme(httpAuthScheme) {
- const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
- if (index2 === -1) {
- _httpAuthSchemes.push(httpAuthScheme);
- } else {
- _httpAuthSchemes.splice(index2, 1, httpAuthScheme);
- }
- },
- httpAuthSchemes() {
- return _httpAuthSchemes;
- },
- setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
- _httpAuthSchemeProvider = httpAuthSchemeProvider;
- },
- httpAuthSchemeProvider() {
- return _httpAuthSchemeProvider;
- },
- setCredentials(credentials) {
- _credentials = credentials;
- },
- credentials() {
- return _credentials;
- }
- };
- };
- exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration;
- var resolveHttpAuthRuntimeConfig = (config3) => {
- return {
- httpAuthSchemes: config3.httpAuthSchemes(),
- httpAuthSchemeProvider: config3.httpAuthSchemeProvider(),
- credentials: config3.credentials()
- };
- };
- exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeExtensions.js
-var require_runtimeExtensions = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.resolveRuntimeExtensions = undefined;
- var region_config_resolver_1 = require_dist_cjs87();
- var protocol_http_1 = require_dist_cjs88();
- var smithy_client_1 = require_dist_cjs71();
- var httpAuthExtensionConfiguration_1 = require_httpAuthExtensionConfiguration();
- var resolveRuntimeExtensions = (runtimeConfig, extensions4) => {
- const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig));
- extensions4.forEach((extension) => extension.configure(extensionConfiguration));
- return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration));
- };
- exports.resolveRuntimeExtensions = resolveRuntimeExtensions;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/STSClient.js
-var require_STSClient = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.STSClient = exports.__Client = undefined;
- var middleware_host_header_1 = require_dist_cjs44();
- var middleware_logger_1 = require_dist_cjs45();
- var middleware_recursion_detection_1 = require_dist_cjs48();
- var middleware_user_agent_1 = require_dist_cjs56();
- var config_resolver_1 = require_dist_cjs58();
- var core_1 = require_dist_cjs37();
- var schema_1 = require_schema();
- var middleware_content_length_1 = require_dist_cjs61();
- var middleware_endpoint_1 = require_dist_cjs65();
- var middleware_retry_1 = require_dist_cjs69();
- var smithy_client_1 = require_dist_cjs71();
- Object.defineProperty(exports, "__Client", { enumerable: true, get: function() {
- return smithy_client_1.Client;
- } });
- var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider3();
- var EndpointParameters_1 = require_EndpointParameters();
- var runtimeConfig_1 = require_runtimeConfig3();
- var runtimeExtensions_1 = require_runtimeExtensions();
-
- class STSClient extends smithy_client_1.Client {
- config;
- constructor(...[configuration]) {
- const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {});
- super(_config_0);
- this.initConfig = _config_0;
- const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0);
- const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1);
- const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2);
- const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3);
- const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4);
- const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5);
- const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6);
- const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []);
- this.config = _config_8;
- this.middlewareStack.use((0, schema_1.getSchemaSerdePlugin)(this.config));
- this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config));
- this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config));
- this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config));
- this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config));
- this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config));
- this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config));
- this.middlewareStack.use((0, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, {
- httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider,
- identityProviderConfigProvider: async (config3) => new core_1.DefaultIdentityProviderConfig({
- "aws.auth#sigv4": config3.credentials
- })
- }));
- this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config));
- }
- destroy() {
- super.destroy();
- }
- }
- exports.STSClient = STSClient;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/index.js
-var require_sts = __commonJS((exports) => {
- var STSClient = require_STSClient();
- var smithyClient = require_dist_cjs71();
- var middlewareEndpoint = require_dist_cjs65();
- var EndpointParameters = require_EndpointParameters();
- var schemas_0 = require_schemas_03();
- var errors3 = require_errors3();
- var client3 = require_client();
- var regionConfigResolver = require_dist_cjs87();
- var STSServiceException = require_STSServiceException();
-
- class AssumeRoleCommand extends smithyClient.Command.classBuilder().ep(EndpointParameters.commonParams).m(function(Command3, cs, config3, o2) {
- return [middlewareEndpoint.getEndpointPlugin(config3, Command3.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").sc(schemas_0.AssumeRole$).build() {
- }
-
- class AssumeRoleWithWebIdentityCommand extends smithyClient.Command.classBuilder().ep(EndpointParameters.commonParams).m(function(Command3, cs, config3, o2) {
- return [middlewareEndpoint.getEndpointPlugin(config3, Command3.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").sc(schemas_0.AssumeRoleWithWebIdentity$).build() {
- }
- var commands = {
- AssumeRoleCommand,
- AssumeRoleWithWebIdentityCommand
- };
-
- class STS extends STSClient.STSClient {
- }
- smithyClient.createAggregatedClient(commands, STS);
- var getAccountIdFromAssumedRoleUser = (assumedRoleUser) => {
- if (typeof assumedRoleUser?.Arn === "string") {
- const arnComponents = assumedRoleUser.Arn.split(":");
- if (arnComponents.length > 4 && arnComponents[4] !== "") {
- return arnComponents[4];
- }
- }
- return;
- };
- var resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => {
- const region = typeof _region === "function" ? await _region() : _region;
- const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion;
- let stsDefaultRegion = "";
- const resolvedRegion = region ?? parentRegion ?? (stsDefaultRegion = await regionConfigResolver.stsRegionDefaultResolver(loaderConfig)());
- credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (credential provider clientConfig)`, `${parentRegion} (contextual client)`, `${stsDefaultRegion} (STS default: AWS_REGION, profile region, or us-east-1)`);
- return resolvedRegion;
- };
- var getDefaultRoleAssumer$1 = (stsOptions, STSClient2) => {
- let stsClient;
- let closureSourceCreds;
- return async (sourceCreds, params) => {
- closureSourceCreds = sourceCreds;
- if (!stsClient) {
- const { logger: logger2 = stsOptions?.parentClientConfig?.logger, profile: profile2 = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions;
- const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, {
- logger: logger2,
- profile: profile2
- });
- const isCompatibleRequestHandler = !isH2(requestHandler);
- stsClient = new STSClient2({
- ...stsOptions,
- userAgentAppId,
- profile: profile2,
- credentialDefaultProvider: () => async () => closureSourceCreds,
- region: resolvedRegion,
- requestHandler: isCompatibleRequestHandler ? requestHandler : undefined,
- logger: logger2
- });
- }
- const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params));
- if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
- throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`);
- }
- const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
- const credentials = {
- accessKeyId: Credentials.AccessKeyId,
- secretAccessKey: Credentials.SecretAccessKey,
- sessionToken: Credentials.SessionToken,
- expiration: Credentials.Expiration,
- ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
- ...accountId && { accountId }
- };
- client3.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i");
- return credentials;
- };
- };
- var getDefaultRoleAssumerWithWebIdentity$1 = (stsOptions, STSClient2) => {
- let stsClient;
- return async (params) => {
- if (!stsClient) {
- const { logger: logger2 = stsOptions?.parentClientConfig?.logger, profile: profile2 = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions;
- const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, {
- logger: logger2,
- profile: profile2
- });
- const isCompatibleRequestHandler = !isH2(requestHandler);
- stsClient = new STSClient2({
- ...stsOptions,
- userAgentAppId,
- profile: profile2,
- region: resolvedRegion,
- requestHandler: isCompatibleRequestHandler ? requestHandler : undefined,
- logger: logger2
- });
- }
- const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params));
- if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
- throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`);
- }
- const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
- const credentials = {
- accessKeyId: Credentials.AccessKeyId,
- secretAccessKey: Credentials.SecretAccessKey,
- sessionToken: Credentials.SessionToken,
- expiration: Credentials.Expiration,
- ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
- ...accountId && { accountId }
- };
- if (accountId) {
- client3.setCredentialFeature(credentials, "RESOLVED_ACCOUNT_ID", "T");
- }
- client3.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k");
- return credentials;
- };
- };
- var isH2 = (requestHandler) => {
- return requestHandler?.metadata?.handlerProtocol === "h2";
- };
- var getCustomizableStsClientCtor = (baseCtor, customizations) => {
- if (!customizations)
- return baseCtor;
- else
- return class CustomizableSTSClient extends baseCtor {
- constructor(config3) {
- super(config3);
- for (const customization of customizations) {
- this.middlewareStack.use(customization);
- }
- }
- };
- };
- var getDefaultRoleAssumer = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins));
- var getDefaultRoleAssumerWithWebIdentity = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins));
- var decorateDefaultCredentialProvider = (provider) => (input) => provider({
- roleAssumer: getDefaultRoleAssumer(input),
- roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity(input),
- ...input
- });
- exports.$Command = smithyClient.Command;
- exports.STSServiceException = STSServiceException.STSServiceException;
- exports.AssumeRoleCommand = AssumeRoleCommand;
- exports.AssumeRoleWithWebIdentityCommand = AssumeRoleWithWebIdentityCommand;
- exports.STS = STS;
- exports.decorateDefaultCredentialProvider = decorateDefaultCredentialProvider;
- exports.getDefaultRoleAssumer = getDefaultRoleAssumer;
- exports.getDefaultRoleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity;
- Object.prototype.hasOwnProperty.call(STSClient, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: STSClient["__proto__"]
- });
- Object.keys(STSClient).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = STSClient[k];
- });
- Object.prototype.hasOwnProperty.call(schemas_0, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: schemas_0["__proto__"]
- });
- Object.keys(schemas_0).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = schemas_0[k];
- });
- Object.prototype.hasOwnProperty.call(errors3, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: errors3["__proto__"]
- });
- Object.keys(errors3).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = errors3[k];
- });
-});
-
-// node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js
-var import_client6, import_property_provider19, import_shared_ini_file_loader5, isAssumeRoleProfile = (arg, { profile: profile2 = "default", logger: logger2 } = {}) => {
- return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile: profile2, logger: logger2 }) || isCredentialSourceProfile(arg, { profile: profile2, logger: logger2 }));
-}, isAssumeRoleWithSourceProfile = (arg, { profile: profile2, logger: logger2 }) => {
- const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined";
- if (withSourceProfile) {
- logger2?.debug?.(` ${profile2} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);
- }
- return withSourceProfile;
-}, isCredentialSourceProfile = (arg, { profile: profile2, logger: logger2 }) => {
- const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined";
- if (withProviderProfile) {
- logger2?.debug?.(` ${profile2} isCredentialSourceProfile credential_source=${arg.credential_source}`);
- }
- return withProviderProfile;
-}, resolveAssumeRoleCredentials = async (profileName, profiles, options2, callerClientConfig, visitedProfiles = {}, resolveProfileData) => {
- options2.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");
- const profileData = profiles[profileName];
- const { source_profile, region } = profileData;
- if (!options2.roleAssumer) {
- const { getDefaultRoleAssumer } = await Promise.resolve().then(() => __toESM(require_sts(), 1));
- options2.roleAssumer = getDefaultRoleAssumer({
- ...options2.clientConfig,
- credentialProviderLogger: options2.logger,
- parentClientConfig: {
- ...callerClientConfig,
- ...options2?.parentClientConfig,
- region: region ?? options2?.parentClientConfig?.region ?? callerClientConfig?.region
- }
- }, options2.clientPlugins);
- }
- if (source_profile && source_profile in visitedProfiles) {
- throw new import_property_provider19.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${import_shared_ini_file_loader5.getProfileName(options2)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), { logger: options2.logger });
- }
- options2.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`);
- const sourceCredsProvider = source_profile ? resolveProfileData(source_profile, profiles, options2, callerClientConfig, {
- ...visitedProfiles,
- [source_profile]: true
- }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})) : (await resolveCredentialSource(profileData.credential_source, profileName, options2.logger)(options2))();
- if (isCredentialSourceWithoutRoleArn(profileData)) {
- return sourceCredsProvider.then((creds) => import_client6.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o"));
- } else {
- const params = {
- RoleArn: profileData.role_arn,
- RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`,
- ExternalId: profileData.external_id,
- DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10)
- };
- const { mfa_serial } = profileData;
- if (mfa_serial) {
- if (!options2.mfaCodeProvider) {
- throw new import_property_provider19.CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options2.logger, tryNextLink: false });
- }
- params.SerialNumber = mfa_serial;
- params.TokenCode = await options2.mfaCodeProvider(mfa_serial);
- }
- const sourceCreds = await sourceCredsProvider;
- return options2.roleAssumer(sourceCreds, params).then((creds) => import_client6.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o"));
- }
-}, isCredentialSourceWithoutRoleArn = (section) => {
- return !section.role_arn && !!section.credential_source;
-};
-var init_resolveAssumeRoleCredentials = __esm(() => {
- init_resolveCredentialSource();
- import_client6 = __toESM(require_client(), 1);
- import_property_provider19 = __toESM(require_dist_cjs6(), 1);
- import_shared_ini_file_loader5 = __toESM(require_dist_cjs8(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
-var init_extensions4 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-es/Field.js
-var init_Field2 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
-var init_httpHandler2 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
-class HttpRequest2 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest2({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery2(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest2.clone(this);
- }
-}
-function cloneQuery2(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
-}
-
-// node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-es/types.js
-var init_types6 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-es/index.js
-var init_dist_es9 = __esm(() => {
- init_extensions4();
- init_Field2();
- init_httpHandler2();
- init_types6();
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/auth/httpAuthSchemeProvider.js
-var require_httpAuthSchemeProvider4 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.resolveHttpAuthSchemeConfig = exports.defaultSigninHttpAuthSchemeProvider = exports.defaultSigninHttpAuthSchemeParametersProvider = undefined;
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var util_middleware_1 = require_dist_cjs30();
- var defaultSigninHttpAuthSchemeParametersProvider = async (config3, context, input) => {
- return {
- operation: (0, util_middleware_1.getSmithyContext)(context).operation,
- region: await (0, util_middleware_1.normalizeProvider)(config3.region)() || (() => {
- throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
- })()
- };
- };
- exports.defaultSigninHttpAuthSchemeParametersProvider = defaultSigninHttpAuthSchemeParametersProvider;
- function createAwsAuthSigv4HttpAuthOption(authParameters) {
- return {
- schemeId: "aws.auth#sigv4",
- signingProperties: {
- name: "signin",
- region: authParameters.region
- },
- propertiesExtractor: (config3, context) => ({
- signingProperties: {
- config: config3,
- context
- }
- })
- };
- }
- function createSmithyApiNoAuthHttpAuthOption(authParameters) {
- return {
- schemeId: "smithy.api#noAuth"
- };
- }
- var defaultSigninHttpAuthSchemeProvider = (authParameters) => {
- const options2 = [];
- switch (authParameters.operation) {
- case "CreateOAuth2Token": {
- options2.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
- break;
- }
- default: {
- options2.push(createAwsAuthSigv4HttpAuthOption(authParameters));
- }
- }
- return options2;
- };
- exports.defaultSigninHttpAuthSchemeProvider = defaultSigninHttpAuthSchemeProvider;
- var resolveHttpAuthSchemeConfig = (config3) => {
- const config_0 = (0, httpAuthSchemes_1.resolveAwsSdkSigV4Config)(config3);
- return Object.assign(config_0, {
- authSchemePreference: (0, util_middleware_1.normalizeProvider)(config3.authSchemePreference ?? [])
- });
- };
- exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/ruleset.js
-var require_ruleset4 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ruleSet = undefined;
- var u2 = "required";
- var v = "fn";
- var w = "argv";
- var x2 = "ref";
- var a2 = true;
- var b = "isSet";
- var c5 = "booleanEquals";
- var d = "error";
- var e = "endpoint";
- var f = "tree";
- var g = "PartitionResult";
- var h2 = "stringEquals";
- var i2 = { [u2]: true, default: false, type: "boolean" };
- var j = { [u2]: false, type: "string" };
- var k = { [x2]: "Endpoint" };
- var l = { [v]: c5, [w]: [{ [x2]: "UseFIPS" }, true] };
- var m = { [v]: c5, [w]: [{ [x2]: "UseDualStack" }, true] };
- var n2 = {};
- var o2 = { [v]: "getAttr", [w]: [{ [x2]: g }, "name"] };
- var p = { [v]: c5, [w]: [{ [x2]: "UseFIPS" }, false] };
- var q = { [v]: c5, [w]: [{ [x2]: "UseDualStack" }, false] };
- var r = { [v]: "getAttr", [w]: [{ [x2]: g }, "supportsFIPS"] };
- var s = { [v]: c5, [w]: [true, { [v]: "getAttr", [w]: [{ [x2]: g }, "supportsDualStack"] }] };
- var t = [{ [x2]: "Region" }];
- var _data = {
- version: "1.0",
- parameters: { UseDualStack: i2, UseFIPS: i2, Endpoint: j, Region: j },
- rules: [
- {
- conditions: [{ [v]: b, [w]: [k] }],
- rules: [
- { conditions: [l], error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d },
- {
- rules: [
- {
- conditions: [m],
- error: "Invalid Configuration: Dualstack and custom endpoint are not supported",
- type: d
- },
- { endpoint: { url: k, properties: n2, headers: n2 }, type: e }
- ],
- type: f
- }
- ],
- type: f
- },
- {
- rules: [
- {
- conditions: [{ [v]: b, [w]: t }],
- rules: [
- {
- conditions: [{ [v]: "aws.partition", [w]: t, assign: g }],
- rules: [
- {
- conditions: [{ [v]: h2, [w]: [o2, "aws"] }, p, q],
- endpoint: { url: "https://{Region}.signin.aws.amazon.com", properties: n2, headers: n2 },
- type: e
- },
- {
- conditions: [{ [v]: h2, [w]: [o2, "aws-cn"] }, p, q],
- endpoint: { url: "https://{Region}.signin.amazonaws.cn", properties: n2, headers: n2 },
- type: e
- },
- {
- conditions: [{ [v]: h2, [w]: [o2, "aws-us-gov"] }, p, q],
- endpoint: { url: "https://{Region}.signin.amazonaws-us-gov.com", properties: n2, headers: n2 },
- type: e
- },
- {
- conditions: [l, m],
- rules: [
- {
- conditions: [{ [v]: c5, [w]: [a2, r] }, s],
- rules: [
- {
- endpoint: {
- url: "https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",
- properties: n2,
- headers: n2
- },
- type: e
- }
- ],
- type: f
- },
- {
- error: "FIPS and DualStack are enabled, but this partition does not support one or both",
- type: d
- }
- ],
- type: f
- },
- {
- conditions: [l, q],
- rules: [
- {
- conditions: [{ [v]: c5, [w]: [r, a2] }],
- rules: [
- {
- endpoint: {
- url: "https://signin-fips.{Region}.{PartitionResult#dnsSuffix}",
- properties: n2,
- headers: n2
- },
- type: e
- }
- ],
- type: f
- },
- { error: "FIPS is enabled but this partition does not support FIPS", type: d }
- ],
- type: f
- },
- {
- conditions: [p, m],
- rules: [
- {
- conditions: [s],
- rules: [
- {
- endpoint: {
- url: "https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}",
- properties: n2,
- headers: n2
- },
- type: e
- }
- ],
- type: f
- },
- { error: "DualStack is enabled but this partition does not support DualStack", type: d }
- ],
- type: f
- },
- {
- endpoint: { url: "https://signin.{Region}.{PartitionResult#dnsSuffix}", properties: n2, headers: n2 },
- type: e
- }
- ],
- type: f
- }
- ],
- type: f
- },
- { error: "Invalid Configuration: Missing Region", type: d }
- ],
- type: f
- }
- ]
- };
- exports.ruleSet = _data;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/endpointResolver.js
-var require_endpointResolver4 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.defaultEndpointResolver = undefined;
- var util_endpoints_1 = require_dist_cjs51();
- var util_endpoints_2 = require_dist_cjs50();
- var ruleset_1 = require_ruleset4();
- var cache2 = new util_endpoints_2.EndpointCache({
- size: 50,
- params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
- });
- var defaultEndpointResolver = (endpointParams, context = {}) => {
- return cache2.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
- endpointParams,
- logger: context.logger
- }));
- };
- exports.defaultEndpointResolver = defaultEndpointResolver;
- util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/models/SigninServiceException.js
-var require_SigninServiceException = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.SigninServiceException = exports.__ServiceException = undefined;
- var smithy_client_1 = require_dist_cjs71();
- Object.defineProperty(exports, "__ServiceException", { enumerable: true, get: function() {
- return smithy_client_1.ServiceException;
- } });
-
- class SigninServiceException extends smithy_client_1.ServiceException {
- constructor(options2) {
- super(options2);
- Object.setPrototypeOf(this, SigninServiceException.prototype);
- }
- }
- exports.SigninServiceException = SigninServiceException;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/models/errors.js
-var require_errors4 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ValidationException = exports.TooManyRequestsError = exports.InternalServerException = exports.AccessDeniedException = undefined;
- var SigninServiceException_1 = require_SigninServiceException();
-
- class AccessDeniedException extends SigninServiceException_1.SigninServiceException {
- name = "AccessDeniedException";
- $fault = "client";
- error;
- constructor(opts) {
- super({
- name: "AccessDeniedException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, AccessDeniedException.prototype);
- this.error = opts.error;
- }
- }
- exports.AccessDeniedException = AccessDeniedException;
-
- class InternalServerException extends SigninServiceException_1.SigninServiceException {
- name = "InternalServerException";
- $fault = "server";
- error;
- constructor(opts) {
- super({
- name: "InternalServerException",
- $fault: "server",
- ...opts
- });
- Object.setPrototypeOf(this, InternalServerException.prototype);
- this.error = opts.error;
- }
- }
- exports.InternalServerException = InternalServerException;
-
- class TooManyRequestsError extends SigninServiceException_1.SigninServiceException {
- name = "TooManyRequestsError";
- $fault = "client";
- error;
- constructor(opts) {
- super({
- name: "TooManyRequestsError",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, TooManyRequestsError.prototype);
- this.error = opts.error;
- }
- }
- exports.TooManyRequestsError = TooManyRequestsError;
-
- class ValidationException extends SigninServiceException_1.SigninServiceException {
- name = "ValidationException";
- $fault = "client";
- error;
- constructor(opts) {
- super({
- name: "ValidationException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ValidationException.prototype);
- this.error = opts.error;
- }
- }
- exports.ValidationException = ValidationException;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/schemas/schemas_0.js
-var require_schemas_04 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.CreateOAuth2Token$ = exports.CreateOAuth2TokenResponseBody$ = exports.CreateOAuth2TokenResponse$ = exports.CreateOAuth2TokenRequestBody$ = exports.CreateOAuth2TokenRequest$ = exports.AccessToken$ = exports.errorTypeRegistries = exports.ValidationException$ = exports.TooManyRequestsError$ = exports.InternalServerException$ = exports.AccessDeniedException$ = exports.SigninServiceException$ = undefined;
- var _ADE = "AccessDeniedException";
- var _AT = "AccessToken";
- var _COAT = "CreateOAuth2Token";
- var _COATR = "CreateOAuth2TokenRequest";
- var _COATRB = "CreateOAuth2TokenRequestBody";
- var _COATRBr = "CreateOAuth2TokenResponseBody";
- var _COATRr = "CreateOAuth2TokenResponse";
- var _ISE = "InternalServerException";
- var _RT = "RefreshToken";
- var _TMRE = "TooManyRequestsError";
- var _VE = "ValidationException";
- var _aKI = "accessKeyId";
- var _aT = "accessToken";
- var _c = "client";
- var _cI = "clientId";
- var _cV = "codeVerifier";
- var _co = "code";
- var _e = "error";
- var _eI = "expiresIn";
- var _gT = "grantType";
- var _h = "http";
- var _hE = "httpError";
- var _iT = "idToken";
- var _jN = "jsonName";
- var _m = "message";
- var _rT = "refreshToken";
- var _rU = "redirectUri";
- var _s = "smithy.ts.sdk.synthetic.com.amazonaws.signin";
- var _sAK = "secretAccessKey";
- var _sT = "sessionToken";
- var _se = "server";
- var _tI = "tokenInput";
- var _tO = "tokenOutput";
- var _tT = "tokenType";
- var n0 = "com.amazonaws.signin";
- var schema_1 = require_schema();
- var errors_1 = require_errors4();
- var SigninServiceException_1 = require_SigninServiceException();
- var _s_registry = schema_1.TypeRegistry.for(_s);
- exports.SigninServiceException$ = [-3, _s, "SigninServiceException", 0, [], []];
- _s_registry.registerError(exports.SigninServiceException$, SigninServiceException_1.SigninServiceException);
- var n0_registry = schema_1.TypeRegistry.for(n0);
- exports.AccessDeniedException$ = [-3, n0, _ADE, { [_e]: _c }, [_e, _m], [0, 0], 2];
- n0_registry.registerError(exports.AccessDeniedException$, errors_1.AccessDeniedException);
- exports.InternalServerException$ = [-3, n0, _ISE, { [_e]: _se, [_hE]: 500 }, [_e, _m], [0, 0], 2];
- n0_registry.registerError(exports.InternalServerException$, errors_1.InternalServerException);
- exports.TooManyRequestsError$ = [-3, n0, _TMRE, { [_e]: _c, [_hE]: 429 }, [_e, _m], [0, 0], 2];
- n0_registry.registerError(exports.TooManyRequestsError$, errors_1.TooManyRequestsError);
- exports.ValidationException$ = [-3, n0, _VE, { [_e]: _c, [_hE]: 400 }, [_e, _m], [0, 0], 2];
- n0_registry.registerError(exports.ValidationException$, errors_1.ValidationException);
- exports.errorTypeRegistries = [_s_registry, n0_registry];
- var RefreshToken = [0, n0, _RT, 8, 0];
- exports.AccessToken$ = [
- 3,
- n0,
- _AT,
- 8,
- [_aKI, _sAK, _sT],
- [
- [0, { [_jN]: _aKI }],
- [0, { [_jN]: _sAK }],
- [0, { [_jN]: _sT }]
- ],
- 3
- ];
- exports.CreateOAuth2TokenRequest$ = [
- 3,
- n0,
- _COATR,
- 0,
- [_tI],
- [[() => exports.CreateOAuth2TokenRequestBody$, 16]],
- 1
- ];
- exports.CreateOAuth2TokenRequestBody$ = [
- 3,
- n0,
- _COATRB,
- 0,
- [_cI, _gT, _co, _rU, _cV, _rT],
- [
- [0, { [_jN]: _cI }],
- [0, { [_jN]: _gT }],
- 0,
- [0, { [_jN]: _rU }],
- [0, { [_jN]: _cV }],
- [() => RefreshToken, { [_jN]: _rT }]
- ],
- 2
- ];
- exports.CreateOAuth2TokenResponse$ = [
- 3,
- n0,
- _COATRr,
- 0,
- [_tO],
- [[() => exports.CreateOAuth2TokenResponseBody$, 16]],
- 1
- ];
- exports.CreateOAuth2TokenResponseBody$ = [
- 3,
- n0,
- _COATRBr,
- 0,
- [_aT, _tT, _eI, _rT, _iT],
- [
- [() => exports.AccessToken$, { [_jN]: _aT }],
- [0, { [_jN]: _tT }],
- [1, { [_jN]: _eI }],
- [() => RefreshToken, { [_jN]: _rT }],
- [0, { [_jN]: _iT }]
- ],
- 4
- ];
- exports.CreateOAuth2Token$ = [
- 9,
- n0,
- _COAT,
- { [_h]: ["POST", "/v1/token", 200] },
- () => exports.CreateOAuth2TokenRequest$,
- () => exports.CreateOAuth2TokenResponse$
- ];
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.shared.js
-var require_runtimeConfig_shared4 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRuntimeConfig = undefined;
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var protocols_1 = require_protocols2();
- var core_1 = require_dist_cjs37();
- var smithy_client_1 = require_dist_cjs71();
- var url_parser_1 = require_dist_cjs11();
- var util_base64_1 = require_dist_cjs86();
- var util_utf8_1 = require_dist_cjs17();
- var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider4();
- var endpointResolver_1 = require_endpointResolver4();
- var schemas_0_1 = require_schemas_04();
- var getRuntimeConfig = (config3) => {
- return {
- apiVersion: "2023-01-01",
- base64Decoder: config3?.base64Decoder ?? util_base64_1.fromBase64,
- base64Encoder: config3?.base64Encoder ?? util_base64_1.toBase64,
- disableHostPrefix: config3?.disableHostPrefix ?? false,
- endpointProvider: config3?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver,
- extensions: config3?.extensions ?? [],
- httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSigninHttpAuthSchemeProvider,
- httpAuthSchemes: config3?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
- signer: new httpAuthSchemes_1.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#noAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
- signer: new core_1.NoAuthSigner
- }
- ],
- logger: config3?.logger ?? new smithy_client_1.NoOpLogger,
- protocol: config3?.protocol ?? protocols_1.AwsRestJsonProtocol,
- protocolSettings: config3?.protocolSettings ?? {
- defaultNamespace: "com.amazonaws.signin",
- errorTypeRegistries: schemas_0_1.errorTypeRegistries,
- version: "2023-01-01",
- serviceTarget: "Signin"
- },
- serviceId: config3?.serviceId ?? "Signin",
- urlParser: config3?.urlParser ?? url_parser_1.parseUrl,
- utf8Decoder: config3?.utf8Decoder ?? util_utf8_1.fromUtf8,
- utf8Encoder: config3?.utf8Encoder ?? util_utf8_1.toUtf8
- };
- };
- exports.getRuntimeConfig = getRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.js
-var require_runtimeConfig4 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRuntimeConfig = undefined;
- var tslib_1 = require_tslib();
- var package_json_1 = tslib_1.__importDefault(require_package());
- var client_1 = require_client();
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var util_user_agent_node_1 = require_dist_cjs72();
- var config_resolver_1 = require_dist_cjs58();
- var hash_node_1 = require_dist_cjs75();
- var middleware_retry_1 = require_dist_cjs69();
- var node_config_provider_1 = require_dist_cjs9();
- var node_http_handler_1 = require_dist_cjs5();
- var smithy_client_1 = require_dist_cjs71();
- var util_body_length_node_1 = require_dist_cjs76();
- var util_defaults_mode_node_1 = require_dist_cjs77();
- var util_retry_1 = require_dist_cjs55();
- var runtimeConfig_shared_1 = require_runtimeConfig_shared4();
- var getRuntimeConfig = (config3) => {
- (0, smithy_client_1.emitWarningIfUnsupportedVersion)(process.version);
- const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config3);
- const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
- const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config3);
- (0, client_1.emitWarningIfUnsupportedVersion)(process.version);
- const loaderConfig = {
- profile: config3?.profile,
- logger: clientSharedValues.logger
- };
- return {
- ...clientSharedValues,
- ...config3,
- runtime: "node",
- defaultsMode,
- authSchemePreference: config3?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(httpAuthSchemes_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
- bodyLengthChecker: config3?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength,
- defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
- maxAttempts: config3?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3),
- region: config3?.region ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
- requestHandler: node_http_handler_1.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider),
- retryMode: config3?.retryMode ?? (0, node_config_provider_1.loadConfig)({
- ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
- default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
- }, config3),
- sha256: config3?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"),
- streamCollector: config3?.streamCollector ?? node_http_handler_1.streamCollector,
- useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- useFipsEndpoint: config3?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- userAgentAppId: config3?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
- };
- };
- exports.getRuntimeConfig = getRuntimeConfig;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js
-var require_signin = __commonJS((exports) => {
- var middlewareHostHeader = require_dist_cjs44();
- var middlewareLogger = require_dist_cjs45();
- var middlewareRecursionDetection = require_dist_cjs48();
- var middlewareUserAgent = require_dist_cjs56();
- var configResolver = require_dist_cjs58();
- var core2 = require_dist_cjs37();
- var schema2 = require_schema();
- var middlewareContentLength = require_dist_cjs61();
- var middlewareEndpoint = require_dist_cjs65();
- var middlewareRetry = require_dist_cjs69();
- var smithyClient = require_dist_cjs71();
- var httpAuthSchemeProvider = require_httpAuthSchemeProvider4();
- var runtimeConfig = require_runtimeConfig4();
- var regionConfigResolver = require_dist_cjs87();
- var protocolHttp = require_dist_cjs88();
- var schemas_0 = require_schemas_04();
- var errors3 = require_errors4();
- var SigninServiceException = require_SigninServiceException();
- var resolveClientEndpointParameters = (options2) => {
- return Object.assign(options2, {
- useDualstackEndpoint: options2.useDualstackEndpoint ?? false,
- useFipsEndpoint: options2.useFipsEndpoint ?? false,
- defaultSigningName: "signin"
- });
- };
- var commonParams = {
- UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
- Endpoint: { type: "builtInParams", name: "endpoint" },
- Region: { type: "builtInParams", name: "region" },
- UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
- };
- var getHttpAuthExtensionConfiguration = (runtimeConfig2) => {
- const _httpAuthSchemes = runtimeConfig2.httpAuthSchemes;
- let _httpAuthSchemeProvider = runtimeConfig2.httpAuthSchemeProvider;
- let _credentials = runtimeConfig2.credentials;
- return {
- setHttpAuthScheme(httpAuthScheme) {
- const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
- if (index2 === -1) {
- _httpAuthSchemes.push(httpAuthScheme);
- } else {
- _httpAuthSchemes.splice(index2, 1, httpAuthScheme);
- }
- },
- httpAuthSchemes() {
- return _httpAuthSchemes;
- },
- setHttpAuthSchemeProvider(httpAuthSchemeProvider2) {
- _httpAuthSchemeProvider = httpAuthSchemeProvider2;
- },
- httpAuthSchemeProvider() {
- return _httpAuthSchemeProvider;
- },
- setCredentials(credentials) {
- _credentials = credentials;
- },
- credentials() {
- return _credentials;
- }
- };
- };
- var resolveHttpAuthRuntimeConfig = (config3) => {
- return {
- httpAuthSchemes: config3.httpAuthSchemes(),
- httpAuthSchemeProvider: config3.httpAuthSchemeProvider(),
- credentials: config3.credentials()
- };
- };
- var resolveRuntimeExtensions = (runtimeConfig2, extensions5) => {
- const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig2), smithyClient.getDefaultExtensionConfiguration(runtimeConfig2), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig2), getHttpAuthExtensionConfiguration(runtimeConfig2));
- extensions5.forEach((extension) => extension.configure(extensionConfiguration));
- return Object.assign(runtimeConfig2, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));
- };
-
- class SigninClient extends smithyClient.Client {
- config;
- constructor(...[configuration]) {
- const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {});
- super(_config_0);
- this.initConfig = _config_0;
- const _config_1 = resolveClientEndpointParameters(_config_0);
- const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1);
- const _config_3 = middlewareRetry.resolveRetryConfig(_config_2);
- const _config_4 = configResolver.resolveRegionConfig(_config_3);
- const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4);
- const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5);
- const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6);
- const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);
- this.config = _config_8;
- this.middlewareStack.use(schema2.getSchemaSerdePlugin(this.config));
- this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config));
- this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config));
- this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config));
- this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config));
- this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config));
- this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config));
- this.middlewareStack.use(core2.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
- httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultSigninHttpAuthSchemeParametersProvider,
- identityProviderConfigProvider: async (config3) => new core2.DefaultIdentityProviderConfig({
- "aws.auth#sigv4": config3.credentials
- })
- }));
- this.middlewareStack.use(core2.getHttpSigningPlugin(this.config));
- }
- destroy() {
- super.destroy();
- }
- }
-
- class CreateOAuth2TokenCommand extends smithyClient.Command.classBuilder().ep(commonParams).m(function(Command3, cs, config3, o2) {
- return [middlewareEndpoint.getEndpointPlugin(config3, Command3.getEndpointParameterInstructions())];
- }).s("Signin", "CreateOAuth2Token", {}).n("SigninClient", "CreateOAuth2TokenCommand").sc(schemas_0.CreateOAuth2Token$).build() {
- }
- var commands = {
- CreateOAuth2TokenCommand
- };
-
- class Signin extends SigninClient {
- }
- smithyClient.createAggregatedClient(commands, Signin);
- var OAuth2ErrorCode = {
- AUTHCODE_EXPIRED: "AUTHCODE_EXPIRED",
- INSUFFICIENT_PERMISSIONS: "INSUFFICIENT_PERMISSIONS",
- INVALID_REQUEST: "INVALID_REQUEST",
- SERVER_ERROR: "server_error",
- TOKEN_EXPIRED: "TOKEN_EXPIRED",
- USER_CREDENTIALS_CHANGED: "USER_CREDENTIALS_CHANGED"
- };
- exports.$Command = smithyClient.Command;
- exports.__Client = smithyClient.Client;
- exports.SigninServiceException = SigninServiceException.SigninServiceException;
- exports.CreateOAuth2TokenCommand = CreateOAuth2TokenCommand;
- exports.OAuth2ErrorCode = OAuth2ErrorCode;
- exports.Signin = Signin;
- exports.SigninClient = SigninClient;
- Object.prototype.hasOwnProperty.call(schemas_0, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: schemas_0["__proto__"]
- });
- Object.keys(schemas_0).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = schemas_0[k];
- });
- Object.prototype.hasOwnProperty.call(errors3, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: errors3["__proto__"]
- });
- Object.keys(errors3).forEach(function(k) {
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
- exports[k] = errors3[k];
- });
-});
-
-// node_modules/@aws-sdk/credential-provider-login/dist-es/LoginCredentialsFetcher.js
-import { createHash as createHash3, createPrivateKey, createPublicKey, sign } from "crypto";
-import { promises as fs3 } from "fs";
-import { homedir as homedir9 } from "os";
-import { dirname as dirname12, join as join21 } from "path";
-var import_property_provider20, import_shared_ini_file_loader6, LoginCredentialsFetcher;
-var init_LoginCredentialsFetcher = __esm(() => {
- init_dist_es9();
- import_property_provider20 = __toESM(require_dist_cjs6(), 1);
- import_shared_ini_file_loader6 = __toESM(require_dist_cjs8(), 1);
- LoginCredentialsFetcher = class LoginCredentialsFetcher {
- profileData;
- init;
- callerClientConfig;
- static REFRESH_THRESHOLD = 5 * 60 * 1000;
- constructor(profileData, init, callerClientConfig) {
- this.profileData = profileData;
- this.init = init;
- this.callerClientConfig = callerClientConfig;
- }
- async loadCredentials() {
- const token = await this.loadToken();
- if (!token) {
- throw new import_property_provider20.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`, { tryNextLink: false, logger: this.logger });
- }
- const accessToken = token.accessToken;
- const now = Date.now();
- const expiryTime = new Date(accessToken.expiresAt).getTime();
- const timeUntilExpiry = expiryTime - now;
- if (timeUntilExpiry <= LoginCredentialsFetcher.REFRESH_THRESHOLD) {
- return this.refresh(token);
- }
- return {
- accessKeyId: accessToken.accessKeyId,
- secretAccessKey: accessToken.secretAccessKey,
- sessionToken: accessToken.sessionToken,
- accountId: accessToken.accountId,
- expiration: new Date(accessToken.expiresAt)
- };
- }
- get logger() {
- return this.init?.logger;
- }
- get loginSession() {
- return this.profileData.login_session;
- }
- async refresh(token) {
- const { SigninClient, CreateOAuth2TokenCommand } = await Promise.resolve().then(() => __toESM(require_signin(), 1));
- const { logger: logger2, userAgentAppId } = this.callerClientConfig ?? {};
- const isH2 = (requestHandler2) => {
- return requestHandler2?.metadata?.handlerProtocol === "h2";
- };
- const requestHandler = isH2(this.callerClientConfig?.requestHandler) ? undefined : this.callerClientConfig?.requestHandler;
- const region = this.profileData.region ?? await this.callerClientConfig?.region?.() ?? process.env.AWS_REGION;
- const client3 = new SigninClient({
- credentials: {
- accessKeyId: "",
- secretAccessKey: ""
- },
- region,
- requestHandler,
- logger: logger2,
- userAgentAppId,
- ...this.init?.clientConfig
- });
- this.createDPoPInterceptor(client3.middlewareStack);
- const commandInput = {
- tokenInput: {
- clientId: token.clientId,
- refreshToken: token.refreshToken,
- grantType: "refresh_token"
- }
- };
- try {
- const response2 = await client3.send(new CreateOAuth2TokenCommand(commandInput));
- const { accessKeyId, secretAccessKey, sessionToken } = response2.tokenOutput?.accessToken ?? {};
- const { refreshToken, expiresIn } = response2.tokenOutput ?? {};
- if (!accessKeyId || !secretAccessKey || !sessionToken || !refreshToken) {
- throw new import_property_provider20.CredentialsProviderError("Token refresh response missing required fields", {
- logger: this.logger,
- tryNextLink: false
- });
- }
- const expiresInMs = (expiresIn ?? 900) * 1000;
- const expiration = new Date(Date.now() + expiresInMs);
- const updatedToken = {
- ...token,
- accessToken: {
- ...token.accessToken,
- accessKeyId,
- secretAccessKey,
- sessionToken,
- expiresAt: expiration.toISOString()
- },
- refreshToken
- };
- await this.saveToken(updatedToken);
- const newAccessToken = updatedToken.accessToken;
- return {
- accessKeyId: newAccessToken.accessKeyId,
- secretAccessKey: newAccessToken.secretAccessKey,
- sessionToken: newAccessToken.sessionToken,
- accountId: newAccessToken.accountId,
- expiration
- };
- } catch (error40) {
- if (error40.name === "AccessDeniedException") {
- const errorType = error40.error;
- let message;
- switch (errorType) {
- case "TOKEN_EXPIRED":
- message = "Your session has expired. Please reauthenticate.";
- break;
- case "USER_CREDENTIALS_CHANGED":
- message = "Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";
- break;
- case "INSUFFICIENT_PERMISSIONS":
- message = "Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";
- break;
- default:
- message = `Failed to refresh token: ${String(error40)}. Please re-authenticate using \`aws login\``;
- }
- throw new import_property_provider20.CredentialsProviderError(message, { logger: this.logger, tryNextLink: false });
- }
- throw new import_property_provider20.CredentialsProviderError(`Failed to refresh token: ${String(error40)}. Please re-authenticate using aws login`, { logger: this.logger });
- }
- }
- async loadToken() {
- const tokenFilePath = this.getTokenFilePath();
- try {
- let tokenData;
- try {
- tokenData = await import_shared_ini_file_loader6.readFile(tokenFilePath, { ignoreCache: this.init?.ignoreCache });
- } catch {
- tokenData = await fs3.readFile(tokenFilePath, "utf8");
- }
- const token = JSON.parse(tokenData);
- const missingFields = ["accessToken", "clientId", "refreshToken", "dpopKey"].filter((k) => !token[k]);
- if (!token.accessToken?.accountId) {
- missingFields.push("accountId");
- }
- if (missingFields.length > 0) {
- throw new import_property_provider20.CredentialsProviderError(`Token validation failed, missing fields: ${missingFields.join(", ")}`, {
- logger: this.logger,
- tryNextLink: false
- });
- }
- return token;
- } catch (error40) {
- throw new import_property_provider20.CredentialsProviderError(`Failed to load token from ${tokenFilePath}: ${String(error40)}`, {
- logger: this.logger,
- tryNextLink: false
- });
- }
- }
- async saveToken(token) {
- const tokenFilePath = this.getTokenFilePath();
- const directory = dirname12(tokenFilePath);
- try {
- await fs3.mkdir(directory, { recursive: true });
- } catch (error40) {}
- await fs3.writeFile(tokenFilePath, JSON.stringify(token, null, 2), "utf8");
- }
- getTokenFilePath() {
- const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? join21(homedir9(), ".aws", "login", "cache");
- const loginSessionBytes = Buffer.from(this.loginSession, "utf8");
- const loginSessionSha256 = createHash3("sha256").update(loginSessionBytes).digest("hex");
- return join21(directory, `${loginSessionSha256}.json`);
- }
- derToRawSignature(derSignature) {
- let offset = 2;
- if (derSignature[offset] !== 2) {
- throw new Error("Invalid DER signature");
- }
- offset++;
- const rLength = derSignature[offset++];
- let r = derSignature.subarray(offset, offset + rLength);
- offset += rLength;
- if (derSignature[offset] !== 2) {
- throw new Error("Invalid DER signature");
- }
- offset++;
- const sLength = derSignature[offset++];
- let s = derSignature.subarray(offset, offset + sLength);
- r = r[0] === 0 ? r.subarray(1) : r;
- s = s[0] === 0 ? s.subarray(1) : s;
- const rPadded = Buffer.concat([Buffer.alloc(32 - r.length), r]);
- const sPadded = Buffer.concat([Buffer.alloc(32 - s.length), s]);
- return Buffer.concat([rPadded, sPadded]);
- }
- createDPoPInterceptor(middlewareStack) {
- middlewareStack.add((next) => async (args) => {
- if (HttpRequest2.isInstance(args.request)) {
- const request2 = args.request;
- const actualEndpoint = `${request2.protocol}//${request2.hostname}${request2.port ? `:${request2.port}` : ""}${request2.path}`;
- const dpop = await this.generateDpop(request2.method, actualEndpoint);
- request2.headers = {
- ...request2.headers,
- DPoP: dpop
- };
- }
- return next(args);
- }, {
- step: "finalizeRequest",
- name: "dpopInterceptor",
- override: true
- });
- }
- async generateDpop(method = "POST", endpoint2) {
- const token = await this.loadToken();
- try {
- const privateKey = createPrivateKey({
- key: token.dpopKey,
- format: "pem",
- type: "sec1"
- });
- const publicKey = createPublicKey(privateKey);
- const publicDer = publicKey.export({ format: "der", type: "spki" });
- let pointStart = -1;
- for (let i2 = 0;i2 < publicDer.length; i2++) {
- if (publicDer[i2] === 4) {
- pointStart = i2;
- break;
- }
- }
- const x2 = publicDer.slice(pointStart + 1, pointStart + 33);
- const y2 = publicDer.slice(pointStart + 33, pointStart + 65);
- const header = {
- alg: "ES256",
- typ: "dpop+jwt",
- jwk: {
- kty: "EC",
- crv: "P-256",
- x: x2.toString("base64url"),
- y: y2.toString("base64url")
- }
- };
- const payload = {
- jti: crypto.randomUUID(),
- htm: method,
- htu: endpoint2,
- iat: Math.floor(Date.now() / 1000)
- };
- const headerB64 = Buffer.from(JSON.stringify(header)).toString("base64url");
- const payloadB64 = Buffer.from(JSON.stringify(payload)).toString("base64url");
- const message = `${headerB64}.${payloadB64}`;
- const asn1Signature = sign("sha256", Buffer.from(message), privateKey);
- const rawSignature = this.derToRawSignature(asn1Signature);
- const signatureB64 = rawSignature.toString("base64url");
- return `${message}.${signatureB64}`;
- } catch (error40) {
- throw new import_property_provider20.CredentialsProviderError(`Failed to generate Dpop proof: ${error40 instanceof Error ? error40.message : String(error40)}`, { logger: this.logger, tryNextLink: false });
- }
- }
- };
-});
-
-// node_modules/@aws-sdk/credential-provider-login/dist-es/fromLoginCredentials.js
-var import_client7, import_property_provider21, import_shared_ini_file_loader7, fromLoginCredentials = (init) => async ({ callerClientConfig } = {}) => {
- init?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");
- const profiles = await import_shared_ini_file_loader7.parseKnownFiles(init || {});
- const profileName = import_shared_ini_file_loader7.getProfileName({
- profile: init?.profile ?? callerClientConfig?.profile
- });
- const profile2 = profiles[profileName];
- if (!profile2?.login_session) {
- throw new import_property_provider21.CredentialsProviderError(`Profile ${profileName} does not contain login_session.`, {
- tryNextLink: true,
- logger: init?.logger
- });
- }
- const fetcher = new LoginCredentialsFetcher(profile2, init, callerClientConfig);
- const credentials = await fetcher.loadCredentials();
- return import_client7.setCredentialFeature(credentials, "CREDENTIALS_LOGIN", "AD");
-};
-var init_fromLoginCredentials = __esm(() => {
- init_LoginCredentialsFetcher();
- import_client7 = __toESM(require_client(), 1);
- import_property_provider21 = __toESM(require_dist_cjs6(), 1);
- import_shared_ini_file_loader7 = __toESM(require_dist_cjs8(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-login/dist-es/types.js
-var init_types7 = () => {};
-
-// node_modules/@aws-sdk/credential-provider-login/dist-es/index.js
-var init_dist_es10 = __esm(() => {
- init_fromLoginCredentials();
- init_types7();
-});
-
-// node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveLoginCredentials.js
-var import_client8, isLoginProfile = (data) => {
- return Boolean(data && data.login_session);
-}, resolveLoginCredentials = async (profileName, options2, callerClientConfig) => {
- const credentials = await fromLoginCredentials({
- ...options2,
- profile: profileName
- })({ callerClientConfig });
- return import_client8.setCredentialFeature(credentials, "CREDENTIALS_PROFILE_LOGIN", "AC");
-};
-var init_resolveLoginCredentials = __esm(() => {
- init_dist_es10();
- import_client8 = __toESM(require_client(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js
-var import_client9, getValidatedProcessCredentials = (profileName, data, profiles) => {
- if (data.Version !== 1) {
- throw Error(`Profile ${profileName} credential_process did not return Version 1.`);
- }
- if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) {
- throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);
- }
- if (data.Expiration) {
- const currentTime = new Date;
- const expireTime = new Date(data.Expiration);
- if (expireTime < currentTime) {
- throw Error(`Profile ${profileName} credential_process returned expired credentials.`);
- }
- }
- let accountId = data.AccountId;
- if (!accountId && profiles?.[profileName]?.aws_account_id) {
- accountId = profiles[profileName].aws_account_id;
- }
- const credentials = {
- accessKeyId: data.AccessKeyId,
- secretAccessKey: data.SecretAccessKey,
- ...data.SessionToken && { sessionToken: data.SessionToken },
- ...data.Expiration && { expiration: new Date(data.Expiration) },
- ...data.CredentialScope && { credentialScope: data.CredentialScope },
- ...accountId && { accountId }
- };
- import_client9.setCredentialFeature(credentials, "CREDENTIALS_PROCESS", "w");
- return credentials;
-};
-var init_getValidatedProcessCredentials = __esm(() => {
- import_client9 = __toESM(require_client(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js
-import { exec } from "child_process";
-import { promisify as promisify4 } from "util";
-var import_property_provider22, import_shared_ini_file_loader8, resolveProcessCredentials = async (profileName, profiles, logger2) => {
- const profile2 = profiles[profileName];
- if (profiles[profileName]) {
- const credentialProcess = profile2["credential_process"];
- if (credentialProcess !== undefined) {
- const execPromise = promisify4(import_shared_ini_file_loader8.externalDataInterceptor?.getTokenRecord?.().exec ?? exec);
- try {
- const { stdout } = await execPromise(credentialProcess);
- let data;
- try {
- data = JSON.parse(stdout.trim());
- } catch {
- throw Error(`Profile ${profileName} credential_process returned invalid JSON.`);
- }
- return getValidatedProcessCredentials(profileName, data, profiles);
- } catch (error40) {
- throw new import_property_provider22.CredentialsProviderError(error40.message, { logger: logger2 });
- }
- } else {
- throw new import_property_provider22.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger: logger2 });
- }
- } else {
- throw new import_property_provider22.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, {
- logger: logger2
- });
- }
-};
-var init_resolveProcessCredentials = __esm(() => {
- init_getValidatedProcessCredentials();
- import_property_provider22 = __toESM(require_dist_cjs6(), 1);
- import_shared_ini_file_loader8 = __toESM(require_dist_cjs8(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js
-var import_shared_ini_file_loader9, fromProcess = (init = {}) => async ({ callerClientConfig } = {}) => {
- init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");
- const profiles = await import_shared_ini_file_loader9.parseKnownFiles(init);
- return resolveProcessCredentials(import_shared_ini_file_loader9.getProfileName({
- profile: init.profile ?? callerClientConfig?.profile
- }), profiles, init.logger);
-};
-var init_fromProcess = __esm(() => {
- init_resolveProcessCredentials();
- import_shared_ini_file_loader9 = __toESM(require_dist_cjs8(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-process/dist-es/index.js
-var exports_dist_es6 = {};
-__export(exports_dist_es6, {
- fromProcess: () => fromProcess
-});
-var init_dist_es11 = __esm(() => {
- init_fromProcess();
-});
-
-// node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js
-var import_client10, isProcessProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", resolveProcessCredentials2 = async (options2, profile2) => Promise.resolve().then(() => (init_dist_es11(), exports_dist_es6)).then(({ fromProcess: fromProcess3 }) => fromProcess3({
- ...options2,
- profile: profile2
-})().then((creds) => import_client10.setCredentialFeature(creds, "CREDENTIALS_PROFILE_PROCESS", "v")));
-var init_resolveProcessCredentials2 = __esm(() => {
- import_client10 = __toESM(require_client(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js
-var import_client11, resolveSsoCredentials = async (profile2, profileData, options2 = {}, callerClientConfig) => {
- const { fromSSO: fromSSO3 } = await Promise.resolve().then(() => (init_dist_es8(), exports_dist_es5));
- return fromSSO3({
- profile: profile2,
- logger: options2.logger,
- parentClientConfig: options2.parentClientConfig,
- clientConfig: options2.clientConfig
- })({
- callerClientConfig
- }).then((creds) => {
- if (profileData.sso_session) {
- return import_client11.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO", "r");
- } else {
- return import_client11.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t");
- }
- });
-}, isSsoProfile3 = (arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string");
-var init_resolveSsoCredentials = __esm(() => {
- import_client11 = __toESM(require_client(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js
-var import_client12, isStaticCredsProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1, resolveStaticCredentials = async (profile2, options2) => {
- options2?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");
- const credentials = {
- accessKeyId: profile2.aws_access_key_id,
- secretAccessKey: profile2.aws_secret_access_key,
- sessionToken: profile2.aws_session_token,
- ...profile2.aws_credential_scope && { credentialScope: profile2.aws_credential_scope },
- ...profile2.aws_account_id && { accountId: profile2.aws_account_id }
- };
- return import_client12.setCredentialFeature(credentials, "CREDENTIALS_PROFILE", "n");
-};
-var init_resolveStaticCredentials = __esm(() => {
- import_client12 = __toESM(require_client(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js
-var fromWebToken = (init) => async (awsIdentityProperties) => {
- init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");
- const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init;
- let { roleAssumerWithWebIdentity } = init;
- if (!roleAssumerWithWebIdentity) {
- const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __toESM(require_sts(), 1));
- roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({
- ...init.clientConfig,
- credentialProviderLogger: init.logger,
- parentClientConfig: {
- ...awsIdentityProperties?.callerClientConfig,
- ...init.parentClientConfig
- }
- }, init.clientPlugins);
- }
- return roleAssumerWithWebIdentity({
- RoleArn: roleArn,
- RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,
- WebIdentityToken: webIdentityToken,
- ProviderId: providerId,
- PolicyArns: policyArns,
- Policy: policy,
- DurationSeconds: durationSeconds
- });
-};
-
-// node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js
-import { readFileSync as readFileSync6 } from "fs";
-var import_client13, import_property_provider23, import_shared_ini_file_loader10, ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE", ENV_ROLE_ARN = "AWS_ROLE_ARN", ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME", fromTokenFile = (init = {}) => async (awsIdentityProperties) => {
- init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");
- const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE];
- const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN];
- const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME];
- if (!webIdentityTokenFile || !roleArn) {
- throw new import_property_provider23.CredentialsProviderError("Web identity configuration not specified", {
- logger: init.logger
- });
- }
- const credentials = await fromWebToken({
- ...init,
- webIdentityToken: import_shared_ini_file_loader10.externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ?? readFileSync6(webIdentityTokenFile, { encoding: "ascii" }),
- roleArn,
- roleSessionName
- })(awsIdentityProperties);
- if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {
- import_client13.setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h");
- }
- return credentials;
-};
-var init_fromTokenFile = __esm(() => {
- import_client13 = __toESM(require_client(), 1);
- import_property_provider23 = __toESM(require_dist_cjs6(), 1);
- import_shared_ini_file_loader10 = __toESM(require_dist_cjs8(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-web-identity/dist-es/index.js
-var exports_dist_es7 = {};
-__export(exports_dist_es7, {
- fromWebToken: () => fromWebToken,
- fromTokenFile: () => fromTokenFile
-});
-var init_dist_es12 = __esm(() => {
- init_fromTokenFile();
-});
-
-// node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js
-var import_client14, isWebIdentityProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1, resolveWebIdentityCredentials = async (profile2, options2, callerClientConfig) => Promise.resolve().then(() => (init_dist_es12(), exports_dist_es7)).then(({ fromTokenFile: fromTokenFile3 }) => fromTokenFile3({
- webIdentityTokenFile: profile2.web_identity_token_file,
- roleArn: profile2.role_arn,
- roleSessionName: profile2.role_session_name,
- roleAssumerWithWebIdentity: options2.roleAssumerWithWebIdentity,
- logger: options2.logger,
- parentClientConfig: options2.parentClientConfig
-})({
- callerClientConfig
-}).then((creds) => import_client14.setCredentialFeature(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q")));
-var init_resolveWebIdentityCredentials = __esm(() => {
- import_client14 = __toESM(require_client(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js
-var import_property_provider24, resolveProfileData = async (profileName, profiles, options2, callerClientConfig, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => {
- const data = profiles[profileName];
- if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {
- return resolveStaticCredentials(data, options2);
- }
- if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options2.logger })) {
- return resolveAssumeRoleCredentials(profileName, profiles, options2, callerClientConfig, visitedProfiles, resolveProfileData);
- }
- if (isStaticCredsProfile(data)) {
- return resolveStaticCredentials(data, options2);
- }
- if (isWebIdentityProfile(data)) {
- return resolveWebIdentityCredentials(data, options2, callerClientConfig);
- }
- if (isProcessProfile(data)) {
- return resolveProcessCredentials2(options2, profileName);
- }
- if (isSsoProfile3(data)) {
- return await resolveSsoCredentials(profileName, data, options2, callerClientConfig);
- }
- if (isLoginProfile(data)) {
- return resolveLoginCredentials(profileName, options2, callerClientConfig);
- }
- throw new import_property_provider24.CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options2.logger });
-};
-var init_resolveProfileData = __esm(() => {
- init_resolveAssumeRoleCredentials();
- init_resolveLoginCredentials();
- init_resolveProcessCredentials2();
- init_resolveSsoCredentials();
- init_resolveStaticCredentials();
- init_resolveWebIdentityCredentials();
- import_property_provider24 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js
-var import_shared_ini_file_loader11, fromIni = (init = {}) => async ({ callerClientConfig } = {}) => {
- init.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");
- const profiles = await import_shared_ini_file_loader11.parseKnownFiles(init);
- return resolveProfileData(import_shared_ini_file_loader11.getProfileName({
- profile: init.profile ?? callerClientConfig?.profile
- }), profiles, init, callerClientConfig);
-};
-var init_fromIni = __esm(() => {
- init_resolveProfileData();
- import_shared_ini_file_loader11 = __toESM(require_dist_cjs8(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-ini/dist-es/index.js
-var exports_dist_es8 = {};
-__export(exports_dist_es8, {
- fromIni: () => fromIni
-});
-var init_dist_es13 = __esm(() => {
- init_fromIni();
-});
-
-// node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js
-var import_property_provider25, import_shared_ini_file_loader12, multipleCredentialSourceWarningEmitted = false, defaultProvider = (init = {}) => memoizeChain([
- async () => {
- const profile2 = init.profile ?? process.env[import_shared_ini_file_loader12.ENV_PROFILE];
- if (profile2) {
- const envStaticCredentialsAreSet = process.env[ENV_KEY] && process.env[ENV_SECRET];
- if (envStaticCredentialsAreSet) {
- if (!multipleCredentialSourceWarningEmitted) {
- const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" ? init.logger.warn.bind(init.logger) : console.warn;
- warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
- Multiple credential sources detected:
- Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.
- This SDK will proceed with the AWS_PROFILE value.
-
- However, a future version may change this behavior to prefer the ENV static credentials.
- Please ensure that your environment only sets either the AWS_PROFILE or the
- AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.
-`);
- multipleCredentialSourceWarningEmitted = true;
- }
- }
- throw new import_property_provider25.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", {
- logger: init.logger,
- tryNextLink: true
- });
- }
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv");
- return fromEnv(init)();
- },
- async (awsIdentityProperties) => {
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");
- const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;
- if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
- throw new import_property_provider25.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init.logger });
- }
- const { fromSSO: fromSSO3 } = await Promise.resolve().then(() => (init_dist_es8(), exports_dist_es5));
- return fromSSO3(init)(awsIdentityProperties);
- },
- async (awsIdentityProperties) => {
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");
- const { fromIni: fromIni3 } = await Promise.resolve().then(() => (init_dist_es13(), exports_dist_es8));
- return fromIni3(init)(awsIdentityProperties);
- },
- async (awsIdentityProperties) => {
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");
- const { fromProcess: fromProcess3 } = await Promise.resolve().then(() => (init_dist_es11(), exports_dist_es6));
- return fromProcess3(init)(awsIdentityProperties);
- },
- async (awsIdentityProperties) => {
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");
- const { fromTokenFile: fromTokenFile3 } = await Promise.resolve().then(() => (init_dist_es12(), exports_dist_es7));
- return fromTokenFile3(init)(awsIdentityProperties);
- },
- async () => {
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider");
- return (await remoteProvider(init))();
- },
- async () => {
- throw new import_property_provider25.CredentialsProviderError("Could not load credentials from any providers", {
- tryNextLink: false,
- logger: init.logger
- });
- }
-], credentialsTreatedAsExpired), credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== undefined, credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000;
-var init_defaultProvider = __esm(() => {
- init_dist_es();
- init_remoteProvider();
- import_property_provider25 = __toESM(require_dist_cjs6(), 1);
- import_shared_ini_file_loader12 = __toESM(require_dist_cjs8(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-node/dist-es/index.js
-var exports_dist_es9 = {};
-__export(exports_dist_es9, {
- defaultProvider: () => defaultProvider,
- credentialsWillNeedRefresh: () => credentialsWillNeedRefresh,
- credentialsTreatedAsExpired: () => credentialsTreatedAsExpired
-});
-var init_dist_es14 = __esm(() => {
- init_defaultProvider();
-});
-
-// src/utils/proxy.ts
-function disableKeepAlive() {
- keepAliveDisabled = true;
-}
-function getAddressFamily(options2) {
- switch (options2.family) {
- case 0:
- case 4:
- case 6:
- return options2.family;
- case "IPv6":
- return 6;
- case "IPv4":
- case undefined:
- return 4;
- default:
- throw new Error(`Unsupported address family: ${options2.family}`);
- }
-}
-function getProxyUrl(env4 = process.env) {
- return env4.https_proxy || env4.HTTPS_PROXY || env4.http_proxy || env4.HTTP_PROXY;
-}
-function getNoProxy(env4 = process.env) {
- return env4.no_proxy || env4.NO_PROXY;
-}
-function shouldBypassProxy(urlString, noProxy = getNoProxy()) {
- if (!noProxy)
- return false;
- if (noProxy === "*")
- return true;
- try {
- const url3 = new URL(urlString);
- const hostname2 = url3.hostname.toLowerCase();
- const port = url3.port || (url3.protocol === "https:" ? "443" : "80");
- const hostWithPort = `${hostname2}:${port}`;
- const noProxyList = noProxy.split(/[,\s]+/).filter(Boolean);
- return noProxyList.some((pattern) => {
- pattern = pattern.toLowerCase().trim();
- if (pattern.includes(":")) {
- return hostWithPort === pattern;
- }
- if (pattern.startsWith(".")) {
- const suffix = pattern;
- return hostname2 === pattern.substring(1) || hostname2.endsWith(suffix);
- }
- return hostname2 === pattern;
- });
- } catch {
- return false;
- }
-}
-function createHttpsProxyAgent(proxyUrl, extra = {}) {
- const mtlsConfig = getMTLSConfig();
- const caCerts = getCACertificates();
- const agentOptions = {
- ...mtlsConfig && {
- cert: mtlsConfig.cert,
- key: mtlsConfig.key,
- passphrase: mtlsConfig.passphrase
- },
- ...caCerts && { ca: caCerts }
- };
- if (isEnvTruthy(process.env.CLAUDE_CODE_PROXY_RESOLVES_HOSTS)) {
- agentOptions.lookup = (hostname2, options2, callback) => {
- callback(null, hostname2, getAddressFamily(options2));
- };
- }
- return new import_https_proxy_agent.HttpsProxyAgent(proxyUrl, { ...agentOptions, ...extra });
-}
-function createAxiosInstance(extra = {}) {
- const proxyUrl = getProxyUrl();
- const mtlsAgent = getMTLSAgent();
- const instance = axios_default.create({ proxy: false });
- if (!proxyUrl) {
- if (mtlsAgent)
- instance.defaults.httpsAgent = mtlsAgent;
- return instance;
- }
- const proxyAgent = createHttpsProxyAgent(proxyUrl, extra);
- instance.interceptors.request.use((config3) => {
- if (config3.url && shouldBypassProxy(config3.url)) {
- config3.httpsAgent = mtlsAgent;
- config3.httpAgent = mtlsAgent;
- } else {
- config3.httpsAgent = proxyAgent;
- config3.httpAgent = proxyAgent;
- }
- return config3;
- });
- return instance;
-}
-function getWebSocketProxyAgent(url3) {
- const proxyUrl = getProxyUrl();
- if (!proxyUrl) {
- return;
- }
- if (shouldBypassProxy(url3)) {
- return;
- }
- return createHttpsProxyAgent(proxyUrl);
-}
-function getWebSocketProxyUrl(url3) {
- const proxyUrl = getProxyUrl();
- if (!proxyUrl) {
- return;
- }
- if (shouldBypassProxy(url3)) {
- return;
- }
- return proxyUrl;
-}
-function getProxyFetchOptions(opts) {
- const base2 = keepAliveDisabled ? { keepalive: false } : {};
- if (opts?.forAnthropicAPI) {
- const unixSocket = process.env.ANTHROPIC_UNIX_SOCKET;
- if (unixSocket && typeof Bun !== "undefined") {
- return { ...base2, unix: unixSocket };
- }
- }
- const proxyUrl = getProxyUrl();
- if (proxyUrl) {
- if (typeof Bun !== "undefined") {
- return { ...base2, proxy: proxyUrl, ...getTLSFetchOptions() };
- }
- return { ...base2, dispatcher: getProxyAgent(proxyUrl) };
- }
- return { ...base2, ...getTLSFetchOptions() };
-}
-function configureGlobalAgents() {
- const proxyUrl = getProxyUrl();
- const mtlsAgent = getMTLSAgent();
- if (proxyInterceptorId !== undefined) {
- axios_default.interceptors.request.eject(proxyInterceptorId);
- proxyInterceptorId = undefined;
- }
- axios_default.defaults.proxy = undefined;
- axios_default.defaults.httpAgent = undefined;
- axios_default.defaults.httpsAgent = undefined;
- if (proxyUrl) {
- axios_default.defaults.proxy = false;
- const proxyAgent = createHttpsProxyAgent(proxyUrl);
- proxyInterceptorId = axios_default.interceptors.request.use((config3) => {
- if (config3.url && shouldBypassProxy(config3.url)) {
- if (mtlsAgent) {
- config3.httpsAgent = mtlsAgent;
- config3.httpAgent = mtlsAgent;
- } else {
- delete config3.httpsAgent;
- delete config3.httpAgent;
- }
- } else {
- config3.httpsAgent = proxyAgent;
- config3.httpAgent = proxyAgent;
- }
- return config3;
- });
- __require("undici").setGlobalDispatcher(getProxyAgent(proxyUrl));
- } else if (mtlsAgent) {
- axios_default.defaults.httpsAgent = mtlsAgent;
- const mtlsOptions = getTLSFetchOptions();
- if (mtlsOptions.dispatcher) {
- __require("undici").setGlobalDispatcher(mtlsOptions.dispatcher);
- }
- }
-}
-async function getAWSClientProxyConfig() {
- const proxyUrl = getProxyUrl();
- if (!proxyUrl) {
- return {};
- }
- const [{ NodeHttpHandler: NodeHttpHandler2 }, { defaultProvider: defaultProvider3 }] = await Promise.all([
- Promise.resolve().then(() => __toESM(require_dist_cjs5(), 1)),
- Promise.resolve().then(() => (init_dist_es14(), exports_dist_es9))
- ]);
- const agent = createHttpsProxyAgent(proxyUrl);
- const requestHandler = new NodeHttpHandler2({
- httpAgent: agent,
- httpsAgent: agent
- });
- return {
- requestHandler,
- credentials: defaultProvider3({
- clientConfig: { requestHandler }
- })
- };
-}
-function clearProxyCache() {
- getProxyAgent.cache.clear?.();
- logForDebugging("Cleared proxy agent cache");
-}
-var import_https_proxy_agent, keepAliveDisabled = false, getProxyAgent, proxyInterceptorId;
-var init_proxy = __esm(() => {
- init_axios2();
- init_memoize();
- init_caCerts();
- init_debug();
- init_envUtils();
- init_mtls();
- import_https_proxy_agent = __toESM(require_dist2(), 1);
- getProxyAgent = memoize_default((uri2) => {
- const undiciMod = __require("undici");
- const mtlsConfig = getMTLSConfig();
- const caCerts = getCACertificates();
- const proxyOptions = {
- httpProxy: uri2,
- httpsProxy: uri2,
- noProxy: process.env.NO_PROXY || process.env.no_proxy
- };
- if (mtlsConfig || caCerts) {
- const tlsOpts = {
- ...mtlsConfig && {
- cert: mtlsConfig.cert,
- key: mtlsConfig.key,
- passphrase: mtlsConfig.passphrase
- },
- ...caCerts && { ca: caCerts }
- };
- proxyOptions.connect = tlsOpts;
- proxyOptions.requestTls = tlsOpts;
- }
- return new undiciMod.EnvHttpProxyAgent(proxyOptions);
- });
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/client.js
-class Client2 {
- config;
- middlewareStack = import_middleware_stack3.constructStack();
- initConfig;
- handlers;
- constructor(config3) {
- this.config = config3;
- const { protocol, protocolSettings } = config3;
- if (protocolSettings) {
- if (typeof protocol === "function") {
- config3.protocol = new protocol(protocolSettings);
- }
- }
- }
- send(command3, optionsOrCb, cb) {
- const options2 = typeof optionsOrCb !== "function" ? optionsOrCb : undefined;
- const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
- const useHandlerCache = options2 === undefined && this.config.cacheMiddleware === true;
- let handler;
- if (useHandlerCache) {
- if (!this.handlers) {
- this.handlers = new WeakMap;
- }
- const handlers = this.handlers;
- if (handlers.has(command3.constructor)) {
- handler = handlers.get(command3.constructor);
- } else {
- handler = command3.resolveMiddleware(this.middlewareStack, this.config, options2);
- handlers.set(command3.constructor, handler);
- }
- } else {
- delete this.handlers;
- handler = command3.resolveMiddleware(this.middlewareStack, this.config, options2);
- }
- if (callback) {
- handler(command3).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => {});
- } else {
- return handler(command3).then((result) => result.output);
- }
- }
- destroy() {
- this.config?.requestHandler?.destroy?.();
- delete this.handlers;
- }
-}
-var import_middleware_stack3;
-var init_client3 = __esm(() => {
- import_middleware_stack3 = __toESM(require_dist_cjs12(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js
-var import_protocols4;
-var init_collect_stream_body2 = __esm(() => {
- import_protocols4 = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/abort.js
-var init_abort3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/auth/auth.js
-var HttpAuthLocation2;
-var init_auth3 = __esm(() => {
- (function(HttpAuthLocation3) {
- HttpAuthLocation3["HEADER"] = "header";
- HttpAuthLocation3["QUERY"] = "query";
- })(HttpAuthLocation2 || (HttpAuthLocation2 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
-var HttpApiKeyAuthLocation2;
-var init_HttpApiKeyAuth2 = __esm(() => {
- (function(HttpApiKeyAuthLocation3) {
- HttpApiKeyAuthLocation3["HEADER"] = "header";
- HttpApiKeyAuthLocation3["QUERY"] = "query";
- })(HttpApiKeyAuthLocation2 || (HttpApiKeyAuthLocation2 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js
-var init_HttpAuthScheme2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js
-var init_HttpAuthSchemeProvider2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/auth/HttpSigner.js
-var init_HttpSigner2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js
-var init_IdentityProviderConfig2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/auth/index.js
-var init_auth4 = __esm(() => {
- init_auth3();
- init_HttpApiKeyAuth2();
- init_HttpAuthScheme2();
- init_HttpAuthSchemeProvider2();
- init_HttpSigner2();
- init_IdentityProviderConfig2();
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js
-var init_blob_payload_input_types2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/checksum.js
-var init_checksum4 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/client.js
-var init_client4 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/command.js
-var init_command5 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/connection/config.js
-var init_config3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/connection/manager.js
-var init_manager2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/connection/pool.js
-var init_pool2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/connection/index.js
-var init_connection2 = __esm(() => {
- init_config3();
- init_manager2();
- init_pool2();
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/crypto.js
-var init_crypto3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/encode.js
-var init_encode2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/endpoint.js
-var EndpointURLScheme2;
-var init_endpoint2 = __esm(() => {
- (function(EndpointURLScheme3) {
- EndpointURLScheme3["HTTP"] = "http";
- EndpointURLScheme3["HTTPS"] = "https";
- })(EndpointURLScheme2 || (EndpointURLScheme2 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js
-var init_EndpointRuleObject2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js
-var init_ErrorRuleObject2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js
-var init_RuleSetObject2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/endpoints/shared.js
-var init_shared4 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js
-var init_TreeRuleObject2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/endpoints/index.js
-var init_endpoints2 = __esm(() => {
- init_EndpointRuleObject2();
- init_ErrorRuleObject2();
- init_RuleSetObject2();
- init_shared4();
- init_TreeRuleObject2();
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/eventStream.js
-var init_eventStream2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/extensions/checksum.js
-var AlgorithmId2;
-var init_checksum5 = __esm(() => {
- (function(AlgorithmId3) {
- AlgorithmId3["MD5"] = "md5";
- AlgorithmId3["CRC32"] = "crc32";
- AlgorithmId3["CRC32C"] = "crc32c";
- AlgorithmId3["SHA1"] = "sha1";
- AlgorithmId3["SHA256"] = "sha256";
- })(AlgorithmId2 || (AlgorithmId2 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js
-var init_defaultClientConfiguration2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js
-var init_defaultExtensionConfiguration3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/extensions/index.js
-var init_extensions5 = __esm(() => {
- init_checksum5();
- init_defaultClientConfiguration2();
- init_defaultExtensionConfiguration3();
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/feature-ids.js
-var init_feature_ids2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/http.js
-var FieldPosition2;
-var init_http3 = __esm(() => {
- (function(FieldPosition3) {
- FieldPosition3[FieldPosition3["HEADER"] = 0] = "HEADER";
- FieldPosition3[FieldPosition3["TRAILER"] = 1] = "TRAILER";
- })(FieldPosition2 || (FieldPosition2 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js
-var init_httpHandlerInitialization2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js
-var init_apiKeyIdentity2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js
-var init_awsCredentialIdentity2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/identity/identity.js
-var init_identity4 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js
-var init_tokenIdentity2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/identity/index.js
-var init_identity5 = __esm(() => {
- init_apiKeyIdentity2();
- init_awsCredentialIdentity2();
- init_identity4();
- init_tokenIdentity2();
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/logger.js
-var init_logger2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/middleware.js
-var SMITHY_CONTEXT_KEY2 = "__smithy_context";
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/pagination.js
-var init_pagination3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/profile.js
-var IniSectionType2;
-var init_profile2 = __esm(() => {
- (function(IniSectionType3) {
- IniSectionType3["PROFILE"] = "profile";
- IniSectionType3["SSO_SESSION"] = "sso-session";
- IniSectionType3["SERVICES"] = "services";
- })(IniSectionType2 || (IniSectionType2 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/response.js
-var init_response2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/retry.js
-var init_retry2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/schema/schema.js
-var init_schema2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/schema/traits.js
-var init_traits2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/schema/schema-deprecated.js
-var init_schema_deprecated2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/schema/sentinels.js
-var init_sentinels2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/schema/static-schemas.js
-var init_static_schemas2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/serde.js
-var init_serde2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/shapes.js
-var init_shapes2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/signature.js
-var init_signature2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/stream.js
-var init_stream3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js
-var init_streaming_blob_common_types2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js
-var init_streaming_blob_payload_input_types2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js
-var init_streaming_blob_payload_output_types2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/transfer.js
-var RequestHandlerProtocol2;
-var init_transfer2 = __esm(() => {
- (function(RequestHandlerProtocol3) {
- RequestHandlerProtocol3["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol3["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol3["TDS_8_0"] = "tds/8.0";
- })(RequestHandlerProtocol2 || (RequestHandlerProtocol2 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js
-var init_client_payload_blob_type_narrow2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/transform/mutable.js
-var init_mutable2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/transform/no-undefined.js
-var init_no_undefined2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/transform/type-transform.js
-var init_type_transform2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/uri.js
-var init_uri2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/util.js
-var init_util4 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/waiter.js
-var init_waiter2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-es/index.js
-var init_dist_es15 = __esm(() => {
- init_abort3();
- init_auth4();
- init_blob_payload_input_types2();
- init_checksum4();
- init_client4();
- init_command5();
- init_connection2();
- init_crypto3();
- init_encode2();
- init_endpoint2();
- init_endpoints2();
- init_eventStream2();
- init_extensions5();
- init_feature_ids2();
- init_http3();
- init_httpHandlerInitialization2();
- init_identity5();
- init_logger2();
- init_pagination3();
- init_profile2();
- init_response2();
- init_retry2();
- init_schema2();
- init_traits2();
- init_schema_deprecated2();
- init_sentinels2();
- init_static_schemas2();
- init_serde2();
- init_shapes2();
- init_signature2();
- init_stream3();
- init_streaming_blob_common_types2();
- init_streaming_blob_payload_input_types2();
- init_streaming_blob_payload_output_types2();
- init_transfer2();
- init_client_payload_blob_type_narrow2();
- init_mutable2();
- init_no_undefined2();
- init_type_transform2();
- init_uri2();
- init_util4();
- init_waiter2();
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/schemaLogFilter.js
-function schemaLogFilter2(schema3, data) {
- if (data == null) {
- return data;
- }
- const ns = import_schema2.NormalizedSchema.of(schema3);
- if (ns.getMergedTraits().sensitive) {
- return SENSITIVE_STRING3;
- }
- if (ns.isListSchema()) {
- const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING3;
- }
- } else if (ns.isMapSchema()) {
- const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING3;
- }
- } else if (ns.isStructSchema() && typeof data === "object") {
- const object2 = data;
- const newObject = {};
- for (const [member, memberNs] of ns.structIterator()) {
- if (object2[member] != null) {
- newObject[member] = schemaLogFilter2(memberNs, object2[member]);
- }
- }
- return newObject;
- }
- return data;
-}
-var import_schema2, SENSITIVE_STRING3 = "***SensitiveInformation***";
-var init_schemaLogFilter2 = __esm(() => {
- import_schema2 = __toESM(require_schema(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/command.js
-class Command3 {
- middlewareStack = import_middleware_stack4.constructStack();
- schema;
- static classBuilder() {
- return new ClassBuilder2;
- }
- resolveMiddlewareWithContext(clientStack, configuration, options2, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
- for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options2)) {
- this.middlewareStack.use(mw);
- }
- const stack = clientStack.concat(this.middlewareStack);
- const { logger: logger3 } = configuration;
- const handlerExecutionContext = {
- logger: logger3,
- clientName,
- commandName,
- inputFilterSensitiveLog,
- outputFilterSensitiveLog,
- [SMITHY_CONTEXT_KEY2]: {
- commandInstance: this,
- ...smithyContext
- },
- ...additionalContext
- };
- const { requestHandler } = configuration;
- return stack.resolve((request2) => requestHandler.handle(request2.request, options2 || {}), handlerExecutionContext);
- }
-}
-
-class ClassBuilder2 {
- _init = () => {};
- _ep = {};
- _middlewareFn = () => [];
- _commandName = "";
- _clientName = "";
- _additionalContext = {};
- _smithyContext = {};
- _inputFilterSensitiveLog = undefined;
- _outputFilterSensitiveLog = undefined;
- _serializer = null;
- _deserializer = null;
- _operationSchema;
- init(cb) {
- this._init = cb;
- }
- ep(endpointParameterInstructions) {
- this._ep = endpointParameterInstructions;
- return this;
- }
- m(middlewareSupplier) {
- this._middlewareFn = middlewareSupplier;
- return this;
- }
- s(service, operation, smithyContext = {}) {
- this._smithyContext = {
- service,
- operation,
- ...smithyContext
- };
- return this;
- }
- c(additionalContext = {}) {
- this._additionalContext = additionalContext;
- return this;
- }
- n(clientName, commandName) {
- this._clientName = clientName;
- this._commandName = commandName;
- return this;
- }
- f(inputFilter = (_) => _, outputFilter = (_) => _) {
- this._inputFilterSensitiveLog = inputFilter;
- this._outputFilterSensitiveLog = outputFilter;
- return this;
- }
- ser(serializer) {
- this._serializer = serializer;
- return this;
- }
- de(deserializer) {
- this._deserializer = deserializer;
- return this;
- }
- sc(operation) {
- this._operationSchema = operation;
- this._smithyContext.operationSchema = operation;
- return this;
- }
- build() {
- const closure = this;
- let CommandRef;
- return CommandRef = class extends Command3 {
- input;
- static getEndpointParameterInstructions() {
- return closure._ep;
- }
- constructor(...[input]) {
- super();
- this.input = input ?? {};
- closure._init(this);
- this.schema = closure._operationSchema;
- }
- resolveMiddleware(stack, configuration, options2) {
- const op = closure._operationSchema;
- const input = op?.[4] ?? op?.input;
- const output = op?.[5] ?? op?.output;
- return this.resolveMiddlewareWithContext(stack, configuration, options2, {
- CommandCtor: CommandRef,
- middlewareFn: closure._middlewareFn,
- clientName: closure._clientName,
- commandName: closure._commandName,
- inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter2.bind(null, input) : (_) => _),
- outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter2.bind(null, output) : (_) => _),
- smithyContext: closure._smithyContext,
- additionalContext: closure._additionalContext
- });
- }
- serialize = closure._serializer;
- deserialize = closure._deserializer;
- };
- }
-}
-var import_middleware_stack4;
-var init_command6 = __esm(() => {
- init_dist_es15();
- init_schemaLogFilter2();
- import_middleware_stack4 = __toESM(require_dist_cjs12(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/constants.js
-var SENSITIVE_STRING4 = "***SensitiveInformation***";
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js
-var createAggregatedClient2 = (commands, Client3, options2) => {
- for (const [command4, CommandCtor] of Object.entries(commands)) {
- const methodImpl = async function(args, optionsOrCb, cb) {
- const command5 = new CommandCtor(args);
- if (typeof optionsOrCb === "function") {
- this.send(command5, optionsOrCb);
- } else if (typeof cb === "function") {
- if (typeof optionsOrCb !== "object")
- throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
- this.send(command5, optionsOrCb || {}, cb);
- } else {
- return this.send(command5, optionsOrCb);
- }
- };
- const methodName = (command4[0].toLowerCase() + command4.slice(1)).replace(/Command$/, "");
- Client3.prototype[methodName] = methodImpl;
- }
- const { paginators = {}, waiters = {} } = options2 ?? {};
- for (const [paginatorName, paginatorFn] of Object.entries(paginators)) {
- if (Client3.prototype[paginatorName] === undefined) {
- Client3.prototype[paginatorName] = function(commandInput = {}, paginationConfiguration, ...rest) {
- return paginatorFn({
- ...paginationConfiguration,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
- for (const [waiterName, waiterFn] of Object.entries(waiters)) {
- if (Client3.prototype[waiterName] === undefined) {
- Client3.prototype[waiterName] = async function(commandInput = {}, waiterConfiguration, ...rest) {
- let config4 = waiterConfiguration;
- if (typeof waiterConfiguration === "number") {
- config4 = {
- maxWaitTime: waiterConfiguration
- };
- }
- return waiterFn({
- ...config4,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
-};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/exceptions.js
-var ServiceException2, decorateServiceException2 = (exception, additions = {}) => {
- Object.entries(additions).filter(([, v]) => v !== undefined).forEach(([k, v]) => {
- if (exception[k] == undefined || exception[k] === "") {
- exception[k] = v;
- }
- });
- const message = exception.message || exception.Message || "UnknownError";
- exception.message = message;
- delete exception.Message;
- return exception;
-};
-var init_exceptions2 = __esm(() => {
- ServiceException2 = class ServiceException2 extends Error {
- $fault;
- $response;
- $retryable;
- $metadata;
- constructor(options2) {
- super(options2.message);
- Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
- this.name = options2.name;
- this.$fault = options2.$fault;
- this.$metadata = options2.$metadata;
- }
- static isInstance(value) {
- if (!value)
- return false;
- const candidate = value;
- return ServiceException2.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
- }
- static [Symbol.hasInstance](instance) {
- if (!instance)
- return false;
- const candidate = instance;
- if (this === ServiceException2) {
- return ServiceException2.isInstance(instance);
- }
- if (ServiceException2.isInstance(instance)) {
- if (candidate.name && this.name) {
- return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
- }
- return this.prototype.isPrototypeOf(instance);
- }
- return false;
- }
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js
-var throwDefaultError2 = ({ output, parsedBody, exceptionCtor, errorCode }) => {
- const $metadata = deserializeMetadata2(output);
- const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined;
- const response3 = new exceptionCtor({
- name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
- $fault: "client",
- $metadata
- });
- throw decorateServiceException2(response3, parsedBody);
-}, withBaseException2 = (ExceptionCtor) => {
- return ({ output, parsedBody, errorCode }) => {
- throwDefaultError2({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
- };
-}, deserializeMetadata2 = (output) => ({
- httpStatusCode: output.statusCode,
- requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
- extendedRequestId: output.headers["x-amz-id-2"],
- cfId: output.headers["x-amz-cf-id"]
-});
-var init_default_error_handler2 = __esm(() => {
- init_exceptions2();
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js
-var loadConfigsForDefaultMode2 = (mode) => {
- switch (mode) {
- case "standard":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "in-region":
- return {
- retryMode: "standard",
- connectionTimeout: 1100
- };
- case "cross-region":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "mobile":
- return {
- retryMode: "standard",
- connectionTimeout: 30000
- };
- default:
- return {};
- }
-};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js
-var warningEmitted2 = false, emitWarningIfUnsupportedVersion3 = (version2) => {
- if (version2 && !warningEmitted2 && parseInt(version2.substring(1, version2.indexOf("."))) < 16) {
- warningEmitted2 = true;
- }
-};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js
-var import_protocols5;
-var init_extended_encode_uri_component2 = __esm(() => {
- import_protocols5 = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js
-var knownAlgorithms2, getChecksumConfiguration2 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- for (const id in AlgorithmId2) {
- const algorithmId = AlgorithmId2[id];
- if (runtimeConfig[algorithmId] === undefined) {
- continue;
- }
- checksumAlgorithms.push({
- algorithmId: () => algorithmId,
- checksumConstructor: () => runtimeConfig[algorithmId]
- });
- }
- for (const [id, ChecksumCtor] of Object.entries(runtimeConfig.checksumAlgorithms ?? {})) {
- checksumAlgorithms.push({
- algorithmId: () => id,
- checksumConstructor: () => ChecksumCtor
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- runtimeConfig.checksumAlgorithms = runtimeConfig.checksumAlgorithms ?? {};
- const id = algo.algorithmId();
- const ctor = algo.checksumConstructor();
- if (knownAlgorithms2.includes(id)) {
- runtimeConfig.checksumAlgorithms[id.toUpperCase()] = ctor;
- } else {
- runtimeConfig.checksumAlgorithms[id] = ctor;
- }
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
-}, resolveChecksumRuntimeConfig2 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- const id = checksumAlgorithm.algorithmId();
- if (knownAlgorithms2.includes(id)) {
- runtimeConfig[id] = checksumAlgorithm.checksumConstructor();
- }
- });
- return runtimeConfig;
-};
-var init_checksum6 = __esm(() => {
- init_dist_es15();
- knownAlgorithms2 = Object.values(AlgorithmId2);
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js
-var getRetryConfiguration2 = (runtimeConfig) => {
- return {
- setRetryStrategy(retryStrategy) {
- runtimeConfig.retryStrategy = retryStrategy;
- },
- retryStrategy() {
- return runtimeConfig.retryStrategy;
- }
- };
-}, resolveRetryRuntimeConfig2 = (retryStrategyConfiguration) => {
- const runtimeConfig = {};
- runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
- return runtimeConfig;
-};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js
-var getDefaultExtensionConfiguration2 = (runtimeConfig) => {
- return Object.assign(getChecksumConfiguration2(runtimeConfig), getRetryConfiguration2(runtimeConfig));
-}, getDefaultClientConfiguration2, resolveDefaultRuntimeConfig2 = (config4) => {
- return Object.assign(resolveChecksumRuntimeConfig2(config4), resolveRetryRuntimeConfig2(config4));
-};
-var init_defaultExtensionConfiguration4 = __esm(() => {
- init_checksum6();
- getDefaultClientConfiguration2 = getDefaultExtensionConfiguration2;
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/extensions/index.js
-var init_extensions6 = __esm(() => {
- init_defaultExtensionConfiguration4();
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js
-var getArrayIfSingleItem2 = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray];
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js
-var getValueFromTextNode2 = (obj) => {
- const textNodeName = "#text";
- for (const key in obj) {
- if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) {
- obj[key] = obj[key][textNodeName];
- } else if (typeof obj[key] === "object" && obj[key] !== null) {
- obj[key] = getValueFromTextNode2(obj[key]);
- }
- }
- return obj;
-};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js
-var isSerializableHeaderValue2 = (value) => {
- return value != null;
-};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js
-class NoOpLogger3 {
- trace() {}
- debug() {}
- info() {}
- warn() {}
- error() {}
-}
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/object-mapping.js
-function map3(arg0, arg1, arg2) {
- let target;
- let filter2;
- let instructions;
- if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
- target = {};
- instructions = arg0;
- } else {
- target = arg0;
- if (typeof arg1 === "function") {
- filter2 = arg1;
- instructions = arg2;
- return mapWithFilter2(target, filter2, instructions);
- } else {
- instructions = arg1;
- }
- }
- for (const key of Object.keys(instructions)) {
- if (!Array.isArray(instructions[key])) {
- target[key] = instructions[key];
- continue;
- }
- applyInstruction2(target, null, instructions, key);
- }
- return target;
-}
-var convertMap2 = (target) => {
- const output = {};
- for (const [k, v] of Object.entries(target || {})) {
- output[k] = [, v];
- }
- return output;
-}, take2 = (source, instructions) => {
- const out = {};
- for (const key in instructions) {
- applyInstruction2(out, source, instructions, key);
- }
- return out;
-}, mapWithFilter2 = (target, filter2, instructions) => {
- return map3(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
- if (Array.isArray(value)) {
- _instructions[key] = value;
- } else {
- if (typeof value === "function") {
- _instructions[key] = [filter2, value()];
- } else {
- _instructions[key] = [filter2, value];
- }
- }
- return _instructions;
- }, {}));
-}, applyInstruction2 = (target, source, instructions, targetKey) => {
- if (source !== null) {
- let instruction = instructions[targetKey];
- if (typeof instruction === "function") {
- instruction = [, instruction];
- }
- const [filter3 = nonNullish2, valueFn = pass2, sourceKey = targetKey] = instruction;
- if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) {
- target[targetKey] = valueFn(source[sourceKey]);
- }
- return;
- }
- let [filter2, value] = instructions[targetKey];
- if (typeof value === "function") {
- let _value;
- const defaultFilterPassed = filter2 === undefined && (_value = value()) != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(undefined) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed) {
- target[targetKey] = _value;
- } else if (customFilterPassed) {
- target[targetKey] = value();
- }
- } else {
- const defaultFilterPassed = filter2 === undefined && value != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed || customFilterPassed) {
- target[targetKey] = value;
- }
- }
-}, nonNullish2 = (_) => _ != null, pass2 = (_) => _;
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/resolve-path.js
-var import_protocols6;
-var init_resolve_path2 = __esm(() => {
- import_protocols6 = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/ser-utils.js
-var serializeFloat2 = (value) => {
- if (value !== value) {
- return "NaN";
- }
- switch (value) {
- case Infinity:
- return "Infinity";
- case -Infinity:
- return "-Infinity";
- default:
- return value;
- }
-}, serializeDateTime2 = (date5) => date5.toISOString().replace(".000Z", "Z");
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/serde-json.js
-var _json2 = (obj) => {
- if (obj == null) {
- return {};
- }
- if (Array.isArray(obj)) {
- return obj.filter((_) => _ != null).map(_json2);
- }
- if (typeof obj === "object") {
- const target = {};
- for (const key of Object.keys(obj)) {
- if (obj[key] == null) {
- continue;
- }
- target[key] = _json2(obj[key]);
- }
- return target;
- }
- return obj;
-};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-es/index.js
-var exports_dist_es10 = {};
-__export(exports_dist_es10, {
- withBaseException: () => withBaseException2,
- throwDefaultError: () => throwDefaultError2,
- take: () => take2,
- serializeFloat: () => serializeFloat2,
- serializeDateTime: () => serializeDateTime2,
- resolvedPath: () => import_protocols6.resolvedPath,
- resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig2,
- map: () => map3,
- loadConfigsForDefaultMode: () => loadConfigsForDefaultMode2,
- isSerializableHeaderValue: () => isSerializableHeaderValue2,
- getValueFromTextNode: () => getValueFromTextNode2,
- getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration2,
- getDefaultClientConfiguration: () => getDefaultClientConfiguration2,
- getArrayIfSingleItem: () => getArrayIfSingleItem2,
- extendedEncodeURIComponent: () => import_protocols5.extendedEncodeURIComponent,
- emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion3,
- decorateServiceException: () => decorateServiceException2,
- createAggregatedClient: () => createAggregatedClient2,
- convertMap: () => convertMap2,
- collectBody: () => import_protocols4.collectBody,
- _json: () => _json2,
- ServiceException: () => ServiceException2,
- SENSITIVE_STRING: () => SENSITIVE_STRING4,
- NoOpLogger: () => NoOpLogger3,
- Command: () => Command3,
- Client: () => Client2
-});
-var init_dist_es16 = __esm(() => {
- init_client3();
- init_collect_stream_body2();
- init_command6();
- init_default_error_handler2();
- init_exceptions2();
- init_extended_encode_uri_component2();
- init_extensions6();
- init_resolve_path2();
- __reExport(exports_dist_es10, __toESM(require_serde(), 1));
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/auth/httpAuthSchemeProvider.js
-function createAwsAuthSigv4HttpAuthOption(authParameters) {
- return {
- schemeId: "aws.auth#sigv4",
- signingProperties: {
- name: "bedrock",
- region: authParameters.region
- },
- propertiesExtractor: (config4, context) => ({
- signingProperties: {
- config: config4,
- context
- }
- })
- };
-}
-function createSmithyApiHttpBearerAuthHttpAuthOption(authParameters) {
- return {
- schemeId: "smithy.api#httpBearerAuth",
- propertiesExtractor: ({ profile: profile3, filepath, configFilepath, ignoreCache }, context) => ({
- identityProperties: {
- profile: profile3,
- filepath,
- configFilepath,
- ignoreCache
- }
- })
- };
-}
-var import_httpAuthSchemes2, import_core17, import_util_middleware, defaultBedrockHttpAuthSchemeParametersProvider = async (config4, context, input) => {
- return {
- operation: import_util_middleware.getSmithyContext(context).operation,
- region: await import_util_middleware.normalizeProvider(config4.region)() || (() => {
- throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
- })()
- };
-}, defaultBedrockHttpAuthSchemeProvider = (authParameters) => {
- const options2 = [];
- switch (authParameters.operation) {
- default: {
- options2.push(createAwsAuthSigv4HttpAuthOption(authParameters));
- options2.push(createSmithyApiHttpBearerAuthHttpAuthOption(authParameters));
- }
- }
- return options2;
-}, resolveHttpAuthSchemeConfig = (config4) => {
- const token = import_core17.memoizeIdentityProvider(config4.token, import_core17.isIdentityExpired, import_core17.doesIdentityRequireRefresh);
- const config_0 = import_httpAuthSchemes2.resolveAwsSdkSigV4Config(config4);
- return Object.assign(config_0, {
- authSchemePreference: import_util_middleware.normalizeProvider(config4.authSchemePreference ?? []),
- token
- });
-};
-var init_httpAuthSchemeProvider = __esm(() => {
- import_httpAuthSchemes2 = __toESM(require_httpAuthSchemes(), 1);
- import_core17 = __toESM(require_dist_cjs37(), 1);
- import_util_middleware = __toESM(require_dist_cjs30(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/endpoint/EndpointParameters.js
-var resolveClientEndpointParameters = (options2) => {
- return Object.assign(options2, {
- useDualstackEndpoint: options2.useDualstackEndpoint ?? false,
- useFipsEndpoint: options2.useFipsEndpoint ?? false,
- defaultSigningName: "bedrock"
- });
-}, commonParams;
-var init_EndpointParameters = __esm(() => {
- commonParams = {
- UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
- Endpoint: { type: "builtInParams", name: "endpoint" },
- Region: { type: "builtInParams", name: "region" },
- UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/package.json
-var package_default;
-var init_package = __esm(() => {
- package_default = {
- name: "@aws-sdk/client-bedrock",
- description: "AWS SDK for JavaScript Bedrock Client for Node.js, Browser and React Native",
- version: "3.1020.0",
- scripts: {
- build: "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs",
- "build:cjs": "node ../../scripts/compilation/inline client-bedrock",
- "build:es": "tsc -p tsconfig.es.json",
- "build:include:deps": 'yarn g:turbo run build -F="$npm_package_name"',
- "build:types": "tsc -p tsconfig.types.json",
- "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
- clean: "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",
- "extract:docs": "api-extractor run --local",
- "generate:client": "node ../../scripts/generate-clients/single-service --solo bedrock",
- "test:index": "tsc --noEmit ./test/index-types.ts && node ./test/index-objects.spec.mjs"
- },
- main: "./dist-cjs/index.js",
- types: "./dist-types/index.d.ts",
- module: "./dist-es/index.js",
- sideEffects: false,
- dependencies: {
- "@aws-crypto/sha256-browser": "5.2.0",
- "@aws-crypto/sha256-js": "5.2.0",
- "@aws-sdk/core": "^3.973.26",
- "@aws-sdk/credential-provider-node": "^3.972.28",
- "@aws-sdk/middleware-host-header": "^3.972.8",
- "@aws-sdk/middleware-logger": "^3.972.8",
- "@aws-sdk/middleware-recursion-detection": "^3.972.9",
- "@aws-sdk/middleware-user-agent": "^3.972.27",
- "@aws-sdk/region-config-resolver": "^3.972.10",
- "@aws-sdk/token-providers": "3.1020.0",
- "@aws-sdk/types": "^3.973.6",
- "@aws-sdk/util-endpoints": "^3.996.5",
- "@aws-sdk/util-user-agent-browser": "^3.972.8",
- "@aws-sdk/util-user-agent-node": "^3.973.13",
- "@smithy/config-resolver": "^4.4.13",
- "@smithy/core": "^3.23.13",
- "@smithy/fetch-http-handler": "^5.3.15",
- "@smithy/hash-node": "^4.2.12",
- "@smithy/invalid-dependency": "^4.2.12",
- "@smithy/middleware-content-length": "^4.2.12",
- "@smithy/middleware-endpoint": "^4.4.28",
- "@smithy/middleware-retry": "^4.4.45",
- "@smithy/middleware-serde": "^4.2.16",
- "@smithy/middleware-stack": "^4.2.12",
- "@smithy/node-config-provider": "^4.3.12",
- "@smithy/node-http-handler": "^4.5.1",
- "@smithy/protocol-http": "^5.3.12",
- "@smithy/smithy-client": "^4.12.8",
- "@smithy/types": "^4.13.1",
- "@smithy/url-parser": "^4.2.12",
- "@smithy/util-base64": "^4.3.2",
- "@smithy/util-body-length-browser": "^4.2.2",
- "@smithy/util-body-length-node": "^4.2.3",
- "@smithy/util-defaults-mode-browser": "^4.3.44",
- "@smithy/util-defaults-mode-node": "^4.2.48",
- "@smithy/util-endpoints": "^3.3.3",
- "@smithy/util-middleware": "^4.2.12",
- "@smithy/util-retry": "^4.2.12",
- "@smithy/util-utf8": "^4.2.2",
- tslib: "^2.6.2"
- },
- devDependencies: {
- "@tsconfig/node20": "20.1.8",
- "@types/node": "^20.14.8",
- concurrently: "7.0.0",
- "downlevel-dts": "0.10.1",
- premove: "4.0.0",
- typescript: "~5.8.3"
- },
- engines: {
- node: ">=20.0.0"
- },
- typesVersions: {
- "<4.5": {
- "dist-types/*": [
- "dist-types/ts3.4/*"
- ]
- }
- },
- files: [
- "dist-*/**"
- ],
- author: {
- name: "AWS SDK for JavaScript Team",
- url: "https://aws.amazon.com/javascript/"
- },
- license: "Apache-2.0",
- browser: {
- "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
- },
- "react-native": {
- "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
- },
- homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-bedrock",
- repository: {
- type: "git",
- url: "https://github.com/aws/aws-sdk-js-v3.git",
- directory: "clients/client-bedrock"
- }
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-es/index.js
-var isArrayBuffer3 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-es/index.js
-import { Buffer as Buffer8 } from "buffer";
-var fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
- if (!isArrayBuffer3(input)) {
- throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
- }
- return Buffer8.from(input, offset, length);
-}, fromString = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? Buffer8.from(input, encoding) : Buffer8.from(input);
-};
-var init_dist_es17 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-es/fromBase64.js
-var BASE64_REGEX, fromBase64 = (input) => {
- if (input.length * 3 % 4 !== 0) {
- throw new TypeError(`Incorrect padding on base64 string.`);
- }
- if (!BASE64_REGEX.exec(input)) {
- throw new TypeError(`Invalid base64 string.`);
- }
- const buffer = fromString(input, "base64");
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
-};
-var init_fromBase64 = __esm(() => {
- init_dist_es17();
- BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-es/toBase64.js
-var import_util_utf8, toBase64 = (_input) => {
- let input;
- if (typeof _input === "string") {
- input = import_util_utf8.fromUtf8(_input);
- } else {
- input = _input;
- }
- if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
- throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
- }
- return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("base64");
-};
-var init_toBase64 = __esm(() => {
- init_dist_es17();
- import_util_utf8 = __toESM(require_dist_cjs17(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-es/index.js
-var init_dist_es18 = __esm(() => {
- init_fromBase64();
- init_toBase64();
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/endpoint/ruleset.js
-var s = "required", t = "fn", u2 = "argv", v = "ref", a2 = true, b = "isSet", c5 = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h2, i2, j, k, l, m, n2, o2, p, q, r, _data, ruleSet;
-var init_ruleset = __esm(() => {
- h2 = { [s]: false, type: "string" };
- i2 = { [s]: true, default: false, type: "boolean" };
- j = { [v]: "Endpoint" };
- k = { [t]: c5, [u2]: [{ [v]: "UseFIPS" }, true] };
- l = { [t]: c5, [u2]: [{ [v]: "UseDualStack" }, true] };
- m = {};
- n2 = { [t]: "getAttr", [u2]: [{ [v]: g }, "supportsFIPS"] };
- o2 = { [t]: c5, [u2]: [true, { [t]: "getAttr", [u2]: [{ [v]: g }, "supportsDualStack"] }] };
- p = [k];
- q = [l];
- r = [{ [v]: "Region" }];
- _data = { version: "1.0", parameters: { Region: h2, UseDualStack: i2, UseFIPS: i2, Endpoint: h2 }, rules: [{ conditions: [{ [t]: b, [u2]: [j] }], rules: [{ conditions: p, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { rules: [{ conditions: q, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: j, properties: m, headers: m }, type: e }], type: f }], type: f }, { rules: [{ conditions: [{ [t]: b, [u2]: r }], rules: [{ conditions: [{ [t]: "aws.partition", [u2]: r, assign: g }], rules: [{ conditions: [k, l], rules: [{ conditions: [{ [t]: c5, [u2]: [a2, n2] }, o2], rules: [{ rules: [{ endpoint: { url: "https://bedrock-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: p, rules: [{ conditions: [{ [t]: c5, [u2]: [n2, a2] }], rules: [{ rules: [{ endpoint: { url: "https://bedrock-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: q, rules: [{ conditions: [o2], rules: [{ rules: [{ endpoint: { url: "https://bedrock.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { rules: [{ endpoint: { url: "https://bedrock.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }], type: f }] };
- ruleSet = _data;
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/endpoint/endpointResolver.js
-var import_util_endpoints, import_util_endpoints2, cache2, defaultEndpointResolver = (endpointParams, context = {}) => {
- return cache2.get(endpointParams, () => import_util_endpoints2.resolveEndpoint(ruleSet, {
- endpointParams,
- logger: context.logger
- }));
-};
-var init_endpointResolver = __esm(() => {
- init_ruleset();
- import_util_endpoints = __toESM(require_dist_cjs51(), 1);
- import_util_endpoints2 = __toESM(require_dist_cjs50(), 1);
- cache2 = new import_util_endpoints2.EndpointCache({
- size: 50,
- params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
- });
- import_util_endpoints2.customEndpointFunctions.aws = import_util_endpoints.awsEndpointFunctions;
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/models/BedrockServiceException.js
-var BedrockServiceException;
-var init_BedrockServiceException = __esm(() => {
- init_dist_es16();
- BedrockServiceException = class BedrockServiceException extends ServiceException2 {
- constructor(options2) {
- super(options2);
- Object.setPrototypeOf(this, BedrockServiceException.prototype);
- }
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/models/errors.js
-var AccessDeniedException, InternalServerException, ResourceNotFoundException, ThrottlingException, ValidationException, ConflictException, ServiceQuotaExceededException, TooManyTagsException, ResourceInUseException, ServiceUnavailableException;
-var init_errors4 = __esm(() => {
- init_BedrockServiceException();
- AccessDeniedException = class AccessDeniedException extends BedrockServiceException {
- name = "AccessDeniedException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "AccessDeniedException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, AccessDeniedException.prototype);
- }
- };
- InternalServerException = class InternalServerException extends BedrockServiceException {
- name = "InternalServerException";
- $fault = "server";
- constructor(opts) {
- super({
- name: "InternalServerException",
- $fault: "server",
- ...opts
- });
- Object.setPrototypeOf(this, InternalServerException.prototype);
- }
- };
- ResourceNotFoundException = class ResourceNotFoundException extends BedrockServiceException {
- name = "ResourceNotFoundException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ResourceNotFoundException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ResourceNotFoundException.prototype);
- }
- };
- ThrottlingException = class ThrottlingException extends BedrockServiceException {
- name = "ThrottlingException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ThrottlingException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ThrottlingException.prototype);
- }
- };
- ValidationException = class ValidationException extends BedrockServiceException {
- name = "ValidationException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ValidationException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ValidationException.prototype);
- }
- };
- ConflictException = class ConflictException extends BedrockServiceException {
- name = "ConflictException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ConflictException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ConflictException.prototype);
- }
- };
- ServiceQuotaExceededException = class ServiceQuotaExceededException extends BedrockServiceException {
- name = "ServiceQuotaExceededException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ServiceQuotaExceededException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ServiceQuotaExceededException.prototype);
- }
- };
- TooManyTagsException = class TooManyTagsException extends BedrockServiceException {
- name = "TooManyTagsException";
- $fault = "client";
- resourceName;
- constructor(opts) {
- super({
- name: "TooManyTagsException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, TooManyTagsException.prototype);
- this.resourceName = opts.resourceName;
- }
- };
- ResourceInUseException = class ResourceInUseException extends BedrockServiceException {
- name = "ResourceInUseException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ResourceInUseException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ResourceInUseException.prototype);
- }
- };
- ServiceUnavailableException = class ServiceUnavailableException extends BedrockServiceException {
- name = "ServiceUnavailableException";
- $fault = "server";
- constructor(opts) {
- super({
- name: "ServiceUnavailableException",
- $fault: "server",
- ...opts
- });
- Object.setPrototypeOf(this, ServiceUnavailableException.prototype);
- }
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/schemas/schemas_0.js
-var import_schema3, _AA = "AgreementAvailability", _ADE = "AccessDeniedException", _AEC = "AutomatedEvaluationConfig", _AECM = "AutomatedEvaluationCustomMetrics", _AECMC = "AutomatedEvaluationCustomMetricConfig", _AECMS = "AutomatedEvaluationCustomMetricSource", _AEGIIC = "AccountEnforcedGuardrailInferenceInputConfiguration", _AEGOC = "AccountEnforcedGuardrailOutputConfiguration", _AEGOCc = "AccountEnforcedGuardrailsOutputConfiguration", _ARCDSL = "AutomatedReasoningCheckDifferenceScenarioList", _ARCF = "AutomatedReasoningCheckFinding", _ARCFL = "AutomatedReasoningCheckFindingList", _ARCIF = "AutomatedReasoningCheckImpossibleFinding", _ARCIFu = "AutomatedReasoningCheckInvalidFinding", _ARCITR = "AutomatedReasoningCheckInputTextReference", _ARCITRL = "AutomatedReasoningCheckInputTextReferenceList", _ARCLW = "AutomatedReasoningCheckLogicWarning", _ARCNTF = "AutomatedReasoningCheckNoTranslationsFinding", _ARCR = "AutomatedReasoningCheckRule", _ARCRL = "AutomatedReasoningCheckRuleList", _ARCS = "AutomatedReasoningCheckScenario", _ARCSF = "AutomatedReasoningCheckSatisfiableFinding", _ARCT = "AutomatedReasoningCheckTranslation", _ARCTAF = "AutomatedReasoningCheckTranslationAmbiguousFinding", _ARCTCF = "AutomatedReasoningCheckTooComplexFinding", _ARCTL = "AutomatedReasoningCheckTranslationList", _ARCTO = "AutomatedReasoningCheckTranslationOption", _ARCTOL = "AutomatedReasoningCheckTranslationOptionList", _ARCVF = "AutomatedReasoningCheckValidFinding", _ARLS = "AutomatedReasoningLogicStatement", _ARLSC = "AutomatedReasoningLogicStatementContent", _ARLSL = "AutomatedReasoningLogicStatementList", _ARNLSC = "AutomatedReasoningNaturalLanguageStatementContent", _ARPA = "AutomatedReasoningPolicyAnnotation", _ARPAC = "AutomatedReasoningPolicyAnnotatedChunk", _ARPACL = "AutomatedReasoningPolicyAnnotatedChunkList", _ARPACLu = "AutomatedReasoningPolicyAnnotatedContentList", _ARPACu = "AutomatedReasoningPolicyAnnotatedContent", _ARPAFNL = "AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage", _ARPAIC = "AutomatedReasoningPolicyAnnotationIngestContent", _ARPAL = "AutomatedReasoningPolicyAnnotatedLine", _ARPALu = "AutomatedReasoningPolicyAnnotationList", _ARPARA = "AutomatedReasoningPolicyAddRuleAnnotation", _ARPARFNLA = "AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation", _ARPARM = "AutomatedReasoningPolicyAddRuleMutation", _ARPARNL = "AutomatedReasoningPolicyAnnotationRuleNaturalLanguage", _ARPAS = "AutomatedReasoningPolicyAtomicStatement", _ARPASL = "AutomatedReasoningPolicyAtomicStatementList", _ARPATA = "AutomatedReasoningPolicyAddTypeAnnotation", _ARPATM = "AutomatedReasoningPolicyAddTypeMutation", _ARPATV = "AutomatedReasoningPolicyAddTypeValue", _ARPAVA = "AutomatedReasoningPolicyAddVariableAnnotation", _ARPAVM = "AutomatedReasoningPolicyAddVariableMutation", _ARPBDB = "AutomatedReasoningPolicyBuildDocumentBlob", _ARPBDD = "AutomatedReasoningPolicyBuildDocumentDescription", _ARPBDN = "AutomatedReasoningPolicyBuildDocumentName", _ARPBL = "AutomatedReasoningPolicyBuildLog", _ARPBLE = "AutomatedReasoningPolicyBuildLogEntry", _ARPBLEL = "AutomatedReasoningPolicyBuildLogEntryList", _ARPBRA = "AutomatedReasoningPolicyBuildResultAssets", _ARPBRAM = "AutomatedReasoningPolicyBuildResultAssetManifest", _ARPBRAME = "AutomatedReasoningPolicyBuildResultAssetManifestEntry", _ARPBRAML = "AutomatedReasoningPolicyBuildResultAssetManifestList", _ARPBRAN = "AutomatedReasoningPolicyBuildResultAssetName", _ARPBS = "AutomatedReasoningPolicyBuildStep", _ARPBSC = "AutomatedReasoningPolicyBuildStepContext", _ARPBSL = "AutomatedReasoningPolicyBuildStepList", _ARPBSM = "AutomatedReasoningPolicyBuildStepMessage", _ARPBSML = "AutomatedReasoningPolicyBuildStepMessageList", _ARPBWD = "AutomatedReasoningPolicyBuildWorkflowDocument", _ARPBWDL = "AutomatedReasoningPolicyBuildWorkflowDocumentList", _ARPBWRC = "AutomatedReasoningPolicyBuildWorkflowRepairContent", _ARPBWS = "AutomatedReasoningPolicyBuildWorkflowSource", _ARPBWSu = "AutomatedReasoningPolicyBuildWorkflowSummary", _ARPBWSut = "AutomatedReasoningPolicyBuildWorkflowSummaries", _ARPD = "AutomatedReasoningPolicyDescription", _ARPDE = "AutomatedReasoningPolicyDefinitionElement", _ARPDQR = "AutomatedReasoningPolicyDefinitionQualityReport", _ARPDR = "AutomatedReasoningPolicyDefinitionRule", _ARPDRA = "AutomatedReasoningPolicyDeleteRuleAnnotation", _ARPDRAE = "AutomatedReasoningPolicyDefinitionRuleAlternateExpression", _ARPDRE = "AutomatedReasoningPolicyDefinitionRuleExpression", _ARPDRL = "AutomatedReasoningPolicyDefinitionRuleList", _ARPDRM = "AutomatedReasoningPolicyDeleteRuleMutation", _ARPDRS = "AutomatedReasoningPolicyDisjointRuleSet", _ARPDRSL = "AutomatedReasoningPolicyDisjointRuleSetList", _ARPDT = "AutomatedReasoningPolicyDefinitionType", _ARPDTA = "AutomatedReasoningPolicyDeleteTypeAnnotation", _ARPDTD = "AutomatedReasoningPolicyDefinitionTypeDescription", _ARPDTL = "AutomatedReasoningPolicyDefinitionTypeList", _ARPDTM = "AutomatedReasoningPolicyDeleteTypeMutation", _ARPDTN = "AutomatedReasoningPolicyDefinitionTypeName", _ARPDTNL = "AutomatedReasoningPolicyDefinitionTypeNameList", _ARPDTV = "AutomatedReasoningPolicyDefinitionTypeValue", _ARPDTVD = "AutomatedReasoningPolicyDefinitionTypeValueDescription", _ARPDTVL = "AutomatedReasoningPolicyDefinitionTypeValueList", _ARPDTVP = "AutomatedReasoningPolicyDefinitionTypeValuePair", _ARPDTVPL = "AutomatedReasoningPolicyDefinitionTypeValuePairList", _ARPDTVu = "AutomatedReasoningPolicyDeleteTypeValue", _ARPDV = "AutomatedReasoningPolicyDefinitionVariable", _ARPDVA = "AutomatedReasoningPolicyDeleteVariableAnnotation", _ARPDVD = "AutomatedReasoningPolicyDefinitionVariableDescription", _ARPDVL = "AutomatedReasoningPolicyDefinitionVariableList", _ARPDVM = "AutomatedReasoningPolicyDeleteVariableMutation", _ARPDVN = "AutomatedReasoningPolicyDefinitionVariableName", _ARPDVNL = "AutomatedReasoningPolicyDefinitionVariableNameList", _ARPDu = "AutomatedReasoningPolicyDefinition", _ARPFR = "AutomatedReasoningPolicyFidelityReport", _ARPGFRC = "AutomatedReasoningPolicyGenerateFidelityReportContent", _ARPGFRDL = "AutomatedReasoningPolicyGenerateFidelityReportDocumentList", _ARPGTC = "AutomatedReasoningPolicyGeneratedTestCase", _ARPGTCL = "AutomatedReasoningPolicyGeneratedTestCaseList", _ARPGTCu = "AutomatedReasoningPolicyGeneratedTestCases", _ARPICA = "AutomatedReasoningPolicyIngestContentAnnotation", _ARPJL = "AutomatedReasoningPolicyJustificationList", _ARPJT = "AutomatedReasoningPolicyJustificationText", _ARPLT = "AutomatedReasoningPolicyLineText", _ARPM = "AutomatedReasoningPolicyMutation", _ARPN = "AutomatedReasoningPolicyName", _ARPP = "AutomatedReasoningPolicyPlanning", _ARPRR = "AutomatedReasoningPolicyRuleReport", _ARPRRM = "AutomatedReasoningPolicyRuleReportMap", _ARPRSD = "AutomatedReasoningPolicyReportSourceDocument", _ARPRSDL = "AutomatedReasoningPolicyReportSourceDocumentList", _ARPS = "AutomatedReasoningPolicyScenario", _ARPSAE = "AutomatedReasoningPolicyScenarioAlternateExpression", _ARPSD = "AutomatedReasoningPolicySourceDocument", _ARPSE = "AutomatedReasoningPolicyScenarioExpression", _ARPSL = "AutomatedReasoningPolicyStatementLocation", _ARPSLu = "AutomatedReasoningPolicyScenarioList", _ARPSR = "AutomatedReasoningPolicyStatementReference", _ARPSRL = "AutomatedReasoningPolicyStatementReferenceList", _ARPST = "AutomatedReasoningPolicyStatementText", _ARPSu = "AutomatedReasoningPolicyScenarios", _ARPSut = "AutomatedReasoningPolicySummary", _ARPSuto = "AutomatedReasoningPolicySummaries", _ARPTC = "AutomatedReasoningPolicyTestCase", _ARPTCL = "AutomatedReasoningPolicyTestCaseList", _ARPTGC = "AutomatedReasoningPolicyTestGuardContent", _ARPTL = "AutomatedReasoningPolicyTestList", _ARPTQC = "AutomatedReasoningPolicyTestQueryContent", _ARPTR = "AutomatedReasoningPolicyTestResult", _ARPTVA = "AutomatedReasoningPolicyTypeValueAnnotation", _ARPTVAL = "AutomatedReasoningPolicyTypeValueAnnotationList", _ARPUFRFA = "AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation", _ARPUFSFA = "AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation", _ARPURA = "AutomatedReasoningPolicyUpdateRuleAnnotation", _ARPURM = "AutomatedReasoningPolicyUpdateRuleMutation", _ARPUTA = "AutomatedReasoningPolicyUpdateTypeAnnotation", _ARPUTM = "AutomatedReasoningPolicyUpdateTypeMutation", _ARPUTV = "AutomatedReasoningPolicyUpdateTypeValue", _ARPUVA = "AutomatedReasoningPolicyUpdateVariableAnnotation", _ARPUVM = "AutomatedReasoningPolicyUpdateVariableMutation", _ARPVR = "AutomatedReasoningPolicyVariableReport", _ARPVRM = "AutomatedReasoningPolicyVariableReportMap", _ARPWTC = "AutomatedReasoningPolicyWorkflowTypeContent", _BCB = "ByteContentBlob", _BCD = "ByteContentDoc", _BDEJ = "BatchDeleteEvaluationJob", _BDEJE = "BatchDeleteEvaluationJobError", _BDEJEa = "BatchDeleteEvaluationJobErrors", _BDEJI = "BatchDeleteEvaluationJobItem", _BDEJIa = "BatchDeleteEvaluationJobItems", _BDEJR = "BatchDeleteEvaluationJobRequest", _BDEJRa = "BatchDeleteEvaluationJobResponse", _BEM = "BedrockEvaluatorModel", _BEMe = "BedrockEvaluatorModels", _CARP = "CreateAutomatedReasoningPolicy", _CARPBW = "CancelAutomatedReasoningPolicyBuildWorkflow", _CARPBWR = "CancelAutomatedReasoningPolicyBuildWorkflowRequest", _CARPBWRa = "CancelAutomatedReasoningPolicyBuildWorkflowResponse", _CARPR = "CreateAutomatedReasoningPolicyRequest", _CARPRr = "CreateAutomatedReasoningPolicyResponse", _CARPTC = "CreateAutomatedReasoningPolicyTestCase", _CARPTCR = "CreateAutomatedReasoningPolicyTestCaseRequest", _CARPTCRr = "CreateAutomatedReasoningPolicyTestCaseResponse", _CARPV = "CreateAutomatedReasoningPolicyVersion", _CARPVR = "CreateAutomatedReasoningPolicyVersionRequest", _CARPVRr = "CreateAutomatedReasoningPolicyVersionResponse", _CC = "CustomizationConfig", _CCM = "CreateCustomModel", _CCMD = "CreateCustomModelDeployment", _CCMDR = "CreateCustomModelDeploymentRequest", _CCMDRr = "CreateCustomModelDeploymentResponse", _CCMR = "CreateCustomModelRequest", _CCMRr = "CreateCustomModelResponse", _CE = "ConflictException", _CEJ = "CreateEvaluationJob", _CEJR = "CreateEvaluationJobRequest", _CEJRr = "CreateEvaluationJobResponse", _CFMA = "CreateFoundationModelAgreement", _CFMAR = "CreateFoundationModelAgreementRequest", _CFMARr = "CreateFoundationModelAgreementResponse", _CG = "CreateGuardrail", _CGR = "CreateGuardrailRequest", _CGRr = "CreateGuardrailResponse", _CGV = "CreateGuardrailVersion", _CGVR = "CreateGuardrailVersionRequest", _CGVRr = "CreateGuardrailVersionResponse", _CIP = "CreateInferenceProfile", _CIPR = "CreateInferenceProfileRequest", _CIPRr = "CreateInferenceProfileResponse", _CMBEM = "CustomMetricBedrockEvaluatorModel", _CMBEMu = "CustomMetricBedrockEvaluatorModels", _CMCJ = "CreateModelCopyJob", _CMCJR = "CreateModelCopyJobRequest", _CMCJRr = "CreateModelCopyJobResponse", _CMCJRre = "CreateModelCustomizationJobRequest", _CMCJRrea = "CreateModelCustomizationJobResponse", _CMCJr = "CreateModelCustomizationJob", _CMD = "CustomMetricDefinition", _CMDS = "CustomModelDeploymentSummary", _CMDSL = "CustomModelDeploymentSummaryList", _CMDUD = "CustomModelDeploymentUpdateDetails", _CMEMC = "CustomMetricEvaluatorModelConfig", _CMIJ = "CreateModelImportJob", _CMIJR = "CreateModelImportJobRequest", _CMIJRr = "CreateModelImportJobResponse", _CMIJRre = "CreateModelInvocationJobRequest", _CMIJRrea = "CreateModelInvocationJobResponse", _CMIJr = "CreateModelInvocationJob", _CMME = "CreateMarketplaceModelEndpoint", _CMMER = "CreateMarketplaceModelEndpointRequest", _CMMERr = "CreateMarketplaceModelEndpointResponse", _CMS = "CustomModelSummary", _CMSL = "CustomModelSummaryList", _CMU = "CustomModelUnits", _CPMT = "CreateProvisionedModelThroughput", _CPMTR = "CreateProvisionedModelThroughputRequest", _CPMTRr = "CreateProvisionedModelThroughputResponse", _CPR = "CreatePromptRouter", _CPRR = "CreatePromptRouterRequest", _CPRRr = "CreatePromptRouterResponse", _CWC = "CloudWatchConfig", _DARP = "DeleteAutomatedReasoningPolicy", _DARPBW = "DeleteAutomatedReasoningPolicyBuildWorkflow", _DARPBWR = "DeleteAutomatedReasoningPolicyBuildWorkflowRequest", _DARPBWRe = "DeleteAutomatedReasoningPolicyBuildWorkflowResponse", _DARPR = "DeleteAutomatedReasoningPolicyRequest", _DARPRe = "DeleteAutomatedReasoningPolicyResponse", _DARPTC = "DeleteAutomatedReasoningPolicyTestCase", _DARPTCR = "DeleteAutomatedReasoningPolicyTestCaseRequest", _DARPTCRe = "DeleteAutomatedReasoningPolicyTestCaseResponse", _DC = "DistillationConfig", _DCM = "DeleteCustomModel", _DCMD = "DeleteCustomModelDeployment", _DCMDR = "DeleteCustomModelDeploymentRequest", _DCMDRe = "DeleteCustomModelDeploymentResponse", _DCMR = "DeleteCustomModelRequest", _DCMRe = "DeleteCustomModelResponse", _DEGC = "DeleteEnforcedGuardrailConfiguration", _DEGCR = "DeleteEnforcedGuardrailConfigurationRequest", _DEGCRe = "DeleteEnforcedGuardrailConfigurationResponse", _DFMA = "DeleteFoundationModelAgreement", _DFMAR = "DeleteFoundationModelAgreementRequest", _DFMARe = "DeleteFoundationModelAgreementResponse", _DG = "DeleteGuardrail", _DGR = "DeleteGuardrailRequest", _DGRe = "DeleteGuardrailResponse", _DIM = "DeleteImportedModel", _DIMR = "DeleteImportedModelRequest", _DIMRe = "DeleteImportedModelResponse", _DIP = "DeleteInferenceProfile", _DIPR = "DeleteInferenceProfileRequest", _DIPRe = "DeleteInferenceProfileResponse", _DMILC = "DeleteModelInvocationLoggingConfiguration", _DMILCR = "DeleteModelInvocationLoggingConfigurationRequest", _DMILCRe = "DeleteModelInvocationLoggingConfigurationResponse", _DMME = "DeleteMarketplaceModelEndpoint", _DMMER = "DeleteMarketplaceModelEndpointRequest", _DMMERe = "DeleteMarketplaceModelEndpointResponse", _DMMERer = "DeregisterMarketplaceModelEndpointRequest", _DMMERere = "DeregisterMarketplaceModelEndpointResponse", _DMMEe = "DeregisterMarketplaceModelEndpoint", _DPD = "DataProcessingDetails", _DPMT = "DeleteProvisionedModelThroughput", _DPMTR = "DeleteProvisionedModelThroughputRequest", _DPMTRe = "DeleteProvisionedModelThroughputResponse", _DPR = "DimensionalPriceRate", _DPRR = "DeletePromptRouterRequest", _DPRRe = "DeletePromptRouterResponse", _DPRe = "DeletePromptRouter", _EARPV = "ExportAutomatedReasoningPolicyVersion", _EARPVR = "ExportAutomatedReasoningPolicyVersionRequest", _EARPVRx = "ExportAutomatedReasoningPolicyVersionResponse", _EBM = "EvaluationBedrockModel", _EC = "EndpointConfig", _ECv = "EvaluationConfig", _ED = "EvaluationDataset", _EDL = "EvaluationDatasetLocation", _EDMC = "EvaluationDatasetMetricConfig", _EDMCv = "EvaluationDatasetMetricConfigs", _EDN = "EvaluationDatasetName", _EIC = "EvaluationInferenceConfig", _EICS = "EvaluationInferenceConfigSummary", _EJD = "EvaluationJobDescription", _EJI = "EvaluationJobIdentifier", _EJIv = "EvaluationJobIdentifiers", _EMC = "EvaluationModelConfigs", _EMCS = "EvaluationModelConfigSummary", _EMCv = "EvaluationModelConfig", _EMCva = "EvaluatorModelConfig", _EMD = "EvaluationMetricDescription", _EMIP = "EvaluationModelInferenceParams", _EMN = "EvaluationMetricName", _EMNv = "EvaluationMetricNames", _EODC = "EvaluationOutputDataConfig", _EPIS = "EvaluationPrecomputedInferenceSource", _EPRAGSC = "EvaluationPrecomputedRetrieveAndGenerateSourceConfig", _EPRSC = "EvaluationPrecomputedRetrieveSourceConfig", _EPRSCv = "EvaluationPrecomputedRagSourceConfig", _ERCS = "EvaluationRagConfigSummary", _ES = "EvaluationSummary", _ESGC = "ExternalSourcesGenerationConfiguration", _ESRAGC = "ExternalSourcesRetrieveAndGenerateConfiguration", _ESv = "EvaluationSummaries", _ESx = "ExternalSource", _ESxt = "ExternalSources", _FA = "FilterAttribute", _FFR = "FieldForReranking", _FFRi = "FieldsForReranking", _FMD = "FoundationModelDetails", _FML = "FoundationModelLifecycle", _FMS = "FoundationModelSummary", _FMSL = "FoundationModelSummaryList", _GARP = "GuardrailAutomatedReasoningPolicy", _GARPA = "GetAutomatedReasoningPolicyAnnotations", _GARPAR = "GetAutomatedReasoningPolicyAnnotationsRequest", _GARPARe = "GetAutomatedReasoningPolicyAnnotationsResponse", _GARPBW = "GetAutomatedReasoningPolicyBuildWorkflow", _GARPBWR = "GetAutomatedReasoningPolicyBuildWorkflowRequest", _GARPBWRA = "GetAutomatedReasoningPolicyBuildWorkflowResultAssets", _GARPBWRAR = "GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest", _GARPBWRARe = "GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse", _GARPBWRe = "GetAutomatedReasoningPolicyBuildWorkflowResponse", _GARPC = "GuardrailAutomatedReasoningPolicyConfig", _GARPNS = "GetAutomatedReasoningPolicyNextScenario", _GARPNSR = "GetAutomatedReasoningPolicyNextScenarioRequest", _GARPNSRe = "GetAutomatedReasoningPolicyNextScenarioResponse", _GARPR = "GetAutomatedReasoningPolicyRequest", _GARPRe = "GetAutomatedReasoningPolicyResponse", _GARPTC = "GetAutomatedReasoningPolicyTestCase", _GARPTCR = "GetAutomatedReasoningPolicyTestCaseRequest", _GARPTCRe = "GetAutomatedReasoningPolicyTestCaseResponse", _GARPTR = "GetAutomatedReasoningPolicyTestResult", _GARPTRR = "GetAutomatedReasoningPolicyTestResultRequest", _GARPTRRe = "GetAutomatedReasoningPolicyTestResultResponse", _GARPe = "GetAutomatedReasoningPolicy", _GBM = "GuardrailBlockedMessaging", _GC = "GenerationConfiguration", _GCF = "GuardrailContentFilter", _GCFA = "GuardrailContentFilterAction", _GCFC = "GuardrailContentFilterConfig", _GCFCu = "GuardrailContentFiltersConfig", _GCFT = "GuardrailContentFiltersTier", _GCFTC = "GuardrailContentFiltersTierConfig", _GCFTN = "GuardrailContentFiltersTierName", _GCFu = "GuardrailContentFilters", _GCGA = "GuardrailContextualGroundingAction", _GCGF = "GuardrailContextualGroundingFilter", _GCGFC = "GuardrailContextualGroundingFilterConfig", _GCGFCu = "GuardrailContextualGroundingFiltersConfig", _GCGFu = "GuardrailContextualGroundingFilters", _GCGP = "GuardrailContextualGroundingPolicy", _GCGPC = "GuardrailContextualGroundingPolicyConfig", _GCM = "GetCustomModel", _GCMD = "GetCustomModelDeployment", _GCMDR = "GetCustomModelDeploymentRequest", _GCMDRe = "GetCustomModelDeploymentResponse", _GCMR = "GetCustomModelRequest", _GCMRe = "GetCustomModelResponse", _GCP = "GuardrailContentPolicy", _GCPC = "GuardrailContentPolicyConfig", _GCRC = "GuardrailCrossRegionConfig", _GCRD = "GuardrailCrossRegionDetails", _GCr = "GraderConfig", _GCu = "GuardrailConfiguration", _GD = "GuardrailDescription", _GEJ = "GetEvaluationJob", _GEJR = "GetEvaluationJobRequest", _GEJRe = "GetEvaluationJobResponse", _GFM = "GetFoundationModel", _GFMA = "GetFoundationModelAvailability", _GFMAR = "GetFoundationModelAvailabilityRequest", _GFMARe = "GetFoundationModelAvailabilityResponse", _GFMR = "GetFoundationModelRequest", _GFMRe = "GetFoundationModelResponse", _GFR = "GuardrailFailureRecommendation", _GFRu = "GuardrailFailureRecommendations", _GG = "GetGuardrail", _GGR = "GetGuardrailRequest", _GGRe = "GetGuardrailResponse", _GIM = "GetImportedModel", _GIMR = "GetImportedModelRequest", _GIMRe = "GetImportedModelResponse", _GIP = "GetInferenceProfile", _GIPR = "GetInferenceProfileRequest", _GIPRe = "GetInferenceProfileResponse", _GM = "GuardrailModality", _GMCJ = "GetModelCopyJob", _GMCJR = "GetModelCopyJobRequest", _GMCJRe = "GetModelCopyJobResponse", _GMCJRet = "GetModelCustomizationJobRequest", _GMCJReto = "GetModelCustomizationJobResponse", _GMCJe = "GetModelCustomizationJob", _GMIJ = "GetModelImportJob", _GMIJR = "GetModelImportJobRequest", _GMIJRe = "GetModelImportJobResponse", _GMIJRet = "GetModelInvocationJobRequest", _GMIJReto = "GetModelInvocationJobResponse", _GMIJe = "GetModelInvocationJob", _GMILC = "GetModelInvocationLoggingConfiguration", _GMILCR = "GetModelInvocationLoggingConfigurationRequest", _GMILCRe = "GetModelInvocationLoggingConfigurationResponse", _GMME = "GetMarketplaceModelEndpoint", _GMMER = "GetMarketplaceModelEndpointRequest", _GMMERe = "GetMarketplaceModelEndpointResponse", _GMW = "GuardrailManagedWords", _GMWC = "GuardrailManagedWordsConfig", _GMWL = "GuardrailManagedWordLists", _GMWLC = "GuardrailManagedWordListsConfig", _GMu = "GuardrailModalities", _GN = "GuardrailName", _GPE = "GuardrailPiiEntity", _GPEC = "GuardrailPiiEntityConfig", _GPECu = "GuardrailPiiEntitiesConfig", _GPEu = "GuardrailPiiEntities", _GPMT = "GetProvisionedModelThroughput", _GPMTR = "GetProvisionedModelThroughputRequest", _GPMTRe = "GetProvisionedModelThroughputResponse", _GPR = "GetPromptRouter", _GPRR = "GetPromptRouterRequest", _GPRRe = "GetPromptRouterResponse", _GR = "GuardrailRegex", _GRC = "GuardrailRegexConfig", _GRCu = "GuardrailRegexesConfig", _GRu = "GuardrailRegexes", _GS = "GuardrailSummary", _GSIP = "GuardrailSensitiveInformationPolicy", _GSIPC = "GuardrailSensitiveInformationPolicyConfig", _GSR = "GuardrailStatusReason", _GSRu = "GuardrailStatusReasons", _GSu = "GuardrailSummaries", _GT = "GuardrailTopic", _GTA = "GuardrailTopicAction", _GTC = "GuardrailTopicConfig", _GTCu = "GuardrailTopicsConfig", _GTD = "GuardrailTopicDefinition", _GTE = "GuardrailTopicExample", _GTEu = "GuardrailTopicExamples", _GTN = "GuardrailTopicName", _GTP = "GuardrailTopicPolicy", _GTPC = "GuardrailTopicPolicyConfig", _GTT = "GuardrailTopicsTier", _GTTC = "GuardrailTopicsTierConfig", _GTTN = "GuardrailTopicsTierName", _GTu = "GuardrailTopics", _GUCFMA = "GetUseCaseForModelAccess", _GUCFMAR = "GetUseCaseForModelAccessRequest", _GUCFMARe = "GetUseCaseForModelAccessResponse", _GW = "GuardrailWord", _GWA = "GuardrailWordAction", _GWC = "GuardrailWordConfig", _GWCu = "GuardrailWordsConfig", _GWP = "GuardrailWordPolicy", _GWPC = "GuardrailWordPolicyConfig", _GWu = "GuardrailWords", _HEC = "HumanEvaluationConfig", _HECM = "HumanEvaluationCustomMetric", _HECMu = "HumanEvaluationCustomMetrics", _HTI = "HumanTaskInstructions", _HWC = "HumanWorkflowConfig", _I = "Identifier", _IFC = "ImplicitFilterConfiguration", _ILC = "InvocationLogsConfig", _ILS = "InvocationLogSource", _IMS = "ImportedModelSummary", _IMSL = "ImportedModelSummaryList", _IPD = "InferenceProfileDescription", _IPM = "InferenceProfileModel", _IPMS = "InferenceProfileModelSource", _IPMn = "InferenceProfileModels", _IPS = "InferenceProfileSummary", _IPSn = "InferenceProfileSummaries", _ISE = "InternalServerException", _KBC = "KnowledgeBaseConfig", _KBRAGC = "KnowledgeBaseRetrieveAndGenerateConfiguration", _KBRC = "KnowledgeBaseRetrievalConfiguration", _KBVSC = "KnowledgeBaseVectorSearchConfiguration", _KIC = "KbInferenceConfig", _LARP = "ListAutomatedReasoningPolicies", _LARPBW = "ListAutomatedReasoningPolicyBuildWorkflows", _LARPBWR = "ListAutomatedReasoningPolicyBuildWorkflowsRequest", _LARPBWRi = "ListAutomatedReasoningPolicyBuildWorkflowsResponse", _LARPR = "ListAutomatedReasoningPoliciesRequest", _LARPRi = "ListAutomatedReasoningPoliciesResponse", _LARPTC = "ListAutomatedReasoningPolicyTestCases", _LARPTCR = "ListAutomatedReasoningPolicyTestCasesRequest", _LARPTCRi = "ListAutomatedReasoningPolicyTestCasesResponse", _LARPTR = "ListAutomatedReasoningPolicyTestResults", _LARPTRR = "ListAutomatedReasoningPolicyTestResultsRequest", _LARPTRRi = "ListAutomatedReasoningPolicyTestResultsResponse", _LC = "LoggingConfig", _LCM = "ListCustomModels", _LCMD = "ListCustomModelDeployments", _LCMDR = "ListCustomModelDeploymentsRequest", _LCMDRi = "ListCustomModelDeploymentsResponse", _LCMR = "ListCustomModelsRequest", _LCMRi = "ListCustomModelsResponse", _LEGC = "ListEnforcedGuardrailsConfiguration", _LEGCR = "ListEnforcedGuardrailsConfigurationRequest", _LEGCRi = "ListEnforcedGuardrailsConfigurationResponse", _LEJ = "ListEvaluationJobs", _LEJR = "ListEvaluationJobsRequest", _LEJRi = "ListEvaluationJobsResponse", _LFM = "ListFoundationModels", _LFMAO = "ListFoundationModelAgreementOffers", _LFMAOR = "ListFoundationModelAgreementOffersRequest", _LFMAORi = "ListFoundationModelAgreementOffersResponse", _LFMR = "ListFoundationModelsRequest", _LFMRi = "ListFoundationModelsResponse", _LG = "ListGuardrails", _LGC = "LambdaGraderConfig", _LGR = "ListGuardrailsRequest", _LGRi = "ListGuardrailsResponse", _LIM = "ListImportedModels", _LIMR = "ListImportedModelsRequest", _LIMRi = "ListImportedModelsResponse", _LIP = "ListInferenceProfiles", _LIPR = "ListInferenceProfilesRequest", _LIPRi = "ListInferenceProfilesResponse", _LMCJ = "ListModelCopyJobs", _LMCJR = "ListModelCopyJobsRequest", _LMCJRi = "ListModelCopyJobsResponse", _LMCJRis = "ListModelCustomizationJobsRequest", _LMCJRist = "ListModelCustomizationJobsResponse", _LMCJi = "ListModelCustomizationJobs", _LMIJ = "ListModelImportJobs", _LMIJR = "ListModelImportJobsRequest", _LMIJRi = "ListModelImportJobsResponse", _LMIJRis = "ListModelInvocationJobsRequest", _LMIJRist = "ListModelInvocationJobsResponse", _LMIJi = "ListModelInvocationJobs", _LMME = "ListMarketplaceModelEndpoints", _LMMER = "ListMarketplaceModelEndpointsRequest", _LMMERi = "ListMarketplaceModelEndpointsResponse", _LPMT = "ListProvisionedModelThroughputs", _LPMTR = "ListProvisionedModelThroughputsRequest", _LPMTRi = "ListProvisionedModelThroughputsResponse", _LPR = "ListPromptRouters", _LPRR = "ListPromptRoutersRequest", _LPRRi = "ListPromptRoutersResponse", _LT = "LegalTerm", _LTFR = "ListTagsForResource", _LTFRR = "ListTagsForResourceRequest", _LTFRRi = "ListTagsForResourceResponse", _M = "Message", _MAS = "MetadataAttributeSchema", _MASL = "MetadataAttributeSchemaList", _MCFR = "MetadataConfigurationForReranking", _MCJS = "ModelCopyJobSummary", _MCJSo = "ModelCustomizationJobSummary", _MCJSod = "ModelCopyJobSummaries", _MCJSode = "ModelCustomizationJobSummaries", _MDS = "ModelDataSource", _ME = "ModelEnforcement", _MIJIDC = "ModelInvocationJobInputDataConfig", _MIJODC = "ModelInvocationJobOutputDataConfig", _MIJS = "ModelImportJobSummary", _MIJSIDC = "ModelInvocationJobS3InputDataConfig", _MIJSODC = "ModelInvocationJobS3OutputDataConfig", _MIJSo = "ModelInvocationJobSummary", _MIJSod = "ModelImportJobSummaries", _MIJSode = "ModelInvocationJobSummaries", _MME = "MarketplaceModelEndpoint", _MMES = "MarketplaceModelEndpointSummary", _MMESa = "MarketplaceModelEndpointSummaries", _MN = "MetricName", _O = "Offer", _OC = "OrchestrationConfiguration", _ODC = "OutputDataConfig", _Of = "Offers", _PC = "PerformanceConfiguration", _PEGC = "PutEnforcedGuardrailConfiguration", _PEGCR = "PutEnforcedGuardrailConfigurationRequest", _PEGCRu = "PutEnforcedGuardrailConfigurationResponse", _PMILC = "PutModelInvocationLoggingConfiguration", _PMILCR = "PutModelInvocationLoggingConfigurationRequest", _PMILCRu = "PutModelInvocationLoggingConfigurationResponse", _PMS = "ProvisionedModelSummary", _PMSr = "ProvisionedModelSummaries", _PRD = "PromptRouterDescription", _PRS = "PromptRouterSummary", _PRSr = "PromptRouterSummaries", _PRTM = "PromptRouterTargetModel", _PRTMr = "PromptRouterTargetModels", _PT = "PricingTerm", _PTr = "PromptTemplate", _PUCFMA = "PutUseCaseForModelAccess", _PUCFMAR = "PutUseCaseForModelAccessRequest", _PUCFMARu = "PutUseCaseForModelAccessResponse", _QTC = "QueryTransformationConfiguration", _RAGC = "RetrieveAndGenerateConfiguration", _RAGCo = "RAGConfig", _RC = "RetrieveConfig", _RCa = "RagConfigs", _RCat = "RateCard", _RCo = "RoutingCriteria", _RF = "RetrievalFilter", _RFL = "RetrievalFilterList", _RFTC = "RFTConfig", _RFTHP = "RFTHyperParameters", _RIUE = "ResourceInUseException", _RMBF = "RequestMetadataBaseFilters", _RMF = "RequestMetadataFilters", _RMFL = "RequestMetadataFiltersList", _RMM = "RequestMetadataMap", _RMME = "RegisterMarketplaceModelEndpoint", _RMMER = "RegisterMarketplaceModelEndpointRequest", _RMMERe = "RegisterMarketplaceModelEndpointResponse", _RMSMC = "RerankingMetadataSelectiveModeConfiguration", _RNFE = "ResourceNotFoundException", _RS = "RatingScale", _RSI = "RatingScaleItem", _RSIV = "RatingScaleItemValue", _SARPBW = "StartAutomatedReasoningPolicyBuildWorkflow", _SARPBWR = "StartAutomatedReasoningPolicyBuildWorkflowRequest", _SARPBWRt = "StartAutomatedReasoningPolicyBuildWorkflowResponse", _SARPTW = "StartAutomatedReasoningPolicyTestWorkflow", _SARPTWR = "StartAutomatedReasoningPolicyTestWorkflowRequest", _SARPTWRt = "StartAutomatedReasoningPolicyTestWorkflowResponse", _SC = "S3Config", _SD = "StatusDetails", _SDS = "S3DataSource", _SEJ = "StopEvaluationJob", _SEJR = "StopEvaluationJobRequest", _SEJRt = "StopEvaluationJobResponse", _SMCJ = "StopModelCustomizationJob", _SMCJR = "StopModelCustomizationJobRequest", _SMCJRt = "StopModelCustomizationJobResponse", _SME = "SageMakerEndpoint", _SMIJ = "StopModelInvocationJob", _SMIJR = "StopModelInvocationJobRequest", _SMIJRt = "StopModelInvocationJobResponse", _SOD = "S3ObjectDoc", _SQEE = "ServiceQuotaExceededException", _ST = "SupportTerm", _SUE = "ServiceUnavailableException", _T = "Tag", _TD = "TermDetails", _TDC = "TrainingDataConfig", _TDr = "TrainingDetails", _TE = "ThrottlingException", _TIC = "TextInferenceConfig", _TL = "TagList", _TM = "TrainingMetrics", _TMC = "TeacherModelConfig", _TMTE = "TooManyTagsException", _TPT = "TextPromptTemplate", _TR = "TagResource", _TRR = "TagResourceRequest", _TRRa = "TagResourceResponse", _UARP = "UpdateAutomatedReasoningPolicy", _UARPA = "UpdateAutomatedReasoningPolicyAnnotations", _UARPAR = "UpdateAutomatedReasoningPolicyAnnotationsRequest", _UARPARp = "UpdateAutomatedReasoningPolicyAnnotationsResponse", _UARPR = "UpdateAutomatedReasoningPolicyRequest", _UARPRp = "UpdateAutomatedReasoningPolicyResponse", _UARPTC = "UpdateAutomatedReasoningPolicyTestCase", _UARPTCR = "UpdateAutomatedReasoningPolicyTestCaseRequest", _UARPTCRp = "UpdateAutomatedReasoningPolicyTestCaseResponse", _UCMD = "UpdateCustomModelDeployment", _UCMDR = "UpdateCustomModelDeploymentRequest", _UCMDRp = "UpdateCustomModelDeploymentResponse", _UG = "UpdateGuardrail", _UGR = "UpdateGuardrailRequest", _UGRp = "UpdateGuardrailResponse", _UMME = "UpdateMarketplaceModelEndpoint", _UMMER = "UpdateMarketplaceModelEndpointRequest", _UMMERp = "UpdateMarketplaceModelEndpointResponse", _UPMT = "UpdateProvisionedModelThroughput", _UPMTR = "UpdateProvisionedModelThroughputRequest", _UPMTRp = "UpdateProvisionedModelThroughputResponse", _UR = "UntagResource", _URR = "UntagResourceRequest", _URRn = "UntagResourceResponse", _V = "Validator", _VC = "VpcConfig", _VD = "ValidationDetails", _VDC = "ValidationDataConfig", _VE = "ValidationException", _VM = "ValidatorMetric", _VMa = "ValidationMetrics", _VSBRC = "VectorSearchBedrockRerankingConfiguration", _VSBRMC = "VectorSearchBedrockRerankingModelConfiguration", _VSRC = "VectorSearchRerankingConfiguration", _VT = "ValidityTerm", _Va = "Validators", _a2 = "annotation", _aA = "agreementAvailability", _aAn = "andAll", _aD = "agreementDuration", _aDDE = "audioDataDeliveryEnabled", _aE = "alternateExpression", _aEc = "acceptEula", _aI = "assetId", _aJ = "accuracyJustification", _aM = "assetManifest", _aMRF = "additionalModelRequestFields", _aN = "assetName", _aR = "addRule", _aRFNL = "addRuleFromNaturalLanguage", _aRP = "automatedReasoningPolicy", _aRPBWS = "automatedReasoningPolicyBuildWorkflowSummaries", _aRPC = "automatedReasoningPolicyConfig", _aRPS = "automatedReasoningPolicySummaries", _aS = "accuracyScore", _aSH = "annotationSetHash", _aSt = "atomicStatements", _aSu = "authorizationStatus", _aT = "assetType", _aTE = "applicationTypeEquals", _aTFR = "aggregatedTestFindingsResult", _aTV = "addTypeValue", _aTd = "addType", _aTp = "applicationType", _aV = "addVariable", _ac = "action", _an = "annotations", _ar = "arn", _au = "automated", _bC = "byteContent", _bCT = "byCustomizationType", _bEM = "bedrockEvaluatorModels", _bIM = "blockedInputMessaging", _bIT = "byInferenceType", _bKBI = "bedrockKnowledgeBaseIdentifiers", _bL = "buildLog", _bM = "bedrockModel", _bMA = "baseModelArn", _bMAE = "baseModelArnEquals", _bMI = "baseModelIdentifier", _bMIe = "bedrockModelIdentifiers", _bMN = "baseModelName", _bN = "bucketName", _bOM = "blockedOutputsMessaging", _bOMy = "byOutputModality", _bP = "byProvider", _bRC = "bedrockRerankingConfiguration", _bS = "buildSteps", _bSa = "batchSize", _bWA = "buildWorkflowAssets", _bWI = "buildWorkflowId", _bWT = "buildWorkflowType", _c = "client", _cA = "createdAt", _cAr = "createdAfter", _cB = "createdBy", _cBr = "createdBefore", _cC = "customizationConfig", _cD = "commitmentDuration", _cEKI = "customerEncryptionKeyId", _cET = "commitmentExpirationTime", _cF = "copyFrom", _cFS = "claimsFalseScenario", _cGP = "contextualGroundingPolicy", _cGPC = "contextualGroundingPolicyConfig", _cI = "configId", _cM = "customMetrics", _cMA = "customModelArn", _cMC = "customMetricConfig", _cMD = "customMetricDefinition", _cMDA = "customModelDeploymentArn", _cMDI = "customModelDeploymentIdentifier", _cMDN = "customModelDeploymentName", _cMEMI = "customMetricsEvaluatorModelIdentifiers", _cMKKI = "customModelKmsKeyId", _cMN = "customModelName", _cMT = "customModelTags", _cMU = "customModelUnits", _cMUPMC = "customModelUnitsPerModelCopy", _cMUV = "customModelUnitsVersion", _cP = "contentPolicy", _cPC = "contentPolicyConfig", _cR = "contradictingRules", _cRC = "crossRegionConfig", _cRD = "crossRegionDetails", _cRT = "clientRequestToken", _cRo = "conflictingRules", _cS = "coverageScore", _cSu = "customizationsSupported", _cT = "confidenceThreshold", _cTA = "creationTimeAfter", _cTB = "creationTimeBefore", _cTS = "claimsTrueScenario", _cTo = "contentType", _cTr = "creationTime", _cTu = "customizationType", _cWC = "cloudWatchConfig", _cl = "claims", _co = "confidence", _cod = "code", _con = "content", _cont = "context", _d = "description", _dC = "documentContent", _dCT = "documentContentType", _dCi = "distillationConfig", _dD = "documentDescription", _dH = "documentHash", _dHe = "definitionHash", _dI = "documentId", _dL = "datasetLocation", _dMA = "desiredModelArn", _dMC = "datasetMetricConfigs", _dMI = "desiredModelId", _dMU = "desiredModelUnits", _dN = "documentName", _dPD = "dataProcessingDetails", _dPMN = "desiredProvisionedModelName", _dR = "deleteRule", _dRS = "disjointRuleSets", _dS = "differenceScenarios", _dSo = "documentSources", _dT = "deleteType", _dTV = "deleteTypeValue", _dV = "deleteVariable", _da = "data", _dat = "dataset", _de = "definition", _di = "dimension", _do = "document", _doc = "documents", _e = "error", _eA = "endpointArn", _eAFR = "expectedAggregatedFindingsResult", _eAn = "entitlementAvailability", _eC = "evaluationConfig", _eCn = "endpointConfig", _eCp = "epochCount", _eDDE = "embeddingDataDeliveryEnabled", _eI = "endpointIdentifier", _eIv = "evalInterval", _eJ = "evaluationJobs", _eM = "errorMessage", _eMC = "evaluatorModelConfig", _eMI = "evaluatorModelIdentifiers", _eMx = "excludedModels", _eN = "endpointName", _eOLT = "endOfLifeTime", _eR = "expectedResult", _eRx = "executionRole", _eS = "endpointStatus", _eSC = "externalSourcesConfiguration", _eSM = "endpointStatusMessage", _eT = "endTime", _eTT = "evaluationTaskTypes", _en = "entries", _ena = "enabled", _eq = "equals", _er = "errors", _ex = "expression", _exa = "examples", _f = "feedback", _fC = "filtersConfig", _fD = "formData", _fDA = "flowDefinitionArn", _fM = "fallbackModel", _fMA = "foundationModelArn", _fMAE = "foundationModelArnEquals", _fMa = "failureMessage", _fMai = "failureMessages", _fN = "fieldName", _fR = "failureRecommendations", _fRi = "fidelityReport", _fTE = "fieldsToExclude", _fTI = "fieldsToInclude", _fV = "floatValue", _fi = "filters", _fil = "filter", _fo = "force", _g = "guardrails", _gA = "guardrailArn", _gC = "guardContent", _gCe = "generationConfiguration", _gCr = "graderConfig", _gCu = "guardrailConfiguration", _gCua = "guardrailsConfig", _gFRC = "generateFidelityReportContent", _gI = "guardrailIdentifier", _gIC = "guardrailInferenceConfig", _gIu = "guardrailId", _gJ = "groundingJustifications", _gPA = "guardrailProfileArn", _gPI = "guardrailProfileIdentifier", _gPIu = "guardrailProfileId", _gS = "groundingStatements", _gT = "greaterThan", _gTC = "generatedTestCases", _gTOE = "greaterThanOrEquals", _gV = "guardrailVersion", _h = "human", _hE = "httpError", _hH = "httpHeader", _hP = "hyperParameters", _hQ = "httpQuery", _hWC = "humanWorkflowConfig", _ht = "http", _i = "id", _iA = "inputAction", _iC = "inferenceConfig", _iCS = "inferenceConfigSummary", _iCn = "ingestContent", _iDC = "inputDataConfig", _iDDE = "imageDataDeliveryEnabled", _iE = "inputEnabled", _iFC = "implicitFilterConfiguration", _iIC = "initialInstanceCount", _iJS = "invocationJobSummaries", _iLC = "invocationLogsConfig", _iLS = "invocationLogSource", _iM = "inputModalities", _iMA = "importedModelArn", _iMKKA = "importedModelKmsKeyArn", _iMKKI = "importedModelKmsKeyId", _iMN = "importedModelName", _iMT = "importedModelTags", _iMTn = "inferenceMaxTokens", _iMn = "includedModels", _iO = "isOwned", _iP = "inferenceParams", _iPA = "inferenceProfileArn", _iPI = "inferenceProfileIdentifier", _iPIn = "inferenceProfileId", _iPN = "inferenceProfileName", _iPS = "inferenceProfileSummaries", _iS = "instructSupported", _iSI = "inferenceSourceIdentifier", _iSn = "inputStrength", _iT = "inputTags", _iTS = "inferenceTypesSupported", _iTd = "idempotencyToken", _iTn = "instanceType", _id = "identifier", _im = "impossible", _in = "instructions", _in_ = "in", _inv = "invalid", _jA = "jobArn", _jD = "jobDescription", _jET = "jobExpirationTime", _jI = "jobIdentifier", _jIo = "jobIdentifiers", _jN = "jobName", _jS = "jobStatus", _jSo = "jobSummaries", _jT = "jobTags", _jTo = "jobType", _k = "key", _kBC = "knowledgeBaseConfiguration", _kBCn = "knowledgeBaseConfig", _kBI = "knowledgeBaseId", _kBRC = "knowledgeBaseRetrievalConfiguration", _kEK = "kmsEncryptionKey", _kIC = "kbInferenceConfig", _kKA = "kmsKeyArn", _kKI = "kmsKeyId", _kP = "keyPrefix", _l = "logic", _lA = "lambdaArn", _lC = "loggingConfig", _lCi = "listContains", _lDDSC = "largeDataDeliveryS3Config", _lG = "lambdaGrader", _lGN = "logGroupName", _lMT = "lastModifiedTime", _lN = "lineNumber", _lR = "learningRate", _lT = "lineText", _lTOE = "lessThanOrEquals", _lTe = "legacyTime", _lTeg = "legalTerm", _lTes = "lessThan", _lUA = "lastUpdatedAt", _lUASH = "lastUpdatedAnnotationSetHash", _lUDH = "lastUpdatedDefinitionHash", _lW = "logicWarning", _la = "latency", _li = "lines", _lin = "line", _lo = "location", _m = "message", _mA = "modelArn", _mAE = "modelArnEquals", _mAe = "metadataAttributes", _mAo = "modelArchitecture", _mC = "modelConfiguration", _mCJS = "modelCopyJobSummaries", _mCJSo = "modelCustomizationJobSummaries", _mCS = "modelConfigSummary", _mCe = "metadataConfiguration", _mD = "modelDetails", _mDN = "modelDeploymentName", _mDS = "modelDataSource", _mDSo = "modelDeploymentSummaries", _mE = "modelEnforcement", _mI = "modelIdentifier", _mIJS = "modelImportJobSummaries", _mIT = "modelInvocationType", _mIo = "modelId", _mIod = "modelIdentifiers", _mKKA = "modelKmsKeyArn", _mKKI = "modelKmsKeyId", _mL = "modelLifecycle", _mME = "marketplaceModelEndpoint", _mMEa = "marketplaceModelEndpoints", _mN = "modelName", _mNe = "metricNames", _mPL = "maxPromptLength", _mR = "maxResults", _mRLFI = "maxResponseLengthForInference", _mS = "modelSource", _mSC = "modelSourceConfig", _mSE = "modelSourceEquals", _mSI = "modelSourceIdentifier", _mSo = "modelStatus", _mSod = "modelSummaries", _mT = "messageType", _mTa = "maxTokens", _mTo = "modelTags", _mU = "modelUnits", _mWL = "managedWordLists", _mWLC = "managedWordListsConfig", _me = "messages", _mo = "models", _mu = "mutation", _n = "name", _nC = "nameContains", _nE = "notEquals", _nI = "notIn", _nL = "naturalLanguage", _nN = "newName", _nOR = "numberOfResults", _nORR = "numberOfRerankedResults", _nT = "nextToken", _nTo = "noTranslations", _nV = "newValue", _o = "owner", _oA = "outputAction", _oAI = "ownerAccountId", _oAr = "orAll", _oC = "orchestrationConfiguration", _oDC = "outputDataConfig", _oE = "outputEnabled", _oI = "offerId", _oM = "outputModalities", _oMA = "outputModelArn", _oMKKA = "outputModelKmsKeyArn", _oMN = "outputModelName", _oMNC = "outputModelNameContains", _oS = "outputStrength", _oST = "overrideSearchType", _oT = "offerToken", _oTf = "offerType", _of = "offers", _op = "options", _p = "premises", _pA = "policyArn", _pC = "performanceConfig", _pD = "policyDefinition", _pDR = "policyDefinitionRule", _pDT = "policyDefinitionType", _pDV = "policyDefinitionVariable", _pE = "priorElement", _pEAT = "publicExtendedAccessTime", _pEC = "piiEntitiesConfig", _pEi = "piiEntities", _pI = "policyId", _pIS = "precomputedInferenceSource", _pISI = "precomputedInferenceSourceIdentifiers", _pMA = "provisionedModelArn", _pMI = "provisionedModelId", _pMN = "provisionedModelName", _pMS = "provisionedModelSummaries", _pN = "pageNumber", _pNr = "providerName", _pRA = "promptRouterArn", _pRAo = "policyRepairAssets", _pRN = "promptRouterName", _pRS = "promptRouterSummaries", _pRSC = "precomputedRagSourceConfig", _pRSI = "precomputedRagSourceIdentifiers", _pS = "policyScenarios", _pT = "promptTemplate", _pV = "policyVariable", _pVA = "policyVersionArn", _pa = "pattern", _pl = "planning", _po = "policies", _pr = "price", _qC = "queryContent", _qR = "qualityReport", _qTC = "queryTransformationConfiguration", _r = "rule", _rA = "roleArn", _rAGC = "retrieveAndGenerateConfig", _rAGSC = "retrieveAndGenerateSourceConfig", _rARN = "resourceARN", _rAe = "regionAvailability", _rC = "ruleCount", _rCS = "ragConfigSummary", _rCa = "rateCard", _rCag = "ragConfigs", _rCe = "regexesConfig", _rCer = "rerankingConfiguration", _rCet = "retrievalConfiguration", _rCetr = "retrieveConfig", _rCf = "rftConfig", _rCo = "routingCriteria", _rE = "reasoningEffort", _rI = "ruleId", _rIa = "ragIdentifiers", _rIu = "ruleIds", _rM = "ratingMethod", _rMF = "requestMetadataFilters", _rN = "resourceName", _rPD = "refundPolicyDescription", _rQD = "responseQualityDifference", _rR = "ruleReports", _rS = "ratingScale", _rSC = "retrieveSourceConfig", _rSI = "ragSourceIdentifier", _rSS = "responseStreamingSupported", _re = "regexes", _ru = "rules", _s = "smithy.ts.sdk.synthetic.com.amazonaws.bedrock", _sAE = "sourceAccountEquals", _sAI = "sourceAccountId", _sB = "sortBy", _sBO = "s3BucketOwner", _sC = "s3Config", _sCo = "sourceContent", _sCt = "stringContains", _sD = "statusDetails", _sDS = "s3DataSource", _sE = "scenarioExpression", _sEKI = "s3EncryptionKeyId", _sEt = "statusEquals", _sGI = "securityGroupIds", _sI = "statementId", _sIDC = "s3InputDataConfig", _sIF = "s3InputFormat", _sIP = "sensitiveInformationPolicy", _sIPC = "sensitiveInformationPolicyConfig", _sIu = "subnetIds", _sL = "s3Location", _sM = "statusMessage", _sMA = "sourceModelArn", _sMAE = "sourceModelArnEquals", _sMC = "selectiveModeConfiguration", _sMN = "sourceModelName", _sMa = "sageMaker", _sMe = "selectionMode", _sO = "sortOrder", _sODC = "s3OutputDataConfig", _sOLT = "startOfLifeTime", _sR = "supportingRules", _sRt = "statusReasons", _sS = "stopSequences", _sT = "sourceType", _sTA = "submitTimeAfter", _sTB = "submitTimeBefore", _sTu = "submitTime", _sTup = "supportTerm", _sU = "s3Uri", _sV = "stringValue", _sW = "startsWith", _sa = "satisfiable", _sc = "scenario", _se = "server", _so = "sources", _st = "status", _sta = "statements", _t = "translation", _tA = "translationAmbiguous", _tC = "typeCount", _tCI = "testCaseId", _tCIe = "testCaseIds", _tCe = "testCase", _tCes = "testCases", _tCi = "tierConfig", _tCo = "topicsConfig", _tCoo = "tooComplex", _tD = "termDetails", _tDC = "trainingDataConfig", _tDDE = "textDataDeliveryEnabled", _tDIH = "timeoutDurationInHours", _tDr = "trainingDetails", _tE = "typeEquals", _tF = "testFindings", _tIC = "textInferenceConfig", _tK = "tagKeys", _tL = "trainingLoss", _tM = "trainingMetrics", _tMA = "targetModelArn", _tMC = "teacherModelConfig", _tMI = "teacherModelIdentifier", _tMKKA = "targetModelKmsKeyArn", _tMN = "targetModelName", _tMNC = "targetModelNameContains", _tMT = "targetModelTags", _tN = "typeName", _tNi = "tierName", _tP = "topicPolicy", _tPC = "topicPolicyConfig", _tPT = "textPromptTemplate", _tPo = "topP", _tR = "testResult", _tRR = "testRunResult", _tRS = "testRunStatus", _tRe = "testResults", _tSPP = "trainingSamplePerPrompt", _tT = "taskType", _ta = "tags", _te = "text", _tem = "temperature", _th = "threshold", _ti = "tier", _to = "topics", _tr = "translations", _ty = "type", _typ = "types", _u = "unit", _uA = "updatedAt", _uB = "updatedBy", _uBPT = "usageBasedPricingTerm", _uC = "untranslatedClaims", _uD = "updateDetails", _uFRF = "updateFromRulesFeedback", _uFSF = "updateFromScenarioFeedback", _uP = "untranslatedPremises", _uPR = "usePromptResponse", _uR = "updateRule", _uS = "updateStatus", _uT = "unusedTypes", _uTV = "unusedTypeValues", _uTVp = "updateTypeValue", _uTp = "updateType", _uV = "unusedVariables", _uVp = "updateVariable", _ur = "url", _uri = "uri", _v = "values", _vC = "variableCount", _vCp = "vpcConfig", _vD = "validationDetails", _vDC = "validationDataConfig", _vDDE = "videoDataDeliveryEnabled", _vL = "validationLoss", _vM = "validationMetrics", _vN = "valueName", _vR = "variableReports", _vSC = "vectorSearchConfiguration", _vT = "validityTerm", _va = "value", _val = "validators", _vali = "valid", _var = "variable", _vari = "variables", _ve = "version", _vp = "vpc", _w = "words", _wC = "workflowContent", _wCo = "wordsConfig", _wP = "wordPolicy", _wPC = "wordPolicyConfig", _xact = "x-amz-client-token", n0 = "com.amazonaws.bedrock", _s_registry, BedrockServiceException$, n0_registry, AccessDeniedException$, ConflictException$, InternalServerException$, ResourceInUseException$, ResourceNotFoundException$, ServiceQuotaExceededException$, ServiceUnavailableException$, ThrottlingException$, TooManyTagsException$, ValidationException$, errorTypeRegistries, AutomatedReasoningLogicStatementContent, AutomatedReasoningNaturalLanguageStatementContent, AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage, AutomatedReasoningPolicyAnnotationIngestContent, AutomatedReasoningPolicyAnnotationRuleNaturalLanguage, AutomatedReasoningPolicyBuildDocumentBlob, AutomatedReasoningPolicyBuildDocumentDescription, AutomatedReasoningPolicyBuildDocumentName, AutomatedReasoningPolicyBuildResultAssetName, AutomatedReasoningPolicyDefinitionRuleAlternateExpression, AutomatedReasoningPolicyDefinitionRuleExpression, AutomatedReasoningPolicyDefinitionTypeDescription, AutomatedReasoningPolicyDefinitionTypeName, AutomatedReasoningPolicyDefinitionTypeValueDescription, AutomatedReasoningPolicyDefinitionVariableDescription, AutomatedReasoningPolicyDefinitionVariableName, AutomatedReasoningPolicyDescription, AutomatedReasoningPolicyJustificationText, AutomatedReasoningPolicyLineText, AutomatedReasoningPolicyName, AutomatedReasoningPolicyScenarioAlternateExpression, AutomatedReasoningPolicyScenarioExpression, AutomatedReasoningPolicyStatementText, AutomatedReasoningPolicyTestGuardContent, AutomatedReasoningPolicyTestQueryContent, ByteContentBlob, EvaluationDatasetName, EvaluationJobDescription, EvaluationJobIdentifier, EvaluationMetricDescription, EvaluationMetricName, EvaluationModelInferenceParams, GuardrailBlockedMessaging, GuardrailContentFilterAction, GuardrailContentFiltersTierName, GuardrailContextualGroundingAction, GuardrailDescription, GuardrailFailureRecommendation, GuardrailModality, GuardrailName, GuardrailStatusReason, GuardrailTopicAction, GuardrailTopicDefinition, GuardrailTopicExample, GuardrailTopicName, GuardrailTopicsTierName, GuardrailWordAction, HumanTaskInstructions, Identifier, InferenceProfileDescription, Message, MetricName, PromptRouterDescription, TextPromptTemplate, AccountEnforcedGuardrailInferenceInputConfiguration$, AccountEnforcedGuardrailOutputConfiguration$, AgreementAvailability$, AutomatedEvaluationConfig$, AutomatedEvaluationCustomMetricConfig$, AutomatedReasoningCheckImpossibleFinding$, AutomatedReasoningCheckInputTextReference$, AutomatedReasoningCheckInvalidFinding$, AutomatedReasoningCheckLogicWarning$, AutomatedReasoningCheckNoTranslationsFinding$, AutomatedReasoningCheckRule$, AutomatedReasoningCheckSatisfiableFinding$, AutomatedReasoningCheckScenario$, AutomatedReasoningCheckTooComplexFinding$, AutomatedReasoningCheckTranslation$, AutomatedReasoningCheckTranslationAmbiguousFinding$, AutomatedReasoningCheckTranslationOption$, AutomatedReasoningCheckValidFinding$, AutomatedReasoningLogicStatement$, AutomatedReasoningPolicyAddRuleAnnotation$, AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation$, AutomatedReasoningPolicyAddRuleMutation$, AutomatedReasoningPolicyAddTypeAnnotation$, AutomatedReasoningPolicyAddTypeMutation$, AutomatedReasoningPolicyAddTypeValue$, AutomatedReasoningPolicyAddVariableAnnotation$, AutomatedReasoningPolicyAddVariableMutation$, AutomatedReasoningPolicyAnnotatedChunk$, AutomatedReasoningPolicyAnnotatedLine$, AutomatedReasoningPolicyAtomicStatement$, AutomatedReasoningPolicyBuildLog$, AutomatedReasoningPolicyBuildLogEntry$, AutomatedReasoningPolicyBuildResultAssetManifest$, AutomatedReasoningPolicyBuildResultAssetManifestEntry$, AutomatedReasoningPolicyBuildStep$, AutomatedReasoningPolicyBuildStepMessage$, AutomatedReasoningPolicyBuildWorkflowDocument$, AutomatedReasoningPolicyBuildWorkflowRepairContent$, AutomatedReasoningPolicyBuildWorkflowSource$, AutomatedReasoningPolicyBuildWorkflowSummary$, AutomatedReasoningPolicyDefinition$, AutomatedReasoningPolicyDefinitionQualityReport$, AutomatedReasoningPolicyDefinitionRule$, AutomatedReasoningPolicyDefinitionType$, AutomatedReasoningPolicyDefinitionTypeValue$, AutomatedReasoningPolicyDefinitionTypeValuePair$, AutomatedReasoningPolicyDefinitionVariable$, AutomatedReasoningPolicyDeleteRuleAnnotation$, AutomatedReasoningPolicyDeleteRuleMutation$, AutomatedReasoningPolicyDeleteTypeAnnotation$, AutomatedReasoningPolicyDeleteTypeMutation$, AutomatedReasoningPolicyDeleteTypeValue$, AutomatedReasoningPolicyDeleteVariableAnnotation$, AutomatedReasoningPolicyDeleteVariableMutation$, AutomatedReasoningPolicyDisjointRuleSet$, AutomatedReasoningPolicyFidelityReport$, AutomatedReasoningPolicyGeneratedTestCase$, AutomatedReasoningPolicyGeneratedTestCases$, AutomatedReasoningPolicyIngestContentAnnotation$, AutomatedReasoningPolicyPlanning$, AutomatedReasoningPolicyReportSourceDocument$, AutomatedReasoningPolicyRuleReport$, AutomatedReasoningPolicyScenario$, AutomatedReasoningPolicyScenarios$, AutomatedReasoningPolicySourceDocument$, AutomatedReasoningPolicyStatementLocation$, AutomatedReasoningPolicyStatementReference$, AutomatedReasoningPolicySummary$, AutomatedReasoningPolicyTestCase$, AutomatedReasoningPolicyTestResult$, AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation$, AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation$, AutomatedReasoningPolicyUpdateRuleAnnotation$, AutomatedReasoningPolicyUpdateRuleMutation$, AutomatedReasoningPolicyUpdateTypeAnnotation$, AutomatedReasoningPolicyUpdateTypeMutation$, AutomatedReasoningPolicyUpdateTypeValue$, AutomatedReasoningPolicyUpdateVariableAnnotation$, AutomatedReasoningPolicyUpdateVariableMutation$, AutomatedReasoningPolicyVariableReport$, BatchDeleteEvaluationJobError$, BatchDeleteEvaluationJobItem$, BatchDeleteEvaluationJobRequest$, BatchDeleteEvaluationJobResponse$, BedrockEvaluatorModel$, ByteContentDoc$, CancelAutomatedReasoningPolicyBuildWorkflowRequest$, CancelAutomatedReasoningPolicyBuildWorkflowResponse$, CloudWatchConfig$, CreateAutomatedReasoningPolicyRequest$, CreateAutomatedReasoningPolicyResponse$, CreateAutomatedReasoningPolicyTestCaseRequest$, CreateAutomatedReasoningPolicyTestCaseResponse$, CreateAutomatedReasoningPolicyVersionRequest$, CreateAutomatedReasoningPolicyVersionResponse$, CreateCustomModelDeploymentRequest$, CreateCustomModelDeploymentResponse$, CreateCustomModelRequest$, CreateCustomModelResponse$, CreateEvaluationJobRequest$, CreateEvaluationJobResponse$, CreateFoundationModelAgreementRequest$, CreateFoundationModelAgreementResponse$, CreateGuardrailRequest$, CreateGuardrailResponse$, CreateGuardrailVersionRequest$, CreateGuardrailVersionResponse$, CreateInferenceProfileRequest$, CreateInferenceProfileResponse$, CreateMarketplaceModelEndpointRequest$, CreateMarketplaceModelEndpointResponse$, CreateModelCopyJobRequest$, CreateModelCopyJobResponse$, CreateModelCustomizationJobRequest$, CreateModelCustomizationJobResponse$, CreateModelImportJobRequest$, CreateModelImportJobResponse$, CreateModelInvocationJobRequest$, CreateModelInvocationJobResponse$, CreatePromptRouterRequest$, CreatePromptRouterResponse$, CreateProvisionedModelThroughputRequest$, CreateProvisionedModelThroughputResponse$, CustomMetricBedrockEvaluatorModel$, CustomMetricDefinition$, CustomMetricEvaluatorModelConfig$, CustomModelDeploymentSummary$, CustomModelDeploymentUpdateDetails$, CustomModelSummary$, CustomModelUnits$, DataProcessingDetails$, DeleteAutomatedReasoningPolicyBuildWorkflowRequest$, DeleteAutomatedReasoningPolicyBuildWorkflowResponse$, DeleteAutomatedReasoningPolicyRequest$, DeleteAutomatedReasoningPolicyResponse$, DeleteAutomatedReasoningPolicyTestCaseRequest$, DeleteAutomatedReasoningPolicyTestCaseResponse$, DeleteCustomModelDeploymentRequest$, DeleteCustomModelDeploymentResponse$, DeleteCustomModelRequest$, DeleteCustomModelResponse$, DeleteEnforcedGuardrailConfigurationRequest$, DeleteEnforcedGuardrailConfigurationResponse$, DeleteFoundationModelAgreementRequest$, DeleteFoundationModelAgreementResponse$, DeleteGuardrailRequest$, DeleteGuardrailResponse$, DeleteImportedModelRequest$, DeleteImportedModelResponse$, DeleteInferenceProfileRequest$, DeleteInferenceProfileResponse$, DeleteMarketplaceModelEndpointRequest$, DeleteMarketplaceModelEndpointResponse$, DeleteModelInvocationLoggingConfigurationRequest$, DeleteModelInvocationLoggingConfigurationResponse$, DeletePromptRouterRequest$, DeletePromptRouterResponse$, DeleteProvisionedModelThroughputRequest$, DeleteProvisionedModelThroughputResponse$, DeregisterMarketplaceModelEndpointRequest$, DeregisterMarketplaceModelEndpointResponse$, DimensionalPriceRate$, DistillationConfig$, EvaluationBedrockModel$, EvaluationDataset$, EvaluationDatasetMetricConfig$, EvaluationInferenceConfigSummary$, EvaluationModelConfigSummary$, EvaluationOutputDataConfig$, EvaluationPrecomputedInferenceSource$, EvaluationPrecomputedRetrieveAndGenerateSourceConfig$, EvaluationPrecomputedRetrieveSourceConfig$, EvaluationRagConfigSummary$, EvaluationSummary$, ExportAutomatedReasoningPolicyVersionRequest$, ExportAutomatedReasoningPolicyVersionResponse$, ExternalSource$, ExternalSourcesGenerationConfiguration$, ExternalSourcesRetrieveAndGenerateConfiguration$, FieldForReranking$, FilterAttribute$, FoundationModelDetails$, FoundationModelLifecycle$, FoundationModelSummary$, GenerationConfiguration$, GetAutomatedReasoningPolicyAnnotationsRequest$, GetAutomatedReasoningPolicyAnnotationsResponse$, GetAutomatedReasoningPolicyBuildWorkflowRequest$, GetAutomatedReasoningPolicyBuildWorkflowResponse$, GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest$, GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse$, GetAutomatedReasoningPolicyNextScenarioRequest$, GetAutomatedReasoningPolicyNextScenarioResponse$, GetAutomatedReasoningPolicyRequest$, GetAutomatedReasoningPolicyResponse$, GetAutomatedReasoningPolicyTestCaseRequest$, GetAutomatedReasoningPolicyTestCaseResponse$, GetAutomatedReasoningPolicyTestResultRequest$, GetAutomatedReasoningPolicyTestResultResponse$, GetCustomModelDeploymentRequest$, GetCustomModelDeploymentResponse$, GetCustomModelRequest$, GetCustomModelResponse$, GetEvaluationJobRequest$, GetEvaluationJobResponse$, GetFoundationModelAvailabilityRequest$, GetFoundationModelAvailabilityResponse$, GetFoundationModelRequest$, GetFoundationModelResponse$, GetGuardrailRequest$, GetGuardrailResponse$, GetImportedModelRequest$, GetImportedModelResponse$, GetInferenceProfileRequest$, GetInferenceProfileResponse$, GetMarketplaceModelEndpointRequest$, GetMarketplaceModelEndpointResponse$, GetModelCopyJobRequest$, GetModelCopyJobResponse$, GetModelCustomizationJobRequest$, GetModelCustomizationJobResponse$, GetModelImportJobRequest$, GetModelImportJobResponse$, GetModelInvocationJobRequest$, GetModelInvocationJobResponse$, GetModelInvocationLoggingConfigurationRequest$, GetModelInvocationLoggingConfigurationResponse$, GetPromptRouterRequest$, GetPromptRouterResponse$, GetProvisionedModelThroughputRequest$, GetProvisionedModelThroughputResponse$, GetUseCaseForModelAccessRequest$, GetUseCaseForModelAccessResponse$, GuardrailAutomatedReasoningPolicy$, GuardrailAutomatedReasoningPolicyConfig$, GuardrailConfiguration$, GuardrailContentFilter$, GuardrailContentFilterConfig$, GuardrailContentFiltersTier$, GuardrailContentFiltersTierConfig$, GuardrailContentPolicy$, GuardrailContentPolicyConfig$, GuardrailContextualGroundingFilter$, GuardrailContextualGroundingFilterConfig$, GuardrailContextualGroundingPolicy$, GuardrailContextualGroundingPolicyConfig$, GuardrailCrossRegionConfig$, GuardrailCrossRegionDetails$, GuardrailManagedWords$, GuardrailManagedWordsConfig$, GuardrailPiiEntity$, GuardrailPiiEntityConfig$, GuardrailRegex$, GuardrailRegexConfig$, GuardrailSensitiveInformationPolicy$, GuardrailSensitiveInformationPolicyConfig$, GuardrailSummary$, GuardrailTopic$, GuardrailTopicConfig$, GuardrailTopicPolicy$, GuardrailTopicPolicyConfig$, GuardrailTopicsTier$, GuardrailTopicsTierConfig$, GuardrailWord$, GuardrailWordConfig$, GuardrailWordPolicy$, GuardrailWordPolicyConfig$, HumanEvaluationConfig$, HumanEvaluationCustomMetric$, HumanWorkflowConfig$, ImplicitFilterConfiguration$, ImportedModelSummary$, InferenceProfileModel$, InferenceProfileSummary$, InvocationLogsConfig$, KbInferenceConfig$, KnowledgeBaseRetrievalConfiguration$, KnowledgeBaseRetrieveAndGenerateConfiguration$, KnowledgeBaseVectorSearchConfiguration$, LambdaGraderConfig$, LegalTerm$, ListAutomatedReasoningPoliciesRequest$, ListAutomatedReasoningPoliciesResponse$, ListAutomatedReasoningPolicyBuildWorkflowsRequest$, ListAutomatedReasoningPolicyBuildWorkflowsResponse$, ListAutomatedReasoningPolicyTestCasesRequest$, ListAutomatedReasoningPolicyTestCasesResponse$, ListAutomatedReasoningPolicyTestResultsRequest$, ListAutomatedReasoningPolicyTestResultsResponse$, ListCustomModelDeploymentsRequest$, ListCustomModelDeploymentsResponse$, ListCustomModelsRequest$, ListCustomModelsResponse$, ListEnforcedGuardrailsConfigurationRequest$, ListEnforcedGuardrailsConfigurationResponse$, ListEvaluationJobsRequest$, ListEvaluationJobsResponse$, ListFoundationModelAgreementOffersRequest$, ListFoundationModelAgreementOffersResponse$, ListFoundationModelsRequest$, ListFoundationModelsResponse$, ListGuardrailsRequest$, ListGuardrailsResponse$, ListImportedModelsRequest$, ListImportedModelsResponse$, ListInferenceProfilesRequest$, ListInferenceProfilesResponse$, ListMarketplaceModelEndpointsRequest$, ListMarketplaceModelEndpointsResponse$, ListModelCopyJobsRequest$, ListModelCopyJobsResponse$, ListModelCustomizationJobsRequest$, ListModelCustomizationJobsResponse$, ListModelImportJobsRequest$, ListModelImportJobsResponse$, ListModelInvocationJobsRequest$, ListModelInvocationJobsResponse$, ListPromptRoutersRequest$, ListPromptRoutersResponse$, ListProvisionedModelThroughputsRequest$, ListProvisionedModelThroughputsResponse$, ListTagsForResourceRequest$, ListTagsForResourceResponse$, LoggingConfig$, MarketplaceModelEndpoint$, MarketplaceModelEndpointSummary$, MetadataAttributeSchema$, MetadataConfigurationForReranking$, ModelCopyJobSummary$, ModelCustomizationJobSummary$, ModelEnforcement$, ModelImportJobSummary$, ModelInvocationJobS3InputDataConfig$, ModelInvocationJobS3OutputDataConfig$, ModelInvocationJobSummary$, Offer$, OrchestrationConfiguration$, OutputDataConfig$, PerformanceConfiguration$, PricingTerm$, PromptRouterSummary$, PromptRouterTargetModel$, PromptTemplate$, ProvisionedModelSummary$, PutEnforcedGuardrailConfigurationRequest$, PutEnforcedGuardrailConfigurationResponse$, PutModelInvocationLoggingConfigurationRequest$, PutModelInvocationLoggingConfigurationResponse$, PutUseCaseForModelAccessRequest$, PutUseCaseForModelAccessResponse$, QueryTransformationConfiguration$, RatingScaleItem$, RegisterMarketplaceModelEndpointRequest$, RegisterMarketplaceModelEndpointResponse$, RequestMetadataBaseFilters$, RetrieveAndGenerateConfiguration$, RetrieveConfig$, RFTConfig$, RFTHyperParameters$, RoutingCriteria$, S3Config$, S3DataSource$, S3ObjectDoc$, SageMakerEndpoint$, StartAutomatedReasoningPolicyBuildWorkflowRequest$, StartAutomatedReasoningPolicyBuildWorkflowResponse$, StartAutomatedReasoningPolicyTestWorkflowRequest$, StartAutomatedReasoningPolicyTestWorkflowResponse$, StatusDetails$, StopEvaluationJobRequest$, StopEvaluationJobResponse$, StopModelCustomizationJobRequest$, StopModelCustomizationJobResponse$, StopModelInvocationJobRequest$, StopModelInvocationJobResponse$, SupportTerm$, Tag$, TagResourceRequest$, TagResourceResponse$, TeacherModelConfig$, TermDetails$, TextInferenceConfig$, TrainingDataConfig$, TrainingDetails$, TrainingMetrics$, UntagResourceRequest$, UntagResourceResponse$, UpdateAutomatedReasoningPolicyAnnotationsRequest$, UpdateAutomatedReasoningPolicyAnnotationsResponse$, UpdateAutomatedReasoningPolicyRequest$, UpdateAutomatedReasoningPolicyResponse$, UpdateAutomatedReasoningPolicyTestCaseRequest$, UpdateAutomatedReasoningPolicyTestCaseResponse$, UpdateCustomModelDeploymentRequest$, UpdateCustomModelDeploymentResponse$, UpdateGuardrailRequest$, UpdateGuardrailResponse$, UpdateMarketplaceModelEndpointRequest$, UpdateMarketplaceModelEndpointResponse$, UpdateProvisionedModelThroughputRequest$, UpdateProvisionedModelThroughputResponse$, ValidationDataConfig$, ValidationDetails$, Validator$, ValidatorMetric$, ValidityTerm$, VectorSearchBedrockRerankingConfiguration$, VectorSearchBedrockRerankingModelConfiguration$, VectorSearchRerankingConfiguration$, VpcConfig$, AccountEnforcedGuardrailsOutputConfiguration, AutomatedEvaluationCustomMetrics, AutomatedReasoningCheckDifferenceScenarioList, AutomatedReasoningCheckFindingList, AutomatedReasoningCheckInputTextReferenceList, AutomatedReasoningCheckRuleList, AutomatedReasoningCheckTranslationList, AutomatedReasoningCheckTranslationOptionList, AutomatedReasoningLogicStatementList, AutomatedReasoningPolicyAnnotatedChunkList, AutomatedReasoningPolicyAnnotatedContentList, AutomatedReasoningPolicyAnnotationList, AutomatedReasoningPolicyArnList, AutomatedReasoningPolicyAtomicStatementList, AutomatedReasoningPolicyBuildLogEntryList, AutomatedReasoningPolicyBuildResultAssetManifestList, AutomatedReasoningPolicyBuildStepList, AutomatedReasoningPolicyBuildStepMessageList, AutomatedReasoningPolicyBuildWorkflowDocumentList, AutomatedReasoningPolicyBuildWorkflowSummaries, AutomatedReasoningPolicyConflictedRuleIdList, AutomatedReasoningPolicyDefinitionRuleIdList, AutomatedReasoningPolicyDefinitionRuleList, AutomatedReasoningPolicyDefinitionTypeList, AutomatedReasoningPolicyDefinitionTypeNameList, AutomatedReasoningPolicyDefinitionTypeValueList, AutomatedReasoningPolicyDefinitionTypeValuePairList, AutomatedReasoningPolicyDefinitionVariableList, AutomatedReasoningPolicyDefinitionVariableNameList, AutomatedReasoningPolicyDisjointedRuleIdList, AutomatedReasoningPolicyDisjointRuleSetList, AutomatedReasoningPolicyGeneratedTestCaseList, AutomatedReasoningPolicyGenerateFidelityReportDocumentList, AutomatedReasoningPolicyJustificationList, AutomatedReasoningPolicyLineNumberList, AutomatedReasoningPolicyReportSourceDocumentList, AutomatedReasoningPolicyScenarioList, AutomatedReasoningPolicyStatementReferenceList, AutomatedReasoningPolicySummaries, AutomatedReasoningPolicyTestCaseIdList, AutomatedReasoningPolicyTestCaseList, AutomatedReasoningPolicyTestList, AutomatedReasoningPolicyTypeValueAnnotationList, BatchDeleteEvaluationJobErrors, BatchDeleteEvaluationJobItems, BedrockEvaluatorModels, CustomMetricBedrockEvaluatorModels, CustomModelDeploymentSummaryList, CustomModelSummaryList, ErrorMessages, EvaluationBedrockKnowledgeBaseIdentifiers, EvaluationBedrockModelIdentifiers, EvaluationDatasetMetricConfigs, EvaluationJobIdentifiers, EvaluationMetricNames, EvaluationModelConfigs, EvaluationPrecomputedInferenceSourceIdentifiers, EvaluationPrecomputedRagSourceIdentifiers, EvaluationSummaries, EvaluationTaskTypes, EvaluatorModelIdentifiers, ExcludedModelsList, ExternalSources, FieldsForReranking, FoundationModelSummaryList, GuardrailContentFilters, GuardrailContentFiltersConfig, GuardrailContextualGroundingFilters, GuardrailContextualGroundingFiltersConfig, GuardrailFailureRecommendations, GuardrailManagedWordLists, GuardrailManagedWordListsConfig, GuardrailModalities, GuardrailPiiEntities, GuardrailPiiEntitiesConfig, GuardrailRegexes, GuardrailRegexesConfig, GuardrailStatusReasons, GuardrailSummaries, GuardrailTopicExamples, GuardrailTopics, GuardrailTopicsConfig, GuardrailWords, GuardrailWordsConfig, HumanEvaluationCustomMetrics, ImportedModelSummaryList, IncludedModelsList, InferenceProfileModels, InferenceProfileSummaries, InferenceTypeList, MarketplaceModelEndpointSummaries, MetadataAttributeSchemaList, ModelCopyJobSummaries, ModelCustomizationJobSummaries, ModelCustomizationList, ModelImportJobSummaries, ModelInvocationJobSummaries, ModelModalityList, Offers, PromptRouterSummaries, PromptRouterTargetModels, ProvisionedModelSummaries, RagConfigs, RAGStopSequences, RateCard, RatingScale, RequestMetadataFiltersList, RetrievalFilterList, SecurityGroupIds, SubnetIds, TagKeyList, TagList, ValidationMetrics, Validators, AdditionalModelRequestFields, AutomatedReasoningPolicyRuleReportMap, AutomatedReasoningPolicyVariableReportMap, ModelCustomizationHyperParameters, RequestMetadataMap, AutomatedEvaluationCustomMetricSource$, AutomatedReasoningCheckFinding$, AutomatedReasoningPolicyAnnotatedContent$, AutomatedReasoningPolicyAnnotation$, AutomatedReasoningPolicyBuildResultAssets$, AutomatedReasoningPolicyBuildStepContext$, AutomatedReasoningPolicyDefinitionElement$, AutomatedReasoningPolicyGenerateFidelityReportContent$, AutomatedReasoningPolicyMutation$, AutomatedReasoningPolicyTypeValueAnnotation$, AutomatedReasoningPolicyWorkflowTypeContent$, CustomizationConfig$, EndpointConfig$, EvaluationConfig$, EvaluationDatasetLocation$, EvaluationInferenceConfig$, EvaluationModelConfig$, EvaluationPrecomputedRagSourceConfig$, EvaluatorModelConfig$, GraderConfig$, InferenceProfileModelSource$, InvocationLogSource$, KnowledgeBaseConfig$, ModelDataSource$, ModelInvocationJobInputDataConfig$, ModelInvocationJobOutputDataConfig$, RAGConfig$, RatingScaleItemValue$, RequestMetadataFilters$, RerankingMetadataSelectiveModeConfiguration$, RetrievalFilter$, BatchDeleteEvaluationJob$, CancelAutomatedReasoningPolicyBuildWorkflow$, CreateAutomatedReasoningPolicy$, CreateAutomatedReasoningPolicyTestCase$, CreateAutomatedReasoningPolicyVersion$, CreateCustomModel$, CreateCustomModelDeployment$, CreateEvaluationJob$, CreateFoundationModelAgreement$, CreateGuardrail$, CreateGuardrailVersion$, CreateInferenceProfile$, CreateMarketplaceModelEndpoint$, CreateModelCopyJob$, CreateModelCustomizationJob$, CreateModelImportJob$, CreateModelInvocationJob$, CreatePromptRouter$, CreateProvisionedModelThroughput$, DeleteAutomatedReasoningPolicy$, DeleteAutomatedReasoningPolicyBuildWorkflow$, DeleteAutomatedReasoningPolicyTestCase$, DeleteCustomModel$, DeleteCustomModelDeployment$, DeleteEnforcedGuardrailConfiguration$, DeleteFoundationModelAgreement$, DeleteGuardrail$, DeleteImportedModel$, DeleteInferenceProfile$, DeleteMarketplaceModelEndpoint$, DeleteModelInvocationLoggingConfiguration$, DeletePromptRouter$, DeleteProvisionedModelThroughput$, DeregisterMarketplaceModelEndpoint$, ExportAutomatedReasoningPolicyVersion$, GetAutomatedReasoningPolicy$, GetAutomatedReasoningPolicyAnnotations$, GetAutomatedReasoningPolicyBuildWorkflow$, GetAutomatedReasoningPolicyBuildWorkflowResultAssets$, GetAutomatedReasoningPolicyNextScenario$, GetAutomatedReasoningPolicyTestCase$, GetAutomatedReasoningPolicyTestResult$, GetCustomModel$, GetCustomModelDeployment$, GetEvaluationJob$, GetFoundationModel$, GetFoundationModelAvailability$, GetGuardrail$, GetImportedModel$, GetInferenceProfile$, GetMarketplaceModelEndpoint$, GetModelCopyJob$, GetModelCustomizationJob$, GetModelImportJob$, GetModelInvocationJob$, GetModelInvocationLoggingConfiguration$, GetPromptRouter$, GetProvisionedModelThroughput$, GetUseCaseForModelAccess$, ListAutomatedReasoningPolicies$, ListAutomatedReasoningPolicyBuildWorkflows$, ListAutomatedReasoningPolicyTestCases$, ListAutomatedReasoningPolicyTestResults$, ListCustomModelDeployments$, ListCustomModels$, ListEnforcedGuardrailsConfiguration$, ListEvaluationJobs$, ListFoundationModelAgreementOffers$, ListFoundationModels$, ListGuardrails$, ListImportedModels$, ListInferenceProfiles$, ListMarketplaceModelEndpoints$, ListModelCopyJobs$, ListModelCustomizationJobs$, ListModelImportJobs$, ListModelInvocationJobs$, ListPromptRouters$, ListProvisionedModelThroughputs$, ListTagsForResource$, PutEnforcedGuardrailConfiguration$, PutModelInvocationLoggingConfiguration$, PutUseCaseForModelAccess$, RegisterMarketplaceModelEndpoint$, StartAutomatedReasoningPolicyBuildWorkflow$, StartAutomatedReasoningPolicyTestWorkflow$, StopEvaluationJob$, StopModelCustomizationJob$, StopModelInvocationJob$, TagResource$, UntagResource$, UpdateAutomatedReasoningPolicy$, UpdateAutomatedReasoningPolicyAnnotations$, UpdateAutomatedReasoningPolicyTestCase$, UpdateCustomModelDeployment$, UpdateGuardrail$, UpdateMarketplaceModelEndpoint$, UpdateProvisionedModelThroughput$;
-var init_schemas_0 = __esm(() => {
- init_BedrockServiceException();
- init_errors4();
- import_schema3 = __toESM(require_schema(), 1);
- _s_registry = import_schema3.TypeRegistry.for(_s);
- BedrockServiceException$ = [-3, _s, "BedrockServiceException", 0, [], []];
- _s_registry.registerError(BedrockServiceException$, BedrockServiceException);
- n0_registry = import_schema3.TypeRegistry.for(n0);
- AccessDeniedException$ = [
- -3,
- n0,
- _ADE,
- { [_e]: _c, [_hE]: 403 },
- [_m],
- [0]
- ];
- n0_registry.registerError(AccessDeniedException$, AccessDeniedException);
- ConflictException$ = [
- -3,
- n0,
- _CE,
- { [_e]: _c, [_hE]: 400 },
- [_m],
- [0]
- ];
- n0_registry.registerError(ConflictException$, ConflictException);
- InternalServerException$ = [
- -3,
- n0,
- _ISE,
- { [_e]: _se, [_hE]: 500 },
- [_m],
- [0]
- ];
- n0_registry.registerError(InternalServerException$, InternalServerException);
- ResourceInUseException$ = [
- -3,
- n0,
- _RIUE,
- { [_e]: _c, [_hE]: 400 },
- [_m],
- [0]
- ];
- n0_registry.registerError(ResourceInUseException$, ResourceInUseException);
- ResourceNotFoundException$ = [
- -3,
- n0,
- _RNFE,
- { [_e]: _c, [_hE]: 404 },
- [_m],
- [0]
- ];
- n0_registry.registerError(ResourceNotFoundException$, ResourceNotFoundException);
- ServiceQuotaExceededException$ = [
- -3,
- n0,
- _SQEE,
- { [_e]: _c, [_hE]: 400 },
- [_m],
- [0]
- ];
- n0_registry.registerError(ServiceQuotaExceededException$, ServiceQuotaExceededException);
- ServiceUnavailableException$ = [
- -3,
- n0,
- _SUE,
- { [_e]: _se, [_hE]: 503 },
- [_m],
- [0]
- ];
- n0_registry.registerError(ServiceUnavailableException$, ServiceUnavailableException);
- ThrottlingException$ = [
- -3,
- n0,
- _TE,
- { [_e]: _c, [_hE]: 429 },
- [_m],
- [0]
- ];
- n0_registry.registerError(ThrottlingException$, ThrottlingException);
- TooManyTagsException$ = [
- -3,
- n0,
- _TMTE,
- { [_e]: _c, [_hE]: 400 },
- [_m, _rN],
- [0, 0]
- ];
- n0_registry.registerError(TooManyTagsException$, TooManyTagsException);
- ValidationException$ = [
- -3,
- n0,
- _VE,
- { [_e]: _c, [_hE]: 400 },
- [_m],
- [0]
- ];
- n0_registry.registerError(ValidationException$, ValidationException);
- errorTypeRegistries = [
- _s_registry,
- n0_registry
- ];
- AutomatedReasoningLogicStatementContent = [0, n0, _ARLSC, 8, 0];
- AutomatedReasoningNaturalLanguageStatementContent = [0, n0, _ARNLSC, 8, 0];
- AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage = [0, n0, _ARPAFNL, 8, 0];
- AutomatedReasoningPolicyAnnotationIngestContent = [0, n0, _ARPAIC, 8, 0];
- AutomatedReasoningPolicyAnnotationRuleNaturalLanguage = [0, n0, _ARPARNL, 8, 0];
- AutomatedReasoningPolicyBuildDocumentBlob = [0, n0, _ARPBDB, 8, 21];
- AutomatedReasoningPolicyBuildDocumentDescription = [0, n0, _ARPBDD, 8, 0];
- AutomatedReasoningPolicyBuildDocumentName = [0, n0, _ARPBDN, 8, 0];
- AutomatedReasoningPolicyBuildResultAssetName = [0, n0, _ARPBRAN, 8, 0];
- AutomatedReasoningPolicyDefinitionRuleAlternateExpression = [0, n0, _ARPDRAE, 8, 0];
- AutomatedReasoningPolicyDefinitionRuleExpression = [0, n0, _ARPDRE, 8, 0];
- AutomatedReasoningPolicyDefinitionTypeDescription = [0, n0, _ARPDTD, 8, 0];
- AutomatedReasoningPolicyDefinitionTypeName = [0, n0, _ARPDTN, 8, 0];
- AutomatedReasoningPolicyDefinitionTypeValueDescription = [0, n0, _ARPDTVD, 8, 0];
- AutomatedReasoningPolicyDefinitionVariableDescription = [0, n0, _ARPDVD, 8, 0];
- AutomatedReasoningPolicyDefinitionVariableName = [0, n0, _ARPDVN, 8, 0];
- AutomatedReasoningPolicyDescription = [0, n0, _ARPD, 8, 0];
- AutomatedReasoningPolicyJustificationText = [0, n0, _ARPJT, 8, 0];
- AutomatedReasoningPolicyLineText = [0, n0, _ARPLT, 8, 0];
- AutomatedReasoningPolicyName = [0, n0, _ARPN, 8, 0];
- AutomatedReasoningPolicyScenarioAlternateExpression = [0, n0, _ARPSAE, 8, 0];
- AutomatedReasoningPolicyScenarioExpression = [0, n0, _ARPSE, 8, 0];
- AutomatedReasoningPolicyStatementText = [0, n0, _ARPST, 8, 0];
- AutomatedReasoningPolicyTestGuardContent = [0, n0, _ARPTGC, 8, 0];
- AutomatedReasoningPolicyTestQueryContent = [0, n0, _ARPTQC, 8, 0];
- ByteContentBlob = [0, n0, _BCB, 8, 21];
- EvaluationDatasetName = [0, n0, _EDN, 8, 0];
- EvaluationJobDescription = [0, n0, _EJD, 8, 0];
- EvaluationJobIdentifier = [0, n0, _EJI, 8, 0];
- EvaluationMetricDescription = [0, n0, _EMD, 8, 0];
- EvaluationMetricName = [0, n0, _EMN, 8, 0];
- EvaluationModelInferenceParams = [0, n0, _EMIP, 8, 0];
- GuardrailBlockedMessaging = [0, n0, _GBM, 8, 0];
- GuardrailContentFilterAction = [0, n0, _GCFA, 8, 0];
- GuardrailContentFiltersTierName = [0, n0, _GCFTN, 8, 0];
- GuardrailContextualGroundingAction = [0, n0, _GCGA, 8, 0];
- GuardrailDescription = [0, n0, _GD, 8, 0];
- GuardrailFailureRecommendation = [0, n0, _GFR, 8, 0];
- GuardrailModality = [0, n0, _GM, 8, 0];
- GuardrailName = [0, n0, _GN, 8, 0];
- GuardrailStatusReason = [0, n0, _GSR, 8, 0];
- GuardrailTopicAction = [0, n0, _GTA, 8, 0];
- GuardrailTopicDefinition = [0, n0, _GTD, 8, 0];
- GuardrailTopicExample = [0, n0, _GTE, 8, 0];
- GuardrailTopicName = [0, n0, _GTN, 8, 0];
- GuardrailTopicsTierName = [0, n0, _GTTN, 8, 0];
- GuardrailWordAction = [0, n0, _GWA, 8, 0];
- HumanTaskInstructions = [0, n0, _HTI, 8, 0];
- Identifier = [0, n0, _I, 8, 0];
- InferenceProfileDescription = [0, n0, _IPD, 8, 0];
- Message = [0, n0, _M, 8, 0];
- MetricName = [0, n0, _MN, 8, 0];
- PromptRouterDescription = [0, n0, _PRD, 8, 0];
- TextPromptTemplate = [0, n0, _TPT, 8, 0];
- AccountEnforcedGuardrailInferenceInputConfiguration$ = [
- 3,
- n0,
- _AEGIIC,
- 0,
- [_gI, _gV, _iT, _mE],
- [0, 0, 0, () => ModelEnforcement$],
- 3
- ];
- AccountEnforcedGuardrailOutputConfiguration$ = [
- 3,
- n0,
- _AEGOC,
- 0,
- [_cI, _gA, _gIu, _iT, _gV, _cA, _cB, _uA, _uB, _o, _mE],
- [0, 0, 0, 0, 0, 5, 0, 5, 0, 0, () => ModelEnforcement$]
- ];
- AgreementAvailability$ = [
- 3,
- n0,
- _AA,
- 0,
- [_st, _eM],
- [0, 0],
- 1
- ];
- AutomatedEvaluationConfig$ = [
- 3,
- n0,
- _AEC,
- 0,
- [_dMC, _eMC, _cMC],
- [[() => EvaluationDatasetMetricConfigs, 0], () => EvaluatorModelConfig$, [() => AutomatedEvaluationCustomMetricConfig$, 0]],
- 1
- ];
- AutomatedEvaluationCustomMetricConfig$ = [
- 3,
- n0,
- _AECMC,
- 0,
- [_cM, _eMC],
- [[() => AutomatedEvaluationCustomMetrics, 0], () => CustomMetricEvaluatorModelConfig$],
- 2
- ];
- AutomatedReasoningCheckImpossibleFinding$ = [
- 3,
- n0,
- _ARCIF,
- 0,
- [_t, _cR, _lW],
- [[() => AutomatedReasoningCheckTranslation$, 0], () => AutomatedReasoningCheckRuleList, [() => AutomatedReasoningCheckLogicWarning$, 0]]
- ];
- AutomatedReasoningCheckInputTextReference$ = [
- 3,
- n0,
- _ARCITR,
- 0,
- [_te],
- [[() => AutomatedReasoningNaturalLanguageStatementContent, 0]]
- ];
- AutomatedReasoningCheckInvalidFinding$ = [
- 3,
- n0,
- _ARCIFu,
- 0,
- [_t, _cR, _lW],
- [[() => AutomatedReasoningCheckTranslation$, 0], () => AutomatedReasoningCheckRuleList, [() => AutomatedReasoningCheckLogicWarning$, 0]]
- ];
- AutomatedReasoningCheckLogicWarning$ = [
- 3,
- n0,
- _ARCLW,
- 0,
- [_ty, _p, _cl],
- [0, [() => AutomatedReasoningLogicStatementList, 0], [() => AutomatedReasoningLogicStatementList, 0]]
- ];
- AutomatedReasoningCheckNoTranslationsFinding$ = [
- 3,
- n0,
- _ARCNTF,
- 0,
- [],
- []
- ];
- AutomatedReasoningCheckRule$ = [
- 3,
- n0,
- _ARCR,
- 0,
- [_i, _pVA],
- [0, 0]
- ];
- AutomatedReasoningCheckSatisfiableFinding$ = [
- 3,
- n0,
- _ARCSF,
- 0,
- [_t, _cTS, _cFS, _lW],
- [[() => AutomatedReasoningCheckTranslation$, 0], [() => AutomatedReasoningCheckScenario$, 0], [() => AutomatedReasoningCheckScenario$, 0], [() => AutomatedReasoningCheckLogicWarning$, 0]]
- ];
- AutomatedReasoningCheckScenario$ = [
- 3,
- n0,
- _ARCS,
- 0,
- [_sta],
- [[() => AutomatedReasoningLogicStatementList, 0]]
- ];
- AutomatedReasoningCheckTooComplexFinding$ = [
- 3,
- n0,
- _ARCTCF,
- 0,
- [],
- []
- ];
- AutomatedReasoningCheckTranslation$ = [
- 3,
- n0,
- _ARCT,
- 0,
- [_cl, _co, _p, _uP, _uC],
- [[() => AutomatedReasoningLogicStatementList, 0], 1, [() => AutomatedReasoningLogicStatementList, 0], [() => AutomatedReasoningCheckInputTextReferenceList, 0], [() => AutomatedReasoningCheckInputTextReferenceList, 0]],
- 2
- ];
- AutomatedReasoningCheckTranslationAmbiguousFinding$ = [
- 3,
- n0,
- _ARCTAF,
- 0,
- [_op, _dS],
- [[() => AutomatedReasoningCheckTranslationOptionList, 0], [() => AutomatedReasoningCheckDifferenceScenarioList, 0]]
- ];
- AutomatedReasoningCheckTranslationOption$ = [
- 3,
- n0,
- _ARCTO,
- 0,
- [_tr],
- [[() => AutomatedReasoningCheckTranslationList, 0]]
- ];
- AutomatedReasoningCheckValidFinding$ = [
- 3,
- n0,
- _ARCVF,
- 0,
- [_t, _cTS, _sR, _lW],
- [[() => AutomatedReasoningCheckTranslation$, 0], [() => AutomatedReasoningCheckScenario$, 0], () => AutomatedReasoningCheckRuleList, [() => AutomatedReasoningCheckLogicWarning$, 0]]
- ];
- AutomatedReasoningLogicStatement$ = [
- 3,
- n0,
- _ARLS,
- 0,
- [_l, _nL],
- [[() => AutomatedReasoningLogicStatementContent, 0], [() => AutomatedReasoningNaturalLanguageStatementContent, 0]],
- 1
- ];
- AutomatedReasoningPolicyAddRuleAnnotation$ = [
- 3,
- n0,
- _ARPARA,
- 0,
- [_ex],
- [[() => AutomatedReasoningPolicyDefinitionRuleExpression, 0]],
- 1
- ];
- AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation$ = [
- 3,
- n0,
- _ARPARFNLA,
- 0,
- [_nL],
- [[() => AutomatedReasoningPolicyAnnotationRuleNaturalLanguage, 0]],
- 1
- ];
- AutomatedReasoningPolicyAddRuleMutation$ = [
- 3,
- n0,
- _ARPARM,
- 0,
- [_r],
- [[() => AutomatedReasoningPolicyDefinitionRule$, 0]],
- 1
- ];
- AutomatedReasoningPolicyAddTypeAnnotation$ = [
- 3,
- n0,
- _ARPATA,
- 0,
- [_n, _d, _v],
- [[() => AutomatedReasoningPolicyDefinitionTypeName, 0], [() => AutomatedReasoningPolicyDefinitionTypeDescription, 0], [() => AutomatedReasoningPolicyDefinitionTypeValueList, 0]],
- 3
- ];
- AutomatedReasoningPolicyAddTypeMutation$ = [
- 3,
- n0,
- _ARPATM,
- 0,
- [_ty],
- [[() => AutomatedReasoningPolicyDefinitionType$, 0]],
- 1
- ];
- AutomatedReasoningPolicyAddTypeValue$ = [
- 3,
- n0,
- _ARPATV,
- 0,
- [_va, _d],
- [0, [() => AutomatedReasoningPolicyDefinitionTypeValueDescription, 0]],
- 1
- ];
- AutomatedReasoningPolicyAddVariableAnnotation$ = [
- 3,
- n0,
- _ARPAVA,
- 0,
- [_n, _ty, _d],
- [[() => AutomatedReasoningPolicyDefinitionVariableName, 0], [() => AutomatedReasoningPolicyDefinitionTypeName, 0], [() => AutomatedReasoningPolicyDefinitionVariableDescription, 0]],
- 3
- ];
- AutomatedReasoningPolicyAddVariableMutation$ = [
- 3,
- n0,
- _ARPAVM,
- 0,
- [_var],
- [[() => AutomatedReasoningPolicyDefinitionVariable$, 0]],
- 1
- ];
- AutomatedReasoningPolicyAnnotatedChunk$ = [
- 3,
- n0,
- _ARPAC,
- 0,
- [_con, _pN],
- [[() => AutomatedReasoningPolicyAnnotatedContentList, 0], 1],
- 1
- ];
- AutomatedReasoningPolicyAnnotatedLine$ = [
- 3,
- n0,
- _ARPAL,
- 0,
- [_lN, _lT],
- [1, [() => AutomatedReasoningPolicyLineText, 0]]
- ];
- AutomatedReasoningPolicyAtomicStatement$ = [
- 3,
- n0,
- _ARPAS,
- 0,
- [_i, _te, _lo],
- [0, [() => AutomatedReasoningPolicyStatementText, 0], () => AutomatedReasoningPolicyStatementLocation$],
- 3
- ];
- AutomatedReasoningPolicyBuildLog$ = [
- 3,
- n0,
- _ARPBL,
- 0,
- [_en],
- [[() => AutomatedReasoningPolicyBuildLogEntryList, 0]],
- 1
- ];
- AutomatedReasoningPolicyBuildLogEntry$ = [
- 3,
- n0,
- _ARPBLE,
- 0,
- [_a2, _st, _bS],
- [[() => AutomatedReasoningPolicyAnnotation$, 0], 0, [() => AutomatedReasoningPolicyBuildStepList, 0]],
- 3
- ];
- AutomatedReasoningPolicyBuildResultAssetManifest$ = [
- 3,
- n0,
- _ARPBRAM,
- 0,
- [_en],
- [[() => AutomatedReasoningPolicyBuildResultAssetManifestList, 0]],
- 1
- ];
- AutomatedReasoningPolicyBuildResultAssetManifestEntry$ = [
- 3,
- n0,
- _ARPBRAME,
- 0,
- [_aT, _aN, _aI],
- [0, [() => AutomatedReasoningPolicyBuildResultAssetName, 0], 0],
- 1
- ];
- AutomatedReasoningPolicyBuildStep$ = [
- 3,
- n0,
- _ARPBS,
- 0,
- [_cont, _me, _pE],
- [[() => AutomatedReasoningPolicyBuildStepContext$, 0], () => AutomatedReasoningPolicyBuildStepMessageList, [() => AutomatedReasoningPolicyDefinitionElement$, 0]],
- 2
- ];
- AutomatedReasoningPolicyBuildStepMessage$ = [
- 3,
- n0,
- _ARPBSM,
- 0,
- [_m, _mT],
- [0, 0],
- 2
- ];
- AutomatedReasoningPolicyBuildWorkflowDocument$ = [
- 3,
- n0,
- _ARPBWD,
- 0,
- [_do, _dCT, _dN, _dD],
- [[() => AutomatedReasoningPolicyBuildDocumentBlob, 0], 0, [() => AutomatedReasoningPolicyBuildDocumentName, 0], [() => AutomatedReasoningPolicyBuildDocumentDescription, 0]],
- 3
- ];
- AutomatedReasoningPolicyBuildWorkflowRepairContent$ = [
- 3,
- n0,
- _ARPBWRC,
- 0,
- [_an],
- [[() => AutomatedReasoningPolicyAnnotationList, 0]],
- 1
- ];
- AutomatedReasoningPolicyBuildWorkflowSource$ = [
- 3,
- n0,
- _ARPBWS,
- 0,
- [_pD, _wC],
- [[() => AutomatedReasoningPolicyDefinition$, 0], [() => AutomatedReasoningPolicyWorkflowTypeContent$, 0]]
- ];
- AutomatedReasoningPolicyBuildWorkflowSummary$ = [
- 3,
- n0,
- _ARPBWSu,
- 0,
- [_pA, _bWI, _st, _bWT, _cA, _uA],
- [0, 0, 0, 0, 5, 5],
- 6
- ];
- AutomatedReasoningPolicyDefinition$ = [
- 3,
- n0,
- _ARPDu,
- 0,
- [_ve, _typ, _ru, _vari],
- [0, [() => AutomatedReasoningPolicyDefinitionTypeList, 0], [() => AutomatedReasoningPolicyDefinitionRuleList, 0], [() => AutomatedReasoningPolicyDefinitionVariableList, 0]]
- ];
- AutomatedReasoningPolicyDefinitionQualityReport$ = [
- 3,
- n0,
- _ARPDQR,
- 0,
- [_tC, _vC, _rC, _uT, _uTV, _uV, _cRo, _dRS],
- [1, 1, 1, [() => AutomatedReasoningPolicyDefinitionTypeNameList, 0], [() => AutomatedReasoningPolicyDefinitionTypeValuePairList, 0], [() => AutomatedReasoningPolicyDefinitionVariableNameList, 0], 64 | 0, [() => AutomatedReasoningPolicyDisjointRuleSetList, 0]],
- 8
- ];
- AutomatedReasoningPolicyDefinitionRule$ = [
- 3,
- n0,
- _ARPDR,
- 0,
- [_i, _ex, _aE],
- [0, [() => AutomatedReasoningPolicyDefinitionRuleExpression, 0], [() => AutomatedReasoningPolicyDefinitionRuleAlternateExpression, 0]],
- 2
- ];
- AutomatedReasoningPolicyDefinitionType$ = [
- 3,
- n0,
- _ARPDT,
- 0,
- [_n, _v, _d],
- [[() => AutomatedReasoningPolicyDefinitionTypeName, 0], [() => AutomatedReasoningPolicyDefinitionTypeValueList, 0], [() => AutomatedReasoningPolicyDefinitionTypeDescription, 0]],
- 2
- ];
- AutomatedReasoningPolicyDefinitionTypeValue$ = [
- 3,
- n0,
- _ARPDTV,
- 0,
- [_va, _d],
- [0, [() => AutomatedReasoningPolicyDefinitionTypeValueDescription, 0]],
- 1
- ];
- AutomatedReasoningPolicyDefinitionTypeValuePair$ = [
- 3,
- n0,
- _ARPDTVP,
- 0,
- [_tN, _vN],
- [[() => AutomatedReasoningPolicyDefinitionTypeName, 0], 0],
- 2
- ];
- AutomatedReasoningPolicyDefinitionVariable$ = [
- 3,
- n0,
- _ARPDV,
- 0,
- [_n, _ty, _d],
- [[() => AutomatedReasoningPolicyDefinitionVariableName, 0], [() => AutomatedReasoningPolicyDefinitionTypeName, 0], [() => AutomatedReasoningPolicyDefinitionVariableDescription, 0]],
- 3
- ];
- AutomatedReasoningPolicyDeleteRuleAnnotation$ = [
- 3,
- n0,
- _ARPDRA,
- 0,
- [_rI],
- [0],
- 1
- ];
- AutomatedReasoningPolicyDeleteRuleMutation$ = [
- 3,
- n0,
- _ARPDRM,
- 0,
- [_i],
- [0],
- 1
- ];
- AutomatedReasoningPolicyDeleteTypeAnnotation$ = [
- 3,
- n0,
- _ARPDTA,
- 0,
- [_n],
- [[() => AutomatedReasoningPolicyDefinitionTypeName, 0]],
- 1
- ];
- AutomatedReasoningPolicyDeleteTypeMutation$ = [
- 3,
- n0,
- _ARPDTM,
- 0,
- [_n],
- [[() => AutomatedReasoningPolicyDefinitionTypeName, 0]],
- 1
- ];
- AutomatedReasoningPolicyDeleteTypeValue$ = [
- 3,
- n0,
- _ARPDTVu,
- 0,
- [_va],
- [0],
- 1
- ];
- AutomatedReasoningPolicyDeleteVariableAnnotation$ = [
- 3,
- n0,
- _ARPDVA,
- 0,
- [_n],
- [[() => AutomatedReasoningPolicyDefinitionVariableName, 0]],
- 1
- ];
- AutomatedReasoningPolicyDeleteVariableMutation$ = [
- 3,
- n0,
- _ARPDVM,
- 0,
- [_n],
- [[() => AutomatedReasoningPolicyDefinitionVariableName, 0]],
- 1
- ];
- AutomatedReasoningPolicyDisjointRuleSet$ = [
- 3,
- n0,
- _ARPDRS,
- 0,
- [_vari, _ru],
- [[() => AutomatedReasoningPolicyDefinitionVariableNameList, 0], 64 | 0],
- 2
- ];
- AutomatedReasoningPolicyFidelityReport$ = [
- 3,
- n0,
- _ARPFR,
- 0,
- [_cS, _aS, _rR, _vR, _dSo],
- [1, 1, [() => AutomatedReasoningPolicyRuleReportMap, 0], [() => AutomatedReasoningPolicyVariableReportMap, 0], [() => AutomatedReasoningPolicyReportSourceDocumentList, 0]],
- 5
- ];
- AutomatedReasoningPolicyGeneratedTestCase$ = [
- 3,
- n0,
- _ARPGTC,
- 0,
- [_qC, _gC, _eAFR],
- [[() => AutomatedReasoningPolicyTestQueryContent, 0], [() => AutomatedReasoningPolicyTestGuardContent, 0], 0],
- 3
- ];
- AutomatedReasoningPolicyGeneratedTestCases$ = [
- 3,
- n0,
- _ARPGTCu,
- 0,
- [_gTC],
- [[() => AutomatedReasoningPolicyGeneratedTestCaseList, 0]],
- 1
- ];
- AutomatedReasoningPolicyIngestContentAnnotation$ = [
- 3,
- n0,
- _ARPICA,
- 0,
- [_con],
- [[() => AutomatedReasoningPolicyAnnotationIngestContent, 0]],
- 1
- ];
- AutomatedReasoningPolicyPlanning$ = [
- 3,
- n0,
- _ARPP,
- 0,
- [],
- []
- ];
- AutomatedReasoningPolicyReportSourceDocument$ = [
- 3,
- n0,
- _ARPRSD,
- 0,
- [_dN, _dH, _dI, _aSt, _dC],
- [[() => AutomatedReasoningPolicyBuildDocumentName, 0], 0, 0, [() => AutomatedReasoningPolicyAtomicStatementList, 0], [() => AutomatedReasoningPolicyAnnotatedChunkList, 0]],
- 5
- ];
- AutomatedReasoningPolicyRuleReport$ = [
- 3,
- n0,
- _ARPRR,
- 0,
- [_r, _gS, _gJ, _aS, _aJ],
- [0, () => AutomatedReasoningPolicyStatementReferenceList, [() => AutomatedReasoningPolicyJustificationList, 0], 1, [() => AutomatedReasoningPolicyJustificationText, 0]],
- 1
- ];
- AutomatedReasoningPolicyScenario$ = [
- 3,
- n0,
- _ARPS,
- 0,
- [_ex, _aE, _eR, _rIu],
- [[() => AutomatedReasoningPolicyScenarioExpression, 0], [() => AutomatedReasoningPolicyScenarioAlternateExpression, 0], 0, 64 | 0],
- 4
- ];
- AutomatedReasoningPolicyScenarios$ = [
- 3,
- n0,
- _ARPSu,
- 0,
- [_pS],
- [[() => AutomatedReasoningPolicyScenarioList, 0]],
- 1
- ];
- AutomatedReasoningPolicySourceDocument$ = [
- 3,
- n0,
- _ARPSD,
- 0,
- [_do, _dCT, _dN, _dH, _dD],
- [[() => AutomatedReasoningPolicyBuildDocumentBlob, 0], 0, [() => AutomatedReasoningPolicyBuildDocumentName, 0], 0, [() => AutomatedReasoningPolicyBuildDocumentDescription, 0]],
- 4
- ];
- AutomatedReasoningPolicyStatementLocation$ = [
- 3,
- n0,
- _ARPSL,
- 0,
- [_li],
- [64 | 1],
- 1
- ];
- AutomatedReasoningPolicyStatementReference$ = [
- 3,
- n0,
- _ARPSR,
- 0,
- [_dI, _sI],
- [0, 0],
- 2
- ];
- AutomatedReasoningPolicySummary$ = [
- 3,
- n0,
- _ARPSut,
- 0,
- [_pA, _n, _ve, _pI, _cA, _uA, _d],
- [0, [() => AutomatedReasoningPolicyName, 0], 0, 0, 5, 5, [() => AutomatedReasoningPolicyDescription, 0]],
- 6
- ];
- AutomatedReasoningPolicyTestCase$ = [
- 3,
- n0,
- _ARPTC,
- 0,
- [_tCI, _gC, _cA, _uA, _qC, _eAFR, _cT],
- [0, [() => AutomatedReasoningPolicyTestGuardContent, 0], 5, 5, [() => AutomatedReasoningPolicyTestQueryContent, 0], 0, 1],
- 4
- ];
- AutomatedReasoningPolicyTestResult$ = [
- 3,
- n0,
- _ARPTR,
- 0,
- [_tCe, _pA, _tRS, _uA, _tF, _tRR, _aTFR],
- [[() => AutomatedReasoningPolicyTestCase$, 0], 0, 0, 5, [() => AutomatedReasoningCheckFindingList, 0], 0, 0],
- 4
- ];
- AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation$ = [
- 3,
- n0,
- _ARPUFRFA,
- 0,
- [_f, _rIu],
- [[() => AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage, 0], 64 | 0],
- 1
- ];
- AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation$ = [
- 3,
- n0,
- _ARPUFSFA,
- 0,
- [_sE, _rIu, _f],
- [[() => AutomatedReasoningPolicyScenarioExpression, 0], 64 | 0, [() => AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage, 0]],
- 1
- ];
- AutomatedReasoningPolicyUpdateRuleAnnotation$ = [
- 3,
- n0,
- _ARPURA,
- 0,
- [_rI, _ex],
- [0, [() => AutomatedReasoningPolicyDefinitionRuleExpression, 0]],
- 2
- ];
- AutomatedReasoningPolicyUpdateRuleMutation$ = [
- 3,
- n0,
- _ARPURM,
- 0,
- [_r],
- [[() => AutomatedReasoningPolicyDefinitionRule$, 0]],
- 1
- ];
- AutomatedReasoningPolicyUpdateTypeAnnotation$ = [
- 3,
- n0,
- _ARPUTA,
- 0,
- [_n, _v, _nN, _d],
- [[() => AutomatedReasoningPolicyDefinitionTypeName, 0], [() => AutomatedReasoningPolicyTypeValueAnnotationList, 0], [() => AutomatedReasoningPolicyDefinitionTypeName, 0], [() => AutomatedReasoningPolicyDefinitionTypeDescription, 0]],
- 2
- ];
- AutomatedReasoningPolicyUpdateTypeMutation$ = [
- 3,
- n0,
- _ARPUTM,
- 0,
- [_ty],
- [[() => AutomatedReasoningPolicyDefinitionType$, 0]],
- 1
- ];
- AutomatedReasoningPolicyUpdateTypeValue$ = [
- 3,
- n0,
- _ARPUTV,
- 0,
- [_va, _nV, _d],
- [0, 0, [() => AutomatedReasoningPolicyDefinitionTypeValueDescription, 0]],
- 1
- ];
- AutomatedReasoningPolicyUpdateVariableAnnotation$ = [
- 3,
- n0,
- _ARPUVA,
- 0,
- [_n, _nN, _d],
- [[() => AutomatedReasoningPolicyDefinitionVariableName, 0], [() => AutomatedReasoningPolicyDefinitionVariableName, 0], [() => AutomatedReasoningPolicyDefinitionVariableDescription, 0]],
- 1
- ];
- AutomatedReasoningPolicyUpdateVariableMutation$ = [
- 3,
- n0,
- _ARPUVM,
- 0,
- [_var],
- [[() => AutomatedReasoningPolicyDefinitionVariable$, 0]],
- 1
- ];
- AutomatedReasoningPolicyVariableReport$ = [
- 3,
- n0,
- _ARPVR,
- 0,
- [_pV, _gS, _gJ, _aS, _aJ],
- [[() => AutomatedReasoningPolicyDefinitionVariableName, 0], () => AutomatedReasoningPolicyStatementReferenceList, [() => AutomatedReasoningPolicyJustificationList, 0], 1, [() => AutomatedReasoningPolicyJustificationText, 0]],
- 1
- ];
- BatchDeleteEvaluationJobError$ = [
- 3,
- n0,
- _BDEJE,
- 0,
- [_jI, _cod, _m],
- [[() => EvaluationJobIdentifier, 0], 0, 0],
- 2
- ];
- BatchDeleteEvaluationJobItem$ = [
- 3,
- n0,
- _BDEJI,
- 0,
- [_jI, _jS],
- [[() => EvaluationJobIdentifier, 0], 0],
- 2
- ];
- BatchDeleteEvaluationJobRequest$ = [
- 3,
- n0,
- _BDEJR,
- 0,
- [_jIo],
- [[() => EvaluationJobIdentifiers, 0]],
- 1
- ];
- BatchDeleteEvaluationJobResponse$ = [
- 3,
- n0,
- _BDEJRa,
- 0,
- [_er, _eJ],
- [[() => BatchDeleteEvaluationJobErrors, 0], [() => BatchDeleteEvaluationJobItems, 0]],
- 2
- ];
- BedrockEvaluatorModel$ = [
- 3,
- n0,
- _BEM,
- 0,
- [_mI],
- [0],
- 1
- ];
- ByteContentDoc$ = [
- 3,
- n0,
- _BCD,
- 0,
- [_id, _cTo, _da],
- [[() => Identifier, 0], 0, [() => ByteContentBlob, 0]],
- 3
- ];
- CancelAutomatedReasoningPolicyBuildWorkflowRequest$ = [
- 3,
- n0,
- _CARPBWR,
- 0,
- [_pA, _bWI],
- [[0, 1], [0, 1]],
- 2
- ];
- CancelAutomatedReasoningPolicyBuildWorkflowResponse$ = [
- 3,
- n0,
- _CARPBWRa,
- 0,
- [],
- []
- ];
- CloudWatchConfig$ = [
- 3,
- n0,
- _CWC,
- 0,
- [_lGN, _rA, _lDDSC],
- [0, 0, () => S3Config$],
- 2
- ];
- CreateAutomatedReasoningPolicyRequest$ = [
- 3,
- n0,
- _CARPR,
- 0,
- [_n, _d, _cRT, _pD, _kKI, _ta],
- [[() => AutomatedReasoningPolicyName, 0], [() => AutomatedReasoningPolicyDescription, 0], [0, 4], [() => AutomatedReasoningPolicyDefinition$, 0], 0, () => TagList],
- 1
- ];
- CreateAutomatedReasoningPolicyResponse$ = [
- 3,
- n0,
- _CARPRr,
- 0,
- [_pA, _ve, _n, _cA, _uA, _d, _dHe],
- [0, 0, [() => AutomatedReasoningPolicyName, 0], 5, 5, [() => AutomatedReasoningPolicyDescription, 0], 0],
- 5
- ];
- CreateAutomatedReasoningPolicyTestCaseRequest$ = [
- 3,
- n0,
- _CARPTCR,
- 0,
- [_pA, _gC, _eAFR, _qC, _cRT, _cT],
- [[0, 1], [() => AutomatedReasoningPolicyTestGuardContent, 0], 0, [() => AutomatedReasoningPolicyTestQueryContent, 0], [0, 4], 1],
- 3
- ];
- CreateAutomatedReasoningPolicyTestCaseResponse$ = [
- 3,
- n0,
- _CARPTCRr,
- 0,
- [_pA, _tCI],
- [0, 0],
- 2
- ];
- CreateAutomatedReasoningPolicyVersionRequest$ = [
- 3,
- n0,
- _CARPVR,
- 0,
- [_pA, _lUDH, _cRT, _ta],
- [[0, 1], 0, [0, 4], () => TagList],
- 2
- ];
- CreateAutomatedReasoningPolicyVersionResponse$ = [
- 3,
- n0,
- _CARPVRr,
- 0,
- [_pA, _ve, _n, _dHe, _cA, _d],
- [0, 0, [() => AutomatedReasoningPolicyName, 0], 0, 5, [() => AutomatedReasoningPolicyDescription, 0]],
- 5
- ];
- CreateCustomModelDeploymentRequest$ = [
- 3,
- n0,
- _CCMDR,
- 0,
- [_mDN, _mA, _d, _ta, _cRT],
- [0, 0, 0, () => TagList, [0, 4]],
- 2
- ];
- CreateCustomModelDeploymentResponse$ = [
- 3,
- n0,
- _CCMDRr,
- 0,
- [_cMDA],
- [0],
- 1
- ];
- CreateCustomModelRequest$ = [
- 3,
- n0,
- _CCMR,
- 0,
- [_mN, _mSC, _mKKA, _rA, _mTo, _cRT],
- [0, () => ModelDataSource$, 0, 0, () => TagList, [0, 4]],
- 2
- ];
- CreateCustomModelResponse$ = [
- 3,
- n0,
- _CCMRr,
- 0,
- [_mA],
- [0],
- 1
- ];
- CreateEvaluationJobRequest$ = [
- 3,
- n0,
- _CEJR,
- 0,
- [_jN, _rA, _eC, _iC, _oDC, _jD, _cRT, _cEKI, _jT, _aTp],
- [0, 0, [() => EvaluationConfig$, 0], [() => EvaluationInferenceConfig$, 0], () => EvaluationOutputDataConfig$, [() => EvaluationJobDescription, 0], [0, 4], 0, () => TagList, 0],
- 5
- ];
- CreateEvaluationJobResponse$ = [
- 3,
- n0,
- _CEJRr,
- 0,
- [_jA],
- [0],
- 1
- ];
- CreateFoundationModelAgreementRequest$ = [
- 3,
- n0,
- _CFMAR,
- 0,
- [_oT, _mIo],
- [0, 0],
- 2
- ];
- CreateFoundationModelAgreementResponse$ = [
- 3,
- n0,
- _CFMARr,
- 0,
- [_mIo],
- [0],
- 1
- ];
- CreateGuardrailRequest$ = [
- 3,
- n0,
- _CGR,
- 0,
- [_n, _bIM, _bOM, _d, _tPC, _cPC, _wPC, _sIPC, _cGPC, _aRPC, _cRC, _kKI, _ta, _cRT],
- [[() => GuardrailName, 0], [() => GuardrailBlockedMessaging, 0], [() => GuardrailBlockedMessaging, 0], [() => GuardrailDescription, 0], [() => GuardrailTopicPolicyConfig$, 0], [() => GuardrailContentPolicyConfig$, 0], [() => GuardrailWordPolicyConfig$, 0], () => GuardrailSensitiveInformationPolicyConfig$, [() => GuardrailContextualGroundingPolicyConfig$, 0], () => GuardrailAutomatedReasoningPolicyConfig$, () => GuardrailCrossRegionConfig$, 0, () => TagList, [0, 4]],
- 3
- ];
- CreateGuardrailResponse$ = [
- 3,
- n0,
- _CGRr,
- 0,
- [_gIu, _gA, _ve, _cA],
- [0, 0, 0, 5],
- 4
- ];
- CreateGuardrailVersionRequest$ = [
- 3,
- n0,
- _CGVR,
- 0,
- [_gI, _d, _cRT],
- [[0, 1], [() => GuardrailDescription, 0], [0, 4]],
- 1
- ];
- CreateGuardrailVersionResponse$ = [
- 3,
- n0,
- _CGVRr,
- 0,
- [_gIu, _ve],
- [0, 0],
- 2
- ];
- CreateInferenceProfileRequest$ = [
- 3,
- n0,
- _CIPR,
- 0,
- [_iPN, _mS, _d, _cRT, _ta],
- [0, () => InferenceProfileModelSource$, [() => InferenceProfileDescription, 0], [0, 4], () => TagList],
- 2
- ];
- CreateInferenceProfileResponse$ = [
- 3,
- n0,
- _CIPRr,
- 0,
- [_iPA, _st],
- [0, 0],
- 1
- ];
- CreateMarketplaceModelEndpointRequest$ = [
- 3,
- n0,
- _CMMER,
- 0,
- [_mSI, _eCn, _eN, _aEc, _cRT, _ta],
- [0, () => EndpointConfig$, 0, 2, [0, 4], () => TagList],
- 3
- ];
- CreateMarketplaceModelEndpointResponse$ = [
- 3,
- n0,
- _CMMERr,
- 0,
- [_mME],
- [() => MarketplaceModelEndpoint$],
- 1
- ];
- CreateModelCopyJobRequest$ = [
- 3,
- n0,
- _CMCJR,
- 0,
- [_sMA, _tMN, _mKKI, _tMT, _cRT],
- [0, 0, 0, () => TagList, [0, 4]],
- 2
- ];
- CreateModelCopyJobResponse$ = [
- 3,
- n0,
- _CMCJRr,
- 0,
- [_jA],
- [0],
- 1
- ];
- CreateModelCustomizationJobRequest$ = [
- 3,
- n0,
- _CMCJRre,
- 0,
- [_jN, _cMN, _rA, _bMI, _tDC, _oDC, _cRT, _cTu, _cMKKI, _jT, _cMT, _vDC, _hP, _vCp, _cC],
- [0, 0, 0, 0, [() => TrainingDataConfig$, 0], () => OutputDataConfig$, [0, 4], 0, 0, () => TagList, () => TagList, () => ValidationDataConfig$, 128 | 0, () => VpcConfig$, () => CustomizationConfig$],
- 6
- ];
- CreateModelCustomizationJobResponse$ = [
- 3,
- n0,
- _CMCJRrea,
- 0,
- [_jA],
- [0],
- 1
- ];
- CreateModelImportJobRequest$ = [
- 3,
- n0,
- _CMIJR,
- 0,
- [_jN, _iMN, _rA, _mDS, _jT, _iMT, _cRT, _vCp, _iMKKI],
- [0, 0, 0, () => ModelDataSource$, () => TagList, () => TagList, 0, () => VpcConfig$, 0],
- 4
- ];
- CreateModelImportJobResponse$ = [
- 3,
- n0,
- _CMIJRr,
- 0,
- [_jA],
- [0],
- 1
- ];
- CreateModelInvocationJobRequest$ = [
- 3,
- n0,
- _CMIJRre,
- 0,
- [_jN, _rA, _mIo, _iDC, _oDC, _cRT, _vCp, _tDIH, _ta, _mIT],
- [0, 0, 0, () => ModelInvocationJobInputDataConfig$, () => ModelInvocationJobOutputDataConfig$, [0, 4], () => VpcConfig$, 1, () => TagList, 0],
- 5
- ];
- CreateModelInvocationJobResponse$ = [
- 3,
- n0,
- _CMIJRrea,
- 0,
- [_jA],
- [0],
- 1
- ];
- CreatePromptRouterRequest$ = [
- 3,
- n0,
- _CPRR,
- 0,
- [_pRN, _mo, _rCo, _fM, _cRT, _d, _ta],
- [0, () => PromptRouterTargetModels, () => RoutingCriteria$, () => PromptRouterTargetModel$, [0, 4], [() => PromptRouterDescription, 0], () => TagList],
- 4
- ];
- CreatePromptRouterResponse$ = [
- 3,
- n0,
- _CPRRr,
- 0,
- [_pRA],
- [0]
- ];
- CreateProvisionedModelThroughputRequest$ = [
- 3,
- n0,
- _CPMTR,
- 0,
- [_mU, _pMN, _mIo, _cRT, _cD, _ta],
- [1, 0, 0, [0, 4], 0, () => TagList],
- 3
- ];
- CreateProvisionedModelThroughputResponse$ = [
- 3,
- n0,
- _CPMTRr,
- 0,
- [_pMA],
- [0],
- 1
- ];
- CustomMetricBedrockEvaluatorModel$ = [
- 3,
- n0,
- _CMBEM,
- 0,
- [_mI],
- [0],
- 1
- ];
- CustomMetricDefinition$ = [
- 3,
- n0,
- _CMD,
- 8,
- [_n, _in, _rS],
- [[() => MetricName, 0], 0, () => RatingScale],
- 2
- ];
- CustomMetricEvaluatorModelConfig$ = [
- 3,
- n0,
- _CMEMC,
- 0,
- [_bEM],
- [() => CustomMetricBedrockEvaluatorModels],
- 1
- ];
- CustomModelDeploymentSummary$ = [
- 3,
- n0,
- _CMDS,
- 0,
- [_cMDA, _cMDN, _mA, _cA, _st, _lUA, _fMa],
- [0, 0, 0, 5, 0, 5, 0],
- 5
- ];
- CustomModelDeploymentUpdateDetails$ = [
- 3,
- n0,
- _CMDUD,
- 0,
- [_mA, _uS],
- [0, 0],
- 2
- ];
- CustomModelSummary$ = [
- 3,
- n0,
- _CMS,
- 0,
- [_mA, _mN, _cTr, _bMA, _bMN, _cTu, _oAI, _mSo],
- [0, 0, 5, 0, 0, 0, 0, 0],
- 5
- ];
- CustomModelUnits$ = [
- 3,
- n0,
- _CMU,
- 0,
- [_cMUPMC, _cMUV],
- [1, 0]
- ];
- DataProcessingDetails$ = [
- 3,
- n0,
- _DPD,
- 0,
- [_st, _cTr, _lMT],
- [0, 5, 5]
- ];
- DeleteAutomatedReasoningPolicyBuildWorkflowRequest$ = [
- 3,
- n0,
- _DARPBWR,
- 0,
- [_pA, _bWI, _lUA],
- [[0, 1], [0, 1], [5, { [_hQ]: _uA }]],
- 3
- ];
- DeleteAutomatedReasoningPolicyBuildWorkflowResponse$ = [
- 3,
- n0,
- _DARPBWRe,
- 0,
- [],
- []
- ];
- DeleteAutomatedReasoningPolicyRequest$ = [
- 3,
- n0,
- _DARPR,
- 0,
- [_pA, _fo],
- [[0, 1], [2, { [_hQ]: _fo }]],
- 1
- ];
- DeleteAutomatedReasoningPolicyResponse$ = [
- 3,
- n0,
- _DARPRe,
- 0,
- [],
- []
- ];
- DeleteAutomatedReasoningPolicyTestCaseRequest$ = [
- 3,
- n0,
- _DARPTCR,
- 0,
- [_pA, _tCI, _lUA],
- [[0, 1], [0, 1], [5, { [_hQ]: _uA }]],
- 3
- ];
- DeleteAutomatedReasoningPolicyTestCaseResponse$ = [
- 3,
- n0,
- _DARPTCRe,
- 0,
- [],
- []
- ];
- DeleteCustomModelDeploymentRequest$ = [
- 3,
- n0,
- _DCMDR,
- 0,
- [_cMDI],
- [[0, 1]],
- 1
- ];
- DeleteCustomModelDeploymentResponse$ = [
- 3,
- n0,
- _DCMDRe,
- 0,
- [],
- []
- ];
- DeleteCustomModelRequest$ = [
- 3,
- n0,
- _DCMR,
- 0,
- [_mI],
- [[0, 1]],
- 1
- ];
- DeleteCustomModelResponse$ = [
- 3,
- n0,
- _DCMRe,
- 0,
- [],
- []
- ];
- DeleteEnforcedGuardrailConfigurationRequest$ = [
- 3,
- n0,
- _DEGCR,
- 0,
- [_cI],
- [[0, 1]],
- 1
- ];
- DeleteEnforcedGuardrailConfigurationResponse$ = [
- 3,
- n0,
- _DEGCRe,
- 0,
- [],
- []
- ];
- DeleteFoundationModelAgreementRequest$ = [
- 3,
- n0,
- _DFMAR,
- 0,
- [_mIo],
- [0],
- 1
- ];
- DeleteFoundationModelAgreementResponse$ = [
- 3,
- n0,
- _DFMARe,
- 0,
- [],
- []
- ];
- DeleteGuardrailRequest$ = [
- 3,
- n0,
- _DGR,
- 0,
- [_gI, _gV],
- [[0, 1], [0, { [_hQ]: _gV }]],
- 1
- ];
- DeleteGuardrailResponse$ = [
- 3,
- n0,
- _DGRe,
- 0,
- [],
- []
- ];
- DeleteImportedModelRequest$ = [
- 3,
- n0,
- _DIMR,
- 0,
- [_mI],
- [[0, 1]],
- 1
- ];
- DeleteImportedModelResponse$ = [
- 3,
- n0,
- _DIMRe,
- 0,
- [],
- []
- ];
- DeleteInferenceProfileRequest$ = [
- 3,
- n0,
- _DIPR,
- 0,
- [_iPI],
- [[0, 1]],
- 1
- ];
- DeleteInferenceProfileResponse$ = [
- 3,
- n0,
- _DIPRe,
- 0,
- [],
- []
- ];
- DeleteMarketplaceModelEndpointRequest$ = [
- 3,
- n0,
- _DMMER,
- 0,
- [_eA],
- [[0, 1]],
- 1
- ];
- DeleteMarketplaceModelEndpointResponse$ = [
- 3,
- n0,
- _DMMERe,
- 0,
- [],
- []
- ];
- DeleteModelInvocationLoggingConfigurationRequest$ = [
- 3,
- n0,
- _DMILCR,
- 0,
- [],
- []
- ];
- DeleteModelInvocationLoggingConfigurationResponse$ = [
- 3,
- n0,
- _DMILCRe,
- 0,
- [],
- []
- ];
- DeletePromptRouterRequest$ = [
- 3,
- n0,
- _DPRR,
- 0,
- [_pRA],
- [[0, 1]],
- 1
- ];
- DeletePromptRouterResponse$ = [
- 3,
- n0,
- _DPRRe,
- 0,
- [],
- []
- ];
- DeleteProvisionedModelThroughputRequest$ = [
- 3,
- n0,
- _DPMTR,
- 0,
- [_pMI],
- [[0, 1]],
- 1
- ];
- DeleteProvisionedModelThroughputResponse$ = [
- 3,
- n0,
- _DPMTRe,
- 0,
- [],
- []
- ];
- DeregisterMarketplaceModelEndpointRequest$ = [
- 3,
- n0,
- _DMMERer,
- 0,
- [_eA],
- [[0, 1]],
- 1
- ];
- DeregisterMarketplaceModelEndpointResponse$ = [
- 3,
- n0,
- _DMMERere,
- 0,
- [],
- []
- ];
- DimensionalPriceRate$ = [
- 3,
- n0,
- _DPR,
- 0,
- [_di, _pr, _d, _u],
- [0, 0, 0, 0]
- ];
- DistillationConfig$ = [
- 3,
- n0,
- _DC,
- 0,
- [_tMC],
- [() => TeacherModelConfig$],
- 1
- ];
- EvaluationBedrockModel$ = [
- 3,
- n0,
- _EBM,
- 0,
- [_mI, _iP, _pC],
- [0, [() => EvaluationModelInferenceParams, 0], () => PerformanceConfiguration$],
- 1
- ];
- EvaluationDataset$ = [
- 3,
- n0,
- _ED,
- 0,
- [_n, _dL],
- [[() => EvaluationDatasetName, 0], () => EvaluationDatasetLocation$],
- 1
- ];
- EvaluationDatasetMetricConfig$ = [
- 3,
- n0,
- _EDMC,
- 0,
- [_tT, _dat, _mNe],
- [0, [() => EvaluationDataset$, 0], [() => EvaluationMetricNames, 0]],
- 3
- ];
- EvaluationInferenceConfigSummary$ = [
- 3,
- n0,
- _EICS,
- 0,
- [_mCS, _rCS],
- [() => EvaluationModelConfigSummary$, () => EvaluationRagConfigSummary$]
- ];
- EvaluationModelConfigSummary$ = [
- 3,
- n0,
- _EMCS,
- 0,
- [_bMIe, _pISI],
- [64 | 0, 64 | 0]
- ];
- EvaluationOutputDataConfig$ = [
- 3,
- n0,
- _EODC,
- 0,
- [_sU],
- [0],
- 1
- ];
- EvaluationPrecomputedInferenceSource$ = [
- 3,
- n0,
- _EPIS,
- 0,
- [_iSI],
- [0],
- 1
- ];
- EvaluationPrecomputedRetrieveAndGenerateSourceConfig$ = [
- 3,
- n0,
- _EPRAGSC,
- 0,
- [_rSI],
- [0],
- 1
- ];
- EvaluationPrecomputedRetrieveSourceConfig$ = [
- 3,
- n0,
- _EPRSC,
- 0,
- [_rSI],
- [0],
- 1
- ];
- EvaluationRagConfigSummary$ = [
- 3,
- n0,
- _ERCS,
- 0,
- [_bKBI, _pRSI],
- [64 | 0, 64 | 0]
- ];
- EvaluationSummary$ = [
- 3,
- n0,
- _ES,
- 0,
- [_jA, _jN, _st, _cTr, _jTo, _eTT, _mIod, _rIa, _eMI, _cMEMI, _iCS, _aTp],
- [0, 0, 0, 5, 0, 64 | 0, 64 | 0, 64 | 0, 64 | 0, 64 | 0, () => EvaluationInferenceConfigSummary$, 0],
- 6
- ];
- ExportAutomatedReasoningPolicyVersionRequest$ = [
- 3,
- n0,
- _EARPVR,
- 0,
- [_pA],
- [[0, 1]],
- 1
- ];
- ExportAutomatedReasoningPolicyVersionResponse$ = [
- 3,
- n0,
- _EARPVRx,
- 0,
- [_pD],
- [[() => AutomatedReasoningPolicyDefinition$, 16]],
- 1
- ];
- ExternalSource$ = [
- 3,
- n0,
- _ESx,
- 0,
- [_sT, _sL, _bC],
- [0, () => S3ObjectDoc$, [() => ByteContentDoc$, 0]],
- 1
- ];
- ExternalSourcesGenerationConfiguration$ = [
- 3,
- n0,
- _ESGC,
- 0,
- [_pT, _gCu, _kIC, _aMRF],
- [[() => PromptTemplate$, 0], () => GuardrailConfiguration$, () => KbInferenceConfig$, 128 | 15]
- ];
- ExternalSourcesRetrieveAndGenerateConfiguration$ = [
- 3,
- n0,
- _ESRAGC,
- 0,
- [_mA, _so, _gCe],
- [0, [() => ExternalSources, 0], [() => ExternalSourcesGenerationConfiguration$, 0]],
- 2
- ];
- FieldForReranking$ = [
- 3,
- n0,
- _FFR,
- 0,
- [_fN],
- [0],
- 1
- ];
- FilterAttribute$ = [
- 3,
- n0,
- _FA,
- 0,
- [_k, _va],
- [0, 15],
- 2
- ];
- FoundationModelDetails$ = [
- 3,
- n0,
- _FMD,
- 0,
- [_mA, _mIo, _mN, _pNr, _iM, _oM, _rSS, _cSu, _iTS, _mL],
- [0, 0, 0, 0, 64 | 0, 64 | 0, 2, 64 | 0, 64 | 0, () => FoundationModelLifecycle$],
- 2
- ];
- FoundationModelLifecycle$ = [
- 3,
- n0,
- _FML,
- 0,
- [_st, _sOLT, _eOLT, _lTe, _pEAT],
- [0, 5, 5, 5, 5],
- 1
- ];
- FoundationModelSummary$ = [
- 3,
- n0,
- _FMS,
- 0,
- [_mA, _mIo, _mN, _pNr, _iM, _oM, _rSS, _cSu, _iTS, _mL],
- [0, 0, 0, 0, 64 | 0, 64 | 0, 2, 64 | 0, 64 | 0, () => FoundationModelLifecycle$],
- 2
- ];
- GenerationConfiguration$ = [
- 3,
- n0,
- _GC,
- 0,
- [_pT, _gCu, _kIC, _aMRF],
- [[() => PromptTemplate$, 0], () => GuardrailConfiguration$, () => KbInferenceConfig$, 128 | 15]
- ];
- GetAutomatedReasoningPolicyAnnotationsRequest$ = [
- 3,
- n0,
- _GARPAR,
- 0,
- [_pA, _bWI],
- [[0, 1], [0, 1]],
- 2
- ];
- GetAutomatedReasoningPolicyAnnotationsResponse$ = [
- 3,
- n0,
- _GARPARe,
- 0,
- [_pA, _n, _bWI, _an, _aSH, _uA],
- [0, [() => AutomatedReasoningPolicyName, 0], 0, [() => AutomatedReasoningPolicyAnnotationList, 0], 0, 5],
- 6
- ];
- GetAutomatedReasoningPolicyBuildWorkflowRequest$ = [
- 3,
- n0,
- _GARPBWR,
- 0,
- [_pA, _bWI],
- [[0, 1], [0, 1]],
- 2
- ];
- GetAutomatedReasoningPolicyBuildWorkflowResponse$ = [
- 3,
- n0,
- _GARPBWRe,
- 0,
- [_pA, _bWI, _st, _bWT, _cA, _uA, _dN, _dCT, _dD],
- [0, 0, 0, 0, 5, 5, [() => AutomatedReasoningPolicyBuildDocumentName, 0], 0, [() => AutomatedReasoningPolicyBuildDocumentDescription, 0]],
- 6
- ];
- GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest$ = [
- 3,
- n0,
- _GARPBWRAR,
- 0,
- [_pA, _bWI, _aT, _aI],
- [[0, 1], [0, 1], [0, { [_hQ]: _aT }], [0, { [_hQ]: _aI }]],
- 3
- ];
- GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse$ = [
- 3,
- n0,
- _GARPBWRARe,
- 0,
- [_pA, _bWI, _bWA],
- [0, 0, [() => AutomatedReasoningPolicyBuildResultAssets$, 0]],
- 2
- ];
- GetAutomatedReasoningPolicyNextScenarioRequest$ = [
- 3,
- n0,
- _GARPNSR,
- 0,
- [_pA, _bWI],
- [[0, 1], [0, 1]],
- 2
- ];
- GetAutomatedReasoningPolicyNextScenarioResponse$ = [
- 3,
- n0,
- _GARPNSRe,
- 0,
- [_pA, _sc],
- [0, [() => AutomatedReasoningPolicyScenario$, 0]],
- 1
- ];
- GetAutomatedReasoningPolicyRequest$ = [
- 3,
- n0,
- _GARPR,
- 0,
- [_pA],
- [[0, 1]],
- 1
- ];
- GetAutomatedReasoningPolicyResponse$ = [
- 3,
- n0,
- _GARPRe,
- 0,
- [_pA, _n, _ve, _pI, _dHe, _uA, _d, _kKA, _cA],
- [0, [() => AutomatedReasoningPolicyName, 0], 0, 0, 0, 5, [() => AutomatedReasoningPolicyDescription, 0], 0, 5],
- 6
- ];
- GetAutomatedReasoningPolicyTestCaseRequest$ = [
- 3,
- n0,
- _GARPTCR,
- 0,
- [_pA, _tCI],
- [[0, 1], [0, 1]],
- 2
- ];
- GetAutomatedReasoningPolicyTestCaseResponse$ = [
- 3,
- n0,
- _GARPTCRe,
- 0,
- [_pA, _tCe],
- [0, [() => AutomatedReasoningPolicyTestCase$, 0]],
- 2
- ];
- GetAutomatedReasoningPolicyTestResultRequest$ = [
- 3,
- n0,
- _GARPTRR,
- 0,
- [_pA, _bWI, _tCI],
- [[0, 1], [0, 1], [0, 1]],
- 3
- ];
- GetAutomatedReasoningPolicyTestResultResponse$ = [
- 3,
- n0,
- _GARPTRRe,
- 0,
- [_tR],
- [[() => AutomatedReasoningPolicyTestResult$, 0]],
- 1
- ];
- GetCustomModelDeploymentRequest$ = [
- 3,
- n0,
- _GCMDR,
- 0,
- [_cMDI],
- [[0, 1]],
- 1
- ];
- GetCustomModelDeploymentResponse$ = [
- 3,
- n0,
- _GCMDRe,
- 0,
- [_cMDA, _mDN, _mA, _cA, _st, _d, _uD, _fMa, _lUA],
- [0, 0, 0, 5, 0, 0, () => CustomModelDeploymentUpdateDetails$, 0, 5],
- 5
- ];
- GetCustomModelRequest$ = [
- 3,
- n0,
- _GCMR,
- 0,
- [_mI],
- [[0, 1]],
- 1
- ];
- GetCustomModelResponse$ = [
- 3,
- n0,
- _GCMRe,
- 0,
- [_mA, _mN, _cTr, _jN, _jA, _bMA, _cTu, _mKKA, _hP, _tDC, _vDC, _oDC, _tM, _vM, _cC, _mSo, _fMa],
- [0, 0, 5, 0, 0, 0, 0, 0, 128 | 0, [() => TrainingDataConfig$, 0], () => ValidationDataConfig$, () => OutputDataConfig$, () => TrainingMetrics$, () => ValidationMetrics, () => CustomizationConfig$, 0, 0],
- 3
- ];
- GetEvaluationJobRequest$ = [
- 3,
- n0,
- _GEJR,
- 0,
- [_jI],
- [[() => EvaluationJobIdentifier, 1]],
- 1
- ];
- GetEvaluationJobResponse$ = [
- 3,
- n0,
- _GEJRe,
- 0,
- [_jN, _st, _jA, _rA, _jTo, _eC, _iC, _oDC, _cTr, _jD, _cEKI, _aTp, _lMT, _fMai],
- [0, 0, 0, 0, 0, [() => EvaluationConfig$, 0], [() => EvaluationInferenceConfig$, 0], () => EvaluationOutputDataConfig$, 5, [() => EvaluationJobDescription, 0], 0, 0, 5, 64 | 0],
- 9
- ];
- GetFoundationModelAvailabilityRequest$ = [
- 3,
- n0,
- _GFMAR,
- 0,
- [_mIo],
- [[0, 1]],
- 1
- ];
- GetFoundationModelAvailabilityResponse$ = [
- 3,
- n0,
- _GFMARe,
- 0,
- [_mIo, _aA, _aSu, _eAn, _rAe],
- [0, () => AgreementAvailability$, 0, 0, 0],
- 5
- ];
- GetFoundationModelRequest$ = [
- 3,
- n0,
- _GFMR,
- 0,
- [_mI],
- [[0, 1]],
- 1
- ];
- GetFoundationModelResponse$ = [
- 3,
- n0,
- _GFMRe,
- 0,
- [_mD],
- [() => FoundationModelDetails$]
- ];
- GetGuardrailRequest$ = [
- 3,
- n0,
- _GGR,
- 0,
- [_gI, _gV],
- [[0, 1], [0, { [_hQ]: _gV }]],
- 1
- ];
- GetGuardrailResponse$ = [
- 3,
- n0,
- _GGRe,
- 0,
- [_n, _gIu, _gA, _ve, _st, _cA, _uA, _bIM, _bOM, _d, _tP, _cP, _wP, _sIP, _cGP, _aRP, _cRD, _sRt, _fR, _kKA],
- [[() => GuardrailName, 0], 0, 0, 0, 0, 5, 5, [() => GuardrailBlockedMessaging, 0], [() => GuardrailBlockedMessaging, 0], [() => GuardrailDescription, 0], [() => GuardrailTopicPolicy$, 0], [() => GuardrailContentPolicy$, 0], [() => GuardrailWordPolicy$, 0], () => GuardrailSensitiveInformationPolicy$, [() => GuardrailContextualGroundingPolicy$, 0], () => GuardrailAutomatedReasoningPolicy$, () => GuardrailCrossRegionDetails$, [() => GuardrailStatusReasons, 0], [() => GuardrailFailureRecommendations, 0], 0],
- 9
- ];
- GetImportedModelRequest$ = [
- 3,
- n0,
- _GIMR,
- 0,
- [_mI],
- [[0, 1]],
- 1
- ];
- GetImportedModelResponse$ = [
- 3,
- n0,
- _GIMRe,
- 0,
- [_mA, _mN, _jN, _jA, _mDS, _cTr, _mAo, _mKKA, _iS, _cMU],
- [0, 0, 0, 0, () => ModelDataSource$, 5, 0, 0, 2, () => CustomModelUnits$]
- ];
- GetInferenceProfileRequest$ = [
- 3,
- n0,
- _GIPR,
- 0,
- [_iPI],
- [[0, 1]],
- 1
- ];
- GetInferenceProfileResponse$ = [
- 3,
- n0,
- _GIPRe,
- 0,
- [_iPN, _iPA, _mo, _iPIn, _st, _ty, _d, _cA, _uA],
- [0, 0, () => InferenceProfileModels, 0, 0, 0, [() => InferenceProfileDescription, 0], 5, 5],
- 6
- ];
- GetMarketplaceModelEndpointRequest$ = [
- 3,
- n0,
- _GMMER,
- 0,
- [_eA],
- [[0, 1]],
- 1
- ];
- GetMarketplaceModelEndpointResponse$ = [
- 3,
- n0,
- _GMMERe,
- 0,
- [_mME],
- [() => MarketplaceModelEndpoint$]
- ];
- GetModelCopyJobRequest$ = [
- 3,
- n0,
- _GMCJR,
- 0,
- [_jA],
- [[0, 1]],
- 1
- ];
- GetModelCopyJobResponse$ = [
- 3,
- n0,
- _GMCJRe,
- 0,
- [_jA, _st, _cTr, _tMA, _sAI, _sMA, _tMN, _tMKKA, _tMT, _fMa, _sMN],
- [0, 0, 5, 0, 0, 0, 0, 0, () => TagList, 0, 0],
- 6
- ];
- GetModelCustomizationJobRequest$ = [
- 3,
- n0,
- _GMCJRet,
- 0,
- [_jI],
- [[0, 1]],
- 1
- ];
- GetModelCustomizationJobResponse$ = [
- 3,
- n0,
- _GMCJReto,
- 0,
- [_jA, _jN, _oMN, _rA, _cTr, _bMA, _tDC, _vDC, _oDC, _oMA, _cRT, _st, _sD, _fMa, _lMT, _eT, _hP, _cTu, _oMKKA, _tM, _vM, _vCp, _cC],
- [0, 0, 0, 0, 5, 0, [() => TrainingDataConfig$, 0], () => ValidationDataConfig$, () => OutputDataConfig$, 0, 0, 0, () => StatusDetails$, 0, 5, 5, 128 | 0, 0, 0, () => TrainingMetrics$, () => ValidationMetrics, () => VpcConfig$, () => CustomizationConfig$],
- 9
- ];
- GetModelImportJobRequest$ = [
- 3,
- n0,
- _GMIJR,
- 0,
- [_jI],
- [[0, 1]],
- 1
- ];
- GetModelImportJobResponse$ = [
- 3,
- n0,
- _GMIJRe,
- 0,
- [_jA, _jN, _iMN, _iMA, _rA, _mDS, _st, _fMa, _cTr, _lMT, _eT, _vCp, _iMKKA],
- [0, 0, 0, 0, 0, () => ModelDataSource$, 0, 0, 5, 5, 5, () => VpcConfig$, 0]
- ];
- GetModelInvocationJobRequest$ = [
- 3,
- n0,
- _GMIJRet,
- 0,
- [_jI],
- [[0, 1]],
- 1
- ];
- GetModelInvocationJobResponse$ = [
- 3,
- n0,
- _GMIJReto,
- 0,
- [_jA, _mIo, _rA, _sTu, _iDC, _oDC, _jN, _cRT, _st, _m, _lMT, _eT, _vCp, _tDIH, _jET, _mIT],
- [0, 0, 0, 5, () => ModelInvocationJobInputDataConfig$, () => ModelInvocationJobOutputDataConfig$, 0, 0, 0, [() => Message, 0], 5, 5, () => VpcConfig$, 1, 5, 0],
- 6
- ];
- GetModelInvocationLoggingConfigurationRequest$ = [
- 3,
- n0,
- _GMILCR,
- 0,
- [],
- []
- ];
- GetModelInvocationLoggingConfigurationResponse$ = [
- 3,
- n0,
- _GMILCRe,
- 0,
- [_lC],
- [() => LoggingConfig$]
- ];
- GetPromptRouterRequest$ = [
- 3,
- n0,
- _GPRR,
- 0,
- [_pRA],
- [[0, 1]],
- 1
- ];
- GetPromptRouterResponse$ = [
- 3,
- n0,
- _GPRRe,
- 0,
- [_pRN, _rCo, _pRA, _mo, _fM, _st, _ty, _d, _cA, _uA],
- [0, () => RoutingCriteria$, 0, () => PromptRouterTargetModels, () => PromptRouterTargetModel$, 0, 0, [() => PromptRouterDescription, 0], 5, 5],
- 7
- ];
- GetProvisionedModelThroughputRequest$ = [
- 3,
- n0,
- _GPMTR,
- 0,
- [_pMI],
- [[0, 1]],
- 1
- ];
- GetProvisionedModelThroughputResponse$ = [
- 3,
- n0,
- _GPMTRe,
- 0,
- [_mU, _dMU, _pMN, _pMA, _mA, _dMA, _fMA, _st, _cTr, _lMT, _fMa, _cD, _cET],
- [1, 1, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 5],
- 10
- ];
- GetUseCaseForModelAccessRequest$ = [
- 3,
- n0,
- _GUCFMAR,
- 0,
- [],
- []
- ];
- GetUseCaseForModelAccessResponse$ = [
- 3,
- n0,
- _GUCFMARe,
- 0,
- [_fD],
- [21],
- 1
- ];
- GuardrailAutomatedReasoningPolicy$ = [
- 3,
- n0,
- _GARP,
- 0,
- [_po, _cT],
- [64 | 0, 1],
- 1
- ];
- GuardrailAutomatedReasoningPolicyConfig$ = [
- 3,
- n0,
- _GARPC,
- 0,
- [_po, _cT],
- [64 | 0, 1],
- 1
- ];
- GuardrailConfiguration$ = [
- 3,
- n0,
- _GCu,
- 0,
- [_gIu, _gV],
- [0, 0],
- 2
- ];
- GuardrailContentFilter$ = [
- 3,
- n0,
- _GCF,
- 0,
- [_ty, _iSn, _oS, _iM, _oM, _iA, _oA, _iE, _oE],
- [0, 0, 0, [() => GuardrailModalities, 0], [() => GuardrailModalities, 0], [() => GuardrailContentFilterAction, 0], [() => GuardrailContentFilterAction, 0], 2, 2],
- 3
- ];
- GuardrailContentFilterConfig$ = [
- 3,
- n0,
- _GCFC,
- 0,
- [_ty, _iSn, _oS, _iM, _oM, _iA, _oA, _iE, _oE],
- [0, 0, 0, [() => GuardrailModalities, 0], [() => GuardrailModalities, 0], [() => GuardrailContentFilterAction, 0], [() => GuardrailContentFilterAction, 0], 2, 2],
- 3
- ];
- GuardrailContentFiltersTier$ = [
- 3,
- n0,
- _GCFT,
- 0,
- [_tNi],
- [[() => GuardrailContentFiltersTierName, 0]],
- 1
- ];
- GuardrailContentFiltersTierConfig$ = [
- 3,
- n0,
- _GCFTC,
- 0,
- [_tNi],
- [[() => GuardrailContentFiltersTierName, 0]],
- 1
- ];
- GuardrailContentPolicy$ = [
- 3,
- n0,
- _GCP,
- 0,
- [_fi, _ti],
- [[() => GuardrailContentFilters, 0], [() => GuardrailContentFiltersTier$, 0]]
- ];
- GuardrailContentPolicyConfig$ = [
- 3,
- n0,
- _GCPC,
- 0,
- [_fC, _tCi],
- [[() => GuardrailContentFiltersConfig, 0], [() => GuardrailContentFiltersTierConfig$, 0]],
- 1
- ];
- GuardrailContextualGroundingFilter$ = [
- 3,
- n0,
- _GCGF,
- 0,
- [_ty, _th, _ac, _ena],
- [0, 1, [() => GuardrailContextualGroundingAction, 0], 2],
- 2
- ];
- GuardrailContextualGroundingFilterConfig$ = [
- 3,
- n0,
- _GCGFC,
- 0,
- [_ty, _th, _ac, _ena],
- [0, 1, [() => GuardrailContextualGroundingAction, 0], 2],
- 2
- ];
- GuardrailContextualGroundingPolicy$ = [
- 3,
- n0,
- _GCGP,
- 0,
- [_fi],
- [[() => GuardrailContextualGroundingFilters, 0]],
- 1
- ];
- GuardrailContextualGroundingPolicyConfig$ = [
- 3,
- n0,
- _GCGPC,
- 0,
- [_fC],
- [[() => GuardrailContextualGroundingFiltersConfig, 0]],
- 1
- ];
- GuardrailCrossRegionConfig$ = [
- 3,
- n0,
- _GCRC,
- 0,
- [_gPI],
- [0],
- 1
- ];
- GuardrailCrossRegionDetails$ = [
- 3,
- n0,
- _GCRD,
- 0,
- [_gPIu, _gPA],
- [0, 0]
- ];
- GuardrailManagedWords$ = [
- 3,
- n0,
- _GMW,
- 0,
- [_ty, _iA, _oA, _iE, _oE],
- [0, [() => GuardrailWordAction, 0], [() => GuardrailWordAction, 0], 2, 2],
- 1
- ];
- GuardrailManagedWordsConfig$ = [
- 3,
- n0,
- _GMWC,
- 0,
- [_ty, _iA, _oA, _iE, _oE],
- [0, [() => GuardrailWordAction, 0], [() => GuardrailWordAction, 0], 2, 2],
- 1
- ];
- GuardrailPiiEntity$ = [
- 3,
- n0,
- _GPE,
- 0,
- [_ty, _ac, _iA, _oA, _iE, _oE],
- [0, 0, 0, 0, 2, 2],
- 2
- ];
- GuardrailPiiEntityConfig$ = [
- 3,
- n0,
- _GPEC,
- 0,
- [_ty, _ac, _iA, _oA, _iE, _oE],
- [0, 0, 0, 0, 2, 2],
- 2
- ];
- GuardrailRegex$ = [
- 3,
- n0,
- _GR,
- 0,
- [_n, _pa, _ac, _d, _iA, _oA, _iE, _oE],
- [0, 0, 0, 0, 0, 0, 2, 2],
- 3
- ];
- GuardrailRegexConfig$ = [
- 3,
- n0,
- _GRC,
- 0,
- [_n, _pa, _ac, _d, _iA, _oA, _iE, _oE],
- [0, 0, 0, 0, 0, 0, 2, 2],
- 3
- ];
- GuardrailSensitiveInformationPolicy$ = [
- 3,
- n0,
- _GSIP,
- 0,
- [_pEi, _re],
- [() => GuardrailPiiEntities, () => GuardrailRegexes]
- ];
- GuardrailSensitiveInformationPolicyConfig$ = [
- 3,
- n0,
- _GSIPC,
- 0,
- [_pEC, _rCe],
- [() => GuardrailPiiEntitiesConfig, () => GuardrailRegexesConfig]
- ];
- GuardrailSummary$ = [
- 3,
- n0,
- _GS,
- 0,
- [_i, _ar, _st, _n, _ve, _cA, _uA, _d, _cRD],
- [0, 0, 0, [() => GuardrailName, 0], 0, 5, 5, [() => GuardrailDescription, 0], () => GuardrailCrossRegionDetails$],
- 7
- ];
- GuardrailTopic$ = [
- 3,
- n0,
- _GT,
- 0,
- [_n, _de, _exa, _ty, _iA, _oA, _iE, _oE],
- [[() => GuardrailTopicName, 0], [() => GuardrailTopicDefinition, 0], [() => GuardrailTopicExamples, 0], 0, [() => GuardrailTopicAction, 0], [() => GuardrailTopicAction, 0], 2, 2],
- 2
- ];
- GuardrailTopicConfig$ = [
- 3,
- n0,
- _GTC,
- 0,
- [_n, _de, _ty, _exa, _iA, _oA, _iE, _oE],
- [[() => GuardrailTopicName, 0], [() => GuardrailTopicDefinition, 0], 0, [() => GuardrailTopicExamples, 0], [() => GuardrailTopicAction, 0], [() => GuardrailTopicAction, 0], 2, 2],
- 3
- ];
- GuardrailTopicPolicy$ = [
- 3,
- n0,
- _GTP,
- 0,
- [_to, _ti],
- [[() => GuardrailTopics, 0], [() => GuardrailTopicsTier$, 0]],
- 1
- ];
- GuardrailTopicPolicyConfig$ = [
- 3,
- n0,
- _GTPC,
- 0,
- [_tCo, _tCi],
- [[() => GuardrailTopicsConfig, 0], [() => GuardrailTopicsTierConfig$, 0]],
- 1
- ];
- GuardrailTopicsTier$ = [
- 3,
- n0,
- _GTT,
- 0,
- [_tNi],
- [[() => GuardrailTopicsTierName, 0]],
- 1
- ];
- GuardrailTopicsTierConfig$ = [
- 3,
- n0,
- _GTTC,
- 0,
- [_tNi],
- [[() => GuardrailTopicsTierName, 0]],
- 1
- ];
- GuardrailWord$ = [
- 3,
- n0,
- _GW,
- 0,
- [_te, _iA, _oA, _iE, _oE],
- [0, [() => GuardrailWordAction, 0], [() => GuardrailWordAction, 0], 2, 2],
- 1
- ];
- GuardrailWordConfig$ = [
- 3,
- n0,
- _GWC,
- 0,
- [_te, _iA, _oA, _iE, _oE],
- [0, [() => GuardrailWordAction, 0], [() => GuardrailWordAction, 0], 2, 2],
- 1
- ];
- GuardrailWordPolicy$ = [
- 3,
- n0,
- _GWP,
- 0,
- [_w, _mWL],
- [[() => GuardrailWords, 0], [() => GuardrailManagedWordLists, 0]]
- ];
- GuardrailWordPolicyConfig$ = [
- 3,
- n0,
- _GWPC,
- 0,
- [_wCo, _mWLC],
- [[() => GuardrailWordsConfig, 0], [() => GuardrailManagedWordListsConfig, 0]]
- ];
- HumanEvaluationConfig$ = [
- 3,
- n0,
- _HEC,
- 0,
- [_dMC, _hWC, _cM],
- [[() => EvaluationDatasetMetricConfigs, 0], [() => HumanWorkflowConfig$, 0], [() => HumanEvaluationCustomMetrics, 0]],
- 1
- ];
- HumanEvaluationCustomMetric$ = [
- 3,
- n0,
- _HECM,
- 0,
- [_n, _rM, _d],
- [[() => EvaluationMetricName, 0], 0, [() => EvaluationMetricDescription, 0]],
- 2
- ];
- HumanWorkflowConfig$ = [
- 3,
- n0,
- _HWC,
- 0,
- [_fDA, _in],
- [0, [() => HumanTaskInstructions, 0]],
- 1
- ];
- ImplicitFilterConfiguration$ = [
- 3,
- n0,
- _IFC,
- 0,
- [_mAe, _mA],
- [[() => MetadataAttributeSchemaList, 0], 0],
- 2
- ];
- ImportedModelSummary$ = [
- 3,
- n0,
- _IMS,
- 0,
- [_mA, _mN, _cTr, _iS, _mAo],
- [0, 0, 5, 2, 0],
- 3
- ];
- InferenceProfileModel$ = [
- 3,
- n0,
- _IPM,
- 0,
- [_mA],
- [0]
- ];
- InferenceProfileSummary$ = [
- 3,
- n0,
- _IPS,
- 0,
- [_iPN, _iPA, _mo, _iPIn, _st, _ty, _d, _cA, _uA],
- [0, 0, () => InferenceProfileModels, 0, 0, 0, [() => InferenceProfileDescription, 0], 5, 5],
- 6
- ];
- InvocationLogsConfig$ = [
- 3,
- n0,
- _ILC,
- 0,
- [_iLS, _uPR, _rMF],
- [() => InvocationLogSource$, 2, [() => RequestMetadataFilters$, 0]],
- 1
- ];
- KbInferenceConfig$ = [
- 3,
- n0,
- _KIC,
- 0,
- [_tIC],
- [() => TextInferenceConfig$]
- ];
- KnowledgeBaseRetrievalConfiguration$ = [
- 3,
- n0,
- _KBRC,
- 0,
- [_vSC],
- [[() => KnowledgeBaseVectorSearchConfiguration$, 0]],
- 1
- ];
- KnowledgeBaseRetrieveAndGenerateConfiguration$ = [
- 3,
- n0,
- _KBRAGC,
- 0,
- [_kBI, _mA, _rCet, _gCe, _oC],
- [0, 0, [() => KnowledgeBaseRetrievalConfiguration$, 0], [() => GenerationConfiguration$, 0], () => OrchestrationConfiguration$],
- 2
- ];
- KnowledgeBaseVectorSearchConfiguration$ = [
- 3,
- n0,
- _KBVSC,
- 0,
- [_nOR, _oST, _fil, _iFC, _rCer],
- [1, 0, [() => RetrievalFilter$, 0], [() => ImplicitFilterConfiguration$, 0], [() => VectorSearchRerankingConfiguration$, 0]]
- ];
- LambdaGraderConfig$ = [
- 3,
- n0,
- _LGC,
- 0,
- [_lA],
- [0],
- 1
- ];
- LegalTerm$ = [
- 3,
- n0,
- _LT,
- 0,
- [_ur],
- [0]
- ];
- ListAutomatedReasoningPoliciesRequest$ = [
- 3,
- n0,
- _LARPR,
- 0,
- [_pA, _nT, _mR],
- [[0, { [_hQ]: _pA }], [0, { [_hQ]: _nT }], [1, { [_hQ]: _mR }]]
- ];
- ListAutomatedReasoningPoliciesResponse$ = [
- 3,
- n0,
- _LARPRi,
- 0,
- [_aRPS, _nT],
- [[() => AutomatedReasoningPolicySummaries, 0], 0],
- 1
- ];
- ListAutomatedReasoningPolicyBuildWorkflowsRequest$ = [
- 3,
- n0,
- _LARPBWR,
- 0,
- [_pA, _nT, _mR],
- [[0, 1], [0, { [_hQ]: _nT }], [1, { [_hQ]: _mR }]],
- 1
- ];
- ListAutomatedReasoningPolicyBuildWorkflowsResponse$ = [
- 3,
- n0,
- _LARPBWRi,
- 0,
- [_aRPBWS, _nT],
- [() => AutomatedReasoningPolicyBuildWorkflowSummaries, 0],
- 1
- ];
- ListAutomatedReasoningPolicyTestCasesRequest$ = [
- 3,
- n0,
- _LARPTCR,
- 0,
- [_pA, _nT, _mR],
- [[0, 1], [0, { [_hQ]: _nT }], [1, { [_hQ]: _mR }]],
- 1
- ];
- ListAutomatedReasoningPolicyTestCasesResponse$ = [
- 3,
- n0,
- _LARPTCRi,
- 0,
- [_tCes, _nT],
- [[() => AutomatedReasoningPolicyTestCaseList, 0], 0],
- 1
- ];
- ListAutomatedReasoningPolicyTestResultsRequest$ = [
- 3,
- n0,
- _LARPTRR,
- 0,
- [_pA, _bWI, _nT, _mR],
- [[0, 1], [0, 1], [0, { [_hQ]: _nT }], [1, { [_hQ]: _mR }]],
- 2
- ];
- ListAutomatedReasoningPolicyTestResultsResponse$ = [
- 3,
- n0,
- _LARPTRRi,
- 0,
- [_tRe, _nT],
- [[() => AutomatedReasoningPolicyTestList, 0], 0],
- 1
- ];
- ListCustomModelDeploymentsRequest$ = [
- 3,
- n0,
- _LCMDR,
- 0,
- [_cBr, _cAr, _nC, _mR, _nT, _sB, _sO, _sEt, _mAE],
- [[5, { [_hQ]: _cBr }], [5, { [_hQ]: _cAr }], [0, { [_hQ]: _nC }], [1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _sB }], [0, { [_hQ]: _sO }], [0, { [_hQ]: _sEt }], [0, { [_hQ]: _mAE }]]
- ];
- ListCustomModelDeploymentsResponse$ = [
- 3,
- n0,
- _LCMDRi,
- 0,
- [_nT, _mDSo],
- [0, () => CustomModelDeploymentSummaryList]
- ];
- ListCustomModelsRequest$ = [
- 3,
- n0,
- _LCMR,
- 0,
- [_cTB, _cTA, _nC, _bMAE, _fMAE, _mR, _nT, _sB, _sO, _iO, _mSo],
- [[5, { [_hQ]: _cTB }], [5, { [_hQ]: _cTA }], [0, { [_hQ]: _nC }], [0, { [_hQ]: _bMAE }], [0, { [_hQ]: _fMAE }], [1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _sB }], [0, { [_hQ]: _sO }], [2, { [_hQ]: _iO }], [0, { [_hQ]: _mSo }]]
- ];
- ListCustomModelsResponse$ = [
- 3,
- n0,
- _LCMRi,
- 0,
- [_nT, _mSod],
- [0, () => CustomModelSummaryList]
- ];
- ListEnforcedGuardrailsConfigurationRequest$ = [
- 3,
- n0,
- _LEGCR,
- 0,
- [_nT],
- [[0, { [_hQ]: _nT }]]
- ];
- ListEnforcedGuardrailsConfigurationResponse$ = [
- 3,
- n0,
- _LEGCRi,
- 0,
- [_gCua, _nT],
- [() => AccountEnforcedGuardrailsOutputConfiguration, 0],
- 1
- ];
- ListEvaluationJobsRequest$ = [
- 3,
- n0,
- _LEJR,
- 0,
- [_cTA, _cTB, _sEt, _aTE, _nC, _mR, _nT, _sB, _sO],
- [[5, { [_hQ]: _cTA }], [5, { [_hQ]: _cTB }], [0, { [_hQ]: _sEt }], [0, { [_hQ]: _aTE }], [0, { [_hQ]: _nC }], [1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _sB }], [0, { [_hQ]: _sO }]]
- ];
- ListEvaluationJobsResponse$ = [
- 3,
- n0,
- _LEJRi,
- 0,
- [_nT, _jSo],
- [0, () => EvaluationSummaries]
- ];
- ListFoundationModelAgreementOffersRequest$ = [
- 3,
- n0,
- _LFMAOR,
- 0,
- [_mIo, _oTf],
- [[0, 1], [0, { [_hQ]: _oTf }]],
- 1
- ];
- ListFoundationModelAgreementOffersResponse$ = [
- 3,
- n0,
- _LFMAORi,
- 0,
- [_mIo, _of],
- [0, () => Offers],
- 2
- ];
- ListFoundationModelsRequest$ = [
- 3,
- n0,
- _LFMR,
- 0,
- [_bP, _bCT, _bOMy, _bIT],
- [[0, { [_hQ]: _bP }], [0, { [_hQ]: _bCT }], [0, { [_hQ]: _bOMy }], [0, { [_hQ]: _bIT }]]
- ];
- ListFoundationModelsResponse$ = [
- 3,
- n0,
- _LFMRi,
- 0,
- [_mSod],
- [() => FoundationModelSummaryList]
- ];
- ListGuardrailsRequest$ = [
- 3,
- n0,
- _LGR,
- 0,
- [_gI, _mR, _nT],
- [[0, { [_hQ]: _gI }], [1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }]]
- ];
- ListGuardrailsResponse$ = [
- 3,
- n0,
- _LGRi,
- 0,
- [_g, _nT],
- [[() => GuardrailSummaries, 0], 0],
- 1
- ];
- ListImportedModelsRequest$ = [
- 3,
- n0,
- _LIMR,
- 0,
- [_cTB, _cTA, _nC, _mR, _nT, _sB, _sO],
- [[5, { [_hQ]: _cTB }], [5, { [_hQ]: _cTA }], [0, { [_hQ]: _nC }], [1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _sB }], [0, { [_hQ]: _sO }]]
- ];
- ListImportedModelsResponse$ = [
- 3,
- n0,
- _LIMRi,
- 0,
- [_nT, _mSod],
- [0, () => ImportedModelSummaryList]
- ];
- ListInferenceProfilesRequest$ = [
- 3,
- n0,
- _LIPR,
- 0,
- [_mR, _nT, _tE],
- [[1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _ty }]]
- ];
- ListInferenceProfilesResponse$ = [
- 3,
- n0,
- _LIPRi,
- 0,
- [_iPS, _nT],
- [[() => InferenceProfileSummaries, 0], 0]
- ];
- ListMarketplaceModelEndpointsRequest$ = [
- 3,
- n0,
- _LMMER,
- 0,
- [_mR, _nT, _mSE],
- [[1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _mSI }]]
- ];
- ListMarketplaceModelEndpointsResponse$ = [
- 3,
- n0,
- _LMMERi,
- 0,
- [_mMEa, _nT],
- [() => MarketplaceModelEndpointSummaries, 0]
- ];
- ListModelCopyJobsRequest$ = [
- 3,
- n0,
- _LMCJR,
- 0,
- [_cTA, _cTB, _sEt, _sAE, _sMAE, _tMNC, _mR, _nT, _sB, _sO],
- [[5, { [_hQ]: _cTA }], [5, { [_hQ]: _cTB }], [0, { [_hQ]: _sEt }], [0, { [_hQ]: _sAE }], [0, { [_hQ]: _sMAE }], [0, { [_hQ]: _oMNC }], [1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _sB }], [0, { [_hQ]: _sO }]]
- ];
- ListModelCopyJobsResponse$ = [
- 3,
- n0,
- _LMCJRi,
- 0,
- [_nT, _mCJS],
- [0, () => ModelCopyJobSummaries]
- ];
- ListModelCustomizationJobsRequest$ = [
- 3,
- n0,
- _LMCJRis,
- 0,
- [_cTA, _cTB, _sEt, _nC, _mR, _nT, _sB, _sO],
- [[5, { [_hQ]: _cTA }], [5, { [_hQ]: _cTB }], [0, { [_hQ]: _sEt }], [0, { [_hQ]: _nC }], [1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _sB }], [0, { [_hQ]: _sO }]]
- ];
- ListModelCustomizationJobsResponse$ = [
- 3,
- n0,
- _LMCJRist,
- 0,
- [_nT, _mCJSo],
- [0, () => ModelCustomizationJobSummaries]
- ];
- ListModelImportJobsRequest$ = [
- 3,
- n0,
- _LMIJR,
- 0,
- [_cTA, _cTB, _sEt, _nC, _mR, _nT, _sB, _sO],
- [[5, { [_hQ]: _cTA }], [5, { [_hQ]: _cTB }], [0, { [_hQ]: _sEt }], [0, { [_hQ]: _nC }], [1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _sB }], [0, { [_hQ]: _sO }]]
- ];
- ListModelImportJobsResponse$ = [
- 3,
- n0,
- _LMIJRi,
- 0,
- [_nT, _mIJS],
- [0, () => ModelImportJobSummaries]
- ];
- ListModelInvocationJobsRequest$ = [
- 3,
- n0,
- _LMIJRis,
- 0,
- [_sTA, _sTB, _sEt, _nC, _mR, _nT, _sB, _sO],
- [[5, { [_hQ]: _sTA }], [5, { [_hQ]: _sTB }], [0, { [_hQ]: _sEt }], [0, { [_hQ]: _nC }], [1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _sB }], [0, { [_hQ]: _sO }]]
- ];
- ListModelInvocationJobsResponse$ = [
- 3,
- n0,
- _LMIJRist,
- 0,
- [_nT, _iJS],
- [0, [() => ModelInvocationJobSummaries, 0]]
- ];
- ListPromptRoutersRequest$ = [
- 3,
- n0,
- _LPRR,
- 0,
- [_mR, _nT, _ty],
- [[1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _ty }]]
- ];
- ListPromptRoutersResponse$ = [
- 3,
- n0,
- _LPRRi,
- 0,
- [_pRS, _nT],
- [[() => PromptRouterSummaries, 0], 0]
- ];
- ListProvisionedModelThroughputsRequest$ = [
- 3,
- n0,
- _LPMTR,
- 0,
- [_cTA, _cTB, _sEt, _mAE, _nC, _mR, _nT, _sB, _sO],
- [[5, { [_hQ]: _cTA }], [5, { [_hQ]: _cTB }], [0, { [_hQ]: _sEt }], [0, { [_hQ]: _mAE }], [0, { [_hQ]: _nC }], [1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _sB }], [0, { [_hQ]: _sO }]]
- ];
- ListProvisionedModelThroughputsResponse$ = [
- 3,
- n0,
- _LPMTRi,
- 0,
- [_nT, _pMS],
- [0, () => ProvisionedModelSummaries]
- ];
- ListTagsForResourceRequest$ = [
- 3,
- n0,
- _LTFRR,
- 0,
- [_rARN],
- [0],
- 1
- ];
- ListTagsForResourceResponse$ = [
- 3,
- n0,
- _LTFRRi,
- 0,
- [_ta],
- [() => TagList]
- ];
- LoggingConfig$ = [
- 3,
- n0,
- _LC,
- 0,
- [_cWC, _sC, _tDDE, _iDDE, _eDDE, _vDDE, _aDDE],
- [() => CloudWatchConfig$, () => S3Config$, 2, 2, 2, 2, 2]
- ];
- MarketplaceModelEndpoint$ = [
- 3,
- n0,
- _MME,
- 0,
- [_eA, _mSI, _cA, _uA, _eCn, _eS, _st, _sM, _eSM],
- [0, 0, 5, 5, () => EndpointConfig$, 0, 0, 0, 0],
- 6
- ];
- MarketplaceModelEndpointSummary$ = [
- 3,
- n0,
- _MMES,
- 0,
- [_eA, _mSI, _cA, _uA, _st, _sM],
- [0, 0, 5, 5, 0, 0],
- 4
- ];
- MetadataAttributeSchema$ = [
- 3,
- n0,
- _MAS,
- 8,
- [_k, _ty, _d],
- [0, 0, 0],
- 3
- ];
- MetadataConfigurationForReranking$ = [
- 3,
- n0,
- _MCFR,
- 0,
- [_sMe, _sMC],
- [0, [() => RerankingMetadataSelectiveModeConfiguration$, 0]],
- 1
- ];
- ModelCopyJobSummary$ = [
- 3,
- n0,
- _MCJS,
- 0,
- [_jA, _st, _cTr, _tMA, _sAI, _sMA, _tMN, _tMKKA, _tMT, _fMa, _sMN],
- [0, 0, 5, 0, 0, 0, 0, 0, () => TagList, 0, 0],
- 6
- ];
- ModelCustomizationJobSummary$ = [
- 3,
- n0,
- _MCJSo,
- 0,
- [_jA, _bMA, _jN, _st, _cTr, _sD, _lMT, _eT, _cMA, _cMN, _cTu],
- [0, 0, 0, 0, 5, () => StatusDetails$, 5, 5, 0, 0, 0],
- 5
- ];
- ModelEnforcement$ = [
- 3,
- n0,
- _ME,
- 0,
- [_iMn, _eMx],
- [64 | 0, 64 | 0],
- 2
- ];
- ModelImportJobSummary$ = [
- 3,
- n0,
- _MIJS,
- 0,
- [_jA, _jN, _st, _cTr, _lMT, _eT, _iMA, _iMN],
- [0, 0, 0, 5, 5, 5, 0, 0],
- 4
- ];
- ModelInvocationJobS3InputDataConfig$ = [
- 3,
- n0,
- _MIJSIDC,
- 0,
- [_sU, _sIF, _sBO],
- [0, 0, 0],
- 1
- ];
- ModelInvocationJobS3OutputDataConfig$ = [
- 3,
- n0,
- _MIJSODC,
- 0,
- [_sU, _sEKI, _sBO],
- [0, 0, 0],
- 1
- ];
- ModelInvocationJobSummary$ = [
- 3,
- n0,
- _MIJSo,
- 0,
- [_jA, _jN, _mIo, _rA, _sTu, _iDC, _oDC, _cRT, _st, _m, _lMT, _eT, _vCp, _tDIH, _jET, _mIT],
- [0, 0, 0, 0, 5, () => ModelInvocationJobInputDataConfig$, () => ModelInvocationJobOutputDataConfig$, 0, 0, [() => Message, 0], 5, 5, () => VpcConfig$, 1, 5, 0],
- 7
- ];
- Offer$ = [
- 3,
- n0,
- _O,
- 0,
- [_oT, _tD, _oI],
- [0, () => TermDetails$, 0],
- 2
- ];
- OrchestrationConfiguration$ = [
- 3,
- n0,
- _OC,
- 0,
- [_qTC],
- [() => QueryTransformationConfiguration$],
- 1
- ];
- OutputDataConfig$ = [
- 3,
- n0,
- _ODC,
- 0,
- [_sU],
- [0],
- 1
- ];
- PerformanceConfiguration$ = [
- 3,
- n0,
- _PC,
- 0,
- [_la],
- [0]
- ];
- PricingTerm$ = [
- 3,
- n0,
- _PT,
- 0,
- [_rCa],
- [() => RateCard],
- 1
- ];
- PromptRouterSummary$ = [
- 3,
- n0,
- _PRS,
- 0,
- [_pRN, _rCo, _pRA, _mo, _fM, _st, _ty, _d, _cA, _uA],
- [0, () => RoutingCriteria$, 0, () => PromptRouterTargetModels, () => PromptRouterTargetModel$, 0, 0, [() => PromptRouterDescription, 0], 5, 5],
- 7
- ];
- PromptRouterTargetModel$ = [
- 3,
- n0,
- _PRTM,
- 0,
- [_mA],
- [0],
- 1
- ];
- PromptTemplate$ = [
- 3,
- n0,
- _PTr,
- 0,
- [_tPT],
- [[() => TextPromptTemplate, 0]]
- ];
- ProvisionedModelSummary$ = [
- 3,
- n0,
- _PMS,
- 0,
- [_pMN, _pMA, _mA, _dMA, _fMA, _mU, _dMU, _st, _cTr, _lMT, _cD, _cET],
- [0, 0, 0, 0, 0, 1, 1, 0, 5, 5, 0, 5],
- 10
- ];
- PutEnforcedGuardrailConfigurationRequest$ = [
- 3,
- n0,
- _PEGCR,
- 0,
- [_gIC, _cI],
- [() => AccountEnforcedGuardrailInferenceInputConfiguration$, 0],
- 1
- ];
- PutEnforcedGuardrailConfigurationResponse$ = [
- 3,
- n0,
- _PEGCRu,
- 0,
- [_cI, _uA, _uB],
- [0, 5, 0]
- ];
- PutModelInvocationLoggingConfigurationRequest$ = [
- 3,
- n0,
- _PMILCR,
- 0,
- [_lC],
- [() => LoggingConfig$],
- 1
- ];
- PutModelInvocationLoggingConfigurationResponse$ = [
- 3,
- n0,
- _PMILCRu,
- 0,
- [],
- []
- ];
- PutUseCaseForModelAccessRequest$ = [
- 3,
- n0,
- _PUCFMAR,
- 0,
- [_fD],
- [21],
- 1
- ];
- PutUseCaseForModelAccessResponse$ = [
- 3,
- n0,
- _PUCFMARu,
- 0,
- [],
- []
- ];
- QueryTransformationConfiguration$ = [
- 3,
- n0,
- _QTC,
- 0,
- [_ty],
- [0],
- 1
- ];
- RatingScaleItem$ = [
- 3,
- n0,
- _RSI,
- 0,
- [_de, _va],
- [0, () => RatingScaleItemValue$],
- 2
- ];
- RegisterMarketplaceModelEndpointRequest$ = [
- 3,
- n0,
- _RMMER,
- 0,
- [_eI, _mSI],
- [[0, 1], 0],
- 2
- ];
- RegisterMarketplaceModelEndpointResponse$ = [
- 3,
- n0,
- _RMMERe,
- 0,
- [_mME],
- [() => MarketplaceModelEndpoint$],
- 1
- ];
- RequestMetadataBaseFilters$ = [
- 3,
- n0,
- _RMBF,
- 0,
- [_eq, _nE],
- [[() => RequestMetadataMap, 0], [() => RequestMetadataMap, 0]]
- ];
- RetrieveAndGenerateConfiguration$ = [
- 3,
- n0,
- _RAGC,
- 0,
- [_ty, _kBC, _eSC],
- [0, [() => KnowledgeBaseRetrieveAndGenerateConfiguration$, 0], [() => ExternalSourcesRetrieveAndGenerateConfiguration$, 0]],
- 1
- ];
- RetrieveConfig$ = [
- 3,
- n0,
- _RC,
- 0,
- [_kBI, _kBRC],
- [0, [() => KnowledgeBaseRetrievalConfiguration$, 0]],
- 2
- ];
- RFTConfig$ = [
- 3,
- n0,
- _RFTC,
- 0,
- [_gCr, _hP],
- [() => GraderConfig$, () => RFTHyperParameters$]
- ];
- RFTHyperParameters$ = [
- 3,
- n0,
- _RFTHP,
- 0,
- [_eCp, _bSa, _lR, _mPL, _tSPP, _iMTn, _rE, _eIv],
- [1, 1, 1, 1, 1, 1, 0, 1]
- ];
- RoutingCriteria$ = [
- 3,
- n0,
- _RCo,
- 0,
- [_rQD],
- [1],
- 1
- ];
- S3Config$ = [
- 3,
- n0,
- _SC,
- 0,
- [_bN, _kP],
- [0, 0],
- 1
- ];
- S3DataSource$ = [
- 3,
- n0,
- _SDS,
- 0,
- [_sU],
- [0],
- 1
- ];
- S3ObjectDoc$ = [
- 3,
- n0,
- _SOD,
- 0,
- [_uri],
- [0],
- 1
- ];
- SageMakerEndpoint$ = [
- 3,
- n0,
- _SME,
- 0,
- [_iIC, _iTn, _eRx, _kEK, _vp],
- [1, 0, 0, 0, () => VpcConfig$],
- 3
- ];
- StartAutomatedReasoningPolicyBuildWorkflowRequest$ = [
- 3,
- n0,
- _SARPBWR,
- 0,
- [_pA, _bWT, _sCo, _cRT],
- [[0, 1], [0, 1], [() => AutomatedReasoningPolicyBuildWorkflowSource$, 16], [0, { [_hH]: _xact, [_iTd]: 1 }]],
- 3
- ];
- StartAutomatedReasoningPolicyBuildWorkflowResponse$ = [
- 3,
- n0,
- _SARPBWRt,
- 0,
- [_pA, _bWI],
- [0, 0],
- 2
- ];
- StartAutomatedReasoningPolicyTestWorkflowRequest$ = [
- 3,
- n0,
- _SARPTWR,
- 0,
- [_pA, _bWI, _tCIe, _cRT],
- [[0, 1], [0, 1], 64 | 0, [0, 4]],
- 2
- ];
- StartAutomatedReasoningPolicyTestWorkflowResponse$ = [
- 3,
- n0,
- _SARPTWRt,
- 0,
- [_pA],
- [0],
- 1
- ];
- StatusDetails$ = [
- 3,
- n0,
- _SD,
- 0,
- [_vD, _dPD, _tDr],
- [() => ValidationDetails$, () => DataProcessingDetails$, () => TrainingDetails$]
- ];
- StopEvaluationJobRequest$ = [
- 3,
- n0,
- _SEJR,
- 0,
- [_jI],
- [[() => EvaluationJobIdentifier, 1]],
- 1
- ];
- StopEvaluationJobResponse$ = [
- 3,
- n0,
- _SEJRt,
- 0,
- [],
- []
- ];
- StopModelCustomizationJobRequest$ = [
- 3,
- n0,
- _SMCJR,
- 0,
- [_jI],
- [[0, 1]],
- 1
- ];
- StopModelCustomizationJobResponse$ = [
- 3,
- n0,
- _SMCJRt,
- 0,
- [],
- []
- ];
- StopModelInvocationJobRequest$ = [
- 3,
- n0,
- _SMIJR,
- 0,
- [_jI],
- [[0, 1]],
- 1
- ];
- StopModelInvocationJobResponse$ = [
- 3,
- n0,
- _SMIJRt,
- 0,
- [],
- []
- ];
- SupportTerm$ = [
- 3,
- n0,
- _ST,
- 0,
- [_rPD],
- [0]
- ];
- Tag$ = [
- 3,
- n0,
- _T,
- 0,
- [_k, _va],
- [0, 0],
- 2
- ];
- TagResourceRequest$ = [
- 3,
- n0,
- _TRR,
- 0,
- [_rARN, _ta],
- [0, () => TagList],
- 2
- ];
- TagResourceResponse$ = [
- 3,
- n0,
- _TRRa,
- 0,
- [],
- []
- ];
- TeacherModelConfig$ = [
- 3,
- n0,
- _TMC,
- 0,
- [_tMI, _mRLFI],
- [0, 1],
- 1
- ];
- TermDetails$ = [
- 3,
- n0,
- _TD,
- 0,
- [_uBPT, _lTeg, _sTup, _vT],
- [() => PricingTerm$, () => LegalTerm$, () => SupportTerm$, () => ValidityTerm$],
- 3
- ];
- TextInferenceConfig$ = [
- 3,
- n0,
- _TIC,
- 0,
- [_tem, _tPo, _mTa, _sS],
- [1, 1, 1, 64 | 0]
- ];
- TrainingDataConfig$ = [
- 3,
- n0,
- _TDC,
- 0,
- [_sU, _iLC],
- [0, [() => InvocationLogsConfig$, 0]]
- ];
- TrainingDetails$ = [
- 3,
- n0,
- _TDr,
- 0,
- [_st, _cTr, _lMT],
- [0, 5, 5]
- ];
- TrainingMetrics$ = [
- 3,
- n0,
- _TM,
- 0,
- [_tL],
- [1]
- ];
- UntagResourceRequest$ = [
- 3,
- n0,
- _URR,
- 0,
- [_rARN, _tK],
- [0, 64 | 0],
- 2
- ];
- UntagResourceResponse$ = [
- 3,
- n0,
- _URRn,
- 0,
- [],
- []
- ];
- UpdateAutomatedReasoningPolicyAnnotationsRequest$ = [
- 3,
- n0,
- _UARPAR,
- 0,
- [_pA, _bWI, _an, _lUASH],
- [[0, 1], [0, 1], [() => AutomatedReasoningPolicyAnnotationList, 0], 0],
- 4
- ];
- UpdateAutomatedReasoningPolicyAnnotationsResponse$ = [
- 3,
- n0,
- _UARPARp,
- 0,
- [_pA, _bWI, _aSH, _uA],
- [0, 0, 0, 5],
- 4
- ];
- UpdateAutomatedReasoningPolicyRequest$ = [
- 3,
- n0,
- _UARPR,
- 0,
- [_pA, _pD, _n, _d],
- [[0, 1], [() => AutomatedReasoningPolicyDefinition$, 0], [() => AutomatedReasoningPolicyName, 0], [() => AutomatedReasoningPolicyDescription, 0]],
- 2
- ];
- UpdateAutomatedReasoningPolicyResponse$ = [
- 3,
- n0,
- _UARPRp,
- 0,
- [_pA, _n, _dHe, _uA],
- [0, [() => AutomatedReasoningPolicyName, 0], 0, 5],
- 4
- ];
- UpdateAutomatedReasoningPolicyTestCaseRequest$ = [
- 3,
- n0,
- _UARPTCR,
- 0,
- [_pA, _tCI, _gC, _lUA, _eAFR, _qC, _cT, _cRT],
- [[0, 1], [0, 1], [() => AutomatedReasoningPolicyTestGuardContent, 0], 5, 0, [() => AutomatedReasoningPolicyTestQueryContent, 0], 1, [0, 4]],
- 5
- ];
- UpdateAutomatedReasoningPolicyTestCaseResponse$ = [
- 3,
- n0,
- _UARPTCRp,
- 0,
- [_pA, _tCI],
- [0, 0],
- 2
- ];
- UpdateCustomModelDeploymentRequest$ = [
- 3,
- n0,
- _UCMDR,
- 0,
- [_mA, _cMDI],
- [0, [0, 1]],
- 2
- ];
- UpdateCustomModelDeploymentResponse$ = [
- 3,
- n0,
- _UCMDRp,
- 0,
- [_cMDA],
- [0],
- 1
- ];
- UpdateGuardrailRequest$ = [
- 3,
- n0,
- _UGR,
- 0,
- [_gI, _n, _bIM, _bOM, _d, _tPC, _cPC, _wPC, _sIPC, _cGPC, _aRPC, _cRC, _kKI],
- [[0, 1], [() => GuardrailName, 0], [() => GuardrailBlockedMessaging, 0], [() => GuardrailBlockedMessaging, 0], [() => GuardrailDescription, 0], [() => GuardrailTopicPolicyConfig$, 0], [() => GuardrailContentPolicyConfig$, 0], [() => GuardrailWordPolicyConfig$, 0], () => GuardrailSensitiveInformationPolicyConfig$, [() => GuardrailContextualGroundingPolicyConfig$, 0], () => GuardrailAutomatedReasoningPolicyConfig$, () => GuardrailCrossRegionConfig$, 0],
- 4
- ];
- UpdateGuardrailResponse$ = [
- 3,
- n0,
- _UGRp,
- 0,
- [_gIu, _gA, _ve, _uA],
- [0, 0, 0, 5],
- 4
- ];
- UpdateMarketplaceModelEndpointRequest$ = [
- 3,
- n0,
- _UMMER,
- 0,
- [_eA, _eCn, _cRT],
- [[0, 1], () => EndpointConfig$, [0, 4]],
- 2
- ];
- UpdateMarketplaceModelEndpointResponse$ = [
- 3,
- n0,
- _UMMERp,
- 0,
- [_mME],
- [() => MarketplaceModelEndpoint$],
- 1
- ];
- UpdateProvisionedModelThroughputRequest$ = [
- 3,
- n0,
- _UPMTR,
- 0,
- [_pMI, _dPMN, _dMI],
- [[0, 1], 0, 0],
- 1
- ];
- UpdateProvisionedModelThroughputResponse$ = [
- 3,
- n0,
- _UPMTRp,
- 0,
- [],
- []
- ];
- ValidationDataConfig$ = [
- 3,
- n0,
- _VDC,
- 0,
- [_val],
- [() => Validators],
- 1
- ];
- ValidationDetails$ = [
- 3,
- n0,
- _VD,
- 0,
- [_st, _cTr, _lMT],
- [0, 5, 5]
- ];
- Validator$ = [
- 3,
- n0,
- _V,
- 0,
- [_sU],
- [0],
- 1
- ];
- ValidatorMetric$ = [
- 3,
- n0,
- _VM,
- 0,
- [_vL],
- [1]
- ];
- ValidityTerm$ = [
- 3,
- n0,
- _VT,
- 0,
- [_aD],
- [0]
- ];
- VectorSearchBedrockRerankingConfiguration$ = [
- 3,
- n0,
- _VSBRC,
- 0,
- [_mC, _nORR, _mCe],
- [() => VectorSearchBedrockRerankingModelConfiguration$, 1, [() => MetadataConfigurationForReranking$, 0]],
- 1
- ];
- VectorSearchBedrockRerankingModelConfiguration$ = [
- 3,
- n0,
- _VSBRMC,
- 0,
- [_mA, _aMRF],
- [0, 128 | 15],
- 1
- ];
- VectorSearchRerankingConfiguration$ = [
- 3,
- n0,
- _VSRC,
- 0,
- [_ty, _bRC],
- [0, [() => VectorSearchBedrockRerankingConfiguration$, 0]],
- 1
- ];
- VpcConfig$ = [
- 3,
- n0,
- _VC,
- 0,
- [_sIu, _sGI],
- [64 | 0, 64 | 0],
- 2
- ];
- AccountEnforcedGuardrailsOutputConfiguration = [
- 1,
- n0,
- _AEGOCc,
- 0,
- () => AccountEnforcedGuardrailOutputConfiguration$
- ];
- AutomatedEvaluationCustomMetrics = [
- 1,
- n0,
- _AECM,
- 0,
- [
- () => AutomatedEvaluationCustomMetricSource$,
- 0
- ]
- ];
- AutomatedReasoningCheckDifferenceScenarioList = [
- 1,
- n0,
- _ARCDSL,
- 0,
- [
- () => AutomatedReasoningCheckScenario$,
- 0
- ]
- ];
- AutomatedReasoningCheckFindingList = [
- 1,
- n0,
- _ARCFL,
- 0,
- [
- () => AutomatedReasoningCheckFinding$,
- 0
- ]
- ];
- AutomatedReasoningCheckInputTextReferenceList = [
- 1,
- n0,
- _ARCITRL,
- 0,
- [
- () => AutomatedReasoningCheckInputTextReference$,
- 0
- ]
- ];
- AutomatedReasoningCheckRuleList = [
- 1,
- n0,
- _ARCRL,
- 0,
- () => AutomatedReasoningCheckRule$
- ];
- AutomatedReasoningCheckTranslationList = [
- 1,
- n0,
- _ARCTL,
- 0,
- [
- () => AutomatedReasoningCheckTranslation$,
- 0
- ]
- ];
- AutomatedReasoningCheckTranslationOptionList = [
- 1,
- n0,
- _ARCTOL,
- 0,
- [
- () => AutomatedReasoningCheckTranslationOption$,
- 0
- ]
- ];
- AutomatedReasoningLogicStatementList = [
- 1,
- n0,
- _ARLSL,
- 0,
- [
- () => AutomatedReasoningLogicStatement$,
- 0
- ]
- ];
- AutomatedReasoningPolicyAnnotatedChunkList = [
- 1,
- n0,
- _ARPACL,
- 0,
- [
- () => AutomatedReasoningPolicyAnnotatedChunk$,
- 0
- ]
- ];
- AutomatedReasoningPolicyAnnotatedContentList = [
- 1,
- n0,
- _ARPACLu,
- 0,
- [
- () => AutomatedReasoningPolicyAnnotatedContent$,
- 0
- ]
- ];
- AutomatedReasoningPolicyAnnotationList = [
- 1,
- n0,
- _ARPALu,
- 0,
- [
- () => AutomatedReasoningPolicyAnnotation$,
- 0
- ]
- ];
- AutomatedReasoningPolicyArnList = 64 | 0;
- AutomatedReasoningPolicyAtomicStatementList = [
- 1,
- n0,
- _ARPASL,
- 0,
- [
- () => AutomatedReasoningPolicyAtomicStatement$,
- 0
- ]
- ];
- AutomatedReasoningPolicyBuildLogEntryList = [
- 1,
- n0,
- _ARPBLEL,
- 0,
- [
- () => AutomatedReasoningPolicyBuildLogEntry$,
- 0
- ]
- ];
- AutomatedReasoningPolicyBuildResultAssetManifestList = [
- 1,
- n0,
- _ARPBRAML,
- 0,
- [
- () => AutomatedReasoningPolicyBuildResultAssetManifestEntry$,
- 0
- ]
- ];
- AutomatedReasoningPolicyBuildStepList = [
- 1,
- n0,
- _ARPBSL,
- 0,
- [
- () => AutomatedReasoningPolicyBuildStep$,
- 0
- ]
- ];
- AutomatedReasoningPolicyBuildStepMessageList = [
- 1,
- n0,
- _ARPBSML,
- 0,
- () => AutomatedReasoningPolicyBuildStepMessage$
- ];
- AutomatedReasoningPolicyBuildWorkflowDocumentList = [
- 1,
- n0,
- _ARPBWDL,
- 0,
- [
- () => AutomatedReasoningPolicyBuildWorkflowDocument$,
- 0
- ]
- ];
- AutomatedReasoningPolicyBuildWorkflowSummaries = [
- 1,
- n0,
- _ARPBWSut,
- 0,
- () => AutomatedReasoningPolicyBuildWorkflowSummary$
- ];
- AutomatedReasoningPolicyConflictedRuleIdList = 64 | 0;
- AutomatedReasoningPolicyDefinitionRuleIdList = 64 | 0;
- AutomatedReasoningPolicyDefinitionRuleList = [
- 1,
- n0,
- _ARPDRL,
- 0,
- [
- () => AutomatedReasoningPolicyDefinitionRule$,
- 0
- ]
- ];
- AutomatedReasoningPolicyDefinitionTypeList = [
- 1,
- n0,
- _ARPDTL,
- 0,
- [
- () => AutomatedReasoningPolicyDefinitionType$,
- 0
- ]
- ];
- AutomatedReasoningPolicyDefinitionTypeNameList = [
- 1,
- n0,
- _ARPDTNL,
- 0,
- [
- () => AutomatedReasoningPolicyDefinitionTypeName,
- 0
- ]
- ];
- AutomatedReasoningPolicyDefinitionTypeValueList = [
- 1,
- n0,
- _ARPDTVL,
- 0,
- [
- () => AutomatedReasoningPolicyDefinitionTypeValue$,
- 0
- ]
- ];
- AutomatedReasoningPolicyDefinitionTypeValuePairList = [
- 1,
- n0,
- _ARPDTVPL,
- 0,
- [
- () => AutomatedReasoningPolicyDefinitionTypeValuePair$,
- 0
- ]
- ];
- AutomatedReasoningPolicyDefinitionVariableList = [
- 1,
- n0,
- _ARPDVL,
- 0,
- [
- () => AutomatedReasoningPolicyDefinitionVariable$,
- 0
- ]
- ];
- AutomatedReasoningPolicyDefinitionVariableNameList = [
- 1,
- n0,
- _ARPDVNL,
- 0,
- [
- () => AutomatedReasoningPolicyDefinitionVariableName,
- 0
- ]
- ];
- AutomatedReasoningPolicyDisjointedRuleIdList = 64 | 0;
- AutomatedReasoningPolicyDisjointRuleSetList = [
- 1,
- n0,
- _ARPDRSL,
- 0,
- [
- () => AutomatedReasoningPolicyDisjointRuleSet$,
- 0
- ]
- ];
- AutomatedReasoningPolicyGeneratedTestCaseList = [
- 1,
- n0,
- _ARPGTCL,
- 0,
- [
- () => AutomatedReasoningPolicyGeneratedTestCase$,
- 0
- ]
- ];
- AutomatedReasoningPolicyGenerateFidelityReportDocumentList = [
- 1,
- n0,
- _ARPGFRDL,
- 0,
- [
- () => AutomatedReasoningPolicyBuildWorkflowDocument$,
- 0
- ]
- ];
- AutomatedReasoningPolicyJustificationList = [
- 1,
- n0,
- _ARPJL,
- 0,
- [
- () => AutomatedReasoningPolicyJustificationText,
- 0
- ]
- ];
- AutomatedReasoningPolicyLineNumberList = 64 | 1;
- AutomatedReasoningPolicyReportSourceDocumentList = [
- 1,
- n0,
- _ARPRSDL,
- 0,
- [
- () => AutomatedReasoningPolicyReportSourceDocument$,
- 0
- ]
- ];
- AutomatedReasoningPolicyScenarioList = [
- 1,
- n0,
- _ARPSLu,
- 0,
- [
- () => AutomatedReasoningPolicyScenario$,
- 0
- ]
- ];
- AutomatedReasoningPolicyStatementReferenceList = [
- 1,
- n0,
- _ARPSRL,
- 0,
- () => AutomatedReasoningPolicyStatementReference$
- ];
- AutomatedReasoningPolicySummaries = [
- 1,
- n0,
- _ARPSuto,
- 0,
- [
- () => AutomatedReasoningPolicySummary$,
- 0
- ]
- ];
- AutomatedReasoningPolicyTestCaseIdList = 64 | 0;
- AutomatedReasoningPolicyTestCaseList = [
- 1,
- n0,
- _ARPTCL,
- 0,
- [
- () => AutomatedReasoningPolicyTestCase$,
- 0
- ]
- ];
- AutomatedReasoningPolicyTestList = [
- 1,
- n0,
- _ARPTL,
- 0,
- [
- () => AutomatedReasoningPolicyTestResult$,
- 0
- ]
- ];
- AutomatedReasoningPolicyTypeValueAnnotationList = [
- 1,
- n0,
- _ARPTVAL,
- 0,
- [
- () => AutomatedReasoningPolicyTypeValueAnnotation$,
- 0
- ]
- ];
- BatchDeleteEvaluationJobErrors = [
- 1,
- n0,
- _BDEJEa,
- 0,
- [
- () => BatchDeleteEvaluationJobError$,
- 0
- ]
- ];
- BatchDeleteEvaluationJobItems = [
- 1,
- n0,
- _BDEJIa,
- 0,
- [
- () => BatchDeleteEvaluationJobItem$,
- 0
- ]
- ];
- BedrockEvaluatorModels = [
- 1,
- n0,
- _BEMe,
- 0,
- () => BedrockEvaluatorModel$
- ];
- CustomMetricBedrockEvaluatorModels = [
- 1,
- n0,
- _CMBEMu,
- 0,
- () => CustomMetricBedrockEvaluatorModel$
- ];
- CustomModelDeploymentSummaryList = [
- 1,
- n0,
- _CMDSL,
- 0,
- () => CustomModelDeploymentSummary$
- ];
- CustomModelSummaryList = [
- 1,
- n0,
- _CMSL,
- 0,
- () => CustomModelSummary$
- ];
- ErrorMessages = 64 | 0;
- EvaluationBedrockKnowledgeBaseIdentifiers = 64 | 0;
- EvaluationBedrockModelIdentifiers = 64 | 0;
- EvaluationDatasetMetricConfigs = [
- 1,
- n0,
- _EDMCv,
- 0,
- [
- () => EvaluationDatasetMetricConfig$,
- 0
- ]
- ];
- EvaluationJobIdentifiers = [
- 1,
- n0,
- _EJIv,
- 0,
- [
- () => EvaluationJobIdentifier,
- 0
- ]
- ];
- EvaluationMetricNames = [
- 1,
- n0,
- _EMNv,
- 0,
- [
- () => EvaluationMetricName,
- 0
- ]
- ];
- EvaluationModelConfigs = [
- 1,
- n0,
- _EMC,
- 0,
- [
- () => EvaluationModelConfig$,
- 0
- ]
- ];
- EvaluationPrecomputedInferenceSourceIdentifiers = 64 | 0;
- EvaluationPrecomputedRagSourceIdentifiers = 64 | 0;
- EvaluationSummaries = [
- 1,
- n0,
- _ESv,
- 0,
- () => EvaluationSummary$
- ];
- EvaluationTaskTypes = 64 | 0;
- EvaluatorModelIdentifiers = 64 | 0;
- ExcludedModelsList = 64 | 0;
- ExternalSources = [
- 1,
- n0,
- _ESxt,
- 0,
- [
- () => ExternalSource$,
- 0
- ]
- ];
- FieldsForReranking = [
- 1,
- n0,
- _FFRi,
- 8,
- () => FieldForReranking$
- ];
- FoundationModelSummaryList = [
- 1,
- n0,
- _FMSL,
- 0,
- () => FoundationModelSummary$
- ];
- GuardrailContentFilters = [
- 1,
- n0,
- _GCFu,
- 0,
- [
- () => GuardrailContentFilter$,
- 0
- ]
- ];
- GuardrailContentFiltersConfig = [
- 1,
- n0,
- _GCFCu,
- 0,
- [
- () => GuardrailContentFilterConfig$,
- 0
- ]
- ];
- GuardrailContextualGroundingFilters = [
- 1,
- n0,
- _GCGFu,
- 0,
- [
- () => GuardrailContextualGroundingFilter$,
- 0
- ]
- ];
- GuardrailContextualGroundingFiltersConfig = [
- 1,
- n0,
- _GCGFCu,
- 0,
- [
- () => GuardrailContextualGroundingFilterConfig$,
- 0
- ]
- ];
- GuardrailFailureRecommendations = [
- 1,
- n0,
- _GFRu,
- 0,
- [
- () => GuardrailFailureRecommendation,
- 0
- ]
- ];
- GuardrailManagedWordLists = [
- 1,
- n0,
- _GMWL,
- 0,
- [
- () => GuardrailManagedWords$,
- 0
- ]
- ];
- GuardrailManagedWordListsConfig = [
- 1,
- n0,
- _GMWLC,
- 0,
- [
- () => GuardrailManagedWordsConfig$,
- 0
- ]
- ];
- GuardrailModalities = [
- 1,
- n0,
- _GMu,
- 0,
- [
- () => GuardrailModality,
- 0
- ]
- ];
- GuardrailPiiEntities = [
- 1,
- n0,
- _GPEu,
- 0,
- () => GuardrailPiiEntity$
- ];
- GuardrailPiiEntitiesConfig = [
- 1,
- n0,
- _GPECu,
- 0,
- () => GuardrailPiiEntityConfig$
- ];
- GuardrailRegexes = [
- 1,
- n0,
- _GRu,
- 0,
- () => GuardrailRegex$
- ];
- GuardrailRegexesConfig = [
- 1,
- n0,
- _GRCu,
- 0,
- () => GuardrailRegexConfig$
- ];
- GuardrailStatusReasons = [
- 1,
- n0,
- _GSRu,
- 0,
- [
- () => GuardrailStatusReason,
- 0
- ]
- ];
- GuardrailSummaries = [
- 1,
- n0,
- _GSu,
- 0,
- [
- () => GuardrailSummary$,
- 0
- ]
- ];
- GuardrailTopicExamples = [
- 1,
- n0,
- _GTEu,
- 0,
- [
- () => GuardrailTopicExample,
- 0
- ]
- ];
- GuardrailTopics = [
- 1,
- n0,
- _GTu,
- 0,
- [
- () => GuardrailTopic$,
- 0
- ]
- ];
- GuardrailTopicsConfig = [
- 1,
- n0,
- _GTCu,
- 0,
- [
- () => GuardrailTopicConfig$,
- 0
- ]
- ];
- GuardrailWords = [
- 1,
- n0,
- _GWu,
- 0,
- [
- () => GuardrailWord$,
- 0
- ]
- ];
- GuardrailWordsConfig = [
- 1,
- n0,
- _GWCu,
- 0,
- [
- () => GuardrailWordConfig$,
- 0
- ]
- ];
- HumanEvaluationCustomMetrics = [
- 1,
- n0,
- _HECMu,
- 0,
- [
- () => HumanEvaluationCustomMetric$,
- 0
- ]
- ];
- ImportedModelSummaryList = [
- 1,
- n0,
- _IMSL,
- 0,
- () => ImportedModelSummary$
- ];
- IncludedModelsList = 64 | 0;
- InferenceProfileModels = [
- 1,
- n0,
- _IPMn,
- 0,
- () => InferenceProfileModel$
- ];
- InferenceProfileSummaries = [
- 1,
- n0,
- _IPSn,
- 0,
- [
- () => InferenceProfileSummary$,
- 0
- ]
- ];
- InferenceTypeList = 64 | 0;
- MarketplaceModelEndpointSummaries = [
- 1,
- n0,
- _MMESa,
- 0,
- () => MarketplaceModelEndpointSummary$
- ];
- MetadataAttributeSchemaList = [
- 1,
- n0,
- _MASL,
- 0,
- [
- () => MetadataAttributeSchema$,
- 0
- ]
- ];
- ModelCopyJobSummaries = [
- 1,
- n0,
- _MCJSod,
- 0,
- () => ModelCopyJobSummary$
- ];
- ModelCustomizationJobSummaries = [
- 1,
- n0,
- _MCJSode,
- 0,
- () => ModelCustomizationJobSummary$
- ];
- ModelCustomizationList = 64 | 0;
- ModelImportJobSummaries = [
- 1,
- n0,
- _MIJSod,
- 0,
- () => ModelImportJobSummary$
- ];
- ModelInvocationJobSummaries = [
- 1,
- n0,
- _MIJSode,
- 0,
- [
- () => ModelInvocationJobSummary$,
- 0
- ]
- ];
- ModelModalityList = 64 | 0;
- Offers = [
- 1,
- n0,
- _Of,
- 0,
- () => Offer$
- ];
- PromptRouterSummaries = [
- 1,
- n0,
- _PRSr,
- 0,
- [
- () => PromptRouterSummary$,
- 0
- ]
- ];
- PromptRouterTargetModels = [
- 1,
- n0,
- _PRTMr,
- 0,
- () => PromptRouterTargetModel$
- ];
- ProvisionedModelSummaries = [
- 1,
- n0,
- _PMSr,
- 0,
- () => ProvisionedModelSummary$
- ];
- RagConfigs = [
- 1,
- n0,
- _RCa,
- 0,
- [
- () => RAGConfig$,
- 0
- ]
- ];
- RAGStopSequences = 64 | 0;
- RateCard = [
- 1,
- n0,
- _RCat,
- 0,
- () => DimensionalPriceRate$
- ];
- RatingScale = [
- 1,
- n0,
- _RS,
- 0,
- () => RatingScaleItem$
- ];
- RequestMetadataFiltersList = [
- 1,
- n0,
- _RMFL,
- 0,
- [
- () => RequestMetadataBaseFilters$,
- 0
- ]
- ];
- RetrievalFilterList = [
- 1,
- n0,
- _RFL,
- 0,
- [
- () => RetrievalFilter$,
- 0
- ]
- ];
- SecurityGroupIds = 64 | 0;
- SubnetIds = 64 | 0;
- TagKeyList = 64 | 0;
- TagList = [
- 1,
- n0,
- _TL,
- 0,
- () => Tag$
- ];
- ValidationMetrics = [
- 1,
- n0,
- _VMa,
- 0,
- () => ValidatorMetric$
- ];
- Validators = [
- 1,
- n0,
- _Va,
- 0,
- () => Validator$
- ];
- AdditionalModelRequestFields = 128 | 15;
- AutomatedReasoningPolicyRuleReportMap = [
- 2,
- n0,
- _ARPRRM,
- 0,
- [
- 0,
- 0
- ],
- [
- () => AutomatedReasoningPolicyRuleReport$,
- 0
- ]
- ];
- AutomatedReasoningPolicyVariableReportMap = [
- 2,
- n0,
- _ARPVRM,
- 0,
- [
- () => AutomatedReasoningPolicyDefinitionVariableName,
- 0
- ],
- [
- () => AutomatedReasoningPolicyVariableReport$,
- 0
- ]
- ];
- ModelCustomizationHyperParameters = 128 | 0;
- RequestMetadataMap = [
- 2,
- n0,
- _RMM,
- 8,
- 0,
- 0
- ];
- AutomatedEvaluationCustomMetricSource$ = [
- 4,
- n0,
- _AECMS,
- 0,
- [_cMD],
- [[() => CustomMetricDefinition$, 0]]
- ];
- AutomatedReasoningCheckFinding$ = [
- 4,
- n0,
- _ARCF,
- 0,
- [_vali, _inv, _sa, _im, _tA, _tCoo, _nTo],
- [[() => AutomatedReasoningCheckValidFinding$, 0], [() => AutomatedReasoningCheckInvalidFinding$, 0], [() => AutomatedReasoningCheckSatisfiableFinding$, 0], [() => AutomatedReasoningCheckImpossibleFinding$, 0], [() => AutomatedReasoningCheckTranslationAmbiguousFinding$, 0], () => AutomatedReasoningCheckTooComplexFinding$, () => AutomatedReasoningCheckNoTranslationsFinding$]
- ];
- AutomatedReasoningPolicyAnnotatedContent$ = [
- 4,
- n0,
- _ARPACu,
- 0,
- [_lin],
- [[() => AutomatedReasoningPolicyAnnotatedLine$, 0]]
- ];
- AutomatedReasoningPolicyAnnotation$ = [
- 4,
- n0,
- _ARPA,
- 0,
- [_aTd, _uTp, _dT, _aV, _uVp, _dV, _aR, _uR, _dR, _aRFNL, _uFRF, _uFSF, _iCn],
- [[() => AutomatedReasoningPolicyAddTypeAnnotation$, 0], [() => AutomatedReasoningPolicyUpdateTypeAnnotation$, 0], [() => AutomatedReasoningPolicyDeleteTypeAnnotation$, 0], [() => AutomatedReasoningPolicyAddVariableAnnotation$, 0], [() => AutomatedReasoningPolicyUpdateVariableAnnotation$, 0], [() => AutomatedReasoningPolicyDeleteVariableAnnotation$, 0], [() => AutomatedReasoningPolicyAddRuleAnnotation$, 0], [() => AutomatedReasoningPolicyUpdateRuleAnnotation$, 0], () => AutomatedReasoningPolicyDeleteRuleAnnotation$, [() => AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation$, 0], [() => AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation$, 0], [() => AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation$, 0], [() => AutomatedReasoningPolicyIngestContentAnnotation$, 0]]
- ];
- AutomatedReasoningPolicyBuildResultAssets$ = [
- 4,
- n0,
- _ARPBRA,
- 0,
- [_pD, _qR, _bL, _gTC, _pS, _aM, _do, _fRi],
- [[() => AutomatedReasoningPolicyDefinition$, 0], [() => AutomatedReasoningPolicyDefinitionQualityReport$, 0], [() => AutomatedReasoningPolicyBuildLog$, 0], [() => AutomatedReasoningPolicyGeneratedTestCases$, 0], [() => AutomatedReasoningPolicyScenarios$, 0], [() => AutomatedReasoningPolicyBuildResultAssetManifest$, 0], [() => AutomatedReasoningPolicySourceDocument$, 0], [() => AutomatedReasoningPolicyFidelityReport$, 0]]
- ];
- AutomatedReasoningPolicyBuildStepContext$ = [
- 4,
- n0,
- _ARPBSC,
- 0,
- [_pl, _mu],
- [() => AutomatedReasoningPolicyPlanning$, [() => AutomatedReasoningPolicyMutation$, 0]]
- ];
- AutomatedReasoningPolicyDefinitionElement$ = [
- 4,
- n0,
- _ARPDE,
- 0,
- [_pDV, _pDT, _pDR],
- [[() => AutomatedReasoningPolicyDefinitionVariable$, 0], [() => AutomatedReasoningPolicyDefinitionType$, 0], [() => AutomatedReasoningPolicyDefinitionRule$, 0]]
- ];
- AutomatedReasoningPolicyGenerateFidelityReportContent$ = [
- 4,
- n0,
- _ARPGFRC,
- 0,
- [_doc],
- [[() => AutomatedReasoningPolicyGenerateFidelityReportDocumentList, 0]]
- ];
- AutomatedReasoningPolicyMutation$ = [
- 4,
- n0,
- _ARPM,
- 0,
- [_aTd, _uTp, _dT, _aV, _uVp, _dV, _aR, _uR, _dR],
- [[() => AutomatedReasoningPolicyAddTypeMutation$, 0], [() => AutomatedReasoningPolicyUpdateTypeMutation$, 0], [() => AutomatedReasoningPolicyDeleteTypeMutation$, 0], [() => AutomatedReasoningPolicyAddVariableMutation$, 0], [() => AutomatedReasoningPolicyUpdateVariableMutation$, 0], [() => AutomatedReasoningPolicyDeleteVariableMutation$, 0], [() => AutomatedReasoningPolicyAddRuleMutation$, 0], [() => AutomatedReasoningPolicyUpdateRuleMutation$, 0], () => AutomatedReasoningPolicyDeleteRuleMutation$]
- ];
- AutomatedReasoningPolicyTypeValueAnnotation$ = [
- 4,
- n0,
- _ARPTVA,
- 0,
- [_aTV, _uTVp, _dTV],
- [[() => AutomatedReasoningPolicyAddTypeValue$, 0], [() => AutomatedReasoningPolicyUpdateTypeValue$, 0], () => AutomatedReasoningPolicyDeleteTypeValue$]
- ];
- AutomatedReasoningPolicyWorkflowTypeContent$ = [
- 4,
- n0,
- _ARPWTC,
- 0,
- [_doc, _pRAo, _gFRC],
- [[() => AutomatedReasoningPolicyBuildWorkflowDocumentList, 0], [() => AutomatedReasoningPolicyBuildWorkflowRepairContent$, 0], [() => AutomatedReasoningPolicyGenerateFidelityReportContent$, 0]]
- ];
- CustomizationConfig$ = [
- 4,
- n0,
- _CC,
- 0,
- [_dCi, _rCf],
- [() => DistillationConfig$, () => RFTConfig$]
- ];
- EndpointConfig$ = [
- 4,
- n0,
- _EC,
- 0,
- [_sMa],
- [() => SageMakerEndpoint$]
- ];
- EvaluationConfig$ = [
- 4,
- n0,
- _ECv,
- 0,
- [_au, _h],
- [[() => AutomatedEvaluationConfig$, 0], [() => HumanEvaluationConfig$, 0]]
- ];
- EvaluationDatasetLocation$ = [
- 4,
- n0,
- _EDL,
- 0,
- [_sU],
- [0]
- ];
- EvaluationInferenceConfig$ = [
- 4,
- n0,
- _EIC,
- 0,
- [_mo, _rCag],
- [[() => EvaluationModelConfigs, 0], [() => RagConfigs, 0]]
- ];
- EvaluationModelConfig$ = [
- 4,
- n0,
- _EMCv,
- 0,
- [_bM, _pIS],
- [[() => EvaluationBedrockModel$, 0], () => EvaluationPrecomputedInferenceSource$]
- ];
- EvaluationPrecomputedRagSourceConfig$ = [
- 4,
- n0,
- _EPRSCv,
- 0,
- [_rSC, _rAGSC],
- [() => EvaluationPrecomputedRetrieveSourceConfig$, () => EvaluationPrecomputedRetrieveAndGenerateSourceConfig$]
- ];
- EvaluatorModelConfig$ = [
- 4,
- n0,
- _EMCva,
- 0,
- [_bEM],
- [() => BedrockEvaluatorModels]
- ];
- GraderConfig$ = [
- 4,
- n0,
- _GCr,
- 0,
- [_lG],
- [() => LambdaGraderConfig$]
- ];
- InferenceProfileModelSource$ = [
- 4,
- n0,
- _IPMS,
- 0,
- [_cF],
- [0]
- ];
- InvocationLogSource$ = [
- 4,
- n0,
- _ILS,
- 0,
- [_sU],
- [0]
- ];
- KnowledgeBaseConfig$ = [
- 4,
- n0,
- _KBC,
- 0,
- [_rCetr, _rAGC],
- [[() => RetrieveConfig$, 0], [() => RetrieveAndGenerateConfiguration$, 0]]
- ];
- ModelDataSource$ = [
- 4,
- n0,
- _MDS,
- 0,
- [_sDS],
- [() => S3DataSource$]
- ];
- ModelInvocationJobInputDataConfig$ = [
- 4,
- n0,
- _MIJIDC,
- 0,
- [_sIDC],
- [() => ModelInvocationJobS3InputDataConfig$]
- ];
- ModelInvocationJobOutputDataConfig$ = [
- 4,
- n0,
- _MIJODC,
- 0,
- [_sODC],
- [() => ModelInvocationJobS3OutputDataConfig$]
- ];
- RAGConfig$ = [
- 4,
- n0,
- _RAGCo,
- 0,
- [_kBCn, _pRSC],
- [[() => KnowledgeBaseConfig$, 0], () => EvaluationPrecomputedRagSourceConfig$]
- ];
- RatingScaleItemValue$ = [
- 4,
- n0,
- _RSIV,
- 0,
- [_sV, _fV],
- [0, 1]
- ];
- RequestMetadataFilters$ = [
- 4,
- n0,
- _RMF,
- 0,
- [_eq, _nE, _aAn, _oAr],
- [[() => RequestMetadataMap, 0], [() => RequestMetadataMap, 0], [() => RequestMetadataFiltersList, 0], [() => RequestMetadataFiltersList, 0]]
- ];
- RerankingMetadataSelectiveModeConfiguration$ = [
- 4,
- n0,
- _RMSMC,
- 0,
- [_fTI, _fTE],
- [[() => FieldsForReranking, 0], [() => FieldsForReranking, 0]]
- ];
- RetrievalFilter$ = [
- 4,
- n0,
- _RF,
- 8,
- [_eq, _nE, _gT, _gTOE, _lTes, _lTOE, _in_, _nI, _sW, _lCi, _sCt, _aAn, _oAr],
- [() => FilterAttribute$, () => FilterAttribute$, () => FilterAttribute$, () => FilterAttribute$, () => FilterAttribute$, () => FilterAttribute$, () => FilterAttribute$, () => FilterAttribute$, () => FilterAttribute$, () => FilterAttribute$, () => FilterAttribute$, [() => RetrievalFilterList, 0], [() => RetrievalFilterList, 0]]
- ];
- BatchDeleteEvaluationJob$ = [
- 9,
- n0,
- _BDEJ,
- { [_ht]: ["POST", "/evaluation-jobs/batch-delete", 202] },
- () => BatchDeleteEvaluationJobRequest$,
- () => BatchDeleteEvaluationJobResponse$
- ];
- CancelAutomatedReasoningPolicyBuildWorkflow$ = [
- 9,
- n0,
- _CARPBW,
- { [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/cancel", 202] },
- () => CancelAutomatedReasoningPolicyBuildWorkflowRequest$,
- () => CancelAutomatedReasoningPolicyBuildWorkflowResponse$
- ];
- CreateAutomatedReasoningPolicy$ = [
- 9,
- n0,
- _CARP,
- { [_ht]: ["POST", "/automated-reasoning-policies", 200] },
- () => CreateAutomatedReasoningPolicyRequest$,
- () => CreateAutomatedReasoningPolicyResponse$
- ];
- CreateAutomatedReasoningPolicyTestCase$ = [
- 9,
- n0,
- _CARPTC,
- { [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/test-cases", 200] },
- () => CreateAutomatedReasoningPolicyTestCaseRequest$,
- () => CreateAutomatedReasoningPolicyTestCaseResponse$
- ];
- CreateAutomatedReasoningPolicyVersion$ = [
- 9,
- n0,
- _CARPV,
- { [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/versions", 200] },
- () => CreateAutomatedReasoningPolicyVersionRequest$,
- () => CreateAutomatedReasoningPolicyVersionResponse$
- ];
- CreateCustomModel$ = [
- 9,
- n0,
- _CCM,
- { [_ht]: ["POST", "/custom-models/create-custom-model", 202] },
- () => CreateCustomModelRequest$,
- () => CreateCustomModelResponse$
- ];
- CreateCustomModelDeployment$ = [
- 9,
- n0,
- _CCMD,
- { [_ht]: ["POST", "/model-customization/custom-model-deployments", 202] },
- () => CreateCustomModelDeploymentRequest$,
- () => CreateCustomModelDeploymentResponse$
- ];
- CreateEvaluationJob$ = [
- 9,
- n0,
- _CEJ,
- { [_ht]: ["POST", "/evaluation-jobs", 202] },
- () => CreateEvaluationJobRequest$,
- () => CreateEvaluationJobResponse$
- ];
- CreateFoundationModelAgreement$ = [
- 9,
- n0,
- _CFMA,
- { [_ht]: ["POST", "/create-foundation-model-agreement", 202] },
- () => CreateFoundationModelAgreementRequest$,
- () => CreateFoundationModelAgreementResponse$
- ];
- CreateGuardrail$ = [
- 9,
- n0,
- _CG,
- { [_ht]: ["POST", "/guardrails", 202] },
- () => CreateGuardrailRequest$,
- () => CreateGuardrailResponse$
- ];
- CreateGuardrailVersion$ = [
- 9,
- n0,
- _CGV,
- { [_ht]: ["POST", "/guardrails/{guardrailIdentifier}", 202] },
- () => CreateGuardrailVersionRequest$,
- () => CreateGuardrailVersionResponse$
- ];
- CreateInferenceProfile$ = [
- 9,
- n0,
- _CIP,
- { [_ht]: ["POST", "/inference-profiles", 201] },
- () => CreateInferenceProfileRequest$,
- () => CreateInferenceProfileResponse$
- ];
- CreateMarketplaceModelEndpoint$ = [
- 9,
- n0,
- _CMME,
- { [_ht]: ["POST", "/marketplace-model/endpoints", 200] },
- () => CreateMarketplaceModelEndpointRequest$,
- () => CreateMarketplaceModelEndpointResponse$
- ];
- CreateModelCopyJob$ = [
- 9,
- n0,
- _CMCJ,
- { [_ht]: ["POST", "/model-copy-jobs", 201] },
- () => CreateModelCopyJobRequest$,
- () => CreateModelCopyJobResponse$
- ];
- CreateModelCustomizationJob$ = [
- 9,
- n0,
- _CMCJr,
- { [_ht]: ["POST", "/model-customization-jobs", 201] },
- () => CreateModelCustomizationJobRequest$,
- () => CreateModelCustomizationJobResponse$
- ];
- CreateModelImportJob$ = [
- 9,
- n0,
- _CMIJ,
- { [_ht]: ["POST", "/model-import-jobs", 201] },
- () => CreateModelImportJobRequest$,
- () => CreateModelImportJobResponse$
- ];
- CreateModelInvocationJob$ = [
- 9,
- n0,
- _CMIJr,
- { [_ht]: ["POST", "/model-invocation-job", 200] },
- () => CreateModelInvocationJobRequest$,
- () => CreateModelInvocationJobResponse$
- ];
- CreatePromptRouter$ = [
- 9,
- n0,
- _CPR,
- { [_ht]: ["POST", "/prompt-routers", 200] },
- () => CreatePromptRouterRequest$,
- () => CreatePromptRouterResponse$
- ];
- CreateProvisionedModelThroughput$ = [
- 9,
- n0,
- _CPMT,
- { [_ht]: ["POST", "/provisioned-model-throughput", 201] },
- () => CreateProvisionedModelThroughputRequest$,
- () => CreateProvisionedModelThroughputResponse$
- ];
- DeleteAutomatedReasoningPolicy$ = [
- 9,
- n0,
- _DARP,
- { [_ht]: ["DELETE", "/automated-reasoning-policies/{policyArn}", 202] },
- () => DeleteAutomatedReasoningPolicyRequest$,
- () => DeleteAutomatedReasoningPolicyResponse$
- ];
- DeleteAutomatedReasoningPolicyBuildWorkflow$ = [
- 9,
- n0,
- _DARPBW,
- { [_ht]: ["DELETE", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}", 202] },
- () => DeleteAutomatedReasoningPolicyBuildWorkflowRequest$,
- () => DeleteAutomatedReasoningPolicyBuildWorkflowResponse$
- ];
- DeleteAutomatedReasoningPolicyTestCase$ = [
- 9,
- n0,
- _DARPTC,
- { [_ht]: ["DELETE", "/automated-reasoning-policies/{policyArn}/test-cases/{testCaseId}", 202] },
- () => DeleteAutomatedReasoningPolicyTestCaseRequest$,
- () => DeleteAutomatedReasoningPolicyTestCaseResponse$
- ];
- DeleteCustomModel$ = [
- 9,
- n0,
- _DCM,
- { [_ht]: ["DELETE", "/custom-models/{modelIdentifier}", 200] },
- () => DeleteCustomModelRequest$,
- () => DeleteCustomModelResponse$
- ];
- DeleteCustomModelDeployment$ = [
- 9,
- n0,
- _DCMD,
- { [_ht]: ["DELETE", "/model-customization/custom-model-deployments/{customModelDeploymentIdentifier}", 200] },
- () => DeleteCustomModelDeploymentRequest$,
- () => DeleteCustomModelDeploymentResponse$
- ];
- DeleteEnforcedGuardrailConfiguration$ = [
- 9,
- n0,
- _DEGC,
- { [_ht]: ["DELETE", "/enforcedGuardrailsConfiguration/{configId}", 200] },
- () => DeleteEnforcedGuardrailConfigurationRequest$,
- () => DeleteEnforcedGuardrailConfigurationResponse$
- ];
- DeleteFoundationModelAgreement$ = [
- 9,
- n0,
- _DFMA,
- { [_ht]: ["POST", "/delete-foundation-model-agreement", 202] },
- () => DeleteFoundationModelAgreementRequest$,
- () => DeleteFoundationModelAgreementResponse$
- ];
- DeleteGuardrail$ = [
- 9,
- n0,
- _DG,
- { [_ht]: ["DELETE", "/guardrails/{guardrailIdentifier}", 202] },
- () => DeleteGuardrailRequest$,
- () => DeleteGuardrailResponse$
- ];
- DeleteImportedModel$ = [
- 9,
- n0,
- _DIM,
- { [_ht]: ["DELETE", "/imported-models/{modelIdentifier}", 200] },
- () => DeleteImportedModelRequest$,
- () => DeleteImportedModelResponse$
- ];
- DeleteInferenceProfile$ = [
- 9,
- n0,
- _DIP,
- { [_ht]: ["DELETE", "/inference-profiles/{inferenceProfileIdentifier}", 200] },
- () => DeleteInferenceProfileRequest$,
- () => DeleteInferenceProfileResponse$
- ];
- DeleteMarketplaceModelEndpoint$ = [
- 9,
- n0,
- _DMME,
- { [_ht]: ["DELETE", "/marketplace-model/endpoints/{endpointArn}", 200] },
- () => DeleteMarketplaceModelEndpointRequest$,
- () => DeleteMarketplaceModelEndpointResponse$
- ];
- DeleteModelInvocationLoggingConfiguration$ = [
- 9,
- n0,
- _DMILC,
- { [_ht]: ["DELETE", "/logging/modelinvocations", 200] },
- () => DeleteModelInvocationLoggingConfigurationRequest$,
- () => DeleteModelInvocationLoggingConfigurationResponse$
- ];
- DeletePromptRouter$ = [
- 9,
- n0,
- _DPRe,
- { [_ht]: ["DELETE", "/prompt-routers/{promptRouterArn}", 200] },
- () => DeletePromptRouterRequest$,
- () => DeletePromptRouterResponse$
- ];
- DeleteProvisionedModelThroughput$ = [
- 9,
- n0,
- _DPMT,
- { [_ht]: ["DELETE", "/provisioned-model-throughput/{provisionedModelId}", 200] },
- () => DeleteProvisionedModelThroughputRequest$,
- () => DeleteProvisionedModelThroughputResponse$
- ];
- DeregisterMarketplaceModelEndpoint$ = [
- 9,
- n0,
- _DMMEe,
- { [_ht]: ["DELETE", "/marketplace-model/endpoints/{endpointArn}/registration", 200] },
- () => DeregisterMarketplaceModelEndpointRequest$,
- () => DeregisterMarketplaceModelEndpointResponse$
- ];
- ExportAutomatedReasoningPolicyVersion$ = [
- 9,
- n0,
- _EARPV,
- { [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/export", 200] },
- () => ExportAutomatedReasoningPolicyVersionRequest$,
- () => ExportAutomatedReasoningPolicyVersionResponse$
- ];
- GetAutomatedReasoningPolicy$ = [
- 9,
- n0,
- _GARPe,
- { [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}", 200] },
- () => GetAutomatedReasoningPolicyRequest$,
- () => GetAutomatedReasoningPolicyResponse$
- ];
- GetAutomatedReasoningPolicyAnnotations$ = [
- 9,
- n0,
- _GARPA,
- { [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/annotations", 200] },
- () => GetAutomatedReasoningPolicyAnnotationsRequest$,
- () => GetAutomatedReasoningPolicyAnnotationsResponse$
- ];
- GetAutomatedReasoningPolicyBuildWorkflow$ = [
- 9,
- n0,
- _GARPBW,
- { [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}", 200] },
- () => GetAutomatedReasoningPolicyBuildWorkflowRequest$,
- () => GetAutomatedReasoningPolicyBuildWorkflowResponse$
- ];
- GetAutomatedReasoningPolicyBuildWorkflowResultAssets$ = [
- 9,
- n0,
- _GARPBWRA,
- { [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/result-assets", 200] },
- () => GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest$,
- () => GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse$
- ];
- GetAutomatedReasoningPolicyNextScenario$ = [
- 9,
- n0,
- _GARPNS,
- { [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/scenarios", 200] },
- () => GetAutomatedReasoningPolicyNextScenarioRequest$,
- () => GetAutomatedReasoningPolicyNextScenarioResponse$
- ];
- GetAutomatedReasoningPolicyTestCase$ = [
- 9,
- n0,
- _GARPTC,
- { [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/test-cases/{testCaseId}", 200] },
- () => GetAutomatedReasoningPolicyTestCaseRequest$,
- () => GetAutomatedReasoningPolicyTestCaseResponse$
- ];
- GetAutomatedReasoningPolicyTestResult$ = [
- 9,
- n0,
- _GARPTR,
- { [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/test-cases/{testCaseId}/test-results", 200] },
- () => GetAutomatedReasoningPolicyTestResultRequest$,
- () => GetAutomatedReasoningPolicyTestResultResponse$
- ];
- GetCustomModel$ = [
- 9,
- n0,
- _GCM,
- { [_ht]: ["GET", "/custom-models/{modelIdentifier}", 200] },
- () => GetCustomModelRequest$,
- () => GetCustomModelResponse$
- ];
- GetCustomModelDeployment$ = [
- 9,
- n0,
- _GCMD,
- { [_ht]: ["GET", "/model-customization/custom-model-deployments/{customModelDeploymentIdentifier}", 200] },
- () => GetCustomModelDeploymentRequest$,
- () => GetCustomModelDeploymentResponse$
- ];
- GetEvaluationJob$ = [
- 9,
- n0,
- _GEJ,
- { [_ht]: ["GET", "/evaluation-jobs/{jobIdentifier}", 200] },
- () => GetEvaluationJobRequest$,
- () => GetEvaluationJobResponse$
- ];
- GetFoundationModel$ = [
- 9,
- n0,
- _GFM,
- { [_ht]: ["GET", "/foundation-models/{modelIdentifier}", 200] },
- () => GetFoundationModelRequest$,
- () => GetFoundationModelResponse$
- ];
- GetFoundationModelAvailability$ = [
- 9,
- n0,
- _GFMA,
- { [_ht]: ["GET", "/foundation-model-availability/{modelId}", 200] },
- () => GetFoundationModelAvailabilityRequest$,
- () => GetFoundationModelAvailabilityResponse$
- ];
- GetGuardrail$ = [
- 9,
- n0,
- _GG,
- { [_ht]: ["GET", "/guardrails/{guardrailIdentifier}", 200] },
- () => GetGuardrailRequest$,
- () => GetGuardrailResponse$
- ];
- GetImportedModel$ = [
- 9,
- n0,
- _GIM,
- { [_ht]: ["GET", "/imported-models/{modelIdentifier}", 200] },
- () => GetImportedModelRequest$,
- () => GetImportedModelResponse$
- ];
- GetInferenceProfile$ = [
- 9,
- n0,
- _GIP,
- { [_ht]: ["GET", "/inference-profiles/{inferenceProfileIdentifier}", 200] },
- () => GetInferenceProfileRequest$,
- () => GetInferenceProfileResponse$
- ];
- GetMarketplaceModelEndpoint$ = [
- 9,
- n0,
- _GMME,
- { [_ht]: ["GET", "/marketplace-model/endpoints/{endpointArn}", 200] },
- () => GetMarketplaceModelEndpointRequest$,
- () => GetMarketplaceModelEndpointResponse$
- ];
- GetModelCopyJob$ = [
- 9,
- n0,
- _GMCJ,
- { [_ht]: ["GET", "/model-copy-jobs/{jobArn}", 200] },
- () => GetModelCopyJobRequest$,
- () => GetModelCopyJobResponse$
- ];
- GetModelCustomizationJob$ = [
- 9,
- n0,
- _GMCJe,
- { [_ht]: ["GET", "/model-customization-jobs/{jobIdentifier}", 200] },
- () => GetModelCustomizationJobRequest$,
- () => GetModelCustomizationJobResponse$
- ];
- GetModelImportJob$ = [
- 9,
- n0,
- _GMIJ,
- { [_ht]: ["GET", "/model-import-jobs/{jobIdentifier}", 200] },
- () => GetModelImportJobRequest$,
- () => GetModelImportJobResponse$
- ];
- GetModelInvocationJob$ = [
- 9,
- n0,
- _GMIJe,
- { [_ht]: ["GET", "/model-invocation-job/{jobIdentifier}", 200] },
- () => GetModelInvocationJobRequest$,
- () => GetModelInvocationJobResponse$
- ];
- GetModelInvocationLoggingConfiguration$ = [
- 9,
- n0,
- _GMILC,
- { [_ht]: ["GET", "/logging/modelinvocations", 200] },
- () => GetModelInvocationLoggingConfigurationRequest$,
- () => GetModelInvocationLoggingConfigurationResponse$
- ];
- GetPromptRouter$ = [
- 9,
- n0,
- _GPR,
- { [_ht]: ["GET", "/prompt-routers/{promptRouterArn}", 200] },
- () => GetPromptRouterRequest$,
- () => GetPromptRouterResponse$
- ];
- GetProvisionedModelThroughput$ = [
- 9,
- n0,
- _GPMT,
- { [_ht]: ["GET", "/provisioned-model-throughput/{provisionedModelId}", 200] },
- () => GetProvisionedModelThroughputRequest$,
- () => GetProvisionedModelThroughputResponse$
- ];
- GetUseCaseForModelAccess$ = [
- 9,
- n0,
- _GUCFMA,
- { [_ht]: ["GET", "/use-case-for-model-access", 200] },
- () => GetUseCaseForModelAccessRequest$,
- () => GetUseCaseForModelAccessResponse$
- ];
- ListAutomatedReasoningPolicies$ = [
- 9,
- n0,
- _LARP,
- { [_ht]: ["GET", "/automated-reasoning-policies", 200] },
- () => ListAutomatedReasoningPoliciesRequest$,
- () => ListAutomatedReasoningPoliciesResponse$
- ];
- ListAutomatedReasoningPolicyBuildWorkflows$ = [
- 9,
- n0,
- _LARPBW,
- { [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows", 200] },
- () => ListAutomatedReasoningPolicyBuildWorkflowsRequest$,
- () => ListAutomatedReasoningPolicyBuildWorkflowsResponse$
- ];
- ListAutomatedReasoningPolicyTestCases$ = [
- 9,
- n0,
- _LARPTC,
- { [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/test-cases", 200] },
- () => ListAutomatedReasoningPolicyTestCasesRequest$,
- () => ListAutomatedReasoningPolicyTestCasesResponse$
- ];
- ListAutomatedReasoningPolicyTestResults$ = [
- 9,
- n0,
- _LARPTR,
- { [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/test-results", 200] },
- () => ListAutomatedReasoningPolicyTestResultsRequest$,
- () => ListAutomatedReasoningPolicyTestResultsResponse$
- ];
- ListCustomModelDeployments$ = [
- 9,
- n0,
- _LCMD,
- { [_ht]: ["GET", "/model-customization/custom-model-deployments", 200] },
- () => ListCustomModelDeploymentsRequest$,
- () => ListCustomModelDeploymentsResponse$
- ];
- ListCustomModels$ = [
- 9,
- n0,
- _LCM,
- { [_ht]: ["GET", "/custom-models", 200] },
- () => ListCustomModelsRequest$,
- () => ListCustomModelsResponse$
- ];
- ListEnforcedGuardrailsConfiguration$ = [
- 9,
- n0,
- _LEGC,
- { [_ht]: ["GET", "/enforcedGuardrailsConfiguration", 200] },
- () => ListEnforcedGuardrailsConfigurationRequest$,
- () => ListEnforcedGuardrailsConfigurationResponse$
- ];
- ListEvaluationJobs$ = [
- 9,
- n0,
- _LEJ,
- { [_ht]: ["GET", "/evaluation-jobs", 200] },
- () => ListEvaluationJobsRequest$,
- () => ListEvaluationJobsResponse$
- ];
- ListFoundationModelAgreementOffers$ = [
- 9,
- n0,
- _LFMAO,
- { [_ht]: ["GET", "/list-foundation-model-agreement-offers/{modelId}", 200] },
- () => ListFoundationModelAgreementOffersRequest$,
- () => ListFoundationModelAgreementOffersResponse$
- ];
- ListFoundationModels$ = [
- 9,
- n0,
- _LFM,
- { [_ht]: ["GET", "/foundation-models", 200] },
- () => ListFoundationModelsRequest$,
- () => ListFoundationModelsResponse$
- ];
- ListGuardrails$ = [
- 9,
- n0,
- _LG,
- { [_ht]: ["GET", "/guardrails", 200] },
- () => ListGuardrailsRequest$,
- () => ListGuardrailsResponse$
- ];
- ListImportedModels$ = [
- 9,
- n0,
- _LIM,
- { [_ht]: ["GET", "/imported-models", 200] },
- () => ListImportedModelsRequest$,
- () => ListImportedModelsResponse$
- ];
- ListInferenceProfiles$ = [
- 9,
- n0,
- _LIP,
- { [_ht]: ["GET", "/inference-profiles", 200] },
- () => ListInferenceProfilesRequest$,
- () => ListInferenceProfilesResponse$
- ];
- ListMarketplaceModelEndpoints$ = [
- 9,
- n0,
- _LMME,
- { [_ht]: ["GET", "/marketplace-model/endpoints", 200] },
- () => ListMarketplaceModelEndpointsRequest$,
- () => ListMarketplaceModelEndpointsResponse$
- ];
- ListModelCopyJobs$ = [
- 9,
- n0,
- _LMCJ,
- { [_ht]: ["GET", "/model-copy-jobs", 200] },
- () => ListModelCopyJobsRequest$,
- () => ListModelCopyJobsResponse$
- ];
- ListModelCustomizationJobs$ = [
- 9,
- n0,
- _LMCJi,
- { [_ht]: ["GET", "/model-customization-jobs", 200] },
- () => ListModelCustomizationJobsRequest$,
- () => ListModelCustomizationJobsResponse$
- ];
- ListModelImportJobs$ = [
- 9,
- n0,
- _LMIJ,
- { [_ht]: ["GET", "/model-import-jobs", 200] },
- () => ListModelImportJobsRequest$,
- () => ListModelImportJobsResponse$
- ];
- ListModelInvocationJobs$ = [
- 9,
- n0,
- _LMIJi,
- { [_ht]: ["GET", "/model-invocation-jobs", 200] },
- () => ListModelInvocationJobsRequest$,
- () => ListModelInvocationJobsResponse$
- ];
- ListPromptRouters$ = [
- 9,
- n0,
- _LPR,
- { [_ht]: ["GET", "/prompt-routers", 200] },
- () => ListPromptRoutersRequest$,
- () => ListPromptRoutersResponse$
- ];
- ListProvisionedModelThroughputs$ = [
- 9,
- n0,
- _LPMT,
- { [_ht]: ["GET", "/provisioned-model-throughputs", 200] },
- () => ListProvisionedModelThroughputsRequest$,
- () => ListProvisionedModelThroughputsResponse$
- ];
- ListTagsForResource$ = [
- 9,
- n0,
- _LTFR,
- { [_ht]: ["POST", "/listTagsForResource", 200] },
- () => ListTagsForResourceRequest$,
- () => ListTagsForResourceResponse$
- ];
- PutEnforcedGuardrailConfiguration$ = [
- 9,
- n0,
- _PEGC,
- { [_ht]: ["PUT", "/enforcedGuardrailsConfiguration", 200] },
- () => PutEnforcedGuardrailConfigurationRequest$,
- () => PutEnforcedGuardrailConfigurationResponse$
- ];
- PutModelInvocationLoggingConfiguration$ = [
- 9,
- n0,
- _PMILC,
- { [_ht]: ["PUT", "/logging/modelinvocations", 200] },
- () => PutModelInvocationLoggingConfigurationRequest$,
- () => PutModelInvocationLoggingConfigurationResponse$
- ];
- PutUseCaseForModelAccess$ = [
- 9,
- n0,
- _PUCFMA,
- { [_ht]: ["POST", "/use-case-for-model-access", 201] },
- () => PutUseCaseForModelAccessRequest$,
- () => PutUseCaseForModelAccessResponse$
- ];
- RegisterMarketplaceModelEndpoint$ = [
- 9,
- n0,
- _RMME,
- { [_ht]: ["POST", "/marketplace-model/endpoints/{endpointIdentifier}/registration", 200] },
- () => RegisterMarketplaceModelEndpointRequest$,
- () => RegisterMarketplaceModelEndpointResponse$
- ];
- StartAutomatedReasoningPolicyBuildWorkflow$ = [
- 9,
- n0,
- _SARPBW,
- { [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowType}/start", 200] },
- () => StartAutomatedReasoningPolicyBuildWorkflowRequest$,
- () => StartAutomatedReasoningPolicyBuildWorkflowResponse$
- ];
- StartAutomatedReasoningPolicyTestWorkflow$ = [
- 9,
- n0,
- _SARPTW,
- { [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/test-workflows", 200] },
- () => StartAutomatedReasoningPolicyTestWorkflowRequest$,
- () => StartAutomatedReasoningPolicyTestWorkflowResponse$
- ];
- StopEvaluationJob$ = [
- 9,
- n0,
- _SEJ,
- { [_ht]: ["POST", "/evaluation-job/{jobIdentifier}/stop", 200] },
- () => StopEvaluationJobRequest$,
- () => StopEvaluationJobResponse$
- ];
- StopModelCustomizationJob$ = [
- 9,
- n0,
- _SMCJ,
- { [_ht]: ["POST", "/model-customization-jobs/{jobIdentifier}/stop", 200] },
- () => StopModelCustomizationJobRequest$,
- () => StopModelCustomizationJobResponse$
- ];
- StopModelInvocationJob$ = [
- 9,
- n0,
- _SMIJ,
- { [_ht]: ["POST", "/model-invocation-job/{jobIdentifier}/stop", 200] },
- () => StopModelInvocationJobRequest$,
- () => StopModelInvocationJobResponse$
- ];
- TagResource$ = [
- 9,
- n0,
- _TR,
- { [_ht]: ["POST", "/tagResource", 200] },
- () => TagResourceRequest$,
- () => TagResourceResponse$
- ];
- UntagResource$ = [
- 9,
- n0,
- _UR,
- { [_ht]: ["POST", "/untagResource", 200] },
- () => UntagResourceRequest$,
- () => UntagResourceResponse$
- ];
- UpdateAutomatedReasoningPolicy$ = [
- 9,
- n0,
- _UARP,
- { [_ht]: ["PATCH", "/automated-reasoning-policies/{policyArn}", 200] },
- () => UpdateAutomatedReasoningPolicyRequest$,
- () => UpdateAutomatedReasoningPolicyResponse$
- ];
- UpdateAutomatedReasoningPolicyAnnotations$ = [
- 9,
- n0,
- _UARPA,
- { [_ht]: ["PATCH", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/annotations", 200] },
- () => UpdateAutomatedReasoningPolicyAnnotationsRequest$,
- () => UpdateAutomatedReasoningPolicyAnnotationsResponse$
- ];
- UpdateAutomatedReasoningPolicyTestCase$ = [
- 9,
- n0,
- _UARPTC,
- { [_ht]: ["PATCH", "/automated-reasoning-policies/{policyArn}/test-cases/{testCaseId}", 200] },
- () => UpdateAutomatedReasoningPolicyTestCaseRequest$,
- () => UpdateAutomatedReasoningPolicyTestCaseResponse$
- ];
- UpdateCustomModelDeployment$ = [
- 9,
- n0,
- _UCMD,
- { [_ht]: ["PATCH", "/model-customization/custom-model-deployments/{customModelDeploymentIdentifier}", 202] },
- () => UpdateCustomModelDeploymentRequest$,
- () => UpdateCustomModelDeploymentResponse$
- ];
- UpdateGuardrail$ = [
- 9,
- n0,
- _UG,
- { [_ht]: ["PUT", "/guardrails/{guardrailIdentifier}", 202] },
- () => UpdateGuardrailRequest$,
- () => UpdateGuardrailResponse$
- ];
- UpdateMarketplaceModelEndpoint$ = [
- 9,
- n0,
- _UMME,
- { [_ht]: ["PATCH", "/marketplace-model/endpoints/{endpointArn}", 200] },
- () => UpdateMarketplaceModelEndpointRequest$,
- () => UpdateMarketplaceModelEndpointResponse$
- ];
- UpdateProvisionedModelThroughput$ = [
- 9,
- n0,
- _UPMT,
- { [_ht]: ["PATCH", "/provisioned-model-throughput/{provisionedModelId}", 200] },
- () => UpdateProvisionedModelThroughputRequest$,
- () => UpdateProvisionedModelThroughputResponse$
- ];
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/runtimeConfig.shared.js
-var import_httpAuthSchemes3, import_protocols7, import_core18, import_url_parser2, import_util_utf82, getRuntimeConfig = (config4) => {
- return {
- apiVersion: "2023-04-20",
- base64Decoder: config4?.base64Decoder ?? fromBase64,
- base64Encoder: config4?.base64Encoder ?? toBase64,
- disableHostPrefix: config4?.disableHostPrefix ?? false,
- endpointProvider: config4?.endpointProvider ?? defaultEndpointResolver,
- extensions: config4?.extensions ?? [],
- httpAuthSchemeProvider: config4?.httpAuthSchemeProvider ?? defaultBedrockHttpAuthSchemeProvider,
- httpAuthSchemes: config4?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
- signer: new import_httpAuthSchemes3.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#httpBearerAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth"),
- signer: new import_core18.HttpBearerAuthSigner
- }
- ],
- logger: config4?.logger ?? new NoOpLogger3,
- protocol: config4?.protocol ?? import_protocols7.AwsRestJsonProtocol,
- protocolSettings: config4?.protocolSettings ?? {
- defaultNamespace: "com.amazonaws.bedrock",
- errorTypeRegistries,
- version: "2023-04-20",
- serviceTarget: "AmazonBedrockControlPlaneService"
- },
- serviceId: config4?.serviceId ?? "Bedrock",
- urlParser: config4?.urlParser ?? import_url_parser2.parseUrl,
- utf8Decoder: config4?.utf8Decoder ?? import_util_utf82.fromUtf8,
- utf8Encoder: config4?.utf8Encoder ?? import_util_utf82.toUtf8
- };
-};
-var init_runtimeConfig_shared = __esm(() => {
- init_dist_es16();
- init_dist_es18();
- init_httpAuthSchemeProvider();
- init_endpointResolver();
- init_schemas_0();
- import_httpAuthSchemes3 = __toESM(require_httpAuthSchemes(), 1);
- import_protocols7 = __toESM(require_protocols2(), 1);
- import_core18 = __toESM(require_dist_cjs37(), 1);
- import_url_parser2 = __toESM(require_dist_cjs11(), 1);
- import_util_utf82 = __toESM(require_dist_cjs17(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/runtimeConfig.js
-var import_client15, import_httpAuthSchemes4, import_util_user_agent_node, import_config_resolver, import_core19, import_hash_node, import_middleware_retry, import_node_config_provider3, import_node_http_handler2, import_util_body_length_node, import_util_defaults_mode_node, import_util_retry, getRuntimeConfig2 = (config4) => {
- emitWarningIfUnsupportedVersion3(process.version);
- const defaultsMode = import_util_defaults_mode_node.resolveDefaultsModeConfig(config4);
- const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode2);
- const clientSharedValues = getRuntimeConfig(config4);
- import_client15.emitWarningIfUnsupportedVersion(process.version);
- const loaderConfig = {
- profile: config4?.profile,
- logger: clientSharedValues.logger,
- signingName: "bedrock"
- };
- return {
- ...clientSharedValues,
- ...config4,
- runtime: "node",
- defaultsMode,
- authSchemePreference: config4?.authSchemePreference ?? import_node_config_provider3.loadConfig(import_httpAuthSchemes4.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
- bodyLengthChecker: config4?.bodyLengthChecker ?? import_util_body_length_node.calculateBodyLength,
- credentialDefaultProvider: config4?.credentialDefaultProvider ?? defaultProvider,
- defaultUserAgentProvider: config4?.defaultUserAgentProvider ?? import_util_user_agent_node.createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }),
- httpAuthSchemes: config4?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
- signer: new import_httpAuthSchemes4.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#httpBearerAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth") || (async (idProps) => {
- try {
- return await fromEnvSigningName({ signingName: "bedrock" })();
- } catch (error40) {
- return await nodeProvider(idProps)(idProps);
- }
- }),
- signer: new import_core19.HttpBearerAuthSigner
- }
- ],
- maxAttempts: config4?.maxAttempts ?? import_node_config_provider3.loadConfig(import_middleware_retry.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config4),
- region: config4?.region ?? import_node_config_provider3.loadConfig(import_config_resolver.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
- requestHandler: import_node_http_handler2.NodeHttpHandler.create(config4?.requestHandler ?? defaultConfigProvider),
- retryMode: config4?.retryMode ?? import_node_config_provider3.loadConfig({
- ...import_middleware_retry.NODE_RETRY_MODE_CONFIG_OPTIONS,
- default: async () => (await defaultConfigProvider()).retryMode || import_util_retry.DEFAULT_RETRY_MODE
- }, config4),
- sha256: config4?.sha256 ?? import_hash_node.Hash.bind(null, "sha256"),
- streamCollector: config4?.streamCollector ?? import_node_http_handler2.streamCollector,
- useDualstackEndpoint: config4?.useDualstackEndpoint ?? import_node_config_provider3.loadConfig(import_config_resolver.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- useFipsEndpoint: config4?.useFipsEndpoint ?? import_node_config_provider3.loadConfig(import_config_resolver.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- userAgentAppId: config4?.userAgentAppId ?? import_node_config_provider3.loadConfig(import_util_user_agent_node.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
- };
-};
-var init_runtimeConfig = __esm(() => {
- init_package();
- init_dist_es14();
- init_dist_es7();
- init_dist_es16();
- init_runtimeConfig_shared();
- import_client15 = __toESM(require_client(), 1);
- import_httpAuthSchemes4 = __toESM(require_httpAuthSchemes(), 1);
- import_util_user_agent_node = __toESM(require_dist_cjs72(), 1);
- import_config_resolver = __toESM(require_dist_cjs58(), 1);
- import_core19 = __toESM(require_dist_cjs37(), 1);
- import_hash_node = __toESM(require_dist_cjs75(), 1);
- import_middleware_retry = __toESM(require_dist_cjs69(), 1);
- import_node_config_provider3 = __toESM(require_dist_cjs9(), 1);
- import_node_http_handler2 = __toESM(require_dist_cjs5(), 1);
- import_util_body_length_node = __toESM(require_dist_cjs76(), 1);
- import_util_defaults_mode_node = __toESM(require_dist_cjs77(), 1);
- import_util_retry = __toESM(require_dist_cjs55(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
-var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
-}, resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
-};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
-var init_extensions7 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-es/Field.js
-var init_Field3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
-var init_httpHandler3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-es/types.js
-var init_types8 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-es/index.js
-var init_dist_es19 = __esm(() => {
- init_extensions7();
- init_Field3();
- init_httpHandler3();
- init_types8();
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/auth/httpAuthExtensionConfiguration.js
-var getHttpAuthExtensionConfiguration = (runtimeConfig) => {
- const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
- let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
- let _credentials = runtimeConfig.credentials;
- let _token = runtimeConfig.token;
- return {
- setHttpAuthScheme(httpAuthScheme) {
- const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
- if (index2 === -1) {
- _httpAuthSchemes.push(httpAuthScheme);
- } else {
- _httpAuthSchemes.splice(index2, 1, httpAuthScheme);
- }
- },
- httpAuthSchemes() {
- return _httpAuthSchemes;
- },
- setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
- _httpAuthSchemeProvider = httpAuthSchemeProvider;
- },
- httpAuthSchemeProvider() {
- return _httpAuthSchemeProvider;
- },
- setCredentials(credentials) {
- _credentials = credentials;
- },
- credentials() {
- return _credentials;
- },
- setToken(token) {
- _token = token;
- },
- token() {
- return _token;
- }
- };
-}, resolveHttpAuthRuntimeConfig = (config4) => {
- return {
- httpAuthSchemes: config4.httpAuthSchemes(),
- httpAuthSchemeProvider: config4.httpAuthSchemeProvider(),
- credentials: config4.credentials(),
- token: config4.token()
- };
-};
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/runtimeExtensions.js
-var import_region_config_resolver, resolveRuntimeExtensions = (runtimeConfig, extensions8) => {
- const extensionConfiguration = Object.assign(import_region_config_resolver.getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration2(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));
- extensions8.forEach((extension) => extension.configure(extensionConfiguration));
- return Object.assign(runtimeConfig, import_region_config_resolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig2(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));
-};
-var init_runtimeExtensions = __esm(() => {
- init_dist_es19();
- init_dist_es16();
- import_region_config_resolver = __toESM(require_dist_cjs87(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/BedrockClient.js
-var import_middleware_host_header, import_middleware_logger, import_middleware_recursion_detection, import_middleware_user_agent, import_config_resolver2, import_core20, import_schema4, import_middleware_content_length, import_middleware_endpoint, import_middleware_retry2, BedrockClient;
-var init_BedrockClient = __esm(() => {
- init_dist_es16();
- init_httpAuthSchemeProvider();
- init_EndpointParameters();
- init_runtimeConfig();
- init_runtimeExtensions();
- import_middleware_host_header = __toESM(require_dist_cjs44(), 1);
- import_middleware_logger = __toESM(require_dist_cjs45(), 1);
- import_middleware_recursion_detection = __toESM(require_dist_cjs48(), 1);
- import_middleware_user_agent = __toESM(require_dist_cjs56(), 1);
- import_config_resolver2 = __toESM(require_dist_cjs58(), 1);
- import_core20 = __toESM(require_dist_cjs37(), 1);
- import_schema4 = __toESM(require_schema(), 1);
- import_middleware_content_length = __toESM(require_dist_cjs61(), 1);
- import_middleware_endpoint = __toESM(require_dist_cjs65(), 1);
- import_middleware_retry2 = __toESM(require_dist_cjs69(), 1);
- BedrockClient = class BedrockClient extends Client2 {
- config;
- constructor(...[configuration]) {
- const _config_0 = getRuntimeConfig2(configuration || {});
- super(_config_0);
- this.initConfig = _config_0;
- const _config_1 = resolveClientEndpointParameters(_config_0);
- const _config_2 = import_middleware_user_agent.resolveUserAgentConfig(_config_1);
- const _config_3 = import_middleware_retry2.resolveRetryConfig(_config_2);
- const _config_4 = import_config_resolver2.resolveRegionConfig(_config_3);
- const _config_5 = import_middleware_host_header.resolveHostHeaderConfig(_config_4);
- const _config_6 = import_middleware_endpoint.resolveEndpointConfig(_config_5);
- const _config_7 = resolveHttpAuthSchemeConfig(_config_6);
- const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);
- this.config = _config_8;
- this.middlewareStack.use(import_schema4.getSchemaSerdePlugin(this.config));
- this.middlewareStack.use(import_middleware_user_agent.getUserAgentPlugin(this.config));
- this.middlewareStack.use(import_middleware_retry2.getRetryPlugin(this.config));
- this.middlewareStack.use(import_middleware_content_length.getContentLengthPlugin(this.config));
- this.middlewareStack.use(import_middleware_host_header.getHostHeaderPlugin(this.config));
- this.middlewareStack.use(import_middleware_logger.getLoggerPlugin(this.config));
- this.middlewareStack.use(import_middleware_recursion_detection.getRecursionDetectionPlugin(this.config));
- this.middlewareStack.use(import_core20.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
- httpAuthSchemeParametersProvider: defaultBedrockHttpAuthSchemeParametersProvider,
- identityProviderConfigProvider: async (config4) => new import_core20.DefaultIdentityProviderConfig({
- "aws.auth#sigv4": config4.credentials,
- "smithy.api#httpBearerAuth": config4.token
- })
- }));
- this.middlewareStack.use(import_core20.getHttpSigningPlugin(this.config));
- }
- destroy() {
- super.destroy();
- }
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/BatchDeleteEvaluationJobCommand.js
-var import_middleware_endpoint2, BatchDeleteEvaluationJobCommand;
-var init_BatchDeleteEvaluationJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint2 = __toESM(require_dist_cjs65(), 1);
- BatchDeleteEvaluationJobCommand = class BatchDeleteEvaluationJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint2.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "BatchDeleteEvaluationJob", {}).n("BedrockClient", "BatchDeleteEvaluationJobCommand").sc(BatchDeleteEvaluationJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CancelAutomatedReasoningPolicyBuildWorkflowCommand.js
-var import_middleware_endpoint3, CancelAutomatedReasoningPolicyBuildWorkflowCommand;
-var init_CancelAutomatedReasoningPolicyBuildWorkflowCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint3 = __toESM(require_dist_cjs65(), 1);
- CancelAutomatedReasoningPolicyBuildWorkflowCommand = class CancelAutomatedReasoningPolicyBuildWorkflowCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint3.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CancelAutomatedReasoningPolicyBuildWorkflow", {}).n("BedrockClient", "CancelAutomatedReasoningPolicyBuildWorkflowCommand").sc(CancelAutomatedReasoningPolicyBuildWorkflow$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateAutomatedReasoningPolicyCommand.js
-var import_middleware_endpoint4, CreateAutomatedReasoningPolicyCommand;
-var init_CreateAutomatedReasoningPolicyCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint4 = __toESM(require_dist_cjs65(), 1);
- CreateAutomatedReasoningPolicyCommand = class CreateAutomatedReasoningPolicyCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint4.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateAutomatedReasoningPolicy", {}).n("BedrockClient", "CreateAutomatedReasoningPolicyCommand").sc(CreateAutomatedReasoningPolicy$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateAutomatedReasoningPolicyTestCaseCommand.js
-var import_middleware_endpoint5, CreateAutomatedReasoningPolicyTestCaseCommand;
-var init_CreateAutomatedReasoningPolicyTestCaseCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint5 = __toESM(require_dist_cjs65(), 1);
- CreateAutomatedReasoningPolicyTestCaseCommand = class CreateAutomatedReasoningPolicyTestCaseCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint5.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateAutomatedReasoningPolicyTestCase", {}).n("BedrockClient", "CreateAutomatedReasoningPolicyTestCaseCommand").sc(CreateAutomatedReasoningPolicyTestCase$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateAutomatedReasoningPolicyVersionCommand.js
-var import_middleware_endpoint6, CreateAutomatedReasoningPolicyVersionCommand;
-var init_CreateAutomatedReasoningPolicyVersionCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint6 = __toESM(require_dist_cjs65(), 1);
- CreateAutomatedReasoningPolicyVersionCommand = class CreateAutomatedReasoningPolicyVersionCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint6.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateAutomatedReasoningPolicyVersion", {}).n("BedrockClient", "CreateAutomatedReasoningPolicyVersionCommand").sc(CreateAutomatedReasoningPolicyVersion$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateCustomModelCommand.js
-var import_middleware_endpoint7, CreateCustomModelCommand;
-var init_CreateCustomModelCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint7 = __toESM(require_dist_cjs65(), 1);
- CreateCustomModelCommand = class CreateCustomModelCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint7.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateCustomModel", {}).n("BedrockClient", "CreateCustomModelCommand").sc(CreateCustomModel$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateCustomModelDeploymentCommand.js
-var import_middleware_endpoint8, CreateCustomModelDeploymentCommand;
-var init_CreateCustomModelDeploymentCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint8 = __toESM(require_dist_cjs65(), 1);
- CreateCustomModelDeploymentCommand = class CreateCustomModelDeploymentCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint8.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateCustomModelDeployment", {}).n("BedrockClient", "CreateCustomModelDeploymentCommand").sc(CreateCustomModelDeployment$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateEvaluationJobCommand.js
-var import_middleware_endpoint9, CreateEvaluationJobCommand;
-var init_CreateEvaluationJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint9 = __toESM(require_dist_cjs65(), 1);
- CreateEvaluationJobCommand = class CreateEvaluationJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint9.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateEvaluationJob", {}).n("BedrockClient", "CreateEvaluationJobCommand").sc(CreateEvaluationJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateFoundationModelAgreementCommand.js
-var import_middleware_endpoint10, CreateFoundationModelAgreementCommand;
-var init_CreateFoundationModelAgreementCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint10 = __toESM(require_dist_cjs65(), 1);
- CreateFoundationModelAgreementCommand = class CreateFoundationModelAgreementCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint10.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateFoundationModelAgreement", {}).n("BedrockClient", "CreateFoundationModelAgreementCommand").sc(CreateFoundationModelAgreement$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateGuardrailCommand.js
-var import_middleware_endpoint11, CreateGuardrailCommand;
-var init_CreateGuardrailCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint11 = __toESM(require_dist_cjs65(), 1);
- CreateGuardrailCommand = class CreateGuardrailCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint11.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateGuardrail", {}).n("BedrockClient", "CreateGuardrailCommand").sc(CreateGuardrail$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateGuardrailVersionCommand.js
-var import_middleware_endpoint12, CreateGuardrailVersionCommand;
-var init_CreateGuardrailVersionCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint12 = __toESM(require_dist_cjs65(), 1);
- CreateGuardrailVersionCommand = class CreateGuardrailVersionCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint12.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateGuardrailVersion", {}).n("BedrockClient", "CreateGuardrailVersionCommand").sc(CreateGuardrailVersion$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateInferenceProfileCommand.js
-var import_middleware_endpoint13, CreateInferenceProfileCommand;
-var init_CreateInferenceProfileCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint13 = __toESM(require_dist_cjs65(), 1);
- CreateInferenceProfileCommand = class CreateInferenceProfileCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint13.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateInferenceProfile", {}).n("BedrockClient", "CreateInferenceProfileCommand").sc(CreateInferenceProfile$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateMarketplaceModelEndpointCommand.js
-var import_middleware_endpoint14, CreateMarketplaceModelEndpointCommand;
-var init_CreateMarketplaceModelEndpointCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint14 = __toESM(require_dist_cjs65(), 1);
- CreateMarketplaceModelEndpointCommand = class CreateMarketplaceModelEndpointCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint14.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateMarketplaceModelEndpoint", {}).n("BedrockClient", "CreateMarketplaceModelEndpointCommand").sc(CreateMarketplaceModelEndpoint$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateModelCopyJobCommand.js
-var import_middleware_endpoint15, CreateModelCopyJobCommand;
-var init_CreateModelCopyJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint15 = __toESM(require_dist_cjs65(), 1);
- CreateModelCopyJobCommand = class CreateModelCopyJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint15.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateModelCopyJob", {}).n("BedrockClient", "CreateModelCopyJobCommand").sc(CreateModelCopyJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateModelCustomizationJobCommand.js
-var import_middleware_endpoint16, CreateModelCustomizationJobCommand;
-var init_CreateModelCustomizationJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint16 = __toESM(require_dist_cjs65(), 1);
- CreateModelCustomizationJobCommand = class CreateModelCustomizationJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint16.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateModelCustomizationJob", {}).n("BedrockClient", "CreateModelCustomizationJobCommand").sc(CreateModelCustomizationJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateModelImportJobCommand.js
-var import_middleware_endpoint17, CreateModelImportJobCommand;
-var init_CreateModelImportJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint17 = __toESM(require_dist_cjs65(), 1);
- CreateModelImportJobCommand = class CreateModelImportJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint17.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateModelImportJob", {}).n("BedrockClient", "CreateModelImportJobCommand").sc(CreateModelImportJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateModelInvocationJobCommand.js
-var import_middleware_endpoint18, CreateModelInvocationJobCommand;
-var init_CreateModelInvocationJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint18 = __toESM(require_dist_cjs65(), 1);
- CreateModelInvocationJobCommand = class CreateModelInvocationJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint18.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateModelInvocationJob", {}).n("BedrockClient", "CreateModelInvocationJobCommand").sc(CreateModelInvocationJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreatePromptRouterCommand.js
-var import_middleware_endpoint19, CreatePromptRouterCommand;
-var init_CreatePromptRouterCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint19 = __toESM(require_dist_cjs65(), 1);
- CreatePromptRouterCommand = class CreatePromptRouterCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint19.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreatePromptRouter", {}).n("BedrockClient", "CreatePromptRouterCommand").sc(CreatePromptRouter$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/CreateProvisionedModelThroughputCommand.js
-var import_middleware_endpoint20, CreateProvisionedModelThroughputCommand;
-var init_CreateProvisionedModelThroughputCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint20 = __toESM(require_dist_cjs65(), 1);
- CreateProvisionedModelThroughputCommand = class CreateProvisionedModelThroughputCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint20.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "CreateProvisionedModelThroughput", {}).n("BedrockClient", "CreateProvisionedModelThroughputCommand").sc(CreateProvisionedModelThroughput$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteAutomatedReasoningPolicyBuildWorkflowCommand.js
-var import_middleware_endpoint21, DeleteAutomatedReasoningPolicyBuildWorkflowCommand;
-var init_DeleteAutomatedReasoningPolicyBuildWorkflowCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint21 = __toESM(require_dist_cjs65(), 1);
- DeleteAutomatedReasoningPolicyBuildWorkflowCommand = class DeleteAutomatedReasoningPolicyBuildWorkflowCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint21.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteAutomatedReasoningPolicyBuildWorkflow", {}).n("BedrockClient", "DeleteAutomatedReasoningPolicyBuildWorkflowCommand").sc(DeleteAutomatedReasoningPolicyBuildWorkflow$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteAutomatedReasoningPolicyCommand.js
-var import_middleware_endpoint22, DeleteAutomatedReasoningPolicyCommand;
-var init_DeleteAutomatedReasoningPolicyCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint22 = __toESM(require_dist_cjs65(), 1);
- DeleteAutomatedReasoningPolicyCommand = class DeleteAutomatedReasoningPolicyCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint22.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteAutomatedReasoningPolicy", {}).n("BedrockClient", "DeleteAutomatedReasoningPolicyCommand").sc(DeleteAutomatedReasoningPolicy$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteAutomatedReasoningPolicyTestCaseCommand.js
-var import_middleware_endpoint23, DeleteAutomatedReasoningPolicyTestCaseCommand;
-var init_DeleteAutomatedReasoningPolicyTestCaseCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint23 = __toESM(require_dist_cjs65(), 1);
- DeleteAutomatedReasoningPolicyTestCaseCommand = class DeleteAutomatedReasoningPolicyTestCaseCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint23.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteAutomatedReasoningPolicyTestCase", {}).n("BedrockClient", "DeleteAutomatedReasoningPolicyTestCaseCommand").sc(DeleteAutomatedReasoningPolicyTestCase$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteCustomModelCommand.js
-var import_middleware_endpoint24, DeleteCustomModelCommand;
-var init_DeleteCustomModelCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint24 = __toESM(require_dist_cjs65(), 1);
- DeleteCustomModelCommand = class DeleteCustomModelCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint24.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteCustomModel", {}).n("BedrockClient", "DeleteCustomModelCommand").sc(DeleteCustomModel$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteCustomModelDeploymentCommand.js
-var import_middleware_endpoint25, DeleteCustomModelDeploymentCommand;
-var init_DeleteCustomModelDeploymentCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint25 = __toESM(require_dist_cjs65(), 1);
- DeleteCustomModelDeploymentCommand = class DeleteCustomModelDeploymentCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint25.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteCustomModelDeployment", {}).n("BedrockClient", "DeleteCustomModelDeploymentCommand").sc(DeleteCustomModelDeployment$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteEnforcedGuardrailConfigurationCommand.js
-var import_middleware_endpoint26, DeleteEnforcedGuardrailConfigurationCommand;
-var init_DeleteEnforcedGuardrailConfigurationCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint26 = __toESM(require_dist_cjs65(), 1);
- DeleteEnforcedGuardrailConfigurationCommand = class DeleteEnforcedGuardrailConfigurationCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint26.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteEnforcedGuardrailConfiguration", {}).n("BedrockClient", "DeleteEnforcedGuardrailConfigurationCommand").sc(DeleteEnforcedGuardrailConfiguration$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteFoundationModelAgreementCommand.js
-var import_middleware_endpoint27, DeleteFoundationModelAgreementCommand;
-var init_DeleteFoundationModelAgreementCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint27 = __toESM(require_dist_cjs65(), 1);
- DeleteFoundationModelAgreementCommand = class DeleteFoundationModelAgreementCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint27.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteFoundationModelAgreement", {}).n("BedrockClient", "DeleteFoundationModelAgreementCommand").sc(DeleteFoundationModelAgreement$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteGuardrailCommand.js
-var import_middleware_endpoint28, DeleteGuardrailCommand;
-var init_DeleteGuardrailCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint28 = __toESM(require_dist_cjs65(), 1);
- DeleteGuardrailCommand = class DeleteGuardrailCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint28.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteGuardrail", {}).n("BedrockClient", "DeleteGuardrailCommand").sc(DeleteGuardrail$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteImportedModelCommand.js
-var import_middleware_endpoint29, DeleteImportedModelCommand;
-var init_DeleteImportedModelCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint29 = __toESM(require_dist_cjs65(), 1);
- DeleteImportedModelCommand = class DeleteImportedModelCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint29.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteImportedModel", {}).n("BedrockClient", "DeleteImportedModelCommand").sc(DeleteImportedModel$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteInferenceProfileCommand.js
-var import_middleware_endpoint30, DeleteInferenceProfileCommand;
-var init_DeleteInferenceProfileCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint30 = __toESM(require_dist_cjs65(), 1);
- DeleteInferenceProfileCommand = class DeleteInferenceProfileCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint30.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteInferenceProfile", {}).n("BedrockClient", "DeleteInferenceProfileCommand").sc(DeleteInferenceProfile$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteMarketplaceModelEndpointCommand.js
-var import_middleware_endpoint31, DeleteMarketplaceModelEndpointCommand;
-var init_DeleteMarketplaceModelEndpointCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint31 = __toESM(require_dist_cjs65(), 1);
- DeleteMarketplaceModelEndpointCommand = class DeleteMarketplaceModelEndpointCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint31.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteMarketplaceModelEndpoint", {}).n("BedrockClient", "DeleteMarketplaceModelEndpointCommand").sc(DeleteMarketplaceModelEndpoint$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteModelInvocationLoggingConfigurationCommand.js
-var import_middleware_endpoint32, DeleteModelInvocationLoggingConfigurationCommand;
-var init_DeleteModelInvocationLoggingConfigurationCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint32 = __toESM(require_dist_cjs65(), 1);
- DeleteModelInvocationLoggingConfigurationCommand = class DeleteModelInvocationLoggingConfigurationCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint32.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteModelInvocationLoggingConfiguration", {}).n("BedrockClient", "DeleteModelInvocationLoggingConfigurationCommand").sc(DeleteModelInvocationLoggingConfiguration$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeletePromptRouterCommand.js
-var import_middleware_endpoint33, DeletePromptRouterCommand;
-var init_DeletePromptRouterCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint33 = __toESM(require_dist_cjs65(), 1);
- DeletePromptRouterCommand = class DeletePromptRouterCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint33.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeletePromptRouter", {}).n("BedrockClient", "DeletePromptRouterCommand").sc(DeletePromptRouter$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeleteProvisionedModelThroughputCommand.js
-var import_middleware_endpoint34, DeleteProvisionedModelThroughputCommand;
-var init_DeleteProvisionedModelThroughputCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint34 = __toESM(require_dist_cjs65(), 1);
- DeleteProvisionedModelThroughputCommand = class DeleteProvisionedModelThroughputCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint34.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeleteProvisionedModelThroughput", {}).n("BedrockClient", "DeleteProvisionedModelThroughputCommand").sc(DeleteProvisionedModelThroughput$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/DeregisterMarketplaceModelEndpointCommand.js
-var import_middleware_endpoint35, DeregisterMarketplaceModelEndpointCommand;
-var init_DeregisterMarketplaceModelEndpointCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint35 = __toESM(require_dist_cjs65(), 1);
- DeregisterMarketplaceModelEndpointCommand = class DeregisterMarketplaceModelEndpointCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint35.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "DeregisterMarketplaceModelEndpoint", {}).n("BedrockClient", "DeregisterMarketplaceModelEndpointCommand").sc(DeregisterMarketplaceModelEndpoint$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ExportAutomatedReasoningPolicyVersionCommand.js
-var import_middleware_endpoint36, ExportAutomatedReasoningPolicyVersionCommand;
-var init_ExportAutomatedReasoningPolicyVersionCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint36 = __toESM(require_dist_cjs65(), 1);
- ExportAutomatedReasoningPolicyVersionCommand = class ExportAutomatedReasoningPolicyVersionCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint36.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ExportAutomatedReasoningPolicyVersion", {}).n("BedrockClient", "ExportAutomatedReasoningPolicyVersionCommand").sc(ExportAutomatedReasoningPolicyVersion$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetAutomatedReasoningPolicyAnnotationsCommand.js
-var import_middleware_endpoint37, GetAutomatedReasoningPolicyAnnotationsCommand;
-var init_GetAutomatedReasoningPolicyAnnotationsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint37 = __toESM(require_dist_cjs65(), 1);
- GetAutomatedReasoningPolicyAnnotationsCommand = class GetAutomatedReasoningPolicyAnnotationsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint37.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyAnnotations", {}).n("BedrockClient", "GetAutomatedReasoningPolicyAnnotationsCommand").sc(GetAutomatedReasoningPolicyAnnotations$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetAutomatedReasoningPolicyBuildWorkflowCommand.js
-var import_middleware_endpoint38, GetAutomatedReasoningPolicyBuildWorkflowCommand;
-var init_GetAutomatedReasoningPolicyBuildWorkflowCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint38 = __toESM(require_dist_cjs65(), 1);
- GetAutomatedReasoningPolicyBuildWorkflowCommand = class GetAutomatedReasoningPolicyBuildWorkflowCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint38.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyBuildWorkflow", {}).n("BedrockClient", "GetAutomatedReasoningPolicyBuildWorkflowCommand").sc(GetAutomatedReasoningPolicyBuildWorkflow$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand.js
-var import_middleware_endpoint39, GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand;
-var init_GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint39 = __toESM(require_dist_cjs65(), 1);
- GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand = class GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint39.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyBuildWorkflowResultAssets", {}).n("BedrockClient", "GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand").sc(GetAutomatedReasoningPolicyBuildWorkflowResultAssets$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetAutomatedReasoningPolicyCommand.js
-var import_middleware_endpoint40, GetAutomatedReasoningPolicyCommand;
-var init_GetAutomatedReasoningPolicyCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint40 = __toESM(require_dist_cjs65(), 1);
- GetAutomatedReasoningPolicyCommand = class GetAutomatedReasoningPolicyCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint40.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicy", {}).n("BedrockClient", "GetAutomatedReasoningPolicyCommand").sc(GetAutomatedReasoningPolicy$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetAutomatedReasoningPolicyNextScenarioCommand.js
-var import_middleware_endpoint41, GetAutomatedReasoningPolicyNextScenarioCommand;
-var init_GetAutomatedReasoningPolicyNextScenarioCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint41 = __toESM(require_dist_cjs65(), 1);
- GetAutomatedReasoningPolicyNextScenarioCommand = class GetAutomatedReasoningPolicyNextScenarioCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint41.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyNextScenario", {}).n("BedrockClient", "GetAutomatedReasoningPolicyNextScenarioCommand").sc(GetAutomatedReasoningPolicyNextScenario$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetAutomatedReasoningPolicyTestCaseCommand.js
-var import_middleware_endpoint42, GetAutomatedReasoningPolicyTestCaseCommand;
-var init_GetAutomatedReasoningPolicyTestCaseCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint42 = __toESM(require_dist_cjs65(), 1);
- GetAutomatedReasoningPolicyTestCaseCommand = class GetAutomatedReasoningPolicyTestCaseCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint42.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyTestCase", {}).n("BedrockClient", "GetAutomatedReasoningPolicyTestCaseCommand").sc(GetAutomatedReasoningPolicyTestCase$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetAutomatedReasoningPolicyTestResultCommand.js
-var import_middleware_endpoint43, GetAutomatedReasoningPolicyTestResultCommand;
-var init_GetAutomatedReasoningPolicyTestResultCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint43 = __toESM(require_dist_cjs65(), 1);
- GetAutomatedReasoningPolicyTestResultCommand = class GetAutomatedReasoningPolicyTestResultCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint43.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyTestResult", {}).n("BedrockClient", "GetAutomatedReasoningPolicyTestResultCommand").sc(GetAutomatedReasoningPolicyTestResult$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetCustomModelCommand.js
-var import_middleware_endpoint44, GetCustomModelCommand;
-var init_GetCustomModelCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint44 = __toESM(require_dist_cjs65(), 1);
- GetCustomModelCommand = class GetCustomModelCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint44.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetCustomModel", {}).n("BedrockClient", "GetCustomModelCommand").sc(GetCustomModel$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetCustomModelDeploymentCommand.js
-var import_middleware_endpoint45, GetCustomModelDeploymentCommand;
-var init_GetCustomModelDeploymentCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint45 = __toESM(require_dist_cjs65(), 1);
- GetCustomModelDeploymentCommand = class GetCustomModelDeploymentCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint45.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetCustomModelDeployment", {}).n("BedrockClient", "GetCustomModelDeploymentCommand").sc(GetCustomModelDeployment$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetEvaluationJobCommand.js
-var import_middleware_endpoint46, GetEvaluationJobCommand;
-var init_GetEvaluationJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint46 = __toESM(require_dist_cjs65(), 1);
- GetEvaluationJobCommand = class GetEvaluationJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint46.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetEvaluationJob", {}).n("BedrockClient", "GetEvaluationJobCommand").sc(GetEvaluationJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetFoundationModelAvailabilityCommand.js
-var import_middleware_endpoint47, GetFoundationModelAvailabilityCommand;
-var init_GetFoundationModelAvailabilityCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint47 = __toESM(require_dist_cjs65(), 1);
- GetFoundationModelAvailabilityCommand = class GetFoundationModelAvailabilityCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint47.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetFoundationModelAvailability", {}).n("BedrockClient", "GetFoundationModelAvailabilityCommand").sc(GetFoundationModelAvailability$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetFoundationModelCommand.js
-var import_middleware_endpoint48, GetFoundationModelCommand;
-var init_GetFoundationModelCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint48 = __toESM(require_dist_cjs65(), 1);
- GetFoundationModelCommand = class GetFoundationModelCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint48.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetFoundationModel", {}).n("BedrockClient", "GetFoundationModelCommand").sc(GetFoundationModel$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetGuardrailCommand.js
-var import_middleware_endpoint49, GetGuardrailCommand;
-var init_GetGuardrailCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint49 = __toESM(require_dist_cjs65(), 1);
- GetGuardrailCommand = class GetGuardrailCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint49.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetGuardrail", {}).n("BedrockClient", "GetGuardrailCommand").sc(GetGuardrail$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetImportedModelCommand.js
-var import_middleware_endpoint50, GetImportedModelCommand;
-var init_GetImportedModelCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint50 = __toESM(require_dist_cjs65(), 1);
- GetImportedModelCommand = class GetImportedModelCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint50.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetImportedModel", {}).n("BedrockClient", "GetImportedModelCommand").sc(GetImportedModel$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetInferenceProfileCommand.js
-var import_middleware_endpoint51, GetInferenceProfileCommand;
-var init_GetInferenceProfileCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint51 = __toESM(require_dist_cjs65(), 1);
- GetInferenceProfileCommand = class GetInferenceProfileCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint51.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetInferenceProfile", {}).n("BedrockClient", "GetInferenceProfileCommand").sc(GetInferenceProfile$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetMarketplaceModelEndpointCommand.js
-var import_middleware_endpoint52, GetMarketplaceModelEndpointCommand;
-var init_GetMarketplaceModelEndpointCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint52 = __toESM(require_dist_cjs65(), 1);
- GetMarketplaceModelEndpointCommand = class GetMarketplaceModelEndpointCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint52.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetMarketplaceModelEndpoint", {}).n("BedrockClient", "GetMarketplaceModelEndpointCommand").sc(GetMarketplaceModelEndpoint$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetModelCopyJobCommand.js
-var import_middleware_endpoint53, GetModelCopyJobCommand;
-var init_GetModelCopyJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint53 = __toESM(require_dist_cjs65(), 1);
- GetModelCopyJobCommand = class GetModelCopyJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint53.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetModelCopyJob", {}).n("BedrockClient", "GetModelCopyJobCommand").sc(GetModelCopyJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetModelCustomizationJobCommand.js
-var import_middleware_endpoint54, GetModelCustomizationJobCommand;
-var init_GetModelCustomizationJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint54 = __toESM(require_dist_cjs65(), 1);
- GetModelCustomizationJobCommand = class GetModelCustomizationJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint54.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetModelCustomizationJob", {}).n("BedrockClient", "GetModelCustomizationJobCommand").sc(GetModelCustomizationJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetModelImportJobCommand.js
-var import_middleware_endpoint55, GetModelImportJobCommand;
-var init_GetModelImportJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint55 = __toESM(require_dist_cjs65(), 1);
- GetModelImportJobCommand = class GetModelImportJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint55.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetModelImportJob", {}).n("BedrockClient", "GetModelImportJobCommand").sc(GetModelImportJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetModelInvocationJobCommand.js
-var import_middleware_endpoint56, GetModelInvocationJobCommand;
-var init_GetModelInvocationJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint56 = __toESM(require_dist_cjs65(), 1);
- GetModelInvocationJobCommand = class GetModelInvocationJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint56.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetModelInvocationJob", {}).n("BedrockClient", "GetModelInvocationJobCommand").sc(GetModelInvocationJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetModelInvocationLoggingConfigurationCommand.js
-var import_middleware_endpoint57, GetModelInvocationLoggingConfigurationCommand;
-var init_GetModelInvocationLoggingConfigurationCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint57 = __toESM(require_dist_cjs65(), 1);
- GetModelInvocationLoggingConfigurationCommand = class GetModelInvocationLoggingConfigurationCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint57.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetModelInvocationLoggingConfiguration", {}).n("BedrockClient", "GetModelInvocationLoggingConfigurationCommand").sc(GetModelInvocationLoggingConfiguration$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetPromptRouterCommand.js
-var import_middleware_endpoint58, GetPromptRouterCommand;
-var init_GetPromptRouterCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint58 = __toESM(require_dist_cjs65(), 1);
- GetPromptRouterCommand = class GetPromptRouterCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint58.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetPromptRouter", {}).n("BedrockClient", "GetPromptRouterCommand").sc(GetPromptRouter$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetProvisionedModelThroughputCommand.js
-var import_middleware_endpoint59, GetProvisionedModelThroughputCommand;
-var init_GetProvisionedModelThroughputCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint59 = __toESM(require_dist_cjs65(), 1);
- GetProvisionedModelThroughputCommand = class GetProvisionedModelThroughputCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint59.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetProvisionedModelThroughput", {}).n("BedrockClient", "GetProvisionedModelThroughputCommand").sc(GetProvisionedModelThroughput$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/GetUseCaseForModelAccessCommand.js
-var import_middleware_endpoint60, GetUseCaseForModelAccessCommand;
-var init_GetUseCaseForModelAccessCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint60 = __toESM(require_dist_cjs65(), 1);
- GetUseCaseForModelAccessCommand = class GetUseCaseForModelAccessCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint60.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "GetUseCaseForModelAccess", {}).n("BedrockClient", "GetUseCaseForModelAccessCommand").sc(GetUseCaseForModelAccess$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListAutomatedReasoningPoliciesCommand.js
-var import_middleware_endpoint61, ListAutomatedReasoningPoliciesCommand;
-var init_ListAutomatedReasoningPoliciesCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint61 = __toESM(require_dist_cjs65(), 1);
- ListAutomatedReasoningPoliciesCommand = class ListAutomatedReasoningPoliciesCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint61.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicies", {}).n("BedrockClient", "ListAutomatedReasoningPoliciesCommand").sc(ListAutomatedReasoningPolicies$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListAutomatedReasoningPolicyBuildWorkflowsCommand.js
-var import_middleware_endpoint62, ListAutomatedReasoningPolicyBuildWorkflowsCommand;
-var init_ListAutomatedReasoningPolicyBuildWorkflowsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint62 = __toESM(require_dist_cjs65(), 1);
- ListAutomatedReasoningPolicyBuildWorkflowsCommand = class ListAutomatedReasoningPolicyBuildWorkflowsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint62.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicyBuildWorkflows", {}).n("BedrockClient", "ListAutomatedReasoningPolicyBuildWorkflowsCommand").sc(ListAutomatedReasoningPolicyBuildWorkflows$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListAutomatedReasoningPolicyTestCasesCommand.js
-var import_middleware_endpoint63, ListAutomatedReasoningPolicyTestCasesCommand;
-var init_ListAutomatedReasoningPolicyTestCasesCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint63 = __toESM(require_dist_cjs65(), 1);
- ListAutomatedReasoningPolicyTestCasesCommand = class ListAutomatedReasoningPolicyTestCasesCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint63.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicyTestCases", {}).n("BedrockClient", "ListAutomatedReasoningPolicyTestCasesCommand").sc(ListAutomatedReasoningPolicyTestCases$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListAutomatedReasoningPolicyTestResultsCommand.js
-var import_middleware_endpoint64, ListAutomatedReasoningPolicyTestResultsCommand;
-var init_ListAutomatedReasoningPolicyTestResultsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint64 = __toESM(require_dist_cjs65(), 1);
- ListAutomatedReasoningPolicyTestResultsCommand = class ListAutomatedReasoningPolicyTestResultsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint64.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicyTestResults", {}).n("BedrockClient", "ListAutomatedReasoningPolicyTestResultsCommand").sc(ListAutomatedReasoningPolicyTestResults$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListCustomModelDeploymentsCommand.js
-var import_middleware_endpoint65, ListCustomModelDeploymentsCommand;
-var init_ListCustomModelDeploymentsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint65 = __toESM(require_dist_cjs65(), 1);
- ListCustomModelDeploymentsCommand = class ListCustomModelDeploymentsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint65.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListCustomModelDeployments", {}).n("BedrockClient", "ListCustomModelDeploymentsCommand").sc(ListCustomModelDeployments$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListCustomModelsCommand.js
-var import_middleware_endpoint66, ListCustomModelsCommand;
-var init_ListCustomModelsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint66 = __toESM(require_dist_cjs65(), 1);
- ListCustomModelsCommand = class ListCustomModelsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint66.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListCustomModels", {}).n("BedrockClient", "ListCustomModelsCommand").sc(ListCustomModels$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListEnforcedGuardrailsConfigurationCommand.js
-var import_middleware_endpoint67, ListEnforcedGuardrailsConfigurationCommand;
-var init_ListEnforcedGuardrailsConfigurationCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint67 = __toESM(require_dist_cjs65(), 1);
- ListEnforcedGuardrailsConfigurationCommand = class ListEnforcedGuardrailsConfigurationCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint67.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListEnforcedGuardrailsConfiguration", {}).n("BedrockClient", "ListEnforcedGuardrailsConfigurationCommand").sc(ListEnforcedGuardrailsConfiguration$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListEvaluationJobsCommand.js
-var import_middleware_endpoint68, ListEvaluationJobsCommand;
-var init_ListEvaluationJobsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint68 = __toESM(require_dist_cjs65(), 1);
- ListEvaluationJobsCommand = class ListEvaluationJobsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint68.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListEvaluationJobs", {}).n("BedrockClient", "ListEvaluationJobsCommand").sc(ListEvaluationJobs$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListFoundationModelAgreementOffersCommand.js
-var import_middleware_endpoint69, ListFoundationModelAgreementOffersCommand;
-var init_ListFoundationModelAgreementOffersCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint69 = __toESM(require_dist_cjs65(), 1);
- ListFoundationModelAgreementOffersCommand = class ListFoundationModelAgreementOffersCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint69.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListFoundationModelAgreementOffers", {}).n("BedrockClient", "ListFoundationModelAgreementOffersCommand").sc(ListFoundationModelAgreementOffers$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListFoundationModelsCommand.js
-var import_middleware_endpoint70, ListFoundationModelsCommand;
-var init_ListFoundationModelsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint70 = __toESM(require_dist_cjs65(), 1);
- ListFoundationModelsCommand = class ListFoundationModelsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint70.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListFoundationModels", {}).n("BedrockClient", "ListFoundationModelsCommand").sc(ListFoundationModels$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListGuardrailsCommand.js
-var import_middleware_endpoint71, ListGuardrailsCommand;
-var init_ListGuardrailsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint71 = __toESM(require_dist_cjs65(), 1);
- ListGuardrailsCommand = class ListGuardrailsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint71.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListGuardrails", {}).n("BedrockClient", "ListGuardrailsCommand").sc(ListGuardrails$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListImportedModelsCommand.js
-var import_middleware_endpoint72, ListImportedModelsCommand;
-var init_ListImportedModelsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint72 = __toESM(require_dist_cjs65(), 1);
- ListImportedModelsCommand = class ListImportedModelsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint72.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListImportedModels", {}).n("BedrockClient", "ListImportedModelsCommand").sc(ListImportedModels$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListInferenceProfilesCommand.js
-var import_middleware_endpoint73, ListInferenceProfilesCommand;
-var init_ListInferenceProfilesCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint73 = __toESM(require_dist_cjs65(), 1);
- ListInferenceProfilesCommand = class ListInferenceProfilesCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint73.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListInferenceProfiles", {}).n("BedrockClient", "ListInferenceProfilesCommand").sc(ListInferenceProfiles$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListMarketplaceModelEndpointsCommand.js
-var import_middleware_endpoint74, ListMarketplaceModelEndpointsCommand;
-var init_ListMarketplaceModelEndpointsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint74 = __toESM(require_dist_cjs65(), 1);
- ListMarketplaceModelEndpointsCommand = class ListMarketplaceModelEndpointsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint74.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListMarketplaceModelEndpoints", {}).n("BedrockClient", "ListMarketplaceModelEndpointsCommand").sc(ListMarketplaceModelEndpoints$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListModelCopyJobsCommand.js
-var import_middleware_endpoint75, ListModelCopyJobsCommand;
-var init_ListModelCopyJobsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint75 = __toESM(require_dist_cjs65(), 1);
- ListModelCopyJobsCommand = class ListModelCopyJobsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint75.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListModelCopyJobs", {}).n("BedrockClient", "ListModelCopyJobsCommand").sc(ListModelCopyJobs$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListModelCustomizationJobsCommand.js
-var import_middleware_endpoint76, ListModelCustomizationJobsCommand;
-var init_ListModelCustomizationJobsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint76 = __toESM(require_dist_cjs65(), 1);
- ListModelCustomizationJobsCommand = class ListModelCustomizationJobsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint76.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListModelCustomizationJobs", {}).n("BedrockClient", "ListModelCustomizationJobsCommand").sc(ListModelCustomizationJobs$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListModelImportJobsCommand.js
-var import_middleware_endpoint77, ListModelImportJobsCommand;
-var init_ListModelImportJobsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint77 = __toESM(require_dist_cjs65(), 1);
- ListModelImportJobsCommand = class ListModelImportJobsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint77.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListModelImportJobs", {}).n("BedrockClient", "ListModelImportJobsCommand").sc(ListModelImportJobs$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListModelInvocationJobsCommand.js
-var import_middleware_endpoint78, ListModelInvocationJobsCommand;
-var init_ListModelInvocationJobsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint78 = __toESM(require_dist_cjs65(), 1);
- ListModelInvocationJobsCommand = class ListModelInvocationJobsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint78.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListModelInvocationJobs", {}).n("BedrockClient", "ListModelInvocationJobsCommand").sc(ListModelInvocationJobs$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListPromptRoutersCommand.js
-var import_middleware_endpoint79, ListPromptRoutersCommand;
-var init_ListPromptRoutersCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint79 = __toESM(require_dist_cjs65(), 1);
- ListPromptRoutersCommand = class ListPromptRoutersCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint79.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListPromptRouters", {}).n("BedrockClient", "ListPromptRoutersCommand").sc(ListPromptRouters$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListProvisionedModelThroughputsCommand.js
-var import_middleware_endpoint80, ListProvisionedModelThroughputsCommand;
-var init_ListProvisionedModelThroughputsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint80 = __toESM(require_dist_cjs65(), 1);
- ListProvisionedModelThroughputsCommand = class ListProvisionedModelThroughputsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint80.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListProvisionedModelThroughputs", {}).n("BedrockClient", "ListProvisionedModelThroughputsCommand").sc(ListProvisionedModelThroughputs$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/ListTagsForResourceCommand.js
-var import_middleware_endpoint81, ListTagsForResourceCommand;
-var init_ListTagsForResourceCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint81 = __toESM(require_dist_cjs65(), 1);
- ListTagsForResourceCommand = class ListTagsForResourceCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint81.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "ListTagsForResource", {}).n("BedrockClient", "ListTagsForResourceCommand").sc(ListTagsForResource$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/PutEnforcedGuardrailConfigurationCommand.js
-var import_middleware_endpoint82, PutEnforcedGuardrailConfigurationCommand;
-var init_PutEnforcedGuardrailConfigurationCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint82 = __toESM(require_dist_cjs65(), 1);
- PutEnforcedGuardrailConfigurationCommand = class PutEnforcedGuardrailConfigurationCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint82.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "PutEnforcedGuardrailConfiguration", {}).n("BedrockClient", "PutEnforcedGuardrailConfigurationCommand").sc(PutEnforcedGuardrailConfiguration$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/PutModelInvocationLoggingConfigurationCommand.js
-var import_middleware_endpoint83, PutModelInvocationLoggingConfigurationCommand;
-var init_PutModelInvocationLoggingConfigurationCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint83 = __toESM(require_dist_cjs65(), 1);
- PutModelInvocationLoggingConfigurationCommand = class PutModelInvocationLoggingConfigurationCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint83.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "PutModelInvocationLoggingConfiguration", {}).n("BedrockClient", "PutModelInvocationLoggingConfigurationCommand").sc(PutModelInvocationLoggingConfiguration$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/PutUseCaseForModelAccessCommand.js
-var import_middleware_endpoint84, PutUseCaseForModelAccessCommand;
-var init_PutUseCaseForModelAccessCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint84 = __toESM(require_dist_cjs65(), 1);
- PutUseCaseForModelAccessCommand = class PutUseCaseForModelAccessCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint84.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "PutUseCaseForModelAccess", {}).n("BedrockClient", "PutUseCaseForModelAccessCommand").sc(PutUseCaseForModelAccess$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/RegisterMarketplaceModelEndpointCommand.js
-var import_middleware_endpoint85, RegisterMarketplaceModelEndpointCommand;
-var init_RegisterMarketplaceModelEndpointCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint85 = __toESM(require_dist_cjs65(), 1);
- RegisterMarketplaceModelEndpointCommand = class RegisterMarketplaceModelEndpointCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint85.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "RegisterMarketplaceModelEndpoint", {}).n("BedrockClient", "RegisterMarketplaceModelEndpointCommand").sc(RegisterMarketplaceModelEndpoint$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/StartAutomatedReasoningPolicyBuildWorkflowCommand.js
-var import_middleware_endpoint86, StartAutomatedReasoningPolicyBuildWorkflowCommand;
-var init_StartAutomatedReasoningPolicyBuildWorkflowCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint86 = __toESM(require_dist_cjs65(), 1);
- StartAutomatedReasoningPolicyBuildWorkflowCommand = class StartAutomatedReasoningPolicyBuildWorkflowCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint86.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "StartAutomatedReasoningPolicyBuildWorkflow", {}).n("BedrockClient", "StartAutomatedReasoningPolicyBuildWorkflowCommand").sc(StartAutomatedReasoningPolicyBuildWorkflow$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/StartAutomatedReasoningPolicyTestWorkflowCommand.js
-var import_middleware_endpoint87, StartAutomatedReasoningPolicyTestWorkflowCommand;
-var init_StartAutomatedReasoningPolicyTestWorkflowCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint87 = __toESM(require_dist_cjs65(), 1);
- StartAutomatedReasoningPolicyTestWorkflowCommand = class StartAutomatedReasoningPolicyTestWorkflowCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint87.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "StartAutomatedReasoningPolicyTestWorkflow", {}).n("BedrockClient", "StartAutomatedReasoningPolicyTestWorkflowCommand").sc(StartAutomatedReasoningPolicyTestWorkflow$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/StopEvaluationJobCommand.js
-var import_middleware_endpoint88, StopEvaluationJobCommand;
-var init_StopEvaluationJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint88 = __toESM(require_dist_cjs65(), 1);
- StopEvaluationJobCommand = class StopEvaluationJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint88.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "StopEvaluationJob", {}).n("BedrockClient", "StopEvaluationJobCommand").sc(StopEvaluationJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/StopModelCustomizationJobCommand.js
-var import_middleware_endpoint89, StopModelCustomizationJobCommand;
-var init_StopModelCustomizationJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint89 = __toESM(require_dist_cjs65(), 1);
- StopModelCustomizationJobCommand = class StopModelCustomizationJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint89.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "StopModelCustomizationJob", {}).n("BedrockClient", "StopModelCustomizationJobCommand").sc(StopModelCustomizationJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/StopModelInvocationJobCommand.js
-var import_middleware_endpoint90, StopModelInvocationJobCommand;
-var init_StopModelInvocationJobCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint90 = __toESM(require_dist_cjs65(), 1);
- StopModelInvocationJobCommand = class StopModelInvocationJobCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint90.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "StopModelInvocationJob", {}).n("BedrockClient", "StopModelInvocationJobCommand").sc(StopModelInvocationJob$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/TagResourceCommand.js
-var import_middleware_endpoint91, TagResourceCommand;
-var init_TagResourceCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint91 = __toESM(require_dist_cjs65(), 1);
- TagResourceCommand = class TagResourceCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint91.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "TagResource", {}).n("BedrockClient", "TagResourceCommand").sc(TagResource$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/UntagResourceCommand.js
-var import_middleware_endpoint92, UntagResourceCommand;
-var init_UntagResourceCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint92 = __toESM(require_dist_cjs65(), 1);
- UntagResourceCommand = class UntagResourceCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint92.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "UntagResource", {}).n("BedrockClient", "UntagResourceCommand").sc(UntagResource$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/UpdateAutomatedReasoningPolicyAnnotationsCommand.js
-var import_middleware_endpoint93, UpdateAutomatedReasoningPolicyAnnotationsCommand;
-var init_UpdateAutomatedReasoningPolicyAnnotationsCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint93 = __toESM(require_dist_cjs65(), 1);
- UpdateAutomatedReasoningPolicyAnnotationsCommand = class UpdateAutomatedReasoningPolicyAnnotationsCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint93.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "UpdateAutomatedReasoningPolicyAnnotations", {}).n("BedrockClient", "UpdateAutomatedReasoningPolicyAnnotationsCommand").sc(UpdateAutomatedReasoningPolicyAnnotations$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/UpdateAutomatedReasoningPolicyCommand.js
-var import_middleware_endpoint94, UpdateAutomatedReasoningPolicyCommand;
-var init_UpdateAutomatedReasoningPolicyCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint94 = __toESM(require_dist_cjs65(), 1);
- UpdateAutomatedReasoningPolicyCommand = class UpdateAutomatedReasoningPolicyCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint94.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "UpdateAutomatedReasoningPolicy", {}).n("BedrockClient", "UpdateAutomatedReasoningPolicyCommand").sc(UpdateAutomatedReasoningPolicy$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/UpdateAutomatedReasoningPolicyTestCaseCommand.js
-var import_middleware_endpoint95, UpdateAutomatedReasoningPolicyTestCaseCommand;
-var init_UpdateAutomatedReasoningPolicyTestCaseCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint95 = __toESM(require_dist_cjs65(), 1);
- UpdateAutomatedReasoningPolicyTestCaseCommand = class UpdateAutomatedReasoningPolicyTestCaseCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint95.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "UpdateAutomatedReasoningPolicyTestCase", {}).n("BedrockClient", "UpdateAutomatedReasoningPolicyTestCaseCommand").sc(UpdateAutomatedReasoningPolicyTestCase$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/UpdateCustomModelDeploymentCommand.js
-var import_middleware_endpoint96, UpdateCustomModelDeploymentCommand;
-var init_UpdateCustomModelDeploymentCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint96 = __toESM(require_dist_cjs65(), 1);
- UpdateCustomModelDeploymentCommand = class UpdateCustomModelDeploymentCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint96.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "UpdateCustomModelDeployment", {}).n("BedrockClient", "UpdateCustomModelDeploymentCommand").sc(UpdateCustomModelDeployment$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/UpdateGuardrailCommand.js
-var import_middleware_endpoint97, UpdateGuardrailCommand;
-var init_UpdateGuardrailCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint97 = __toESM(require_dist_cjs65(), 1);
- UpdateGuardrailCommand = class UpdateGuardrailCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint97.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "UpdateGuardrail", {}).n("BedrockClient", "UpdateGuardrailCommand").sc(UpdateGuardrail$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/UpdateMarketplaceModelEndpointCommand.js
-var import_middleware_endpoint98, UpdateMarketplaceModelEndpointCommand;
-var init_UpdateMarketplaceModelEndpointCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint98 = __toESM(require_dist_cjs65(), 1);
- UpdateMarketplaceModelEndpointCommand = class UpdateMarketplaceModelEndpointCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint98.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "UpdateMarketplaceModelEndpoint", {}).n("BedrockClient", "UpdateMarketplaceModelEndpointCommand").sc(UpdateMarketplaceModelEndpoint$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/UpdateProvisionedModelThroughputCommand.js
-var import_middleware_endpoint99, UpdateProvisionedModelThroughputCommand;
-var init_UpdateProvisionedModelThroughputCommand = __esm(() => {
- init_dist_es16();
- init_EndpointParameters();
- init_schemas_0();
- import_middleware_endpoint99 = __toESM(require_dist_cjs65(), 1);
- UpdateProvisionedModelThroughputCommand = class UpdateProvisionedModelThroughputCommand extends Command3.classBuilder().ep(commonParams).m(function(Command4, cs, config4, o3) {
- return [import_middleware_endpoint99.getEndpointPlugin(config4, Command4.getEndpointParameterInstructions())];
- }).s("AmazonBedrockControlPlaneService", "UpdateProvisionedModelThroughput", {}).n("BedrockClient", "UpdateProvisionedModelThroughputCommand").sc(UpdateProvisionedModelThroughput$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListAutomatedReasoningPoliciesPaginator.js
-var import_core21, paginateListAutomatedReasoningPolicies;
-var init_ListAutomatedReasoningPoliciesPaginator = __esm(() => {
- init_BedrockClient();
- init_ListAutomatedReasoningPoliciesCommand();
- import_core21 = __toESM(require_dist_cjs37(), 1);
- paginateListAutomatedReasoningPolicies = import_core21.createPaginator(BedrockClient, ListAutomatedReasoningPoliciesCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListAutomatedReasoningPolicyBuildWorkflowsPaginator.js
-var import_core22, paginateListAutomatedReasoningPolicyBuildWorkflows;
-var init_ListAutomatedReasoningPolicyBuildWorkflowsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListAutomatedReasoningPolicyBuildWorkflowsCommand();
- import_core22 = __toESM(require_dist_cjs37(), 1);
- paginateListAutomatedReasoningPolicyBuildWorkflows = import_core22.createPaginator(BedrockClient, ListAutomatedReasoningPolicyBuildWorkflowsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListAutomatedReasoningPolicyTestCasesPaginator.js
-var import_core23, paginateListAutomatedReasoningPolicyTestCases;
-var init_ListAutomatedReasoningPolicyTestCasesPaginator = __esm(() => {
- init_BedrockClient();
- init_ListAutomatedReasoningPolicyTestCasesCommand();
- import_core23 = __toESM(require_dist_cjs37(), 1);
- paginateListAutomatedReasoningPolicyTestCases = import_core23.createPaginator(BedrockClient, ListAutomatedReasoningPolicyTestCasesCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListAutomatedReasoningPolicyTestResultsPaginator.js
-var import_core24, paginateListAutomatedReasoningPolicyTestResults;
-var init_ListAutomatedReasoningPolicyTestResultsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListAutomatedReasoningPolicyTestResultsCommand();
- import_core24 = __toESM(require_dist_cjs37(), 1);
- paginateListAutomatedReasoningPolicyTestResults = import_core24.createPaginator(BedrockClient, ListAutomatedReasoningPolicyTestResultsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListCustomModelDeploymentsPaginator.js
-var import_core25, paginateListCustomModelDeployments;
-var init_ListCustomModelDeploymentsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListCustomModelDeploymentsCommand();
- import_core25 = __toESM(require_dist_cjs37(), 1);
- paginateListCustomModelDeployments = import_core25.createPaginator(BedrockClient, ListCustomModelDeploymentsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListCustomModelsPaginator.js
-var import_core26, paginateListCustomModels;
-var init_ListCustomModelsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListCustomModelsCommand();
- import_core26 = __toESM(require_dist_cjs37(), 1);
- paginateListCustomModels = import_core26.createPaginator(BedrockClient, ListCustomModelsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListEnforcedGuardrailsConfigurationPaginator.js
-var import_core27, paginateListEnforcedGuardrailsConfiguration;
-var init_ListEnforcedGuardrailsConfigurationPaginator = __esm(() => {
- init_BedrockClient();
- init_ListEnforcedGuardrailsConfigurationCommand();
- import_core27 = __toESM(require_dist_cjs37(), 1);
- paginateListEnforcedGuardrailsConfiguration = import_core27.createPaginator(BedrockClient, ListEnforcedGuardrailsConfigurationCommand, "nextToken", "nextToken", "");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListEvaluationJobsPaginator.js
-var import_core28, paginateListEvaluationJobs;
-var init_ListEvaluationJobsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListEvaluationJobsCommand();
- import_core28 = __toESM(require_dist_cjs37(), 1);
- paginateListEvaluationJobs = import_core28.createPaginator(BedrockClient, ListEvaluationJobsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListGuardrailsPaginator.js
-var import_core29, paginateListGuardrails;
-var init_ListGuardrailsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListGuardrailsCommand();
- import_core29 = __toESM(require_dist_cjs37(), 1);
- paginateListGuardrails = import_core29.createPaginator(BedrockClient, ListGuardrailsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListImportedModelsPaginator.js
-var import_core30, paginateListImportedModels;
-var init_ListImportedModelsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListImportedModelsCommand();
- import_core30 = __toESM(require_dist_cjs37(), 1);
- paginateListImportedModels = import_core30.createPaginator(BedrockClient, ListImportedModelsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListInferenceProfilesPaginator.js
-var import_core31, paginateListInferenceProfiles;
-var init_ListInferenceProfilesPaginator = __esm(() => {
- init_BedrockClient();
- init_ListInferenceProfilesCommand();
- import_core31 = __toESM(require_dist_cjs37(), 1);
- paginateListInferenceProfiles = import_core31.createPaginator(BedrockClient, ListInferenceProfilesCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListMarketplaceModelEndpointsPaginator.js
-var import_core32, paginateListMarketplaceModelEndpoints;
-var init_ListMarketplaceModelEndpointsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListMarketplaceModelEndpointsCommand();
- import_core32 = __toESM(require_dist_cjs37(), 1);
- paginateListMarketplaceModelEndpoints = import_core32.createPaginator(BedrockClient, ListMarketplaceModelEndpointsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListModelCopyJobsPaginator.js
-var import_core33, paginateListModelCopyJobs;
-var init_ListModelCopyJobsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListModelCopyJobsCommand();
- import_core33 = __toESM(require_dist_cjs37(), 1);
- paginateListModelCopyJobs = import_core33.createPaginator(BedrockClient, ListModelCopyJobsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListModelCustomizationJobsPaginator.js
-var import_core34, paginateListModelCustomizationJobs;
-var init_ListModelCustomizationJobsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListModelCustomizationJobsCommand();
- import_core34 = __toESM(require_dist_cjs37(), 1);
- paginateListModelCustomizationJobs = import_core34.createPaginator(BedrockClient, ListModelCustomizationJobsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListModelImportJobsPaginator.js
-var import_core35, paginateListModelImportJobs;
-var init_ListModelImportJobsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListModelImportJobsCommand();
- import_core35 = __toESM(require_dist_cjs37(), 1);
- paginateListModelImportJobs = import_core35.createPaginator(BedrockClient, ListModelImportJobsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListModelInvocationJobsPaginator.js
-var import_core36, paginateListModelInvocationJobs;
-var init_ListModelInvocationJobsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListModelInvocationJobsCommand();
- import_core36 = __toESM(require_dist_cjs37(), 1);
- paginateListModelInvocationJobs = import_core36.createPaginator(BedrockClient, ListModelInvocationJobsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListPromptRoutersPaginator.js
-var import_core37, paginateListPromptRouters;
-var init_ListPromptRoutersPaginator = __esm(() => {
- init_BedrockClient();
- init_ListPromptRoutersCommand();
- import_core37 = __toESM(require_dist_cjs37(), 1);
- paginateListPromptRouters = import_core37.createPaginator(BedrockClient, ListPromptRoutersCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/ListProvisionedModelThroughputsPaginator.js
-var import_core38, paginateListProvisionedModelThroughputs;
-var init_ListProvisionedModelThroughputsPaginator = __esm(() => {
- init_BedrockClient();
- init_ListProvisionedModelThroughputsCommand();
- import_core38 = __toESM(require_dist_cjs37(), 1);
- paginateListProvisionedModelThroughputs = import_core38.createPaginator(BedrockClient, ListProvisionedModelThroughputsCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/Bedrock.js
-var commands, paginators, Bedrock;
-var init_Bedrock = __esm(() => {
- init_dist_es16();
- init_BedrockClient();
- init_BatchDeleteEvaluationJobCommand();
- init_CancelAutomatedReasoningPolicyBuildWorkflowCommand();
- init_CreateAutomatedReasoningPolicyCommand();
- init_CreateAutomatedReasoningPolicyTestCaseCommand();
- init_CreateAutomatedReasoningPolicyVersionCommand();
- init_CreateCustomModelCommand();
- init_CreateCustomModelDeploymentCommand();
- init_CreateEvaluationJobCommand();
- init_CreateFoundationModelAgreementCommand();
- init_CreateGuardrailCommand();
- init_CreateGuardrailVersionCommand();
- init_CreateInferenceProfileCommand();
- init_CreateMarketplaceModelEndpointCommand();
- init_CreateModelCopyJobCommand();
- init_CreateModelCustomizationJobCommand();
- init_CreateModelImportJobCommand();
- init_CreateModelInvocationJobCommand();
- init_CreatePromptRouterCommand();
- init_CreateProvisionedModelThroughputCommand();
- init_DeleteAutomatedReasoningPolicyBuildWorkflowCommand();
- init_DeleteAutomatedReasoningPolicyCommand();
- init_DeleteAutomatedReasoningPolicyTestCaseCommand();
- init_DeleteCustomModelCommand();
- init_DeleteCustomModelDeploymentCommand();
- init_DeleteEnforcedGuardrailConfigurationCommand();
- init_DeleteFoundationModelAgreementCommand();
- init_DeleteGuardrailCommand();
- init_DeleteImportedModelCommand();
- init_DeleteInferenceProfileCommand();
- init_DeleteMarketplaceModelEndpointCommand();
- init_DeleteModelInvocationLoggingConfigurationCommand();
- init_DeletePromptRouterCommand();
- init_DeleteProvisionedModelThroughputCommand();
- init_DeregisterMarketplaceModelEndpointCommand();
- init_ExportAutomatedReasoningPolicyVersionCommand();
- init_GetAutomatedReasoningPolicyAnnotationsCommand();
- init_GetAutomatedReasoningPolicyBuildWorkflowCommand();
- init_GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand();
- init_GetAutomatedReasoningPolicyCommand();
- init_GetAutomatedReasoningPolicyNextScenarioCommand();
- init_GetAutomatedReasoningPolicyTestCaseCommand();
- init_GetAutomatedReasoningPolicyTestResultCommand();
- init_GetCustomModelCommand();
- init_GetCustomModelDeploymentCommand();
- init_GetEvaluationJobCommand();
- init_GetFoundationModelAvailabilityCommand();
- init_GetFoundationModelCommand();
- init_GetGuardrailCommand();
- init_GetImportedModelCommand();
- init_GetInferenceProfileCommand();
- init_GetMarketplaceModelEndpointCommand();
- init_GetModelCopyJobCommand();
- init_GetModelCustomizationJobCommand();
- init_GetModelImportJobCommand();
- init_GetModelInvocationJobCommand();
- init_GetModelInvocationLoggingConfigurationCommand();
- init_GetPromptRouterCommand();
- init_GetProvisionedModelThroughputCommand();
- init_GetUseCaseForModelAccessCommand();
- init_ListAutomatedReasoningPoliciesCommand();
- init_ListAutomatedReasoningPolicyBuildWorkflowsCommand();
- init_ListAutomatedReasoningPolicyTestCasesCommand();
- init_ListAutomatedReasoningPolicyTestResultsCommand();
- init_ListCustomModelDeploymentsCommand();
- init_ListCustomModelsCommand();
- init_ListEnforcedGuardrailsConfigurationCommand();
- init_ListEvaluationJobsCommand();
- init_ListFoundationModelAgreementOffersCommand();
- init_ListFoundationModelsCommand();
- init_ListGuardrailsCommand();
- init_ListImportedModelsCommand();
- init_ListInferenceProfilesCommand();
- init_ListMarketplaceModelEndpointsCommand();
- init_ListModelCopyJobsCommand();
- init_ListModelCustomizationJobsCommand();
- init_ListModelImportJobsCommand();
- init_ListModelInvocationJobsCommand();
- init_ListPromptRoutersCommand();
- init_ListProvisionedModelThroughputsCommand();
- init_ListTagsForResourceCommand();
- init_PutEnforcedGuardrailConfigurationCommand();
- init_PutModelInvocationLoggingConfigurationCommand();
- init_PutUseCaseForModelAccessCommand();
- init_RegisterMarketplaceModelEndpointCommand();
- init_StartAutomatedReasoningPolicyBuildWorkflowCommand();
- init_StartAutomatedReasoningPolicyTestWorkflowCommand();
- init_StopEvaluationJobCommand();
- init_StopModelCustomizationJobCommand();
- init_StopModelInvocationJobCommand();
- init_TagResourceCommand();
- init_UntagResourceCommand();
- init_UpdateAutomatedReasoningPolicyAnnotationsCommand();
- init_UpdateAutomatedReasoningPolicyCommand();
- init_UpdateAutomatedReasoningPolicyTestCaseCommand();
- init_UpdateCustomModelDeploymentCommand();
- init_UpdateGuardrailCommand();
- init_UpdateMarketplaceModelEndpointCommand();
- init_UpdateProvisionedModelThroughputCommand();
- init_ListAutomatedReasoningPoliciesPaginator();
- init_ListAutomatedReasoningPolicyBuildWorkflowsPaginator();
- init_ListAutomatedReasoningPolicyTestCasesPaginator();
- init_ListAutomatedReasoningPolicyTestResultsPaginator();
- init_ListCustomModelDeploymentsPaginator();
- init_ListCustomModelsPaginator();
- init_ListEnforcedGuardrailsConfigurationPaginator();
- init_ListEvaluationJobsPaginator();
- init_ListGuardrailsPaginator();
- init_ListImportedModelsPaginator();
- init_ListInferenceProfilesPaginator();
- init_ListMarketplaceModelEndpointsPaginator();
- init_ListModelCopyJobsPaginator();
- init_ListModelCustomizationJobsPaginator();
- init_ListModelImportJobsPaginator();
- init_ListModelInvocationJobsPaginator();
- init_ListPromptRoutersPaginator();
- init_ListProvisionedModelThroughputsPaginator();
- commands = {
- BatchDeleteEvaluationJobCommand,
- CancelAutomatedReasoningPolicyBuildWorkflowCommand,
- CreateAutomatedReasoningPolicyCommand,
- CreateAutomatedReasoningPolicyTestCaseCommand,
- CreateAutomatedReasoningPolicyVersionCommand,
- CreateCustomModelCommand,
- CreateCustomModelDeploymentCommand,
- CreateEvaluationJobCommand,
- CreateFoundationModelAgreementCommand,
- CreateGuardrailCommand,
- CreateGuardrailVersionCommand,
- CreateInferenceProfileCommand,
- CreateMarketplaceModelEndpointCommand,
- CreateModelCopyJobCommand,
- CreateModelCustomizationJobCommand,
- CreateModelImportJobCommand,
- CreateModelInvocationJobCommand,
- CreatePromptRouterCommand,
- CreateProvisionedModelThroughputCommand,
- DeleteAutomatedReasoningPolicyCommand,
- DeleteAutomatedReasoningPolicyBuildWorkflowCommand,
- DeleteAutomatedReasoningPolicyTestCaseCommand,
- DeleteCustomModelCommand,
- DeleteCustomModelDeploymentCommand,
- DeleteEnforcedGuardrailConfigurationCommand,
- DeleteFoundationModelAgreementCommand,
- DeleteGuardrailCommand,
- DeleteImportedModelCommand,
- DeleteInferenceProfileCommand,
- DeleteMarketplaceModelEndpointCommand,
- DeleteModelInvocationLoggingConfigurationCommand,
- DeletePromptRouterCommand,
- DeleteProvisionedModelThroughputCommand,
- DeregisterMarketplaceModelEndpointCommand,
- ExportAutomatedReasoningPolicyVersionCommand,
- GetAutomatedReasoningPolicyCommand,
- GetAutomatedReasoningPolicyAnnotationsCommand,
- GetAutomatedReasoningPolicyBuildWorkflowCommand,
- GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand,
- GetAutomatedReasoningPolicyNextScenarioCommand,
- GetAutomatedReasoningPolicyTestCaseCommand,
- GetAutomatedReasoningPolicyTestResultCommand,
- GetCustomModelCommand,
- GetCustomModelDeploymentCommand,
- GetEvaluationJobCommand,
- GetFoundationModelCommand,
- GetFoundationModelAvailabilityCommand,
- GetGuardrailCommand,
- GetImportedModelCommand,
- GetInferenceProfileCommand,
- GetMarketplaceModelEndpointCommand,
- GetModelCopyJobCommand,
- GetModelCustomizationJobCommand,
- GetModelImportJobCommand,
- GetModelInvocationJobCommand,
- GetModelInvocationLoggingConfigurationCommand,
- GetPromptRouterCommand,
- GetProvisionedModelThroughputCommand,
- GetUseCaseForModelAccessCommand,
- ListAutomatedReasoningPoliciesCommand,
- ListAutomatedReasoningPolicyBuildWorkflowsCommand,
- ListAutomatedReasoningPolicyTestCasesCommand,
- ListAutomatedReasoningPolicyTestResultsCommand,
- ListCustomModelDeploymentsCommand,
- ListCustomModelsCommand,
- ListEnforcedGuardrailsConfigurationCommand,
- ListEvaluationJobsCommand,
- ListFoundationModelAgreementOffersCommand,
- ListFoundationModelsCommand,
- ListGuardrailsCommand,
- ListImportedModelsCommand,
- ListInferenceProfilesCommand,
- ListMarketplaceModelEndpointsCommand,
- ListModelCopyJobsCommand,
- ListModelCustomizationJobsCommand,
- ListModelImportJobsCommand,
- ListModelInvocationJobsCommand,
- ListPromptRoutersCommand,
- ListProvisionedModelThroughputsCommand,
- ListTagsForResourceCommand,
- PutEnforcedGuardrailConfigurationCommand,
- PutModelInvocationLoggingConfigurationCommand,
- PutUseCaseForModelAccessCommand,
- RegisterMarketplaceModelEndpointCommand,
- StartAutomatedReasoningPolicyBuildWorkflowCommand,
- StartAutomatedReasoningPolicyTestWorkflowCommand,
- StopEvaluationJobCommand,
- StopModelCustomizationJobCommand,
- StopModelInvocationJobCommand,
- TagResourceCommand,
- UntagResourceCommand,
- UpdateAutomatedReasoningPolicyCommand,
- UpdateAutomatedReasoningPolicyAnnotationsCommand,
- UpdateAutomatedReasoningPolicyTestCaseCommand,
- UpdateCustomModelDeploymentCommand,
- UpdateGuardrailCommand,
- UpdateMarketplaceModelEndpointCommand,
- UpdateProvisionedModelThroughputCommand
- };
- paginators = {
- paginateListAutomatedReasoningPolicies,
- paginateListAutomatedReasoningPolicyBuildWorkflows,
- paginateListAutomatedReasoningPolicyTestCases,
- paginateListAutomatedReasoningPolicyTestResults,
- paginateListCustomModelDeployments,
- paginateListCustomModels,
- paginateListEnforcedGuardrailsConfiguration,
- paginateListEvaluationJobs,
- paginateListGuardrails,
- paginateListImportedModels,
- paginateListInferenceProfiles,
- paginateListMarketplaceModelEndpoints,
- paginateListModelCopyJobs,
- paginateListModelCustomizationJobs,
- paginateListModelImportJobs,
- paginateListModelInvocationJobs,
- paginateListPromptRouters,
- paginateListProvisionedModelThroughputs
- };
- Bedrock = class Bedrock extends BedrockClient {
- };
- createAggregatedClient2(commands, Bedrock, { paginators });
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/commands/index.js
-var init_commands = __esm(() => {
- init_BatchDeleteEvaluationJobCommand();
- init_CancelAutomatedReasoningPolicyBuildWorkflowCommand();
- init_CreateAutomatedReasoningPolicyCommand();
- init_CreateAutomatedReasoningPolicyTestCaseCommand();
- init_CreateAutomatedReasoningPolicyVersionCommand();
- init_CreateCustomModelCommand();
- init_CreateCustomModelDeploymentCommand();
- init_CreateEvaluationJobCommand();
- init_CreateFoundationModelAgreementCommand();
- init_CreateGuardrailCommand();
- init_CreateGuardrailVersionCommand();
- init_CreateInferenceProfileCommand();
- init_CreateMarketplaceModelEndpointCommand();
- init_CreateModelCopyJobCommand();
- init_CreateModelCustomizationJobCommand();
- init_CreateModelImportJobCommand();
- init_CreateModelInvocationJobCommand();
- init_CreatePromptRouterCommand();
- init_CreateProvisionedModelThroughputCommand();
- init_DeleteAutomatedReasoningPolicyBuildWorkflowCommand();
- init_DeleteAutomatedReasoningPolicyCommand();
- init_DeleteAutomatedReasoningPolicyTestCaseCommand();
- init_DeleteCustomModelCommand();
- init_DeleteCustomModelDeploymentCommand();
- init_DeleteEnforcedGuardrailConfigurationCommand();
- init_DeleteFoundationModelAgreementCommand();
- init_DeleteGuardrailCommand();
- init_DeleteImportedModelCommand();
- init_DeleteInferenceProfileCommand();
- init_DeleteMarketplaceModelEndpointCommand();
- init_DeleteModelInvocationLoggingConfigurationCommand();
- init_DeletePromptRouterCommand();
- init_DeleteProvisionedModelThroughputCommand();
- init_DeregisterMarketplaceModelEndpointCommand();
- init_ExportAutomatedReasoningPolicyVersionCommand();
- init_GetAutomatedReasoningPolicyAnnotationsCommand();
- init_GetAutomatedReasoningPolicyBuildWorkflowCommand();
- init_GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand();
- init_GetAutomatedReasoningPolicyCommand();
- init_GetAutomatedReasoningPolicyNextScenarioCommand();
- init_GetAutomatedReasoningPolicyTestCaseCommand();
- init_GetAutomatedReasoningPolicyTestResultCommand();
- init_GetCustomModelCommand();
- init_GetCustomModelDeploymentCommand();
- init_GetEvaluationJobCommand();
- init_GetFoundationModelAvailabilityCommand();
- init_GetFoundationModelCommand();
- init_GetGuardrailCommand();
- init_GetImportedModelCommand();
- init_GetInferenceProfileCommand();
- init_GetMarketplaceModelEndpointCommand();
- init_GetModelCopyJobCommand();
- init_GetModelCustomizationJobCommand();
- init_GetModelImportJobCommand();
- init_GetModelInvocationJobCommand();
- init_GetModelInvocationLoggingConfigurationCommand();
- init_GetPromptRouterCommand();
- init_GetProvisionedModelThroughputCommand();
- init_GetUseCaseForModelAccessCommand();
- init_ListAutomatedReasoningPoliciesCommand();
- init_ListAutomatedReasoningPolicyBuildWorkflowsCommand();
- init_ListAutomatedReasoningPolicyTestCasesCommand();
- init_ListAutomatedReasoningPolicyTestResultsCommand();
- init_ListCustomModelDeploymentsCommand();
- init_ListCustomModelsCommand();
- init_ListEnforcedGuardrailsConfigurationCommand();
- init_ListEvaluationJobsCommand();
- init_ListFoundationModelAgreementOffersCommand();
- init_ListFoundationModelsCommand();
- init_ListGuardrailsCommand();
- init_ListImportedModelsCommand();
- init_ListInferenceProfilesCommand();
- init_ListMarketplaceModelEndpointsCommand();
- init_ListModelCopyJobsCommand();
- init_ListModelCustomizationJobsCommand();
- init_ListModelImportJobsCommand();
- init_ListModelInvocationJobsCommand();
- init_ListPromptRoutersCommand();
- init_ListProvisionedModelThroughputsCommand();
- init_ListTagsForResourceCommand();
- init_PutEnforcedGuardrailConfigurationCommand();
- init_PutModelInvocationLoggingConfigurationCommand();
- init_PutUseCaseForModelAccessCommand();
- init_RegisterMarketplaceModelEndpointCommand();
- init_StartAutomatedReasoningPolicyBuildWorkflowCommand();
- init_StartAutomatedReasoningPolicyTestWorkflowCommand();
- init_StopEvaluationJobCommand();
- init_StopModelCustomizationJobCommand();
- init_StopModelInvocationJobCommand();
- init_TagResourceCommand();
- init_UntagResourceCommand();
- init_UpdateAutomatedReasoningPolicyAnnotationsCommand();
- init_UpdateAutomatedReasoningPolicyCommand();
- init_UpdateAutomatedReasoningPolicyTestCaseCommand();
- init_UpdateCustomModelDeploymentCommand();
- init_UpdateGuardrailCommand();
- init_UpdateMarketplaceModelEndpointCommand();
- init_UpdateProvisionedModelThroughputCommand();
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/Interfaces.js
-var init_Interfaces = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/pagination/index.js
-var init_pagination4 = __esm(() => {
- init_Interfaces();
- init_ListAutomatedReasoningPoliciesPaginator();
- init_ListAutomatedReasoningPolicyBuildWorkflowsPaginator();
- init_ListAutomatedReasoningPolicyTestCasesPaginator();
- init_ListAutomatedReasoningPolicyTestResultsPaginator();
- init_ListCustomModelDeploymentsPaginator();
- init_ListCustomModelsPaginator();
- init_ListEnforcedGuardrailsConfigurationPaginator();
- init_ListEvaluationJobsPaginator();
- init_ListGuardrailsPaginator();
- init_ListImportedModelsPaginator();
- init_ListInferenceProfilesPaginator();
- init_ListMarketplaceModelEndpointsPaginator();
- init_ListModelCopyJobsPaginator();
- init_ListModelCustomizationJobsPaginator();
- init_ListModelImportJobsPaginator();
- init_ListModelInvocationJobsPaginator();
- init_ListPromptRoutersPaginator();
- init_ListProvisionedModelThroughputsPaginator();
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/models/enums.js
-var InputTags, ConfigurationOwner, AgreementStatus, AutomatedReasoningCheckResult, AutomatedReasoningPolicyBuildWorkflowType, AutomatedReasoningPolicyBuildDocumentContentType, AutomatedReasoningPolicyBuildWorkflowStatus, AutomatedReasoningPolicyBuildResultAssetType, AutomatedReasoningPolicyBuildMessageType, AutomatedReasoningPolicyAnnotationStatus, AutomatedReasoningCheckLogicWarningType, AutomatedReasoningPolicyTestRunResult, AutomatedReasoningPolicyTestRunStatus, Status, CustomModelDeploymentStatus, CustomModelDeploymentUpdateStatus, SortModelsBy, SortOrder, ReasoningEffort, CustomizationType, ModelStatus, EvaluationJobStatus, ApplicationType, EvaluationTaskType, PerformanceConfigLatency, ExternalSourceType, QueryTransformationType, AttributeType, SearchType, RerankingMetadataSelectionMode, VectorSearchRerankingConfigurationType, RetrieveAndGenerateType, EvaluationJobType, SortJobsBy, GuardrailContentFilterAction2, GuardrailModality2, GuardrailFilterStrength, GuardrailContentFilterType, GuardrailContentFiltersTierName2, GuardrailContextualGroundingAction2, GuardrailContextualGroundingFilterType, GuardrailSensitiveInformationAction, GuardrailPiiEntityType, GuardrailTopicsTierName2, GuardrailTopicAction2, GuardrailTopicType, GuardrailWordAction2, GuardrailManagedWordsType, GuardrailStatus, InferenceProfileStatus, InferenceProfileType, ModelCopyJobStatus, ModelImportJobStatus, S3InputFormat, ModelInvocationType, ModelInvocationJobStatus, ModelCustomization, InferenceType, ModelModality, FoundationModelLifecycleStatus, PromptRouterStatus, PromptRouterType, CommitmentDuration, ProvisionedModelStatus, SortByProvisionedModels, AuthorizationStatus, EntitlementAvailability, RegionAvailability, OfferType, ModelCustomizationJobStatus, JobStatusDetails, FineTuningJobStatus;
-var init_enums = __esm(() => {
- InputTags = {
- HONOR: "HONOR",
- IGNORE: "IGNORE"
- };
- ConfigurationOwner = {
- ACCOUNT: "ACCOUNT"
- };
- AgreementStatus = {
- AVAILABLE: "AVAILABLE",
- ERROR: "ERROR",
- NOT_AVAILABLE: "NOT_AVAILABLE",
- PENDING: "PENDING"
- };
- AutomatedReasoningCheckResult = {
- IMPOSSIBLE: "IMPOSSIBLE",
- INVALID: "INVALID",
- NO_TRANSLATION: "NO_TRANSLATION",
- SATISFIABLE: "SATISFIABLE",
- TOO_COMPLEX: "TOO_COMPLEX",
- TRANSLATION_AMBIGUOUS: "TRANSLATION_AMBIGUOUS",
- VALID: "VALID"
- };
- AutomatedReasoningPolicyBuildWorkflowType = {
- GENERATE_FIDELITY_REPORT: "GENERATE_FIDELITY_REPORT",
- GENERATE_POLICY_SCENARIOS: "GENERATE_POLICY_SCENARIOS",
- IMPORT_POLICY: "IMPORT_POLICY",
- INGEST_CONTENT: "INGEST_CONTENT",
- REFINE_POLICY: "REFINE_POLICY"
- };
- AutomatedReasoningPolicyBuildDocumentContentType = {
- PDF: "pdf",
- TEXT: "txt"
- };
- AutomatedReasoningPolicyBuildWorkflowStatus = {
- BUILDING: "BUILDING",
- CANCELLED: "CANCELLED",
- CANCEL_REQUESTED: "CANCEL_REQUESTED",
- COMPLETED: "COMPLETED",
- FAILED: "FAILED",
- PREPROCESSING: "PREPROCESSING",
- SCHEDULED: "SCHEDULED",
- TESTING: "TESTING"
- };
- AutomatedReasoningPolicyBuildResultAssetType = {
- ASSET_MANIFEST: "ASSET_MANIFEST",
- BUILD_LOG: "BUILD_LOG",
- FIDELITY_REPORT: "FIDELITY_REPORT",
- GENERATED_TEST_CASES: "GENERATED_TEST_CASES",
- POLICY_DEFINITION: "POLICY_DEFINITION",
- POLICY_SCENARIOS: "POLICY_SCENARIOS",
- QUALITY_REPORT: "QUALITY_REPORT",
- SOURCE_DOCUMENT: "SOURCE_DOCUMENT"
- };
- AutomatedReasoningPolicyBuildMessageType = {
- ERROR: "ERROR",
- INFO: "INFO",
- WARNING: "WARNING"
- };
- AutomatedReasoningPolicyAnnotationStatus = {
- APPLIED: "APPLIED",
- FAILED: "FAILED"
- };
- AutomatedReasoningCheckLogicWarningType = {
- ALWAYS_FALSE: "ALWAYS_FALSE",
- ALWAYS_TRUE: "ALWAYS_TRUE"
- };
- AutomatedReasoningPolicyTestRunResult = {
- FAILED: "FAILED",
- PASSED: "PASSED"
- };
- AutomatedReasoningPolicyTestRunStatus = {
- COMPLETED: "COMPLETED",
- FAILED: "FAILED",
- IN_PROGRESS: "IN_PROGRESS",
- NOT_STARTED: "NOT_STARTED",
- SCHEDULED: "SCHEDULED"
- };
- Status = {
- INCOMPATIBLE_ENDPOINT: "INCOMPATIBLE_ENDPOINT",
- REGISTERED: "REGISTERED"
- };
- CustomModelDeploymentStatus = {
- ACTIVE: "Active",
- CREATING: "Creating",
- FAILED: "Failed"
- };
- CustomModelDeploymentUpdateStatus = {
- UPDATE_COMPLETED: "UpdateCompleted",
- UPDATE_FAILED: "UpdateFailed",
- UPDATING: "Updating"
- };
- SortModelsBy = {
- CREATION_TIME: "CreationTime"
- };
- SortOrder = {
- ASCENDING: "Ascending",
- DESCENDING: "Descending"
- };
- ReasoningEffort = {
- HIGH: "high",
- LOW: "low",
- MEDIUM: "medium"
- };
- CustomizationType = {
- CONTINUED_PRE_TRAINING: "CONTINUED_PRE_TRAINING",
- DISTILLATION: "DISTILLATION",
- FINE_TUNING: "FINE_TUNING",
- IMPORTED: "IMPORTED",
- REINFORCEMENT_FINE_TUNING: "REINFORCEMENT_FINE_TUNING"
- };
- ModelStatus = {
- ACTIVE: "Active",
- CREATING: "Creating",
- FAILED: "Failed"
- };
- EvaluationJobStatus = {
- COMPLETED: "Completed",
- DELETING: "Deleting",
- FAILED: "Failed",
- IN_PROGRESS: "InProgress",
- STOPPED: "Stopped",
- STOPPING: "Stopping"
- };
- ApplicationType = {
- MODEL_EVALUATION: "ModelEvaluation",
- RAG_EVALUATION: "RagEvaluation"
- };
- EvaluationTaskType = {
- CLASSIFICATION: "Classification",
- CUSTOM: "Custom",
- GENERATION: "Generation",
- QUESTION_AND_ANSWER: "QuestionAndAnswer",
- SUMMARIZATION: "Summarization"
- };
- PerformanceConfigLatency = {
- OPTIMIZED: "optimized",
- STANDARD: "standard"
- };
- ExternalSourceType = {
- BYTE_CONTENT: "BYTE_CONTENT",
- S3: "S3"
- };
- QueryTransformationType = {
- QUERY_DECOMPOSITION: "QUERY_DECOMPOSITION"
- };
- AttributeType = {
- BOOLEAN: "BOOLEAN",
- NUMBER: "NUMBER",
- STRING: "STRING",
- STRING_LIST: "STRING_LIST"
- };
- SearchType = {
- HYBRID: "HYBRID",
- SEMANTIC: "SEMANTIC"
- };
- RerankingMetadataSelectionMode = {
- ALL: "ALL",
- SELECTIVE: "SELECTIVE"
- };
- VectorSearchRerankingConfigurationType = {
- BEDROCK_RERANKING_MODEL: "BEDROCK_RERANKING_MODEL"
- };
- RetrieveAndGenerateType = {
- EXTERNAL_SOURCES: "EXTERNAL_SOURCES",
- KNOWLEDGE_BASE: "KNOWLEDGE_BASE"
- };
- EvaluationJobType = {
- AUTOMATED: "Automated",
- HUMAN: "Human"
- };
- SortJobsBy = {
- CREATION_TIME: "CreationTime"
- };
- GuardrailContentFilterAction2 = {
- BLOCK: "BLOCK",
- NONE: "NONE"
- };
- GuardrailModality2 = {
- IMAGE: "IMAGE",
- TEXT: "TEXT"
- };
- GuardrailFilterStrength = {
- HIGH: "HIGH",
- LOW: "LOW",
- MEDIUM: "MEDIUM",
- NONE: "NONE"
- };
- GuardrailContentFilterType = {
- HATE: "HATE",
- INSULTS: "INSULTS",
- MISCONDUCT: "MISCONDUCT",
- PROMPT_ATTACK: "PROMPT_ATTACK",
- SEXUAL: "SEXUAL",
- VIOLENCE: "VIOLENCE"
- };
- GuardrailContentFiltersTierName2 = {
- CLASSIC: "CLASSIC",
- STANDARD: "STANDARD"
- };
- GuardrailContextualGroundingAction2 = {
- BLOCK: "BLOCK",
- NONE: "NONE"
- };
- GuardrailContextualGroundingFilterType = {
- GROUNDING: "GROUNDING",
- RELEVANCE: "RELEVANCE"
- };
- GuardrailSensitiveInformationAction = {
- ANONYMIZE: "ANONYMIZE",
- BLOCK: "BLOCK",
- NONE: "NONE"
- };
- GuardrailPiiEntityType = {
- ADDRESS: "ADDRESS",
- AGE: "AGE",
- AWS_ACCESS_KEY: "AWS_ACCESS_KEY",
- AWS_SECRET_KEY: "AWS_SECRET_KEY",
- CA_HEALTH_NUMBER: "CA_HEALTH_NUMBER",
- CA_SOCIAL_INSURANCE_NUMBER: "CA_SOCIAL_INSURANCE_NUMBER",
- CREDIT_DEBIT_CARD_CVV: "CREDIT_DEBIT_CARD_CVV",
- CREDIT_DEBIT_CARD_EXPIRY: "CREDIT_DEBIT_CARD_EXPIRY",
- CREDIT_DEBIT_CARD_NUMBER: "CREDIT_DEBIT_CARD_NUMBER",
- DRIVER_ID: "DRIVER_ID",
- EMAIL: "EMAIL",
- INTERNATIONAL_BANK_ACCOUNT_NUMBER: "INTERNATIONAL_BANK_ACCOUNT_NUMBER",
- IP_ADDRESS: "IP_ADDRESS",
- LICENSE_PLATE: "LICENSE_PLATE",
- MAC_ADDRESS: "MAC_ADDRESS",
- NAME: "NAME",
- PASSWORD: "PASSWORD",
- PHONE: "PHONE",
- PIN: "PIN",
- SWIFT_CODE: "SWIFT_CODE",
- UK_NATIONAL_HEALTH_SERVICE_NUMBER: "UK_NATIONAL_HEALTH_SERVICE_NUMBER",
- UK_NATIONAL_INSURANCE_NUMBER: "UK_NATIONAL_INSURANCE_NUMBER",
- UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER: "UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER",
- URL: "URL",
- USERNAME: "USERNAME",
- US_BANK_ACCOUNT_NUMBER: "US_BANK_ACCOUNT_NUMBER",
- US_BANK_ROUTING_NUMBER: "US_BANK_ROUTING_NUMBER",
- US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER: "US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER",
- US_PASSPORT_NUMBER: "US_PASSPORT_NUMBER",
- US_SOCIAL_SECURITY_NUMBER: "US_SOCIAL_SECURITY_NUMBER",
- VEHICLE_IDENTIFICATION_NUMBER: "VEHICLE_IDENTIFICATION_NUMBER"
- };
- GuardrailTopicsTierName2 = {
- CLASSIC: "CLASSIC",
- STANDARD: "STANDARD"
- };
- GuardrailTopicAction2 = {
- BLOCK: "BLOCK",
- NONE: "NONE"
- };
- GuardrailTopicType = {
- DENY: "DENY"
- };
- GuardrailWordAction2 = {
- BLOCK: "BLOCK",
- NONE: "NONE"
- };
- GuardrailManagedWordsType = {
- PROFANITY: "PROFANITY"
- };
- GuardrailStatus = {
- CREATING: "CREATING",
- DELETING: "DELETING",
- FAILED: "FAILED",
- READY: "READY",
- UPDATING: "UPDATING",
- VERSIONING: "VERSIONING"
- };
- InferenceProfileStatus = {
- ACTIVE: "ACTIVE"
- };
- InferenceProfileType = {
- APPLICATION: "APPLICATION",
- SYSTEM_DEFINED: "SYSTEM_DEFINED"
- };
- ModelCopyJobStatus = {
- COMPLETED: "Completed",
- FAILED: "Failed",
- IN_PROGRESS: "InProgress"
- };
- ModelImportJobStatus = {
- COMPLETED: "Completed",
- FAILED: "Failed",
- IN_PROGRESS: "InProgress"
- };
- S3InputFormat = {
- JSONL: "JSONL"
- };
- ModelInvocationType = {
- Converse: "Converse",
- InvokeModel: "InvokeModel"
- };
- ModelInvocationJobStatus = {
- COMPLETED: "Completed",
- EXPIRED: "Expired",
- FAILED: "Failed",
- IN_PROGRESS: "InProgress",
- PARTIALLY_COMPLETED: "PartiallyCompleted",
- SCHEDULED: "Scheduled",
- STOPPED: "Stopped",
- STOPPING: "Stopping",
- SUBMITTED: "Submitted",
- VALIDATING: "Validating"
- };
- ModelCustomization = {
- CONTINUED_PRE_TRAINING: "CONTINUED_PRE_TRAINING",
- DISTILLATION: "DISTILLATION",
- FINE_TUNING: "FINE_TUNING"
- };
- InferenceType = {
- ON_DEMAND: "ON_DEMAND",
- PROVISIONED: "PROVISIONED"
- };
- ModelModality = {
- EMBEDDING: "EMBEDDING",
- IMAGE: "IMAGE",
- TEXT: "TEXT"
- };
- FoundationModelLifecycleStatus = {
- ACTIVE: "ACTIVE",
- LEGACY: "LEGACY"
- };
- PromptRouterStatus = {
- AVAILABLE: "AVAILABLE"
- };
- PromptRouterType = {
- CUSTOM: "custom",
- DEFAULT: "default"
- };
- CommitmentDuration = {
- ONE_MONTH: "OneMonth",
- SIX_MONTHS: "SixMonths"
- };
- ProvisionedModelStatus = {
- CREATING: "Creating",
- FAILED: "Failed",
- IN_SERVICE: "InService",
- UPDATING: "Updating"
- };
- SortByProvisionedModels = {
- CREATION_TIME: "CreationTime"
- };
- AuthorizationStatus = {
- AUTHORIZED: "AUTHORIZED",
- NOT_AUTHORIZED: "NOT_AUTHORIZED"
- };
- EntitlementAvailability = {
- AVAILABLE: "AVAILABLE",
- NOT_AVAILABLE: "NOT_AVAILABLE"
- };
- RegionAvailability = {
- AVAILABLE: "AVAILABLE",
- NOT_AVAILABLE: "NOT_AVAILABLE"
- };
- OfferType = {
- ALL: "ALL",
- PUBLIC: "PUBLIC"
- };
- ModelCustomizationJobStatus = {
- COMPLETED: "Completed",
- FAILED: "Failed",
- IN_PROGRESS: "InProgress",
- STOPPED: "Stopped",
- STOPPING: "Stopping"
- };
- JobStatusDetails = {
- COMPLETED: "Completed",
- FAILED: "Failed",
- IN_PROGRESS: "InProgress",
- NOT_STARTED: "NotStarted",
- STOPPED: "Stopped",
- STOPPING: "Stopping"
- };
- FineTuningJobStatus = {
- COMPLETED: "Completed",
- FAILED: "Failed",
- IN_PROGRESS: "InProgress",
- STOPPED: "Stopped",
- STOPPING: "Stopping"
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/models/models_0.js
-var init_models_0 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/models/models_1.js
-var init_models_1 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock/dist-es/index.js
-var exports_dist_es11 = {};
-__export(exports_dist_es11, {
- paginateListProvisionedModelThroughputs: () => paginateListProvisionedModelThroughputs,
- paginateListPromptRouters: () => paginateListPromptRouters,
- paginateListModelInvocationJobs: () => paginateListModelInvocationJobs,
- paginateListModelImportJobs: () => paginateListModelImportJobs,
- paginateListModelCustomizationJobs: () => paginateListModelCustomizationJobs,
- paginateListModelCopyJobs: () => paginateListModelCopyJobs,
- paginateListMarketplaceModelEndpoints: () => paginateListMarketplaceModelEndpoints,
- paginateListInferenceProfiles: () => paginateListInferenceProfiles,
- paginateListImportedModels: () => paginateListImportedModels,
- paginateListGuardrails: () => paginateListGuardrails,
- paginateListEvaluationJobs: () => paginateListEvaluationJobs,
- paginateListEnforcedGuardrailsConfiguration: () => paginateListEnforcedGuardrailsConfiguration,
- paginateListCustomModels: () => paginateListCustomModels,
- paginateListCustomModelDeployments: () => paginateListCustomModelDeployments,
- paginateListAutomatedReasoningPolicyTestResults: () => paginateListAutomatedReasoningPolicyTestResults,
- paginateListAutomatedReasoningPolicyTestCases: () => paginateListAutomatedReasoningPolicyTestCases,
- paginateListAutomatedReasoningPolicyBuildWorkflows: () => paginateListAutomatedReasoningPolicyBuildWorkflows,
- paginateListAutomatedReasoningPolicies: () => paginateListAutomatedReasoningPolicies,
- errorTypeRegistries: () => errorTypeRegistries,
- __Client: () => Client2,
- VpcConfig$: () => VpcConfig$,
- VectorSearchRerankingConfigurationType: () => VectorSearchRerankingConfigurationType,
- VectorSearchRerankingConfiguration$: () => VectorSearchRerankingConfiguration$,
- VectorSearchBedrockRerankingModelConfiguration$: () => VectorSearchBedrockRerankingModelConfiguration$,
- VectorSearchBedrockRerankingConfiguration$: () => VectorSearchBedrockRerankingConfiguration$,
- ValidityTerm$: () => ValidityTerm$,
- ValidatorMetric$: () => ValidatorMetric$,
- Validator$: () => Validator$,
- ValidationException$: () => ValidationException$,
- ValidationException: () => ValidationException,
- ValidationDetails$: () => ValidationDetails$,
- ValidationDataConfig$: () => ValidationDataConfig$,
- UpdateProvisionedModelThroughputResponse$: () => UpdateProvisionedModelThroughputResponse$,
- UpdateProvisionedModelThroughputRequest$: () => UpdateProvisionedModelThroughputRequest$,
- UpdateProvisionedModelThroughputCommand: () => UpdateProvisionedModelThroughputCommand,
- UpdateProvisionedModelThroughput$: () => UpdateProvisionedModelThroughput$,
- UpdateMarketplaceModelEndpointResponse$: () => UpdateMarketplaceModelEndpointResponse$,
- UpdateMarketplaceModelEndpointRequest$: () => UpdateMarketplaceModelEndpointRequest$,
- UpdateMarketplaceModelEndpointCommand: () => UpdateMarketplaceModelEndpointCommand,
- UpdateMarketplaceModelEndpoint$: () => UpdateMarketplaceModelEndpoint$,
- UpdateGuardrailResponse$: () => UpdateGuardrailResponse$,
- UpdateGuardrailRequest$: () => UpdateGuardrailRequest$,
- UpdateGuardrailCommand: () => UpdateGuardrailCommand,
- UpdateGuardrail$: () => UpdateGuardrail$,
- UpdateCustomModelDeploymentResponse$: () => UpdateCustomModelDeploymentResponse$,
- UpdateCustomModelDeploymentRequest$: () => UpdateCustomModelDeploymentRequest$,
- UpdateCustomModelDeploymentCommand: () => UpdateCustomModelDeploymentCommand,
- UpdateCustomModelDeployment$: () => UpdateCustomModelDeployment$,
- UpdateAutomatedReasoningPolicyTestCaseResponse$: () => UpdateAutomatedReasoningPolicyTestCaseResponse$,
- UpdateAutomatedReasoningPolicyTestCaseRequest$: () => UpdateAutomatedReasoningPolicyTestCaseRequest$,
- UpdateAutomatedReasoningPolicyTestCaseCommand: () => UpdateAutomatedReasoningPolicyTestCaseCommand,
- UpdateAutomatedReasoningPolicyTestCase$: () => UpdateAutomatedReasoningPolicyTestCase$,
- UpdateAutomatedReasoningPolicyResponse$: () => UpdateAutomatedReasoningPolicyResponse$,
- UpdateAutomatedReasoningPolicyRequest$: () => UpdateAutomatedReasoningPolicyRequest$,
- UpdateAutomatedReasoningPolicyCommand: () => UpdateAutomatedReasoningPolicyCommand,
- UpdateAutomatedReasoningPolicyAnnotationsResponse$: () => UpdateAutomatedReasoningPolicyAnnotationsResponse$,
- UpdateAutomatedReasoningPolicyAnnotationsRequest$: () => UpdateAutomatedReasoningPolicyAnnotationsRequest$,
- UpdateAutomatedReasoningPolicyAnnotationsCommand: () => UpdateAutomatedReasoningPolicyAnnotationsCommand,
- UpdateAutomatedReasoningPolicyAnnotations$: () => UpdateAutomatedReasoningPolicyAnnotations$,
- UpdateAutomatedReasoningPolicy$: () => UpdateAutomatedReasoningPolicy$,
- UntagResourceResponse$: () => UntagResourceResponse$,
- UntagResourceRequest$: () => UntagResourceRequest$,
- UntagResourceCommand: () => UntagResourceCommand,
- UntagResource$: () => UntagResource$,
- TrainingMetrics$: () => TrainingMetrics$,
- TrainingDetails$: () => TrainingDetails$,
- TrainingDataConfig$: () => TrainingDataConfig$,
- TooManyTagsException$: () => TooManyTagsException$,
- TooManyTagsException: () => TooManyTagsException,
- ThrottlingException$: () => ThrottlingException$,
- ThrottlingException: () => ThrottlingException,
- TextInferenceConfig$: () => TextInferenceConfig$,
- TermDetails$: () => TermDetails$,
- TeacherModelConfig$: () => TeacherModelConfig$,
- TagResourceResponse$: () => TagResourceResponse$,
- TagResourceRequest$: () => TagResourceRequest$,
- TagResourceCommand: () => TagResourceCommand,
- TagResource$: () => TagResource$,
- Tag$: () => Tag$,
- SupportTerm$: () => SupportTerm$,
- StopModelInvocationJobResponse$: () => StopModelInvocationJobResponse$,
- StopModelInvocationJobRequest$: () => StopModelInvocationJobRequest$,
- StopModelInvocationJobCommand: () => StopModelInvocationJobCommand,
- StopModelInvocationJob$: () => StopModelInvocationJob$,
- StopModelCustomizationJobResponse$: () => StopModelCustomizationJobResponse$,
- StopModelCustomizationJobRequest$: () => StopModelCustomizationJobRequest$,
- StopModelCustomizationJobCommand: () => StopModelCustomizationJobCommand,
- StopModelCustomizationJob$: () => StopModelCustomizationJob$,
- StopEvaluationJobResponse$: () => StopEvaluationJobResponse$,
- StopEvaluationJobRequest$: () => StopEvaluationJobRequest$,
- StopEvaluationJobCommand: () => StopEvaluationJobCommand,
- StopEvaluationJob$: () => StopEvaluationJob$,
- StatusDetails$: () => StatusDetails$,
- Status: () => Status,
- StartAutomatedReasoningPolicyTestWorkflowResponse$: () => StartAutomatedReasoningPolicyTestWorkflowResponse$,
- StartAutomatedReasoningPolicyTestWorkflowRequest$: () => StartAutomatedReasoningPolicyTestWorkflowRequest$,
- StartAutomatedReasoningPolicyTestWorkflowCommand: () => StartAutomatedReasoningPolicyTestWorkflowCommand,
- StartAutomatedReasoningPolicyTestWorkflow$: () => StartAutomatedReasoningPolicyTestWorkflow$,
- StartAutomatedReasoningPolicyBuildWorkflowResponse$: () => StartAutomatedReasoningPolicyBuildWorkflowResponse$,
- StartAutomatedReasoningPolicyBuildWorkflowRequest$: () => StartAutomatedReasoningPolicyBuildWorkflowRequest$,
- StartAutomatedReasoningPolicyBuildWorkflowCommand: () => StartAutomatedReasoningPolicyBuildWorkflowCommand,
- StartAutomatedReasoningPolicyBuildWorkflow$: () => StartAutomatedReasoningPolicyBuildWorkflow$,
- SortOrder: () => SortOrder,
- SortModelsBy: () => SortModelsBy,
- SortJobsBy: () => SortJobsBy,
- SortByProvisionedModels: () => SortByProvisionedModels,
- ServiceUnavailableException$: () => ServiceUnavailableException$,
- ServiceUnavailableException: () => ServiceUnavailableException,
- ServiceQuotaExceededException$: () => ServiceQuotaExceededException$,
- ServiceQuotaExceededException: () => ServiceQuotaExceededException,
- SearchType: () => SearchType,
- SageMakerEndpoint$: () => SageMakerEndpoint$,
- S3ObjectDoc$: () => S3ObjectDoc$,
- S3InputFormat: () => S3InputFormat,
- S3DataSource$: () => S3DataSource$,
- S3Config$: () => S3Config$,
- RoutingCriteria$: () => RoutingCriteria$,
- RetrieveConfig$: () => RetrieveConfig$,
- RetrieveAndGenerateType: () => RetrieveAndGenerateType,
- RetrieveAndGenerateConfiguration$: () => RetrieveAndGenerateConfiguration$,
- RetrievalFilter$: () => RetrievalFilter$,
- ResourceNotFoundException$: () => ResourceNotFoundException$,
- ResourceNotFoundException: () => ResourceNotFoundException,
- ResourceInUseException$: () => ResourceInUseException$,
- ResourceInUseException: () => ResourceInUseException,
- RerankingMetadataSelectiveModeConfiguration$: () => RerankingMetadataSelectiveModeConfiguration$,
- RerankingMetadataSelectionMode: () => RerankingMetadataSelectionMode,
- RequestMetadataFilters$: () => RequestMetadataFilters$,
- RequestMetadataBaseFilters$: () => RequestMetadataBaseFilters$,
- RegisterMarketplaceModelEndpointResponse$: () => RegisterMarketplaceModelEndpointResponse$,
- RegisterMarketplaceModelEndpointRequest$: () => RegisterMarketplaceModelEndpointRequest$,
- RegisterMarketplaceModelEndpointCommand: () => RegisterMarketplaceModelEndpointCommand,
- RegisterMarketplaceModelEndpoint$: () => RegisterMarketplaceModelEndpoint$,
- RegionAvailability: () => RegionAvailability,
- ReasoningEffort: () => ReasoningEffort,
- RatingScaleItemValue$: () => RatingScaleItemValue$,
- RatingScaleItem$: () => RatingScaleItem$,
- RFTHyperParameters$: () => RFTHyperParameters$,
- RFTConfig$: () => RFTConfig$,
- RAGConfig$: () => RAGConfig$,
- QueryTransformationType: () => QueryTransformationType,
- QueryTransformationConfiguration$: () => QueryTransformationConfiguration$,
- PutUseCaseForModelAccessResponse$: () => PutUseCaseForModelAccessResponse$,
- PutUseCaseForModelAccessRequest$: () => PutUseCaseForModelAccessRequest$,
- PutUseCaseForModelAccessCommand: () => PutUseCaseForModelAccessCommand,
- PutUseCaseForModelAccess$: () => PutUseCaseForModelAccess$,
- PutModelInvocationLoggingConfigurationResponse$: () => PutModelInvocationLoggingConfigurationResponse$,
- PutModelInvocationLoggingConfigurationRequest$: () => PutModelInvocationLoggingConfigurationRequest$,
- PutModelInvocationLoggingConfigurationCommand: () => PutModelInvocationLoggingConfigurationCommand,
- PutModelInvocationLoggingConfiguration$: () => PutModelInvocationLoggingConfiguration$,
- PutEnforcedGuardrailConfigurationResponse$: () => PutEnforcedGuardrailConfigurationResponse$,
- PutEnforcedGuardrailConfigurationRequest$: () => PutEnforcedGuardrailConfigurationRequest$,
- PutEnforcedGuardrailConfigurationCommand: () => PutEnforcedGuardrailConfigurationCommand,
- PutEnforcedGuardrailConfiguration$: () => PutEnforcedGuardrailConfiguration$,
- ProvisionedModelSummary$: () => ProvisionedModelSummary$,
- ProvisionedModelStatus: () => ProvisionedModelStatus,
- PromptTemplate$: () => PromptTemplate$,
- PromptRouterType: () => PromptRouterType,
- PromptRouterTargetModel$: () => PromptRouterTargetModel$,
- PromptRouterSummary$: () => PromptRouterSummary$,
- PromptRouterStatus: () => PromptRouterStatus,
- PricingTerm$: () => PricingTerm$,
- PerformanceConfiguration$: () => PerformanceConfiguration$,
- PerformanceConfigLatency: () => PerformanceConfigLatency,
- OutputDataConfig$: () => OutputDataConfig$,
- OrchestrationConfiguration$: () => OrchestrationConfiguration$,
- OfferType: () => OfferType,
- Offer$: () => Offer$,
- ModelStatus: () => ModelStatus,
- ModelModality: () => ModelModality,
- ModelInvocationType: () => ModelInvocationType,
- ModelInvocationJobSummary$: () => ModelInvocationJobSummary$,
- ModelInvocationJobStatus: () => ModelInvocationJobStatus,
- ModelInvocationJobS3OutputDataConfig$: () => ModelInvocationJobS3OutputDataConfig$,
- ModelInvocationJobS3InputDataConfig$: () => ModelInvocationJobS3InputDataConfig$,
- ModelInvocationJobOutputDataConfig$: () => ModelInvocationJobOutputDataConfig$,
- ModelInvocationJobInputDataConfig$: () => ModelInvocationJobInputDataConfig$,
- ModelImportJobSummary$: () => ModelImportJobSummary$,
- ModelImportJobStatus: () => ModelImportJobStatus,
- ModelEnforcement$: () => ModelEnforcement$,
- ModelDataSource$: () => ModelDataSource$,
- ModelCustomizationJobSummary$: () => ModelCustomizationJobSummary$,
- ModelCustomizationJobStatus: () => ModelCustomizationJobStatus,
- ModelCustomization: () => ModelCustomization,
- ModelCopyJobSummary$: () => ModelCopyJobSummary$,
- ModelCopyJobStatus: () => ModelCopyJobStatus,
- MetadataConfigurationForReranking$: () => MetadataConfigurationForReranking$,
- MetadataAttributeSchema$: () => MetadataAttributeSchema$,
- MarketplaceModelEndpointSummary$: () => MarketplaceModelEndpointSummary$,
- MarketplaceModelEndpoint$: () => MarketplaceModelEndpoint$,
- LoggingConfig$: () => LoggingConfig$,
- ListTagsForResourceResponse$: () => ListTagsForResourceResponse$,
- ListTagsForResourceRequest$: () => ListTagsForResourceRequest$,
- ListTagsForResourceCommand: () => ListTagsForResourceCommand,
- ListTagsForResource$: () => ListTagsForResource$,
- ListProvisionedModelThroughputsResponse$: () => ListProvisionedModelThroughputsResponse$,
- ListProvisionedModelThroughputsRequest$: () => ListProvisionedModelThroughputsRequest$,
- ListProvisionedModelThroughputsCommand: () => ListProvisionedModelThroughputsCommand,
- ListProvisionedModelThroughputs$: () => ListProvisionedModelThroughputs$,
- ListPromptRoutersResponse$: () => ListPromptRoutersResponse$,
- ListPromptRoutersRequest$: () => ListPromptRoutersRequest$,
- ListPromptRoutersCommand: () => ListPromptRoutersCommand,
- ListPromptRouters$: () => ListPromptRouters$,
- ListModelInvocationJobsResponse$: () => ListModelInvocationJobsResponse$,
- ListModelInvocationJobsRequest$: () => ListModelInvocationJobsRequest$,
- ListModelInvocationJobsCommand: () => ListModelInvocationJobsCommand,
- ListModelInvocationJobs$: () => ListModelInvocationJobs$,
- ListModelImportJobsResponse$: () => ListModelImportJobsResponse$,
- ListModelImportJobsRequest$: () => ListModelImportJobsRequest$,
- ListModelImportJobsCommand: () => ListModelImportJobsCommand,
- ListModelImportJobs$: () => ListModelImportJobs$,
- ListModelCustomizationJobsResponse$: () => ListModelCustomizationJobsResponse$,
- ListModelCustomizationJobsRequest$: () => ListModelCustomizationJobsRequest$,
- ListModelCustomizationJobsCommand: () => ListModelCustomizationJobsCommand,
- ListModelCustomizationJobs$: () => ListModelCustomizationJobs$,
- ListModelCopyJobsResponse$: () => ListModelCopyJobsResponse$,
- ListModelCopyJobsRequest$: () => ListModelCopyJobsRequest$,
- ListModelCopyJobsCommand: () => ListModelCopyJobsCommand,
- ListModelCopyJobs$: () => ListModelCopyJobs$,
- ListMarketplaceModelEndpointsResponse$: () => ListMarketplaceModelEndpointsResponse$,
- ListMarketplaceModelEndpointsRequest$: () => ListMarketplaceModelEndpointsRequest$,
- ListMarketplaceModelEndpointsCommand: () => ListMarketplaceModelEndpointsCommand,
- ListMarketplaceModelEndpoints$: () => ListMarketplaceModelEndpoints$,
- ListInferenceProfilesResponse$: () => ListInferenceProfilesResponse$,
- ListInferenceProfilesRequest$: () => ListInferenceProfilesRequest$,
- ListInferenceProfilesCommand: () => ListInferenceProfilesCommand,
- ListInferenceProfiles$: () => ListInferenceProfiles$,
- ListImportedModelsResponse$: () => ListImportedModelsResponse$,
- ListImportedModelsRequest$: () => ListImportedModelsRequest$,
- ListImportedModelsCommand: () => ListImportedModelsCommand,
- ListImportedModels$: () => ListImportedModels$,
- ListGuardrailsResponse$: () => ListGuardrailsResponse$,
- ListGuardrailsRequest$: () => ListGuardrailsRequest$,
- ListGuardrailsCommand: () => ListGuardrailsCommand,
- ListGuardrails$: () => ListGuardrails$,
- ListFoundationModelsResponse$: () => ListFoundationModelsResponse$,
- ListFoundationModelsRequest$: () => ListFoundationModelsRequest$,
- ListFoundationModelsCommand: () => ListFoundationModelsCommand,
- ListFoundationModels$: () => ListFoundationModels$,
- ListFoundationModelAgreementOffersResponse$: () => ListFoundationModelAgreementOffersResponse$,
- ListFoundationModelAgreementOffersRequest$: () => ListFoundationModelAgreementOffersRequest$,
- ListFoundationModelAgreementOffersCommand: () => ListFoundationModelAgreementOffersCommand,
- ListFoundationModelAgreementOffers$: () => ListFoundationModelAgreementOffers$,
- ListEvaluationJobsResponse$: () => ListEvaluationJobsResponse$,
- ListEvaluationJobsRequest$: () => ListEvaluationJobsRequest$,
- ListEvaluationJobsCommand: () => ListEvaluationJobsCommand,
- ListEvaluationJobs$: () => ListEvaluationJobs$,
- ListEnforcedGuardrailsConfigurationResponse$: () => ListEnforcedGuardrailsConfigurationResponse$,
- ListEnforcedGuardrailsConfigurationRequest$: () => ListEnforcedGuardrailsConfigurationRequest$,
- ListEnforcedGuardrailsConfigurationCommand: () => ListEnforcedGuardrailsConfigurationCommand,
- ListEnforcedGuardrailsConfiguration$: () => ListEnforcedGuardrailsConfiguration$,
- ListCustomModelsResponse$: () => ListCustomModelsResponse$,
- ListCustomModelsRequest$: () => ListCustomModelsRequest$,
- ListCustomModelsCommand: () => ListCustomModelsCommand,
- ListCustomModels$: () => ListCustomModels$,
- ListCustomModelDeploymentsResponse$: () => ListCustomModelDeploymentsResponse$,
- ListCustomModelDeploymentsRequest$: () => ListCustomModelDeploymentsRequest$,
- ListCustomModelDeploymentsCommand: () => ListCustomModelDeploymentsCommand,
- ListCustomModelDeployments$: () => ListCustomModelDeployments$,
- ListAutomatedReasoningPolicyTestResultsResponse$: () => ListAutomatedReasoningPolicyTestResultsResponse$,
- ListAutomatedReasoningPolicyTestResultsRequest$: () => ListAutomatedReasoningPolicyTestResultsRequest$,
- ListAutomatedReasoningPolicyTestResultsCommand: () => ListAutomatedReasoningPolicyTestResultsCommand,
- ListAutomatedReasoningPolicyTestResults$: () => ListAutomatedReasoningPolicyTestResults$,
- ListAutomatedReasoningPolicyTestCasesResponse$: () => ListAutomatedReasoningPolicyTestCasesResponse$,
- ListAutomatedReasoningPolicyTestCasesRequest$: () => ListAutomatedReasoningPolicyTestCasesRequest$,
- ListAutomatedReasoningPolicyTestCasesCommand: () => ListAutomatedReasoningPolicyTestCasesCommand,
- ListAutomatedReasoningPolicyTestCases$: () => ListAutomatedReasoningPolicyTestCases$,
- ListAutomatedReasoningPolicyBuildWorkflowsResponse$: () => ListAutomatedReasoningPolicyBuildWorkflowsResponse$,
- ListAutomatedReasoningPolicyBuildWorkflowsRequest$: () => ListAutomatedReasoningPolicyBuildWorkflowsRequest$,
- ListAutomatedReasoningPolicyBuildWorkflowsCommand: () => ListAutomatedReasoningPolicyBuildWorkflowsCommand,
- ListAutomatedReasoningPolicyBuildWorkflows$: () => ListAutomatedReasoningPolicyBuildWorkflows$,
- ListAutomatedReasoningPoliciesResponse$: () => ListAutomatedReasoningPoliciesResponse$,
- ListAutomatedReasoningPoliciesRequest$: () => ListAutomatedReasoningPoliciesRequest$,
- ListAutomatedReasoningPoliciesCommand: () => ListAutomatedReasoningPoliciesCommand,
- ListAutomatedReasoningPolicies$: () => ListAutomatedReasoningPolicies$,
- LegalTerm$: () => LegalTerm$,
- LambdaGraderConfig$: () => LambdaGraderConfig$,
- KnowledgeBaseVectorSearchConfiguration$: () => KnowledgeBaseVectorSearchConfiguration$,
- KnowledgeBaseRetrieveAndGenerateConfiguration$: () => KnowledgeBaseRetrieveAndGenerateConfiguration$,
- KnowledgeBaseRetrievalConfiguration$: () => KnowledgeBaseRetrievalConfiguration$,
- KnowledgeBaseConfig$: () => KnowledgeBaseConfig$,
- KbInferenceConfig$: () => KbInferenceConfig$,
- JobStatusDetails: () => JobStatusDetails,
- InvocationLogsConfig$: () => InvocationLogsConfig$,
- InvocationLogSource$: () => InvocationLogSource$,
- InternalServerException$: () => InternalServerException$,
- InternalServerException: () => InternalServerException,
- InputTags: () => InputTags,
- InferenceType: () => InferenceType,
- InferenceProfileType: () => InferenceProfileType,
- InferenceProfileSummary$: () => InferenceProfileSummary$,
- InferenceProfileStatus: () => InferenceProfileStatus,
- InferenceProfileModelSource$: () => InferenceProfileModelSource$,
- InferenceProfileModel$: () => InferenceProfileModel$,
- ImportedModelSummary$: () => ImportedModelSummary$,
- ImplicitFilterConfiguration$: () => ImplicitFilterConfiguration$,
- HumanWorkflowConfig$: () => HumanWorkflowConfig$,
- HumanEvaluationCustomMetric$: () => HumanEvaluationCustomMetric$,
- HumanEvaluationConfig$: () => HumanEvaluationConfig$,
- GuardrailWordPolicyConfig$: () => GuardrailWordPolicyConfig$,
- GuardrailWordPolicy$: () => GuardrailWordPolicy$,
- GuardrailWordConfig$: () => GuardrailWordConfig$,
- GuardrailWordAction: () => GuardrailWordAction2,
- GuardrailWord$: () => GuardrailWord$,
- GuardrailTopicsTierName: () => GuardrailTopicsTierName2,
- GuardrailTopicsTierConfig$: () => GuardrailTopicsTierConfig$,
- GuardrailTopicsTier$: () => GuardrailTopicsTier$,
- GuardrailTopicType: () => GuardrailTopicType,
- GuardrailTopicPolicyConfig$: () => GuardrailTopicPolicyConfig$,
- GuardrailTopicPolicy$: () => GuardrailTopicPolicy$,
- GuardrailTopicConfig$: () => GuardrailTopicConfig$,
- GuardrailTopicAction: () => GuardrailTopicAction2,
- GuardrailTopic$: () => GuardrailTopic$,
- GuardrailSummary$: () => GuardrailSummary$,
- GuardrailStatus: () => GuardrailStatus,
- GuardrailSensitiveInformationPolicyConfig$: () => GuardrailSensitiveInformationPolicyConfig$,
- GuardrailSensitiveInformationPolicy$: () => GuardrailSensitiveInformationPolicy$,
- GuardrailSensitiveInformationAction: () => GuardrailSensitiveInformationAction,
- GuardrailRegexConfig$: () => GuardrailRegexConfig$,
- GuardrailRegex$: () => GuardrailRegex$,
- GuardrailPiiEntityType: () => GuardrailPiiEntityType,
- GuardrailPiiEntityConfig$: () => GuardrailPiiEntityConfig$,
- GuardrailPiiEntity$: () => GuardrailPiiEntity$,
- GuardrailModality: () => GuardrailModality2,
- GuardrailManagedWordsType: () => GuardrailManagedWordsType,
- GuardrailManagedWordsConfig$: () => GuardrailManagedWordsConfig$,
- GuardrailManagedWords$: () => GuardrailManagedWords$,
- GuardrailFilterStrength: () => GuardrailFilterStrength,
- GuardrailCrossRegionDetails$: () => GuardrailCrossRegionDetails$,
- GuardrailCrossRegionConfig$: () => GuardrailCrossRegionConfig$,
- GuardrailContextualGroundingPolicyConfig$: () => GuardrailContextualGroundingPolicyConfig$,
- GuardrailContextualGroundingPolicy$: () => GuardrailContextualGroundingPolicy$,
- GuardrailContextualGroundingFilterType: () => GuardrailContextualGroundingFilterType,
- GuardrailContextualGroundingFilterConfig$: () => GuardrailContextualGroundingFilterConfig$,
- GuardrailContextualGroundingFilter$: () => GuardrailContextualGroundingFilter$,
- GuardrailContextualGroundingAction: () => GuardrailContextualGroundingAction2,
- GuardrailContentPolicyConfig$: () => GuardrailContentPolicyConfig$,
- GuardrailContentPolicy$: () => GuardrailContentPolicy$,
- GuardrailContentFiltersTierName: () => GuardrailContentFiltersTierName2,
- GuardrailContentFiltersTierConfig$: () => GuardrailContentFiltersTierConfig$,
- GuardrailContentFiltersTier$: () => GuardrailContentFiltersTier$,
- GuardrailContentFilterType: () => GuardrailContentFilterType,
- GuardrailContentFilterConfig$: () => GuardrailContentFilterConfig$,
- GuardrailContentFilterAction: () => GuardrailContentFilterAction2,
- GuardrailContentFilter$: () => GuardrailContentFilter$,
- GuardrailConfiguration$: () => GuardrailConfiguration$,
- GuardrailAutomatedReasoningPolicyConfig$: () => GuardrailAutomatedReasoningPolicyConfig$,
- GuardrailAutomatedReasoningPolicy$: () => GuardrailAutomatedReasoningPolicy$,
- GraderConfig$: () => GraderConfig$,
- GetUseCaseForModelAccessResponse$: () => GetUseCaseForModelAccessResponse$,
- GetUseCaseForModelAccessRequest$: () => GetUseCaseForModelAccessRequest$,
- GetUseCaseForModelAccessCommand: () => GetUseCaseForModelAccessCommand,
- GetUseCaseForModelAccess$: () => GetUseCaseForModelAccess$,
- GetProvisionedModelThroughputResponse$: () => GetProvisionedModelThroughputResponse$,
- GetProvisionedModelThroughputRequest$: () => GetProvisionedModelThroughputRequest$,
- GetProvisionedModelThroughputCommand: () => GetProvisionedModelThroughputCommand,
- GetProvisionedModelThroughput$: () => GetProvisionedModelThroughput$,
- GetPromptRouterResponse$: () => GetPromptRouterResponse$,
- GetPromptRouterRequest$: () => GetPromptRouterRequest$,
- GetPromptRouterCommand: () => GetPromptRouterCommand,
- GetPromptRouter$: () => GetPromptRouter$,
- GetModelInvocationLoggingConfigurationResponse$: () => GetModelInvocationLoggingConfigurationResponse$,
- GetModelInvocationLoggingConfigurationRequest$: () => GetModelInvocationLoggingConfigurationRequest$,
- GetModelInvocationLoggingConfigurationCommand: () => GetModelInvocationLoggingConfigurationCommand,
- GetModelInvocationLoggingConfiguration$: () => GetModelInvocationLoggingConfiguration$,
- GetModelInvocationJobResponse$: () => GetModelInvocationJobResponse$,
- GetModelInvocationJobRequest$: () => GetModelInvocationJobRequest$,
- GetModelInvocationJobCommand: () => GetModelInvocationJobCommand,
- GetModelInvocationJob$: () => GetModelInvocationJob$,
- GetModelImportJobResponse$: () => GetModelImportJobResponse$,
- GetModelImportJobRequest$: () => GetModelImportJobRequest$,
- GetModelImportJobCommand: () => GetModelImportJobCommand,
- GetModelImportJob$: () => GetModelImportJob$,
- GetModelCustomizationJobResponse$: () => GetModelCustomizationJobResponse$,
- GetModelCustomizationJobRequest$: () => GetModelCustomizationJobRequest$,
- GetModelCustomizationJobCommand: () => GetModelCustomizationJobCommand,
- GetModelCustomizationJob$: () => GetModelCustomizationJob$,
- GetModelCopyJobResponse$: () => GetModelCopyJobResponse$,
- GetModelCopyJobRequest$: () => GetModelCopyJobRequest$,
- GetModelCopyJobCommand: () => GetModelCopyJobCommand,
- GetModelCopyJob$: () => GetModelCopyJob$,
- GetMarketplaceModelEndpointResponse$: () => GetMarketplaceModelEndpointResponse$,
- GetMarketplaceModelEndpointRequest$: () => GetMarketplaceModelEndpointRequest$,
- GetMarketplaceModelEndpointCommand: () => GetMarketplaceModelEndpointCommand,
- GetMarketplaceModelEndpoint$: () => GetMarketplaceModelEndpoint$,
- GetInferenceProfileResponse$: () => GetInferenceProfileResponse$,
- GetInferenceProfileRequest$: () => GetInferenceProfileRequest$,
- GetInferenceProfileCommand: () => GetInferenceProfileCommand,
- GetInferenceProfile$: () => GetInferenceProfile$,
- GetImportedModelResponse$: () => GetImportedModelResponse$,
- GetImportedModelRequest$: () => GetImportedModelRequest$,
- GetImportedModelCommand: () => GetImportedModelCommand,
- GetImportedModel$: () => GetImportedModel$,
- GetGuardrailResponse$: () => GetGuardrailResponse$,
- GetGuardrailRequest$: () => GetGuardrailRequest$,
- GetGuardrailCommand: () => GetGuardrailCommand,
- GetGuardrail$: () => GetGuardrail$,
- GetFoundationModelResponse$: () => GetFoundationModelResponse$,
- GetFoundationModelRequest$: () => GetFoundationModelRequest$,
- GetFoundationModelCommand: () => GetFoundationModelCommand,
- GetFoundationModelAvailabilityResponse$: () => GetFoundationModelAvailabilityResponse$,
- GetFoundationModelAvailabilityRequest$: () => GetFoundationModelAvailabilityRequest$,
- GetFoundationModelAvailabilityCommand: () => GetFoundationModelAvailabilityCommand,
- GetFoundationModelAvailability$: () => GetFoundationModelAvailability$,
- GetFoundationModel$: () => GetFoundationModel$,
- GetEvaluationJobResponse$: () => GetEvaluationJobResponse$,
- GetEvaluationJobRequest$: () => GetEvaluationJobRequest$,
- GetEvaluationJobCommand: () => GetEvaluationJobCommand,
- GetEvaluationJob$: () => GetEvaluationJob$,
- GetCustomModelResponse$: () => GetCustomModelResponse$,
- GetCustomModelRequest$: () => GetCustomModelRequest$,
- GetCustomModelDeploymentResponse$: () => GetCustomModelDeploymentResponse$,
- GetCustomModelDeploymentRequest$: () => GetCustomModelDeploymentRequest$,
- GetCustomModelDeploymentCommand: () => GetCustomModelDeploymentCommand,
- GetCustomModelDeployment$: () => GetCustomModelDeployment$,
- GetCustomModelCommand: () => GetCustomModelCommand,
- GetCustomModel$: () => GetCustomModel$,
- GetAutomatedReasoningPolicyTestResultResponse$: () => GetAutomatedReasoningPolicyTestResultResponse$,
- GetAutomatedReasoningPolicyTestResultRequest$: () => GetAutomatedReasoningPolicyTestResultRequest$,
- GetAutomatedReasoningPolicyTestResultCommand: () => GetAutomatedReasoningPolicyTestResultCommand,
- GetAutomatedReasoningPolicyTestResult$: () => GetAutomatedReasoningPolicyTestResult$,
- GetAutomatedReasoningPolicyTestCaseResponse$: () => GetAutomatedReasoningPolicyTestCaseResponse$,
- GetAutomatedReasoningPolicyTestCaseRequest$: () => GetAutomatedReasoningPolicyTestCaseRequest$,
- GetAutomatedReasoningPolicyTestCaseCommand: () => GetAutomatedReasoningPolicyTestCaseCommand,
- GetAutomatedReasoningPolicyTestCase$: () => GetAutomatedReasoningPolicyTestCase$,
- GetAutomatedReasoningPolicyResponse$: () => GetAutomatedReasoningPolicyResponse$,
- GetAutomatedReasoningPolicyRequest$: () => GetAutomatedReasoningPolicyRequest$,
- GetAutomatedReasoningPolicyNextScenarioResponse$: () => GetAutomatedReasoningPolicyNextScenarioResponse$,
- GetAutomatedReasoningPolicyNextScenarioRequest$: () => GetAutomatedReasoningPolicyNextScenarioRequest$,
- GetAutomatedReasoningPolicyNextScenarioCommand: () => GetAutomatedReasoningPolicyNextScenarioCommand,
- GetAutomatedReasoningPolicyNextScenario$: () => GetAutomatedReasoningPolicyNextScenario$,
- GetAutomatedReasoningPolicyCommand: () => GetAutomatedReasoningPolicyCommand,
- GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse$: () => GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse$,
- GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest$: () => GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest$,
- GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand: () => GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand,
- GetAutomatedReasoningPolicyBuildWorkflowResultAssets$: () => GetAutomatedReasoningPolicyBuildWorkflowResultAssets$,
- GetAutomatedReasoningPolicyBuildWorkflowResponse$: () => GetAutomatedReasoningPolicyBuildWorkflowResponse$,
- GetAutomatedReasoningPolicyBuildWorkflowRequest$: () => GetAutomatedReasoningPolicyBuildWorkflowRequest$,
- GetAutomatedReasoningPolicyBuildWorkflowCommand: () => GetAutomatedReasoningPolicyBuildWorkflowCommand,
- GetAutomatedReasoningPolicyBuildWorkflow$: () => GetAutomatedReasoningPolicyBuildWorkflow$,
- GetAutomatedReasoningPolicyAnnotationsResponse$: () => GetAutomatedReasoningPolicyAnnotationsResponse$,
- GetAutomatedReasoningPolicyAnnotationsRequest$: () => GetAutomatedReasoningPolicyAnnotationsRequest$,
- GetAutomatedReasoningPolicyAnnotationsCommand: () => GetAutomatedReasoningPolicyAnnotationsCommand,
- GetAutomatedReasoningPolicyAnnotations$: () => GetAutomatedReasoningPolicyAnnotations$,
- GetAutomatedReasoningPolicy$: () => GetAutomatedReasoningPolicy$,
- GenerationConfiguration$: () => GenerationConfiguration$,
- FoundationModelSummary$: () => FoundationModelSummary$,
- FoundationModelLifecycleStatus: () => FoundationModelLifecycleStatus,
- FoundationModelLifecycle$: () => FoundationModelLifecycle$,
- FoundationModelDetails$: () => FoundationModelDetails$,
- FineTuningJobStatus: () => FineTuningJobStatus,
- FilterAttribute$: () => FilterAttribute$,
- FieldForReranking$: () => FieldForReranking$,
- ExternalSourcesRetrieveAndGenerateConfiguration$: () => ExternalSourcesRetrieveAndGenerateConfiguration$,
- ExternalSourcesGenerationConfiguration$: () => ExternalSourcesGenerationConfiguration$,
- ExternalSourceType: () => ExternalSourceType,
- ExternalSource$: () => ExternalSource$,
- ExportAutomatedReasoningPolicyVersionResponse$: () => ExportAutomatedReasoningPolicyVersionResponse$,
- ExportAutomatedReasoningPolicyVersionRequest$: () => ExportAutomatedReasoningPolicyVersionRequest$,
- ExportAutomatedReasoningPolicyVersionCommand: () => ExportAutomatedReasoningPolicyVersionCommand,
- ExportAutomatedReasoningPolicyVersion$: () => ExportAutomatedReasoningPolicyVersion$,
- EvaluatorModelConfig$: () => EvaluatorModelConfig$,
- EvaluationTaskType: () => EvaluationTaskType,
- EvaluationSummary$: () => EvaluationSummary$,
- EvaluationRagConfigSummary$: () => EvaluationRagConfigSummary$,
- EvaluationPrecomputedRetrieveSourceConfig$: () => EvaluationPrecomputedRetrieveSourceConfig$,
- EvaluationPrecomputedRetrieveAndGenerateSourceConfig$: () => EvaluationPrecomputedRetrieveAndGenerateSourceConfig$,
- EvaluationPrecomputedRagSourceConfig$: () => EvaluationPrecomputedRagSourceConfig$,
- EvaluationPrecomputedInferenceSource$: () => EvaluationPrecomputedInferenceSource$,
- EvaluationOutputDataConfig$: () => EvaluationOutputDataConfig$,
- EvaluationModelConfigSummary$: () => EvaluationModelConfigSummary$,
- EvaluationModelConfig$: () => EvaluationModelConfig$,
- EvaluationJobType: () => EvaluationJobType,
- EvaluationJobStatus: () => EvaluationJobStatus,
- EvaluationInferenceConfigSummary$: () => EvaluationInferenceConfigSummary$,
- EvaluationInferenceConfig$: () => EvaluationInferenceConfig$,
- EvaluationDatasetMetricConfig$: () => EvaluationDatasetMetricConfig$,
- EvaluationDatasetLocation$: () => EvaluationDatasetLocation$,
- EvaluationDataset$: () => EvaluationDataset$,
- EvaluationConfig$: () => EvaluationConfig$,
- EvaluationBedrockModel$: () => EvaluationBedrockModel$,
- EntitlementAvailability: () => EntitlementAvailability,
- EndpointConfig$: () => EndpointConfig$,
- DistillationConfig$: () => DistillationConfig$,
- DimensionalPriceRate$: () => DimensionalPriceRate$,
- DeregisterMarketplaceModelEndpointResponse$: () => DeregisterMarketplaceModelEndpointResponse$,
- DeregisterMarketplaceModelEndpointRequest$: () => DeregisterMarketplaceModelEndpointRequest$,
- DeregisterMarketplaceModelEndpointCommand: () => DeregisterMarketplaceModelEndpointCommand,
- DeregisterMarketplaceModelEndpoint$: () => DeregisterMarketplaceModelEndpoint$,
- DeleteProvisionedModelThroughputResponse$: () => DeleteProvisionedModelThroughputResponse$,
- DeleteProvisionedModelThroughputRequest$: () => DeleteProvisionedModelThroughputRequest$,
- DeleteProvisionedModelThroughputCommand: () => DeleteProvisionedModelThroughputCommand,
- DeleteProvisionedModelThroughput$: () => DeleteProvisionedModelThroughput$,
- DeletePromptRouterResponse$: () => DeletePromptRouterResponse$,
- DeletePromptRouterRequest$: () => DeletePromptRouterRequest$,
- DeletePromptRouterCommand: () => DeletePromptRouterCommand,
- DeletePromptRouter$: () => DeletePromptRouter$,
- DeleteModelInvocationLoggingConfigurationResponse$: () => DeleteModelInvocationLoggingConfigurationResponse$,
- DeleteModelInvocationLoggingConfigurationRequest$: () => DeleteModelInvocationLoggingConfigurationRequest$,
- DeleteModelInvocationLoggingConfigurationCommand: () => DeleteModelInvocationLoggingConfigurationCommand,
- DeleteModelInvocationLoggingConfiguration$: () => DeleteModelInvocationLoggingConfiguration$,
- DeleteMarketplaceModelEndpointResponse$: () => DeleteMarketplaceModelEndpointResponse$,
- DeleteMarketplaceModelEndpointRequest$: () => DeleteMarketplaceModelEndpointRequest$,
- DeleteMarketplaceModelEndpointCommand: () => DeleteMarketplaceModelEndpointCommand,
- DeleteMarketplaceModelEndpoint$: () => DeleteMarketplaceModelEndpoint$,
- DeleteInferenceProfileResponse$: () => DeleteInferenceProfileResponse$,
- DeleteInferenceProfileRequest$: () => DeleteInferenceProfileRequest$,
- DeleteInferenceProfileCommand: () => DeleteInferenceProfileCommand,
- DeleteInferenceProfile$: () => DeleteInferenceProfile$,
- DeleteImportedModelResponse$: () => DeleteImportedModelResponse$,
- DeleteImportedModelRequest$: () => DeleteImportedModelRequest$,
- DeleteImportedModelCommand: () => DeleteImportedModelCommand,
- DeleteImportedModel$: () => DeleteImportedModel$,
- DeleteGuardrailResponse$: () => DeleteGuardrailResponse$,
- DeleteGuardrailRequest$: () => DeleteGuardrailRequest$,
- DeleteGuardrailCommand: () => DeleteGuardrailCommand,
- DeleteGuardrail$: () => DeleteGuardrail$,
- DeleteFoundationModelAgreementResponse$: () => DeleteFoundationModelAgreementResponse$,
- DeleteFoundationModelAgreementRequest$: () => DeleteFoundationModelAgreementRequest$,
- DeleteFoundationModelAgreementCommand: () => DeleteFoundationModelAgreementCommand,
- DeleteFoundationModelAgreement$: () => DeleteFoundationModelAgreement$,
- DeleteEnforcedGuardrailConfigurationResponse$: () => DeleteEnforcedGuardrailConfigurationResponse$,
- DeleteEnforcedGuardrailConfigurationRequest$: () => DeleteEnforcedGuardrailConfigurationRequest$,
- DeleteEnforcedGuardrailConfigurationCommand: () => DeleteEnforcedGuardrailConfigurationCommand,
- DeleteEnforcedGuardrailConfiguration$: () => DeleteEnforcedGuardrailConfiguration$,
- DeleteCustomModelResponse$: () => DeleteCustomModelResponse$,
- DeleteCustomModelRequest$: () => DeleteCustomModelRequest$,
- DeleteCustomModelDeploymentResponse$: () => DeleteCustomModelDeploymentResponse$,
- DeleteCustomModelDeploymentRequest$: () => DeleteCustomModelDeploymentRequest$,
- DeleteCustomModelDeploymentCommand: () => DeleteCustomModelDeploymentCommand,
- DeleteCustomModelDeployment$: () => DeleteCustomModelDeployment$,
- DeleteCustomModelCommand: () => DeleteCustomModelCommand,
- DeleteCustomModel$: () => DeleteCustomModel$,
- DeleteAutomatedReasoningPolicyTestCaseResponse$: () => DeleteAutomatedReasoningPolicyTestCaseResponse$,
- DeleteAutomatedReasoningPolicyTestCaseRequest$: () => DeleteAutomatedReasoningPolicyTestCaseRequest$,
- DeleteAutomatedReasoningPolicyTestCaseCommand: () => DeleteAutomatedReasoningPolicyTestCaseCommand,
- DeleteAutomatedReasoningPolicyTestCase$: () => DeleteAutomatedReasoningPolicyTestCase$,
- DeleteAutomatedReasoningPolicyResponse$: () => DeleteAutomatedReasoningPolicyResponse$,
- DeleteAutomatedReasoningPolicyRequest$: () => DeleteAutomatedReasoningPolicyRequest$,
- DeleteAutomatedReasoningPolicyCommand: () => DeleteAutomatedReasoningPolicyCommand,
- DeleteAutomatedReasoningPolicyBuildWorkflowResponse$: () => DeleteAutomatedReasoningPolicyBuildWorkflowResponse$,
- DeleteAutomatedReasoningPolicyBuildWorkflowRequest$: () => DeleteAutomatedReasoningPolicyBuildWorkflowRequest$,
- DeleteAutomatedReasoningPolicyBuildWorkflowCommand: () => DeleteAutomatedReasoningPolicyBuildWorkflowCommand,
- DeleteAutomatedReasoningPolicyBuildWorkflow$: () => DeleteAutomatedReasoningPolicyBuildWorkflow$,
- DeleteAutomatedReasoningPolicy$: () => DeleteAutomatedReasoningPolicy$,
- DataProcessingDetails$: () => DataProcessingDetails$,
- CustomizationType: () => CustomizationType,
- CustomizationConfig$: () => CustomizationConfig$,
- CustomModelUnits$: () => CustomModelUnits$,
- CustomModelSummary$: () => CustomModelSummary$,
- CustomModelDeploymentUpdateStatus: () => CustomModelDeploymentUpdateStatus,
- CustomModelDeploymentUpdateDetails$: () => CustomModelDeploymentUpdateDetails$,
- CustomModelDeploymentSummary$: () => CustomModelDeploymentSummary$,
- CustomModelDeploymentStatus: () => CustomModelDeploymentStatus,
- CustomMetricEvaluatorModelConfig$: () => CustomMetricEvaluatorModelConfig$,
- CustomMetricDefinition$: () => CustomMetricDefinition$,
- CustomMetricBedrockEvaluatorModel$: () => CustomMetricBedrockEvaluatorModel$,
- CreateProvisionedModelThroughputResponse$: () => CreateProvisionedModelThroughputResponse$,
- CreateProvisionedModelThroughputRequest$: () => CreateProvisionedModelThroughputRequest$,
- CreateProvisionedModelThroughputCommand: () => CreateProvisionedModelThroughputCommand,
- CreateProvisionedModelThroughput$: () => CreateProvisionedModelThroughput$,
- CreatePromptRouterResponse$: () => CreatePromptRouterResponse$,
- CreatePromptRouterRequest$: () => CreatePromptRouterRequest$,
- CreatePromptRouterCommand: () => CreatePromptRouterCommand,
- CreatePromptRouter$: () => CreatePromptRouter$,
- CreateModelInvocationJobResponse$: () => CreateModelInvocationJobResponse$,
- CreateModelInvocationJobRequest$: () => CreateModelInvocationJobRequest$,
- CreateModelInvocationJobCommand: () => CreateModelInvocationJobCommand,
- CreateModelInvocationJob$: () => CreateModelInvocationJob$,
- CreateModelImportJobResponse$: () => CreateModelImportJobResponse$,
- CreateModelImportJobRequest$: () => CreateModelImportJobRequest$,
- CreateModelImportJobCommand: () => CreateModelImportJobCommand,
- CreateModelImportJob$: () => CreateModelImportJob$,
- CreateModelCustomizationJobResponse$: () => CreateModelCustomizationJobResponse$,
- CreateModelCustomizationJobRequest$: () => CreateModelCustomizationJobRequest$,
- CreateModelCustomizationJobCommand: () => CreateModelCustomizationJobCommand,
- CreateModelCustomizationJob$: () => CreateModelCustomizationJob$,
- CreateModelCopyJobResponse$: () => CreateModelCopyJobResponse$,
- CreateModelCopyJobRequest$: () => CreateModelCopyJobRequest$,
- CreateModelCopyJobCommand: () => CreateModelCopyJobCommand,
- CreateModelCopyJob$: () => CreateModelCopyJob$,
- CreateMarketplaceModelEndpointResponse$: () => CreateMarketplaceModelEndpointResponse$,
- CreateMarketplaceModelEndpointRequest$: () => CreateMarketplaceModelEndpointRequest$,
- CreateMarketplaceModelEndpointCommand: () => CreateMarketplaceModelEndpointCommand,
- CreateMarketplaceModelEndpoint$: () => CreateMarketplaceModelEndpoint$,
- CreateInferenceProfileResponse$: () => CreateInferenceProfileResponse$,
- CreateInferenceProfileRequest$: () => CreateInferenceProfileRequest$,
- CreateInferenceProfileCommand: () => CreateInferenceProfileCommand,
- CreateInferenceProfile$: () => CreateInferenceProfile$,
- CreateGuardrailVersionResponse$: () => CreateGuardrailVersionResponse$,
- CreateGuardrailVersionRequest$: () => CreateGuardrailVersionRequest$,
- CreateGuardrailVersionCommand: () => CreateGuardrailVersionCommand,
- CreateGuardrailVersion$: () => CreateGuardrailVersion$,
- CreateGuardrailResponse$: () => CreateGuardrailResponse$,
- CreateGuardrailRequest$: () => CreateGuardrailRequest$,
- CreateGuardrailCommand: () => CreateGuardrailCommand,
- CreateGuardrail$: () => CreateGuardrail$,
- CreateFoundationModelAgreementResponse$: () => CreateFoundationModelAgreementResponse$,
- CreateFoundationModelAgreementRequest$: () => CreateFoundationModelAgreementRequest$,
- CreateFoundationModelAgreementCommand: () => CreateFoundationModelAgreementCommand,
- CreateFoundationModelAgreement$: () => CreateFoundationModelAgreement$,
- CreateEvaluationJobResponse$: () => CreateEvaluationJobResponse$,
- CreateEvaluationJobRequest$: () => CreateEvaluationJobRequest$,
- CreateEvaluationJobCommand: () => CreateEvaluationJobCommand,
- CreateEvaluationJob$: () => CreateEvaluationJob$,
- CreateCustomModelResponse$: () => CreateCustomModelResponse$,
- CreateCustomModelRequest$: () => CreateCustomModelRequest$,
- CreateCustomModelDeploymentResponse$: () => CreateCustomModelDeploymentResponse$,
- CreateCustomModelDeploymentRequest$: () => CreateCustomModelDeploymentRequest$,
- CreateCustomModelDeploymentCommand: () => CreateCustomModelDeploymentCommand,
- CreateCustomModelDeployment$: () => CreateCustomModelDeployment$,
- CreateCustomModelCommand: () => CreateCustomModelCommand,
- CreateCustomModel$: () => CreateCustomModel$,
- CreateAutomatedReasoningPolicyVersionResponse$: () => CreateAutomatedReasoningPolicyVersionResponse$,
- CreateAutomatedReasoningPolicyVersionRequest$: () => CreateAutomatedReasoningPolicyVersionRequest$,
- CreateAutomatedReasoningPolicyVersionCommand: () => CreateAutomatedReasoningPolicyVersionCommand,
- CreateAutomatedReasoningPolicyVersion$: () => CreateAutomatedReasoningPolicyVersion$,
- CreateAutomatedReasoningPolicyTestCaseResponse$: () => CreateAutomatedReasoningPolicyTestCaseResponse$,
- CreateAutomatedReasoningPolicyTestCaseRequest$: () => CreateAutomatedReasoningPolicyTestCaseRequest$,
- CreateAutomatedReasoningPolicyTestCaseCommand: () => CreateAutomatedReasoningPolicyTestCaseCommand,
- CreateAutomatedReasoningPolicyTestCase$: () => CreateAutomatedReasoningPolicyTestCase$,
- CreateAutomatedReasoningPolicyResponse$: () => CreateAutomatedReasoningPolicyResponse$,
- CreateAutomatedReasoningPolicyRequest$: () => CreateAutomatedReasoningPolicyRequest$,
- CreateAutomatedReasoningPolicyCommand: () => CreateAutomatedReasoningPolicyCommand,
- CreateAutomatedReasoningPolicy$: () => CreateAutomatedReasoningPolicy$,
- ConflictException$: () => ConflictException$,
- ConflictException: () => ConflictException,
- ConfigurationOwner: () => ConfigurationOwner,
- CommitmentDuration: () => CommitmentDuration,
- CloudWatchConfig$: () => CloudWatchConfig$,
- CancelAutomatedReasoningPolicyBuildWorkflowResponse$: () => CancelAutomatedReasoningPolicyBuildWorkflowResponse$,
- CancelAutomatedReasoningPolicyBuildWorkflowRequest$: () => CancelAutomatedReasoningPolicyBuildWorkflowRequest$,
- CancelAutomatedReasoningPolicyBuildWorkflowCommand: () => CancelAutomatedReasoningPolicyBuildWorkflowCommand,
- CancelAutomatedReasoningPolicyBuildWorkflow$: () => CancelAutomatedReasoningPolicyBuildWorkflow$,
- ByteContentDoc$: () => ByteContentDoc$,
- BedrockServiceException$: () => BedrockServiceException$,
- BedrockServiceException: () => BedrockServiceException,
- BedrockEvaluatorModel$: () => BedrockEvaluatorModel$,
- BedrockClient: () => BedrockClient,
- Bedrock: () => Bedrock,
- BatchDeleteEvaluationJobResponse$: () => BatchDeleteEvaluationJobResponse$,
- BatchDeleteEvaluationJobRequest$: () => BatchDeleteEvaluationJobRequest$,
- BatchDeleteEvaluationJobItem$: () => BatchDeleteEvaluationJobItem$,
- BatchDeleteEvaluationJobError$: () => BatchDeleteEvaluationJobError$,
- BatchDeleteEvaluationJobCommand: () => BatchDeleteEvaluationJobCommand,
- BatchDeleteEvaluationJob$: () => BatchDeleteEvaluationJob$,
- AutomatedReasoningPolicyWorkflowTypeContent$: () => AutomatedReasoningPolicyWorkflowTypeContent$,
- AutomatedReasoningPolicyVariableReport$: () => AutomatedReasoningPolicyVariableReport$,
- AutomatedReasoningPolicyUpdateVariableMutation$: () => AutomatedReasoningPolicyUpdateVariableMutation$,
- AutomatedReasoningPolicyUpdateVariableAnnotation$: () => AutomatedReasoningPolicyUpdateVariableAnnotation$,
- AutomatedReasoningPolicyUpdateTypeValue$: () => AutomatedReasoningPolicyUpdateTypeValue$,
- AutomatedReasoningPolicyUpdateTypeMutation$: () => AutomatedReasoningPolicyUpdateTypeMutation$,
- AutomatedReasoningPolicyUpdateTypeAnnotation$: () => AutomatedReasoningPolicyUpdateTypeAnnotation$,
- AutomatedReasoningPolicyUpdateRuleMutation$: () => AutomatedReasoningPolicyUpdateRuleMutation$,
- AutomatedReasoningPolicyUpdateRuleAnnotation$: () => AutomatedReasoningPolicyUpdateRuleAnnotation$,
- AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation$: () => AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation$,
- AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation$: () => AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation$,
- AutomatedReasoningPolicyTypeValueAnnotation$: () => AutomatedReasoningPolicyTypeValueAnnotation$,
- AutomatedReasoningPolicyTestRunStatus: () => AutomatedReasoningPolicyTestRunStatus,
- AutomatedReasoningPolicyTestRunResult: () => AutomatedReasoningPolicyTestRunResult,
- AutomatedReasoningPolicyTestResult$: () => AutomatedReasoningPolicyTestResult$,
- AutomatedReasoningPolicyTestCase$: () => AutomatedReasoningPolicyTestCase$,
- AutomatedReasoningPolicySummary$: () => AutomatedReasoningPolicySummary$,
- AutomatedReasoningPolicyStatementReference$: () => AutomatedReasoningPolicyStatementReference$,
- AutomatedReasoningPolicyStatementLocation$: () => AutomatedReasoningPolicyStatementLocation$,
- AutomatedReasoningPolicySourceDocument$: () => AutomatedReasoningPolicySourceDocument$,
- AutomatedReasoningPolicyScenarios$: () => AutomatedReasoningPolicyScenarios$,
- AutomatedReasoningPolicyScenario$: () => AutomatedReasoningPolicyScenario$,
- AutomatedReasoningPolicyRuleReport$: () => AutomatedReasoningPolicyRuleReport$,
- AutomatedReasoningPolicyReportSourceDocument$: () => AutomatedReasoningPolicyReportSourceDocument$,
- AutomatedReasoningPolicyPlanning$: () => AutomatedReasoningPolicyPlanning$,
- AutomatedReasoningPolicyMutation$: () => AutomatedReasoningPolicyMutation$,
- AutomatedReasoningPolicyIngestContentAnnotation$: () => AutomatedReasoningPolicyIngestContentAnnotation$,
- AutomatedReasoningPolicyGeneratedTestCases$: () => AutomatedReasoningPolicyGeneratedTestCases$,
- AutomatedReasoningPolicyGeneratedTestCase$: () => AutomatedReasoningPolicyGeneratedTestCase$,
- AutomatedReasoningPolicyGenerateFidelityReportContent$: () => AutomatedReasoningPolicyGenerateFidelityReportContent$,
- AutomatedReasoningPolicyFidelityReport$: () => AutomatedReasoningPolicyFidelityReport$,
- AutomatedReasoningPolicyDisjointRuleSet$: () => AutomatedReasoningPolicyDisjointRuleSet$,
- AutomatedReasoningPolicyDeleteVariableMutation$: () => AutomatedReasoningPolicyDeleteVariableMutation$,
- AutomatedReasoningPolicyDeleteVariableAnnotation$: () => AutomatedReasoningPolicyDeleteVariableAnnotation$,
- AutomatedReasoningPolicyDeleteTypeValue$: () => AutomatedReasoningPolicyDeleteTypeValue$,
- AutomatedReasoningPolicyDeleteTypeMutation$: () => AutomatedReasoningPolicyDeleteTypeMutation$,
- AutomatedReasoningPolicyDeleteTypeAnnotation$: () => AutomatedReasoningPolicyDeleteTypeAnnotation$,
- AutomatedReasoningPolicyDeleteRuleMutation$: () => AutomatedReasoningPolicyDeleteRuleMutation$,
- AutomatedReasoningPolicyDeleteRuleAnnotation$: () => AutomatedReasoningPolicyDeleteRuleAnnotation$,
- AutomatedReasoningPolicyDefinitionVariable$: () => AutomatedReasoningPolicyDefinitionVariable$,
- AutomatedReasoningPolicyDefinitionTypeValuePair$: () => AutomatedReasoningPolicyDefinitionTypeValuePair$,
- AutomatedReasoningPolicyDefinitionTypeValue$: () => AutomatedReasoningPolicyDefinitionTypeValue$,
- AutomatedReasoningPolicyDefinitionType$: () => AutomatedReasoningPolicyDefinitionType$,
- AutomatedReasoningPolicyDefinitionRule$: () => AutomatedReasoningPolicyDefinitionRule$,
- AutomatedReasoningPolicyDefinitionQualityReport$: () => AutomatedReasoningPolicyDefinitionQualityReport$,
- AutomatedReasoningPolicyDefinitionElement$: () => AutomatedReasoningPolicyDefinitionElement$,
- AutomatedReasoningPolicyDefinition$: () => AutomatedReasoningPolicyDefinition$,
- AutomatedReasoningPolicyBuildWorkflowType: () => AutomatedReasoningPolicyBuildWorkflowType,
- AutomatedReasoningPolicyBuildWorkflowSummary$: () => AutomatedReasoningPolicyBuildWorkflowSummary$,
- AutomatedReasoningPolicyBuildWorkflowStatus: () => AutomatedReasoningPolicyBuildWorkflowStatus,
- AutomatedReasoningPolicyBuildWorkflowSource$: () => AutomatedReasoningPolicyBuildWorkflowSource$,
- AutomatedReasoningPolicyBuildWorkflowRepairContent$: () => AutomatedReasoningPolicyBuildWorkflowRepairContent$,
- AutomatedReasoningPolicyBuildWorkflowDocument$: () => AutomatedReasoningPolicyBuildWorkflowDocument$,
- AutomatedReasoningPolicyBuildStepMessage$: () => AutomatedReasoningPolicyBuildStepMessage$,
- AutomatedReasoningPolicyBuildStepContext$: () => AutomatedReasoningPolicyBuildStepContext$,
- AutomatedReasoningPolicyBuildStep$: () => AutomatedReasoningPolicyBuildStep$,
- AutomatedReasoningPolicyBuildResultAssets$: () => AutomatedReasoningPolicyBuildResultAssets$,
- AutomatedReasoningPolicyBuildResultAssetType: () => AutomatedReasoningPolicyBuildResultAssetType,
- AutomatedReasoningPolicyBuildResultAssetManifestEntry$: () => AutomatedReasoningPolicyBuildResultAssetManifestEntry$,
- AutomatedReasoningPolicyBuildResultAssetManifest$: () => AutomatedReasoningPolicyBuildResultAssetManifest$,
- AutomatedReasoningPolicyBuildMessageType: () => AutomatedReasoningPolicyBuildMessageType,
- AutomatedReasoningPolicyBuildLogEntry$: () => AutomatedReasoningPolicyBuildLogEntry$,
- AutomatedReasoningPolicyBuildLog$: () => AutomatedReasoningPolicyBuildLog$,
- AutomatedReasoningPolicyBuildDocumentContentType: () => AutomatedReasoningPolicyBuildDocumentContentType,
- AutomatedReasoningPolicyAtomicStatement$: () => AutomatedReasoningPolicyAtomicStatement$,
- AutomatedReasoningPolicyAnnotationStatus: () => AutomatedReasoningPolicyAnnotationStatus,
- AutomatedReasoningPolicyAnnotation$: () => AutomatedReasoningPolicyAnnotation$,
- AutomatedReasoningPolicyAnnotatedLine$: () => AutomatedReasoningPolicyAnnotatedLine$,
- AutomatedReasoningPolicyAnnotatedContent$: () => AutomatedReasoningPolicyAnnotatedContent$,
- AutomatedReasoningPolicyAnnotatedChunk$: () => AutomatedReasoningPolicyAnnotatedChunk$,
- AutomatedReasoningPolicyAddVariableMutation$: () => AutomatedReasoningPolicyAddVariableMutation$,
- AutomatedReasoningPolicyAddVariableAnnotation$: () => AutomatedReasoningPolicyAddVariableAnnotation$,
- AutomatedReasoningPolicyAddTypeValue$: () => AutomatedReasoningPolicyAddTypeValue$,
- AutomatedReasoningPolicyAddTypeMutation$: () => AutomatedReasoningPolicyAddTypeMutation$,
- AutomatedReasoningPolicyAddTypeAnnotation$: () => AutomatedReasoningPolicyAddTypeAnnotation$,
- AutomatedReasoningPolicyAddRuleMutation$: () => AutomatedReasoningPolicyAddRuleMutation$,
- AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation$: () => AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation$,
- AutomatedReasoningPolicyAddRuleAnnotation$: () => AutomatedReasoningPolicyAddRuleAnnotation$,
- AutomatedReasoningLogicStatement$: () => AutomatedReasoningLogicStatement$,
- AutomatedReasoningCheckValidFinding$: () => AutomatedReasoningCheckValidFinding$,
- AutomatedReasoningCheckTranslationOption$: () => AutomatedReasoningCheckTranslationOption$,
- AutomatedReasoningCheckTranslationAmbiguousFinding$: () => AutomatedReasoningCheckTranslationAmbiguousFinding$,
- AutomatedReasoningCheckTranslation$: () => AutomatedReasoningCheckTranslation$,
- AutomatedReasoningCheckTooComplexFinding$: () => AutomatedReasoningCheckTooComplexFinding$,
- AutomatedReasoningCheckScenario$: () => AutomatedReasoningCheckScenario$,
- AutomatedReasoningCheckSatisfiableFinding$: () => AutomatedReasoningCheckSatisfiableFinding$,
- AutomatedReasoningCheckRule$: () => AutomatedReasoningCheckRule$,
- AutomatedReasoningCheckResult: () => AutomatedReasoningCheckResult,
- AutomatedReasoningCheckNoTranslationsFinding$: () => AutomatedReasoningCheckNoTranslationsFinding$,
- AutomatedReasoningCheckLogicWarningType: () => AutomatedReasoningCheckLogicWarningType,
- AutomatedReasoningCheckLogicWarning$: () => AutomatedReasoningCheckLogicWarning$,
- AutomatedReasoningCheckInvalidFinding$: () => AutomatedReasoningCheckInvalidFinding$,
- AutomatedReasoningCheckInputTextReference$: () => AutomatedReasoningCheckInputTextReference$,
- AutomatedReasoningCheckImpossibleFinding$: () => AutomatedReasoningCheckImpossibleFinding$,
- AutomatedReasoningCheckFinding$: () => AutomatedReasoningCheckFinding$,
- AutomatedEvaluationCustomMetricSource$: () => AutomatedEvaluationCustomMetricSource$,
- AutomatedEvaluationCustomMetricConfig$: () => AutomatedEvaluationCustomMetricConfig$,
- AutomatedEvaluationConfig$: () => AutomatedEvaluationConfig$,
- AuthorizationStatus: () => AuthorizationStatus,
- AttributeType: () => AttributeType,
- ApplicationType: () => ApplicationType,
- AgreementStatus: () => AgreementStatus,
- AgreementAvailability$: () => AgreementAvailability$,
- AccountEnforcedGuardrailOutputConfiguration$: () => AccountEnforcedGuardrailOutputConfiguration$,
- AccountEnforcedGuardrailInferenceInputConfiguration$: () => AccountEnforcedGuardrailInferenceInputConfiguration$,
- AccessDeniedException$: () => AccessDeniedException$,
- AccessDeniedException: () => AccessDeniedException,
- $Command: () => Command3
-});
-var init_dist_es20 = __esm(() => {
- init_BedrockServiceException();
- init_BedrockClient();
- init_Bedrock();
- init_commands();
- init_schemas_0();
- init_pagination4();
- init_enums();
- init_errors4();
- init_models_0();
- init_models_1();
-});
-
-// node_modules/@aws-sdk/middleware-eventstream/dist-es/eventStreamConfiguration.js
-function resolveEventStreamConfig(input) {
- const eventSigner = input.signer;
- const messageSigner = input.signer;
- const newInput = Object.assign(input, {
- eventSigner,
- messageSigner
- });
- const eventStreamPayloadHandler = newInput.eventStreamPayloadHandlerProvider(newInput);
- return Object.assign(newInput, {
- eventStreamPayloadHandler
- });
-}
-
-// node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
-var init_extensions8 = () => {};
-
-// node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-es/Field.js
-var init_Field4 = () => {};
-
-// node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
-var init_httpHandler4 = () => {};
-
-// node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
-class HttpRequest3 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest3({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery3(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest3.clone(this);
- }
-}
-function cloneQuery3(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
-}
-
-// node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-es/types.js
-var init_types9 = () => {};
-
-// node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-es/index.js
-var init_dist_es21 = __esm(() => {
- init_extensions8();
- init_Field4();
- init_httpHandler4();
- init_types9();
-});
-
-// node_modules/@aws-sdk/middleware-eventstream/dist-es/eventStreamHandlingMiddleware.js
-var eventStreamHandlingMiddleware = (options2) => (next, context) => async (args) => {
- const { request: request2 } = args;
- if (!HttpRequest3.isInstance(request2))
- return next(args);
- return options2.eventStreamPayloadHandler.handle(next, args, context);
-}, eventStreamHandlingMiddlewareOptions;
-var init_eventStreamHandlingMiddleware = __esm(() => {
- init_dist_es21();
- eventStreamHandlingMiddlewareOptions = {
- tags: ["EVENT_STREAM", "SIGNATURE", "HANDLE"],
- name: "eventStreamHandlingMiddleware",
- relation: "after",
- toMiddleware: "awsAuthMiddleware",
- override: true
- };
-});
-
-// node_modules/@aws-sdk/middleware-eventstream/dist-es/eventStreamHeaderMiddleware.js
-var eventStreamHeaderMiddleware = (next) => async (args) => {
- const { request: request2 } = args;
- if (!HttpRequest3.isInstance(request2))
- return next(args);
- request2.headers = {
- ...request2.headers,
- "content-type": "application/vnd.amazon.eventstream",
- "x-amz-content-sha256": "STREAMING-AWS4-HMAC-SHA256-EVENTS"
- };
- return next({
- ...args,
- request: request2
- });
-}, eventStreamHeaderMiddlewareOptions;
-var init_eventStreamHeaderMiddleware = __esm(() => {
- init_dist_es21();
- eventStreamHeaderMiddlewareOptions = {
- step: "build",
- tags: ["EVENT_STREAM", "HEADER", "CONTENT_TYPE", "CONTENT_SHA256"],
- name: "eventStreamHeaderMiddleware",
- override: true
- };
-});
-
-// node_modules/@aws-sdk/middleware-eventstream/dist-es/getEventStreamPlugin.js
-var getEventStreamPlugin = (options2) => ({
- applyToStack: (clientStack) => {
- clientStack.addRelativeTo(eventStreamHandlingMiddleware(options2), eventStreamHandlingMiddlewareOptions);
- clientStack.add(eventStreamHeaderMiddleware, eventStreamHeaderMiddlewareOptions);
- }
-});
-var init_getEventStreamPlugin = __esm(() => {
- init_eventStreamHandlingMiddleware();
- init_eventStreamHeaderMiddleware();
-});
-
-// node_modules/@aws-sdk/middleware-eventstream/dist-es/index.js
-var init_dist_es22 = __esm(() => {
- init_eventStreamHandlingMiddleware();
- init_eventStreamHeaderMiddleware();
- init_getEventStreamPlugin();
-});
-
-// node_modules/tslib/modules/index.js
-var import_tslib, __extends, __assign, __rest, __decorate, __param, __esDecorate, __runInitializers, __propKey, __setFunctionName, __metadata, __awaiter, __generator, __exportStar, __createBinding, __values, __read, __spread, __spreadArrays, __spreadArray, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault, __classPrivateFieldGet5, __classPrivateFieldSet5, __classPrivateFieldIn, __addDisposableResource, __disposeResources, __rewriteRelativeImportExtension;
-var init_modules = __esm(() => {
- import_tslib = __toESM(require_tslib(), 1);
- ({
- __extends,
- __assign,
- __rest,
- __decorate,
- __param,
- __esDecorate,
- __runInitializers,
- __propKey,
- __setFunctionName,
- __metadata,
- __awaiter,
- __generator,
- __exportStar,
- __createBinding,
- __values,
- __read,
- __spread,
- __spreadArrays,
- __spreadArray,
- __await,
- __asyncGenerator,
- __asyncDelegator,
- __asyncValues,
- __makeTemplateObject,
- __importStar,
- __importDefault,
- __classPrivateFieldGet: __classPrivateFieldGet5,
- __classPrivateFieldSet: __classPrivateFieldSet5,
- __classPrivateFieldIn,
- __addDisposableResource,
- __disposeResources,
- __rewriteRelativeImportExtension
- } = import_tslib.default);
-});
-
-// node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-es/index.js
-var isArrayBuffer4 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
-
-// node_modules/@smithy/util-buffer-from/dist-es/index.js
-import { Buffer as Buffer9 } from "buffer";
-var fromArrayBuffer2 = (input, offset = 0, length = input.byteLength - offset) => {
- if (!isArrayBuffer4(input)) {
- throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
- }
- return Buffer9.from(input, offset, length);
-}, fromString2 = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? Buffer9.from(input, encoding) : Buffer9.from(input);
-};
-var init_dist_es23 = () => {};
-
-// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js
-var fromUtf83 = (input) => {
- const buf = fromString2(input, "utf8");
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
-};
-var init_fromUtf8 = __esm(() => {
- init_dist_es23();
-});
-
-// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
-var init_toUint8Array = __esm(() => {
- init_fromUtf8();
-});
-
-// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/toUtf8.js
-var init_toUtf8 = __esm(() => {
- init_dist_es23();
-});
-
-// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/index.js
-var init_dist_es24 = __esm(() => {
- init_fromUtf8();
- init_toUint8Array();
- init_toUtf8();
-});
-
-// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/module/convertToBuffer.js
-function convertToBuffer(data) {
- if (data instanceof Uint8Array)
- return data;
- if (typeof data === "string") {
- return fromUtf85(data);
- }
- if (ArrayBuffer.isView(data)) {
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
- }
- return new Uint8Array(data);
-}
-var fromUtf85;
-var init_convertToBuffer = __esm(() => {
- init_dist_es24();
- fromUtf85 = typeof Buffer !== "undefined" && Buffer.from ? function(input) {
- return Buffer.from(input, "utf8");
- } : fromUtf83;
-});
-
-// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/module/isEmptyData.js
-function isEmptyData(data) {
- if (typeof data === "string") {
- return data.length === 0;
- }
- return data.byteLength === 0;
-}
-
-// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/module/numToUint8.js
-function numToUint8(num) {
- return new Uint8Array([
- (num & 4278190080) >> 24,
- (num & 16711680) >> 16,
- (num & 65280) >> 8,
- num & 255
- ]);
-}
-
-// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/module/uint32ArrayFrom.js
-function uint32ArrayFrom(a_lookUpTable) {
- if (!Uint32Array.from) {
- var return_array = new Uint32Array(a_lookUpTable.length);
- var a_index = 0;
- while (a_index < a_lookUpTable.length) {
- return_array[a_index] = a_lookUpTable[a_index];
- a_index += 1;
- }
- return return_array;
- }
- return Uint32Array.from(a_lookUpTable);
-}
-
-// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/module/index.js
-var init_module = __esm(() => {
- init_convertToBuffer();
-});
-
-// node_modules/@aws-crypto/crc32/build/module/aws_crc32.js
-var AwsCrc32;
-var init_aws_crc32 = __esm(() => {
- init_modules();
- init_module();
- init_module2();
- AwsCrc32 = function() {
- function AwsCrc322() {
- this.crc32 = new Crc32;
- }
- AwsCrc322.prototype.update = function(toHash) {
- if (isEmptyData(toHash))
- return;
- this.crc32.update(convertToBuffer(toHash));
- };
- AwsCrc322.prototype.digest = function() {
- return __awaiter(this, undefined, undefined, function() {
- return __generator(this, function(_a3) {
- return [2, numToUint8(this.crc32.digest())];
- });
- });
- };
- AwsCrc322.prototype.reset = function() {
- this.crc32 = new Crc32;
- };
- return AwsCrc322;
- }();
-});
-
-// node_modules/@aws-crypto/crc32/build/module/index.js
-var Crc32, a_lookUpTable, lookupTable;
-var init_module2 = __esm(() => {
- init_modules();
- init_module();
- init_aws_crc32();
- Crc32 = function() {
- function Crc322() {
- this.checksum = 4294967295;
- }
- Crc322.prototype.update = function(data) {
- var e_1, _a3;
- try {
- for (var data_1 = __values(data), data_1_1 = data_1.next();!data_1_1.done; data_1_1 = data_1.next()) {
- var byte = data_1_1.value;
- this.checksum = this.checksum >>> 8 ^ lookupTable[(this.checksum ^ byte) & 255];
- }
- } catch (e_1_1) {
- e_1 = { error: e_1_1 };
- } finally {
- try {
- if (data_1_1 && !data_1_1.done && (_a3 = data_1.return))
- _a3.call(data_1);
- } finally {
- if (e_1)
- throw e_1.error;
- }
- }
- return this;
- };
- Crc322.prototype.digest = function() {
- return (this.checksum ^ 4294967295) >>> 0;
- };
- return Crc322;
- }();
- a_lookUpTable = [
- 0,
- 1996959894,
- 3993919788,
- 2567524794,
- 124634137,
- 1886057615,
- 3915621685,
- 2657392035,
- 249268274,
- 2044508324,
- 3772115230,
- 2547177864,
- 162941995,
- 2125561021,
- 3887607047,
- 2428444049,
- 498536548,
- 1789927666,
- 4089016648,
- 2227061214,
- 450548861,
- 1843258603,
- 4107580753,
- 2211677639,
- 325883990,
- 1684777152,
- 4251122042,
- 2321926636,
- 335633487,
- 1661365465,
- 4195302755,
- 2366115317,
- 997073096,
- 1281953886,
- 3579855332,
- 2724688242,
- 1006888145,
- 1258607687,
- 3524101629,
- 2768942443,
- 901097722,
- 1119000684,
- 3686517206,
- 2898065728,
- 853044451,
- 1172266101,
- 3705015759,
- 2882616665,
- 651767980,
- 1373503546,
- 3369554304,
- 3218104598,
- 565507253,
- 1454621731,
- 3485111705,
- 3099436303,
- 671266974,
- 1594198024,
- 3322730930,
- 2970347812,
- 795835527,
- 1483230225,
- 3244367275,
- 3060149565,
- 1994146192,
- 31158534,
- 2563907772,
- 4023717930,
- 1907459465,
- 112637215,
- 2680153253,
- 3904427059,
- 2013776290,
- 251722036,
- 2517215374,
- 3775830040,
- 2137656763,
- 141376813,
- 2439277719,
- 3865271297,
- 1802195444,
- 476864866,
- 2238001368,
- 4066508878,
- 1812370925,
- 453092731,
- 2181625025,
- 4111451223,
- 1706088902,
- 314042704,
- 2344532202,
- 4240017532,
- 1658658271,
- 366619977,
- 2362670323,
- 4224994405,
- 1303535960,
- 984961486,
- 2747007092,
- 3569037538,
- 1256170817,
- 1037604311,
- 2765210733,
- 3554079995,
- 1131014506,
- 879679996,
- 2909243462,
- 3663771856,
- 1141124467,
- 855842277,
- 2852801631,
- 3708648649,
- 1342533948,
- 654459306,
- 3188396048,
- 3373015174,
- 1466479909,
- 544179635,
- 3110523913,
- 3462522015,
- 1591671054,
- 702138776,
- 2966460450,
- 3352799412,
- 1504918807,
- 783551873,
- 3082640443,
- 3233442989,
- 3988292384,
- 2596254646,
- 62317068,
- 1957810842,
- 3939845945,
- 2647816111,
- 81470997,
- 1943803523,
- 3814918930,
- 2489596804,
- 225274430,
- 2053790376,
- 3826175755,
- 2466906013,
- 167816743,
- 2097651377,
- 4027552580,
- 2265490386,
- 503444072,
- 1762050814,
- 4150417245,
- 2154129355,
- 426522225,
- 1852507879,
- 4275313526,
- 2312317920,
- 282753626,
- 1742555852,
- 4189708143,
- 2394877945,
- 397917763,
- 1622183637,
- 3604390888,
- 2714866558,
- 953729732,
- 1340076626,
- 3518719985,
- 2797360999,
- 1068828381,
- 1219638859,
- 3624741850,
- 2936675148,
- 906185462,
- 1090812512,
- 3747672003,
- 2825379669,
- 829329135,
- 1181335161,
- 3412177804,
- 3160834842,
- 628085408,
- 1382605366,
- 3423369109,
- 3138078467,
- 570562233,
- 1426400815,
- 3317316542,
- 2998733608,
- 733239954,
- 1555261956,
- 3268935591,
- 3050360625,
- 752459403,
- 1541320221,
- 2607071920,
- 3965973030,
- 1969922972,
- 40735498,
- 2617837225,
- 3943577151,
- 1913087877,
- 83908371,
- 2512341634,
- 3803740692,
- 2075208622,
- 213261112,
- 2463272603,
- 3855990285,
- 2094854071,
- 198958881,
- 2262029012,
- 4057260610,
- 1759359992,
- 534414190,
- 2176718541,
- 4139329115,
- 1873836001,
- 414664567,
- 2282248934,
- 4279200368,
- 1711684554,
- 285281116,
- 2405801727,
- 4167216745,
- 1634467795,
- 376229701,
- 2685067896,
- 3608007406,
- 1308918612,
- 956543938,
- 2808555105,
- 3495958263,
- 1231636301,
- 1047427035,
- 2932959818,
- 3654703836,
- 1088359270,
- 936918000,
- 2847714899,
- 3736837829,
- 1202900863,
- 817233897,
- 3183342108,
- 3401237130,
- 1404277552,
- 615818150,
- 3134207493,
- 3453421203,
- 1423857449,
- 601450431,
- 3009837614,
- 3294710456,
- 1567103746,
- 711928724,
- 3020668471,
- 3272380065,
- 1510334235,
- 755167117
- ];
- lookupTable = uint32ArrayFrom(a_lookUpTable);
-});
-
-// node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-es/index.js
-function fromHex(encoded) {
- if (encoded.length % 2 !== 0) {
- throw new Error("Hex encoded strings must have an even number length");
- }
- const out = new Uint8Array(encoded.length / 2);
- for (let i3 = 0;i3 < encoded.length; i3 += 2) {
- const encodedByte = encoded.slice(i3, i3 + 2).toLowerCase();
- if (encodedByte in HEX_TO_SHORT) {
- out[i3 / 2] = HEX_TO_SHORT[encodedByte];
- } else {
- throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
- }
- }
- return out;
-}
-function toHex(bytes) {
- let out = "";
- for (let i3 = 0;i3 < bytes.byteLength; i3++) {
- out += SHORT_TO_HEX[bytes[i3]];
- }
- return out;
-}
-var SHORT_TO_HEX, HEX_TO_SHORT;
-var init_dist_es25 = __esm(() => {
- SHORT_TO_HEX = {};
- HEX_TO_SHORT = {};
- for (let i3 = 0;i3 < 256; i3++) {
- let encodedByte = i3.toString(16).toLowerCase();
- if (encodedByte.length === 1) {
- encodedByte = `0${encodedByte}`;
- }
- SHORT_TO_HEX[i3] = encodedByte;
- HEX_TO_SHORT[encodedByte] = i3;
- }
-});
-
-// node_modules/@smithy/eventstream-codec/dist-es/Int64.js
-class Int64 {
- bytes;
- constructor(bytes) {
- this.bytes = bytes;
- if (bytes.byteLength !== 8) {
- throw new Error("Int64 buffers must be exactly 8 bytes");
- }
- }
- static fromNumber(number4) {
- if (number4 > 9223372036854776000 || number4 < -9223372036854776000) {
- throw new Error(`${number4} is too large (or, if negative, too small) to represent as an Int64`);
- }
- const bytes = new Uint8Array(8);
- for (let i3 = 7, remaining = Math.abs(Math.round(number4));i3 > -1 && remaining > 0; i3--, remaining /= 256) {
- bytes[i3] = remaining;
- }
- if (number4 < 0) {
- negate(bytes);
- }
- return new Int64(bytes);
- }
- valueOf() {
- const bytes = this.bytes.slice(0);
- const negative = bytes[0] & 128;
- if (negative) {
- negate(bytes);
- }
- return parseInt(toHex(bytes), 16) * (negative ? -1 : 1);
- }
- toString() {
- return String(this.valueOf());
- }
-}
-function negate(bytes) {
- for (let i3 = 0;i3 < 8; i3++) {
- bytes[i3] ^= 255;
- }
- for (let i3 = 7;i3 > -1; i3--) {
- bytes[i3]++;
- if (bytes[i3] !== 0)
- break;
- }
-}
-var init_Int64 = __esm(() => {
- init_dist_es25();
-});
-
-// node_modules/@smithy/eventstream-codec/dist-es/HeaderMarshaller.js
-class HeaderMarshaller {
- toUtf8;
- fromUtf8;
- constructor(toUtf83, fromUtf86) {
- this.toUtf8 = toUtf83;
- this.fromUtf8 = fromUtf86;
- }
- format(headers) {
- const chunks = [];
- for (const headerName of Object.keys(headers)) {
- const bytes = this.fromUtf8(headerName);
- chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
- }
- const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
- let position2 = 0;
- for (const chunk of chunks) {
- out.set(chunk, position2);
- position2 += chunk.byteLength;
- }
- return out;
- }
- formatHeaderValue(header) {
- switch (header.type) {
- case "boolean":
- return Uint8Array.from([header.value ? 0 : 1]);
- case "byte":
- return Uint8Array.from([2, header.value]);
- case "short":
- const shortView = new DataView(new ArrayBuffer(3));
- shortView.setUint8(0, 3);
- shortView.setInt16(1, header.value, false);
- return new Uint8Array(shortView.buffer);
- case "integer":
- const intView = new DataView(new ArrayBuffer(5));
- intView.setUint8(0, 4);
- intView.setInt32(1, header.value, false);
- return new Uint8Array(intView.buffer);
- case "long":
- const longBytes = new Uint8Array(9);
- longBytes[0] = 5;
- longBytes.set(header.value.bytes, 1);
- return longBytes;
- case "binary":
- const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
- binView.setUint8(0, 6);
- binView.setUint16(1, header.value.byteLength, false);
- const binBytes = new Uint8Array(binView.buffer);
- binBytes.set(header.value, 3);
- return binBytes;
- case "string":
- const utf8Bytes = this.fromUtf8(header.value);
- const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
- strView.setUint8(0, 7);
- strView.setUint16(1, utf8Bytes.byteLength, false);
- const strBytes = new Uint8Array(strView.buffer);
- strBytes.set(utf8Bytes, 3);
- return strBytes;
- case "timestamp":
- const tsBytes = new Uint8Array(9);
- tsBytes[0] = 8;
- tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1);
- return tsBytes;
- case "uuid":
- if (!UUID_PATTERN.test(header.value)) {
- throw new Error(`Invalid UUID received: ${header.value}`);
- }
- const uuidBytes = new Uint8Array(17);
- uuidBytes[0] = 9;
- uuidBytes.set(fromHex(header.value.replace(/\-/g, "")), 1);
- return uuidBytes;
- }
- }
- parse(headers) {
- const out = {};
- let position2 = 0;
- while (position2 < headers.byteLength) {
- const nameLength = headers.getUint8(position2++);
- const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position2, nameLength));
- position2 += nameLength;
- switch (headers.getUint8(position2++)) {
- case 0:
- out[name] = {
- type: BOOLEAN_TAG,
- value: true
- };
- break;
- case 1:
- out[name] = {
- type: BOOLEAN_TAG,
- value: false
- };
- break;
- case 2:
- out[name] = {
- type: BYTE_TAG,
- value: headers.getInt8(position2++)
- };
- break;
- case 3:
- out[name] = {
- type: SHORT_TAG,
- value: headers.getInt16(position2, false)
- };
- position2 += 2;
- break;
- case 4:
- out[name] = {
- type: INT_TAG,
- value: headers.getInt32(position2, false)
- };
- position2 += 4;
- break;
- case 5:
- out[name] = {
- type: LONG_TAG,
- value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position2, 8))
- };
- position2 += 8;
- break;
- case 6:
- const binaryLength = headers.getUint16(position2, false);
- position2 += 2;
- out[name] = {
- type: BINARY_TAG,
- value: new Uint8Array(headers.buffer, headers.byteOffset + position2, binaryLength)
- };
- position2 += binaryLength;
- break;
- case 7:
- const stringLength = headers.getUint16(position2, false);
- position2 += 2;
- out[name] = {
- type: STRING_TAG,
- value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position2, stringLength))
- };
- position2 += stringLength;
- break;
- case 8:
- out[name] = {
- type: TIMESTAMP_TAG,
- value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position2, 8)).valueOf())
- };
- position2 += 8;
- break;
- case 9:
- const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position2, 16);
- position2 += 16;
- out[name] = {
- type: UUID_TAG,
- value: `${toHex(uuidBytes.subarray(0, 4))}-${toHex(uuidBytes.subarray(4, 6))}-${toHex(uuidBytes.subarray(6, 8))}-${toHex(uuidBytes.subarray(8, 10))}-${toHex(uuidBytes.subarray(10))}`
- };
- break;
- default:
- throw new Error(`Unrecognized header type tag`);
- }
- }
- return out;
- }
-}
-var HEADER_VALUE_TYPE, BOOLEAN_TAG = "boolean", BYTE_TAG = "byte", SHORT_TAG = "short", INT_TAG = "integer", LONG_TAG = "long", BINARY_TAG = "binary", STRING_TAG = "string", TIMESTAMP_TAG = "timestamp", UUID_TAG = "uuid", UUID_PATTERN;
-var init_HeaderMarshaller = __esm(() => {
- init_dist_es25();
- init_Int64();
- (function(HEADER_VALUE_TYPE2) {
- HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue";
- HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse";
- HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte";
- HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short";
- HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer";
- HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long";
- HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray";
- HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string";
- HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp";
- HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid";
- })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {}));
- UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
-});
-
-// node_modules/@smithy/eventstream-codec/dist-es/splitMessage.js
-function splitMessage({ byteLength, byteOffset, buffer }) {
- if (byteLength < MINIMUM_MESSAGE_LENGTH) {
- throw new Error("Provided message too short to accommodate event stream message overhead");
- }
- const view = new DataView(buffer, byteOffset, byteLength);
- const messageLength = view.getUint32(0, false);
- if (byteLength !== messageLength) {
- throw new Error("Reported message length does not match received message length");
- }
- const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false);
- const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false);
- const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false);
- const checksummer = new Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH));
- if (expectedPreludeChecksum !== checksummer.digest()) {
- throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`);
- }
- checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH)));
- if (expectedMessageChecksum !== checksummer.digest()) {
- throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`);
- }
- return {
- headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength),
- body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH))
- };
-}
-var PRELUDE_MEMBER_LENGTH = 4, PRELUDE_LENGTH, CHECKSUM_LENGTH = 4, MINIMUM_MESSAGE_LENGTH;
-var init_splitMessage = __esm(() => {
- init_module2();
- PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2;
- MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2;
-});
-
-// node_modules/@smithy/eventstream-codec/dist-es/EventStreamCodec.js
-class EventStreamCodec {
- headerMarshaller;
- messageBuffer;
- isEndOfStream;
- constructor(toUtf83, fromUtf86) {
- this.headerMarshaller = new HeaderMarshaller(toUtf83, fromUtf86);
- this.messageBuffer = [];
- this.isEndOfStream = false;
- }
- feed(message) {
- this.messageBuffer.push(this.decode(message));
- }
- endOfStream() {
- this.isEndOfStream = true;
- }
- getMessage() {
- const message = this.messageBuffer.pop();
- const isEndOfStream = this.isEndOfStream;
- return {
- getMessage() {
- return message;
- },
- isEndOfStream() {
- return isEndOfStream;
- }
- };
- }
- getAvailableMessages() {
- const messages = this.messageBuffer;
- this.messageBuffer = [];
- const isEndOfStream = this.isEndOfStream;
- return {
- getMessages() {
- return messages;
- },
- isEndOfStream() {
- return isEndOfStream;
- }
- };
- }
- encode({ headers: rawHeaders, body }) {
- const headers = this.headerMarshaller.format(rawHeaders);
- const length = headers.byteLength + body.byteLength + 16;
- const out = new Uint8Array(length);
- const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
- const checksum3 = new Crc32;
- view.setUint32(0, length, false);
- view.setUint32(4, headers.byteLength, false);
- view.setUint32(8, checksum3.update(out.subarray(0, 8)).digest(), false);
- out.set(headers, 12);
- out.set(body, headers.byteLength + 12);
- view.setUint32(length - 4, checksum3.update(out.subarray(8, length - 4)).digest(), false);
- return out;
- }
- decode(message) {
- const { headers, body } = splitMessage(message);
- return { headers: this.headerMarshaller.parse(headers), body };
- }
- formatHeaders(rawHeaders) {
- return this.headerMarshaller.format(rawHeaders);
- }
-}
-var init_EventStreamCodec = __esm(() => {
- init_module2();
- init_HeaderMarshaller();
- init_splitMessage();
-});
-
-// node_modules/@smithy/eventstream-codec/dist-es/Message.js
-var init_Message = () => {};
-
-// node_modules/@smithy/eventstream-codec/dist-es/MessageDecoderStream.js
-var MessageDecoderStream;
-var init_MessageDecoderStream = __esm(() => {
- MessageDecoderStream = class MessageDecoderStream {
- options;
- constructor(options2) {
- this.options = options2;
- }
- [Symbol.asyncIterator]() {
- return this.asyncIterator();
- }
- async* asyncIterator() {
- for await (const bytes of this.options.inputStream) {
- const decoded = this.options.decoder.decode(bytes);
- yield decoded;
- }
- }
- };
-});
-
-// node_modules/@smithy/eventstream-codec/dist-es/MessageEncoderStream.js
-var MessageEncoderStream;
-var init_MessageEncoderStream = __esm(() => {
- MessageEncoderStream = class MessageEncoderStream {
- options;
- constructor(options2) {
- this.options = options2;
- }
- [Symbol.asyncIterator]() {
- return this.asyncIterator();
- }
- async* asyncIterator() {
- for await (const msg of this.options.messageStream) {
- const encoded = this.options.encoder.encode(msg);
- yield encoded;
- }
- if (this.options.includeEndFrame) {
- yield new Uint8Array(0);
- }
- }
- };
-});
-
-// node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageDecoderStream.js
-var SmithyMessageDecoderStream;
-var init_SmithyMessageDecoderStream = __esm(() => {
- SmithyMessageDecoderStream = class SmithyMessageDecoderStream {
- options;
- constructor(options2) {
- this.options = options2;
- }
- [Symbol.asyncIterator]() {
- return this.asyncIterator();
- }
- async* asyncIterator() {
- for await (const message of this.options.messageStream) {
- const deserialized = await this.options.deserializer(message);
- if (deserialized === undefined)
- continue;
- yield deserialized;
- }
- }
- };
-});
-
-// node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageEncoderStream.js
-var SmithyMessageEncoderStream;
-var init_SmithyMessageEncoderStream = __esm(() => {
- SmithyMessageEncoderStream = class SmithyMessageEncoderStream {
- options;
- constructor(options2) {
- this.options = options2;
- }
- [Symbol.asyncIterator]() {
- return this.asyncIterator();
- }
- async* asyncIterator() {
- for await (const chunk of this.options.inputStream) {
- const payloadBuf = this.options.serializer(chunk);
- yield payloadBuf;
- }
- }
- };
-});
-
-// node_modules/@smithy/eventstream-codec/dist-es/index.js
-var init_dist_es26 = __esm(() => {
- init_EventStreamCodec();
- init_HeaderMarshaller();
- init_Int64();
- init_Message();
- init_MessageDecoderStream();
- init_MessageEncoderStream();
- init_SmithyMessageDecoderStream();
- init_SmithyMessageEncoderStream();
-});
-
-// node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
-var init_extensions9 = () => {};
-
-// node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-es/Field.js
-var init_Field5 = () => {};
-
-// node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
-var init_httpHandler5 = () => {};
-
-// node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
-class HttpRequest4 {
- method;
- protocol;
- hostname;
- port;
- path;
- query;
- headers;
- username;
- password;
- fragment;
- body;
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static clone(request2) {
- const cloned = new HttpRequest4({
- ...request2,
- headers: { ...request2.headers }
- });
- if (cloned.query) {
- cloned.query = cloneQuery4(cloned.query);
- }
- return cloned;
- }
- static isInstance(request2) {
- if (!request2) {
- return false;
- }
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- return HttpRequest4.clone(this);
- }
-}
-function cloneQuery4(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
-}
-
-// node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-es/types.js
-var init_types10 = () => {};
-
-// node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-es/index.js
-var init_dist_es27 = __esm(() => {
- init_extensions9();
- init_Field5();
- init_httpHandler5();
- init_types10();
-});
-
-// node_modules/@aws-sdk/middleware-websocket/dist-es/utils.js
-var isWebSocketRequest = (request2) => request2.protocol === "ws:" || request2.protocol === "wss:";
-
-// node_modules/@aws-sdk/middleware-websocket/dist-es/WebSocketFetchHandler.js
-var init_WebSocketFetchHandler = () => {};
-
-// node_modules/@aws-sdk/middleware-websocket/dist-es/middlewares/websocketEndpointMiddleware.js
-var websocketEndpointMiddleware = (config4, options2) => (next) => (args) => {
- const { request: request2 } = args;
- if (HttpRequest4.isInstance(request2) && config4.requestHandler.metadata?.handlerProtocol?.toLowerCase().includes("websocket")) {
- request2.protocol = "wss:";
- request2.method = "GET";
- request2.path = `${request2.path}-websocket`;
- const { headers } = request2;
- delete headers["content-type"];
- delete headers["x-amz-content-sha256"];
- for (const name of Object.keys(headers)) {
- if (name.indexOf(options2.headerPrefix) === 0) {
- const chunkedName = name.replace(options2.headerPrefix, "");
- request2.query[chunkedName] = headers[name];
- }
- }
- if (headers["x-amz-user-agent"]) {
- request2.query["user-agent"] = headers["x-amz-user-agent"];
- }
- request2.headers = { host: headers.host ?? request2.hostname };
- }
- return next(args);
-}, websocketEndpointMiddlewareOptions;
-var init_websocketEndpointMiddleware = __esm(() => {
- init_dist_es27();
- websocketEndpointMiddlewareOptions = {
- name: "websocketEndpointMiddleware",
- tags: ["WEBSOCKET", "EVENT_STREAM"],
- relation: "after",
- toMiddleware: "eventStreamHeaderMiddleware",
- override: true
- };
-});
-
-// node_modules/@aws-sdk/middleware-websocket/dist-es/middlewares/websocketInjectSessionIdMiddleware.js
-var injectSessionIdMiddleware = () => (next) => async (args) => {
- const requestParams = {
- ...args.input
- };
- const response3 = await next(args);
- const output = response3.output;
- if (requestParams.SessionId && output.SessionId == null) {
- output.SessionId = requestParams.SessionId;
- }
- return response3;
-}, injectSessionIdMiddlewareOptions;
-var init_websocketInjectSessionIdMiddleware = __esm(() => {
- injectSessionIdMiddlewareOptions = {
- step: "initialize",
- name: "injectSessionIdMiddleware",
- tags: ["WEBSOCKET", "EVENT_STREAM"],
- override: true
- };
-});
-
-// node_modules/@aws-sdk/middleware-websocket/dist-es/getWebSocketPlugin.js
-var getWebSocketPlugin = (config4, options2) => ({
- applyToStack: (clientStack) => {
- clientStack.addRelativeTo(websocketEndpointMiddleware(config4, options2), websocketEndpointMiddlewareOptions);
- clientStack.add(injectSessionIdMiddleware(), injectSessionIdMiddlewareOptions);
- }
-});
-var init_getWebSocketPlugin = __esm(() => {
- init_websocketEndpointMiddleware();
- init_websocketInjectSessionIdMiddleware();
-});
-
-// node_modules/@aws-sdk/middleware-websocket/dist-es/WebsocketSignatureV4.js
-class WebsocketSignatureV4 {
- signer;
- constructor(options2) {
- this.signer = options2.signer;
- }
- presign(originalRequest, options2 = {}) {
- return this.signer.presign(originalRequest, options2);
- }
- async sign(toSign, options2) {
- if (HttpRequest4.isInstance(toSign) && isWebSocketRequest(toSign)) {
- const signedRequest = await this.signer.presign({ ...toSign, body: "" }, {
- ...options2,
- expiresIn: 60,
- unsignableHeaders: new Set(Object.keys(toSign.headers).filter((header) => header !== "host"))
- });
- return {
- ...signedRequest,
- body: toSign.body
- };
- } else {
- return this.signer.sign(toSign, options2);
- }
- }
- signMessage(message, args) {
- return this.signer.signMessage(message, args);
- }
-}
-var init_WebsocketSignatureV4 = __esm(() => {
- init_dist_es27();
-});
-
-// node_modules/@aws-sdk/middleware-websocket/dist-es/resolveWebSocketConfig.js
-var resolveWebSocketConfig = (input) => {
- const { signer } = input;
- return Object.assign(input, {
- signer: async (authScheme) => {
- const signerObj = await signer(authScheme);
- if (validateSigner(signerObj)) {
- return new WebsocketSignatureV4({ signer: signerObj });
- }
- throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor.");
- }
- });
-}, validateSigner = (signer) => !!signer;
-var init_resolveWebSocketConfig = __esm(() => {
- init_WebsocketSignatureV4();
-});
-
-// node_modules/@aws-sdk/middleware-websocket/dist-es/ws-eventstream/eventStreamPayloadHandlerProvider.js
-var init_eventStreamPayloadHandlerProvider = () => {};
-
-// node_modules/@aws-sdk/middleware-websocket/dist-es/index.js
-var init_dist_es28 = __esm(() => {
- init_WebSocketFetchHandler();
- init_getWebSocketPlugin();
- init_resolveWebSocketConfig();
- init_eventStreamPayloadHandlerProvider();
-});
-
-// node_modules/@smithy/eventstream-serde-config-resolver/dist-es/EventStreamSerdeConfig.js
-var resolveEventStreamSerdeConfig = (input) => Object.assign(input, {
- eventStreamMarshaller: input.eventStreamSerdeProvider(input)
-});
-
-// node_modules/@smithy/eventstream-serde-config-resolver/dist-es/index.js
-var init_dist_es29 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/client.js
-class Client3 {
- config;
- middlewareStack = import_middleware_stack5.constructStack();
- initConfig;
- handlers;
- constructor(config4) {
- this.config = config4;
- const { protocol, protocolSettings } = config4;
- if (protocolSettings) {
- if (typeof protocol === "function") {
- config4.protocol = new protocol(protocolSettings);
- }
- }
- }
- send(command5, optionsOrCb, cb) {
- const options2 = typeof optionsOrCb !== "function" ? optionsOrCb : undefined;
- const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
- const useHandlerCache = options2 === undefined && this.config.cacheMiddleware === true;
- let handler;
- if (useHandlerCache) {
- if (!this.handlers) {
- this.handlers = new WeakMap;
- }
- const handlers = this.handlers;
- if (handlers.has(command5.constructor)) {
- handler = handlers.get(command5.constructor);
- } else {
- handler = command5.resolveMiddleware(this.middlewareStack, this.config, options2);
- handlers.set(command5.constructor, handler);
- }
- } else {
- delete this.handlers;
- handler = command5.resolveMiddleware(this.middlewareStack, this.config, options2);
- }
- if (callback) {
- handler(command5).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => {});
- } else {
- return handler(command5).then((result) => result.output);
- }
- }
- destroy() {
- this.config?.requestHandler?.destroy?.();
- delete this.handlers;
- }
-}
-var import_middleware_stack5;
-var init_client5 = __esm(() => {
- import_middleware_stack5 = __toESM(require_dist_cjs12(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js
-var import_protocols8;
-var init_collect_stream_body3 = __esm(() => {
- import_protocols8 = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/abort.js
-var init_abort4 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/auth/auth.js
-var HttpAuthLocation3;
-var init_auth5 = __esm(() => {
- (function(HttpAuthLocation4) {
- HttpAuthLocation4["HEADER"] = "header";
- HttpAuthLocation4["QUERY"] = "query";
- })(HttpAuthLocation3 || (HttpAuthLocation3 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
-var HttpApiKeyAuthLocation3;
-var init_HttpApiKeyAuth3 = __esm(() => {
- (function(HttpApiKeyAuthLocation4) {
- HttpApiKeyAuthLocation4["HEADER"] = "header";
- HttpApiKeyAuthLocation4["QUERY"] = "query";
- })(HttpApiKeyAuthLocation3 || (HttpApiKeyAuthLocation3 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js
-var init_HttpAuthScheme3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js
-var init_HttpAuthSchemeProvider3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/auth/HttpSigner.js
-var init_HttpSigner3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js
-var init_IdentityProviderConfig3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/auth/index.js
-var init_auth6 = __esm(() => {
- init_auth5();
- init_HttpApiKeyAuth3();
- init_HttpAuthScheme3();
- init_HttpAuthSchemeProvider3();
- init_HttpSigner3();
- init_IdentityProviderConfig3();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js
-var init_blob_payload_input_types3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/checksum.js
-var init_checksum7 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/client.js
-var init_client6 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/command.js
-var init_command7 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/connection/config.js
-var init_config4 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/connection/manager.js
-var init_manager3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/connection/pool.js
-var init_pool3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/connection/index.js
-var init_connection3 = __esm(() => {
- init_config4();
- init_manager3();
- init_pool3();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/crypto.js
-var init_crypto4 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/encode.js
-var init_encode3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/endpoint.js
-var EndpointURLScheme3;
-var init_endpoint3 = __esm(() => {
- (function(EndpointURLScheme4) {
- EndpointURLScheme4["HTTP"] = "http";
- EndpointURLScheme4["HTTPS"] = "https";
- })(EndpointURLScheme3 || (EndpointURLScheme3 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js
-var init_EndpointRuleObject3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js
-var init_ErrorRuleObject3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js
-var init_RuleSetObject3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/endpoints/shared.js
-var init_shared5 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js
-var init_TreeRuleObject3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/endpoints/index.js
-var init_endpoints3 = __esm(() => {
- init_EndpointRuleObject3();
- init_ErrorRuleObject3();
- init_RuleSetObject3();
- init_shared5();
- init_TreeRuleObject3();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/eventStream.js
-var init_eventStream3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/extensions/checksum.js
-var AlgorithmId3;
-var init_checksum8 = __esm(() => {
- (function(AlgorithmId4) {
- AlgorithmId4["MD5"] = "md5";
- AlgorithmId4["CRC32"] = "crc32";
- AlgorithmId4["CRC32C"] = "crc32c";
- AlgorithmId4["SHA1"] = "sha1";
- AlgorithmId4["SHA256"] = "sha256";
- })(AlgorithmId3 || (AlgorithmId3 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js
-var init_defaultClientConfiguration3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js
-var init_defaultExtensionConfiguration5 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/extensions/index.js
-var init_extensions10 = __esm(() => {
- init_checksum8();
- init_defaultClientConfiguration3();
- init_defaultExtensionConfiguration5();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/feature-ids.js
-var init_feature_ids3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/http.js
-var FieldPosition3;
-var init_http4 = __esm(() => {
- (function(FieldPosition4) {
- FieldPosition4[FieldPosition4["HEADER"] = 0] = "HEADER";
- FieldPosition4[FieldPosition4["TRAILER"] = 1] = "TRAILER";
- })(FieldPosition3 || (FieldPosition3 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js
-var init_httpHandlerInitialization3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js
-var init_apiKeyIdentity3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js
-var init_awsCredentialIdentity3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/identity/identity.js
-var init_identity6 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js
-var init_tokenIdentity3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/identity/index.js
-var init_identity7 = __esm(() => {
- init_apiKeyIdentity3();
- init_awsCredentialIdentity3();
- init_identity6();
- init_tokenIdentity3();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/logger.js
-var init_logger3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/middleware.js
-var SMITHY_CONTEXT_KEY3 = "__smithy_context";
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/pagination.js
-var init_pagination5 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/profile.js
-var IniSectionType3;
-var init_profile3 = __esm(() => {
- (function(IniSectionType4) {
- IniSectionType4["PROFILE"] = "profile";
- IniSectionType4["SSO_SESSION"] = "sso-session";
- IniSectionType4["SERVICES"] = "services";
- })(IniSectionType3 || (IniSectionType3 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/response.js
-var init_response3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/retry.js
-var init_retry3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/schema/schema.js
-var init_schema3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/schema/traits.js
-var init_traits3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/schema/schema-deprecated.js
-var init_schema_deprecated3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/schema/sentinels.js
-var init_sentinels3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/schema/static-schemas.js
-var init_static_schemas3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/serde.js
-var init_serde3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/shapes.js
-var init_shapes3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/signature.js
-var init_signature3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/stream.js
-var init_stream4 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js
-var init_streaming_blob_common_types3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js
-var init_streaming_blob_payload_input_types3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js
-var init_streaming_blob_payload_output_types3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/transfer.js
-var RequestHandlerProtocol3;
-var init_transfer3 = __esm(() => {
- (function(RequestHandlerProtocol4) {
- RequestHandlerProtocol4["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol4["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol4["TDS_8_0"] = "tds/8.0";
- })(RequestHandlerProtocol3 || (RequestHandlerProtocol3 = {}));
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js
-var init_client_payload_blob_type_narrow3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/transform/mutable.js
-var init_mutable3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/transform/no-undefined.js
-var init_no_undefined3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/transform/type-transform.js
-var init_type_transform3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/uri.js
-var init_uri3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/util.js
-var init_util5 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/waiter.js
-var init_waiter3 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-es/index.js
-var init_dist_es30 = __esm(() => {
- init_abort4();
- init_auth6();
- init_blob_payload_input_types3();
- init_checksum7();
- init_client6();
- init_command7();
- init_connection3();
- init_crypto4();
- init_encode3();
- init_endpoint3();
- init_endpoints3();
- init_eventStream3();
- init_extensions10();
- init_feature_ids3();
- init_http4();
- init_httpHandlerInitialization3();
- init_identity7();
- init_logger3();
- init_pagination5();
- init_profile3();
- init_response3();
- init_retry3();
- init_schema3();
- init_traits3();
- init_schema_deprecated3();
- init_sentinels3();
- init_static_schemas3();
- init_serde3();
- init_shapes3();
- init_signature3();
- init_stream4();
- init_streaming_blob_common_types3();
- init_streaming_blob_payload_input_types3();
- init_streaming_blob_payload_output_types3();
- init_transfer3();
- init_client_payload_blob_type_narrow3();
- init_mutable3();
- init_no_undefined3();
- init_type_transform3();
- init_uri3();
- init_util5();
- init_waiter3();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/schemaLogFilter.js
-function schemaLogFilter3(schema4, data) {
- if (data == null) {
- return data;
- }
- const ns = import_schema5.NormalizedSchema.of(schema4);
- if (ns.getMergedTraits().sensitive) {
- return SENSITIVE_STRING5;
- }
- if (ns.isListSchema()) {
- const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING5;
- }
- } else if (ns.isMapSchema()) {
- const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING5;
- }
- } else if (ns.isStructSchema() && typeof data === "object") {
- const object2 = data;
- const newObject = {};
- for (const [member, memberNs] of ns.structIterator()) {
- if (object2[member] != null) {
- newObject[member] = schemaLogFilter3(memberNs, object2[member]);
- }
- }
- return newObject;
- }
- return data;
-}
-var import_schema5, SENSITIVE_STRING5 = "***SensitiveInformation***";
-var init_schemaLogFilter3 = __esm(() => {
- import_schema5 = __toESM(require_schema(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/command.js
-class Command4 {
- middlewareStack = import_middleware_stack6.constructStack();
- schema;
- static classBuilder() {
- return new ClassBuilder3;
- }
- resolveMiddlewareWithContext(clientStack, configuration, options2, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
- for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options2)) {
- this.middlewareStack.use(mw);
- }
- const stack = clientStack.concat(this.middlewareStack);
- const { logger: logger4 } = configuration;
- const handlerExecutionContext = {
- logger: logger4,
- clientName,
- commandName,
- inputFilterSensitiveLog,
- outputFilterSensitiveLog,
- [SMITHY_CONTEXT_KEY3]: {
- commandInstance: this,
- ...smithyContext
- },
- ...additionalContext
- };
- const { requestHandler } = configuration;
- return stack.resolve((request2) => requestHandler.handle(request2.request, options2 || {}), handlerExecutionContext);
- }
-}
-
-class ClassBuilder3 {
- _init = () => {};
- _ep = {};
- _middlewareFn = () => [];
- _commandName = "";
- _clientName = "";
- _additionalContext = {};
- _smithyContext = {};
- _inputFilterSensitiveLog = undefined;
- _outputFilterSensitiveLog = undefined;
- _serializer = null;
- _deserializer = null;
- _operationSchema;
- init(cb) {
- this._init = cb;
- }
- ep(endpointParameterInstructions) {
- this._ep = endpointParameterInstructions;
- return this;
- }
- m(middlewareSupplier) {
- this._middlewareFn = middlewareSupplier;
- return this;
- }
- s(service, operation, smithyContext = {}) {
- this._smithyContext = {
- service,
- operation,
- ...smithyContext
- };
- return this;
- }
- c(additionalContext = {}) {
- this._additionalContext = additionalContext;
- return this;
- }
- n(clientName, commandName) {
- this._clientName = clientName;
- this._commandName = commandName;
- return this;
- }
- f(inputFilter = (_) => _, outputFilter = (_) => _) {
- this._inputFilterSensitiveLog = inputFilter;
- this._outputFilterSensitiveLog = outputFilter;
- return this;
- }
- ser(serializer) {
- this._serializer = serializer;
- return this;
- }
- de(deserializer) {
- this._deserializer = deserializer;
- return this;
- }
- sc(operation) {
- this._operationSchema = operation;
- this._smithyContext.operationSchema = operation;
- return this;
- }
- build() {
- const closure = this;
- let CommandRef;
- return CommandRef = class extends Command4 {
- input;
- static getEndpointParameterInstructions() {
- return closure._ep;
- }
- constructor(...[input]) {
- super();
- this.input = input ?? {};
- closure._init(this);
- this.schema = closure._operationSchema;
- }
- resolveMiddleware(stack, configuration, options2) {
- const op = closure._operationSchema;
- const input = op?.[4] ?? op?.input;
- const output = op?.[5] ?? op?.output;
- return this.resolveMiddlewareWithContext(stack, configuration, options2, {
- CommandCtor: CommandRef,
- middlewareFn: closure._middlewareFn,
- clientName: closure._clientName,
- commandName: closure._commandName,
- inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter3.bind(null, input) : (_) => _),
- outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter3.bind(null, output) : (_) => _),
- smithyContext: closure._smithyContext,
- additionalContext: closure._additionalContext
- });
- }
- serialize = closure._serializer;
- deserialize = closure._deserializer;
- };
- }
-}
-var import_middleware_stack6;
-var init_command8 = __esm(() => {
- init_dist_es30();
- init_schemaLogFilter3();
- import_middleware_stack6 = __toESM(require_dist_cjs12(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/constants.js
-var SENSITIVE_STRING6 = "***SensitiveInformation***";
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js
-var createAggregatedClient3 = (commands3, Client4, options2) => {
- for (const [command6, CommandCtor] of Object.entries(commands3)) {
- const methodImpl = async function(args, optionsOrCb, cb) {
- const command7 = new CommandCtor(args);
- if (typeof optionsOrCb === "function") {
- this.send(command7, optionsOrCb);
- } else if (typeof cb === "function") {
- if (typeof optionsOrCb !== "object")
- throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
- this.send(command7, optionsOrCb || {}, cb);
- } else {
- return this.send(command7, optionsOrCb);
- }
- };
- const methodName = (command6[0].toLowerCase() + command6.slice(1)).replace(/Command$/, "");
- Client4.prototype[methodName] = methodImpl;
- }
- const { paginators: paginators2 = {}, waiters = {} } = options2 ?? {};
- for (const [paginatorName, paginatorFn] of Object.entries(paginators2)) {
- if (Client4.prototype[paginatorName] === undefined) {
- Client4.prototype[paginatorName] = function(commandInput = {}, paginationConfiguration, ...rest) {
- return paginatorFn({
- ...paginationConfiguration,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
- for (const [waiterName, waiterFn] of Object.entries(waiters)) {
- if (Client4.prototype[waiterName] === undefined) {
- Client4.prototype[waiterName] = async function(commandInput = {}, waiterConfiguration, ...rest) {
- let config5 = waiterConfiguration;
- if (typeof waiterConfiguration === "number") {
- config5 = {
- maxWaitTime: waiterConfiguration
- };
- }
- return waiterFn({
- ...config5,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
-};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/exceptions.js
-var ServiceException3, decorateServiceException3 = (exception, additions = {}) => {
- Object.entries(additions).filter(([, v2]) => v2 !== undefined).forEach(([k2, v2]) => {
- if (exception[k2] == undefined || exception[k2] === "") {
- exception[k2] = v2;
- }
- });
- const message = exception.message || exception.Message || "UnknownError";
- exception.message = message;
- delete exception.Message;
- return exception;
-};
-var init_exceptions3 = __esm(() => {
- ServiceException3 = class ServiceException3 extends Error {
- $fault;
- $response;
- $retryable;
- $metadata;
- constructor(options2) {
- super(options2.message);
- Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
- this.name = options2.name;
- this.$fault = options2.$fault;
- this.$metadata = options2.$metadata;
- }
- static isInstance(value) {
- if (!value)
- return false;
- const candidate = value;
- return ServiceException3.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
- }
- static [Symbol.hasInstance](instance) {
- if (!instance)
- return false;
- const candidate = instance;
- if (this === ServiceException3) {
- return ServiceException3.isInstance(instance);
- }
- if (ServiceException3.isInstance(instance)) {
- if (candidate.name && this.name) {
- return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
- }
- return this.prototype.isPrototypeOf(instance);
- }
- return false;
- }
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js
-var throwDefaultError3 = ({ output, parsedBody, exceptionCtor, errorCode }) => {
- const $metadata = deserializeMetadata3(output);
- const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined;
- const response4 = new exceptionCtor({
- name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
- $fault: "client",
- $metadata
- });
- throw decorateServiceException3(response4, parsedBody);
-}, withBaseException3 = (ExceptionCtor) => {
- return ({ output, parsedBody, errorCode }) => {
- throwDefaultError3({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
- };
-}, deserializeMetadata3 = (output) => ({
- httpStatusCode: output.statusCode,
- requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
- extendedRequestId: output.headers["x-amz-id-2"],
- cfId: output.headers["x-amz-cf-id"]
-});
-var init_default_error_handler3 = __esm(() => {
- init_exceptions3();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js
-var loadConfigsForDefaultMode3 = (mode) => {
- switch (mode) {
- case "standard":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "in-region":
- return {
- retryMode: "standard",
- connectionTimeout: 1100
- };
- case "cross-region":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "mobile":
- return {
- retryMode: "standard",
- connectionTimeout: 30000
- };
- default:
- return {};
- }
-};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js
-var warningEmitted3 = false, emitWarningIfUnsupportedVersion5 = (version2) => {
- if (version2 && !warningEmitted3 && parseInt(version2.substring(1, version2.indexOf("."))) < 16) {
- warningEmitted3 = true;
- }
-};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js
-var import_protocols9;
-var init_extended_encode_uri_component3 = __esm(() => {
- import_protocols9 = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js
-var knownAlgorithms3, getChecksumConfiguration3 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- for (const id in AlgorithmId3) {
- const algorithmId = AlgorithmId3[id];
- if (runtimeConfig[algorithmId] === undefined) {
- continue;
- }
- checksumAlgorithms.push({
- algorithmId: () => algorithmId,
- checksumConstructor: () => runtimeConfig[algorithmId]
- });
- }
- for (const [id, ChecksumCtor] of Object.entries(runtimeConfig.checksumAlgorithms ?? {})) {
- checksumAlgorithms.push({
- algorithmId: () => id,
- checksumConstructor: () => ChecksumCtor
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- runtimeConfig.checksumAlgorithms = runtimeConfig.checksumAlgorithms ?? {};
- const id = algo.algorithmId();
- const ctor = algo.checksumConstructor();
- if (knownAlgorithms3.includes(id)) {
- runtimeConfig.checksumAlgorithms[id.toUpperCase()] = ctor;
- } else {
- runtimeConfig.checksumAlgorithms[id] = ctor;
- }
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
-}, resolveChecksumRuntimeConfig3 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- const id = checksumAlgorithm.algorithmId();
- if (knownAlgorithms3.includes(id)) {
- runtimeConfig[id] = checksumAlgorithm.checksumConstructor();
- }
- });
- return runtimeConfig;
-};
-var init_checksum9 = __esm(() => {
- init_dist_es30();
- knownAlgorithms3 = Object.values(AlgorithmId3);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js
-var getRetryConfiguration3 = (runtimeConfig) => {
- return {
- setRetryStrategy(retryStrategy) {
- runtimeConfig.retryStrategy = retryStrategy;
- },
- retryStrategy() {
- return runtimeConfig.retryStrategy;
- }
- };
-}, resolveRetryRuntimeConfig3 = (retryStrategyConfiguration) => {
- const runtimeConfig = {};
- runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
- return runtimeConfig;
-};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js
-var getDefaultExtensionConfiguration3 = (runtimeConfig) => {
- return Object.assign(getChecksumConfiguration3(runtimeConfig), getRetryConfiguration3(runtimeConfig));
-}, getDefaultClientConfiguration3, resolveDefaultRuntimeConfig3 = (config5) => {
- return Object.assign(resolveChecksumRuntimeConfig3(config5), resolveRetryRuntimeConfig3(config5));
-};
-var init_defaultExtensionConfiguration6 = __esm(() => {
- init_checksum9();
- getDefaultClientConfiguration3 = getDefaultExtensionConfiguration3;
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/extensions/index.js
-var init_extensions11 = __esm(() => {
- init_defaultExtensionConfiguration6();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js
-var getArrayIfSingleItem3 = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray];
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js
-var getValueFromTextNode3 = (obj) => {
- const textNodeName = "#text";
- for (const key in obj) {
- if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) {
- obj[key] = obj[key][textNodeName];
- } else if (typeof obj[key] === "object" && obj[key] !== null) {
- obj[key] = getValueFromTextNode3(obj[key]);
- }
- }
- return obj;
-};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js
-var isSerializableHeaderValue3 = (value) => {
- return value != null;
-};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js
-class NoOpLogger5 {
- trace() {}
- debug() {}
- info() {}
- warn() {}
- error() {}
-}
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/object-mapping.js
-function map4(arg0, arg1, arg2) {
- let target;
- let filter2;
- let instructions;
- if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
- target = {};
- instructions = arg0;
- } else {
- target = arg0;
- if (typeof arg1 === "function") {
- filter2 = arg1;
- instructions = arg2;
- return mapWithFilter3(target, filter2, instructions);
- } else {
- instructions = arg1;
- }
- }
- for (const key of Object.keys(instructions)) {
- if (!Array.isArray(instructions[key])) {
- target[key] = instructions[key];
- continue;
- }
- applyInstruction3(target, null, instructions, key);
- }
- return target;
-}
-var convertMap3 = (target) => {
- const output = {};
- for (const [k2, v2] of Object.entries(target || {})) {
- output[k2] = [, v2];
- }
- return output;
-}, take3 = (source, instructions) => {
- const out = {};
- for (const key in instructions) {
- applyInstruction3(out, source, instructions, key);
- }
- return out;
-}, mapWithFilter3 = (target, filter2, instructions) => {
- return map4(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
- if (Array.isArray(value)) {
- _instructions[key] = value;
- } else {
- if (typeof value === "function") {
- _instructions[key] = [filter2, value()];
- } else {
- _instructions[key] = [filter2, value];
- }
- }
- return _instructions;
- }, {}));
-}, applyInstruction3 = (target, source, instructions, targetKey) => {
- if (source !== null) {
- let instruction = instructions[targetKey];
- if (typeof instruction === "function") {
- instruction = [, instruction];
- }
- const [filter3 = nonNullish3, valueFn = pass3, sourceKey = targetKey] = instruction;
- if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) {
- target[targetKey] = valueFn(source[sourceKey]);
- }
- return;
- }
- let [filter2, value] = instructions[targetKey];
- if (typeof value === "function") {
- let _value;
- const defaultFilterPassed = filter2 === undefined && (_value = value()) != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(undefined) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed) {
- target[targetKey] = _value;
- } else if (customFilterPassed) {
- target[targetKey] = value();
- }
- } else {
- const defaultFilterPassed = filter2 === undefined && value != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed || customFilterPassed) {
- target[targetKey] = value;
- }
- }
-}, nonNullish3 = (_) => _ != null, pass3 = (_) => _;
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/resolve-path.js
-var import_protocols10;
-var init_resolve_path3 = __esm(() => {
- import_protocols10 = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/ser-utils.js
-var serializeFloat3 = (value) => {
- if (value !== value) {
- return "NaN";
- }
- switch (value) {
- case Infinity:
- return "Infinity";
- case -Infinity:
- return "-Infinity";
- default:
- return value;
- }
-}, serializeDateTime3 = (date5) => date5.toISOString().replace(".000Z", "Z");
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/serde-json.js
-var _json3 = (obj) => {
- if (obj == null) {
- return {};
- }
- if (Array.isArray(obj)) {
- return obj.filter((_) => _ != null).map(_json3);
- }
- if (typeof obj === "object") {
- const target = {};
- for (const key of Object.keys(obj)) {
- if (obj[key] == null) {
- continue;
- }
- target[key] = _json3(obj[key]);
- }
- return target;
- }
- return obj;
-};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-es/index.js
-var exports_dist_es12 = {};
-__export(exports_dist_es12, {
- withBaseException: () => withBaseException3,
- throwDefaultError: () => throwDefaultError3,
- take: () => take3,
- serializeFloat: () => serializeFloat3,
- serializeDateTime: () => serializeDateTime3,
- resolvedPath: () => import_protocols10.resolvedPath,
- resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig3,
- map: () => map4,
- loadConfigsForDefaultMode: () => loadConfigsForDefaultMode3,
- isSerializableHeaderValue: () => isSerializableHeaderValue3,
- getValueFromTextNode: () => getValueFromTextNode3,
- getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration3,
- getDefaultClientConfiguration: () => getDefaultClientConfiguration3,
- getArrayIfSingleItem: () => getArrayIfSingleItem3,
- extendedEncodeURIComponent: () => import_protocols9.extendedEncodeURIComponent,
- emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion5,
- decorateServiceException: () => decorateServiceException3,
- createAggregatedClient: () => createAggregatedClient3,
- convertMap: () => convertMap3,
- collectBody: () => import_protocols8.collectBody,
- _json: () => _json3,
- ServiceException: () => ServiceException3,
- SENSITIVE_STRING: () => SENSITIVE_STRING6,
- NoOpLogger: () => NoOpLogger5,
- Command: () => Command4,
- Client: () => Client3
-});
-var init_dist_es31 = __esm(() => {
- init_client5();
- init_collect_stream_body3();
- init_command8();
- init_default_error_handler3();
- init_exceptions3();
- init_extended_encode_uri_component3();
- init_extensions11();
- init_resolve_path3();
- __reExport(exports_dist_es12, __toESM(require_serde(), 1));
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/auth/httpAuthSchemeProvider.js
-function createAwsAuthSigv4HttpAuthOption2(authParameters) {
- return {
- schemeId: "aws.auth#sigv4",
- signingProperties: {
- name: "bedrock",
- region: authParameters.region
- },
- propertiesExtractor: (config5, context) => ({
- signingProperties: {
- config: config5,
- context
- }
- })
- };
-}
-function createSmithyApiHttpBearerAuthHttpAuthOption2(authParameters) {
- return {
- schemeId: "smithy.api#httpBearerAuth",
- propertiesExtractor: ({ profile: profile4, filepath, configFilepath, ignoreCache }, context) => ({
- identityProperties: {
- profile: profile4,
- filepath,
- configFilepath,
- ignoreCache
- }
- })
- };
-}
-var import_httpAuthSchemes5, import_core39, import_util_middleware2, defaultBedrockRuntimeHttpAuthSchemeParametersProvider = async (config5, context, input) => {
- return {
- operation: import_util_middleware2.getSmithyContext(context).operation,
- region: await import_util_middleware2.normalizeProvider(config5.region)() || (() => {
- throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
- })()
- };
-}, defaultBedrockRuntimeHttpAuthSchemeProvider = (authParameters) => {
- const options2 = [];
- switch (authParameters.operation) {
- default: {
- options2.push(createAwsAuthSigv4HttpAuthOption2(authParameters));
- options2.push(createSmithyApiHttpBearerAuthHttpAuthOption2(authParameters));
- }
- }
- return options2;
-}, resolveHttpAuthSchemeConfig2 = (config5) => {
- const token = import_core39.memoizeIdentityProvider(config5.token, import_core39.isIdentityExpired, import_core39.doesIdentityRequireRefresh);
- const config_0 = import_httpAuthSchemes5.resolveAwsSdkSigV4Config(config5);
- return Object.assign(config_0, {
- authSchemePreference: import_util_middleware2.normalizeProvider(config5.authSchemePreference ?? []),
- token
- });
-};
-var init_httpAuthSchemeProvider2 = __esm(() => {
- import_httpAuthSchemes5 = __toESM(require_httpAuthSchemes(), 1);
- import_core39 = __toESM(require_dist_cjs37(), 1);
- import_util_middleware2 = __toESM(require_dist_cjs30(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/endpoint/EndpointParameters.js
-var resolveClientEndpointParameters2 = (options2) => {
- return Object.assign(options2, {
- useDualstackEndpoint: options2.useDualstackEndpoint ?? false,
- useFipsEndpoint: options2.useFipsEndpoint ?? false,
- defaultSigningName: "bedrock"
- });
-}, commonParams2;
-var init_EndpointParameters2 = __esm(() => {
- commonParams2 = {
- UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
- Endpoint: { type: "builtInParams", name: "endpoint" },
- Region: { type: "builtInParams", name: "region" },
- UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/package.json
-var package_default2;
-var init_package2 = __esm(() => {
- package_default2 = {
- name: "@aws-sdk/client-bedrock-runtime",
- description: "AWS SDK for JavaScript Bedrock Runtime Client for Node.js, Browser and React Native",
- version: "3.1020.0",
- scripts: {
- build: "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs",
- "build:cjs": "node ../../scripts/compilation/inline client-bedrock-runtime",
- "build:es": "tsc -p tsconfig.es.json",
- "build:include:deps": 'yarn g:turbo run build -F="$npm_package_name"',
- "build:types": "tsc -p tsconfig.types.json",
- "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
- clean: "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",
- "extract:docs": "api-extractor run --local",
- "generate:client": "node ../../scripts/generate-clients/single-service --solo bedrock-runtime",
- test: "yarn g:vitest run --passWithNoTests",
- "test:browser": "yarn g:vitest run -c vitest.config.browser.e2e.mts",
- "test:browser:watch": "yarn g:vitest watch -c vitest.config.browser.e2e.mts",
- "test:e2e": "yarn g:vitest run -c vitest.config.e2e.mts",
- "test:e2e:watch": "yarn g:vitest watch -c vitest.config.e2e.mts",
- "test:index": "tsc --noEmit ./test/index-types.ts && node ./test/index-objects.spec.mjs",
- "test:integration": "yarn g:vitest run --passWithNoTests -c vitest.config.integ.mts",
- "test:integration:watch": "yarn g:vitest run --passWithNoTests -c vitest.config.integ.mts",
- "test:watch": "yarn g:vitest watch --passWithNoTests"
- },
- main: "./dist-cjs/index.js",
- types: "./dist-types/index.d.ts",
- module: "./dist-es/index.js",
- sideEffects: false,
- dependencies: {
- "@aws-crypto/sha256-browser": "5.2.0",
- "@aws-crypto/sha256-js": "5.2.0",
- "@aws-sdk/core": "^3.973.26",
- "@aws-sdk/credential-provider-node": "^3.972.28",
- "@aws-sdk/eventstream-handler-node": "^3.972.12",
- "@aws-sdk/middleware-eventstream": "^3.972.8",
- "@aws-sdk/middleware-host-header": "^3.972.8",
- "@aws-sdk/middleware-logger": "^3.972.8",
- "@aws-sdk/middleware-recursion-detection": "^3.972.9",
- "@aws-sdk/middleware-user-agent": "^3.972.27",
- "@aws-sdk/middleware-websocket": "^3.972.14",
- "@aws-sdk/region-config-resolver": "^3.972.10",
- "@aws-sdk/token-providers": "3.1020.0",
- "@aws-sdk/types": "^3.973.6",
- "@aws-sdk/util-endpoints": "^3.996.5",
- "@aws-sdk/util-user-agent-browser": "^3.972.8",
- "@aws-sdk/util-user-agent-node": "^3.973.13",
- "@smithy/config-resolver": "^4.4.13",
- "@smithy/core": "^3.23.13",
- "@smithy/eventstream-serde-browser": "^4.2.12",
- "@smithy/eventstream-serde-config-resolver": "^4.3.12",
- "@smithy/eventstream-serde-node": "^4.2.12",
- "@smithy/fetch-http-handler": "^5.3.15",
- "@smithy/hash-node": "^4.2.12",
- "@smithy/invalid-dependency": "^4.2.12",
- "@smithy/middleware-content-length": "^4.2.12",
- "@smithy/middleware-endpoint": "^4.4.28",
- "@smithy/middleware-retry": "^4.4.45",
- "@smithy/middleware-serde": "^4.2.16",
- "@smithy/middleware-stack": "^4.2.12",
- "@smithy/node-config-provider": "^4.3.12",
- "@smithy/node-http-handler": "^4.5.1",
- "@smithy/protocol-http": "^5.3.12",
- "@smithy/smithy-client": "^4.12.8",
- "@smithy/types": "^4.13.1",
- "@smithy/url-parser": "^4.2.12",
- "@smithy/util-base64": "^4.3.2",
- "@smithy/util-body-length-browser": "^4.2.2",
- "@smithy/util-body-length-node": "^4.2.3",
- "@smithy/util-defaults-mode-browser": "^4.3.44",
- "@smithy/util-defaults-mode-node": "^4.2.48",
- "@smithy/util-endpoints": "^3.3.3",
- "@smithy/util-middleware": "^4.2.12",
- "@smithy/util-retry": "^4.2.12",
- "@smithy/util-stream": "^4.5.21",
- "@smithy/util-utf8": "^4.2.2",
- tslib: "^2.6.2"
- },
- devDependencies: {
- "@smithy/snapshot-testing": "^2.0.4",
- "@tsconfig/node20": "20.1.8",
- "@types/node": "^20.14.8",
- concurrently: "7.0.0",
- "downlevel-dts": "0.10.1",
- premove: "4.0.0",
- typescript: "~5.8.3",
- vitest: "^4.0.17"
- },
- engines: {
- node: ">=20.0.0"
- },
- typesVersions: {
- "<4.5": {
- "dist-types/*": [
- "dist-types/ts3.4/*"
- ]
- }
- },
- files: [
- "dist-*/**"
- ],
- author: {
- name: "AWS SDK for JavaScript Team",
- url: "https://aws.amazon.com/javascript/"
- },
- license: "Apache-2.0",
- browser: {
- "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
- },
- "react-native": {
- "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
- },
- homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-bedrock-runtime",
- repository: {
- type: "git",
- url: "https://github.com/aws/aws-sdk-js-v3.git",
- directory: "clients/client-bedrock-runtime"
- }
- };
-});
-
-// node_modules/@aws-sdk/eventstream-handler-node/dist-es/EventSigningTransformStream.js
-import { Transform as Transform2 } from "stream";
-function getSignatureBinary(signature4) {
- const buf = Buffer.from(signature4, "hex");
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
-}
-var EventSigningTransformStream;
-var init_EventSigningTransformStream = __esm(() => {
- EventSigningTransformStream = class EventSigningTransformStream extends Transform2 {
- priorSignature;
- messageSigner;
- eventStreamCodec;
- systemClockOffsetProvider;
- constructor(options2) {
- super({
- autoDestroy: true,
- readableObjectMode: true,
- writableObjectMode: true,
- ...options2
- });
- this.priorSignature = options2.priorSignature;
- this.eventStreamCodec = options2.eventStreamCodec;
- this.messageSigner = options2.messageSigner;
- this.systemClockOffsetProvider = options2.systemClockOffsetProvider;
- }
- async _transform(chunk, encoding, callback) {
- try {
- const now = new Date(Date.now() + await this.systemClockOffsetProvider());
- const dateHeader = {
- ":date": { type: "timestamp", value: now }
- };
- const signedMessage = await this.messageSigner.sign({
- message: {
- body: chunk,
- headers: dateHeader
- },
- priorSignature: this.priorSignature
- }, {
- signingDate: now
- });
- this.priorSignature = signedMessage.signature;
- const serializedSigned = this.eventStreamCodec.encode({
- headers: {
- ...dateHeader,
- ":chunk-signature": {
- type: "binary",
- value: getSignatureBinary(signedMessage.signature)
- }
- },
- body: chunk
- });
- this.push(serializedSigned);
- return callback();
- } catch (err) {
- callback(err);
- }
- }
- };
-});
-
-// node_modules/@aws-sdk/eventstream-handler-node/dist-es/EventStreamPayloadHandler.js
-import { PassThrough as PassThrough2, pipeline, Readable as Readable5 } from "stream";
-
-class EventStreamPayloadHandler {
- messageSigner;
- eventStreamCodec;
- systemClockOffsetProvider;
- constructor(options2) {
- this.messageSigner = options2.messageSigner;
- this.eventStreamCodec = new EventStreamCodec(options2.utf8Encoder, options2.utf8Decoder);
- this.systemClockOffsetProvider = async () => options2.systemClockOffset ?? 0;
- }
- async handle(next, args, context = {}) {
- const request2 = args.request;
- const { body: payload, query } = request2;
- if (!(payload instanceof Readable5)) {
- throw new Error("Eventstream payload must be a Readable stream.");
- }
- const payloadStream = payload;
- request2.body = new PassThrough2({
- objectMode: true
- });
- const match = request2.headers?.authorization?.match(/Signature=([\w]+)$/);
- let priorSignature = match?.[1] ?? query?.["X-Amz-Signature"] ?? "";
- if (context.__staticSignature) {
- priorSignature = "";
- }
- const signingStream = new EventSigningTransformStream({
- priorSignature,
- eventStreamCodec: this.eventStreamCodec,
- messageSigner: await this.messageSigner(),
- systemClockOffsetProvider: this.systemClockOffsetProvider
- });
- let resolvePipeline;
- const pipelineError = new Promise((resolve9, reject) => {
- resolvePipeline = () => resolve9(undefined);
- pipeline(payloadStream, signingStream, request2.body, (err) => {
- if (err) {
- reject(new Error(`Pipeline error in @aws-sdk/eventstream-handler-node: ${err.message}`, { cause: err }));
- }
- });
- });
- let result;
- try {
- result = await Promise.race([next(args), pipelineError]);
- } catch (e2) {
- request2.body.end();
- throw e2;
- } finally {
- resolvePipeline();
- }
- return result;
- }
-}
-var init_EventStreamPayloadHandler = __esm(() => {
- init_dist_es26();
- init_EventSigningTransformStream();
-});
-
-// node_modules/@aws-sdk/eventstream-handler-node/dist-es/eventStreamPayloadHandlerProvider.js
-var eventStreamPayloadHandlerProvider2 = (options2) => new EventStreamPayloadHandler(options2);
-var init_eventStreamPayloadHandlerProvider2 = __esm(() => {
- init_EventStreamPayloadHandler();
-});
-
-// node_modules/@aws-sdk/eventstream-handler-node/dist-es/index.js
-var init_dist_es32 = __esm(() => {
- init_eventStreamPayloadHandlerProvider2();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-es/getChunkedStream.js
-function getChunkedStream(source) {
- let currentMessageTotalLength = 0;
- let currentMessagePendingLength = 0;
- let currentMessage = null;
- let messageLengthBuffer = null;
- const allocateMessage = (size) => {
- if (typeof size !== "number") {
- throw new Error("Attempted to allocate an event message where size was not a number: " + size);
- }
- currentMessageTotalLength = size;
- currentMessagePendingLength = 4;
- currentMessage = new Uint8Array(size);
- const currentMessageView = new DataView(currentMessage.buffer);
- currentMessageView.setUint32(0, size, false);
- };
- const iterator2 = async function* () {
- const sourceIterator = source[Symbol.asyncIterator]();
- while (true) {
- const { value, done } = await sourceIterator.next();
- if (done) {
- if (!currentMessageTotalLength) {
- return;
- } else if (currentMessageTotalLength === currentMessagePendingLength) {
- yield currentMessage;
- } else {
- throw new Error("Truncated event message received.");
- }
- return;
- }
- const chunkLength = value.length;
- let currentOffset = 0;
- while (currentOffset < chunkLength) {
- if (!currentMessage) {
- const bytesRemaining = chunkLength - currentOffset;
- if (!messageLengthBuffer) {
- messageLengthBuffer = new Uint8Array(4);
- }
- const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining);
- messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength);
- currentMessagePendingLength += numBytesForTotal;
- currentOffset += numBytesForTotal;
- if (currentMessagePendingLength < 4) {
- break;
- }
- allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false));
- messageLengthBuffer = null;
- }
- const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset);
- currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength);
- currentMessagePendingLength += numBytesToWrite;
- currentOffset += numBytesToWrite;
- if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) {
- yield currentMessage;
- currentMessage = null;
- currentMessageTotalLength = 0;
- currentMessagePendingLength = 0;
- }
- }
- }
- };
- return {
- [Symbol.asyncIterator]: iterator2
- };
-}
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-es/getUnmarshalledStream.js
-function getMessageUnmarshaller(deserializer, toUtf83) {
- return async function(message) {
- const { value: messageType } = message.headers[":message-type"];
- if (messageType === "error") {
- const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError");
- unmodeledError.name = message.headers[":error-code"].value;
- throw unmodeledError;
- } else if (messageType === "exception") {
- const code = message.headers[":exception-type"].value;
- const exception = { [code]: message };
- const deserializedException = await deserializer(exception);
- if (deserializedException.$unknown) {
- const error40 = new Error(toUtf83(message.body));
- error40.name = code;
- throw error40;
- }
- throw deserializedException[code];
- } else if (messageType === "event") {
- const event = {
- [message.headers[":event-type"].value]: message
- };
- const deserialized = await deserializer(event);
- if (deserialized.$unknown)
- return;
- return deserialized;
- } else {
- throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`);
- }
- };
-}
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-es/EventStreamMarshaller.js
-class EventStreamMarshaller {
- eventStreamCodec;
- utfEncoder;
- constructor({ utf8Encoder, utf8Decoder }) {
- this.eventStreamCodec = new EventStreamCodec(utf8Encoder, utf8Decoder);
- this.utfEncoder = utf8Encoder;
- }
- deserialize(body, deserializer) {
- const inputStream = getChunkedStream(body);
- return new SmithyMessageDecoderStream({
- messageStream: new MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }),
- deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder)
- });
- }
- serialize(inputStream, serializer) {
- return new MessageEncoderStream({
- messageStream: new SmithyMessageEncoderStream({ inputStream, serializer }),
- encoder: this.eventStreamCodec,
- includeEndFrame: true
- });
- }
-}
-var init_EventStreamMarshaller = __esm(() => {
- init_dist_es26();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-es/provider.js
-var init_provider = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-es/index.js
-var init_dist_es33 = __esm(() => {
- init_EventStreamMarshaller();
- init_provider();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/dist-es/utils.js
-async function* readabletoIterable(readStream2) {
- let streamEnded = false;
- let generationEnded = false;
- const records = new Array;
- readStream2.on("error", (err) => {
- if (!streamEnded) {
- streamEnded = true;
- }
- if (err) {
- throw err;
- }
- });
- readStream2.on("data", (data) => {
- records.push(data);
- });
- readStream2.on("end", () => {
- streamEnded = true;
- });
- while (!generationEnded) {
- const value = await new Promise((resolve9) => setTimeout(() => resolve9(records.shift()), 0));
- if (value) {
- yield value;
- }
- generationEnded = streamEnded && records.length === 0;
- }
-}
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/dist-es/EventStreamMarshaller.js
-import { Readable as Readable6 } from "stream";
-
-class EventStreamMarshaller3 {
- universalMarshaller;
- constructor({ utf8Encoder, utf8Decoder }) {
- this.universalMarshaller = new EventStreamMarshaller({
- utf8Decoder,
- utf8Encoder
- });
- }
- deserialize(body, deserializer) {
- const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body);
- return this.universalMarshaller.deserialize(bodyIterable, deserializer);
- }
- serialize(input, serializer) {
- return Readable6.from(this.universalMarshaller.serialize(input, serializer));
- }
-}
-var init_EventStreamMarshaller2 = __esm(() => {
- init_dist_es33();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/dist-es/provider.js
-var eventStreamSerdeProvider = (options2) => new EventStreamMarshaller3(options2);
-var init_provider2 = __esm(() => {
- init_EventStreamMarshaller2();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/dist-es/index.js
-var init_dist_es34 = __esm(() => {
- init_EventStreamMarshaller2();
- init_provider2();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-es/index.js
-var isArrayBuffer5 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-es/index.js
-import { Buffer as Buffer10 } from "buffer";
-var fromArrayBuffer3 = (input, offset = 0, length = input.byteLength - offset) => {
- if (!isArrayBuffer5(input)) {
- throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
- }
- return Buffer10.from(input, offset, length);
-}, fromString3 = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? Buffer10.from(input, encoding) : Buffer10.from(input);
-};
-var init_dist_es35 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-es/fromBase64.js
-var BASE64_REGEX2, fromBase643 = (input) => {
- if (input.length * 3 % 4 !== 0) {
- throw new TypeError(`Incorrect padding on base64 string.`);
- }
- if (!BASE64_REGEX2.exec(input)) {
- throw new TypeError(`Invalid base64 string.`);
- }
- const buffer = fromString3(input, "base64");
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
-};
-var init_fromBase642 = __esm(() => {
- init_dist_es35();
- BASE64_REGEX2 = /^[A-Za-z0-9+/]*={0,2}$/;
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-es/toBase64.js
-var import_util_utf84, toBase643 = (_input) => {
- let input;
- if (typeof _input === "string") {
- input = import_util_utf84.fromUtf8(_input);
- } else {
- input = _input;
- }
- if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
- throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
- }
- return fromArrayBuffer3(input.buffer, input.byteOffset, input.byteLength).toString("base64");
-};
-var init_toBase642 = __esm(() => {
- init_dist_es35();
- import_util_utf84 = __toESM(require_dist_cjs17(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-es/index.js
-var init_dist_es36 = __esm(() => {
- init_fromBase642();
- init_toBase642();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/endpoint/ruleset.js
-var s2 = "required", t2 = "fn", u3 = "argv", v2 = "ref", a3 = true, b2 = "isSet", c6 = "booleanEquals", d2 = "error", e2 = "endpoint", f2 = "tree", g2 = "PartitionResult", h3, i3, j2, k2, l2, m2, n3, o3, p2, q2, r2, _data2, ruleSet2;
-var init_ruleset2 = __esm(() => {
- h3 = { [s2]: false, type: "string" };
- i3 = { [s2]: true, default: false, type: "boolean" };
- j2 = { [v2]: "Endpoint" };
- k2 = { [t2]: c6, [u3]: [{ [v2]: "UseFIPS" }, true] };
- l2 = { [t2]: c6, [u3]: [{ [v2]: "UseDualStack" }, true] };
- m2 = {};
- n3 = { [t2]: "getAttr", [u3]: [{ [v2]: g2 }, "supportsFIPS"] };
- o3 = { [t2]: c6, [u3]: [true, { [t2]: "getAttr", [u3]: [{ [v2]: g2 }, "supportsDualStack"] }] };
- p2 = [k2];
- q2 = [l2];
- r2 = [{ [v2]: "Region" }];
- _data2 = { version: "1.0", parameters: { Region: h3, UseDualStack: i3, UseFIPS: i3, Endpoint: h3 }, rules: [{ conditions: [{ [t2]: b2, [u3]: [j2] }], rules: [{ conditions: p2, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d2 }, { rules: [{ conditions: q2, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d2 }, { endpoint: { url: j2, properties: m2, headers: m2 }, type: e2 }], type: f2 }], type: f2 }, { rules: [{ conditions: [{ [t2]: b2, [u3]: r2 }], rules: [{ conditions: [{ [t2]: "aws.partition", [u3]: r2, assign: g2 }], rules: [{ conditions: [k2, l2], rules: [{ conditions: [{ [t2]: c6, [u3]: [a3, n3] }, o3], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m2, headers: m2 }, type: e2 }], type: f2 }], type: f2 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d2 }], type: f2 }, { conditions: p2, rules: [{ conditions: [{ [t2]: c6, [u3]: [n3, a3] }], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m2, headers: m2 }, type: e2 }], type: f2 }], type: f2 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d2 }], type: f2 }, { conditions: q2, rules: [{ conditions: [o3], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m2, headers: m2 }, type: e2 }], type: f2 }], type: f2 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d2 }], type: f2 }, { rules: [{ endpoint: { url: "https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}", properties: m2, headers: m2 }, type: e2 }], type: f2 }], type: f2 }], type: f2 }, { error: "Invalid Configuration: Missing Region", type: d2 }], type: f2 }] };
- ruleSet2 = _data2;
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/endpoint/endpointResolver.js
-var import_util_endpoints3, import_util_endpoints4, cache3, defaultEndpointResolver2 = (endpointParams, context = {}) => {
- return cache3.get(endpointParams, () => import_util_endpoints4.resolveEndpoint(ruleSet2, {
- endpointParams,
- logger: context.logger
- }));
-};
-var init_endpointResolver2 = __esm(() => {
- init_ruleset2();
- import_util_endpoints3 = __toESM(require_dist_cjs51(), 1);
- import_util_endpoints4 = __toESM(require_dist_cjs50(), 1);
- cache3 = new import_util_endpoints4.EndpointCache({
- size: 50,
- params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
- });
- import_util_endpoints4.customEndpointFunctions.aws = import_util_endpoints3.awsEndpointFunctions;
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/models/BedrockRuntimeServiceException.js
-var BedrockRuntimeServiceException;
-var init_BedrockRuntimeServiceException = __esm(() => {
- init_dist_es31();
- BedrockRuntimeServiceException = class BedrockRuntimeServiceException extends ServiceException3 {
- constructor(options2) {
- super(options2);
- Object.setPrototypeOf(this, BedrockRuntimeServiceException.prototype);
- }
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/models/errors.js
-var AccessDeniedException2, InternalServerException2, ThrottlingException2, ValidationException2, ConflictException2, ResourceNotFoundException2, ServiceQuotaExceededException2, ServiceUnavailableException2, ModelErrorException, ModelNotReadyException, ModelTimeoutException, ModelStreamErrorException;
-var init_errors5 = __esm(() => {
- init_BedrockRuntimeServiceException();
- AccessDeniedException2 = class AccessDeniedException2 extends BedrockRuntimeServiceException {
- name = "AccessDeniedException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "AccessDeniedException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, AccessDeniedException2.prototype);
- }
- };
- InternalServerException2 = class InternalServerException2 extends BedrockRuntimeServiceException {
- name = "InternalServerException";
- $fault = "server";
- constructor(opts) {
- super({
- name: "InternalServerException",
- $fault: "server",
- ...opts
- });
- Object.setPrototypeOf(this, InternalServerException2.prototype);
- }
- };
- ThrottlingException2 = class ThrottlingException2 extends BedrockRuntimeServiceException {
- name = "ThrottlingException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ThrottlingException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ThrottlingException2.prototype);
- }
- };
- ValidationException2 = class ValidationException2 extends BedrockRuntimeServiceException {
- name = "ValidationException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ValidationException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ValidationException2.prototype);
- }
- };
- ConflictException2 = class ConflictException2 extends BedrockRuntimeServiceException {
- name = "ConflictException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ConflictException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ConflictException2.prototype);
- }
- };
- ResourceNotFoundException2 = class ResourceNotFoundException2 extends BedrockRuntimeServiceException {
- name = "ResourceNotFoundException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ResourceNotFoundException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ResourceNotFoundException2.prototype);
- }
- };
- ServiceQuotaExceededException2 = class ServiceQuotaExceededException2 extends BedrockRuntimeServiceException {
- name = "ServiceQuotaExceededException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ServiceQuotaExceededException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ServiceQuotaExceededException2.prototype);
- }
- };
- ServiceUnavailableException2 = class ServiceUnavailableException2 extends BedrockRuntimeServiceException {
- name = "ServiceUnavailableException";
- $fault = "server";
- constructor(opts) {
- super({
- name: "ServiceUnavailableException",
- $fault: "server",
- ...opts
- });
- Object.setPrototypeOf(this, ServiceUnavailableException2.prototype);
- }
- };
- ModelErrorException = class ModelErrorException extends BedrockRuntimeServiceException {
- name = "ModelErrorException";
- $fault = "client";
- originalStatusCode;
- resourceName;
- constructor(opts) {
- super({
- name: "ModelErrorException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ModelErrorException.prototype);
- this.originalStatusCode = opts.originalStatusCode;
- this.resourceName = opts.resourceName;
- }
- };
- ModelNotReadyException = class ModelNotReadyException extends BedrockRuntimeServiceException {
- name = "ModelNotReadyException";
- $fault = "client";
- $retryable = {};
- constructor(opts) {
- super({
- name: "ModelNotReadyException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ModelNotReadyException.prototype);
- }
- };
- ModelTimeoutException = class ModelTimeoutException extends BedrockRuntimeServiceException {
- name = "ModelTimeoutException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ModelTimeoutException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ModelTimeoutException.prototype);
- }
- };
- ModelStreamErrorException = class ModelStreamErrorException extends BedrockRuntimeServiceException {
- name = "ModelStreamErrorException";
- $fault = "client";
- originalStatusCode;
- originalMessage;
- constructor(opts) {
- super({
- name: "ModelStreamErrorException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ModelStreamErrorException.prototype);
- this.originalStatusCode = opts.originalStatusCode;
- this.originalMessage = opts.originalMessage;
- }
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/schemas/schemas_0.js
-var import_schema6, _A = "Accept", _AB = "AudioBlock", _ADE2 = "AccessDeniedException", _AG = "ApplyGuardrail", _AGD = "AppliedGuardrailDetails", _AGR = "ApplyGuardrailRequest", _AGRp = "ApplyGuardrailResponse", _AIM = "AsyncInvokeMessage", _AIODC = "AsyncInvokeOutputDataConfig", _AIS = "AsyncInvokeSummary", _AISODC = "AsyncInvokeS3OutputDataConfig", _AISs = "AsyncInvokeSummaries", _AS = "AudioSource", _ATC = "AnyToolChoice", _ATCu = "AutoToolChoice", _B = "Body", _BIPP = "BidirectionalInputPayloadPart", _BOPP = "BidirectionalOutputPayloadPart", _C = "Citation", _CB = "ContentBlocks", _CBD = "ContentBlockDelta", _CBDE = "ContentBlockDeltaEvent", _CBS = "ContentBlockStart", _CBSE = "ContentBlockStartEvent", _CBSEo = "ContentBlockStopEvent", _CBo = "ContentBlock", _CC2 = "CitationsConfig", _CCB = "CitationsContentBlock", _CD = "CacheDetail", _CDL = "CacheDetailsList", _CDi = "CitationsDelta", _CE2 = "ConflictException", _CGC = "CitationGeneratedContent", _CGCL = "CitationGeneratedContentList", _CL = "CitationLocation", _CM = "ConverseMetrics", _CO = "ConverseOutput", _CPB = "CachePointBlock", _CR = "ConverseRequest", _CRo = "ConverseResponse", _CS = "ConverseStream", _CSC = "CitationSourceContent", _CSCD = "CitationSourceContentDelta", _CSCL = "CitationSourceContentList", _CSCLD = "CitationSourceContentListDelta", _CSM = "ConverseStreamMetrics", _CSME = "ConverseStreamMetadataEvent", _CSO = "ConverseStreamOutput", _CSR = "ConverseStreamRequest", _CSRo = "ConverseStreamResponse", _CST = "ConverseStreamTrace", _CT = "ConverseTrace", _CTI = "CountTokensInput", _CTR = "ConverseTokensRequest", _CTRo = "CountTokensRequest", _CTRou = "CountTokensResponse", _CT_ = "Content-Type", _CTo = "CountTokens", _Ci = "Citations", _Co = "Converse", _DB = "DocumentBlock", _DCB = "DocumentContentBlocks", _DCBo = "DocumentContentBlock", _DCL = "DocumentCharLocation", _DCLo = "DocumentChunkLocation", _DPL = "DocumentPageLocation", _DS = "DocumentSource", _EB = "ErrorBlock", _GA = "GuardrailAssessment", _GAI = "GetAsyncInvoke", _GAIR = "GetAsyncInvokeRequest", _GAIRe = "GetAsyncInvokeResponse", _GAL = "GuardrailAssessmentList", _GALM = "GuardrailAssessmentListMap", _GAM = "GuardrailAssessmentMap", _GARDSL = "GuardrailAutomatedReasoningDifferenceScenarioList", _GARF = "GuardrailAutomatedReasoningFinding", _GARFL = "GuardrailAutomatedReasoningFindingList", _GARIF = "GuardrailAutomatedReasoningImpossibleFinding", _GARIFu = "GuardrailAutomatedReasoningInvalidFinding", _GARITR = "GuardrailAutomatedReasoningInputTextReference", _GARITRL = "GuardrailAutomatedReasoningInputTextReferenceList", _GARLW = "GuardrailAutomatedReasoningLogicWarning", _GARNTF = "GuardrailAutomatedReasoningNoTranslationsFinding", _GARPA2 = "GuardrailAutomatedReasoningPolicyAssessment", _GARR = "GuardrailAutomatedReasoningRule", _GARRL = "GuardrailAutomatedReasoningRuleList", _GARS = "GuardrailAutomatedReasoningScenario", _GARSF = "GuardrailAutomatedReasoningSatisfiableFinding", _GARSL = "GuardrailAutomatedReasoningStatementList", _GARSLC = "GuardrailAutomatedReasoningStatementLogicContent", _GARSNLC = "GuardrailAutomatedReasoningStatementNaturalLanguageContent", _GARSu = "GuardrailAutomatedReasoningStatement", _GART = "GuardrailAutomatedReasoningTranslation", _GARTAF = "GuardrailAutomatedReasoningTranslationAmbiguousFinding", _GARTCF = "GuardrailAutomatedReasoningTooComplexFinding", _GARTL = "GuardrailAutomatedReasoningTranslationList", _GARTO = "GuardrailAutomatedReasoningTranslationOption", _GARTOL = "GuardrailAutomatedReasoningTranslationOptionList", _GARVF = "GuardrailAutomatedReasoningValidFinding", _GC2 = "GuardrailConfiguration", _GCB = "GuardrailContentBlock", _GCBL = "GuardrailContentBlockList", _GCCB = "GuardrailConverseContentBlock", _GCF2 = "GuardrailContentFilter", _GCFL = "GuardrailContentFilterList", _GCGF2 = "GuardrailContextualGroundingFilter", _GCGFu2 = "GuardrailContextualGroundingFilters", _GCGPA = "GuardrailContextualGroundingPolicyAssessment", _GCIB = "GuardrailConverseImageBlock", _GCIS = "GuardrailConverseImageSource", _GCPA = "GuardrailContentPolicyAssessment", _GCTB = "GuardrailConverseTextBlock", _GCW = "GuardrailCustomWord", _GCWL = "GuardrailCustomWordList", _GCu2 = "GuardrailCoverage", _GIB = "GuardrailImageBlock", _GIC = "GuardrailImageCoverage", _GIM2 = "GuardrailInvocationMetrics", _GIS = "GuardrailImageSource", _GMW2 = "GuardrailManagedWord", _GMWL2 = "GuardrailManagedWordList", _GOC = "GuardrailOutputContent", _GOCL = "GuardrailOutputContentList", _GPEF = "GuardrailPiiEntityFilter", _GPEFL = "GuardrailPiiEntityFilterList", _GRF = "GuardrailRegexFilter", _GRFL = "GuardrailRegexFilterList", _GSC = "GuardrailStreamConfiguration", _GSIPA = "GuardrailSensitiveInformationPolicyAssessment", _GT2 = "GuardrailTopic", _GTA2 = "GuardrailTraceAssessment", _GTB = "GuardrailTextBlock", _GTCC = "GuardrailTextCharactersCoverage", _GTL = "GuardrailTopicList", _GTPA = "GuardrailTopicPolicyAssessment", _GU = "GuardrailUsage", _GWPA = "GuardrailWordPolicyAssessment", _IB = "ImageBlock", _IBD = "ImageBlockDelta", _IBS = "ImageBlockStart", _IC = "InferenceConfiguration", _IM = "InvokeModel", _IMR = "InvokeModelRequest", _IMRn = "InvokeModelResponse", _IMTR = "InvokeModelTokensRequest", _IMWBS = "InvokeModelWithBidirectionalStream", _IMWBSI = "InvokeModelWithBidirectionalStreamInput", _IMWBSO = "InvokeModelWithBidirectionalStreamOutput", _IMWBSR = "InvokeModelWithBidirectionalStreamRequest", _IMWBSRn = "InvokeModelWithBidirectionalStreamResponse", _IMWRS = "InvokeModelWithResponseStream", _IMWRSR = "InvokeModelWithResponseStreamRequest", _IMWRSRn = "InvokeModelWithResponseStreamResponse", _IS = "ImageSource", _ISE2 = "InternalServerException", _JSD = "JsonSchemaDefinition", _LAI = "ListAsyncInvokes", _LAIR = "ListAsyncInvokesRequest", _LAIRi = "ListAsyncInvokesResponse", _M2 = "Message", _MEE = "ModelErrorException", _MIP = "ModelInputPayload", _MNRE = "ModelNotReadyException", _MSE = "MessageStartEvent", _MSEE = "ModelStreamErrorException", _MSEe = "MessageStopEvent", _MTE = "ModelTimeoutException", _Me = "Messages", _OC2 = "OutputConfig", _OF = "OutputFormat", _OFS = "OutputFormatStructure", _PB = "PartBody", _PC2 = "PerformanceConfiguration", _PP = "PayloadPart", _PRT = "PromptRouterTrace", _PVM = "PromptVariableMap", _PVV = "PromptVariableValues", _RCB = "ReasoningContentBlock", _RCBD = "ReasoningContentBlockDelta", _RM = "RequestMetadata", _RNFE2 = "ResourceNotFoundException", _RS2 = "ResponseStream", _RTB = "ReasoningTextBlock", _SAI = "StartAsyncInvoke", _SAIR = "StartAsyncInvokeRequest", _SAIRt = "StartAsyncInvokeResponse", _SCB = "SystemContentBlocks", _SCBy = "SystemContentBlock", _SL = "S3Location", _SQEE2 = "ServiceQuotaExceededException", _SRB = "SearchResultBlock", _SRCB = "SearchResultContentBlock", _SRCBe = "SearchResultContentBlocks", _SRL = "SearchResultLocation", _ST2 = "ServiceTier", _STC = "SpecificToolChoice", _STy = "SystemTool", _SUE2 = "ServiceUnavailableException", _T2 = "Tag", _TC = "ToolConfiguration", _TCo = "ToolChoice", _TE2 = "ThrottlingException", _TIS = "ToolInputSchema", _TL2 = "TagList", _TRB = "ToolResultBlock", _TRBD = "ToolResultBlocksDelta", _TRBDo = "ToolResultBlockDelta", _TRBS = "ToolResultBlockStart", _TRCB = "ToolResultContentBlocks", _TRCBo = "ToolResultContentBlock", _TS = "ToolSpecification", _TU = "TokenUsage", _TUB = "ToolUseBlock", _TUBD = "ToolUseBlockDelta", _TUBS = "ToolUseBlockStart", _To = "Tools", _Too = "Tool", _VB = "VideoBlock", _VE2 = "ValidationException", _VS = "VideoSource", _WL = "WebLocation", _XABA = "X-Amzn-Bedrock-Accept", _XABCT = "X-Amzn-Bedrock-Content-Type", _XABG = "X-Amzn-Bedrock-GuardrailIdentifier", _XABG_ = "X-Amzn-Bedrock-GuardrailVersion", _XABPL = "X-Amzn-Bedrock-PerformanceConfig-Latency", _XABST = "X-Amzn-Bedrock-Service-Tier", _XABT = "X-Amzn-Bedrock-Trace", _a3 = "action", _aGD = "appliedGuardrailDetails", _aIS = "asyncInvokeSummaries", _aMRF2 = "additionalModelRequestFields", _aMRFP = "additionalModelResponseFieldPaths", _aMRFd = "additionalModelResponseFields", _aR2 = "actionReason", _aRP2 = "automatedReasoningPolicy", _aRPU = "automatedReasoningPolicyUnits", _aRPu = "automatedReasoningPolicies", _ac2 = "accept", _an2 = "any", _as = "assessments", _au2 = "audio", _aut = "auto", _b = "bytes", _bO = "bucketOwner", _bo = "body", _c2 = "client", _cBD = "contentBlockDelta", _cBI = "contentBlockIndex", _cBS = "contentBlockStart", _cBSo = "contentBlockStop", _cC2 = "citationsContent", _cD2 = "cacheDetails", _cFS2 = "claimsFalseScenario", _cGP2 = "contextualGroundingPolicy", _cGPU = "contextualGroundingPolicyUnits", _cP2 = "contentPolicy", _cPIU = "contentPolicyImageUnits", _cPU = "contentPolicyUnits", _cPa = "cachePoint", _cR2 = "contradictingRules", _cRIT = "cacheReadInputTokens", _cRT2 = "clientRequestToken", _cT2 = "contentType", _cTS2 = "claimsTrueScenario", _cW = "customWords", _cWIT = "cacheWriteInputTokens", _ch = "chunk", _ci = "citations", _cit = "citation", _cl2 = "claims", _co2 = "content", _con2 = "context", _conf = "confidence", _conv = "converse", _d2 = "delta", _dC2 = "documentChar", _dCo = "documentChunk", _dI2 = "documentIndex", _dP = "documentPage", _dS2 = "differenceScenarios", _de2 = "detected", _des = "description", _do2 = "domain", _doc2 = "document", _e2 = "error", _eT2 = "endTime", _en2 = "enabled", _end = "end", _f2 = "format", _fM2 = "failureMessage", _fS = "filterStrength", _fi2 = "findings", _fil2 = "filters", _g2 = "guardrail", _gA2 = "guardrailArn", _gC2 = "guardrailCoverage", _gCu2 = "guardrailConfig", _gCua2 = "guardContent", _gI2 = "guardrailId", _gIu2 = "guardrailIdentifier", _gO = "guardrailOrigin", _gOu = "guardrailOwnership", _gPL = "guardrailProcessingLatency", _gV2 = "guardrailVersion", _gu = "guarded", _h2 = "http", _hE2 = "httpError", _hH2 = "httpHeader", _hQ2 = "httpQuery", _i2 = "input", _iA2 = "invocationArn", _iAn = "inputAssessment", _iC2 = "inferenceConfig", _iM2 = "invocationMetrics", _iMI = "invokedModelId", _iMn2 = "invokeModel", _iS2 = "inputSchema", _iSE = "internalServerException", _iT2 = "inputTokens", _id2 = "identifier", _im2 = "images", _ima = "image", _imp = "impossible", _in2 = "invalid", _j = "json", _jS2 = "jsonSchema", _k2 = "key", _kKI2 = "kmsKeyId", _l2 = "location", _lM = "latencyMs", _lMT2 = "lastModifiedTime", _lW2 = "logicWarning", _la2 = "latency", _lo2 = "logic", _m2 = "message", _mA2 = "modelArn", _mI2 = "modelId", _mIo2 = "modelInput", _mO = "modelOutput", _mR2 = "maxResults", _mS2 = "messageStart", _mSEE = "modelStreamErrorException", _mSe = "messageStop", _mT2 = "maxTokens", _mTE = "modelTimeoutException", _mWL2 = "managedWordLists", _ma = "match", _me2 = "messages", _met = "metrics", _meta = "metadata", _n2 = "name", _nL2 = "naturalLanguage", _nT2 = "nextToken", _nTo2 = "noTranslations", _o2 = "outputs", _oA2 = "outputAssessments", _oC2 = "outputConfig", _oDC2 = "outputDataConfig", _oM2 = "originalMessage", _oS2 = "outputScope", _oSC = "originalStatusCode", _oT2 = "outputTokens", _op2 = "options", _ou = "output", _p2 = "premises", _pC2 = "performanceConfig", _pCL = "performanceConfigLatency", _pE2 = "piiEntities", _pR = "promptRouter", _pV2 = "promptVariables", _pVA2 = "policyVersionArn", _q = "qualifiers", _r2 = "regex", _rC2 = "reasoningContent", _rCe2 = "redactedContent", _rM2 = "requestMetadata", _rN2 = "resourceName", _rT = "reasoningText", _re2 = "regexes", _ro = "role", _s2 = "smithy.ts.sdk.synthetic.com.amazonaws.bedrockruntime", _sB2 = "sortBy", _sC2 = "sourceContent", _sE2 = "statusEquals", _sIP2 = "sensitiveInformationPolicy", _sIPFU = "sensitiveInformationPolicyFreeUnits", _sIPU = "sensitiveInformationPolicyUnits", _sL2 = "s3Location", _sO2 = "sortOrder", _sODC2 = "s3OutputDataConfig", _sPM = "streamProcessingMode", _sR2 = "stopReason", _sRI = "searchResultIndex", _sRL = "searchResultLocation", _sRe = "searchResult", _sRu = "supportingRules", _sS2 = "stopSequences", _sT2 = "submitTime", _sTA2 = "submitTimeAfter", _sTB2 = "submitTimeBefore", _sTe = "serviceTier", _sTy = "systemTool", _sU2 = "s3Uri", _sUE = "serviceUnavailableException", _sa2 = "satisfiable", _sc2 = "score", _sch = "schema", _se2 = "server", _si = "signature", _so2 = "source", _st2 = "status", _sta2 = "start", _stat = "statements", _str = "stream", _stre = "streaming", _stri = "strict", _stru = "structure", _sy = "system", _t2 = "ttl", _tA2 = "translationAmbiguous", _tC2 = "toolConfig", _tCe2 = "textCharacters", _tCo2 = "toolChoice", _tCoo2 = "tooComplex", _tE2 = "throttlingException", _tF2 = "textFormat", _tP2 = "topicPolicy", _tPU = "topicPolicyUnits", _tPo2 = "topP", _tR2 = "toolResult", _tS = "toolSpec", _tT2 = "totalTokens", _tU = "toolUse", _tUI = "toolUseId", _ta2 = "tags", _te2 = "text", _tem2 = "temperature", _th2 = "threshold", _ti2 = "title", _to2 = "total", _too = "tools", _tool = "tool", _top = "topics", _tr2 = "trace", _tra = "translation", _tran = "translations", _ty2 = "type", _u2 = "usage", _uC2 = "untranslatedClaims", _uP2 = "untranslatedPremises", _ur2 = "uri", _url2 = "url", _v2 = "value", _vE = "validationException", _va2 = "valid", _vi = "video", _w2 = "web", _wP2 = "wordPolicy", _wPU = "wordPolicyUnits", n02 = "com.amazonaws.bedrockruntime", _s_registry2, BedrockRuntimeServiceException$, n0_registry2, AccessDeniedException$2, ConflictException$2, InternalServerException$2, ModelErrorException$, ModelNotReadyException$, ModelStreamErrorException$, ModelTimeoutException$, ResourceNotFoundException$2, ServiceQuotaExceededException$2, ServiceUnavailableException$2, ThrottlingException$2, ValidationException$2, errorTypeRegistries2, AsyncInvokeMessage, Body, GuardrailAutomatedReasoningStatementLogicContent, GuardrailAutomatedReasoningStatementNaturalLanguageContent, ModelInputPayload, PartBody, AnyToolChoice$, AppliedGuardrailDetails$, ApplyGuardrailRequest$, ApplyGuardrailResponse$, AsyncInvokeS3OutputDataConfig$, AsyncInvokeSummary$, AudioBlock$, AutoToolChoice$, BidirectionalInputPayloadPart$, BidirectionalOutputPayloadPart$, CacheDetail$, CachePointBlock$, Citation$, CitationsConfig$, CitationsContentBlock$, CitationsDelta$, CitationSourceContentDelta$, ContentBlockDeltaEvent$, ContentBlockStartEvent$, ContentBlockStopEvent$, ConverseMetrics$, ConverseRequest$, ConverseResponse$, ConverseStreamMetadataEvent$, ConverseStreamMetrics$, ConverseStreamRequest$, ConverseStreamResponse$, ConverseStreamTrace$, ConverseTokensRequest$, ConverseTrace$, CountTokensRequest$, CountTokensResponse$, DocumentBlock$, DocumentCharLocation$, DocumentChunkLocation$, DocumentPageLocation$, ErrorBlock$, GetAsyncInvokeRequest$, GetAsyncInvokeResponse$, GuardrailAssessment$, GuardrailAutomatedReasoningImpossibleFinding$, GuardrailAutomatedReasoningInputTextReference$, GuardrailAutomatedReasoningInvalidFinding$, GuardrailAutomatedReasoningLogicWarning$, GuardrailAutomatedReasoningNoTranslationsFinding$, GuardrailAutomatedReasoningPolicyAssessment$, GuardrailAutomatedReasoningRule$, GuardrailAutomatedReasoningSatisfiableFinding$, GuardrailAutomatedReasoningScenario$, GuardrailAutomatedReasoningStatement$, GuardrailAutomatedReasoningTooComplexFinding$, GuardrailAutomatedReasoningTranslation$, GuardrailAutomatedReasoningTranslationAmbiguousFinding$, GuardrailAutomatedReasoningTranslationOption$, GuardrailAutomatedReasoningValidFinding$, GuardrailConfiguration$2, GuardrailContentFilter$2, GuardrailContentPolicyAssessment$, GuardrailContextualGroundingFilter$2, GuardrailContextualGroundingPolicyAssessment$, GuardrailConverseImageBlock$, GuardrailConverseTextBlock$, GuardrailCoverage$, GuardrailCustomWord$, GuardrailImageBlock$, GuardrailImageCoverage$, GuardrailInvocationMetrics$, GuardrailManagedWord$, GuardrailOutputContent$, GuardrailPiiEntityFilter$, GuardrailRegexFilter$, GuardrailSensitiveInformationPolicyAssessment$, GuardrailStreamConfiguration$, GuardrailTextBlock$, GuardrailTextCharactersCoverage$, GuardrailTopic$2, GuardrailTopicPolicyAssessment$, GuardrailTraceAssessment$, GuardrailUsage$, GuardrailWordPolicyAssessment$, ImageBlock$, ImageBlockDelta$, ImageBlockStart$, InferenceConfiguration$, InvokeModelRequest$, InvokeModelResponse$, InvokeModelTokensRequest$, InvokeModelWithBidirectionalStreamRequest$, InvokeModelWithBidirectionalStreamResponse$, InvokeModelWithResponseStreamRequest$, InvokeModelWithResponseStreamResponse$, JsonSchemaDefinition$, ListAsyncInvokesRequest$, ListAsyncInvokesResponse$, Message$, MessageStartEvent$, MessageStopEvent$, OutputConfig$, OutputFormat$, PayloadPart$, PerformanceConfiguration$2, PromptRouterTrace$, ReasoningTextBlock$, S3Location$, SearchResultBlock$, SearchResultContentBlock$, SearchResultLocation$, ServiceTier$, SpecificToolChoice$, StartAsyncInvokeRequest$, StartAsyncInvokeResponse$, SystemTool$, Tag$2, TokenUsage$, ToolConfiguration$, ToolResultBlock$, ToolResultBlockStart$, ToolSpecification$, ToolUseBlock$, ToolUseBlockDelta$, ToolUseBlockStart$, VideoBlock$, WebLocation$, AdditionalModelResponseFieldPaths, AsyncInvokeSummaries, CacheDetailsList, CitationGeneratedContentList, Citations, CitationSourceContentList, CitationSourceContentListDelta, ContentBlocks, DocumentContentBlocks, GuardrailAssessmentList, GuardrailAutomatedReasoningDifferenceScenarioList, GuardrailAutomatedReasoningFindingList, GuardrailAutomatedReasoningInputTextReferenceList, GuardrailAutomatedReasoningRuleList, GuardrailAutomatedReasoningStatementList, GuardrailAutomatedReasoningTranslationList, GuardrailAutomatedReasoningTranslationOptionList, GuardrailContentBlockList, GuardrailContentFilterList, GuardrailContentQualifierList, GuardrailContextualGroundingFilters2, GuardrailConverseContentQualifierList, GuardrailCustomWordList, GuardrailManagedWordList, GuardrailOriginList, GuardrailOutputContentList, GuardrailPiiEntityFilterList, GuardrailRegexFilterList, GuardrailTopicList, Messages3, ModelOutputs, NonEmptyStringList, SearchResultContentBlocks, SystemContentBlocks, TagList2, ToolResultBlocksDelta, ToolResultContentBlocks, Tools, GuardrailAssessmentListMap, GuardrailAssessmentMap, PromptVariableMap, RequestMetadata, AsyncInvokeOutputDataConfig$, AudioSource$, CitationGeneratedContent$, CitationLocation$, CitationSourceContent$, ContentBlock$, ContentBlockDelta$, ContentBlockStart$, ConverseOutput$, ConverseStreamOutput$, CountTokensInput$, DocumentContentBlock$, DocumentSource$, GuardrailAutomatedReasoningFinding$, GuardrailContentBlock$, GuardrailConverseContentBlock$, GuardrailConverseImageSource$, GuardrailImageSource$, ImageSource$, InvokeModelWithBidirectionalStreamInput$, InvokeModelWithBidirectionalStreamOutput$, OutputFormatStructure$, PromptVariableValues$, ReasoningContentBlock$, ReasoningContentBlockDelta$, ResponseStream$, SystemContentBlock$, Tool$, ToolChoice$, ToolInputSchema$, ToolResultBlockDelta$, ToolResultContentBlock$, VideoSource$, ApplyGuardrail$, Converse$, ConverseStream$, CountTokens$, GetAsyncInvoke$, InvokeModel$, InvokeModelWithBidirectionalStream$, InvokeModelWithResponseStream$, ListAsyncInvokes$, StartAsyncInvoke$;
-var init_schemas_02 = __esm(() => {
- init_BedrockRuntimeServiceException();
- init_errors5();
- import_schema6 = __toESM(require_schema(), 1);
- _s_registry2 = import_schema6.TypeRegistry.for(_s2);
- BedrockRuntimeServiceException$ = [-3, _s2, "BedrockRuntimeServiceException", 0, [], []];
- _s_registry2.registerError(BedrockRuntimeServiceException$, BedrockRuntimeServiceException);
- n0_registry2 = import_schema6.TypeRegistry.for(n02);
- AccessDeniedException$2 = [
- -3,
- n02,
- _ADE2,
- { [_e2]: _c2, [_hE2]: 403 },
- [_m2],
- [0]
- ];
- n0_registry2.registerError(AccessDeniedException$2, AccessDeniedException2);
- ConflictException$2 = [
- -3,
- n02,
- _CE2,
- { [_e2]: _c2, [_hE2]: 400 },
- [_m2],
- [0]
- ];
- n0_registry2.registerError(ConflictException$2, ConflictException2);
- InternalServerException$2 = [
- -3,
- n02,
- _ISE2,
- { [_e2]: _se2, [_hE2]: 500 },
- [_m2],
- [0]
- ];
- n0_registry2.registerError(InternalServerException$2, InternalServerException2);
- ModelErrorException$ = [
- -3,
- n02,
- _MEE,
- { [_e2]: _c2, [_hE2]: 424 },
- [_m2, _oSC, _rN2],
- [0, 1, 0]
- ];
- n0_registry2.registerError(ModelErrorException$, ModelErrorException);
- ModelNotReadyException$ = [
- -3,
- n02,
- _MNRE,
- { [_e2]: _c2, [_hE2]: 429 },
- [_m2],
- [0]
- ];
- n0_registry2.registerError(ModelNotReadyException$, ModelNotReadyException);
- ModelStreamErrorException$ = [
- -3,
- n02,
- _MSEE,
- { [_e2]: _c2, [_hE2]: 424 },
- [_m2, _oSC, _oM2],
- [0, 1, 0]
- ];
- n0_registry2.registerError(ModelStreamErrorException$, ModelStreamErrorException);
- ModelTimeoutException$ = [
- -3,
- n02,
- _MTE,
- { [_e2]: _c2, [_hE2]: 408 },
- [_m2],
- [0]
- ];
- n0_registry2.registerError(ModelTimeoutException$, ModelTimeoutException);
- ResourceNotFoundException$2 = [
- -3,
- n02,
- _RNFE2,
- { [_e2]: _c2, [_hE2]: 404 },
- [_m2],
- [0]
- ];
- n0_registry2.registerError(ResourceNotFoundException$2, ResourceNotFoundException2);
- ServiceQuotaExceededException$2 = [
- -3,
- n02,
- _SQEE2,
- { [_e2]: _c2, [_hE2]: 400 },
- [_m2],
- [0]
- ];
- n0_registry2.registerError(ServiceQuotaExceededException$2, ServiceQuotaExceededException2);
- ServiceUnavailableException$2 = [
- -3,
- n02,
- _SUE2,
- { [_e2]: _se2, [_hE2]: 503 },
- [_m2],
- [0]
- ];
- n0_registry2.registerError(ServiceUnavailableException$2, ServiceUnavailableException2);
- ThrottlingException$2 = [
- -3,
- n02,
- _TE2,
- { [_e2]: _c2, [_hE2]: 429 },
- [_m2],
- [0]
- ];
- n0_registry2.registerError(ThrottlingException$2, ThrottlingException2);
- ValidationException$2 = [
- -3,
- n02,
- _VE2,
- { [_e2]: _c2, [_hE2]: 400 },
- [_m2],
- [0]
- ];
- n0_registry2.registerError(ValidationException$2, ValidationException2);
- errorTypeRegistries2 = [
- _s_registry2,
- n0_registry2
- ];
- AsyncInvokeMessage = [0, n02, _AIM, 8, 0];
- Body = [0, n02, _B, 8, 21];
- GuardrailAutomatedReasoningStatementLogicContent = [0, n02, _GARSLC, 8, 0];
- GuardrailAutomatedReasoningStatementNaturalLanguageContent = [0, n02, _GARSNLC, 8, 0];
- ModelInputPayload = [0, n02, _MIP, 8, 15];
- PartBody = [0, n02, _PB, 8, 21];
- AnyToolChoice$ = [
- 3,
- n02,
- _ATC,
- 0,
- [],
- []
- ];
- AppliedGuardrailDetails$ = [
- 3,
- n02,
- _AGD,
- 0,
- [_gI2, _gV2, _gA2, _gO, _gOu],
- [0, 0, 0, 64 | 0, 0]
- ];
- ApplyGuardrailRequest$ = [
- 3,
- n02,
- _AGR,
- 0,
- [_gIu2, _gV2, _so2, _co2, _oS2],
- [[0, 1], [0, 1], 0, [() => GuardrailContentBlockList, 0], 0],
- 4
- ];
- ApplyGuardrailResponse$ = [
- 3,
- n02,
- _AGRp,
- 0,
- [_u2, _a3, _o2, _as, _aR2, _gC2],
- [() => GuardrailUsage$, 0, () => GuardrailOutputContentList, [() => GuardrailAssessmentList, 0], 0, () => GuardrailCoverage$],
- 4
- ];
- AsyncInvokeS3OutputDataConfig$ = [
- 3,
- n02,
- _AISODC,
- 0,
- [_sU2, _kKI2, _bO],
- [0, 0, 0],
- 1
- ];
- AsyncInvokeSummary$ = [
- 3,
- n02,
- _AIS,
- 0,
- [_iA2, _mA2, _sT2, _oDC2, _cRT2, _st2, _fM2, _lMT2, _eT2],
- [0, 0, 5, () => AsyncInvokeOutputDataConfig$, 0, 0, [() => AsyncInvokeMessage, 0], 5, 5],
- 4
- ];
- AudioBlock$ = [
- 3,
- n02,
- _AB,
- 0,
- [_f2, _so2, _e2],
- [0, [() => AudioSource$, 0], [() => ErrorBlock$, 0]],
- 2
- ];
- AutoToolChoice$ = [
- 3,
- n02,
- _ATCu,
- 0,
- [],
- []
- ];
- BidirectionalInputPayloadPart$ = [
- 3,
- n02,
- _BIPP,
- 8,
- [_b],
- [[() => PartBody, 0]]
- ];
- BidirectionalOutputPayloadPart$ = [
- 3,
- n02,
- _BOPP,
- 8,
- [_b],
- [[() => PartBody, 0]]
- ];
- CacheDetail$ = [
- 3,
- n02,
- _CD,
- 0,
- [_t2, _iT2],
- [0, 1],
- 2
- ];
- CachePointBlock$ = [
- 3,
- n02,
- _CPB,
- 0,
- [_ty2, _t2],
- [0, 0],
- 1
- ];
- Citation$ = [
- 3,
- n02,
- _C,
- 0,
- [_ti2, _so2, _sC2, _l2],
- [0, 0, () => CitationSourceContentList, () => CitationLocation$]
- ];
- CitationsConfig$ = [
- 3,
- n02,
- _CC2,
- 0,
- [_en2],
- [2],
- 1
- ];
- CitationsContentBlock$ = [
- 3,
- n02,
- _CCB,
- 0,
- [_co2, _ci],
- [() => CitationGeneratedContentList, () => Citations]
- ];
- CitationsDelta$ = [
- 3,
- n02,
- _CDi,
- 0,
- [_ti2, _so2, _sC2, _l2],
- [0, 0, () => CitationSourceContentListDelta, () => CitationLocation$]
- ];
- CitationSourceContentDelta$ = [
- 3,
- n02,
- _CSCD,
- 0,
- [_te2],
- [0]
- ];
- ContentBlockDeltaEvent$ = [
- 3,
- n02,
- _CBDE,
- 0,
- [_d2, _cBI],
- [[() => ContentBlockDelta$, 0], 1],
- 2
- ];
- ContentBlockStartEvent$ = [
- 3,
- n02,
- _CBSE,
- 0,
- [_sta2, _cBI],
- [() => ContentBlockStart$, 1],
- 2
- ];
- ContentBlockStopEvent$ = [
- 3,
- n02,
- _CBSEo,
- 0,
- [_cBI],
- [1],
- 1
- ];
- ConverseMetrics$ = [
- 3,
- n02,
- _CM,
- 0,
- [_lM],
- [1],
- 1
- ];
- ConverseRequest$ = [
- 3,
- n02,
- _CR,
- 0,
- [_mI2, _me2, _sy, _iC2, _tC2, _gCu2, _aMRF2, _pV2, _aMRFP, _rM2, _pC2, _sTe, _oC2],
- [[0, 1], [() => Messages3, 0], [() => SystemContentBlocks, 0], () => InferenceConfiguration$, () => ToolConfiguration$, () => GuardrailConfiguration$2, 15, [() => PromptVariableMap, 0], 64 | 0, [() => RequestMetadata, 0], () => PerformanceConfiguration$2, () => ServiceTier$, [() => OutputConfig$, 0]],
- 1
- ];
- ConverseResponse$ = [
- 3,
- n02,
- _CRo,
- 0,
- [_ou, _sR2, _u2, _met, _aMRFd, _tr2, _pC2, _sTe],
- [[() => ConverseOutput$, 0], 0, () => TokenUsage$, () => ConverseMetrics$, 15, [() => ConverseTrace$, 0], () => PerformanceConfiguration$2, () => ServiceTier$],
- 4
- ];
- ConverseStreamMetadataEvent$ = [
- 3,
- n02,
- _CSME,
- 0,
- [_u2, _met, _tr2, _pC2, _sTe],
- [() => TokenUsage$, () => ConverseStreamMetrics$, [() => ConverseStreamTrace$, 0], () => PerformanceConfiguration$2, () => ServiceTier$],
- 2
- ];
- ConverseStreamMetrics$ = [
- 3,
- n02,
- _CSM,
- 0,
- [_lM],
- [1],
- 1
- ];
- ConverseStreamRequest$ = [
- 3,
- n02,
- _CSR,
- 0,
- [_mI2, _me2, _sy, _iC2, _tC2, _gCu2, _aMRF2, _pV2, _aMRFP, _rM2, _pC2, _sTe, _oC2],
- [[0, 1], [() => Messages3, 0], [() => SystemContentBlocks, 0], () => InferenceConfiguration$, () => ToolConfiguration$, () => GuardrailStreamConfiguration$, 15, [() => PromptVariableMap, 0], 64 | 0, [() => RequestMetadata, 0], () => PerformanceConfiguration$2, () => ServiceTier$, [() => OutputConfig$, 0]],
- 1
- ];
- ConverseStreamResponse$ = [
- 3,
- n02,
- _CSRo,
- 0,
- [_str],
- [[() => ConverseStreamOutput$, 16]]
- ];
- ConverseStreamTrace$ = [
- 3,
- n02,
- _CST,
- 0,
- [_g2, _pR],
- [[() => GuardrailTraceAssessment$, 0], () => PromptRouterTrace$]
- ];
- ConverseTokensRequest$ = [
- 3,
- n02,
- _CTR,
- 0,
- [_me2, _sy, _tC2, _aMRF2],
- [[() => Messages3, 0], [() => SystemContentBlocks, 0], () => ToolConfiguration$, 15]
- ];
- ConverseTrace$ = [
- 3,
- n02,
- _CT,
- 0,
- [_g2, _pR],
- [[() => GuardrailTraceAssessment$, 0], () => PromptRouterTrace$]
- ];
- CountTokensRequest$ = [
- 3,
- n02,
- _CTRo,
- 0,
- [_mI2, _i2],
- [[0, 1], [() => CountTokensInput$, 0]],
- 2
- ];
- CountTokensResponse$ = [
- 3,
- n02,
- _CTRou,
- 0,
- [_iT2],
- [1],
- 1
- ];
- DocumentBlock$ = [
- 3,
- n02,
- _DB,
- 0,
- [_n2, _so2, _f2, _con2, _ci],
- [0, () => DocumentSource$, 0, 0, () => CitationsConfig$],
- 2
- ];
- DocumentCharLocation$ = [
- 3,
- n02,
- _DCL,
- 0,
- [_dI2, _sta2, _end],
- [1, 1, 1]
- ];
- DocumentChunkLocation$ = [
- 3,
- n02,
- _DCLo,
- 0,
- [_dI2, _sta2, _end],
- [1, 1, 1]
- ];
- DocumentPageLocation$ = [
- 3,
- n02,
- _DPL,
- 0,
- [_dI2, _sta2, _end],
- [1, 1, 1]
- ];
- ErrorBlock$ = [
- 3,
- n02,
- _EB,
- 8,
- [_m2],
- [0]
- ];
- GetAsyncInvokeRequest$ = [
- 3,
- n02,
- _GAIR,
- 0,
- [_iA2],
- [[0, 1]],
- 1
- ];
- GetAsyncInvokeResponse$ = [
- 3,
- n02,
- _GAIRe,
- 0,
- [_iA2, _mA2, _st2, _sT2, _oDC2, _cRT2, _fM2, _lMT2, _eT2],
- [0, 0, 0, 5, () => AsyncInvokeOutputDataConfig$, 0, [() => AsyncInvokeMessage, 0], 5, 5],
- 5
- ];
- GuardrailAssessment$ = [
- 3,
- n02,
- _GA,
- 0,
- [_tP2, _cP2, _wP2, _sIP2, _cGP2, _aRP2, _iM2, _aGD],
- [() => GuardrailTopicPolicyAssessment$, () => GuardrailContentPolicyAssessment$, () => GuardrailWordPolicyAssessment$, () => GuardrailSensitiveInformationPolicyAssessment$, () => GuardrailContextualGroundingPolicyAssessment$, [() => GuardrailAutomatedReasoningPolicyAssessment$, 0], () => GuardrailInvocationMetrics$, () => AppliedGuardrailDetails$]
- ];
- GuardrailAutomatedReasoningImpossibleFinding$ = [
- 3,
- n02,
- _GARIF,
- 0,
- [_tra, _cR2, _lW2],
- [[() => GuardrailAutomatedReasoningTranslation$, 0], () => GuardrailAutomatedReasoningRuleList, [() => GuardrailAutomatedReasoningLogicWarning$, 0]]
- ];
- GuardrailAutomatedReasoningInputTextReference$ = [
- 3,
- n02,
- _GARITR,
- 0,
- [_te2],
- [[() => GuardrailAutomatedReasoningStatementNaturalLanguageContent, 0]]
- ];
- GuardrailAutomatedReasoningInvalidFinding$ = [
- 3,
- n02,
- _GARIFu,
- 0,
- [_tra, _cR2, _lW2],
- [[() => GuardrailAutomatedReasoningTranslation$, 0], () => GuardrailAutomatedReasoningRuleList, [() => GuardrailAutomatedReasoningLogicWarning$, 0]]
- ];
- GuardrailAutomatedReasoningLogicWarning$ = [
- 3,
- n02,
- _GARLW,
- 0,
- [_ty2, _p2, _cl2],
- [0, [() => GuardrailAutomatedReasoningStatementList, 0], [() => GuardrailAutomatedReasoningStatementList, 0]]
- ];
- GuardrailAutomatedReasoningNoTranslationsFinding$ = [
- 3,
- n02,
- _GARNTF,
- 0,
- [],
- []
- ];
- GuardrailAutomatedReasoningPolicyAssessment$ = [
- 3,
- n02,
- _GARPA2,
- 0,
- [_fi2],
- [[() => GuardrailAutomatedReasoningFindingList, 0]]
- ];
- GuardrailAutomatedReasoningRule$ = [
- 3,
- n02,
- _GARR,
- 0,
- [_id2, _pVA2],
- [0, 0]
- ];
- GuardrailAutomatedReasoningSatisfiableFinding$ = [
- 3,
- n02,
- _GARSF,
- 0,
- [_tra, _cTS2, _cFS2, _lW2],
- [[() => GuardrailAutomatedReasoningTranslation$, 0], [() => GuardrailAutomatedReasoningScenario$, 0], [() => GuardrailAutomatedReasoningScenario$, 0], [() => GuardrailAutomatedReasoningLogicWarning$, 0]]
- ];
- GuardrailAutomatedReasoningScenario$ = [
- 3,
- n02,
- _GARS,
- 0,
- [_stat],
- [[() => GuardrailAutomatedReasoningStatementList, 0]]
- ];
- GuardrailAutomatedReasoningStatement$ = [
- 3,
- n02,
- _GARSu,
- 0,
- [_lo2, _nL2],
- [[() => GuardrailAutomatedReasoningStatementLogicContent, 0], [() => GuardrailAutomatedReasoningStatementNaturalLanguageContent, 0]]
- ];
- GuardrailAutomatedReasoningTooComplexFinding$ = [
- 3,
- n02,
- _GARTCF,
- 0,
- [],
- []
- ];
- GuardrailAutomatedReasoningTranslation$ = [
- 3,
- n02,
- _GART,
- 0,
- [_p2, _cl2, _uP2, _uC2, _conf],
- [[() => GuardrailAutomatedReasoningStatementList, 0], [() => GuardrailAutomatedReasoningStatementList, 0], [() => GuardrailAutomatedReasoningInputTextReferenceList, 0], [() => GuardrailAutomatedReasoningInputTextReferenceList, 0], 1]
- ];
- GuardrailAutomatedReasoningTranslationAmbiguousFinding$ = [
- 3,
- n02,
- _GARTAF,
- 0,
- [_op2, _dS2],
- [[() => GuardrailAutomatedReasoningTranslationOptionList, 0], [() => GuardrailAutomatedReasoningDifferenceScenarioList, 0]]
- ];
- GuardrailAutomatedReasoningTranslationOption$ = [
- 3,
- n02,
- _GARTO,
- 0,
- [_tran],
- [[() => GuardrailAutomatedReasoningTranslationList, 0]]
- ];
- GuardrailAutomatedReasoningValidFinding$ = [
- 3,
- n02,
- _GARVF,
- 0,
- [_tra, _cTS2, _sRu, _lW2],
- [[() => GuardrailAutomatedReasoningTranslation$, 0], [() => GuardrailAutomatedReasoningScenario$, 0], () => GuardrailAutomatedReasoningRuleList, [() => GuardrailAutomatedReasoningLogicWarning$, 0]]
- ];
- GuardrailConfiguration$2 = [
- 3,
- n02,
- _GC2,
- 0,
- [_gIu2, _gV2, _tr2],
- [0, 0, 0]
- ];
- GuardrailContentFilter$2 = [
- 3,
- n02,
- _GCF2,
- 0,
- [_ty2, _conf, _a3, _fS, _de2],
- [0, 0, 0, 0, 2],
- 3
- ];
- GuardrailContentPolicyAssessment$ = [
- 3,
- n02,
- _GCPA,
- 0,
- [_fil2],
- [() => GuardrailContentFilterList],
- 1
- ];
- GuardrailContextualGroundingFilter$2 = [
- 3,
- n02,
- _GCGF2,
- 0,
- [_ty2, _th2, _sc2, _a3, _de2],
- [0, 1, 1, 0, 2],
- 4
- ];
- GuardrailContextualGroundingPolicyAssessment$ = [
- 3,
- n02,
- _GCGPA,
- 0,
- [_fil2],
- [() => GuardrailContextualGroundingFilters2]
- ];
- GuardrailConverseImageBlock$ = [
- 3,
- n02,
- _GCIB,
- 8,
- [_f2, _so2],
- [0, [() => GuardrailConverseImageSource$, 0]],
- 2
- ];
- GuardrailConverseTextBlock$ = [
- 3,
- n02,
- _GCTB,
- 0,
- [_te2, _q],
- [0, 64 | 0],
- 1
- ];
- GuardrailCoverage$ = [
- 3,
- n02,
- _GCu2,
- 0,
- [_tCe2, _im2],
- [() => GuardrailTextCharactersCoverage$, () => GuardrailImageCoverage$]
- ];
- GuardrailCustomWord$ = [
- 3,
- n02,
- _GCW,
- 0,
- [_ma, _a3, _de2],
- [0, 0, 2],
- 2
- ];
- GuardrailImageBlock$ = [
- 3,
- n02,
- _GIB,
- 8,
- [_f2, _so2],
- [0, [() => GuardrailImageSource$, 0]],
- 2
- ];
- GuardrailImageCoverage$ = [
- 3,
- n02,
- _GIC,
- 0,
- [_gu, _to2],
- [1, 1]
- ];
- GuardrailInvocationMetrics$ = [
- 3,
- n02,
- _GIM2,
- 0,
- [_gPL, _u2, _gC2],
- [1, () => GuardrailUsage$, () => GuardrailCoverage$]
- ];
- GuardrailManagedWord$ = [
- 3,
- n02,
- _GMW2,
- 0,
- [_ma, _ty2, _a3, _de2],
- [0, 0, 0, 2],
- 3
- ];
- GuardrailOutputContent$ = [
- 3,
- n02,
- _GOC,
- 0,
- [_te2],
- [0]
- ];
- GuardrailPiiEntityFilter$ = [
- 3,
- n02,
- _GPEF,
- 0,
- [_ma, _ty2, _a3, _de2],
- [0, 0, 0, 2],
- 3
- ];
- GuardrailRegexFilter$ = [
- 3,
- n02,
- _GRF,
- 0,
- [_a3, _n2, _ma, _r2, _de2],
- [0, 0, 0, 0, 2],
- 1
- ];
- GuardrailSensitiveInformationPolicyAssessment$ = [
- 3,
- n02,
- _GSIPA,
- 0,
- [_pE2, _re2],
- [() => GuardrailPiiEntityFilterList, () => GuardrailRegexFilterList],
- 2
- ];
- GuardrailStreamConfiguration$ = [
- 3,
- n02,
- _GSC,
- 0,
- [_gIu2, _gV2, _tr2, _sPM],
- [0, 0, 0, 0]
- ];
- GuardrailTextBlock$ = [
- 3,
- n02,
- _GTB,
- 0,
- [_te2, _q],
- [0, 64 | 0],
- 1
- ];
- GuardrailTextCharactersCoverage$ = [
- 3,
- n02,
- _GTCC,
- 0,
- [_gu, _to2],
- [1, 1]
- ];
- GuardrailTopic$2 = [
- 3,
- n02,
- _GT2,
- 0,
- [_n2, _ty2, _a3, _de2],
- [0, 0, 0, 2],
- 3
- ];
- GuardrailTopicPolicyAssessment$ = [
- 3,
- n02,
- _GTPA,
- 0,
- [_top],
- [() => GuardrailTopicList],
- 1
- ];
- GuardrailTraceAssessment$ = [
- 3,
- n02,
- _GTA2,
- 0,
- [_mO, _iAn, _oA2, _aR2],
- [64 | 0, [() => GuardrailAssessmentMap, 0], [() => GuardrailAssessmentListMap, 0], 0]
- ];
- GuardrailUsage$ = [
- 3,
- n02,
- _GU,
- 0,
- [_tPU, _cPU, _wPU, _sIPU, _sIPFU, _cGPU, _cPIU, _aRPU, _aRPu],
- [1, 1, 1, 1, 1, 1, 1, 1, 1],
- 6
- ];
- GuardrailWordPolicyAssessment$ = [
- 3,
- n02,
- _GWPA,
- 0,
- [_cW, _mWL2],
- [() => GuardrailCustomWordList, () => GuardrailManagedWordList],
- 2
- ];
- ImageBlock$ = [
- 3,
- n02,
- _IB,
- 0,
- [_f2, _so2, _e2],
- [0, [() => ImageSource$, 0], [() => ErrorBlock$, 0]],
- 2
- ];
- ImageBlockDelta$ = [
- 3,
- n02,
- _IBD,
- 0,
- [_so2, _e2],
- [[() => ImageSource$, 0], [() => ErrorBlock$, 0]]
- ];
- ImageBlockStart$ = [
- 3,
- n02,
- _IBS,
- 0,
- [_f2],
- [0],
- 1
- ];
- InferenceConfiguration$ = [
- 3,
- n02,
- _IC,
- 0,
- [_mT2, _tem2, _tPo2, _sS2],
- [1, 1, 1, 64 | 0]
- ];
- InvokeModelRequest$ = [
- 3,
- n02,
- _IMR,
- 0,
- [_mI2, _bo, _cT2, _ac2, _tr2, _gIu2, _gV2, _pCL, _sTe],
- [[0, 1], [() => Body, 16], [0, { [_hH2]: _CT_ }], [0, { [_hH2]: _A }], [0, { [_hH2]: _XABT }], [0, { [_hH2]: _XABG }], [0, { [_hH2]: _XABG_ }], [0, { [_hH2]: _XABPL }], [0, { [_hH2]: _XABST }]],
- 1
- ];
- InvokeModelResponse$ = [
- 3,
- n02,
- _IMRn,
- 0,
- [_bo, _cT2, _pCL, _sTe],
- [[() => Body, 16], [0, { [_hH2]: _CT_ }], [0, { [_hH2]: _XABPL }], [0, { [_hH2]: _XABST }]],
- 2
- ];
- InvokeModelTokensRequest$ = [
- 3,
- n02,
- _IMTR,
- 0,
- [_bo],
- [[() => Body, 0]],
- 1
- ];
- InvokeModelWithBidirectionalStreamRequest$ = [
- 3,
- n02,
- _IMWBSR,
- 0,
- [_mI2, _bo],
- [[0, 1], [() => InvokeModelWithBidirectionalStreamInput$, 16]],
- 2
- ];
- InvokeModelWithBidirectionalStreamResponse$ = [
- 3,
- n02,
- _IMWBSRn,
- 0,
- [_bo],
- [[() => InvokeModelWithBidirectionalStreamOutput$, 16]],
- 1
- ];
- InvokeModelWithResponseStreamRequest$ = [
- 3,
- n02,
- _IMWRSR,
- 0,
- [_mI2, _bo, _cT2, _ac2, _tr2, _gIu2, _gV2, _pCL, _sTe],
- [[0, 1], [() => Body, 16], [0, { [_hH2]: _CT_ }], [0, { [_hH2]: _XABA }], [0, { [_hH2]: _XABT }], [0, { [_hH2]: _XABG }], [0, { [_hH2]: _XABG_ }], [0, { [_hH2]: _XABPL }], [0, { [_hH2]: _XABST }]],
- 1
- ];
- InvokeModelWithResponseStreamResponse$ = [
- 3,
- n02,
- _IMWRSRn,
- 0,
- [_bo, _cT2, _pCL, _sTe],
- [[() => ResponseStream$, 16], [0, { [_hH2]: _XABCT }], [0, { [_hH2]: _XABPL }], [0, { [_hH2]: _XABST }]],
- 2
- ];
- JsonSchemaDefinition$ = [
- 3,
- n02,
- _JSD,
- 0,
- [_sch, _n2, _des],
- [0, 0, 0],
- 1
- ];
- ListAsyncInvokesRequest$ = [
- 3,
- n02,
- _LAIR,
- 0,
- [_sTA2, _sTB2, _sE2, _mR2, _nT2, _sB2, _sO2],
- [[5, { [_hQ2]: _sTA2 }], [5, { [_hQ2]: _sTB2 }], [0, { [_hQ2]: _sE2 }], [1, { [_hQ2]: _mR2 }], [0, { [_hQ2]: _nT2 }], [0, { [_hQ2]: _sB2 }], [0, { [_hQ2]: _sO2 }]]
- ];
- ListAsyncInvokesResponse$ = [
- 3,
- n02,
- _LAIRi,
- 0,
- [_nT2, _aIS],
- [0, [() => AsyncInvokeSummaries, 0]]
- ];
- Message$ = [
- 3,
- n02,
- _M2,
- 0,
- [_ro, _co2],
- [0, [() => ContentBlocks, 0]],
- 2
- ];
- MessageStartEvent$ = [
- 3,
- n02,
- _MSE,
- 0,
- [_ro],
- [0],
- 1
- ];
- MessageStopEvent$ = [
- 3,
- n02,
- _MSEe,
- 0,
- [_sR2, _aMRFd],
- [0, 15],
- 1
- ];
- OutputConfig$ = [
- 3,
- n02,
- _OC2,
- 0,
- [_tF2],
- [[() => OutputFormat$, 0]]
- ];
- OutputFormat$ = [
- 3,
- n02,
- _OF,
- 0,
- [_ty2, _stru],
- [0, [() => OutputFormatStructure$, 0]],
- 2
- ];
- PayloadPart$ = [
- 3,
- n02,
- _PP,
- 8,
- [_b],
- [[() => PartBody, 0]]
- ];
- PerformanceConfiguration$2 = [
- 3,
- n02,
- _PC2,
- 0,
- [_la2],
- [0]
- ];
- PromptRouterTrace$ = [
- 3,
- n02,
- _PRT,
- 0,
- [_iMI],
- [0]
- ];
- ReasoningTextBlock$ = [
- 3,
- n02,
- _RTB,
- 8,
- [_te2, _si],
- [0, 0],
- 1
- ];
- S3Location$ = [
- 3,
- n02,
- _SL,
- 0,
- [_ur2, _bO],
- [0, 0],
- 1
- ];
- SearchResultBlock$ = [
- 3,
- n02,
- _SRB,
- 0,
- [_so2, _ti2, _co2, _ci],
- [0, 0, () => SearchResultContentBlocks, () => CitationsConfig$],
- 3
- ];
- SearchResultContentBlock$ = [
- 3,
- n02,
- _SRCB,
- 0,
- [_te2],
- [0],
- 1
- ];
- SearchResultLocation$ = [
- 3,
- n02,
- _SRL,
- 0,
- [_sRI, _sta2, _end],
- [1, 1, 1]
- ];
- ServiceTier$ = [
- 3,
- n02,
- _ST2,
- 0,
- [_ty2],
- [0],
- 1
- ];
- SpecificToolChoice$ = [
- 3,
- n02,
- _STC,
- 0,
- [_n2],
- [0],
- 1
- ];
- StartAsyncInvokeRequest$ = [
- 3,
- n02,
- _SAIR,
- 0,
- [_mI2, _mIo2, _oDC2, _cRT2, _ta2],
- [0, [() => ModelInputPayload, 0], () => AsyncInvokeOutputDataConfig$, [0, 4], () => TagList2],
- 3
- ];
- StartAsyncInvokeResponse$ = [
- 3,
- n02,
- _SAIRt,
- 0,
- [_iA2],
- [0],
- 1
- ];
- SystemTool$ = [
- 3,
- n02,
- _STy,
- 0,
- [_n2],
- [0],
- 1
- ];
- Tag$2 = [
- 3,
- n02,
- _T2,
- 0,
- [_k2, _v2],
- [0, 0],
- 2
- ];
- TokenUsage$ = [
- 3,
- n02,
- _TU,
- 0,
- [_iT2, _oT2, _tT2, _cRIT, _cWIT, _cD2],
- [1, 1, 1, 1, 1, () => CacheDetailsList],
- 3
- ];
- ToolConfiguration$ = [
- 3,
- n02,
- _TC,
- 0,
- [_too, _tCo2],
- [() => Tools, () => ToolChoice$],
- 1
- ];
- ToolResultBlock$ = [
- 3,
- n02,
- _TRB,
- 0,
- [_tUI, _co2, _st2, _ty2],
- [0, [() => ToolResultContentBlocks, 0], 0, 0],
- 2
- ];
- ToolResultBlockStart$ = [
- 3,
- n02,
- _TRBS,
- 0,
- [_tUI, _ty2, _st2],
- [0, 0, 0],
- 1
- ];
- ToolSpecification$ = [
- 3,
- n02,
- _TS,
- 0,
- [_n2, _iS2, _des, _stri],
- [0, () => ToolInputSchema$, 0, 2],
- 2
- ];
- ToolUseBlock$ = [
- 3,
- n02,
- _TUB,
- 0,
- [_tUI, _n2, _i2, _ty2],
- [0, 0, 15, 0],
- 3
- ];
- ToolUseBlockDelta$ = [
- 3,
- n02,
- _TUBD,
- 0,
- [_i2],
- [0],
- 1
- ];
- ToolUseBlockStart$ = [
- 3,
- n02,
- _TUBS,
- 0,
- [_tUI, _n2, _ty2],
- [0, 0, 0],
- 2
- ];
- VideoBlock$ = [
- 3,
- n02,
- _VB,
- 0,
- [_f2, _so2],
- [0, () => VideoSource$],
- 2
- ];
- WebLocation$ = [
- 3,
- n02,
- _WL,
- 0,
- [_url2, _do2],
- [0, 0]
- ];
- AdditionalModelResponseFieldPaths = 64 | 0;
- AsyncInvokeSummaries = [
- 1,
- n02,
- _AISs,
- 0,
- [
- () => AsyncInvokeSummary$,
- 0
- ]
- ];
- CacheDetailsList = [
- 1,
- n02,
- _CDL,
- 0,
- () => CacheDetail$
- ];
- CitationGeneratedContentList = [
- 1,
- n02,
- _CGCL,
- 0,
- () => CitationGeneratedContent$
- ];
- Citations = [
- 1,
- n02,
- _Ci,
- 0,
- () => Citation$
- ];
- CitationSourceContentList = [
- 1,
- n02,
- _CSCL,
- 0,
- () => CitationSourceContent$
- ];
- CitationSourceContentListDelta = [
- 1,
- n02,
- _CSCLD,
- 0,
- () => CitationSourceContentDelta$
- ];
- ContentBlocks = [
- 1,
- n02,
- _CB,
- 0,
- [
- () => ContentBlock$,
- 0
- ]
- ];
- DocumentContentBlocks = [
- 1,
- n02,
- _DCB,
- 0,
- () => DocumentContentBlock$
- ];
- GuardrailAssessmentList = [
- 1,
- n02,
- _GAL,
- 0,
- [
- () => GuardrailAssessment$,
- 0
- ]
- ];
- GuardrailAutomatedReasoningDifferenceScenarioList = [
- 1,
- n02,
- _GARDSL,
- 0,
- [
- () => GuardrailAutomatedReasoningScenario$,
- 0
- ]
- ];
- GuardrailAutomatedReasoningFindingList = [
- 1,
- n02,
- _GARFL,
- 0,
- [
- () => GuardrailAutomatedReasoningFinding$,
- 0
- ]
- ];
- GuardrailAutomatedReasoningInputTextReferenceList = [
- 1,
- n02,
- _GARITRL,
- 0,
- [
- () => GuardrailAutomatedReasoningInputTextReference$,
- 0
- ]
- ];
- GuardrailAutomatedReasoningRuleList = [
- 1,
- n02,
- _GARRL,
- 0,
- () => GuardrailAutomatedReasoningRule$
- ];
- GuardrailAutomatedReasoningStatementList = [
- 1,
- n02,
- _GARSL,
- 0,
- [
- () => GuardrailAutomatedReasoningStatement$,
- 0
- ]
- ];
- GuardrailAutomatedReasoningTranslationList = [
- 1,
- n02,
- _GARTL,
- 0,
- [
- () => GuardrailAutomatedReasoningTranslation$,
- 0
- ]
- ];
- GuardrailAutomatedReasoningTranslationOptionList = [
- 1,
- n02,
- _GARTOL,
- 0,
- [
- () => GuardrailAutomatedReasoningTranslationOption$,
- 0
- ]
- ];
- GuardrailContentBlockList = [
- 1,
- n02,
- _GCBL,
- 0,
- [
- () => GuardrailContentBlock$,
- 0
- ]
- ];
- GuardrailContentFilterList = [
- 1,
- n02,
- _GCFL,
- 0,
- () => GuardrailContentFilter$2
- ];
- GuardrailContentQualifierList = 64 | 0;
- GuardrailContextualGroundingFilters2 = [
- 1,
- n02,
- _GCGFu2,
- 0,
- () => GuardrailContextualGroundingFilter$2
- ];
- GuardrailConverseContentQualifierList = 64 | 0;
- GuardrailCustomWordList = [
- 1,
- n02,
- _GCWL,
- 0,
- () => GuardrailCustomWord$
- ];
- GuardrailManagedWordList = [
- 1,
- n02,
- _GMWL2,
- 0,
- () => GuardrailManagedWord$
- ];
- GuardrailOriginList = 64 | 0;
- GuardrailOutputContentList = [
- 1,
- n02,
- _GOCL,
- 0,
- () => GuardrailOutputContent$
- ];
- GuardrailPiiEntityFilterList = [
- 1,
- n02,
- _GPEFL,
- 0,
- () => GuardrailPiiEntityFilter$
- ];
- GuardrailRegexFilterList = [
- 1,
- n02,
- _GRFL,
- 0,
- () => GuardrailRegexFilter$
- ];
- GuardrailTopicList = [
- 1,
- n02,
- _GTL,
- 0,
- () => GuardrailTopic$2
- ];
- Messages3 = [
- 1,
- n02,
- _Me,
- 0,
- [
- () => Message$,
- 0
- ]
- ];
- ModelOutputs = 64 | 0;
- NonEmptyStringList = 64 | 0;
- SearchResultContentBlocks = [
- 1,
- n02,
- _SRCBe,
- 0,
- () => SearchResultContentBlock$
- ];
- SystemContentBlocks = [
- 1,
- n02,
- _SCB,
- 0,
- [
- () => SystemContentBlock$,
- 0
- ]
- ];
- TagList2 = [
- 1,
- n02,
- _TL2,
- 0,
- () => Tag$2
- ];
- ToolResultBlocksDelta = [
- 1,
- n02,
- _TRBD,
- 0,
- () => ToolResultBlockDelta$
- ];
- ToolResultContentBlocks = [
- 1,
- n02,
- _TRCB,
- 0,
- [
- () => ToolResultContentBlock$,
- 0
- ]
- ];
- Tools = [
- 1,
- n02,
- _To,
- 0,
- () => Tool$
- ];
- GuardrailAssessmentListMap = [
- 2,
- n02,
- _GALM,
- 0,
- [
- 0,
- 0
- ],
- [
- () => GuardrailAssessmentList,
- 0
- ]
- ];
- GuardrailAssessmentMap = [
- 2,
- n02,
- _GAM,
- 0,
- [
- 0,
- 0
- ],
- [
- () => GuardrailAssessment$,
- 0
- ]
- ];
- PromptVariableMap = [
- 2,
- n02,
- _PVM,
- 8,
- 0,
- () => PromptVariableValues$
- ];
- RequestMetadata = [
- 2,
- n02,
- _RM,
- 8,
- 0,
- 0
- ];
- AsyncInvokeOutputDataConfig$ = [
- 4,
- n02,
- _AIODC,
- 0,
- [_sODC2],
- [() => AsyncInvokeS3OutputDataConfig$]
- ];
- AudioSource$ = [
- 4,
- n02,
- _AS,
- 8,
- [_b, _sL2],
- [21, () => S3Location$]
- ];
- CitationGeneratedContent$ = [
- 4,
- n02,
- _CGC,
- 0,
- [_te2],
- [0]
- ];
- CitationLocation$ = [
- 4,
- n02,
- _CL,
- 0,
- [_w2, _dC2, _dP, _dCo, _sRL],
- [() => WebLocation$, () => DocumentCharLocation$, () => DocumentPageLocation$, () => DocumentChunkLocation$, () => SearchResultLocation$]
- ];
- CitationSourceContent$ = [
- 4,
- n02,
- _CSC,
- 0,
- [_te2],
- [0]
- ];
- ContentBlock$ = [
- 4,
- n02,
- _CBo,
- 0,
- [_te2, _ima, _doc2, _vi, _au2, _tU, _tR2, _gCua2, _cPa, _rC2, _cC2, _sRe],
- [0, [() => ImageBlock$, 0], () => DocumentBlock$, () => VideoBlock$, [() => AudioBlock$, 0], () => ToolUseBlock$, [() => ToolResultBlock$, 0], [() => GuardrailConverseContentBlock$, 0], () => CachePointBlock$, [() => ReasoningContentBlock$, 0], () => CitationsContentBlock$, () => SearchResultBlock$]
- ];
- ContentBlockDelta$ = [
- 4,
- n02,
- _CBD,
- 0,
- [_te2, _tU, _tR2, _rC2, _cit, _ima],
- [0, () => ToolUseBlockDelta$, () => ToolResultBlocksDelta, [() => ReasoningContentBlockDelta$, 0], () => CitationsDelta$, [() => ImageBlockDelta$, 0]]
- ];
- ContentBlockStart$ = [
- 4,
- n02,
- _CBS,
- 0,
- [_tU, _tR2, _ima],
- [() => ToolUseBlockStart$, () => ToolResultBlockStart$, () => ImageBlockStart$]
- ];
- ConverseOutput$ = [
- 4,
- n02,
- _CO,
- 0,
- [_m2],
- [[() => Message$, 0]]
- ];
- ConverseStreamOutput$ = [
- 4,
- n02,
- _CSO,
- { [_stre]: 1 },
- [_mS2, _cBS, _cBD, _cBSo, _mSe, _meta, _iSE, _mSEE, _vE, _tE2, _sUE],
- [() => MessageStartEvent$, () => ContentBlockStartEvent$, [() => ContentBlockDeltaEvent$, 0], () => ContentBlockStopEvent$, () => MessageStopEvent$, [() => ConverseStreamMetadataEvent$, 0], [() => InternalServerException$2, 0], [() => ModelStreamErrorException$, 0], [() => ValidationException$2, 0], [() => ThrottlingException$2, 0], [() => ServiceUnavailableException$2, 0]]
- ];
- CountTokensInput$ = [
- 4,
- n02,
- _CTI,
- 0,
- [_iMn2, _conv],
- [[() => InvokeModelTokensRequest$, 0], [() => ConverseTokensRequest$, 0]]
- ];
- DocumentContentBlock$ = [
- 4,
- n02,
- _DCBo,
- 0,
- [_te2],
- [0]
- ];
- DocumentSource$ = [
- 4,
- n02,
- _DS,
- 0,
- [_b, _sL2, _te2, _co2],
- [21, () => S3Location$, 0, () => DocumentContentBlocks]
- ];
- GuardrailAutomatedReasoningFinding$ = [
- 4,
- n02,
- _GARF,
- 0,
- [_va2, _in2, _sa2, _imp, _tA2, _tCoo2, _nTo2],
- [[() => GuardrailAutomatedReasoningValidFinding$, 0], [() => GuardrailAutomatedReasoningInvalidFinding$, 0], [() => GuardrailAutomatedReasoningSatisfiableFinding$, 0], [() => GuardrailAutomatedReasoningImpossibleFinding$, 0], [() => GuardrailAutomatedReasoningTranslationAmbiguousFinding$, 0], () => GuardrailAutomatedReasoningTooComplexFinding$, () => GuardrailAutomatedReasoningNoTranslationsFinding$]
- ];
- GuardrailContentBlock$ = [
- 4,
- n02,
- _GCB,
- 0,
- [_te2, _ima],
- [() => GuardrailTextBlock$, [() => GuardrailImageBlock$, 0]]
- ];
- GuardrailConverseContentBlock$ = [
- 4,
- n02,
- _GCCB,
- 0,
- [_te2, _ima],
- [() => GuardrailConverseTextBlock$, [() => GuardrailConverseImageBlock$, 0]]
- ];
- GuardrailConverseImageSource$ = [
- 4,
- n02,
- _GCIS,
- 8,
- [_b],
- [21]
- ];
- GuardrailImageSource$ = [
- 4,
- n02,
- _GIS,
- 8,
- [_b],
- [21]
- ];
- ImageSource$ = [
- 4,
- n02,
- _IS,
- 8,
- [_b, _sL2],
- [21, () => S3Location$]
- ];
- InvokeModelWithBidirectionalStreamInput$ = [
- 4,
- n02,
- _IMWBSI,
- { [_stre]: 1 },
- [_ch],
- [[() => BidirectionalInputPayloadPart$, 0]]
- ];
- InvokeModelWithBidirectionalStreamOutput$ = [
- 4,
- n02,
- _IMWBSO,
- { [_stre]: 1 },
- [_ch, _iSE, _mSEE, _vE, _tE2, _mTE, _sUE],
- [[() => BidirectionalOutputPayloadPart$, 0], [() => InternalServerException$2, 0], [() => ModelStreamErrorException$, 0], [() => ValidationException$2, 0], [() => ThrottlingException$2, 0], [() => ModelTimeoutException$, 0], [() => ServiceUnavailableException$2, 0]]
- ];
- OutputFormatStructure$ = [
- 4,
- n02,
- _OFS,
- 8,
- [_jS2],
- [() => JsonSchemaDefinition$]
- ];
- PromptVariableValues$ = [
- 4,
- n02,
- _PVV,
- 0,
- [_te2],
- [0]
- ];
- ReasoningContentBlock$ = [
- 4,
- n02,
- _RCB,
- 8,
- [_rT, _rCe2],
- [[() => ReasoningTextBlock$, 0], 21]
- ];
- ReasoningContentBlockDelta$ = [
- 4,
- n02,
- _RCBD,
- 8,
- [_te2, _rCe2, _si],
- [0, 21, 0]
- ];
- ResponseStream$ = [
- 4,
- n02,
- _RS2,
- { [_stre]: 1 },
- [_ch, _iSE, _mSEE, _vE, _tE2, _mTE, _sUE],
- [[() => PayloadPart$, 0], [() => InternalServerException$2, 0], [() => ModelStreamErrorException$, 0], [() => ValidationException$2, 0], [() => ThrottlingException$2, 0], [() => ModelTimeoutException$, 0], [() => ServiceUnavailableException$2, 0]]
- ];
- SystemContentBlock$ = [
- 4,
- n02,
- _SCBy,
- 0,
- [_te2, _gCua2, _cPa],
- [0, [() => GuardrailConverseContentBlock$, 0], () => CachePointBlock$]
- ];
- Tool$ = [
- 4,
- n02,
- _Too,
- 0,
- [_tS, _sTy, _cPa],
- [() => ToolSpecification$, () => SystemTool$, () => CachePointBlock$]
- ];
- ToolChoice$ = [
- 4,
- n02,
- _TCo,
- 0,
- [_aut, _an2, _tool],
- [() => AutoToolChoice$, () => AnyToolChoice$, () => SpecificToolChoice$]
- ];
- ToolInputSchema$ = [
- 4,
- n02,
- _TIS,
- 0,
- [_j],
- [15]
- ];
- ToolResultBlockDelta$ = [
- 4,
- n02,
- _TRBDo,
- 0,
- [_te2, _j],
- [0, 15]
- ];
- ToolResultContentBlock$ = [
- 4,
- n02,
- _TRCBo,
- 0,
- [_j, _te2, _ima, _doc2, _vi, _sRe],
- [15, 0, [() => ImageBlock$, 0], () => DocumentBlock$, () => VideoBlock$, () => SearchResultBlock$]
- ];
- VideoSource$ = [
- 4,
- n02,
- _VS,
- 0,
- [_b, _sL2],
- [21, () => S3Location$]
- ];
- ApplyGuardrail$ = [
- 9,
- n02,
- _AG,
- { [_h2]: ["POST", "/guardrail/{guardrailIdentifier}/version/{guardrailVersion}/apply", 200] },
- () => ApplyGuardrailRequest$,
- () => ApplyGuardrailResponse$
- ];
- Converse$ = [
- 9,
- n02,
- _Co,
- { [_h2]: ["POST", "/model/{modelId}/converse", 200] },
- () => ConverseRequest$,
- () => ConverseResponse$
- ];
- ConverseStream$ = [
- 9,
- n02,
- _CS,
- { [_h2]: ["POST", "/model/{modelId}/converse-stream", 200] },
- () => ConverseStreamRequest$,
- () => ConverseStreamResponse$
- ];
- CountTokens$ = [
- 9,
- n02,
- _CTo,
- { [_h2]: ["POST", "/model/{modelId}/count-tokens", 200] },
- () => CountTokensRequest$,
- () => CountTokensResponse$
- ];
- GetAsyncInvoke$ = [
- 9,
- n02,
- _GAI,
- { [_h2]: ["GET", "/async-invoke/{invocationArn}", 200] },
- () => GetAsyncInvokeRequest$,
- () => GetAsyncInvokeResponse$
- ];
- InvokeModel$ = [
- 9,
- n02,
- _IM,
- { [_h2]: ["POST", "/model/{modelId}/invoke", 200] },
- () => InvokeModelRequest$,
- () => InvokeModelResponse$
- ];
- InvokeModelWithBidirectionalStream$ = [
- 9,
- n02,
- _IMWBS,
- { [_h2]: ["POST", "/model/{modelId}/invoke-with-bidirectional-stream", 200] },
- () => InvokeModelWithBidirectionalStreamRequest$,
- () => InvokeModelWithBidirectionalStreamResponse$
- ];
- InvokeModelWithResponseStream$ = [
- 9,
- n02,
- _IMWRS,
- { [_h2]: ["POST", "/model/{modelId}/invoke-with-response-stream", 200] },
- () => InvokeModelWithResponseStreamRequest$,
- () => InvokeModelWithResponseStreamResponse$
- ];
- ListAsyncInvokes$ = [
- 9,
- n02,
- _LAI,
- { [_h2]: ["GET", "/async-invoke", 200] },
- () => ListAsyncInvokesRequest$,
- () => ListAsyncInvokesResponse$
- ];
- StartAsyncInvoke$ = [
- 9,
- n02,
- _SAI,
- { [_h2]: ["POST", "/async-invoke", 200] },
- () => StartAsyncInvokeRequest$,
- () => StartAsyncInvokeResponse$
- ];
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/runtimeConfig.shared.js
-var import_httpAuthSchemes6, import_protocols11, import_core40, import_url_parser3, import_util_utf85, getRuntimeConfig3 = (config5) => {
- return {
- apiVersion: "2023-09-30",
- base64Decoder: config5?.base64Decoder ?? fromBase643,
- base64Encoder: config5?.base64Encoder ?? toBase643,
- disableHostPrefix: config5?.disableHostPrefix ?? false,
- endpointProvider: config5?.endpointProvider ?? defaultEndpointResolver2,
- extensions: config5?.extensions ?? [],
- httpAuthSchemeProvider: config5?.httpAuthSchemeProvider ?? defaultBedrockRuntimeHttpAuthSchemeProvider,
- httpAuthSchemes: config5?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
- signer: new import_httpAuthSchemes6.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#httpBearerAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth"),
- signer: new import_core40.HttpBearerAuthSigner
- }
- ],
- logger: config5?.logger ?? new NoOpLogger5,
- protocol: config5?.protocol ?? import_protocols11.AwsRestJsonProtocol,
- protocolSettings: config5?.protocolSettings ?? {
- defaultNamespace: "com.amazonaws.bedrockruntime",
- errorTypeRegistries: errorTypeRegistries2,
- version: "2023-09-30",
- serviceTarget: "AmazonBedrockFrontendService"
- },
- serviceId: config5?.serviceId ?? "Bedrock Runtime",
- urlParser: config5?.urlParser ?? import_url_parser3.parseUrl,
- utf8Decoder: config5?.utf8Decoder ?? import_util_utf85.fromUtf8,
- utf8Encoder: config5?.utf8Encoder ?? import_util_utf85.toUtf8
- };
-};
-var init_runtimeConfig_shared2 = __esm(() => {
- init_dist_es31();
- init_dist_es36();
- init_httpAuthSchemeProvider2();
- init_endpointResolver2();
- init_schemas_02();
- import_httpAuthSchemes6 = __toESM(require_httpAuthSchemes(), 1);
- import_protocols11 = __toESM(require_protocols2(), 1);
- import_core40 = __toESM(require_dist_cjs37(), 1);
- import_url_parser3 = __toESM(require_dist_cjs11(), 1);
- import_util_utf85 = __toESM(require_dist_cjs17(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/runtimeConfig.js
-var import_client16, import_httpAuthSchemes7, import_util_user_agent_node2, import_config_resolver3, import_core41, import_hash_node2, import_middleware_retry3, import_node_config_provider4, import_node_http_handler3, import_util_body_length_node2, import_util_defaults_mode_node2, import_util_retry2, getRuntimeConfig4 = (config5) => {
- emitWarningIfUnsupportedVersion5(process.version);
- const defaultsMode = import_util_defaults_mode_node2.resolveDefaultsModeConfig(config5);
- const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode3);
- const clientSharedValues = getRuntimeConfig3(config5);
- import_client16.emitWarningIfUnsupportedVersion(process.version);
- const loaderConfig = {
- profile: config5?.profile,
- logger: clientSharedValues.logger,
- signingName: "bedrock"
- };
- return {
- ...clientSharedValues,
- ...config5,
- runtime: "node",
- defaultsMode,
- authSchemePreference: config5?.authSchemePreference ?? import_node_config_provider4.loadConfig(import_httpAuthSchemes7.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
- bodyLengthChecker: config5?.bodyLengthChecker ?? import_util_body_length_node2.calculateBodyLength,
- credentialDefaultProvider: config5?.credentialDefaultProvider ?? defaultProvider,
- defaultUserAgentProvider: config5?.defaultUserAgentProvider ?? import_util_user_agent_node2.createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default2.version }),
- eventStreamPayloadHandlerProvider: config5?.eventStreamPayloadHandlerProvider ?? eventStreamPayloadHandlerProvider2,
- eventStreamSerdeProvider: config5?.eventStreamSerdeProvider ?? eventStreamSerdeProvider,
- httpAuthSchemes: config5?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
- signer: new import_httpAuthSchemes7.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#httpBearerAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth") || (async (idProps) => {
- try {
- return await fromEnvSigningName({ signingName: "bedrock" })();
- } catch (error40) {
- return await nodeProvider(idProps)(idProps);
- }
- }),
- signer: new import_core41.HttpBearerAuthSigner
- }
- ],
- maxAttempts: config5?.maxAttempts ?? import_node_config_provider4.loadConfig(import_middleware_retry3.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config5),
- region: config5?.region ?? import_node_config_provider4.loadConfig(import_config_resolver3.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver3.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
- requestHandler: import_node_http_handler3.NodeHttp2Handler.create(config5?.requestHandler ?? (async () => ({
- ...await defaultConfigProvider(),
- disableConcurrentStreams: true
- }))),
- retryMode: config5?.retryMode ?? import_node_config_provider4.loadConfig({
- ...import_middleware_retry3.NODE_RETRY_MODE_CONFIG_OPTIONS,
- default: async () => (await defaultConfigProvider()).retryMode || import_util_retry2.DEFAULT_RETRY_MODE
- }, config5),
- sha256: config5?.sha256 ?? import_hash_node2.Hash.bind(null, "sha256"),
- streamCollector: config5?.streamCollector ?? import_node_http_handler3.streamCollector,
- useDualstackEndpoint: config5?.useDualstackEndpoint ?? import_node_config_provider4.loadConfig(import_config_resolver3.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- useFipsEndpoint: config5?.useFipsEndpoint ?? import_node_config_provider4.loadConfig(import_config_resolver3.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- userAgentAppId: config5?.userAgentAppId ?? import_node_config_provider4.loadConfig(import_util_user_agent_node2.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
- };
-};
-var init_runtimeConfig2 = __esm(() => {
- init_package2();
- init_dist_es14();
- init_dist_es32();
- init_dist_es7();
- init_dist_es34();
- init_dist_es31();
- init_runtimeConfig_shared2();
- import_client16 = __toESM(require_client(), 1);
- import_httpAuthSchemes7 = __toESM(require_httpAuthSchemes(), 1);
- import_util_user_agent_node2 = __toESM(require_dist_cjs72(), 1);
- import_config_resolver3 = __toESM(require_dist_cjs58(), 1);
- import_core41 = __toESM(require_dist_cjs37(), 1);
- import_hash_node2 = __toESM(require_dist_cjs75(), 1);
- import_middleware_retry3 = __toESM(require_dist_cjs69(), 1);
- import_node_config_provider4 = __toESM(require_dist_cjs9(), 1);
- import_node_http_handler3 = __toESM(require_dist_cjs5(), 1);
- import_util_body_length_node2 = __toESM(require_dist_cjs76(), 1);
- import_util_defaults_mode_node2 = __toESM(require_dist_cjs77(), 1);
- import_util_retry2 = __toESM(require_dist_cjs55(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
-var getHttpHandlerExtensionConfiguration2 = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
-}, resolveHttpHandlerRuntimeConfig2 = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
-};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
-var init_extensions12 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-es/Field.js
-var init_Field6 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
-var init_httpHandler6 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-es/types.js
-var init_types11 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-es/index.js
-var init_dist_es37 = __esm(() => {
- init_extensions12();
- init_Field6();
- init_httpHandler6();
- init_types11();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/auth/httpAuthExtensionConfiguration.js
-var getHttpAuthExtensionConfiguration2 = (runtimeConfig) => {
- const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
- let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
- let _credentials = runtimeConfig.credentials;
- let _token = runtimeConfig.token;
- return {
- setHttpAuthScheme(httpAuthScheme) {
- const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
- if (index2 === -1) {
- _httpAuthSchemes.push(httpAuthScheme);
- } else {
- _httpAuthSchemes.splice(index2, 1, httpAuthScheme);
- }
- },
- httpAuthSchemes() {
- return _httpAuthSchemes;
- },
- setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
- _httpAuthSchemeProvider = httpAuthSchemeProvider;
- },
- httpAuthSchemeProvider() {
- return _httpAuthSchemeProvider;
- },
- setCredentials(credentials) {
- _credentials = credentials;
- },
- credentials() {
- return _credentials;
- },
- setToken(token) {
- _token = token;
- },
- token() {
- return _token;
- }
- };
-}, resolveHttpAuthRuntimeConfig2 = (config5) => {
- return {
- httpAuthSchemes: config5.httpAuthSchemes(),
- httpAuthSchemeProvider: config5.httpAuthSchemeProvider(),
- credentials: config5.credentials(),
- token: config5.token()
- };
-};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/runtimeExtensions.js
-var import_region_config_resolver2, resolveRuntimeExtensions2 = (runtimeConfig, extensions13) => {
- const extensionConfiguration = Object.assign(import_region_config_resolver2.getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration3(runtimeConfig), getHttpHandlerExtensionConfiguration2(runtimeConfig), getHttpAuthExtensionConfiguration2(runtimeConfig));
- extensions13.forEach((extension) => extension.configure(extensionConfiguration));
- return Object.assign(runtimeConfig, import_region_config_resolver2.resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig3(extensionConfiguration), resolveHttpHandlerRuntimeConfig2(extensionConfiguration), resolveHttpAuthRuntimeConfig2(extensionConfiguration));
-};
-var init_runtimeExtensions2 = __esm(() => {
- init_dist_es37();
- init_dist_es31();
- import_region_config_resolver2 = __toESM(require_dist_cjs87(), 1);
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/BedrockRuntimeClient.js
-var import_middleware_host_header2, import_middleware_logger2, import_middleware_recursion_detection2, import_middleware_user_agent2, import_config_resolver4, import_core42, import_schema7, import_middleware_content_length2, import_middleware_endpoint100, import_middleware_retry4, BedrockRuntimeClient;
-var init_BedrockRuntimeClient = __esm(() => {
- init_dist_es22();
- init_dist_es28();
- init_dist_es29();
- init_dist_es31();
- init_httpAuthSchemeProvider2();
- init_EndpointParameters2();
- init_runtimeConfig2();
- init_runtimeExtensions2();
- import_middleware_host_header2 = __toESM(require_dist_cjs44(), 1);
- import_middleware_logger2 = __toESM(require_dist_cjs45(), 1);
- import_middleware_recursion_detection2 = __toESM(require_dist_cjs48(), 1);
- import_middleware_user_agent2 = __toESM(require_dist_cjs56(), 1);
- import_config_resolver4 = __toESM(require_dist_cjs58(), 1);
- import_core42 = __toESM(require_dist_cjs37(), 1);
- import_schema7 = __toESM(require_schema(), 1);
- import_middleware_content_length2 = __toESM(require_dist_cjs61(), 1);
- import_middleware_endpoint100 = __toESM(require_dist_cjs65(), 1);
- import_middleware_retry4 = __toESM(require_dist_cjs69(), 1);
- BedrockRuntimeClient = class BedrockRuntimeClient extends Client3 {
- config;
- constructor(...[configuration]) {
- const _config_0 = getRuntimeConfig4(configuration || {});
- super(_config_0);
- this.initConfig = _config_0;
- const _config_1 = resolveClientEndpointParameters2(_config_0);
- const _config_2 = import_middleware_user_agent2.resolveUserAgentConfig(_config_1);
- const _config_3 = import_middleware_retry4.resolveRetryConfig(_config_2);
- const _config_4 = import_config_resolver4.resolveRegionConfig(_config_3);
- const _config_5 = import_middleware_host_header2.resolveHostHeaderConfig(_config_4);
- const _config_6 = import_middleware_endpoint100.resolveEndpointConfig(_config_5);
- const _config_7 = resolveEventStreamSerdeConfig(_config_6);
- const _config_8 = resolveHttpAuthSchemeConfig2(_config_7);
- const _config_9 = resolveEventStreamConfig(_config_8);
- const _config_10 = resolveWebSocketConfig(_config_9);
- const _config_11 = resolveRuntimeExtensions2(_config_10, configuration?.extensions || []);
- this.config = _config_11;
- this.middlewareStack.use(import_schema7.getSchemaSerdePlugin(this.config));
- this.middlewareStack.use(import_middleware_user_agent2.getUserAgentPlugin(this.config));
- this.middlewareStack.use(import_middleware_retry4.getRetryPlugin(this.config));
- this.middlewareStack.use(import_middleware_content_length2.getContentLengthPlugin(this.config));
- this.middlewareStack.use(import_middleware_host_header2.getHostHeaderPlugin(this.config));
- this.middlewareStack.use(import_middleware_logger2.getLoggerPlugin(this.config));
- this.middlewareStack.use(import_middleware_recursion_detection2.getRecursionDetectionPlugin(this.config));
- this.middlewareStack.use(import_core42.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
- httpAuthSchemeParametersProvider: defaultBedrockRuntimeHttpAuthSchemeParametersProvider,
- identityProviderConfigProvider: async (config5) => new import_core42.DefaultIdentityProviderConfig({
- "aws.auth#sigv4": config5.credentials,
- "smithy.api#httpBearerAuth": config5.token
- })
- }));
- this.middlewareStack.use(import_core42.getHttpSigningPlugin(this.config));
- }
- destroy() {
- super.destroy();
- }
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/ApplyGuardrailCommand.js
-var import_middleware_endpoint101, ApplyGuardrailCommand;
-var init_ApplyGuardrailCommand = __esm(() => {
- init_dist_es31();
- init_EndpointParameters2();
- init_schemas_02();
- import_middleware_endpoint101 = __toESM(require_dist_cjs65(), 1);
- ApplyGuardrailCommand = class ApplyGuardrailCommand extends Command4.classBuilder().ep(commonParams2).m(function(Command5, cs, config5, o4) {
- return [import_middleware_endpoint101.getEndpointPlugin(config5, Command5.getEndpointParameterInstructions())];
- }).s("AmazonBedrockFrontendService", "ApplyGuardrail", {}).n("BedrockRuntimeClient", "ApplyGuardrailCommand").sc(ApplyGuardrail$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/ConverseCommand.js
-var import_middleware_endpoint102, ConverseCommand;
-var init_ConverseCommand = __esm(() => {
- init_dist_es31();
- init_EndpointParameters2();
- init_schemas_02();
- import_middleware_endpoint102 = __toESM(require_dist_cjs65(), 1);
- ConverseCommand = class ConverseCommand extends Command4.classBuilder().ep(commonParams2).m(function(Command5, cs, config5, o4) {
- return [import_middleware_endpoint102.getEndpointPlugin(config5, Command5.getEndpointParameterInstructions())];
- }).s("AmazonBedrockFrontendService", "Converse", {}).n("BedrockRuntimeClient", "ConverseCommand").sc(Converse$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/ConverseStreamCommand.js
-var import_middleware_endpoint103, ConverseStreamCommand;
-var init_ConverseStreamCommand = __esm(() => {
- init_dist_es31();
- init_EndpointParameters2();
- init_schemas_02();
- import_middleware_endpoint103 = __toESM(require_dist_cjs65(), 1);
- ConverseStreamCommand = class ConverseStreamCommand extends Command4.classBuilder().ep(commonParams2).m(function(Command5, cs, config5, o4) {
- return [import_middleware_endpoint103.getEndpointPlugin(config5, Command5.getEndpointParameterInstructions())];
- }).s("AmazonBedrockFrontendService", "ConverseStream", {
- eventStream: {
- output: true
- }
- }).n("BedrockRuntimeClient", "ConverseStreamCommand").sc(ConverseStream$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/CountTokensCommand.js
-var import_middleware_endpoint104, CountTokensCommand;
-var init_CountTokensCommand = __esm(() => {
- init_dist_es31();
- init_EndpointParameters2();
- init_schemas_02();
- import_middleware_endpoint104 = __toESM(require_dist_cjs65(), 1);
- CountTokensCommand = class CountTokensCommand extends Command4.classBuilder().ep(commonParams2).m(function(Command5, cs, config5, o4) {
- return [import_middleware_endpoint104.getEndpointPlugin(config5, Command5.getEndpointParameterInstructions())];
- }).s("AmazonBedrockFrontendService", "CountTokens", {}).n("BedrockRuntimeClient", "CountTokensCommand").sc(CountTokens$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/GetAsyncInvokeCommand.js
-var import_middleware_endpoint105, GetAsyncInvokeCommand;
-var init_GetAsyncInvokeCommand = __esm(() => {
- init_dist_es31();
- init_EndpointParameters2();
- init_schemas_02();
- import_middleware_endpoint105 = __toESM(require_dist_cjs65(), 1);
- GetAsyncInvokeCommand = class GetAsyncInvokeCommand extends Command4.classBuilder().ep(commonParams2).m(function(Command5, cs, config5, o4) {
- return [import_middleware_endpoint105.getEndpointPlugin(config5, Command5.getEndpointParameterInstructions())];
- }).s("AmazonBedrockFrontendService", "GetAsyncInvoke", {}).n("BedrockRuntimeClient", "GetAsyncInvokeCommand").sc(GetAsyncInvoke$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/InvokeModelCommand.js
-var import_middleware_endpoint106, InvokeModelCommand;
-var init_InvokeModelCommand = __esm(() => {
- init_dist_es31();
- init_EndpointParameters2();
- init_schemas_02();
- import_middleware_endpoint106 = __toESM(require_dist_cjs65(), 1);
- InvokeModelCommand = class InvokeModelCommand extends Command4.classBuilder().ep(commonParams2).m(function(Command5, cs, config5, o4) {
- return [import_middleware_endpoint106.getEndpointPlugin(config5, Command5.getEndpointParameterInstructions())];
- }).s("AmazonBedrockFrontendService", "InvokeModel", {}).n("BedrockRuntimeClient", "InvokeModelCommand").sc(InvokeModel$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/InvokeModelWithBidirectionalStreamCommand.js
-var import_middleware_endpoint107, InvokeModelWithBidirectionalStreamCommand;
-var init_InvokeModelWithBidirectionalStreamCommand = __esm(() => {
- init_dist_es22();
- init_dist_es28();
- init_dist_es31();
- init_EndpointParameters2();
- init_schemas_02();
- import_middleware_endpoint107 = __toESM(require_dist_cjs65(), 1);
- InvokeModelWithBidirectionalStreamCommand = class InvokeModelWithBidirectionalStreamCommand extends Command4.classBuilder().ep(commonParams2).m(function(Command5, cs, config5, o4) {
- return [
- import_middleware_endpoint107.getEndpointPlugin(config5, Command5.getEndpointParameterInstructions()),
- getEventStreamPlugin(config5),
- getWebSocketPlugin(config5, {
- headerPrefix: "x-amz-bedrock-"
- })
- ];
- }).s("AmazonBedrockFrontendService", "InvokeModelWithBidirectionalStream", {
- eventStream: {
- input: true,
- output: true
- }
- }).n("BedrockRuntimeClient", "InvokeModelWithBidirectionalStreamCommand").sc(InvokeModelWithBidirectionalStream$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/InvokeModelWithResponseStreamCommand.js
-var import_middleware_endpoint108, InvokeModelWithResponseStreamCommand;
-var init_InvokeModelWithResponseStreamCommand = __esm(() => {
- init_dist_es31();
- init_EndpointParameters2();
- init_schemas_02();
- import_middleware_endpoint108 = __toESM(require_dist_cjs65(), 1);
- InvokeModelWithResponseStreamCommand = class InvokeModelWithResponseStreamCommand extends Command4.classBuilder().ep(commonParams2).m(function(Command5, cs, config5, o4) {
- return [import_middleware_endpoint108.getEndpointPlugin(config5, Command5.getEndpointParameterInstructions())];
- }).s("AmazonBedrockFrontendService", "InvokeModelWithResponseStream", {
- eventStream: {
- output: true
- }
- }).n("BedrockRuntimeClient", "InvokeModelWithResponseStreamCommand").sc(InvokeModelWithResponseStream$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/ListAsyncInvokesCommand.js
-var import_middleware_endpoint109, ListAsyncInvokesCommand;
-var init_ListAsyncInvokesCommand = __esm(() => {
- init_dist_es31();
- init_EndpointParameters2();
- init_schemas_02();
- import_middleware_endpoint109 = __toESM(require_dist_cjs65(), 1);
- ListAsyncInvokesCommand = class ListAsyncInvokesCommand extends Command4.classBuilder().ep(commonParams2).m(function(Command5, cs, config5, o4) {
- return [import_middleware_endpoint109.getEndpointPlugin(config5, Command5.getEndpointParameterInstructions())];
- }).s("AmazonBedrockFrontendService", "ListAsyncInvokes", {}).n("BedrockRuntimeClient", "ListAsyncInvokesCommand").sc(ListAsyncInvokes$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/StartAsyncInvokeCommand.js
-var import_middleware_endpoint110, StartAsyncInvokeCommand;
-var init_StartAsyncInvokeCommand = __esm(() => {
- init_dist_es31();
- init_EndpointParameters2();
- init_schemas_02();
- import_middleware_endpoint110 = __toESM(require_dist_cjs65(), 1);
- StartAsyncInvokeCommand = class StartAsyncInvokeCommand extends Command4.classBuilder().ep(commonParams2).m(function(Command5, cs, config5, o4) {
- return [import_middleware_endpoint110.getEndpointPlugin(config5, Command5.getEndpointParameterInstructions())];
- }).s("AmazonBedrockFrontendService", "StartAsyncInvoke", {}).n("BedrockRuntimeClient", "StartAsyncInvokeCommand").sc(StartAsyncInvoke$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/pagination/ListAsyncInvokesPaginator.js
-var import_core43, paginateListAsyncInvokes;
-var init_ListAsyncInvokesPaginator = __esm(() => {
- init_BedrockRuntimeClient();
- init_ListAsyncInvokesCommand();
- import_core43 = __toESM(require_dist_cjs37(), 1);
- paginateListAsyncInvokes = import_core43.createPaginator(BedrockRuntimeClient, ListAsyncInvokesCommand, "nextToken", "nextToken", "maxResults");
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/BedrockRuntime.js
-var commands3, paginators2, BedrockRuntime;
-var init_BedrockRuntime = __esm(() => {
- init_dist_es31();
- init_BedrockRuntimeClient();
- init_ApplyGuardrailCommand();
- init_ConverseCommand();
- init_ConverseStreamCommand();
- init_CountTokensCommand();
- init_GetAsyncInvokeCommand();
- init_InvokeModelCommand();
- init_InvokeModelWithBidirectionalStreamCommand();
- init_InvokeModelWithResponseStreamCommand();
- init_ListAsyncInvokesCommand();
- init_StartAsyncInvokeCommand();
- init_ListAsyncInvokesPaginator();
- commands3 = {
- ApplyGuardrailCommand,
- ConverseCommand,
- ConverseStreamCommand,
- CountTokensCommand,
- GetAsyncInvokeCommand,
- InvokeModelCommand,
- InvokeModelWithBidirectionalStreamCommand,
- InvokeModelWithResponseStreamCommand,
- ListAsyncInvokesCommand,
- StartAsyncInvokeCommand
- };
- paginators2 = {
- paginateListAsyncInvokes
- };
- BedrockRuntime = class BedrockRuntime extends BedrockRuntimeClient {
- };
- createAggregatedClient3(commands3, BedrockRuntime, { paginators: paginators2 });
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/index.js
-var init_commands2 = __esm(() => {
- init_ApplyGuardrailCommand();
- init_ConverseCommand();
- init_ConverseStreamCommand();
- init_CountTokensCommand();
- init_GetAsyncInvokeCommand();
- init_InvokeModelCommand();
- init_InvokeModelWithBidirectionalStreamCommand();
- init_InvokeModelWithResponseStreamCommand();
- init_ListAsyncInvokesCommand();
- init_StartAsyncInvokeCommand();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/pagination/Interfaces.js
-var init_Interfaces2 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/pagination/index.js
-var init_pagination6 = __esm(() => {
- init_Interfaces2();
- init_ListAsyncInvokesPaginator();
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/models/enums.js
-var AsyncInvokeStatus, SortAsyncInvocationBy, SortOrder2, GuardrailImageFormat, GuardrailContentQualifier, GuardrailOutputScope, GuardrailContentSource, GuardrailAction, GuardrailOrigin, GuardrailOwnership, GuardrailAutomatedReasoningLogicWarningType, GuardrailContentPolicyAction, GuardrailContentFilterConfidence, GuardrailContentFilterStrength, GuardrailContentFilterType2, GuardrailContextualGroundingPolicyAction, GuardrailContextualGroundingFilterType2, GuardrailSensitiveInformationPolicyAction, GuardrailPiiEntityType2, GuardrailTopicPolicyAction, GuardrailTopicType2, GuardrailWordPolicyAction, GuardrailManagedWordType, GuardrailTrace, AudioFormat, CacheTTL, CachePointType, DocumentFormat, GuardrailConverseImageFormat, GuardrailConverseContentQualifier, ImageFormat, VideoFormat, ToolResultStatus, ToolUseType, ConversationRole, OutputFormatType, PerformanceConfigLatency2, ServiceTierType, StopReason, GuardrailStreamProcessingMode, Trace;
-var init_enums2 = __esm(() => {
- AsyncInvokeStatus = {
- COMPLETED: "Completed",
- FAILED: "Failed",
- IN_PROGRESS: "InProgress"
- };
- SortAsyncInvocationBy = {
- SUBMISSION_TIME: "SubmissionTime"
- };
- SortOrder2 = {
- ASCENDING: "Ascending",
- DESCENDING: "Descending"
- };
- GuardrailImageFormat = {
- JPEG: "jpeg",
- PNG: "png"
- };
- GuardrailContentQualifier = {
- GROUNDING_SOURCE: "grounding_source",
- GUARD_CONTENT: "guard_content",
- QUERY: "query"
- };
- GuardrailOutputScope = {
- FULL: "FULL",
- INTERVENTIONS: "INTERVENTIONS"
- };
- GuardrailContentSource = {
- INPUT: "INPUT",
- OUTPUT: "OUTPUT"
- };
- GuardrailAction = {
- GUARDRAIL_INTERVENED: "GUARDRAIL_INTERVENED",
- NONE: "NONE"
- };
- GuardrailOrigin = {
- ACCOUNT_ENFORCED: "ACCOUNT_ENFORCED",
- ORGANIZATION_ENFORCED: "ORGANIZATION_ENFORCED",
- REQUEST: "REQUEST"
- };
- GuardrailOwnership = {
- CROSS_ACCOUNT: "CROSS_ACCOUNT",
- SELF: "SELF"
- };
- GuardrailAutomatedReasoningLogicWarningType = {
- ALWAYS_FALSE: "ALWAYS_FALSE",
- ALWAYS_TRUE: "ALWAYS_TRUE"
- };
- GuardrailContentPolicyAction = {
- BLOCKED: "BLOCKED",
- NONE: "NONE"
- };
- GuardrailContentFilterConfidence = {
- HIGH: "HIGH",
- LOW: "LOW",
- MEDIUM: "MEDIUM",
- NONE: "NONE"
- };
- GuardrailContentFilterStrength = {
- HIGH: "HIGH",
- LOW: "LOW",
- MEDIUM: "MEDIUM",
- NONE: "NONE"
- };
- GuardrailContentFilterType2 = {
- HATE: "HATE",
- INSULTS: "INSULTS",
- MISCONDUCT: "MISCONDUCT",
- PROMPT_ATTACK: "PROMPT_ATTACK",
- SEXUAL: "SEXUAL",
- VIOLENCE: "VIOLENCE"
- };
- GuardrailContextualGroundingPolicyAction = {
- BLOCKED: "BLOCKED",
- NONE: "NONE"
- };
- GuardrailContextualGroundingFilterType2 = {
- GROUNDING: "GROUNDING",
- RELEVANCE: "RELEVANCE"
- };
- GuardrailSensitiveInformationPolicyAction = {
- ANONYMIZED: "ANONYMIZED",
- BLOCKED: "BLOCKED",
- NONE: "NONE"
- };
- GuardrailPiiEntityType2 = {
- ADDRESS: "ADDRESS",
- AGE: "AGE",
- AWS_ACCESS_KEY: "AWS_ACCESS_KEY",
- AWS_SECRET_KEY: "AWS_SECRET_KEY",
- CA_HEALTH_NUMBER: "CA_HEALTH_NUMBER",
- CA_SOCIAL_INSURANCE_NUMBER: "CA_SOCIAL_INSURANCE_NUMBER",
- CREDIT_DEBIT_CARD_CVV: "CREDIT_DEBIT_CARD_CVV",
- CREDIT_DEBIT_CARD_EXPIRY: "CREDIT_DEBIT_CARD_EXPIRY",
- CREDIT_DEBIT_CARD_NUMBER: "CREDIT_DEBIT_CARD_NUMBER",
- DRIVER_ID: "DRIVER_ID",
- EMAIL: "EMAIL",
- INTERNATIONAL_BANK_ACCOUNT_NUMBER: "INTERNATIONAL_BANK_ACCOUNT_NUMBER",
- IP_ADDRESS: "IP_ADDRESS",
- LICENSE_PLATE: "LICENSE_PLATE",
- MAC_ADDRESS: "MAC_ADDRESS",
- NAME: "NAME",
- PASSWORD: "PASSWORD",
- PHONE: "PHONE",
- PIN: "PIN",
- SWIFT_CODE: "SWIFT_CODE",
- UK_NATIONAL_HEALTH_SERVICE_NUMBER: "UK_NATIONAL_HEALTH_SERVICE_NUMBER",
- UK_NATIONAL_INSURANCE_NUMBER: "UK_NATIONAL_INSURANCE_NUMBER",
- UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER: "UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER",
- URL: "URL",
- USERNAME: "USERNAME",
- US_BANK_ACCOUNT_NUMBER: "US_BANK_ACCOUNT_NUMBER",
- US_BANK_ROUTING_NUMBER: "US_BANK_ROUTING_NUMBER",
- US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER: "US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER",
- US_PASSPORT_NUMBER: "US_PASSPORT_NUMBER",
- US_SOCIAL_SECURITY_NUMBER: "US_SOCIAL_SECURITY_NUMBER",
- VEHICLE_IDENTIFICATION_NUMBER: "VEHICLE_IDENTIFICATION_NUMBER"
- };
- GuardrailTopicPolicyAction = {
- BLOCKED: "BLOCKED",
- NONE: "NONE"
- };
- GuardrailTopicType2 = {
- DENY: "DENY"
- };
- GuardrailWordPolicyAction = {
- BLOCKED: "BLOCKED",
- NONE: "NONE"
- };
- GuardrailManagedWordType = {
- PROFANITY: "PROFANITY"
- };
- GuardrailTrace = {
- DISABLED: "disabled",
- ENABLED: "enabled",
- ENABLED_FULL: "enabled_full"
- };
- AudioFormat = {
- AAC: "aac",
- FLAC: "flac",
- M4A: "m4a",
- MKA: "mka",
- MKV: "mkv",
- MP3: "mp3",
- MP4: "mp4",
- MPEG: "mpeg",
- MPGA: "mpga",
- OGG: "ogg",
- OPUS: "opus",
- PCM: "pcm",
- WAV: "wav",
- WEBM: "webm",
- X_AAC: "x-aac"
- };
- CacheTTL = {
- FIVE_MINUTES: "5m",
- ONE_HOUR: "1h"
- };
- CachePointType = {
- DEFAULT: "default"
- };
- DocumentFormat = {
- CSV: "csv",
- DOC: "doc",
- DOCX: "docx",
- HTML: "html",
- MD: "md",
- PDF: "pdf",
- TXT: "txt",
- XLS: "xls",
- XLSX: "xlsx"
- };
- GuardrailConverseImageFormat = {
- JPEG: "jpeg",
- PNG: "png"
- };
- GuardrailConverseContentQualifier = {
- GROUNDING_SOURCE: "grounding_source",
- GUARD_CONTENT: "guard_content",
- QUERY: "query"
- };
- ImageFormat = {
- GIF: "gif",
- JPEG: "jpeg",
- PNG: "png",
- WEBP: "webp"
- };
- VideoFormat = {
- FLV: "flv",
- MKV: "mkv",
- MOV: "mov",
- MP4: "mp4",
- MPEG: "mpeg",
- MPG: "mpg",
- THREE_GP: "three_gp",
- WEBM: "webm",
- WMV: "wmv"
- };
- ToolResultStatus = {
- ERROR: "error",
- SUCCESS: "success"
- };
- ToolUseType = {
- SERVER_TOOL_USE: "server_tool_use"
- };
- ConversationRole = {
- ASSISTANT: "assistant",
- USER: "user"
- };
- OutputFormatType = {
- JSON_SCHEMA: "json_schema"
- };
- PerformanceConfigLatency2 = {
- OPTIMIZED: "optimized",
- STANDARD: "standard"
- };
- ServiceTierType = {
- DEFAULT: "default",
- FLEX: "flex",
- PRIORITY: "priority",
- RESERVED: "reserved"
- };
- StopReason = {
- CONTENT_FILTERED: "content_filtered",
- END_TURN: "end_turn",
- GUARDRAIL_INTERVENED: "guardrail_intervened",
- MALFORMED_MODEL_OUTPUT: "malformed_model_output",
- MALFORMED_TOOL_USE: "malformed_tool_use",
- MAX_TOKENS: "max_tokens",
- MODEL_CONTEXT_WINDOW_EXCEEDED: "model_context_window_exceeded",
- STOP_SEQUENCE: "stop_sequence",
- TOOL_USE: "tool_use"
- };
- GuardrailStreamProcessingMode = {
- ASYNC: "async",
- SYNC: "sync"
- };
- Trace = {
- DISABLED: "DISABLED",
- ENABLED: "ENABLED",
- ENABLED_FULL: "ENABLED_FULL"
- };
-});
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/models/models_0.js
-var init_models_02 = () => {};
-
-// node_modules/@aws-sdk/client-bedrock-runtime/dist-es/index.js
-var exports_dist_es13 = {};
-__export(exports_dist_es13, {
- paginateListAsyncInvokes: () => paginateListAsyncInvokes,
- errorTypeRegistries: () => errorTypeRegistries2,
- __Client: () => Client3,
- WebLocation$: () => WebLocation$,
- VideoSource$: () => VideoSource$,
- VideoFormat: () => VideoFormat,
- VideoBlock$: () => VideoBlock$,
- ValidationException$: () => ValidationException$2,
- ValidationException: () => ValidationException2,
- Trace: () => Trace,
- ToolUseType: () => ToolUseType,
- ToolUseBlockStart$: () => ToolUseBlockStart$,
- ToolUseBlockDelta$: () => ToolUseBlockDelta$,
- ToolUseBlock$: () => ToolUseBlock$,
- ToolSpecification$: () => ToolSpecification$,
- ToolResultStatus: () => ToolResultStatus,
- ToolResultContentBlock$: () => ToolResultContentBlock$,
- ToolResultBlockStart$: () => ToolResultBlockStart$,
- ToolResultBlockDelta$: () => ToolResultBlockDelta$,
- ToolResultBlock$: () => ToolResultBlock$,
- ToolInputSchema$: () => ToolInputSchema$,
- ToolConfiguration$: () => ToolConfiguration$,
- ToolChoice$: () => ToolChoice$,
- Tool$: () => Tool$,
- TokenUsage$: () => TokenUsage$,
- ThrottlingException$: () => ThrottlingException$2,
- ThrottlingException: () => ThrottlingException2,
- Tag$: () => Tag$2,
- SystemTool$: () => SystemTool$,
- SystemContentBlock$: () => SystemContentBlock$,
- StopReason: () => StopReason,
- StartAsyncInvokeResponse$: () => StartAsyncInvokeResponse$,
- StartAsyncInvokeRequest$: () => StartAsyncInvokeRequest$,
- StartAsyncInvokeCommand: () => StartAsyncInvokeCommand,
- StartAsyncInvoke$: () => StartAsyncInvoke$,
- SpecificToolChoice$: () => SpecificToolChoice$,
- SortOrder: () => SortOrder2,
- SortAsyncInvocationBy: () => SortAsyncInvocationBy,
- ServiceUnavailableException$: () => ServiceUnavailableException$2,
- ServiceUnavailableException: () => ServiceUnavailableException2,
- ServiceTierType: () => ServiceTierType,
- ServiceTier$: () => ServiceTier$,
- ServiceQuotaExceededException$: () => ServiceQuotaExceededException$2,
- ServiceQuotaExceededException: () => ServiceQuotaExceededException2,
- SearchResultLocation$: () => SearchResultLocation$,
- SearchResultContentBlock$: () => SearchResultContentBlock$,
- SearchResultBlock$: () => SearchResultBlock$,
- S3Location$: () => S3Location$,
- ResponseStream$: () => ResponseStream$,
- ResourceNotFoundException$: () => ResourceNotFoundException$2,
- ResourceNotFoundException: () => ResourceNotFoundException2,
- ReasoningTextBlock$: () => ReasoningTextBlock$,
- ReasoningContentBlockDelta$: () => ReasoningContentBlockDelta$,
- ReasoningContentBlock$: () => ReasoningContentBlock$,
- PromptVariableValues$: () => PromptVariableValues$,
- PromptRouterTrace$: () => PromptRouterTrace$,
- PerformanceConfiguration$: () => PerformanceConfiguration$2,
- PerformanceConfigLatency: () => PerformanceConfigLatency2,
- PayloadPart$: () => PayloadPart$,
- OutputFormatType: () => OutputFormatType,
- OutputFormatStructure$: () => OutputFormatStructure$,
- OutputFormat$: () => OutputFormat$,
- OutputConfig$: () => OutputConfig$,
- ModelTimeoutException$: () => ModelTimeoutException$,
- ModelTimeoutException: () => ModelTimeoutException,
- ModelStreamErrorException$: () => ModelStreamErrorException$,
- ModelStreamErrorException: () => ModelStreamErrorException,
- ModelNotReadyException$: () => ModelNotReadyException$,
- ModelNotReadyException: () => ModelNotReadyException,
- ModelErrorException$: () => ModelErrorException$,
- ModelErrorException: () => ModelErrorException,
- MessageStopEvent$: () => MessageStopEvent$,
- MessageStartEvent$: () => MessageStartEvent$,
- Message$: () => Message$,
- ListAsyncInvokesResponse$: () => ListAsyncInvokesResponse$,
- ListAsyncInvokesRequest$: () => ListAsyncInvokesRequest$,
- ListAsyncInvokesCommand: () => ListAsyncInvokesCommand,
- ListAsyncInvokes$: () => ListAsyncInvokes$,
- JsonSchemaDefinition$: () => JsonSchemaDefinition$,
- InvokeModelWithResponseStreamResponse$: () => InvokeModelWithResponseStreamResponse$,
- InvokeModelWithResponseStreamRequest$: () => InvokeModelWithResponseStreamRequest$,
- InvokeModelWithResponseStreamCommand: () => InvokeModelWithResponseStreamCommand,
- InvokeModelWithResponseStream$: () => InvokeModelWithResponseStream$,
- InvokeModelWithBidirectionalStreamResponse$: () => InvokeModelWithBidirectionalStreamResponse$,
- InvokeModelWithBidirectionalStreamRequest$: () => InvokeModelWithBidirectionalStreamRequest$,
- InvokeModelWithBidirectionalStreamOutput$: () => InvokeModelWithBidirectionalStreamOutput$,
- InvokeModelWithBidirectionalStreamInput$: () => InvokeModelWithBidirectionalStreamInput$,
- InvokeModelWithBidirectionalStreamCommand: () => InvokeModelWithBidirectionalStreamCommand,
- InvokeModelWithBidirectionalStream$: () => InvokeModelWithBidirectionalStream$,
- InvokeModelTokensRequest$: () => InvokeModelTokensRequest$,
- InvokeModelResponse$: () => InvokeModelResponse$,
- InvokeModelRequest$: () => InvokeModelRequest$,
- InvokeModelCommand: () => InvokeModelCommand,
- InvokeModel$: () => InvokeModel$,
- InternalServerException$: () => InternalServerException$2,
- InternalServerException: () => InternalServerException2,
- InferenceConfiguration$: () => InferenceConfiguration$,
- ImageSource$: () => ImageSource$,
- ImageFormat: () => ImageFormat,
- ImageBlockStart$: () => ImageBlockStart$,
- ImageBlockDelta$: () => ImageBlockDelta$,
- ImageBlock$: () => ImageBlock$,
- GuardrailWordPolicyAssessment$: () => GuardrailWordPolicyAssessment$,
- GuardrailWordPolicyAction: () => GuardrailWordPolicyAction,
- GuardrailUsage$: () => GuardrailUsage$,
- GuardrailTraceAssessment$: () => GuardrailTraceAssessment$,
- GuardrailTrace: () => GuardrailTrace,
- GuardrailTopicType: () => GuardrailTopicType2,
- GuardrailTopicPolicyAssessment$: () => GuardrailTopicPolicyAssessment$,
- GuardrailTopicPolicyAction: () => GuardrailTopicPolicyAction,
- GuardrailTopic$: () => GuardrailTopic$2,
- GuardrailTextCharactersCoverage$: () => GuardrailTextCharactersCoverage$,
- GuardrailTextBlock$: () => GuardrailTextBlock$,
- GuardrailStreamProcessingMode: () => GuardrailStreamProcessingMode,
- GuardrailStreamConfiguration$: () => GuardrailStreamConfiguration$,
- GuardrailSensitiveInformationPolicyAssessment$: () => GuardrailSensitiveInformationPolicyAssessment$,
- GuardrailSensitiveInformationPolicyAction: () => GuardrailSensitiveInformationPolicyAction,
- GuardrailRegexFilter$: () => GuardrailRegexFilter$,
- GuardrailPiiEntityType: () => GuardrailPiiEntityType2,
- GuardrailPiiEntityFilter$: () => GuardrailPiiEntityFilter$,
- GuardrailOwnership: () => GuardrailOwnership,
- GuardrailOutputScope: () => GuardrailOutputScope,
- GuardrailOutputContent$: () => GuardrailOutputContent$,
- GuardrailOrigin: () => GuardrailOrigin,
- GuardrailManagedWordType: () => GuardrailManagedWordType,
- GuardrailManagedWord$: () => GuardrailManagedWord$,
- GuardrailInvocationMetrics$: () => GuardrailInvocationMetrics$,
- GuardrailImageSource$: () => GuardrailImageSource$,
- GuardrailImageFormat: () => GuardrailImageFormat,
- GuardrailImageCoverage$: () => GuardrailImageCoverage$,
- GuardrailImageBlock$: () => GuardrailImageBlock$,
- GuardrailCustomWord$: () => GuardrailCustomWord$,
- GuardrailCoverage$: () => GuardrailCoverage$,
- GuardrailConverseTextBlock$: () => GuardrailConverseTextBlock$,
- GuardrailConverseImageSource$: () => GuardrailConverseImageSource$,
- GuardrailConverseImageFormat: () => GuardrailConverseImageFormat,
- GuardrailConverseImageBlock$: () => GuardrailConverseImageBlock$,
- GuardrailConverseContentQualifier: () => GuardrailConverseContentQualifier,
- GuardrailConverseContentBlock$: () => GuardrailConverseContentBlock$,
- GuardrailContextualGroundingPolicyAssessment$: () => GuardrailContextualGroundingPolicyAssessment$,
- GuardrailContextualGroundingPolicyAction: () => GuardrailContextualGroundingPolicyAction,
- GuardrailContextualGroundingFilterType: () => GuardrailContextualGroundingFilterType2,
- GuardrailContextualGroundingFilter$: () => GuardrailContextualGroundingFilter$2,
- GuardrailContentSource: () => GuardrailContentSource,
- GuardrailContentQualifier: () => GuardrailContentQualifier,
- GuardrailContentPolicyAssessment$: () => GuardrailContentPolicyAssessment$,
- GuardrailContentPolicyAction: () => GuardrailContentPolicyAction,
- GuardrailContentFilterType: () => GuardrailContentFilterType2,
- GuardrailContentFilterStrength: () => GuardrailContentFilterStrength,
- GuardrailContentFilterConfidence: () => GuardrailContentFilterConfidence,
- GuardrailContentFilter$: () => GuardrailContentFilter$2,
- GuardrailContentBlock$: () => GuardrailContentBlock$,
- GuardrailConfiguration$: () => GuardrailConfiguration$2,
- GuardrailAutomatedReasoningValidFinding$: () => GuardrailAutomatedReasoningValidFinding$,
- GuardrailAutomatedReasoningTranslationOption$: () => GuardrailAutomatedReasoningTranslationOption$,
- GuardrailAutomatedReasoningTranslationAmbiguousFinding$: () => GuardrailAutomatedReasoningTranslationAmbiguousFinding$,
- GuardrailAutomatedReasoningTranslation$: () => GuardrailAutomatedReasoningTranslation$,
- GuardrailAutomatedReasoningTooComplexFinding$: () => GuardrailAutomatedReasoningTooComplexFinding$,
- GuardrailAutomatedReasoningStatement$: () => GuardrailAutomatedReasoningStatement$,
- GuardrailAutomatedReasoningScenario$: () => GuardrailAutomatedReasoningScenario$,
- GuardrailAutomatedReasoningSatisfiableFinding$: () => GuardrailAutomatedReasoningSatisfiableFinding$,
- GuardrailAutomatedReasoningRule$: () => GuardrailAutomatedReasoningRule$,
- GuardrailAutomatedReasoningPolicyAssessment$: () => GuardrailAutomatedReasoningPolicyAssessment$,
- GuardrailAutomatedReasoningNoTranslationsFinding$: () => GuardrailAutomatedReasoningNoTranslationsFinding$,
- GuardrailAutomatedReasoningLogicWarningType: () => GuardrailAutomatedReasoningLogicWarningType,
- GuardrailAutomatedReasoningLogicWarning$: () => GuardrailAutomatedReasoningLogicWarning$,
- GuardrailAutomatedReasoningInvalidFinding$: () => GuardrailAutomatedReasoningInvalidFinding$,
- GuardrailAutomatedReasoningInputTextReference$: () => GuardrailAutomatedReasoningInputTextReference$,
- GuardrailAutomatedReasoningImpossibleFinding$: () => GuardrailAutomatedReasoningImpossibleFinding$,
- GuardrailAutomatedReasoningFinding$: () => GuardrailAutomatedReasoningFinding$,
- GuardrailAssessment$: () => GuardrailAssessment$,
- GuardrailAction: () => GuardrailAction,
- GetAsyncInvokeResponse$: () => GetAsyncInvokeResponse$,
- GetAsyncInvokeRequest$: () => GetAsyncInvokeRequest$,
- GetAsyncInvokeCommand: () => GetAsyncInvokeCommand,
- GetAsyncInvoke$: () => GetAsyncInvoke$,
- ErrorBlock$: () => ErrorBlock$,
- DocumentSource$: () => DocumentSource$,
- DocumentPageLocation$: () => DocumentPageLocation$,
- DocumentFormat: () => DocumentFormat,
- DocumentContentBlock$: () => DocumentContentBlock$,
- DocumentChunkLocation$: () => DocumentChunkLocation$,
- DocumentCharLocation$: () => DocumentCharLocation$,
- DocumentBlock$: () => DocumentBlock$,
- CountTokensResponse$: () => CountTokensResponse$,
- CountTokensRequest$: () => CountTokensRequest$,
- CountTokensInput$: () => CountTokensInput$,
- CountTokensCommand: () => CountTokensCommand,
- CountTokens$: () => CountTokens$,
- ConverseTrace$: () => ConverseTrace$,
- ConverseTokensRequest$: () => ConverseTokensRequest$,
- ConverseStreamTrace$: () => ConverseStreamTrace$,
- ConverseStreamResponse$: () => ConverseStreamResponse$,
- ConverseStreamRequest$: () => ConverseStreamRequest$,
- ConverseStreamOutput$: () => ConverseStreamOutput$,
- ConverseStreamMetrics$: () => ConverseStreamMetrics$,
- ConverseStreamMetadataEvent$: () => ConverseStreamMetadataEvent$,
- ConverseStreamCommand: () => ConverseStreamCommand,
- ConverseStream$: () => ConverseStream$,
- ConverseResponse$: () => ConverseResponse$,
- ConverseRequest$: () => ConverseRequest$,
- ConverseOutput$: () => ConverseOutput$,
- ConverseMetrics$: () => ConverseMetrics$,
- ConverseCommand: () => ConverseCommand,
- Converse$: () => Converse$,
- ConversationRole: () => ConversationRole,
- ContentBlockStopEvent$: () => ContentBlockStopEvent$,
- ContentBlockStartEvent$: () => ContentBlockStartEvent$,
- ContentBlockStart$: () => ContentBlockStart$,
- ContentBlockDeltaEvent$: () => ContentBlockDeltaEvent$,
- ContentBlockDelta$: () => ContentBlockDelta$,
- ContentBlock$: () => ContentBlock$,
- ConflictException$: () => ConflictException$2,
- ConflictException: () => ConflictException2,
- CitationsDelta$: () => CitationsDelta$,
- CitationsContentBlock$: () => CitationsContentBlock$,
- CitationsConfig$: () => CitationsConfig$,
- CitationSourceContentDelta$: () => CitationSourceContentDelta$,
- CitationSourceContent$: () => CitationSourceContent$,
- CitationLocation$: () => CitationLocation$,
- CitationGeneratedContent$: () => CitationGeneratedContent$,
- Citation$: () => Citation$,
- CacheTTL: () => CacheTTL,
- CachePointType: () => CachePointType,
- CachePointBlock$: () => CachePointBlock$,
- CacheDetail$: () => CacheDetail$,
- BidirectionalOutputPayloadPart$: () => BidirectionalOutputPayloadPart$,
- BidirectionalInputPayloadPart$: () => BidirectionalInputPayloadPart$,
- BedrockRuntimeServiceException$: () => BedrockRuntimeServiceException$,
- BedrockRuntimeServiceException: () => BedrockRuntimeServiceException,
- BedrockRuntimeClient: () => BedrockRuntimeClient,
- BedrockRuntime: () => BedrockRuntime,
- AutoToolChoice$: () => AutoToolChoice$,
- AudioSource$: () => AudioSource$,
- AudioFormat: () => AudioFormat,
- AudioBlock$: () => AudioBlock$,
- AsyncInvokeSummary$: () => AsyncInvokeSummary$,
- AsyncInvokeStatus: () => AsyncInvokeStatus,
- AsyncInvokeS3OutputDataConfig$: () => AsyncInvokeS3OutputDataConfig$,
- AsyncInvokeOutputDataConfig$: () => AsyncInvokeOutputDataConfig$,
- ApplyGuardrailResponse$: () => ApplyGuardrailResponse$,
- ApplyGuardrailRequest$: () => ApplyGuardrailRequest$,
- ApplyGuardrailCommand: () => ApplyGuardrailCommand,
- ApplyGuardrail$: () => ApplyGuardrail$,
- AppliedGuardrailDetails$: () => AppliedGuardrailDetails$,
- AnyToolChoice$: () => AnyToolChoice$,
- AccessDeniedException$: () => AccessDeniedException$2,
- AccessDeniedException: () => AccessDeniedException2,
- $Command: () => Command4
-});
-var init_dist_es38 = __esm(() => {
- init_BedrockRuntimeServiceException();
- init_BedrockRuntimeClient();
- init_BedrockRuntime();
- init_commands2();
- init_schemas_02();
- init_pagination6();
- init_enums2();
- init_errors5();
- init_models_02();
-});
-
-// src/utils/model/bedrock.ts
-function findFirstMatch(profiles, substring) {
- return profiles.find((p3) => p3.includes(substring)) ?? null;
-}
-async function createBedrockClient() {
- const { BedrockClient: BedrockClient3 } = await Promise.resolve().then(() => (init_dist_es20(), exports_dist_es11));
- const region = getAWSRegion();
- const skipAuth = isEnvTruthy(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH);
- const clientConfig = {
- region,
- ...process.env.ANTHROPIC_BEDROCK_BASE_URL && {
- endpoint: process.env.ANTHROPIC_BEDROCK_BASE_URL
- },
- ...await getAWSClientProxyConfig(),
- ...skipAuth && {
- requestHandler: new (await Promise.resolve().then(() => __toESM(require_dist_cjs5(), 1))).NodeHttpHandler,
- httpAuthSchemes: [
- {
- schemeId: "smithy.api#noAuth",
- identityProvider: () => async () => ({}),
- signer: new (await Promise.resolve().then(() => __toESM(require_dist_cjs37(), 1))).NoAuthSigner
- }
- ],
- httpAuthSchemeProvider: () => [{ schemeId: "smithy.api#noAuth" }]
- }
- };
- if (!skipAuth && !process.env.AWS_BEARER_TOKEN_BEDROCK) {
- const cachedCredentials = await refreshAndGetAwsCredentials();
- if (cachedCredentials) {
- clientConfig.credentials = {
- accessKeyId: cachedCredentials.accessKeyId,
- secretAccessKey: cachedCredentials.secretAccessKey,
- sessionToken: cachedCredentials.sessionToken
- };
- }
- }
- return new BedrockClient3(clientConfig);
-}
-async function createBedrockRuntimeClient() {
- const { BedrockRuntimeClient: BedrockRuntimeClient3 } = await Promise.resolve().then(() => (init_dist_es38(), exports_dist_es13));
- const region = getAWSRegion();
- const skipAuth = isEnvTruthy(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH);
- const clientConfig = {
- region,
- ...process.env.ANTHROPIC_BEDROCK_BASE_URL && {
- endpoint: process.env.ANTHROPIC_BEDROCK_BASE_URL
- },
- ...await getAWSClientProxyConfig(),
- ...skipAuth && {
- requestHandler: new (await Promise.resolve().then(() => __toESM(require_dist_cjs5(), 1))).NodeHttpHandler,
- httpAuthSchemes: [
- {
- schemeId: "smithy.api#noAuth",
- identityProvider: () => async () => ({}),
- signer: new (await Promise.resolve().then(() => __toESM(require_dist_cjs37(), 1))).NoAuthSigner
- }
- ],
- httpAuthSchemeProvider: () => [{ schemeId: "smithy.api#noAuth" }]
- }
- };
- if (!skipAuth && !process.env.AWS_BEARER_TOKEN_BEDROCK) {
- const cachedCredentials = await refreshAndGetAwsCredentials();
- if (cachedCredentials) {
- clientConfig.credentials = {
- accessKeyId: cachedCredentials.accessKeyId,
- secretAccessKey: cachedCredentials.secretAccessKey,
- sessionToken: cachedCredentials.sessionToken
- };
- }
- }
- return new BedrockRuntimeClient3(clientConfig);
-}
-function isFoundationModel(modelId) {
- return modelId.startsWith("anthropic.");
-}
-function extractModelIdFromArn(modelId) {
- if (!modelId.startsWith("arn:")) {
- return modelId;
- }
- const lastSlashIndex = modelId.lastIndexOf("/");
- if (lastSlashIndex === -1) {
- return modelId;
- }
- return modelId.substring(lastSlashIndex + 1);
-}
-function getBedrockRegionPrefix(modelId) {
- const effectiveModelId = extractModelIdFromArn(modelId);
- for (const prefix of BEDROCK_REGION_PREFIXES) {
- if (effectiveModelId.startsWith(`${prefix}.anthropic.`)) {
- return prefix;
- }
- }
- return;
-}
-function applyBedrockRegionPrefix(modelId, prefix) {
- const existingPrefix = getBedrockRegionPrefix(modelId);
- if (existingPrefix) {
- return modelId.replace(`${existingPrefix}.`, `${prefix}.`);
- }
- if (isFoundationModel(modelId)) {
- return `${prefix}.${modelId}`;
- }
- return modelId;
-}
-var getBedrockInferenceProfiles, getInferenceProfileBackingModel, BEDROCK_REGION_PREFIXES;
-var init_bedrock = __esm(() => {
- init_memoize();
- init_auth14();
- init_envUtils();
- init_log2();
- init_proxy();
- getBedrockInferenceProfiles = memoize_default(async function() {
- const [client7, { ListInferenceProfilesCommand: ListInferenceProfilesCommand3 }] = await Promise.all([
- createBedrockClient(),
- Promise.resolve().then(() => (init_dist_es20(), exports_dist_es11))
- ]);
- const allProfiles = [];
- let nextToken;
- try {
- do {
- const command7 = new ListInferenceProfilesCommand3({
- ...nextToken && { nextToken },
- typeEquals: "SYSTEM_DEFINED"
- });
- const response4 = await client7.send(command7);
- if (response4.inferenceProfileSummaries) {
- allProfiles.push(...response4.inferenceProfileSummaries);
- }
- nextToken = response4.nextToken;
- } while (nextToken);
- return allProfiles.filter((profile4) => profile4.inferenceProfileId?.includes("anthropic")).map((profile4) => profile4.inferenceProfileId).filter(Boolean);
- } catch (error40) {
- logError2(error40);
- throw error40;
- }
- });
- getInferenceProfileBackingModel = memoize_default(async function(profileId) {
- try {
- const [client7, { GetInferenceProfileCommand: GetInferenceProfileCommand3 }] = await Promise.all([
- createBedrockClient(),
- Promise.resolve().then(() => (init_dist_es20(), exports_dist_es11))
- ]);
- const command7 = new GetInferenceProfileCommand3({
- inferenceProfileIdentifier: profileId
- });
- const response4 = await client7.send(command7);
- if (!response4.models || response4.models.length === 0) {
- return null;
- }
- const primaryModel = response4.models[0];
- if (!primaryModel?.modelArn) {
- return null;
- }
- const lastSlashIndex = primaryModel.modelArn.lastIndexOf("/");
- return lastSlashIndex >= 0 ? primaryModel.modelArn.substring(lastSlashIndex + 1) : primaryModel.modelArn;
- } catch (error40) {
- logError2(error40);
- return null;
- }
- });
- BEDROCK_REGION_PREFIXES = ["us", "eu", "apac", "global"];
-});
-
-// src/utils/model/configs.ts
-var CLAUDE_3_7_SONNET_CONFIG, CLAUDE_3_5_V2_SONNET_CONFIG, CLAUDE_3_5_HAIKU_CONFIG, CLAUDE_HAIKU_4_5_CONFIG, CLAUDE_SONNET_4_CONFIG, CLAUDE_SONNET_4_5_CONFIG, CLAUDE_OPUS_4_CONFIG, CLAUDE_OPUS_4_1_CONFIG, CLAUDE_OPUS_4_5_CONFIG, CLAUDE_OPUS_4_6_CONFIG, CLAUDE_SONNET_4_6_CONFIG, ALL_MODEL_CONFIGS, CANONICAL_MODEL_IDS, CANONICAL_ID_TO_KEY;
-var init_configs = __esm(() => {
- CLAUDE_3_7_SONNET_CONFIG = {
- firstParty: "claude-3-7-sonnet-20250219",
- bedrock: "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
- vertex: "claude-3-7-sonnet@20250219",
- foundry: "claude-3-7-sonnet"
- };
- CLAUDE_3_5_V2_SONNET_CONFIG = {
- firstParty: "claude-3-5-sonnet-20241022",
- bedrock: "anthropic.claude-3-5-sonnet-20241022-v2:0",
- vertex: "claude-3-5-sonnet-v2@20241022",
- foundry: "claude-3-5-sonnet"
- };
- CLAUDE_3_5_HAIKU_CONFIG = {
- firstParty: "claude-3-5-haiku-20241022",
- bedrock: "us.anthropic.claude-3-5-haiku-20241022-v1:0",
- vertex: "claude-3-5-haiku@20241022",
- foundry: "claude-3-5-haiku"
- };
- CLAUDE_HAIKU_4_5_CONFIG = {
- firstParty: "claude-haiku-4-5-20251001",
- bedrock: "us.anthropic.claude-haiku-4-5-20251001-v1:0",
- vertex: "claude-haiku-4-5@20251001",
- foundry: "claude-haiku-4-5"
- };
- CLAUDE_SONNET_4_CONFIG = {
- firstParty: "claude-sonnet-4-20250514",
- bedrock: "us.anthropic.claude-sonnet-4-20250514-v1:0",
- vertex: "claude-sonnet-4@20250514",
- foundry: "claude-sonnet-4"
- };
- CLAUDE_SONNET_4_5_CONFIG = {
- firstParty: "claude-sonnet-4-5-20250929",
- bedrock: "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
- vertex: "claude-sonnet-4-5@20250929",
- foundry: "claude-sonnet-4-5"
- };
- CLAUDE_OPUS_4_CONFIG = {
- firstParty: "claude-opus-4-20250514",
- bedrock: "us.anthropic.claude-opus-4-20250514-v1:0",
- vertex: "claude-opus-4@20250514",
- foundry: "claude-opus-4"
- };
- CLAUDE_OPUS_4_1_CONFIG = {
- firstParty: "claude-opus-4-1-20250805",
- bedrock: "us.anthropic.claude-opus-4-1-20250805-v1:0",
- vertex: "claude-opus-4-1@20250805",
- foundry: "claude-opus-4-1"
- };
- CLAUDE_OPUS_4_5_CONFIG = {
- firstParty: "claude-opus-4-5-20251101",
- bedrock: "us.anthropic.claude-opus-4-5-20251101-v1:0",
- vertex: "claude-opus-4-5@20251101",
- foundry: "claude-opus-4-5"
- };
- CLAUDE_OPUS_4_6_CONFIG = {
- firstParty: "claude-opus-4-6",
- bedrock: "us.anthropic.claude-opus-4-6-v1",
- vertex: "claude-opus-4-6",
- foundry: "claude-opus-4-6"
- };
- CLAUDE_SONNET_4_6_CONFIG = {
- firstParty: "claude-sonnet-4-6",
- bedrock: "us.anthropic.claude-sonnet-4-6",
- vertex: "claude-sonnet-4-6",
- foundry: "claude-sonnet-4-6"
- };
- ALL_MODEL_CONFIGS = {
- haiku35: CLAUDE_3_5_HAIKU_CONFIG,
- haiku45: CLAUDE_HAIKU_4_5_CONFIG,
- sonnet35: CLAUDE_3_5_V2_SONNET_CONFIG,
- sonnet37: CLAUDE_3_7_SONNET_CONFIG,
- sonnet40: CLAUDE_SONNET_4_CONFIG,
- sonnet45: CLAUDE_SONNET_4_5_CONFIG,
- sonnet46: CLAUDE_SONNET_4_6_CONFIG,
- opus40: CLAUDE_OPUS_4_CONFIG,
- opus41: CLAUDE_OPUS_4_1_CONFIG,
- opus45: CLAUDE_OPUS_4_5_CONFIG,
- opus46: CLAUDE_OPUS_4_6_CONFIG
- };
- CANONICAL_MODEL_IDS = Object.values(ALL_MODEL_CONFIGS).map((c7) => c7.firstParty);
- CANONICAL_ID_TO_KEY = Object.fromEntries(Object.entries(ALL_MODEL_CONFIGS).map(([key, cfg]) => [cfg.firstParty, key]));
-});
-
-// src/utils/model/providers.ts
-function getAPIProvider() {
- return isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) ? "bedrock" : isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) ? "vertex" : isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY) ? "foundry" : "firstParty";
-}
-function getAPIProviderForStatsig() {
- return getAPIProvider();
-}
-function isFirstPartyAnthropicBaseUrl() {
- const baseUrl = process.env.ANTHROPIC_BASE_URL;
- if (!baseUrl) {
- return true;
- }
- try {
- const host = new URL(baseUrl).host;
- const allowedHosts = ["api.anthropic.com"];
- if (process.env.USER_TYPE === "ant") {
- allowedHosts.push("api-staging.anthropic.com");
- }
- return allowedHosts.includes(host);
- } catch {
- return false;
- }
-}
-var init_providers = __esm(() => {
- init_envUtils();
-});
-
-// src/utils/model/modelStrings.ts
-function getBuiltinModelStrings(provider3) {
- const out = {};
- for (const key of MODEL_KEYS) {
- out[key] = ALL_MODEL_CONFIGS[key][provider3];
- }
- return out;
-}
-async function getBedrockModelStrings() {
- const fallback = getBuiltinModelStrings("bedrock");
- let profiles;
- try {
- profiles = await getBedrockInferenceProfiles();
- } catch (error40) {
- logError2(error40);
- return fallback;
- }
- if (!profiles?.length) {
- return fallback;
- }
- const out = {};
- for (const key of MODEL_KEYS) {
- const needle = ALL_MODEL_CONFIGS[key].firstParty;
- out[key] = findFirstMatch(profiles, needle) || fallback[key];
- }
- return out;
-}
-function applyModelOverrides(ms) {
- const overrides = getInitialSettings().modelOverrides;
- if (!overrides) {
- return ms;
- }
- const out = { ...ms };
- for (const [canonicalId, override] of Object.entries(overrides)) {
- const key = CANONICAL_ID_TO_KEY[canonicalId];
- if (key && override) {
- out[key] = override;
- }
- }
- return out;
-}
-function resolveOverriddenModel(modelId) {
- let overrides;
- try {
- overrides = getInitialSettings().modelOverrides;
- } catch {
- return modelId;
- }
- if (!overrides) {
- return modelId;
- }
- for (const [canonicalId, override] of Object.entries(overrides)) {
- if (override === modelId) {
- return canonicalId;
- }
- }
- return modelId;
-}
-function initModelStrings() {
- const ms = getModelStrings();
- if (ms !== null) {
- return;
- }
- if (getAPIProvider() !== "bedrock") {
- setModelStrings(getBuiltinModelStrings(getAPIProvider()));
- return;
- }
- updateBedrockModelStrings();
-}
-function getModelStrings2() {
- const ms = getModelStrings();
- if (ms === null) {
- initModelStrings();
- return applyModelOverrides(getBuiltinModelStrings(getAPIProvider()));
- }
- return applyModelOverrides(ms);
-}
-async function ensureModelStringsInitialized() {
- const ms = getModelStrings();
- if (ms !== null) {
- return;
- }
- if (getAPIProvider() !== "bedrock") {
- setModelStrings(getBuiltinModelStrings(getAPIProvider()));
- return;
- }
- await updateBedrockModelStrings();
-}
-var MODEL_KEYS, updateBedrockModelStrings;
-var init_modelStrings = __esm(() => {
- init_state();
- init_log2();
- init_settings2();
- init_bedrock();
- init_configs();
- init_providers();
- MODEL_KEYS = Object.keys(ALL_MODEL_CONFIGS);
- updateBedrockModelStrings = sequential(async () => {
- if (getModelStrings() !== null) {
- return;
- }
- try {
- const ms = await getBedrockModelStrings();
- setModelStrings(ms);
- } catch (error40) {
- logError2(error40);
- }
- });
-});
-
-// src/utils/billing.ts
-function hasConsoleBillingAccess() {
- if (isEnvTruthy(process.env.DISABLE_COST_WARNINGS)) {
- return false;
- }
- const isSubscriber = isClaudeAISubscriber();
- if (isSubscriber)
- return false;
- const authSource = getAuthTokenSource();
- const hasApiKey = getAnthropicApiKey() !== null;
- if (!authSource.hasToken && !hasApiKey) {
- return false;
- }
- const config5 = getGlobalConfig();
- const orgRole = config5.oauthAccount?.organizationRole;
- const workspaceRole = config5.oauthAccount?.workspaceRole;
- if (!orgRole || !workspaceRole) {
- return false;
- }
- return ["admin", "billing"].includes(orgRole) || ["workspace_admin", "workspace_billing"].includes(workspaceRole);
-}
-function setMockBillingAccessOverride(value) {
- mockBillingAccessOverride = value;
-}
-function hasClaudeAiBillingAccess() {
- if (mockBillingAccessOverride !== null) {
- return mockBillingAccessOverride;
- }
- if (!isClaudeAISubscriber()) {
- return false;
- }
- const subscriptionType = getSubscriptionType();
- if (subscriptionType === "max" || subscriptionType === "pro") {
- return true;
- }
- const config5 = getGlobalConfig();
- const orgRole = config5.oauthAccount?.organizationRole;
- return !!orgRole && ["admin", "billing", "owner", "primary_owner"].includes(orgRole);
-}
-var mockBillingAccessOverride = null;
-var init_billing = __esm(() => {
- init_auth14();
- init_config();
- init_envUtils();
-});
-
-// src/services/mockRateLimits.ts
-function getMockHeaderless429Message() {
- if (process.env.USER_TYPE !== "ant") {
- return null;
- }
- if (process.env.CLAUDE_MOCK_HEADERLESS_429) {
- return process.env.CLAUDE_MOCK_HEADERLESS_429;
- }
- if (!mockEnabled) {
- return null;
- }
- return mockHeaderless429Message;
-}
-function getMockHeaders() {
- if (!mockEnabled || process.env.USER_TYPE !== "ant" || Object.keys(mockHeaders).length === 0) {
- return null;
- }
- return mockHeaders;
-}
-function clearMockHeaders() {
- mockHeaders = {};
- exceededLimits = [];
- mockSubscriptionType = null;
- mockFastModeRateLimitDurationMs = null;
- mockFastModeRateLimitExpiresAt = null;
- mockHeaderless429Message = null;
- setMockBillingAccessOverride(null);
- mockEnabled = false;
-}
-function applyMockHeaders(headers) {
- const mock = getMockHeaders();
- if (!mock) {
- return headers;
- }
- const newHeaders = new globalThis.Headers(headers);
- Object.entries(mock).forEach(([key, value]) => {
- if (value !== undefined) {
- newHeaders.set(key, value);
- }
- });
- return newHeaders;
-}
-function shouldProcessMockLimits() {
- if (process.env.USER_TYPE !== "ant") {
- return false;
- }
- return mockEnabled || Boolean(process.env.CLAUDE_MOCK_HEADERLESS_429);
-}
-function getMockSubscriptionType() {
- if (!mockEnabled || process.env.USER_TYPE !== "ant") {
- return null;
- }
- return mockSubscriptionType || DEFAULT_MOCK_SUBSCRIPTION;
-}
-function shouldUseMockSubscription() {
- return mockEnabled && mockSubscriptionType !== null && process.env.USER_TYPE === "ant";
-}
-function isMockFastModeRateLimitScenario() {
- return mockFastModeRateLimitDurationMs !== null;
-}
-function checkMockFastModeRateLimit(isFastModeActive) {
- if (mockFastModeRateLimitDurationMs === null) {
- return null;
- }
- if (!isFastModeActive) {
- return null;
- }
- if (mockFastModeRateLimitExpiresAt !== null && Date.now() >= mockFastModeRateLimitExpiresAt) {
- clearMockHeaders();
- return null;
- }
- if (mockFastModeRateLimitExpiresAt === null) {
- mockFastModeRateLimitExpiresAt = Date.now() + mockFastModeRateLimitDurationMs;
- }
- const remainingMs = mockFastModeRateLimitExpiresAt - Date.now();
- const headersToSend = { ...mockHeaders };
- headersToSend["retry-after"] = String(Math.max(1, Math.ceil(remainingMs / 1000)));
- return headersToSend;
-}
-var mockHeaders, mockEnabled = false, mockHeaderless429Message = null, mockSubscriptionType = null, mockFastModeRateLimitDurationMs = null, mockFastModeRateLimitExpiresAt = null, DEFAULT_MOCK_SUBSCRIPTION = "max", exceededLimits;
-var init_mockRateLimits = __esm(() => {
- init_billing();
- mockHeaders = {};
- exceededLimits = [];
-});
-
-// src/services/oauth/getOauthProfile.ts
-async function getOauthProfileFromApiKey() {
- const config5 = getGlobalConfig();
- const accountUuid = config5.oauthAccount?.accountUuid;
- const apiKey = getAnthropicApiKey();
- if (!accountUuid || !apiKey) {
- return;
- }
- const endpoint4 = `${getOauthConfig().BASE_API_URL}/api/claude_cli_profile`;
- try {
- const response4 = await axios_default.get(endpoint4, {
- headers: {
- "x-api-key": apiKey,
- "anthropic-beta": OAUTH_BETA_HEADER
- },
- params: {
- account_uuid: accountUuid
- },
- timeout: 1e4
- });
- return response4.data;
- } catch (error40) {
- logError2(error40);
- }
-}
-async function getOauthProfileFromOauthToken(accessToken) {
- const endpoint4 = `${getOauthConfig().BASE_API_URL}/api/oauth/profile`;
- try {
- const response4 = await axios_default.get(endpoint4, {
- headers: {
- Authorization: `Bearer ${accessToken}`,
- "Content-Type": "application/json"
- },
- timeout: 1e4
- });
- return response4.data;
- } catch (error40) {
- logError2(error40);
- }
-}
-var init_getOauthProfile = __esm(() => {
- init_axios2();
- init_oauth();
- init_auth14();
- init_config();
- init_log2();
-});
-
-// src/services/oauth/client.ts
-var exports_client = {};
-__export(exports_client, {
- storeOAuthAccountInfo: () => storeOAuthAccountInfo,
- shouldUseClaudeAIAuth: () => shouldUseClaudeAIAuth,
- refreshOAuthToken: () => refreshOAuthToken,
- populateOAuthAccountInfoIfNeeded: () => populateOAuthAccountInfoIfNeeded,
- parseScopes: () => parseScopes,
- isOAuthTokenExpired: () => isOAuthTokenExpired,
- getOrganizationUUID: () => getOrganizationUUID,
- fetchProfileInfo: () => fetchProfileInfo,
- fetchAndStoreUserRoles: () => fetchAndStoreUserRoles,
- exchangeCodeForTokens: () => exchangeCodeForTokens,
- createAndStoreApiKey: () => createAndStoreApiKey,
- buildAuthUrl: () => buildAuthUrl
-});
-function shouldUseClaudeAIAuth(scopes) {
- return Boolean(scopes?.includes(CLAUDE_AI_INFERENCE_SCOPE));
-}
-function parseScopes(scopeString) {
- return scopeString?.split(" ").filter(Boolean) ?? [];
-}
-function buildAuthUrl({
- codeChallenge,
- state,
- port,
- isManual,
- loginWithClaudeAi,
- inferenceOnly,
- orgUUID,
- loginHint,
- loginMethod
-}) {
- const authUrlBase = loginWithClaudeAi ? getOauthConfig().CLAUDE_AI_AUTHORIZE_URL : getOauthConfig().CONSOLE_AUTHORIZE_URL;
- const authUrl = new URL(authUrlBase);
- authUrl.searchParams.append("code", "true");
- authUrl.searchParams.append("client_id", getOauthConfig().CLIENT_ID);
- authUrl.searchParams.append("response_type", "code");
- authUrl.searchParams.append("redirect_uri", isManual ? getOauthConfig().MANUAL_REDIRECT_URL : `http://localhost:${port}/callback`);
- const scopesToUse = inferenceOnly ? [CLAUDE_AI_INFERENCE_SCOPE] : ALL_OAUTH_SCOPES;
- authUrl.searchParams.append("scope", scopesToUse.join(" "));
- authUrl.searchParams.append("code_challenge", codeChallenge);
- authUrl.searchParams.append("code_challenge_method", "S256");
- authUrl.searchParams.append("state", state);
- if (orgUUID) {
- authUrl.searchParams.append("orgUUID", orgUUID);
- }
- if (loginHint) {
- authUrl.searchParams.append("login_hint", loginHint);
- }
- if (loginMethod) {
- authUrl.searchParams.append("login_method", loginMethod);
- }
- return authUrl.toString();
-}
-async function exchangeCodeForTokens(authorizationCode, state, codeVerifier, port, useManualRedirect = false, expiresIn) {
- const requestBody = {
- grant_type: "authorization_code",
- code: authorizationCode,
- redirect_uri: useManualRedirect ? getOauthConfig().MANUAL_REDIRECT_URL : `http://localhost:${port}/callback`,
- client_id: getOauthConfig().CLIENT_ID,
- code_verifier: codeVerifier,
- state
- };
- if (expiresIn !== undefined) {
- requestBody.expires_in = expiresIn;
- }
- const response4 = await axios_default.post(getOauthConfig().TOKEN_URL, requestBody, {
- headers: { "Content-Type": "application/json" },
- timeout: 15000
- });
- if (response4.status !== 200) {
- throw new Error(response4.status === 401 ? "Authentication failed: Invalid authorization code" : `Token exchange failed (${response4.status}): ${response4.statusText}`);
- }
- logEvent("tengu_oauth_token_exchange_success", {});
- return response4.data;
-}
-async function refreshOAuthToken(refreshToken, { scopes: requestedScopes } = {}) {
- const requestBody = {
- grant_type: "refresh_token",
- refresh_token: refreshToken,
- client_id: getOauthConfig().CLIENT_ID,
- scope: ((requestedScopes?.length) ? requestedScopes : CLAUDE_AI_OAUTH_SCOPES).join(" ")
- };
- try {
- const response4 = await axios_default.post(getOauthConfig().TOKEN_URL, requestBody, {
- headers: { "Content-Type": "application/json" },
- timeout: 15000
- });
- if (response4.status !== 200) {
- throw new Error(`Token refresh failed: ${response4.statusText}`);
- }
- const data = response4.data;
- const {
- access_token: accessToken,
- refresh_token: newRefreshToken = refreshToken,
- expires_in: expiresIn
- } = data;
- const expiresAt = Date.now() + expiresIn * 1000;
- const scopes = parseScopes(data.scope);
- logEvent("tengu_oauth_token_refresh_success", {});
- const config5 = getGlobalConfig();
- const existing = getClaudeAIOAuthTokens();
- const haveProfileAlready = config5.oauthAccount?.billingType !== undefined && config5.oauthAccount?.accountCreatedAt !== undefined && config5.oauthAccount?.subscriptionCreatedAt !== undefined && existing?.subscriptionType != null && existing?.rateLimitTier != null;
- const profileInfo = haveProfileAlready ? null : await fetchProfileInfo(accessToken);
- if (profileInfo && config5.oauthAccount) {
- const updates = {};
- if (profileInfo.displayName !== undefined) {
- updates.displayName = profileInfo.displayName;
- }
- if (typeof profileInfo.hasExtraUsageEnabled === "boolean") {
- updates.hasExtraUsageEnabled = profileInfo.hasExtraUsageEnabled;
- }
- if (profileInfo.billingType !== null) {
- updates.billingType = profileInfo.billingType;
- }
- if (profileInfo.accountCreatedAt !== undefined) {
- updates.accountCreatedAt = profileInfo.accountCreatedAt;
- }
- if (profileInfo.subscriptionCreatedAt !== undefined) {
- updates.subscriptionCreatedAt = profileInfo.subscriptionCreatedAt;
- }
- if (Object.keys(updates).length > 0) {
- saveGlobalConfig((current) => ({
- ...current,
- oauthAccount: current.oauthAccount ? { ...current.oauthAccount, ...updates } : current.oauthAccount
- }));
- }
- }
- return {
- accessToken,
- refreshToken: newRefreshToken,
- expiresAt,
- scopes,
- subscriptionType: profileInfo?.subscriptionType ?? existing?.subscriptionType ?? null,
- rateLimitTier: profileInfo?.rateLimitTier ?? existing?.rateLimitTier ?? null,
- profile: profileInfo?.rawProfile,
- tokenAccount: data.account ? {
- uuid: data.account.uuid,
- emailAddress: data.account.email_address,
- organizationUuid: data.organization?.uuid
- } : undefined
- };
- } catch (error40) {
- const responseBody = axios_default.isAxiosError(error40) && error40.response?.data ? JSON.stringify(error40.response.data) : undefined;
- logEvent("tengu_oauth_token_refresh_failure", {
- error: error40.message,
- ...responseBody && {
- responseBody
- }
- });
- throw error40;
- }
-}
-async function fetchAndStoreUserRoles(accessToken) {
- const response4 = await axios_default.get(getOauthConfig().ROLES_URL, {
- headers: { Authorization: `Bearer ${accessToken}` }
- });
- if (response4.status !== 200) {
- throw new Error(`Failed to fetch user roles: ${response4.statusText}`);
- }
- const data = response4.data;
- const config5 = getGlobalConfig();
- if (!config5.oauthAccount) {
- throw new Error("OAuth account information not found in config");
- }
- saveGlobalConfig((current) => ({
- ...current,
- oauthAccount: current.oauthAccount ? {
- ...current.oauthAccount,
- organizationRole: data.organization_role,
- workspaceRole: data.workspace_role,
- organizationName: data.organization_name
- } : current.oauthAccount
- }));
- logEvent("tengu_oauth_roles_stored", {
- org_role: data.organization_role
- });
-}
-async function createAndStoreApiKey(accessToken) {
- try {
- const response4 = await axios_default.post(getOauthConfig().API_KEY_URL, null, {
- headers: { Authorization: `Bearer ${accessToken}` }
- });
- const apiKey = response4.data?.raw_key;
- if (apiKey) {
- await saveApiKey(apiKey);
- logEvent("tengu_oauth_api_key", {
- status: "success",
- statusCode: response4.status
- });
- return apiKey;
- }
- return null;
- } catch (error40) {
- logEvent("tengu_oauth_api_key", {
- status: "failure",
- error: error40 instanceof Error ? error40.message : String(error40)
- });
- throw error40;
- }
-}
-function isOAuthTokenExpired(expiresAt) {
- if (expiresAt === null) {
- return false;
- }
- const bufferTime = 5 * 60 * 1000;
- const now = Date.now();
- const expiresWithBuffer = now + bufferTime;
- return expiresWithBuffer >= expiresAt;
-}
-async function fetchProfileInfo(accessToken) {
- const profile4 = await getOauthProfileFromOauthToken(accessToken);
- const orgType = profile4?.organization?.organization_type;
- let subscriptionType = null;
- switch (orgType) {
- case "claude_max":
- subscriptionType = "max";
- break;
- case "claude_pro":
- subscriptionType = "pro";
- break;
- case "claude_enterprise":
- subscriptionType = "enterprise";
- break;
- case "claude_team":
- subscriptionType = "team";
- break;
- default:
- subscriptionType = null;
- break;
- }
- const result = {
- subscriptionType,
- rateLimitTier: profile4?.organization?.rate_limit_tier ?? null,
- hasExtraUsageEnabled: profile4?.organization?.has_extra_usage_enabled ?? null,
- billingType: profile4?.organization?.billing_type ?? null
- };
- if (profile4?.account?.display_name) {
- result.displayName = profile4.account.display_name;
- }
- if (profile4?.account?.created_at) {
- result.accountCreatedAt = profile4.account.created_at;
- }
- if (profile4?.organization?.subscription_created_at) {
- result.subscriptionCreatedAt = profile4.organization.subscription_created_at;
- }
- logEvent("tengu_oauth_profile_fetch_success", {});
- return { ...result, rawProfile: profile4 };
-}
-async function getOrganizationUUID() {
- const globalConfig2 = getGlobalConfig();
- const orgUUID = globalConfig2.oauthAccount?.organizationUuid;
- if (orgUUID) {
- return orgUUID;
- }
- const accessToken = getClaudeAIOAuthTokens()?.accessToken;
- if (accessToken === undefined || !hasProfileScope()) {
- return null;
- }
- const profile4 = await getOauthProfileFromOauthToken(accessToken);
- const profileOrgUUID = profile4?.organization?.uuid;
- if (!profileOrgUUID) {
- return null;
- }
- return profileOrgUUID;
-}
-async function populateOAuthAccountInfoIfNeeded() {
- const envAccountUuid = process.env.CLAUDE_CODE_ACCOUNT_UUID;
- const envUserEmail = process.env.CLAUDE_CODE_USER_EMAIL;
- const envOrganizationUuid = process.env.CLAUDE_CODE_ORGANIZATION_UUID;
- const hasEnvVars = Boolean(envAccountUuid && envUserEmail && envOrganizationUuid);
- if (envAccountUuid && envUserEmail && envOrganizationUuid) {
- if (!getGlobalConfig().oauthAccount) {
- storeOAuthAccountInfo({
- accountUuid: envAccountUuid,
- emailAddress: envUserEmail,
- organizationUuid: envOrganizationUuid
- });
- }
- }
- await checkAndRefreshOAuthTokenIfNeeded();
- const config5 = getGlobalConfig();
- if (config5.oauthAccount && config5.oauthAccount.billingType !== undefined && config5.oauthAccount.accountCreatedAt !== undefined && config5.oauthAccount.subscriptionCreatedAt !== undefined || !isClaudeAISubscriber() || !hasProfileScope()) {
- return false;
- }
- const tokens = getClaudeAIOAuthTokens();
- if (tokens?.accessToken) {
- const profile4 = await getOauthProfileFromOauthToken(tokens.accessToken);
- if (profile4) {
- if (hasEnvVars) {
- logForDebugging("OAuth profile fetch succeeded, overriding env var account info", { level: "info" });
- }
- storeOAuthAccountInfo({
- accountUuid: profile4.account.uuid,
- emailAddress: profile4.account.email,
- organizationUuid: profile4.organization.uuid,
- displayName: profile4.account.display_name || undefined,
- hasExtraUsageEnabled: profile4.organization.has_extra_usage_enabled ?? false,
- billingType: profile4.organization.billing_type ?? undefined,
- accountCreatedAt: profile4.account.created_at,
- subscriptionCreatedAt: profile4.organization.subscription_created_at ?? undefined
- });
- return true;
- }
- }
- return false;
-}
-function storeOAuthAccountInfo({
- accountUuid,
- emailAddress,
- organizationUuid,
- displayName,
- hasExtraUsageEnabled,
- billingType,
- accountCreatedAt,
- subscriptionCreatedAt
-}) {
- const accountInfo = {
- accountUuid,
- emailAddress,
- organizationUuid,
- hasExtraUsageEnabled,
- billingType,
- accountCreatedAt,
- subscriptionCreatedAt
- };
- if (displayName) {
- accountInfo.displayName = displayName;
- }
- saveGlobalConfig((current) => {
- if (current.oauthAccount?.accountUuid === accountInfo.accountUuid && current.oauthAccount?.emailAddress === accountInfo.emailAddress && current.oauthAccount?.organizationUuid === accountInfo.organizationUuid && current.oauthAccount?.displayName === accountInfo.displayName && current.oauthAccount?.hasExtraUsageEnabled === accountInfo.hasExtraUsageEnabled && current.oauthAccount?.billingType === accountInfo.billingType && current.oauthAccount?.accountCreatedAt === accountInfo.accountCreatedAt && current.oauthAccount?.subscriptionCreatedAt === accountInfo.subscriptionCreatedAt) {
- return current;
- }
- return { ...current, oauthAccount: accountInfo };
- });
-}
-var init_client7 = __esm(() => {
- init_axios2();
- init_analytics();
- init_oauth();
- init_auth14();
- init_config();
- init_debug();
- init_getOauthProfile();
-});
-
-// src/utils/authFileDescriptor.ts
-import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
-function maybePersistTokenForSubprocesses(path8, token, tokenName) {
- if (!isEnvTruthy(process.env.CLAUDE_CODE_REMOTE)) {
- return;
- }
- try {
- mkdirSync2(CCR_TOKEN_DIR, { recursive: true, mode: 448 });
- writeFileSync2(path8, token, { encoding: "utf8", mode: 384 });
- logForDebugging(`Persisted ${tokenName} to ${path8} for subprocess access`);
- } catch (error40) {
- logForDebugging(`Failed to persist ${tokenName} to disk (non-fatal): ${errorMessage(error40)}`, { level: "error" });
- }
-}
-function readTokenFromWellKnownFile(path8, tokenName) {
- try {
- const fsOps = getFsImplementation();
- const token = fsOps.readFileSync(path8, { encoding: "utf8" }).trim();
- if (!token) {
- return null;
- }
- logForDebugging(`Read ${tokenName} from well-known file ${path8}`);
- return token;
- } catch (error40) {
- if (!isENOENT(error40)) {
- logForDebugging(`Failed to read ${tokenName} from ${path8}: ${errorMessage(error40)}`, { level: "debug" });
- }
- return null;
- }
-}
-function getCredentialFromFd({
- envVar,
- wellKnownPath,
- label,
- getCached,
- setCached
-}) {
- const cached2 = getCached();
- if (cached2 !== undefined) {
- return cached2;
- }
- const fdEnv = process.env[envVar];
- if (!fdEnv) {
- const fromFile = readTokenFromWellKnownFile(wellKnownPath, label);
- setCached(fromFile);
- return fromFile;
- }
- const fd = parseInt(fdEnv, 10);
- if (Number.isNaN(fd)) {
- logForDebugging(`${envVar} must be a valid file descriptor number, got: ${fdEnv}`, { level: "error" });
- setCached(null);
- return null;
- }
- try {
- const fsOps = getFsImplementation();
- const fdPath = process.platform === "darwin" || process.platform === "freebsd" ? `/dev/fd/${fd}` : `/proc/self/fd/${fd}`;
- const token = fsOps.readFileSync(fdPath, { encoding: "utf8" }).trim();
- if (!token) {
- logForDebugging(`File descriptor contained empty ${label}`, {
- level: "error"
- });
- setCached(null);
- return null;
- }
- logForDebugging(`Successfully read ${label} from file descriptor ${fd}`);
- setCached(token);
- maybePersistTokenForSubprocesses(wellKnownPath, token, label);
- return token;
- } catch (error40) {
- logForDebugging(`Failed to read ${label} from file descriptor ${fd}: ${errorMessage(error40)}`, { level: "error" });
- const fromFile = readTokenFromWellKnownFile(wellKnownPath, label);
- setCached(fromFile);
- return fromFile;
- }
-}
-function getOAuthTokenFromFileDescriptor() {
- return getCredentialFromFd({
- envVar: "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
- wellKnownPath: CCR_OAUTH_TOKEN_PATH,
- label: "OAuth token",
- getCached: getOauthTokenFromFd,
- setCached: setOauthTokenFromFd
- });
-}
-function getApiKeyFromFileDescriptor() {
- return getCredentialFromFd({
- envVar: "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
- wellKnownPath: CCR_API_KEY_PATH,
- label: "API key",
- getCached: getApiKeyFromFd,
- setCached: setApiKeyFromFd
- });
-}
-var CCR_TOKEN_DIR = "/home/claude/.claude/remote", CCR_OAUTH_TOKEN_PATH, CCR_API_KEY_PATH, CCR_SESSION_INGRESS_TOKEN_PATH;
-var init_authFileDescriptor = __esm(() => {
- init_state();
- init_debug();
- init_envUtils();
- init_errors();
- init_fsOperations();
- CCR_OAUTH_TOKEN_PATH = `${CCR_TOKEN_DIR}/.oauth_token`;
- CCR_API_KEY_PATH = `${CCR_TOKEN_DIR}/.api_key`;
- CCR_SESSION_INGRESS_TOKEN_PATH = `${CCR_TOKEN_DIR}/.session_ingress_token`;
-});
-
-// src/utils/authPortable.ts
-async function maybeRemoveApiKeyFromMacOSKeychainThrows() {
- if (process.platform === "darwin") {
- const storageServiceName = getMacOsKeychainStorageServiceName();
- const result = await execa(`security delete-generic-password -a $USER -s "${storageServiceName}"`, { shell: true, reject: false });
- if (result.exitCode !== 0) {
- throw new Error("Failed to delete keychain entry");
- }
- }
-}
-function normalizeApiKeyForConfig(apiKey) {
- return apiKey.slice(-20);
-}
-var init_authPortable = __esm(() => {
- init_execa();
- init_macOsKeychainHelpers();
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/client.js
-class Client4 {
- config;
- middlewareStack = import_middleware_stack7.constructStack();
- initConfig;
- handlers;
- constructor(config5) {
- this.config = config5;
- const { protocol, protocolSettings } = config5;
- if (protocolSettings) {
- if (typeof protocol === "function") {
- config5.protocol = new protocol(protocolSettings);
- }
- }
- }
- send(command7, optionsOrCb, cb) {
- const options2 = typeof optionsOrCb !== "function" ? optionsOrCb : undefined;
- const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
- const useHandlerCache = options2 === undefined && this.config.cacheMiddleware === true;
- let handler;
- if (useHandlerCache) {
- if (!this.handlers) {
- this.handlers = new WeakMap;
- }
- const handlers = this.handlers;
- if (handlers.has(command7.constructor)) {
- handler = handlers.get(command7.constructor);
- } else {
- handler = command7.resolveMiddleware(this.middlewareStack, this.config, options2);
- handlers.set(command7.constructor, handler);
- }
- } else {
- delete this.handlers;
- handler = command7.resolveMiddleware(this.middlewareStack, this.config, options2);
- }
- if (callback) {
- handler(command7).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => {});
- } else {
- return handler(command7).then((result) => result.output);
- }
- }
- destroy() {
- this.config?.requestHandler?.destroy?.();
- delete this.handlers;
- }
-}
-var import_middleware_stack7;
-var init_client8 = __esm(() => {
- import_middleware_stack7 = __toESM(require_dist_cjs12(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js
-var import_protocols12;
-var init_collect_stream_body4 = __esm(() => {
- import_protocols12 = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/abort.js
-var init_abort5 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/auth/auth.js
-var HttpAuthLocation4;
-var init_auth7 = __esm(() => {
- (function(HttpAuthLocation5) {
- HttpAuthLocation5["HEADER"] = "header";
- HttpAuthLocation5["QUERY"] = "query";
- })(HttpAuthLocation4 || (HttpAuthLocation4 = {}));
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
-var HttpApiKeyAuthLocation4;
-var init_HttpApiKeyAuth4 = __esm(() => {
- (function(HttpApiKeyAuthLocation5) {
- HttpApiKeyAuthLocation5["HEADER"] = "header";
- HttpApiKeyAuthLocation5["QUERY"] = "query";
- })(HttpApiKeyAuthLocation4 || (HttpApiKeyAuthLocation4 = {}));
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js
-var init_HttpAuthScheme4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js
-var init_HttpAuthSchemeProvider4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/auth/HttpSigner.js
-var init_HttpSigner4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js
-var init_IdentityProviderConfig4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/auth/index.js
-var init_auth8 = __esm(() => {
- init_auth7();
- init_HttpApiKeyAuth4();
- init_HttpAuthScheme4();
- init_HttpAuthSchemeProvider4();
- init_HttpSigner4();
- init_IdentityProviderConfig4();
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js
-var init_blob_payload_input_types4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/checksum.js
-var init_checksum10 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/client.js
-var init_client9 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/command.js
-var init_command9 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/connection/config.js
-var init_config5 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/connection/manager.js
-var init_manager4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/connection/pool.js
-var init_pool4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/connection/index.js
-var init_connection4 = __esm(() => {
- init_config5();
- init_manager4();
- init_pool4();
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/crypto.js
-var init_crypto5 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/encode.js
-var init_encode4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/endpoint.js
-var EndpointURLScheme4;
-var init_endpoint4 = __esm(() => {
- (function(EndpointURLScheme5) {
- EndpointURLScheme5["HTTP"] = "http";
- EndpointURLScheme5["HTTPS"] = "https";
- })(EndpointURLScheme4 || (EndpointURLScheme4 = {}));
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js
-var init_EndpointRuleObject4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js
-var init_ErrorRuleObject4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js
-var init_RuleSetObject4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/endpoints/shared.js
-var init_shared6 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js
-var init_TreeRuleObject4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/endpoints/index.js
-var init_endpoints4 = __esm(() => {
- init_EndpointRuleObject4();
- init_ErrorRuleObject4();
- init_RuleSetObject4();
- init_shared6();
- init_TreeRuleObject4();
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/eventStream.js
-var init_eventStream4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/extensions/checksum.js
-var AlgorithmId4;
-var init_checksum11 = __esm(() => {
- (function(AlgorithmId5) {
- AlgorithmId5["MD5"] = "md5";
- AlgorithmId5["CRC32"] = "crc32";
- AlgorithmId5["CRC32C"] = "crc32c";
- AlgorithmId5["SHA1"] = "sha1";
- AlgorithmId5["SHA256"] = "sha256";
- })(AlgorithmId4 || (AlgorithmId4 = {}));
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js
-var init_defaultClientConfiguration4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js
-var init_defaultExtensionConfiguration7 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/extensions/index.js
-var init_extensions13 = __esm(() => {
- init_checksum11();
- init_defaultClientConfiguration4();
- init_defaultExtensionConfiguration7();
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/feature-ids.js
-var init_feature_ids4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/http.js
-var FieldPosition4;
-var init_http5 = __esm(() => {
- (function(FieldPosition5) {
- FieldPosition5[FieldPosition5["HEADER"] = 0] = "HEADER";
- FieldPosition5[FieldPosition5["TRAILER"] = 1] = "TRAILER";
- })(FieldPosition4 || (FieldPosition4 = {}));
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js
-var init_httpHandlerInitialization4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js
-var init_apiKeyIdentity4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js
-var init_awsCredentialIdentity4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/identity/identity.js
-var init_identity8 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js
-var init_tokenIdentity4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/identity/index.js
-var init_identity9 = __esm(() => {
- init_apiKeyIdentity4();
- init_awsCredentialIdentity4();
- init_identity8();
- init_tokenIdentity4();
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/logger.js
-var init_logger4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/middleware.js
-var SMITHY_CONTEXT_KEY4 = "__smithy_context";
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/pagination.js
-var init_pagination7 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/profile.js
-var IniSectionType4;
-var init_profile4 = __esm(() => {
- (function(IniSectionType5) {
- IniSectionType5["PROFILE"] = "profile";
- IniSectionType5["SSO_SESSION"] = "sso-session";
- IniSectionType5["SERVICES"] = "services";
- })(IniSectionType4 || (IniSectionType4 = {}));
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/response.js
-var init_response4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/retry.js
-var init_retry4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/schema/schema.js
-var init_schema4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/schema/traits.js
-var init_traits4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/schema/schema-deprecated.js
-var init_schema_deprecated4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/schema/sentinels.js
-var init_sentinels4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/schema/static-schemas.js
-var init_static_schemas4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/serde.js
-var init_serde4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/shapes.js
-var init_shapes4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/signature.js
-var init_signature4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/stream.js
-var init_stream5 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js
-var init_streaming_blob_common_types4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js
-var init_streaming_blob_payload_input_types4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js
-var init_streaming_blob_payload_output_types4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/transfer.js
-var RequestHandlerProtocol4;
-var init_transfer4 = __esm(() => {
- (function(RequestHandlerProtocol5) {
- RequestHandlerProtocol5["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol5["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol5["TDS_8_0"] = "tds/8.0";
- })(RequestHandlerProtocol4 || (RequestHandlerProtocol4 = {}));
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js
-var init_client_payload_blob_type_narrow4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/transform/mutable.js
-var init_mutable4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/transform/no-undefined.js
-var init_no_undefined4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/transform/type-transform.js
-var init_type_transform4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/uri.js
-var init_uri4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/util.js
-var init_util6 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/waiter.js
-var init_waiter4 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-es/index.js
-var init_dist_es39 = __esm(() => {
- init_abort5();
- init_auth8();
- init_blob_payload_input_types4();
- init_checksum10();
- init_client9();
- init_command9();
- init_connection4();
- init_crypto5();
- init_encode4();
- init_endpoint4();
- init_endpoints4();
- init_eventStream4();
- init_extensions13();
- init_feature_ids4();
- init_http5();
- init_httpHandlerInitialization4();
- init_identity9();
- init_logger4();
- init_pagination7();
- init_profile4();
- init_response4();
- init_retry4();
- init_schema4();
- init_traits4();
- init_schema_deprecated4();
- init_sentinels4();
- init_static_schemas4();
- init_serde4();
- init_shapes4();
- init_signature4();
- init_stream5();
- init_streaming_blob_common_types4();
- init_streaming_blob_payload_input_types4();
- init_streaming_blob_payload_output_types4();
- init_transfer4();
- init_client_payload_blob_type_narrow4();
- init_mutable4();
- init_no_undefined4();
- init_type_transform4();
- init_uri4();
- init_util6();
- init_waiter4();
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/schemaLogFilter.js
-function schemaLogFilter4(schema5, data) {
- if (data == null) {
- return data;
- }
- const ns = import_schema8.NormalizedSchema.of(schema5);
- if (ns.getMergedTraits().sensitive) {
- return SENSITIVE_STRING7;
- }
- if (ns.isListSchema()) {
- const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING7;
- }
- } else if (ns.isMapSchema()) {
- const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive;
- if (isSensitive) {
- return SENSITIVE_STRING7;
- }
- } else if (ns.isStructSchema() && typeof data === "object") {
- const object2 = data;
- const newObject = {};
- for (const [member, memberNs] of ns.structIterator()) {
- if (object2[member] != null) {
- newObject[member] = schemaLogFilter4(memberNs, object2[member]);
- }
- }
- return newObject;
- }
- return data;
-}
-var import_schema8, SENSITIVE_STRING7 = "***SensitiveInformation***";
-var init_schemaLogFilter4 = __esm(() => {
- import_schema8 = __toESM(require_schema(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/command.js
-class Command5 {
- middlewareStack = import_middleware_stack8.constructStack();
- schema;
- static classBuilder() {
- return new ClassBuilder4;
- }
- resolveMiddlewareWithContext(clientStack, configuration, options2, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
- for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options2)) {
- this.middlewareStack.use(mw);
- }
- const stack = clientStack.concat(this.middlewareStack);
- const { logger: logger5 } = configuration;
- const handlerExecutionContext = {
- logger: logger5,
- clientName,
- commandName,
- inputFilterSensitiveLog,
- outputFilterSensitiveLog,
- [SMITHY_CONTEXT_KEY4]: {
- commandInstance: this,
- ...smithyContext
- },
- ...additionalContext
- };
- const { requestHandler } = configuration;
- return stack.resolve((request2) => requestHandler.handle(request2.request, options2 || {}), handlerExecutionContext);
- }
-}
-
-class ClassBuilder4 {
- _init = () => {};
- _ep = {};
- _middlewareFn = () => [];
- _commandName = "";
- _clientName = "";
- _additionalContext = {};
- _smithyContext = {};
- _inputFilterSensitiveLog = undefined;
- _outputFilterSensitiveLog = undefined;
- _serializer = null;
- _deserializer = null;
- _operationSchema;
- init(cb) {
- this._init = cb;
- }
- ep(endpointParameterInstructions) {
- this._ep = endpointParameterInstructions;
- return this;
- }
- m(middlewareSupplier) {
- this._middlewareFn = middlewareSupplier;
- return this;
- }
- s(service, operation, smithyContext = {}) {
- this._smithyContext = {
- service,
- operation,
- ...smithyContext
- };
- return this;
- }
- c(additionalContext = {}) {
- this._additionalContext = additionalContext;
- return this;
- }
- n(clientName, commandName) {
- this._clientName = clientName;
- this._commandName = commandName;
- return this;
- }
- f(inputFilter = (_) => _, outputFilter = (_) => _) {
- this._inputFilterSensitiveLog = inputFilter;
- this._outputFilterSensitiveLog = outputFilter;
- return this;
- }
- ser(serializer) {
- this._serializer = serializer;
- return this;
- }
- de(deserializer) {
- this._deserializer = deserializer;
- return this;
- }
- sc(operation) {
- this._operationSchema = operation;
- this._smithyContext.operationSchema = operation;
- return this;
- }
- build() {
- const closure = this;
- let CommandRef;
- return CommandRef = class extends Command5 {
- input;
- static getEndpointParameterInstructions() {
- return closure._ep;
- }
- constructor(...[input]) {
- super();
- this.input = input ?? {};
- closure._init(this);
- this.schema = closure._operationSchema;
- }
- resolveMiddleware(stack, configuration, options2) {
- const op = closure._operationSchema;
- const input = op?.[4] ?? op?.input;
- const output = op?.[5] ?? op?.output;
- return this.resolveMiddlewareWithContext(stack, configuration, options2, {
- CommandCtor: CommandRef,
- middlewareFn: closure._middlewareFn,
- clientName: closure._clientName,
- commandName: closure._commandName,
- inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter4.bind(null, input) : (_) => _),
- outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter4.bind(null, output) : (_) => _),
- smithyContext: closure._smithyContext,
- additionalContext: closure._additionalContext
- });
- }
- serialize = closure._serializer;
- deserialize = closure._deserializer;
- };
- }
-}
-var import_middleware_stack8;
-var init_command10 = __esm(() => {
- init_dist_es39();
- init_schemaLogFilter4();
- import_middleware_stack8 = __toESM(require_dist_cjs12(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/constants.js
-var SENSITIVE_STRING8 = "***SensitiveInformation***";
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js
-var createAggregatedClient4 = (commands5, Client5, options2) => {
- for (const [command8, CommandCtor] of Object.entries(commands5)) {
- const methodImpl = async function(args, optionsOrCb, cb) {
- const command9 = new CommandCtor(args);
- if (typeof optionsOrCb === "function") {
- this.send(command9, optionsOrCb);
- } else if (typeof cb === "function") {
- if (typeof optionsOrCb !== "object")
- throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
- this.send(command9, optionsOrCb || {}, cb);
- } else {
- return this.send(command9, optionsOrCb);
- }
- };
- const methodName = (command8[0].toLowerCase() + command8.slice(1)).replace(/Command$/, "");
- Client5.prototype[methodName] = methodImpl;
- }
- const { paginators: paginators3 = {}, waiters = {} } = options2 ?? {};
- for (const [paginatorName, paginatorFn] of Object.entries(paginators3)) {
- if (Client5.prototype[paginatorName] === undefined) {
- Client5.prototype[paginatorName] = function(commandInput = {}, paginationConfiguration, ...rest) {
- return paginatorFn({
- ...paginationConfiguration,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
- for (const [waiterName, waiterFn] of Object.entries(waiters)) {
- if (Client5.prototype[waiterName] === undefined) {
- Client5.prototype[waiterName] = async function(commandInput = {}, waiterConfiguration, ...rest) {
- let config6 = waiterConfiguration;
- if (typeof waiterConfiguration === "number") {
- config6 = {
- maxWaitTime: waiterConfiguration
- };
- }
- return waiterFn({
- ...config6,
- client: this
- }, commandInput, ...rest);
- };
- }
- }
-};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/exceptions.js
-var ServiceException4, decorateServiceException4 = (exception, additions = {}) => {
- Object.entries(additions).filter(([, v3]) => v3 !== undefined).forEach(([k3, v3]) => {
- if (exception[k3] == undefined || exception[k3] === "") {
- exception[k3] = v3;
- }
- });
- const message = exception.message || exception.Message || "UnknownError";
- exception.message = message;
- delete exception.Message;
- return exception;
-};
-var init_exceptions4 = __esm(() => {
- ServiceException4 = class ServiceException4 extends Error {
- $fault;
- $response;
- $retryable;
- $metadata;
- constructor(options2) {
- super(options2.message);
- Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
- this.name = options2.name;
- this.$fault = options2.$fault;
- this.$metadata = options2.$metadata;
- }
- static isInstance(value) {
- if (!value)
- return false;
- const candidate = value;
- return ServiceException4.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
- }
- static [Symbol.hasInstance](instance) {
- if (!instance)
- return false;
- const candidate = instance;
- if (this === ServiceException4) {
- return ServiceException4.isInstance(instance);
- }
- if (ServiceException4.isInstance(instance)) {
- if (candidate.name && this.name) {
- return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
- }
- return this.prototype.isPrototypeOf(instance);
- }
- return false;
- }
- };
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js
-var throwDefaultError4 = ({ output, parsedBody, exceptionCtor, errorCode }) => {
- const $metadata = deserializeMetadata4(output);
- const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined;
- const response5 = new exceptionCtor({
- name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
- $fault: "client",
- $metadata
- });
- throw decorateServiceException4(response5, parsedBody);
-}, withBaseException4 = (ExceptionCtor) => {
- return ({ output, parsedBody, errorCode }) => {
- throwDefaultError4({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
- };
-}, deserializeMetadata4 = (output) => ({
- httpStatusCode: output.statusCode,
- requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
- extendedRequestId: output.headers["x-amz-id-2"],
- cfId: output.headers["x-amz-cf-id"]
-});
-var init_default_error_handler4 = __esm(() => {
- init_exceptions4();
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js
-var loadConfigsForDefaultMode4 = (mode) => {
- switch (mode) {
- case "standard":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "in-region":
- return {
- retryMode: "standard",
- connectionTimeout: 1100
- };
- case "cross-region":
- return {
- retryMode: "standard",
- connectionTimeout: 3100
- };
- case "mobile":
- return {
- retryMode: "standard",
- connectionTimeout: 30000
- };
- default:
- return {};
- }
-};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js
-var warningEmitted4 = false, emitWarningIfUnsupportedVersion7 = (version2) => {
- if (version2 && !warningEmitted4 && parseInt(version2.substring(1, version2.indexOf("."))) < 16) {
- warningEmitted4 = true;
- }
-};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js
-var import_protocols13;
-var init_extended_encode_uri_component4 = __esm(() => {
- import_protocols13 = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js
-var knownAlgorithms4, getChecksumConfiguration4 = (runtimeConfig) => {
- const checksumAlgorithms = [];
- for (const id in AlgorithmId4) {
- const algorithmId = AlgorithmId4[id];
- if (runtimeConfig[algorithmId] === undefined) {
- continue;
- }
- checksumAlgorithms.push({
- algorithmId: () => algorithmId,
- checksumConstructor: () => runtimeConfig[algorithmId]
- });
- }
- for (const [id, ChecksumCtor] of Object.entries(runtimeConfig.checksumAlgorithms ?? {})) {
- checksumAlgorithms.push({
- algorithmId: () => id,
- checksumConstructor: () => ChecksumCtor
- });
- }
- return {
- addChecksumAlgorithm(algo) {
- runtimeConfig.checksumAlgorithms = runtimeConfig.checksumAlgorithms ?? {};
- const id = algo.algorithmId();
- const ctor = algo.checksumConstructor();
- if (knownAlgorithms4.includes(id)) {
- runtimeConfig.checksumAlgorithms[id.toUpperCase()] = ctor;
- } else {
- runtimeConfig.checksumAlgorithms[id] = ctor;
- }
- checksumAlgorithms.push(algo);
- },
- checksumAlgorithms() {
- return checksumAlgorithms;
- }
- };
-}, resolveChecksumRuntimeConfig4 = (clientConfig) => {
- const runtimeConfig = {};
- clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
- const id = checksumAlgorithm.algorithmId();
- if (knownAlgorithms4.includes(id)) {
- runtimeConfig[id] = checksumAlgorithm.checksumConstructor();
- }
- });
- return runtimeConfig;
-};
-var init_checksum12 = __esm(() => {
- init_dist_es39();
- knownAlgorithms4 = Object.values(AlgorithmId4);
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js
-var getRetryConfiguration4 = (runtimeConfig) => {
- return {
- setRetryStrategy(retryStrategy) {
- runtimeConfig.retryStrategy = retryStrategy;
- },
- retryStrategy() {
- return runtimeConfig.retryStrategy;
- }
- };
-}, resolveRetryRuntimeConfig4 = (retryStrategyConfiguration) => {
- const runtimeConfig = {};
- runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
- return runtimeConfig;
-};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js
-var getDefaultExtensionConfiguration4 = (runtimeConfig) => {
- return Object.assign(getChecksumConfiguration4(runtimeConfig), getRetryConfiguration4(runtimeConfig));
-}, getDefaultClientConfiguration4, resolveDefaultRuntimeConfig4 = (config6) => {
- return Object.assign(resolveChecksumRuntimeConfig4(config6), resolveRetryRuntimeConfig4(config6));
-};
-var init_defaultExtensionConfiguration8 = __esm(() => {
- init_checksum12();
- getDefaultClientConfiguration4 = getDefaultExtensionConfiguration4;
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/extensions/index.js
-var init_extensions14 = __esm(() => {
- init_defaultExtensionConfiguration8();
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js
-var getArrayIfSingleItem4 = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray];
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js
-var getValueFromTextNode4 = (obj) => {
- const textNodeName = "#text";
- for (const key in obj) {
- if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) {
- obj[key] = obj[key][textNodeName];
- } else if (typeof obj[key] === "object" && obj[key] !== null) {
- obj[key] = getValueFromTextNode4(obj[key]);
- }
- }
- return obj;
-};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js
-var isSerializableHeaderValue4 = (value) => {
- return value != null;
-};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js
-class NoOpLogger7 {
- trace() {}
- debug() {}
- info() {}
- warn() {}
- error() {}
-}
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/object-mapping.js
-function map5(arg0, arg1, arg2) {
- let target;
- let filter2;
- let instructions;
- if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
- target = {};
- instructions = arg0;
- } else {
- target = arg0;
- if (typeof arg1 === "function") {
- filter2 = arg1;
- instructions = arg2;
- return mapWithFilter4(target, filter2, instructions);
- } else {
- instructions = arg1;
- }
- }
- for (const key of Object.keys(instructions)) {
- if (!Array.isArray(instructions[key])) {
- target[key] = instructions[key];
- continue;
- }
- applyInstruction4(target, null, instructions, key);
- }
- return target;
-}
-var convertMap4 = (target) => {
- const output = {};
- for (const [k3, v3] of Object.entries(target || {})) {
- output[k3] = [, v3];
- }
- return output;
-}, take4 = (source, instructions) => {
- const out = {};
- for (const key in instructions) {
- applyInstruction4(out, source, instructions, key);
- }
- return out;
-}, mapWithFilter4 = (target, filter2, instructions) => {
- return map5(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
- if (Array.isArray(value)) {
- _instructions[key] = value;
- } else {
- if (typeof value === "function") {
- _instructions[key] = [filter2, value()];
- } else {
- _instructions[key] = [filter2, value];
- }
- }
- return _instructions;
- }, {}));
-}, applyInstruction4 = (target, source, instructions, targetKey) => {
- if (source !== null) {
- let instruction = instructions[targetKey];
- if (typeof instruction === "function") {
- instruction = [, instruction];
- }
- const [filter3 = nonNullish4, valueFn = pass4, sourceKey = targetKey] = instruction;
- if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) {
- target[targetKey] = valueFn(source[sourceKey]);
- }
- return;
- }
- let [filter2, value] = instructions[targetKey];
- if (typeof value === "function") {
- let _value;
- const defaultFilterPassed = filter2 === undefined && (_value = value()) != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(undefined) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed) {
- target[targetKey] = _value;
- } else if (customFilterPassed) {
- target[targetKey] = value();
- }
- } else {
- const defaultFilterPassed = filter2 === undefined && value != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed || customFilterPassed) {
- target[targetKey] = value;
- }
- }
-}, nonNullish4 = (_) => _ != null, pass4 = (_) => _;
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/resolve-path.js
-var import_protocols14;
-var init_resolve_path4 = __esm(() => {
- import_protocols14 = __toESM(require_protocols(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/ser-utils.js
-var serializeFloat4 = (value) => {
- if (value !== value) {
- return "NaN";
- }
- switch (value) {
- case Infinity:
- return "Infinity";
- case -Infinity:
- return "-Infinity";
- default:
- return value;
- }
-}, serializeDateTime4 = (date5) => date5.toISOString().replace(".000Z", "Z");
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/serde-json.js
-var _json4 = (obj) => {
- if (obj == null) {
- return {};
- }
- if (Array.isArray(obj)) {
- return obj.filter((_) => _ != null).map(_json4);
- }
- if (typeof obj === "object") {
- const target = {};
- for (const key of Object.keys(obj)) {
- if (obj[key] == null) {
- continue;
- }
- target[key] = _json4(obj[key]);
- }
- return target;
- }
- return obj;
-};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-es/index.js
-var exports_dist_es14 = {};
-__export(exports_dist_es14, {
- withBaseException: () => withBaseException4,
- throwDefaultError: () => throwDefaultError4,
- take: () => take4,
- serializeFloat: () => serializeFloat4,
- serializeDateTime: () => serializeDateTime4,
- resolvedPath: () => import_protocols14.resolvedPath,
- resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig4,
- map: () => map5,
- loadConfigsForDefaultMode: () => loadConfigsForDefaultMode4,
- isSerializableHeaderValue: () => isSerializableHeaderValue4,
- getValueFromTextNode: () => getValueFromTextNode4,
- getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration4,
- getDefaultClientConfiguration: () => getDefaultClientConfiguration4,
- getArrayIfSingleItem: () => getArrayIfSingleItem4,
- extendedEncodeURIComponent: () => import_protocols13.extendedEncodeURIComponent,
- emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion7,
- decorateServiceException: () => decorateServiceException4,
- createAggregatedClient: () => createAggregatedClient4,
- convertMap: () => convertMap4,
- collectBody: () => import_protocols12.collectBody,
- _json: () => _json4,
- ServiceException: () => ServiceException4,
- SENSITIVE_STRING: () => SENSITIVE_STRING8,
- NoOpLogger: () => NoOpLogger7,
- Command: () => Command5,
- Client: () => Client4
-});
-var init_dist_es40 = __esm(() => {
- init_client8();
- init_collect_stream_body4();
- init_command10();
- init_default_error_handler4();
- init_exceptions4();
- init_extended_encode_uri_component4();
- init_extensions14();
- init_resolve_path4();
- __reExport(exports_dist_es14, __toESM(require_serde(), 1));
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/auth/httpAuthSchemeProvider.js
-function createAwsAuthSigv4HttpAuthOption3(authParameters) {
- return {
- schemeId: "aws.auth#sigv4",
- signingProperties: {
- name: "sts",
- region: authParameters.region
- },
- propertiesExtractor: (config6, context) => ({
- signingProperties: {
- config: config6,
- context
- }
- })
- };
-}
-function createSmithyApiNoAuthHttpAuthOption(authParameters) {
- return {
- schemeId: "smithy.api#noAuth"
- };
-}
-var import_httpAuthSchemes8, import_util_middleware3, defaultSTSHttpAuthSchemeParametersProvider = async (config6, context, input) => {
- return {
- operation: import_util_middleware3.getSmithyContext(context).operation,
- region: await import_util_middleware3.normalizeProvider(config6.region)() || (() => {
- throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
- })()
- };
-}, defaultSTSHttpAuthSchemeProvider = (authParameters) => {
- const options2 = [];
- switch (authParameters.operation) {
- case "AssumeRoleWithSAML":
- {
- options2.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
- break;
- }
- ;
- case "AssumeRoleWithWebIdentity":
- {
- options2.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
- break;
- }
- ;
- default: {
- options2.push(createAwsAuthSigv4HttpAuthOption3(authParameters));
- }
- }
- return options2;
-}, resolveStsAuthConfig = (input) => Object.assign(input, {
- stsClientCtor: STSClient
-}), resolveHttpAuthSchemeConfig3 = (config6) => {
- const config_0 = resolveStsAuthConfig(config6);
- const config_1 = import_httpAuthSchemes8.resolveAwsSdkSigV4Config(config_0);
- return Object.assign(config_1, {
- authSchemePreference: import_util_middleware3.normalizeProvider(config6.authSchemePreference ?? [])
- });
-};
-var init_httpAuthSchemeProvider3 = __esm(() => {
- init_STSClient();
- import_httpAuthSchemes8 = __toESM(require_httpAuthSchemes(), 1);
- import_util_middleware3 = __toESM(require_dist_cjs30(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/endpoint/EndpointParameters.js
-var resolveClientEndpointParameters3 = (options2) => {
- return Object.assign(options2, {
- useDualstackEndpoint: options2.useDualstackEndpoint ?? false,
- useFipsEndpoint: options2.useFipsEndpoint ?? false,
- useGlobalEndpoint: options2.useGlobalEndpoint ?? false,
- defaultSigningName: "sts"
- });
-}, commonParams3;
-var init_EndpointParameters3 = __esm(() => {
- commonParams3 = {
- UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" },
- UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
- Endpoint: { type: "builtInParams", name: "endpoint" },
- Region: { type: "builtInParams", name: "region" },
- UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
- };
-});
-
-// node_modules/@aws-sdk/client-sts/package.json
-var package_default3;
-var init_package3 = __esm(() => {
- package_default3 = {
- name: "@aws-sdk/client-sts",
- description: "AWS SDK for JavaScript Sts Client for Node.js, Browser and React Native",
- version: "3.1020.0",
- scripts: {
- build: "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs",
- "build:cjs": "node ../../scripts/compilation/inline client-sts",
- "build:es": "tsc -p tsconfig.es.json",
- "build:include:deps": 'yarn g:turbo run build -F="$npm_package_name"',
- "build:types": "premove ./dist-types tsconfig.types.tsbuildinfo && tsc -p tsconfig.types.json",
- "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
- clean: "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",
- "extract:docs": "api-extractor run --local",
- "generate:client": "node ../../scripts/generate-clients/single-service --solo sts",
- test: "yarn g:vitest run",
- "test:e2e": "yarn g:vitest run -c vitest.config.e2e.mts --mode development",
- "test:e2e:watch": "yarn g:vitest watch -c vitest.config.e2e.mts",
- "test:index": "tsc --noEmit ./test/index-types.ts && node ./test/index-objects.spec.mjs",
- "test:integration": "yarn g:vitest run --passWithNoTests -c vitest.config.integ.mts",
- "test:integration:watch": "yarn g:vitest run --passWithNoTests -c vitest.config.integ.mts",
- "test:watch": "yarn g:vitest watch"
- },
- main: "./dist-cjs/index.js",
- types: "./dist-types/index.d.ts",
- module: "./dist-es/index.js",
- sideEffects: false,
- dependencies: {
- "@aws-crypto/sha256-browser": "5.2.0",
- "@aws-crypto/sha256-js": "5.2.0",
- "@aws-sdk/core": "^3.973.26",
- "@aws-sdk/credential-provider-node": "^3.972.28",
- "@aws-sdk/middleware-host-header": "^3.972.8",
- "@aws-sdk/middleware-logger": "^3.972.8",
- "@aws-sdk/middleware-recursion-detection": "^3.972.9",
- "@aws-sdk/middleware-user-agent": "^3.972.27",
- "@aws-sdk/region-config-resolver": "^3.972.10",
- "@aws-sdk/types": "^3.973.6",
- "@aws-sdk/util-endpoints": "^3.996.5",
- "@aws-sdk/util-user-agent-browser": "^3.972.8",
- "@aws-sdk/util-user-agent-node": "^3.973.13",
- "@smithy/config-resolver": "^4.4.13",
- "@smithy/core": "^3.23.13",
- "@smithy/fetch-http-handler": "^5.3.15",
- "@smithy/hash-node": "^4.2.12",
- "@smithy/invalid-dependency": "^4.2.12",
- "@smithy/middleware-content-length": "^4.2.12",
- "@smithy/middleware-endpoint": "^4.4.28",
- "@smithy/middleware-retry": "^4.4.45",
- "@smithy/middleware-serde": "^4.2.16",
- "@smithy/middleware-stack": "^4.2.12",
- "@smithy/node-config-provider": "^4.3.12",
- "@smithy/node-http-handler": "^4.5.1",
- "@smithy/protocol-http": "^5.3.12",
- "@smithy/smithy-client": "^4.12.8",
- "@smithy/types": "^4.13.1",
- "@smithy/url-parser": "^4.2.12",
- "@smithy/util-base64": "^4.3.2",
- "@smithy/util-body-length-browser": "^4.2.2",
- "@smithy/util-body-length-node": "^4.2.3",
- "@smithy/util-defaults-mode-browser": "^4.3.44",
- "@smithy/util-defaults-mode-node": "^4.2.48",
- "@smithy/util-endpoints": "^3.3.3",
- "@smithy/util-middleware": "^4.2.12",
- "@smithy/util-retry": "^4.2.12",
- "@smithy/util-utf8": "^4.2.2",
- tslib: "^2.6.2"
- },
- devDependencies: {
- "@smithy/snapshot-testing": "^2.0.4",
- "@tsconfig/node20": "20.1.8",
- "@types/node": "^20.14.8",
- concurrently: "7.0.0",
- "downlevel-dts": "0.10.1",
- premove: "4.0.0",
- typescript: "~5.8.3",
- vitest: "^4.0.17"
- },
- engines: {
- node: ">=20.0.0"
- },
- typesVersions: {
- "<4.5": {
- "dist-types/*": [
- "dist-types/ts3.4/*"
- ]
- }
- },
- files: [
- "dist-*/**"
- ],
- author: {
- name: "AWS SDK for JavaScript Team",
- url: "https://aws.amazon.com/javascript/"
- },
- license: "Apache-2.0",
- browser: {
- "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
- },
- "react-native": {
- "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
- },
- homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sts",
- repository: {
- type: "git",
- url: "https://github.com/aws/aws-sdk-js-v3.git",
- directory: "clients/client-sts"
- }
- };
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-es/index.js
-var isArrayBuffer6 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-es/index.js
-import { Buffer as Buffer11 } from "buffer";
-var fromArrayBuffer4 = (input, offset = 0, length = input.byteLength - offset) => {
- if (!isArrayBuffer6(input)) {
- throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
- }
- return Buffer11.from(input, offset, length);
-}, fromString4 = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? Buffer11.from(input, encoding) : Buffer11.from(input);
-};
-var init_dist_es41 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-es/fromBase64.js
-var BASE64_REGEX3, fromBase645 = (input) => {
- if (input.length * 3 % 4 !== 0) {
- throw new TypeError(`Incorrect padding on base64 string.`);
- }
- if (!BASE64_REGEX3.exec(input)) {
- throw new TypeError(`Invalid base64 string.`);
- }
- const buffer = fromString4(input, "base64");
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
-};
-var init_fromBase643 = __esm(() => {
- init_dist_es41();
- BASE64_REGEX3 = /^[A-Za-z0-9+/]*={0,2}$/;
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-es/toBase64.js
-var import_util_utf86, toBase645 = (_input) => {
- let input;
- if (typeof _input === "string") {
- input = import_util_utf86.fromUtf8(_input);
- } else {
- input = _input;
- }
- if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
- throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
- }
- return fromArrayBuffer4(input.buffer, input.byteOffset, input.byteLength).toString("base64");
-};
-var init_toBase643 = __esm(() => {
- init_dist_es41();
- import_util_utf86 = __toESM(require_dist_cjs17(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-es/index.js
-var init_dist_es42 = __esm(() => {
- init_fromBase643();
- init_toBase643();
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/endpoint/ruleset.js
-var F = "required", G3 = "type", H2 = "fn", I2 = "argv", J = "ref", a4 = false, b3 = true, c7 = "booleanEquals", d3 = "stringEquals", e3 = "sigv4", f3 = "sts", g3 = "us-east-1", h4 = "endpoint", i4 = "https://sts.{Region}.{PartitionResult#dnsSuffix}", j3 = "tree", k3 = "error", l3 = "getAttr", m3, n4, o4, p3, q3, r3, s3, t3, u4, v3, w, x2, y2, z2, A, B, C2, D2, E, _data3, ruleSet3;
-var init_ruleset3 = __esm(() => {
- m3 = { [F]: false, [G3]: "string" };
- n4 = { [F]: true, default: false, [G3]: "boolean" };
- o4 = { [J]: "Endpoint" };
- p3 = { [H2]: "isSet", [I2]: [{ [J]: "Region" }] };
- q3 = { [J]: "Region" };
- r3 = { [H2]: "aws.partition", [I2]: [q3], assign: "PartitionResult" };
- s3 = { [J]: "UseFIPS" };
- t3 = { [J]: "UseDualStack" };
- u4 = { url: "https://sts.amazonaws.com", properties: { authSchemes: [{ name: e3, signingName: f3, signingRegion: g3 }] }, headers: {} };
- v3 = {};
- w = { conditions: [{ [H2]: d3, [I2]: [q3, "aws-global"] }], [h4]: u4, [G3]: h4 };
- x2 = { [H2]: c7, [I2]: [s3, true] };
- y2 = { [H2]: c7, [I2]: [t3, true] };
- z2 = { [H2]: l3, [I2]: [{ [J]: "PartitionResult" }, "supportsFIPS"] };
- A = { [J]: "PartitionResult" };
- B = { [H2]: c7, [I2]: [true, { [H2]: l3, [I2]: [A, "supportsDualStack"] }] };
- C2 = [{ [H2]: "isSet", [I2]: [o4] }];
- D2 = [x2];
- E = [y2];
- _data3 = { version: "1.0", parameters: { Region: m3, UseDualStack: n4, UseFIPS: n4, Endpoint: m3, UseGlobalEndpoint: n4 }, rules: [{ conditions: [{ [H2]: c7, [I2]: [{ [J]: "UseGlobalEndpoint" }, b3] }, { [H2]: "not", [I2]: C2 }, p3, r3, { [H2]: c7, [I2]: [s3, a4] }, { [H2]: c7, [I2]: [t3, a4] }], rules: [{ conditions: [{ [H2]: d3, [I2]: [q3, "ap-northeast-1"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "ap-south-1"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "ap-southeast-1"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "ap-southeast-2"] }], endpoint: u4, [G3]: h4 }, w, { conditions: [{ [H2]: d3, [I2]: [q3, "ca-central-1"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "eu-central-1"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "eu-north-1"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "eu-west-1"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "eu-west-2"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "eu-west-3"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "sa-east-1"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, g3] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "us-east-2"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "us-west-1"] }], endpoint: u4, [G3]: h4 }, { conditions: [{ [H2]: d3, [I2]: [q3, "us-west-2"] }], endpoint: u4, [G3]: h4 }, { endpoint: { url: i4, properties: { authSchemes: [{ name: e3, signingName: f3, signingRegion: "{Region}" }] }, headers: v3 }, [G3]: h4 }], [G3]: j3 }, { conditions: C2, rules: [{ conditions: D2, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G3]: k3 }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G3]: k3 }, { endpoint: { url: o4, properties: v3, headers: v3 }, [G3]: h4 }], [G3]: j3 }, { conditions: [p3], rules: [{ conditions: [r3], rules: [{ conditions: [x2, y2], rules: [{ conditions: [{ [H2]: c7, [I2]: [b3, z2] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v3, headers: v3 }, [G3]: h4 }], [G3]: j3 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G3]: k3 }], [G3]: j3 }, { conditions: D2, rules: [{ conditions: [{ [H2]: c7, [I2]: [z2, b3] }], rules: [{ conditions: [{ [H2]: d3, [I2]: [{ [H2]: l3, [I2]: [A, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v3, headers: v3 }, [G3]: h4 }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v3, headers: v3 }, [G3]: h4 }], [G3]: j3 }, { error: "FIPS is enabled but this partition does not support FIPS", [G3]: k3 }], [G3]: j3 }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v3, headers: v3 }, [G3]: h4 }], [G3]: j3 }, { error: "DualStack is enabled but this partition does not support DualStack", [G3]: k3 }], [G3]: j3 }, w, { endpoint: { url: i4, properties: v3, headers: v3 }, [G3]: h4 }], [G3]: j3 }], [G3]: j3 }, { error: "Invalid Configuration: Missing Region", [G3]: k3 }] };
- ruleSet3 = _data3;
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/endpoint/endpointResolver.js
-var import_util_endpoints5, import_util_endpoints6, cache4, defaultEndpointResolver3 = (endpointParams, context = {}) => {
- return cache4.get(endpointParams, () => import_util_endpoints6.resolveEndpoint(ruleSet3, {
- endpointParams,
- logger: context.logger
- }));
-};
-var init_endpointResolver3 = __esm(() => {
- init_ruleset3();
- import_util_endpoints5 = __toESM(require_dist_cjs51(), 1);
- import_util_endpoints6 = __toESM(require_dist_cjs50(), 1);
- cache4 = new import_util_endpoints6.EndpointCache({
- size: 50,
- params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"]
- });
- import_util_endpoints6.customEndpointFunctions.aws = import_util_endpoints5.awsEndpointFunctions;
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/models/STSServiceException.js
-var STSServiceException;
-var init_STSServiceException = __esm(() => {
- init_dist_es40();
- STSServiceException = class STSServiceException extends ServiceException4 {
- constructor(options2) {
- super(options2);
- Object.setPrototypeOf(this, STSServiceException.prototype);
- }
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/models/errors.js
-var ExpiredTokenException, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, IDPRejectedClaimException, InvalidIdentityTokenException, IDPCommunicationErrorException, InvalidAuthorizationMessageException, ExpiredTradeInTokenException, JWTPayloadSizeExceededException, OutboundWebIdentityFederationDisabledException, SessionDurationEscalationException;
-var init_errors6 = __esm(() => {
- init_STSServiceException();
- ExpiredTokenException = class ExpiredTokenException extends STSServiceException {
- name = "ExpiredTokenException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ExpiredTokenException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ExpiredTokenException.prototype);
- }
- };
- MalformedPolicyDocumentException = class MalformedPolicyDocumentException extends STSServiceException {
- name = "MalformedPolicyDocumentException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "MalformedPolicyDocumentException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype);
- }
- };
- PackedPolicyTooLargeException = class PackedPolicyTooLargeException extends STSServiceException {
- name = "PackedPolicyTooLargeException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "PackedPolicyTooLargeException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, PackedPolicyTooLargeException.prototype);
- }
- };
- RegionDisabledException = class RegionDisabledException extends STSServiceException {
- name = "RegionDisabledException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "RegionDisabledException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, RegionDisabledException.prototype);
- }
- };
- IDPRejectedClaimException = class IDPRejectedClaimException extends STSServiceException {
- name = "IDPRejectedClaimException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "IDPRejectedClaimException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, IDPRejectedClaimException.prototype);
- }
- };
- InvalidIdentityTokenException = class InvalidIdentityTokenException extends STSServiceException {
- name = "InvalidIdentityTokenException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "InvalidIdentityTokenException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, InvalidIdentityTokenException.prototype);
- }
- };
- IDPCommunicationErrorException = class IDPCommunicationErrorException extends STSServiceException {
- name = "IDPCommunicationErrorException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "IDPCommunicationErrorException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, IDPCommunicationErrorException.prototype);
- }
- };
- InvalidAuthorizationMessageException = class InvalidAuthorizationMessageException extends STSServiceException {
- name = "InvalidAuthorizationMessageException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "InvalidAuthorizationMessageException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, InvalidAuthorizationMessageException.prototype);
- }
- };
- ExpiredTradeInTokenException = class ExpiredTradeInTokenException extends STSServiceException {
- name = "ExpiredTradeInTokenException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ExpiredTradeInTokenException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ExpiredTradeInTokenException.prototype);
- }
- };
- JWTPayloadSizeExceededException = class JWTPayloadSizeExceededException extends STSServiceException {
- name = "JWTPayloadSizeExceededException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "JWTPayloadSizeExceededException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, JWTPayloadSizeExceededException.prototype);
- }
- };
- OutboundWebIdentityFederationDisabledException = class OutboundWebIdentityFederationDisabledException extends STSServiceException {
- name = "OutboundWebIdentityFederationDisabledException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "OutboundWebIdentityFederationDisabledException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, OutboundWebIdentityFederationDisabledException.prototype);
- }
- };
- SessionDurationEscalationException = class SessionDurationEscalationException extends STSServiceException {
- name = "SessionDurationEscalationException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "SessionDurationEscalationException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, SessionDurationEscalationException.prototype);
- }
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/schemas/schemas_0.js
-var import_schema9, _A2 = "Arn", _AKI = "AccessKeyId", _AP = "AssumedPrincipal", _AR = "AssumeRole", _ARI = "AssumedRoleId", _ARR = "AssumeRoleRequest", _ARRs = "AssumeRoleResponse", _ARRss = "AssumeRootRequest", _ARRssu = "AssumeRootResponse", _ARU = "AssumedRoleUser", _ARWSAML = "AssumeRoleWithSAML", _ARWSAMLR = "AssumeRoleWithSAMLRequest", _ARWSAMLRs = "AssumeRoleWithSAMLResponse", _ARWWI = "AssumeRoleWithWebIdentity", _ARWWIR = "AssumeRoleWithWebIdentityRequest", _ARWWIRs = "AssumeRoleWithWebIdentityResponse", _ARs = "AssumeRoot", _Ac = "Account", _Au = "Audience", _C2 = "Credentials", _CA = "ContextAssertion", _DAM = "DecodeAuthorizationMessage", _DAMR = "DecodeAuthorizationMessageRequest", _DAMRe = "DecodeAuthorizationMessageResponse", _DM = "DecodedMessage", _DS2 = "DurationSeconds", _E = "Expiration", _EI = "ExternalId", _EM = "EncodedMessage", _ETE = "ExpiredTokenException", _ETITE = "ExpiredTradeInTokenException", _FU = "FederatedUser", _FUI = "FederatedUserId", _GAKI = "GetAccessKeyInfo", _GAKIR = "GetAccessKeyInfoRequest", _GAKIRe = "GetAccessKeyInfoResponse", _GCI = "GetCallerIdentity", _GCIR = "GetCallerIdentityRequest", _GCIRe = "GetCallerIdentityResponse", _GDAT = "GetDelegatedAccessToken", _GDATR = "GetDelegatedAccessTokenRequest", _GDATRe = "GetDelegatedAccessTokenResponse", _GFT = "GetFederationToken", _GFTR = "GetFederationTokenRequest", _GFTRe = "GetFederationTokenResponse", _GST = "GetSessionToken", _GSTR = "GetSessionTokenRequest", _GSTRe = "GetSessionTokenResponse", _GWIT = "GetWebIdentityToken", _GWITR = "GetWebIdentityTokenRequest", _GWITRe = "GetWebIdentityTokenResponse", _I2 = "Issuer", _IAME = "InvalidAuthorizationMessageException", _IDPCEE = "IDPCommunicationErrorException", _IDPRCE = "IDPRejectedClaimException", _IITE = "InvalidIdentityTokenException", _JWTPSEE = "JWTPayloadSizeExceededException", _K = "Key", _MPDE = "MalformedPolicyDocumentException", _N = "Name", _NQ = "NameQualifier", _OWIFDE = "OutboundWebIdentityFederationDisabledException", _P = "Policy", _PA = "PolicyArns", _PAr = "PrincipalArn", _PAro = "ProviderArn", _PC3 = "ProvidedContexts", _PCLT = "ProvidedContextsListType", _PCr = "ProvidedContext", _PDT = "PolicyDescriptorType", _PI = "ProviderId", _PPS = "PackedPolicySize", _PPTLE = "PackedPolicyTooLargeException", _Pr = "Provider", _RA = "RoleArn", _RDE = "RegionDisabledException", _RSN = "RoleSessionName", _S = "Subject", _SA = "SigningAlgorithm", _SAK = "SecretAccessKey", _SAMLA = "SAMLAssertion", _SAMLAT = "SAMLAssertionType", _SDEE = "SessionDurationEscalationException", _SFWIT = "SubjectFromWebIdentityToken", _SI = "SourceIdentity", _SN = "SerialNumber", _ST3 = "SubjectType", _STe = "SessionToken", _T3 = "Tags", _TC2 = "TokenCode", _TIT = "TradeInToken", _TP = "TargetPrincipal", _TPA = "TaskPolicyArn", _TTK = "TransitiveTagKeys", _Ta = "Tag", _UI = "UserId", _V2 = "Value", _WIT = "WebIdentityToken", _a4 = "arn", _aKST = "accessKeySecretType", _aQE = "awsQueryError", _c3 = "client", _cTT = "clientTokenType", _e3 = "error", _hE3 = "httpError", _m3 = "message", _pDLT = "policyDescriptorListType", _s3 = "smithy.ts.sdk.synthetic.com.amazonaws.sts", _tITT = "tradeInTokenType", _tLT = "tagListType", _wITT = "webIdentityTokenType", n03 = "com.amazonaws.sts", _s_registry3, STSServiceException$, n0_registry3, ExpiredTokenException$, ExpiredTradeInTokenException$, IDPCommunicationErrorException$, IDPRejectedClaimException$, InvalidAuthorizationMessageException$, InvalidIdentityTokenException$, JWTPayloadSizeExceededException$, MalformedPolicyDocumentException$, OutboundWebIdentityFederationDisabledException$, PackedPolicyTooLargeException$, RegionDisabledException$, SessionDurationEscalationException$, errorTypeRegistries3, accessKeySecretType, clientTokenType, SAMLAssertionType, tradeInTokenType, webIdentityTokenType, AssumedRoleUser$, AssumeRoleRequest$, AssumeRoleResponse$, AssumeRoleWithSAMLRequest$, AssumeRoleWithSAMLResponse$, AssumeRoleWithWebIdentityRequest$, AssumeRoleWithWebIdentityResponse$, AssumeRootRequest$, AssumeRootResponse$, Credentials$, DecodeAuthorizationMessageRequest$, DecodeAuthorizationMessageResponse$, FederatedUser$, GetAccessKeyInfoRequest$, GetAccessKeyInfoResponse$, GetCallerIdentityRequest$, GetCallerIdentityResponse$, GetDelegatedAccessTokenRequest$, GetDelegatedAccessTokenResponse$, GetFederationTokenRequest$, GetFederationTokenResponse$, GetSessionTokenRequest$, GetSessionTokenResponse$, GetWebIdentityTokenRequest$, GetWebIdentityTokenResponse$, PolicyDescriptorType$, ProvidedContext$, Tag$3, policyDescriptorListType, ProvidedContextsListType, tagKeyListType, tagListType, webIdentityTokenAudienceListType, AssumeRole$, AssumeRoleWithSAML$, AssumeRoleWithWebIdentity$, AssumeRoot$, DecodeAuthorizationMessage$, GetAccessKeyInfo$, GetCallerIdentity$, GetDelegatedAccessToken$, GetFederationToken$, GetSessionToken$, GetWebIdentityToken$;
-var init_schemas_03 = __esm(() => {
- init_errors6();
- init_STSServiceException();
- import_schema9 = __toESM(require_schema(), 1);
- _s_registry3 = import_schema9.TypeRegistry.for(_s3);
- STSServiceException$ = [-3, _s3, "STSServiceException", 0, [], []];
- _s_registry3.registerError(STSServiceException$, STSServiceException);
- n0_registry3 = import_schema9.TypeRegistry.for(n03);
- ExpiredTokenException$ = [
- -3,
- n03,
- _ETE,
- { [_aQE]: [`ExpiredTokenException`, 400], [_e3]: _c3, [_hE3]: 400 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(ExpiredTokenException$, ExpiredTokenException);
- ExpiredTradeInTokenException$ = [
- -3,
- n03,
- _ETITE,
- { [_aQE]: [`ExpiredTradeInTokenException`, 400], [_e3]: _c3, [_hE3]: 400 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(ExpiredTradeInTokenException$, ExpiredTradeInTokenException);
- IDPCommunicationErrorException$ = [
- -3,
- n03,
- _IDPCEE,
- { [_aQE]: [`IDPCommunicationError`, 400], [_e3]: _c3, [_hE3]: 400 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(IDPCommunicationErrorException$, IDPCommunicationErrorException);
- IDPRejectedClaimException$ = [
- -3,
- n03,
- _IDPRCE,
- { [_aQE]: [`IDPRejectedClaim`, 403], [_e3]: _c3, [_hE3]: 403 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(IDPRejectedClaimException$, IDPRejectedClaimException);
- InvalidAuthorizationMessageException$ = [
- -3,
- n03,
- _IAME,
- { [_aQE]: [`InvalidAuthorizationMessageException`, 400], [_e3]: _c3, [_hE3]: 400 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(InvalidAuthorizationMessageException$, InvalidAuthorizationMessageException);
- InvalidIdentityTokenException$ = [
- -3,
- n03,
- _IITE,
- { [_aQE]: [`InvalidIdentityToken`, 400], [_e3]: _c3, [_hE3]: 400 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(InvalidIdentityTokenException$, InvalidIdentityTokenException);
- JWTPayloadSizeExceededException$ = [
- -3,
- n03,
- _JWTPSEE,
- { [_aQE]: [`JWTPayloadSizeExceededException`, 400], [_e3]: _c3, [_hE3]: 400 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(JWTPayloadSizeExceededException$, JWTPayloadSizeExceededException);
- MalformedPolicyDocumentException$ = [
- -3,
- n03,
- _MPDE,
- { [_aQE]: [`MalformedPolicyDocument`, 400], [_e3]: _c3, [_hE3]: 400 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(MalformedPolicyDocumentException$, MalformedPolicyDocumentException);
- OutboundWebIdentityFederationDisabledException$ = [
- -3,
- n03,
- _OWIFDE,
- { [_aQE]: [`OutboundWebIdentityFederationDisabledException`, 403], [_e3]: _c3, [_hE3]: 403 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(OutboundWebIdentityFederationDisabledException$, OutboundWebIdentityFederationDisabledException);
- PackedPolicyTooLargeException$ = [
- -3,
- n03,
- _PPTLE,
- { [_aQE]: [`PackedPolicyTooLarge`, 400], [_e3]: _c3, [_hE3]: 400 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(PackedPolicyTooLargeException$, PackedPolicyTooLargeException);
- RegionDisabledException$ = [
- -3,
- n03,
- _RDE,
- { [_aQE]: [`RegionDisabledException`, 403], [_e3]: _c3, [_hE3]: 403 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(RegionDisabledException$, RegionDisabledException);
- SessionDurationEscalationException$ = [
- -3,
- n03,
- _SDEE,
- { [_aQE]: [`SessionDurationEscalationException`, 403], [_e3]: _c3, [_hE3]: 403 },
- [_m3],
- [0]
- ];
- n0_registry3.registerError(SessionDurationEscalationException$, SessionDurationEscalationException);
- errorTypeRegistries3 = [
- _s_registry3,
- n0_registry3
- ];
- accessKeySecretType = [0, n03, _aKST, 8, 0];
- clientTokenType = [0, n03, _cTT, 8, 0];
- SAMLAssertionType = [0, n03, _SAMLAT, 8, 0];
- tradeInTokenType = [0, n03, _tITT, 8, 0];
- webIdentityTokenType = [0, n03, _wITT, 8, 0];
- AssumedRoleUser$ = [
- 3,
- n03,
- _ARU,
- 0,
- [_ARI, _A2],
- [0, 0],
- 2
- ];
- AssumeRoleRequest$ = [
- 3,
- n03,
- _ARR,
- 0,
- [_RA, _RSN, _PA, _P, _DS2, _T3, _TTK, _EI, _SN, _TC2, _SI, _PC3],
- [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType],
- 2
- ];
- AssumeRoleResponse$ = [
- 3,
- n03,
- _ARRs,
- 0,
- [_C2, _ARU, _PPS, _SI],
- [[() => Credentials$, 0], () => AssumedRoleUser$, 1, 0]
- ];
- AssumeRoleWithSAMLRequest$ = [
- 3,
- n03,
- _ARWSAMLR,
- 0,
- [_RA, _PAr, _SAMLA, _PA, _P, _DS2],
- [0, 0, [() => SAMLAssertionType, 0], () => policyDescriptorListType, 0, 1],
- 3
- ];
- AssumeRoleWithSAMLResponse$ = [
- 3,
- n03,
- _ARWSAMLRs,
- 0,
- [_C2, _ARU, _PPS, _S, _ST3, _I2, _Au, _NQ, _SI],
- [[() => Credentials$, 0], () => AssumedRoleUser$, 1, 0, 0, 0, 0, 0, 0]
- ];
- AssumeRoleWithWebIdentityRequest$ = [
- 3,
- n03,
- _ARWWIR,
- 0,
- [_RA, _RSN, _WIT, _PI, _PA, _P, _DS2],
- [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1],
- 3
- ];
- AssumeRoleWithWebIdentityResponse$ = [
- 3,
- n03,
- _ARWWIRs,
- 0,
- [_C2, _SFWIT, _ARU, _PPS, _Pr, _Au, _SI],
- [[() => Credentials$, 0], 0, () => AssumedRoleUser$, 1, 0, 0, 0]
- ];
- AssumeRootRequest$ = [
- 3,
- n03,
- _ARRss,
- 0,
- [_TP, _TPA, _DS2],
- [0, () => PolicyDescriptorType$, 1],
- 2
- ];
- AssumeRootResponse$ = [
- 3,
- n03,
- _ARRssu,
- 0,
- [_C2, _SI],
- [[() => Credentials$, 0], 0]
- ];
- Credentials$ = [
- 3,
- n03,
- _C2,
- 0,
- [_AKI, _SAK, _STe, _E],
- [0, [() => accessKeySecretType, 0], 0, 4],
- 4
- ];
- DecodeAuthorizationMessageRequest$ = [
- 3,
- n03,
- _DAMR,
- 0,
- [_EM],
- [0],
- 1
- ];
- DecodeAuthorizationMessageResponse$ = [
- 3,
- n03,
- _DAMRe,
- 0,
- [_DM],
- [0]
- ];
- FederatedUser$ = [
- 3,
- n03,
- _FU,
- 0,
- [_FUI, _A2],
- [0, 0],
- 2
- ];
- GetAccessKeyInfoRequest$ = [
- 3,
- n03,
- _GAKIR,
- 0,
- [_AKI],
- [0],
- 1
- ];
- GetAccessKeyInfoResponse$ = [
- 3,
- n03,
- _GAKIRe,
- 0,
- [_Ac],
- [0]
- ];
- GetCallerIdentityRequest$ = [
- 3,
- n03,
- _GCIR,
- 0,
- [],
- []
- ];
- GetCallerIdentityResponse$ = [
- 3,
- n03,
- _GCIRe,
- 0,
- [_UI, _Ac, _A2],
- [0, 0, 0]
- ];
- GetDelegatedAccessTokenRequest$ = [
- 3,
- n03,
- _GDATR,
- 0,
- [_TIT],
- [[() => tradeInTokenType, 0]],
- 1
- ];
- GetDelegatedAccessTokenResponse$ = [
- 3,
- n03,
- _GDATRe,
- 0,
- [_C2, _PPS, _AP],
- [[() => Credentials$, 0], 1, 0]
- ];
- GetFederationTokenRequest$ = [
- 3,
- n03,
- _GFTR,
- 0,
- [_N, _P, _PA, _DS2, _T3],
- [0, 0, () => policyDescriptorListType, 1, () => tagListType],
- 1
- ];
- GetFederationTokenResponse$ = [
- 3,
- n03,
- _GFTRe,
- 0,
- [_C2, _FU, _PPS],
- [[() => Credentials$, 0], () => FederatedUser$, 1]
- ];
- GetSessionTokenRequest$ = [
- 3,
- n03,
- _GSTR,
- 0,
- [_DS2, _SN, _TC2],
- [1, 0, 0]
- ];
- GetSessionTokenResponse$ = [
- 3,
- n03,
- _GSTRe,
- 0,
- [_C2],
- [[() => Credentials$, 0]]
- ];
- GetWebIdentityTokenRequest$ = [
- 3,
- n03,
- _GWITR,
- 0,
- [_Au, _SA, _DS2, _T3],
- [64 | 0, 0, 1, () => tagListType],
- 2
- ];
- GetWebIdentityTokenResponse$ = [
- 3,
- n03,
- _GWITRe,
- 0,
- [_WIT, _E],
- [[() => webIdentityTokenType, 0], 4]
- ];
- PolicyDescriptorType$ = [
- 3,
- n03,
- _PDT,
- 0,
- [_a4],
- [0]
- ];
- ProvidedContext$ = [
- 3,
- n03,
- _PCr,
- 0,
- [_PAro, _CA],
- [0, 0]
- ];
- Tag$3 = [
- 3,
- n03,
- _Ta,
- 0,
- [_K, _V2],
- [0, 0],
- 2
- ];
- policyDescriptorListType = [
- 1,
- n03,
- _pDLT,
- 0,
- () => PolicyDescriptorType$
- ];
- ProvidedContextsListType = [
- 1,
- n03,
- _PCLT,
- 0,
- () => ProvidedContext$
- ];
- tagKeyListType = 64 | 0;
- tagListType = [
- 1,
- n03,
- _tLT,
- 0,
- () => Tag$3
- ];
- webIdentityTokenAudienceListType = 64 | 0;
- AssumeRole$ = [
- 9,
- n03,
- _AR,
- 0,
- () => AssumeRoleRequest$,
- () => AssumeRoleResponse$
- ];
- AssumeRoleWithSAML$ = [
- 9,
- n03,
- _ARWSAML,
- 0,
- () => AssumeRoleWithSAMLRequest$,
- () => AssumeRoleWithSAMLResponse$
- ];
- AssumeRoleWithWebIdentity$ = [
- 9,
- n03,
- _ARWWI,
- 0,
- () => AssumeRoleWithWebIdentityRequest$,
- () => AssumeRoleWithWebIdentityResponse$
- ];
- AssumeRoot$ = [
- 9,
- n03,
- _ARs,
- 0,
- () => AssumeRootRequest$,
- () => AssumeRootResponse$
- ];
- DecodeAuthorizationMessage$ = [
- 9,
- n03,
- _DAM,
- 0,
- () => DecodeAuthorizationMessageRequest$,
- () => DecodeAuthorizationMessageResponse$
- ];
- GetAccessKeyInfo$ = [
- 9,
- n03,
- _GAKI,
- 0,
- () => GetAccessKeyInfoRequest$,
- () => GetAccessKeyInfoResponse$
- ];
- GetCallerIdentity$ = [
- 9,
- n03,
- _GCI,
- 0,
- () => GetCallerIdentityRequest$,
- () => GetCallerIdentityResponse$
- ];
- GetDelegatedAccessToken$ = [
- 9,
- n03,
- _GDAT,
- 0,
- () => GetDelegatedAccessTokenRequest$,
- () => GetDelegatedAccessTokenResponse$
- ];
- GetFederationToken$ = [
- 9,
- n03,
- _GFT,
- 0,
- () => GetFederationTokenRequest$,
- () => GetFederationTokenResponse$
- ];
- GetSessionToken$ = [
- 9,
- n03,
- _GST,
- 0,
- () => GetSessionTokenRequest$,
- () => GetSessionTokenResponse$
- ];
- GetWebIdentityToken$ = [
- 9,
- n03,
- _GWIT,
- 0,
- () => GetWebIdentityTokenRequest$,
- () => GetWebIdentityTokenResponse$
- ];
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/runtimeConfig.shared.js
-var import_httpAuthSchemes9, import_protocols15, import_core44, import_url_parser4, import_util_utf87, getRuntimeConfig5 = (config6) => {
- return {
- apiVersion: "2011-06-15",
- base64Decoder: config6?.base64Decoder ?? fromBase645,
- base64Encoder: config6?.base64Encoder ?? toBase645,
- disableHostPrefix: config6?.disableHostPrefix ?? false,
- endpointProvider: config6?.endpointProvider ?? defaultEndpointResolver3,
- extensions: config6?.extensions ?? [],
- httpAuthSchemeProvider: config6?.httpAuthSchemeProvider ?? defaultSTSHttpAuthSchemeProvider,
- httpAuthSchemes: config6?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
- signer: new import_httpAuthSchemes9.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#noAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
- signer: new import_core44.NoAuthSigner
- }
- ],
- logger: config6?.logger ?? new NoOpLogger7,
- protocol: config6?.protocol ?? import_protocols15.AwsQueryProtocol,
- protocolSettings: config6?.protocolSettings ?? {
- defaultNamespace: "com.amazonaws.sts",
- errorTypeRegistries: errorTypeRegistries3,
- xmlNamespace: "https://sts.amazonaws.com/doc/2011-06-15/",
- version: "2011-06-15",
- serviceTarget: "AWSSecurityTokenServiceV20110615"
- },
- serviceId: config6?.serviceId ?? "STS",
- urlParser: config6?.urlParser ?? import_url_parser4.parseUrl,
- utf8Decoder: config6?.utf8Decoder ?? import_util_utf87.fromUtf8,
- utf8Encoder: config6?.utf8Encoder ?? import_util_utf87.toUtf8
- };
-};
-var init_runtimeConfig_shared3 = __esm(() => {
- init_dist_es40();
- init_dist_es42();
- init_httpAuthSchemeProvider3();
- init_endpointResolver3();
- init_schemas_03();
- import_httpAuthSchemes9 = __toESM(require_httpAuthSchemes(), 1);
- import_protocols15 = __toESM(require_protocols2(), 1);
- import_core44 = __toESM(require_dist_cjs37(), 1);
- import_url_parser4 = __toESM(require_dist_cjs11(), 1);
- import_util_utf87 = __toESM(require_dist_cjs17(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/runtimeConfig.js
-var import_client17, import_httpAuthSchemes10, import_util_user_agent_node3, import_config_resolver5, import_core45, import_hash_node3, import_middleware_retry5, import_node_config_provider5, import_node_http_handler4, import_util_body_length_node3, import_util_defaults_mode_node3, import_util_retry3, getRuntimeConfig6 = (config6) => {
- emitWarningIfUnsupportedVersion7(process.version);
- const defaultsMode = import_util_defaults_mode_node3.resolveDefaultsModeConfig(config6);
- const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode4);
- const clientSharedValues = getRuntimeConfig5(config6);
- import_client17.emitWarningIfUnsupportedVersion(process.version);
- const loaderConfig = {
- profile: config6?.profile,
- logger: clientSharedValues.logger
- };
- return {
- ...clientSharedValues,
- ...config6,
- runtime: "node",
- defaultsMode,
- authSchemePreference: config6?.authSchemePreference ?? import_node_config_provider5.loadConfig(import_httpAuthSchemes10.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
- bodyLengthChecker: config6?.bodyLengthChecker ?? import_util_body_length_node3.calculateBodyLength,
- credentialDefaultProvider: config6?.credentialDefaultProvider ?? defaultProvider,
- defaultUserAgentProvider: config6?.defaultUserAgentProvider ?? import_util_user_agent_node3.createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default3.version }),
- httpAuthSchemes: config6?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || (async (idProps) => await defaultProvider(idProps?.__config || {})()),
- signer: new import_httpAuthSchemes10.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#noAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
- signer: new import_core45.NoAuthSigner
- }
- ],
- maxAttempts: config6?.maxAttempts ?? import_node_config_provider5.loadConfig(import_middleware_retry5.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config6),
- region: config6?.region ?? import_node_config_provider5.loadConfig(import_config_resolver5.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver5.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
- requestHandler: import_node_http_handler4.NodeHttpHandler.create(config6?.requestHandler ?? defaultConfigProvider),
- retryMode: config6?.retryMode ?? import_node_config_provider5.loadConfig({
- ...import_middleware_retry5.NODE_RETRY_MODE_CONFIG_OPTIONS,
- default: async () => (await defaultConfigProvider()).retryMode || import_util_retry3.DEFAULT_RETRY_MODE
- }, config6),
- sha256: config6?.sha256 ?? import_hash_node3.Hash.bind(null, "sha256"),
- streamCollector: config6?.streamCollector ?? import_node_http_handler4.streamCollector,
- useDualstackEndpoint: config6?.useDualstackEndpoint ?? import_node_config_provider5.loadConfig(import_config_resolver5.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- useFipsEndpoint: config6?.useFipsEndpoint ?? import_node_config_provider5.loadConfig(import_config_resolver5.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- userAgentAppId: config6?.userAgentAppId ?? import_node_config_provider5.loadConfig(import_util_user_agent_node3.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
- };
-};
-var init_runtimeConfig3 = __esm(() => {
- init_package3();
- init_dist_es14();
- init_dist_es40();
- init_runtimeConfig_shared3();
- import_client17 = __toESM(require_client(), 1);
- import_httpAuthSchemes10 = __toESM(require_httpAuthSchemes(), 1);
- import_util_user_agent_node3 = __toESM(require_dist_cjs72(), 1);
- import_config_resolver5 = __toESM(require_dist_cjs58(), 1);
- import_core45 = __toESM(require_dist_cjs37(), 1);
- import_hash_node3 = __toESM(require_dist_cjs75(), 1);
- import_middleware_retry5 = __toESM(require_dist_cjs69(), 1);
- import_node_config_provider5 = __toESM(require_dist_cjs9(), 1);
- import_node_http_handler4 = __toESM(require_dist_cjs5(), 1);
- import_util_body_length_node3 = __toESM(require_dist_cjs76(), 1);
- import_util_defaults_mode_node3 = __toESM(require_dist_cjs77(), 1);
- import_util_retry3 = __toESM(require_dist_cjs55(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
-var getHttpHandlerExtensionConfiguration3 = (runtimeConfig) => {
- return {
- setHttpHandler(handler) {
- runtimeConfig.httpHandler = handler;
- },
- httpHandler() {
- return runtimeConfig.httpHandler;
- },
- updateHttpClientConfig(key, value) {
- runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
- },
- httpHandlerConfigs() {
- return runtimeConfig.httpHandler.httpHandlerConfigs();
- }
- };
-}, resolveHttpHandlerRuntimeConfig3 = (httpHandlerExtensionConfiguration) => {
- return {
- httpHandler: httpHandlerExtensionConfiguration.httpHandler()
- };
-};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
-var init_extensions15 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/Field.js
-var init_Field7 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
-var init_httpHandler7 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/types.js
-var init_types12 = () => {};
-
-// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/index.js
-var init_dist_es43 = __esm(() => {
- init_extensions15();
- init_Field7();
- init_httpHandler7();
- init_types12();
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/auth/httpAuthExtensionConfiguration.js
-var getHttpAuthExtensionConfiguration3 = (runtimeConfig) => {
- const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
- let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
- let _credentials = runtimeConfig.credentials;
- return {
- setHttpAuthScheme(httpAuthScheme) {
- const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
- if (index2 === -1) {
- _httpAuthSchemes.push(httpAuthScheme);
- } else {
- _httpAuthSchemes.splice(index2, 1, httpAuthScheme);
- }
- },
- httpAuthSchemes() {
- return _httpAuthSchemes;
- },
- setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
- _httpAuthSchemeProvider = httpAuthSchemeProvider;
- },
- httpAuthSchemeProvider() {
- return _httpAuthSchemeProvider;
- },
- setCredentials(credentials) {
- _credentials = credentials;
- },
- credentials() {
- return _credentials;
- }
- };
-}, resolveHttpAuthRuntimeConfig3 = (config6) => {
- return {
- httpAuthSchemes: config6.httpAuthSchemes(),
- httpAuthSchemeProvider: config6.httpAuthSchemeProvider(),
- credentials: config6.credentials()
- };
-};
-
-// node_modules/@aws-sdk/client-sts/dist-es/runtimeExtensions.js
-var import_region_config_resolver3, resolveRuntimeExtensions3 = (runtimeConfig, extensions16) => {
- const extensionConfiguration = Object.assign(import_region_config_resolver3.getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration4(runtimeConfig), getHttpHandlerExtensionConfiguration3(runtimeConfig), getHttpAuthExtensionConfiguration3(runtimeConfig));
- extensions16.forEach((extension) => extension.configure(extensionConfiguration));
- return Object.assign(runtimeConfig, import_region_config_resolver3.resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig4(extensionConfiguration), resolveHttpHandlerRuntimeConfig3(extensionConfiguration), resolveHttpAuthRuntimeConfig3(extensionConfiguration));
-};
-var init_runtimeExtensions3 = __esm(() => {
- init_dist_es43();
- init_dist_es40();
- import_region_config_resolver3 = __toESM(require_dist_cjs87(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/STSClient.js
-var import_middleware_host_header3, import_middleware_logger3, import_middleware_recursion_detection3, import_middleware_user_agent3, import_config_resolver6, import_core46, import_schema10, import_middleware_content_length3, import_middleware_endpoint111, import_middleware_retry6, STSClient;
-var init_STSClient = __esm(() => {
- init_dist_es40();
- init_httpAuthSchemeProvider3();
- init_EndpointParameters3();
- init_runtimeConfig3();
- init_runtimeExtensions3();
- import_middleware_host_header3 = __toESM(require_dist_cjs44(), 1);
- import_middleware_logger3 = __toESM(require_dist_cjs45(), 1);
- import_middleware_recursion_detection3 = __toESM(require_dist_cjs48(), 1);
- import_middleware_user_agent3 = __toESM(require_dist_cjs56(), 1);
- import_config_resolver6 = __toESM(require_dist_cjs58(), 1);
- import_core46 = __toESM(require_dist_cjs37(), 1);
- import_schema10 = __toESM(require_schema(), 1);
- import_middleware_content_length3 = __toESM(require_dist_cjs61(), 1);
- import_middleware_endpoint111 = __toESM(require_dist_cjs65(), 1);
- import_middleware_retry6 = __toESM(require_dist_cjs69(), 1);
- STSClient = class STSClient extends Client4 {
- config;
- constructor(...[configuration]) {
- const _config_0 = getRuntimeConfig6(configuration || {});
- super(_config_0);
- this.initConfig = _config_0;
- const _config_1 = resolveClientEndpointParameters3(_config_0);
- const _config_2 = import_middleware_user_agent3.resolveUserAgentConfig(_config_1);
- const _config_3 = import_middleware_retry6.resolveRetryConfig(_config_2);
- const _config_4 = import_config_resolver6.resolveRegionConfig(_config_3);
- const _config_5 = import_middleware_host_header3.resolveHostHeaderConfig(_config_4);
- const _config_6 = import_middleware_endpoint111.resolveEndpointConfig(_config_5);
- const _config_7 = resolveHttpAuthSchemeConfig3(_config_6);
- const _config_8 = resolveRuntimeExtensions3(_config_7, configuration?.extensions || []);
- this.config = _config_8;
- this.middlewareStack.use(import_schema10.getSchemaSerdePlugin(this.config));
- this.middlewareStack.use(import_middleware_user_agent3.getUserAgentPlugin(this.config));
- this.middlewareStack.use(import_middleware_retry6.getRetryPlugin(this.config));
- this.middlewareStack.use(import_middleware_content_length3.getContentLengthPlugin(this.config));
- this.middlewareStack.use(import_middleware_host_header3.getHostHeaderPlugin(this.config));
- this.middlewareStack.use(import_middleware_logger3.getLoggerPlugin(this.config));
- this.middlewareStack.use(import_middleware_recursion_detection3.getRecursionDetectionPlugin(this.config));
- this.middlewareStack.use(import_core46.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
- httpAuthSchemeParametersProvider: defaultSTSHttpAuthSchemeParametersProvider,
- identityProviderConfigProvider: async (config6) => new import_core46.DefaultIdentityProviderConfig({
- "aws.auth#sigv4": config6.credentials
- })
- }));
- this.middlewareStack.use(import_core46.getHttpSigningPlugin(this.config));
- }
- destroy() {
- super.destroy();
- }
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleCommand.js
-var import_middleware_endpoint112, AssumeRoleCommand;
-var init_AssumeRoleCommand = __esm(() => {
- init_dist_es40();
- init_EndpointParameters3();
- init_schemas_03();
- import_middleware_endpoint112 = __toESM(require_dist_cjs65(), 1);
- AssumeRoleCommand = class AssumeRoleCommand extends Command5.classBuilder().ep(commonParams3).m(function(Command6, cs, config6, o5) {
- return [import_middleware_endpoint112.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").sc(AssumeRole$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleWithSAMLCommand.js
-var import_middleware_endpoint113, AssumeRoleWithSAMLCommand;
-var init_AssumeRoleWithSAMLCommand = __esm(() => {
- init_dist_es40();
- init_EndpointParameters3();
- init_schemas_03();
- import_middleware_endpoint113 = __toESM(require_dist_cjs65(), 1);
- AssumeRoleWithSAMLCommand = class AssumeRoleWithSAMLCommand extends Command5.classBuilder().ep(commonParams3).m(function(Command6, cs, config6, o5) {
- return [import_middleware_endpoint113.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithSAML", {}).n("STSClient", "AssumeRoleWithSAMLCommand").sc(AssumeRoleWithSAML$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleWithWebIdentityCommand.js
-var import_middleware_endpoint114, AssumeRoleWithWebIdentityCommand;
-var init_AssumeRoleWithWebIdentityCommand = __esm(() => {
- init_dist_es40();
- init_EndpointParameters3();
- init_schemas_03();
- import_middleware_endpoint114 = __toESM(require_dist_cjs65(), 1);
- AssumeRoleWithWebIdentityCommand = class AssumeRoleWithWebIdentityCommand extends Command5.classBuilder().ep(commonParams3).m(function(Command6, cs, config6, o5) {
- return [import_middleware_endpoint114.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").sc(AssumeRoleWithWebIdentity$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRootCommand.js
-var import_middleware_endpoint115, AssumeRootCommand;
-var init_AssumeRootCommand = __esm(() => {
- init_dist_es40();
- init_EndpointParameters3();
- init_schemas_03();
- import_middleware_endpoint115 = __toESM(require_dist_cjs65(), 1);
- AssumeRootCommand = class AssumeRootCommand extends Command5.classBuilder().ep(commonParams3).m(function(Command6, cs, config6, o5) {
- return [import_middleware_endpoint115.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "AssumeRoot", {}).n("STSClient", "AssumeRootCommand").sc(AssumeRoot$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/DecodeAuthorizationMessageCommand.js
-var import_middleware_endpoint116, DecodeAuthorizationMessageCommand;
-var init_DecodeAuthorizationMessageCommand = __esm(() => {
- init_dist_es40();
- init_EndpointParameters3();
- init_schemas_03();
- import_middleware_endpoint116 = __toESM(require_dist_cjs65(), 1);
- DecodeAuthorizationMessageCommand = class DecodeAuthorizationMessageCommand extends Command5.classBuilder().ep(commonParams3).m(function(Command6, cs, config6, o5) {
- return [import_middleware_endpoint116.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "DecodeAuthorizationMessage", {}).n("STSClient", "DecodeAuthorizationMessageCommand").sc(DecodeAuthorizationMessage$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/GetAccessKeyInfoCommand.js
-var import_middleware_endpoint117, GetAccessKeyInfoCommand;
-var init_GetAccessKeyInfoCommand = __esm(() => {
- init_dist_es40();
- init_EndpointParameters3();
- init_schemas_03();
- import_middleware_endpoint117 = __toESM(require_dist_cjs65(), 1);
- GetAccessKeyInfoCommand = class GetAccessKeyInfoCommand extends Command5.classBuilder().ep(commonParams3).m(function(Command6, cs, config6, o5) {
- return [import_middleware_endpoint117.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "GetAccessKeyInfo", {}).n("STSClient", "GetAccessKeyInfoCommand").sc(GetAccessKeyInfo$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/GetCallerIdentityCommand.js
-var import_middleware_endpoint118, GetCallerIdentityCommand;
-var init_GetCallerIdentityCommand = __esm(() => {
- init_dist_es40();
- init_EndpointParameters3();
- init_schemas_03();
- import_middleware_endpoint118 = __toESM(require_dist_cjs65(), 1);
- GetCallerIdentityCommand = class GetCallerIdentityCommand extends Command5.classBuilder().ep(commonParams3).m(function(Command6, cs, config6, o5) {
- return [import_middleware_endpoint118.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "GetCallerIdentity", {}).n("STSClient", "GetCallerIdentityCommand").sc(GetCallerIdentity$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/GetDelegatedAccessTokenCommand.js
-var import_middleware_endpoint119, GetDelegatedAccessTokenCommand;
-var init_GetDelegatedAccessTokenCommand = __esm(() => {
- init_dist_es40();
- init_EndpointParameters3();
- init_schemas_03();
- import_middleware_endpoint119 = __toESM(require_dist_cjs65(), 1);
- GetDelegatedAccessTokenCommand = class GetDelegatedAccessTokenCommand extends Command5.classBuilder().ep(commonParams3).m(function(Command6, cs, config6, o5) {
- return [import_middleware_endpoint119.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "GetDelegatedAccessToken", {}).n("STSClient", "GetDelegatedAccessTokenCommand").sc(GetDelegatedAccessToken$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/GetFederationTokenCommand.js
-var import_middleware_endpoint120, GetFederationTokenCommand;
-var init_GetFederationTokenCommand = __esm(() => {
- init_dist_es40();
- init_EndpointParameters3();
- init_schemas_03();
- import_middleware_endpoint120 = __toESM(require_dist_cjs65(), 1);
- GetFederationTokenCommand = class GetFederationTokenCommand extends Command5.classBuilder().ep(commonParams3).m(function(Command6, cs, config6, o5) {
- return [import_middleware_endpoint120.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "GetFederationToken", {}).n("STSClient", "GetFederationTokenCommand").sc(GetFederationToken$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/GetSessionTokenCommand.js
-var import_middleware_endpoint121, GetSessionTokenCommand;
-var init_GetSessionTokenCommand = __esm(() => {
- init_dist_es40();
- init_EndpointParameters3();
- init_schemas_03();
- import_middleware_endpoint121 = __toESM(require_dist_cjs65(), 1);
- GetSessionTokenCommand = class GetSessionTokenCommand extends Command5.classBuilder().ep(commonParams3).m(function(Command6, cs, config6, o5) {
- return [import_middleware_endpoint121.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "GetSessionToken", {}).n("STSClient", "GetSessionTokenCommand").sc(GetSessionToken$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/GetWebIdentityTokenCommand.js
-var import_middleware_endpoint122, GetWebIdentityTokenCommand;
-var init_GetWebIdentityTokenCommand = __esm(() => {
- init_dist_es40();
- init_EndpointParameters3();
- init_schemas_03();
- import_middleware_endpoint122 = __toESM(require_dist_cjs65(), 1);
- GetWebIdentityTokenCommand = class GetWebIdentityTokenCommand extends Command5.classBuilder().ep(commonParams3).m(function(Command6, cs, config6, o5) {
- return [import_middleware_endpoint122.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSSecurityTokenServiceV20110615", "GetWebIdentityToken", {}).n("STSClient", "GetWebIdentityTokenCommand").sc(GetWebIdentityToken$).build() {
- };
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/STS.js
-var commands5, STS;
-var init_STS = __esm(() => {
- init_dist_es40();
- init_AssumeRoleCommand();
- init_AssumeRoleWithSAMLCommand();
- init_AssumeRoleWithWebIdentityCommand();
- init_AssumeRootCommand();
- init_DecodeAuthorizationMessageCommand();
- init_GetAccessKeyInfoCommand();
- init_GetCallerIdentityCommand();
- init_GetDelegatedAccessTokenCommand();
- init_GetFederationTokenCommand();
- init_GetSessionTokenCommand();
- init_GetWebIdentityTokenCommand();
- init_STSClient();
- commands5 = {
- AssumeRoleCommand,
- AssumeRoleWithSAMLCommand,
- AssumeRoleWithWebIdentityCommand,
- AssumeRootCommand,
- DecodeAuthorizationMessageCommand,
- GetAccessKeyInfoCommand,
- GetCallerIdentityCommand,
- GetDelegatedAccessTokenCommand,
- GetFederationTokenCommand,
- GetSessionTokenCommand,
- GetWebIdentityTokenCommand
- };
- STS = class STS extends STSClient {
- };
- createAggregatedClient4(commands5, STS);
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/commands/index.js
-var init_commands3 = __esm(() => {
- init_AssumeRoleCommand();
- init_AssumeRoleWithSAMLCommand();
- init_AssumeRoleWithWebIdentityCommand();
- init_AssumeRootCommand();
- init_DecodeAuthorizationMessageCommand();
- init_GetAccessKeyInfoCommand();
- init_GetCallerIdentityCommand();
- init_GetDelegatedAccessTokenCommand();
- init_GetFederationTokenCommand();
- init_GetSessionTokenCommand();
- init_GetWebIdentityTokenCommand();
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/models/models_0.js
-var init_models_03 = () => {};
-
-// node_modules/@aws-sdk/client-sts/dist-es/defaultStsRoleAssumers.js
-var import_client18, import_region_config_resolver4, getAccountIdFromAssumedRoleUser = (assumedRoleUser) => {
- if (typeof assumedRoleUser?.Arn === "string") {
- const arnComponents = assumedRoleUser.Arn.split(":");
- if (arnComponents.length > 4 && arnComponents[4] !== "") {
- return arnComponents[4];
- }
- }
- return;
-}, resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => {
- const region = typeof _region === "function" ? await _region() : _region;
- const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion;
- let stsDefaultRegion = "";
- const resolvedRegion = region ?? parentRegion ?? (stsDefaultRegion = await import_region_config_resolver4.stsRegionDefaultResolver(loaderConfig)());
- credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (credential provider clientConfig)`, `${parentRegion} (contextual client)`, `${stsDefaultRegion} (STS default: AWS_REGION, profile region, or us-east-1)`);
- return resolvedRegion;
-}, getDefaultRoleAssumer = (stsOptions, STSClient2) => {
- let stsClient;
- let closureSourceCreds;
- return async (sourceCreds, params) => {
- closureSourceCreds = sourceCreds;
- if (!stsClient) {
- const { logger: logger5 = stsOptions?.parentClientConfig?.logger, profile: profile5 = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions;
- const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, {
- logger: logger5,
- profile: profile5
- });
- const isCompatibleRequestHandler = !isH2(requestHandler);
- stsClient = new STSClient2({
- ...stsOptions,
- userAgentAppId,
- profile: profile5,
- credentialDefaultProvider: () => async () => closureSourceCreds,
- region: resolvedRegion,
- requestHandler: isCompatibleRequestHandler ? requestHandler : undefined,
- logger: logger5
- });
- }
- const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params));
- if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
- throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`);
- }
- const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
- const credentials = {
- accessKeyId: Credentials.AccessKeyId,
- secretAccessKey: Credentials.SecretAccessKey,
- sessionToken: Credentials.SessionToken,
- expiration: Credentials.Expiration,
- ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
- ...accountId && { accountId }
- };
- import_client18.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i");
- return credentials;
- };
-}, getDefaultRoleAssumerWithWebIdentity = (stsOptions, STSClient2) => {
- let stsClient;
- return async (params) => {
- if (!stsClient) {
- const { logger: logger5 = stsOptions?.parentClientConfig?.logger, profile: profile5 = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions;
- const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, {
- logger: logger5,
- profile: profile5
- });
- const isCompatibleRequestHandler = !isH2(requestHandler);
- stsClient = new STSClient2({
- ...stsOptions,
- userAgentAppId,
- profile: profile5,
- region: resolvedRegion,
- requestHandler: isCompatibleRequestHandler ? requestHandler : undefined,
- logger: logger5
- });
- }
- const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params));
- if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
- throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`);
- }
- const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
- const credentials = {
- accessKeyId: Credentials.AccessKeyId,
- secretAccessKey: Credentials.SecretAccessKey,
- sessionToken: Credentials.SessionToken,
- expiration: Credentials.Expiration,
- ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
- ...accountId && { accountId }
- };
- if (accountId) {
- import_client18.setCredentialFeature(credentials, "RESOLVED_ACCOUNT_ID", "T");
- }
- import_client18.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k");
- return credentials;
- };
-}, isH2 = (requestHandler) => {
- return requestHandler?.metadata?.handlerProtocol === "h2";
-};
-var init_defaultStsRoleAssumers = __esm(() => {
- init_AssumeRoleCommand();
- init_AssumeRoleWithWebIdentityCommand();
- import_client18 = __toESM(require_client(), 1);
- import_region_config_resolver4 = __toESM(require_dist_cjs87(), 1);
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/defaultRoleAssumers.js
-var getCustomizableStsClientCtor = (baseCtor, customizations) => {
- if (!customizations)
- return baseCtor;
- else
- return class CustomizableSTSClient extends baseCtor {
- constructor(config6) {
- super(config6);
- for (const customization of customizations) {
- this.middlewareStack.use(customization);
- }
- }
- };
-}, getDefaultRoleAssumer2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins)), getDefaultRoleAssumerWithWebIdentity2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins)), decorateDefaultCredentialProvider = (provider3) => (input) => provider3({
- roleAssumer: getDefaultRoleAssumer2(input),
- roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input),
- ...input
-});
-var init_defaultRoleAssumers = __esm(() => {
- init_defaultStsRoleAssumers();
- init_STSClient();
-});
-
-// node_modules/@aws-sdk/client-sts/dist-es/index.js
-var exports_dist_es15 = {};
-__export(exports_dist_es15, {
- getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2,
- getDefaultRoleAssumer: () => getDefaultRoleAssumer2,
- errorTypeRegistries: () => errorTypeRegistries3,
- decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider,
- __Client: () => Client4,
- Tag$: () => Tag$3,
- SessionDurationEscalationException$: () => SessionDurationEscalationException$,
- SessionDurationEscalationException: () => SessionDurationEscalationException,
- STSServiceException$: () => STSServiceException$,
- STSServiceException: () => STSServiceException,
- STSClient: () => STSClient,
- STS: () => STS,
- RegionDisabledException$: () => RegionDisabledException$,
- RegionDisabledException: () => RegionDisabledException,
- ProvidedContext$: () => ProvidedContext$,
- PolicyDescriptorType$: () => PolicyDescriptorType$,
- PackedPolicyTooLargeException$: () => PackedPolicyTooLargeException$,
- PackedPolicyTooLargeException: () => PackedPolicyTooLargeException,
- OutboundWebIdentityFederationDisabledException$: () => OutboundWebIdentityFederationDisabledException$,
- OutboundWebIdentityFederationDisabledException: () => OutboundWebIdentityFederationDisabledException,
- MalformedPolicyDocumentException$: () => MalformedPolicyDocumentException$,
- MalformedPolicyDocumentException: () => MalformedPolicyDocumentException,
- JWTPayloadSizeExceededException$: () => JWTPayloadSizeExceededException$,
- JWTPayloadSizeExceededException: () => JWTPayloadSizeExceededException,
- InvalidIdentityTokenException$: () => InvalidIdentityTokenException$,
- InvalidIdentityTokenException: () => InvalidIdentityTokenException,
- InvalidAuthorizationMessageException$: () => InvalidAuthorizationMessageException$,
- InvalidAuthorizationMessageException: () => InvalidAuthorizationMessageException,
- IDPRejectedClaimException$: () => IDPRejectedClaimException$,
- IDPRejectedClaimException: () => IDPRejectedClaimException,
- IDPCommunicationErrorException$: () => IDPCommunicationErrorException$,
- IDPCommunicationErrorException: () => IDPCommunicationErrorException,
- GetWebIdentityTokenResponse$: () => GetWebIdentityTokenResponse$,
- GetWebIdentityTokenRequest$: () => GetWebIdentityTokenRequest$,
- GetWebIdentityTokenCommand: () => GetWebIdentityTokenCommand,
- GetWebIdentityToken$: () => GetWebIdentityToken$,
- GetSessionTokenResponse$: () => GetSessionTokenResponse$,
- GetSessionTokenRequest$: () => GetSessionTokenRequest$,
- GetSessionTokenCommand: () => GetSessionTokenCommand,
- GetSessionToken$: () => GetSessionToken$,
- GetFederationTokenResponse$: () => GetFederationTokenResponse$,
- GetFederationTokenRequest$: () => GetFederationTokenRequest$,
- GetFederationTokenCommand: () => GetFederationTokenCommand,
- GetFederationToken$: () => GetFederationToken$,
- GetDelegatedAccessTokenResponse$: () => GetDelegatedAccessTokenResponse$,
- GetDelegatedAccessTokenRequest$: () => GetDelegatedAccessTokenRequest$,
- GetDelegatedAccessTokenCommand: () => GetDelegatedAccessTokenCommand,
- GetDelegatedAccessToken$: () => GetDelegatedAccessToken$,
- GetCallerIdentityResponse$: () => GetCallerIdentityResponse$,
- GetCallerIdentityRequest$: () => GetCallerIdentityRequest$,
- GetCallerIdentityCommand: () => GetCallerIdentityCommand,
- GetCallerIdentity$: () => GetCallerIdentity$,
- GetAccessKeyInfoResponse$: () => GetAccessKeyInfoResponse$,
- GetAccessKeyInfoRequest$: () => GetAccessKeyInfoRequest$,
- GetAccessKeyInfoCommand: () => GetAccessKeyInfoCommand,
- GetAccessKeyInfo$: () => GetAccessKeyInfo$,
- FederatedUser$: () => FederatedUser$,
- ExpiredTradeInTokenException$: () => ExpiredTradeInTokenException$,
- ExpiredTradeInTokenException: () => ExpiredTradeInTokenException,
- ExpiredTokenException$: () => ExpiredTokenException$,
- ExpiredTokenException: () => ExpiredTokenException,
- DecodeAuthorizationMessageResponse$: () => DecodeAuthorizationMessageResponse$,
- DecodeAuthorizationMessageRequest$: () => DecodeAuthorizationMessageRequest$,
- DecodeAuthorizationMessageCommand: () => DecodeAuthorizationMessageCommand,
- DecodeAuthorizationMessage$: () => DecodeAuthorizationMessage$,
- Credentials$: () => Credentials$,
- AssumedRoleUser$: () => AssumedRoleUser$,
- AssumeRootResponse$: () => AssumeRootResponse$,
- AssumeRootRequest$: () => AssumeRootRequest$,
- AssumeRootCommand: () => AssumeRootCommand,
- AssumeRoot$: () => AssumeRoot$,
- AssumeRoleWithWebIdentityResponse$: () => AssumeRoleWithWebIdentityResponse$,
- AssumeRoleWithWebIdentityRequest$: () => AssumeRoleWithWebIdentityRequest$,
- AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand,
- AssumeRoleWithWebIdentity$: () => AssumeRoleWithWebIdentity$,
- AssumeRoleWithSAMLResponse$: () => AssumeRoleWithSAMLResponse$,
- AssumeRoleWithSAMLRequest$: () => AssumeRoleWithSAMLRequest$,
- AssumeRoleWithSAMLCommand: () => AssumeRoleWithSAMLCommand,
- AssumeRoleWithSAML$: () => AssumeRoleWithSAML$,
- AssumeRoleResponse$: () => AssumeRoleResponse$,
- AssumeRoleRequest$: () => AssumeRoleRequest$,
- AssumeRoleCommand: () => AssumeRoleCommand,
- AssumeRole$: () => AssumeRole$,
- $Command: () => Command5
-});
-var init_dist_es44 = __esm(() => {
- init_STSServiceException();
- init_STSClient();
- init_STS();
- init_commands3();
- init_schemas_03();
- init_errors6();
- init_models_03();
- init_defaultRoleAssumers();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/createCredentialChain.js
-var import_property_provider26, createCredentialChain = (...credentialProviders) => {
- let expireAfter = -1;
- const baseFunction = async (awsIdentityProperties) => {
- const credentials = await propertyProviderChain(...credentialProviders)(awsIdentityProperties);
- if (!credentials.expiration && expireAfter !== -1) {
- credentials.expiration = new Date(Date.now() + expireAfter);
- }
- return credentials;
- };
- const withOptions = Object.assign(baseFunction, {
- expireAfter(milliseconds) {
- if (milliseconds < 5 * 60000) {
- throw new Error("@aws-sdk/credential-providers - createCredentialChain(...).expireAfter(ms) may not be called with a duration lower than five minutes.");
- }
- expireAfter = milliseconds;
- return withOptions;
- }
- });
- return withOptions;
-}, propertyProviderChain = (...providers) => async (awsIdentityProperties) => {
- if (providers.length === 0) {
- throw new import_property_provider26.ProviderError("No providers in chain", { tryNextLink: false });
- }
- let lastProviderError;
- for (const provider3 of providers) {
- try {
- return await provider3(awsIdentityProperties);
- } catch (err) {
- lastProviderError = err;
- if (err?.tryNextLink) {
- continue;
- }
- throw err;
- }
- }
- throw lastProviderError;
-};
-var init_createCredentialChain = __esm(() => {
- import_property_provider26 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/CognitoProviderParameters.js
-var init_CognitoProviderParameters = () => {};
-
-// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/Logins.js
-var init_Logins = () => {};
-
-// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/Storage.js
-var init_Storage = () => {};
-
-// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/resolveLogins.js
-function resolveLogins(logins) {
- return Promise.all(Object.keys(logins).reduce((arr, name) => {
- const tokenOrProvider = logins[name];
- if (typeof tokenOrProvider === "string") {
- arr.push([name, tokenOrProvider]);
- } else {
- arr.push(tokenOrProvider().then((token) => [name, token]));
- }
- return arr;
- }, [])).then((resolvedPairs) => resolvedPairs.reduce((logins2, [key, value]) => {
- logins2[key] = value;
- return logins2;
- }, {}));
-}
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/auth/httpAuthSchemeProvider.js
-var require_httpAuthSchemeProvider5 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.resolveHttpAuthSchemeConfig = exports.defaultCognitoIdentityHttpAuthSchemeProvider = exports.defaultCognitoIdentityHttpAuthSchemeParametersProvider = undefined;
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var util_middleware_1 = require_dist_cjs30();
- var defaultCognitoIdentityHttpAuthSchemeParametersProvider = async (config6, context, input) => {
- return {
- operation: (0, util_middleware_1.getSmithyContext)(context).operation,
- region: await (0, util_middleware_1.normalizeProvider)(config6.region)() || (() => {
- throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
- })()
- };
- };
- exports.defaultCognitoIdentityHttpAuthSchemeParametersProvider = defaultCognitoIdentityHttpAuthSchemeParametersProvider;
- function createAwsAuthSigv4HttpAuthOption4(authParameters) {
- return {
- schemeId: "aws.auth#sigv4",
- signingProperties: {
- name: "cognito-identity",
- region: authParameters.region
- },
- propertiesExtractor: (config6, context) => ({
- signingProperties: {
- config: config6,
- context
- }
- })
- };
- }
- function createSmithyApiNoAuthHttpAuthOption2(authParameters) {
- return {
- schemeId: "smithy.api#noAuth"
- };
- }
- var defaultCognitoIdentityHttpAuthSchemeProvider = (authParameters) => {
- const options2 = [];
- switch (authParameters.operation) {
- case "GetCredentialsForIdentity": {
- options2.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
- break;
- }
- case "GetId": {
- options2.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
- break;
- }
- default: {
- options2.push(createAwsAuthSigv4HttpAuthOption4(authParameters));
- }
- }
- return options2;
- };
- exports.defaultCognitoIdentityHttpAuthSchemeProvider = defaultCognitoIdentityHttpAuthSchemeProvider;
- var resolveHttpAuthSchemeConfig4 = (config6) => {
- const config_0 = (0, httpAuthSchemes_1.resolveAwsSdkSigV4Config)(config6);
- return Object.assign(config_0, {
- authSchemePreference: (0, util_middleware_1.normalizeProvider)(config6.authSchemePreference ?? [])
- });
- };
- exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig4;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/endpoint/ruleset.js
-var require_ruleset5 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ruleSet = undefined;
- var w2 = "required";
- var x3 = "fn";
- var y3 = "argv";
- var z3 = "ref";
- var a5 = true;
- var b4 = "isSet";
- var c8 = "booleanEquals";
- var d4 = "error";
- var e4 = "endpoint";
- var f4 = "tree";
- var g4 = "PartitionResult";
- var h5 = "getAttr";
- var i5 = "stringEquals";
- var j4 = { [w2]: false, type: "string" };
- var k4 = { [w2]: true, default: false, type: "boolean" };
- var l4 = { [z3]: "Endpoint" };
- var m4 = { [x3]: c8, [y3]: [{ [z3]: "UseFIPS" }, true] };
- var n5 = { [x3]: c8, [y3]: [{ [z3]: "UseDualStack" }, true] };
- var o5 = {};
- var p4 = { [z3]: "Region" };
- var q4 = { [x3]: h5, [y3]: [{ [z3]: g4 }, "supportsFIPS"] };
- var r4 = { [z3]: g4 };
- var s4 = { [x3]: c8, [y3]: [true, { [x3]: h5, [y3]: [r4, "supportsDualStack"] }] };
- var t4 = [m4];
- var u5 = [n5];
- var v4 = [p4];
- var _data4 = {
- version: "1.0",
- parameters: { Region: j4, UseDualStack: k4, UseFIPS: k4, Endpoint: j4 },
- rules: [
- {
- conditions: [{ [x3]: b4, [y3]: [l4] }],
- rules: [
- { conditions: t4, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d4 },
- { conditions: u5, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d4 },
- { endpoint: { url: l4, properties: o5, headers: o5 }, type: e4 }
- ],
- type: f4
- },
- {
- conditions: [{ [x3]: b4, [y3]: v4 }],
- rules: [
- {
- conditions: [{ [x3]: "aws.partition", [y3]: v4, assign: g4 }],
- rules: [
- {
- conditions: [m4, n5],
- rules: [
- {
- conditions: [{ [x3]: c8, [y3]: [a5, q4] }, s4],
- rules: [
- {
- conditions: [{ [x3]: i5, [y3]: [p4, "us-east-1"] }],
- endpoint: {
- url: "https://cognito-identity-fips.us-east-1.amazonaws.com",
- properties: o5,
- headers: o5
- },
- type: e4
- },
- {
- conditions: [{ [x3]: i5, [y3]: [p4, "us-east-2"] }],
- endpoint: {
- url: "https://cognito-identity-fips.us-east-2.amazonaws.com",
- properties: o5,
- headers: o5
- },
- type: e4
- },
- {
- conditions: [{ [x3]: i5, [y3]: [p4, "us-west-1"] }],
- endpoint: {
- url: "https://cognito-identity-fips.us-west-1.amazonaws.com",
- properties: o5,
- headers: o5
- },
- type: e4
- },
- {
- conditions: [{ [x3]: i5, [y3]: [p4, "us-west-2"] }],
- endpoint: {
- url: "https://cognito-identity-fips.us-west-2.amazonaws.com",
- properties: o5,
- headers: o5
- },
- type: e4
- },
- {
- endpoint: {
- url: "https://cognito-identity-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",
- properties: o5,
- headers: o5
- },
- type: e4
- }
- ],
- type: f4
- },
- { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d4 }
- ],
- type: f4
- },
- {
- conditions: t4,
- rules: [
- {
- conditions: [{ [x3]: c8, [y3]: [q4, a5] }],
- rules: [
- {
- endpoint: {
- url: "https://cognito-identity-fips.{Region}.{PartitionResult#dnsSuffix}",
- properties: o5,
- headers: o5
- },
- type: e4
- }
- ],
- type: f4
- },
- { error: "FIPS is enabled but this partition does not support FIPS", type: d4 }
- ],
- type: f4
- },
- {
- conditions: u5,
- rules: [
- {
- conditions: [s4],
- rules: [
- {
- conditions: [{ [x3]: i5, [y3]: ["aws", { [x3]: h5, [y3]: [r4, "name"] }] }],
- endpoint: { url: "https://cognito-identity.{Region}.amazonaws.com", properties: o5, headers: o5 },
- type: e4
- },
- {
- endpoint: {
- url: "https://cognito-identity.{Region}.{PartitionResult#dualStackDnsSuffix}",
- properties: o5,
- headers: o5
- },
- type: e4
- }
- ],
- type: f4
- },
- { error: "DualStack is enabled but this partition does not support DualStack", type: d4 }
- ],
- type: f4
- },
- {
- endpoint: {
- url: "https://cognito-identity.{Region}.{PartitionResult#dnsSuffix}",
- properties: o5,
- headers: o5
- },
- type: e4
- }
- ],
- type: f4
- }
- ],
- type: f4
- },
- { error: "Invalid Configuration: Missing Region", type: d4 }
- ]
- };
- exports.ruleSet = _data4;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/endpoint/endpointResolver.js
-var require_endpointResolver5 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.defaultEndpointResolver = undefined;
- var util_endpoints_1 = require_dist_cjs51();
- var util_endpoints_2 = require_dist_cjs50();
- var ruleset_1 = require_ruleset5();
- var cache5 = new util_endpoints_2.EndpointCache({
- size: 50,
- params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
- });
- var defaultEndpointResolver4 = (endpointParams, context = {}) => {
- return cache5.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
- endpointParams,
- logger: context.logger
- }));
- };
- exports.defaultEndpointResolver = defaultEndpointResolver4;
- util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/models/CognitoIdentityServiceException.js
-var require_CognitoIdentityServiceException = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.CognitoIdentityServiceException = exports.__ServiceException = undefined;
- var smithy_client_1 = require_dist_cjs71();
- Object.defineProperty(exports, "__ServiceException", { enumerable: true, get: function() {
- return smithy_client_1.ServiceException;
- } });
-
- class CognitoIdentityServiceException extends smithy_client_1.ServiceException {
- constructor(options2) {
- super(options2);
- Object.setPrototypeOf(this, CognitoIdentityServiceException.prototype);
- }
- }
- exports.CognitoIdentityServiceException = CognitoIdentityServiceException;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/models/errors.js
-var require_errors5 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.LimitExceededException = exports.TooManyRequestsException = exports.ResourceNotFoundException = exports.ResourceConflictException = exports.NotAuthorizedException = exports.InvalidParameterException = exports.InvalidIdentityPoolConfigurationException = exports.InternalErrorException = exports.ExternalServiceException = undefined;
- var CognitoIdentityServiceException_1 = require_CognitoIdentityServiceException();
-
- class ExternalServiceException extends CognitoIdentityServiceException_1.CognitoIdentityServiceException {
- name = "ExternalServiceException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ExternalServiceException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ExternalServiceException.prototype);
- }
- }
- exports.ExternalServiceException = ExternalServiceException;
-
- class InternalErrorException extends CognitoIdentityServiceException_1.CognitoIdentityServiceException {
- name = "InternalErrorException";
- $fault = "server";
- constructor(opts) {
- super({
- name: "InternalErrorException",
- $fault: "server",
- ...opts
- });
- Object.setPrototypeOf(this, InternalErrorException.prototype);
- }
- }
- exports.InternalErrorException = InternalErrorException;
-
- class InvalidIdentityPoolConfigurationException extends CognitoIdentityServiceException_1.CognitoIdentityServiceException {
- name = "InvalidIdentityPoolConfigurationException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "InvalidIdentityPoolConfigurationException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, InvalidIdentityPoolConfigurationException.prototype);
- }
- }
- exports.InvalidIdentityPoolConfigurationException = InvalidIdentityPoolConfigurationException;
-
- class InvalidParameterException extends CognitoIdentityServiceException_1.CognitoIdentityServiceException {
- name = "InvalidParameterException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "InvalidParameterException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, InvalidParameterException.prototype);
- }
- }
- exports.InvalidParameterException = InvalidParameterException;
-
- class NotAuthorizedException extends CognitoIdentityServiceException_1.CognitoIdentityServiceException {
- name = "NotAuthorizedException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "NotAuthorizedException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, NotAuthorizedException.prototype);
- }
- }
- exports.NotAuthorizedException = NotAuthorizedException;
-
- class ResourceConflictException extends CognitoIdentityServiceException_1.CognitoIdentityServiceException {
- name = "ResourceConflictException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ResourceConflictException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ResourceConflictException.prototype);
- }
- }
- exports.ResourceConflictException = ResourceConflictException;
-
- class ResourceNotFoundException3 extends CognitoIdentityServiceException_1.CognitoIdentityServiceException {
- name = "ResourceNotFoundException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "ResourceNotFoundException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, ResourceNotFoundException3.prototype);
- }
- }
- exports.ResourceNotFoundException = ResourceNotFoundException3;
-
- class TooManyRequestsException extends CognitoIdentityServiceException_1.CognitoIdentityServiceException {
- name = "TooManyRequestsException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "TooManyRequestsException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, TooManyRequestsException.prototype);
- }
- }
- exports.TooManyRequestsException = TooManyRequestsException;
-
- class LimitExceededException extends CognitoIdentityServiceException_1.CognitoIdentityServiceException {
- name = "LimitExceededException";
- $fault = "client";
- constructor(opts) {
- super({
- name: "LimitExceededException",
- $fault: "client",
- ...opts
- });
- Object.setPrototypeOf(this, LimitExceededException.prototype);
- }
- }
- exports.LimitExceededException = LimitExceededException;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/schemas/schemas_0.js
-var require_schemas_05 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.GetId$ = exports.GetCredentialsForIdentity$ = exports.GetIdResponse$ = exports.GetIdInput$ = exports.GetCredentialsForIdentityResponse$ = exports.GetCredentialsForIdentityInput$ = exports.Credentials$ = exports.errorTypeRegistries = exports.TooManyRequestsException$ = exports.ResourceNotFoundException$ = exports.ResourceConflictException$ = exports.NotAuthorizedException$ = exports.LimitExceededException$ = exports.InvalidParameterException$ = exports.InvalidIdentityPoolConfigurationException$ = exports.InternalErrorException$ = exports.ExternalServiceException$ = exports.CognitoIdentityServiceException$ = undefined;
- var _AI = "AccountId";
- var _AKI2 = "AccessKeyId";
- var _C3 = "Credentials";
- var _CRA = "CustomRoleArn";
- var _E2 = "Expiration";
- var _ESE = "ExternalServiceException";
- var _GCFI = "GetCredentialsForIdentity";
- var _GCFII = "GetCredentialsForIdentityInput";
- var _GCFIR = "GetCredentialsForIdentityResponse";
- var _GI = "GetId";
- var _GII = "GetIdInput";
- var _GIR = "GetIdResponse";
- var _IEE = "InternalErrorException";
- var _II = "IdentityId";
- var _IIPCE = "InvalidIdentityPoolConfigurationException";
- var _IPE = "InvalidParameterException";
- var _IPI = "IdentityPoolId";
- var _IPT = "IdentityProviderToken";
- var _L = "Logins";
- var _LEE = "LimitExceededException";
- var _LM = "LoginsMap";
- var _NAE = "NotAuthorizedException";
- var _RCE = "ResourceConflictException";
- var _RNFE3 = "ResourceNotFoundException";
- var _SK = "SecretKey";
- var _SKS = "SecretKeyString";
- var _ST4 = "SessionToken";
- var _TMRE = "TooManyRequestsException";
- var _c4 = "client";
- var _e4 = "error";
- var _hE4 = "httpError";
- var _m4 = "message";
- var _s4 = "smithy.ts.sdk.synthetic.com.amazonaws.cognitoidentity";
- var _se3 = "server";
- var n04 = "com.amazonaws.cognitoidentity";
- var schema_1 = require_schema();
- var CognitoIdentityServiceException_1 = require_CognitoIdentityServiceException();
- var errors_1 = require_errors5();
- var _s_registry4 = schema_1.TypeRegistry.for(_s4);
- exports.CognitoIdentityServiceException$ = [-3, _s4, "CognitoIdentityServiceException", 0, [], []];
- _s_registry4.registerError(exports.CognitoIdentityServiceException$, CognitoIdentityServiceException_1.CognitoIdentityServiceException);
- var n0_registry4 = schema_1.TypeRegistry.for(n04);
- exports.ExternalServiceException$ = [-3, n04, _ESE, { [_e4]: _c4, [_hE4]: 400 }, [_m4], [0]];
- n0_registry4.registerError(exports.ExternalServiceException$, errors_1.ExternalServiceException);
- exports.InternalErrorException$ = [-3, n04, _IEE, { [_e4]: _se3 }, [_m4], [0]];
- n0_registry4.registerError(exports.InternalErrorException$, errors_1.InternalErrorException);
- exports.InvalidIdentityPoolConfigurationException$ = [
- -3,
- n04,
- _IIPCE,
- { [_e4]: _c4, [_hE4]: 400 },
- [_m4],
- [0]
- ];
- n0_registry4.registerError(exports.InvalidIdentityPoolConfigurationException$, errors_1.InvalidIdentityPoolConfigurationException);
- exports.InvalidParameterException$ = [-3, n04, _IPE, { [_e4]: _c4, [_hE4]: 400 }, [_m4], [0]];
- n0_registry4.registerError(exports.InvalidParameterException$, errors_1.InvalidParameterException);
- exports.LimitExceededException$ = [-3, n04, _LEE, { [_e4]: _c4, [_hE4]: 400 }, [_m4], [0]];
- n0_registry4.registerError(exports.LimitExceededException$, errors_1.LimitExceededException);
- exports.NotAuthorizedException$ = [-3, n04, _NAE, { [_e4]: _c4, [_hE4]: 403 }, [_m4], [0]];
- n0_registry4.registerError(exports.NotAuthorizedException$, errors_1.NotAuthorizedException);
- exports.ResourceConflictException$ = [-3, n04, _RCE, { [_e4]: _c4, [_hE4]: 409 }, [_m4], [0]];
- n0_registry4.registerError(exports.ResourceConflictException$, errors_1.ResourceConflictException);
- exports.ResourceNotFoundException$ = [-3, n04, _RNFE3, { [_e4]: _c4, [_hE4]: 404 }, [_m4], [0]];
- n0_registry4.registerError(exports.ResourceNotFoundException$, errors_1.ResourceNotFoundException);
- exports.TooManyRequestsException$ = [-3, n04, _TMRE, { [_e4]: _c4, [_hE4]: 429 }, [_m4], [0]];
- n0_registry4.registerError(exports.TooManyRequestsException$, errors_1.TooManyRequestsException);
- exports.errorTypeRegistries = [_s_registry4, n0_registry4];
- var IdentityProviderToken = [0, n04, _IPT, 8, 0];
- var SecretKeyString = [0, n04, _SKS, 8, 0];
- exports.Credentials$ = [
- 3,
- n04,
- _C3,
- 0,
- [_AKI2, _SK, _ST4, _E2],
- [0, [() => SecretKeyString, 0], 0, 4]
- ];
- exports.GetCredentialsForIdentityInput$ = [
- 3,
- n04,
- _GCFII,
- 0,
- [_II, _L, _CRA],
- [0, [() => LoginsMap, 0], 0],
- 1
- ];
- exports.GetCredentialsForIdentityResponse$ = [
- 3,
- n04,
- _GCFIR,
- 0,
- [_II, _C3],
- [0, [() => exports.Credentials$, 0]]
- ];
- exports.GetIdInput$ = [3, n04, _GII, 0, [_IPI, _AI, _L], [0, 0, [() => LoginsMap, 0]], 1];
- exports.GetIdResponse$ = [3, n04, _GIR, 0, [_II], [0]];
- var LoginsMap = [2, n04, _LM, 0, [0, 0], [() => IdentityProviderToken, 0]];
- exports.GetCredentialsForIdentity$ = [
- 9,
- n04,
- _GCFI,
- 0,
- () => exports.GetCredentialsForIdentityInput$,
- () => exports.GetCredentialsForIdentityResponse$
- ];
- exports.GetId$ = [9, n04, _GI, 0, () => exports.GetIdInput$, () => exports.GetIdResponse$];
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/runtimeConfig.shared.js
-var require_runtimeConfig_shared5 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRuntimeConfig = undefined;
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var protocols_1 = require_protocols2();
- var core_1 = require_dist_cjs37();
- var smithy_client_1 = require_dist_cjs71();
- var url_parser_1 = require_dist_cjs11();
- var util_base64_1 = require_dist_cjs86();
- var util_utf8_1 = require_dist_cjs17();
- var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider5();
- var endpointResolver_1 = require_endpointResolver5();
- var schemas_0_1 = require_schemas_05();
- var getRuntimeConfig7 = (config6) => {
- return {
- apiVersion: "2014-06-30",
- base64Decoder: config6?.base64Decoder ?? util_base64_1.fromBase64,
- base64Encoder: config6?.base64Encoder ?? util_base64_1.toBase64,
- disableHostPrefix: config6?.disableHostPrefix ?? false,
- endpointProvider: config6?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver,
- extensions: config6?.extensions ?? [],
- httpAuthSchemeProvider: config6?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultCognitoIdentityHttpAuthSchemeProvider,
- httpAuthSchemes: config6?.httpAuthSchemes ?? [
- {
- schemeId: "aws.auth#sigv4",
- identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
- signer: new httpAuthSchemes_1.AwsSdkSigV4Signer
- },
- {
- schemeId: "smithy.api#noAuth",
- identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
- signer: new core_1.NoAuthSigner
- }
- ],
- logger: config6?.logger ?? new smithy_client_1.NoOpLogger,
- protocol: config6?.protocol ?? protocols_1.AwsJson1_1Protocol,
- protocolSettings: config6?.protocolSettings ?? {
- defaultNamespace: "com.amazonaws.cognitoidentity",
- errorTypeRegistries: schemas_0_1.errorTypeRegistries,
- xmlNamespace: "http://cognito-identity.amazonaws.com/doc/2014-06-30/",
- version: "2014-06-30",
- serviceTarget: "AWSCognitoIdentityService"
- },
- serviceId: config6?.serviceId ?? "Cognito Identity",
- urlParser: config6?.urlParser ?? url_parser_1.parseUrl,
- utf8Decoder: config6?.utf8Decoder ?? util_utf8_1.fromUtf8,
- utf8Encoder: config6?.utf8Encoder ?? util_utf8_1.toUtf8
- };
- };
- exports.getRuntimeConfig = getRuntimeConfig7;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/runtimeConfig.js
-var require_runtimeConfig5 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRuntimeConfig = undefined;
- var tslib_1 = require_tslib();
- var package_json_1 = tslib_1.__importDefault(require_package());
- var client_1 = require_client();
- var httpAuthSchemes_1 = require_httpAuthSchemes();
- var util_user_agent_node_1 = require_dist_cjs72();
- var config_resolver_1 = require_dist_cjs58();
- var hash_node_1 = require_dist_cjs75();
- var middleware_retry_1 = require_dist_cjs69();
- var node_config_provider_1 = require_dist_cjs9();
- var node_http_handler_1 = require_dist_cjs5();
- var smithy_client_1 = require_dist_cjs71();
- var util_body_length_node_1 = require_dist_cjs76();
- var util_defaults_mode_node_1 = require_dist_cjs77();
- var util_retry_1 = require_dist_cjs55();
- var runtimeConfig_shared_1 = require_runtimeConfig_shared5();
- var getRuntimeConfig7 = (config6) => {
- (0, smithy_client_1.emitWarningIfUnsupportedVersion)(process.version);
- const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config6);
- const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
- const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config6);
- (0, client_1.emitWarningIfUnsupportedVersion)(process.version);
- const loaderConfig = {
- profile: config6?.profile,
- logger: clientSharedValues.logger
- };
- return {
- ...clientSharedValues,
- ...config6,
- runtime: "node",
- defaultsMode,
- authSchemePreference: config6?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(httpAuthSchemes_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
- bodyLengthChecker: config6?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength,
- defaultUserAgentProvider: config6?.defaultUserAgentProvider ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
- maxAttempts: config6?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config6),
- region: config6?.region ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
- requestHandler: node_http_handler_1.NodeHttpHandler.create(config6?.requestHandler ?? defaultConfigProvider),
- retryMode: config6?.retryMode ?? (0, node_config_provider_1.loadConfig)({
- ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
- default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
- }, config6),
- sha256: config6?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"),
- streamCollector: config6?.streamCollector ?? node_http_handler_1.streamCollector,
- useDualstackEndpoint: config6?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- useFipsEndpoint: config6?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
- userAgentAppId: config6?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
- };
- };
- exports.getRuntimeConfig = getRuntimeConfig7;
-});
-
-// node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/index.js
-var require_cognito_identity = __commonJS((exports) => {
- var middlewareHostHeader = require_dist_cjs44();
- var middlewareLogger = require_dist_cjs45();
- var middlewareRecursionDetection = require_dist_cjs48();
- var middlewareUserAgent = require_dist_cjs56();
- var configResolver = require_dist_cjs58();
- var core2 = require_dist_cjs37();
- var schema5 = require_schema();
- var middlewareContentLength = require_dist_cjs61();
- var middlewareEndpoint = require_dist_cjs65();
- var middlewareRetry = require_dist_cjs69();
- var smithyClient = require_dist_cjs71();
- var httpAuthSchemeProvider = require_httpAuthSchemeProvider5();
- var runtimeConfig = require_runtimeConfig5();
- var regionConfigResolver = require_dist_cjs87();
- var protocolHttp = require_dist_cjs88();
- var schemas_04 = require_schemas_05();
- var errors6 = require_errors5();
- var CognitoIdentityServiceException = require_CognitoIdentityServiceException();
- var resolveClientEndpointParameters4 = (options2) => {
- return Object.assign(options2, {
- useDualstackEndpoint: options2.useDualstackEndpoint ?? false,
- useFipsEndpoint: options2.useFipsEndpoint ?? false,
- defaultSigningName: "cognito-identity"
- });
- };
- var commonParams4 = {
- UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
- Endpoint: { type: "builtInParams", name: "endpoint" },
- Region: { type: "builtInParams", name: "region" },
- UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
- };
- var getHttpAuthExtensionConfiguration4 = (runtimeConfig2) => {
- const _httpAuthSchemes = runtimeConfig2.httpAuthSchemes;
- let _httpAuthSchemeProvider = runtimeConfig2.httpAuthSchemeProvider;
- let _credentials = runtimeConfig2.credentials;
- return {
- setHttpAuthScheme(httpAuthScheme) {
- const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
- if (index2 === -1) {
- _httpAuthSchemes.push(httpAuthScheme);
- } else {
- _httpAuthSchemes.splice(index2, 1, httpAuthScheme);
- }
- },
- httpAuthSchemes() {
- return _httpAuthSchemes;
- },
- setHttpAuthSchemeProvider(httpAuthSchemeProvider2) {
- _httpAuthSchemeProvider = httpAuthSchemeProvider2;
- },
- httpAuthSchemeProvider() {
- return _httpAuthSchemeProvider;
- },
- setCredentials(credentials) {
- _credentials = credentials;
- },
- credentials() {
- return _credentials;
- }
- };
- };
- var resolveHttpAuthRuntimeConfig4 = (config6) => {
- return {
- httpAuthSchemes: config6.httpAuthSchemes(),
- httpAuthSchemeProvider: config6.httpAuthSchemeProvider(),
- credentials: config6.credentials()
- };
- };
- var resolveRuntimeExtensions4 = (runtimeConfig2, extensions16) => {
- const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig2), smithyClient.getDefaultExtensionConfiguration(runtimeConfig2), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig2), getHttpAuthExtensionConfiguration4(runtimeConfig2));
- extensions16.forEach((extension) => extension.configure(extensionConfiguration));
- return Object.assign(runtimeConfig2, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig4(extensionConfiguration));
- };
-
- class CognitoIdentityClient extends smithyClient.Client {
- config;
- constructor(...[configuration]) {
- const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {});
- super(_config_0);
- this.initConfig = _config_0;
- const _config_1 = resolveClientEndpointParameters4(_config_0);
- const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1);
- const _config_3 = middlewareRetry.resolveRetryConfig(_config_2);
- const _config_4 = configResolver.resolveRegionConfig(_config_3);
- const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4);
- const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5);
- const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6);
- const _config_8 = resolveRuntimeExtensions4(_config_7, configuration?.extensions || []);
- this.config = _config_8;
- this.middlewareStack.use(schema5.getSchemaSerdePlugin(this.config));
- this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config));
- this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config));
- this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config));
- this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config));
- this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config));
- this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config));
- this.middlewareStack.use(core2.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
- httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultCognitoIdentityHttpAuthSchemeParametersProvider,
- identityProviderConfigProvider: async (config6) => new core2.DefaultIdentityProviderConfig({
- "aws.auth#sigv4": config6.credentials
- })
- }));
- this.middlewareStack.use(core2.getHttpSigningPlugin(this.config));
- }
- destroy() {
- super.destroy();
- }
- }
-
- class GetCredentialsForIdentityCommand extends smithyClient.Command.classBuilder().ep(commonParams4).m(function(Command6, cs, config6, o5) {
- return [middlewareEndpoint.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSCognitoIdentityService", "GetCredentialsForIdentity", {}).n("CognitoIdentityClient", "GetCredentialsForIdentityCommand").sc(schemas_04.GetCredentialsForIdentity$).build() {
- }
-
- class GetIdCommand extends smithyClient.Command.classBuilder().ep(commonParams4).m(function(Command6, cs, config6, o5) {
- return [middlewareEndpoint.getEndpointPlugin(config6, Command6.getEndpointParameterInstructions())];
- }).s("AWSCognitoIdentityService", "GetId", {}).n("CognitoIdentityClient", "GetIdCommand").sc(schemas_04.GetId$).build() {
- }
- var commands7 = {
- GetCredentialsForIdentityCommand,
- GetIdCommand
- };
-
- class CognitoIdentity extends CognitoIdentityClient {
- }
- smithyClient.createAggregatedClient(commands7, CognitoIdentity);
- exports.$Command = smithyClient.Command;
- exports.__Client = smithyClient.Client;
- exports.CognitoIdentityServiceException = CognitoIdentityServiceException.CognitoIdentityServiceException;
- exports.CognitoIdentity = CognitoIdentity;
- exports.CognitoIdentityClient = CognitoIdentityClient;
- exports.GetCredentialsForIdentityCommand = GetCredentialsForIdentityCommand;
- exports.GetIdCommand = GetIdCommand;
- Object.prototype.hasOwnProperty.call(schemas_04, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: schemas_04["__proto__"]
- });
- Object.keys(schemas_04).forEach(function(k4) {
- if (k4 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k4))
- exports[k4] = schemas_04[k4];
- });
- Object.prototype.hasOwnProperty.call(errors6, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
- enumerable: true,
- value: errors6["__proto__"]
- });
- Object.keys(errors6).forEach(function(k4) {
- if (k4 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k4))
- exports[k4] = errors6[k4];
- });
-});
-
-// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/loadCognitoIdentity.js
-var exports_loadCognitoIdentity = {};
-__export(exports_loadCognitoIdentity, {
- GetIdCommand: () => import_cognito_identity.GetIdCommand,
- GetCredentialsForIdentityCommand: () => import_cognito_identity.GetCredentialsForIdentityCommand,
- CognitoIdentityClient: () => import_cognito_identity.CognitoIdentityClient
-});
-var import_cognito_identity;
-var init_loadCognitoIdentity = __esm(() => {
- import_cognito_identity = __toESM(require_cognito_identity(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentity.js
-function fromCognitoIdentity(parameters) {
- return async (awsIdentityProperties) => {
- parameters.logger?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity");
- const { GetCredentialsForIdentityCommand: GetCredentialsForIdentityCommand2, CognitoIdentityClient: CognitoIdentityClient2 } = await Promise.resolve().then(() => (init_loadCognitoIdentity(), exports_loadCognitoIdentity));
- const fromConfigs = (property2) => parameters.clientConfig?.[property2] ?? parameters.parentClientConfig?.[property2] ?? awsIdentityProperties?.callerClientConfig?.[property2];
- const { Credentials: { AccessKeyId = throwOnMissingAccessKeyId(parameters.logger), Expiration, SecretKey = throwOnMissingSecretKey(parameters.logger), SessionToken } = throwOnMissingCredentials(parameters.logger) } = await (parameters.client ?? new CognitoIdentityClient2(Object.assign({}, parameters.clientConfig ?? {}, {
- region: fromConfigs("region"),
- profile: fromConfigs("profile"),
- userAgentAppId: fromConfigs("userAgentAppId")
- }))).send(new GetCredentialsForIdentityCommand2({
- CustomRoleArn: parameters.customRoleArn,
- IdentityId: parameters.identityId,
- Logins: parameters.logins ? await resolveLogins(parameters.logins) : undefined
- }));
- return {
- identityId: parameters.identityId,
- accessKeyId: AccessKeyId,
- secretAccessKey: SecretKey,
- sessionToken: SessionToken,
- expiration: Expiration
- };
- };
-}
-function throwOnMissingAccessKeyId(logger5) {
- throw new import_property_provider27.CredentialsProviderError("Response from Amazon Cognito contained no access key ID", { logger: logger5 });
-}
-function throwOnMissingCredentials(logger5) {
- throw new import_property_provider27.CredentialsProviderError("Response from Amazon Cognito contained no credentials", { logger: logger5 });
-}
-function throwOnMissingSecretKey(logger5) {
- throw new import_property_provider27.CredentialsProviderError("Response from Amazon Cognito contained no secret key", { logger: logger5 });
-}
-var import_property_provider27;
-var init_fromCognitoIdentity = __esm(() => {
- import_property_provider27 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/IndexedDbStorage.js
-class IndexedDbStorage {
- dbName;
- constructor(dbName = "aws:cognito-identity-ids") {
- this.dbName = dbName;
- }
- getItem(key) {
- return this.withObjectStore("readonly", (store) => {
- const req = store.get(key);
- return new Promise((resolve9) => {
- req.onerror = () => resolve9(null);
- req.onsuccess = () => resolve9(req.result ? req.result.value : null);
- });
- }).catch(() => null);
- }
- removeItem(key) {
- return this.withObjectStore("readwrite", (store) => {
- const req = store.delete(key);
- return new Promise((resolve9, reject) => {
- req.onerror = () => reject(req.error);
- req.onsuccess = () => resolve9();
- });
- });
- }
- setItem(id, value) {
- return this.withObjectStore("readwrite", (store) => {
- const req = store.put({ id, value });
- return new Promise((resolve9, reject) => {
- req.onerror = () => reject(req.error);
- req.onsuccess = () => resolve9();
- });
- });
- }
- getDb() {
- const openDbRequest = self.indexedDB.open(this.dbName, 1);
- return new Promise((resolve9, reject) => {
- openDbRequest.onsuccess = () => {
- resolve9(openDbRequest.result);
- };
- openDbRequest.onerror = () => {
- reject(openDbRequest.error);
- };
- openDbRequest.onblocked = () => {
- reject(new Error("Unable to access DB"));
- };
- openDbRequest.onupgradeneeded = () => {
- const db = openDbRequest.result;
- db.onerror = () => {
- reject(new Error("Failed to create object store"));
- };
- db.createObjectStore(STORE_NAME, { keyPath: "id" });
- };
- });
- }
- withObjectStore(mode, action) {
- return this.getDb().then((db) => {
- const tx = db.transaction(STORE_NAME, mode);
- tx.oncomplete = () => db.close();
- return new Promise((resolve9, reject) => {
- tx.onerror = () => reject(tx.error);
- resolve9(action(tx.objectStore(STORE_NAME)));
- }).catch((err) => {
- db.close();
- throw err;
- });
- });
- }
-}
-var STORE_NAME = "IdentityIds";
-
-// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/InMemoryStorage.js
-class InMemoryStorage {
- store;
- constructor(store = {}) {
- this.store = store;
- }
- getItem(key) {
- if (key in this.store) {
- return this.store[key];
- }
- return null;
- }
- removeItem(key) {
- delete this.store[key];
- }
- setItem(key, value) {
- this.store[key] = value;
- }
-}
-
-// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/localStorage.js
-function localStorage2() {
- if (typeof self === "object" && self.indexedDB) {
- return new IndexedDbStorage;
- }
- if (typeof window === "object" && window.localStorage) {
- return window.localStorage;
- }
- return inMemoryStorage;
-}
-var inMemoryStorage;
-var init_localStorage = __esm(() => {
- inMemoryStorage = new InMemoryStorage;
-});
-
-// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentityPool.js
-function fromCognitoIdentityPool({ accountId, cache: cache5 = localStorage2(), client: client9, clientConfig, customRoleArn, identityPoolId, logins, userIdentifier = !logins || Object.keys(logins).length === 0 ? "ANONYMOUS" : undefined, logger: logger5, parentClientConfig }) {
- logger5?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity");
- const cacheKey = userIdentifier ? `aws:cognito-identity-credentials:${identityPoolId}:${userIdentifier}` : undefined;
- let provider3 = async (awsIdentityProperties) => {
- const { GetIdCommand: GetIdCommand2, CognitoIdentityClient: CognitoIdentityClient2 } = await Promise.resolve().then(() => (init_loadCognitoIdentity(), exports_loadCognitoIdentity));
- const fromConfigs = (property2) => clientConfig?.[property2] ?? parentClientConfig?.[property2] ?? awsIdentityProperties?.callerClientConfig?.[property2];
- const _client = client9 ?? new CognitoIdentityClient2(Object.assign({}, clientConfig ?? {}, {
- region: fromConfigs("region"),
- profile: fromConfigs("profile"),
- userAgentAppId: fromConfigs("userAgentAppId")
- }));
- let identityId = cacheKey && await cache5.getItem(cacheKey);
- if (!identityId) {
- const { IdentityId = throwOnMissingId(logger5) } = await _client.send(new GetIdCommand2({
- AccountId: accountId,
- IdentityPoolId: identityPoolId,
- Logins: logins ? await resolveLogins(logins) : undefined
- }));
- identityId = IdentityId;
- if (cacheKey) {
- Promise.resolve(cache5.setItem(cacheKey, identityId)).catch(() => {});
- }
- }
- provider3 = fromCognitoIdentity({
- client: _client,
- customRoleArn,
- logins,
- identityId
- });
- return provider3(awsIdentityProperties);
- };
- return (awsIdentityProperties) => provider3(awsIdentityProperties).catch(async (err) => {
- if (cacheKey) {
- Promise.resolve(cache5.removeItem(cacheKey)).catch(() => {});
- }
- throw err;
- });
-}
-function throwOnMissingId(logger5) {
- throw new import_property_provider28.CredentialsProviderError("Response from Amazon Cognito contained no identity ID", { logger: logger5 });
-}
-var import_property_provider28;
-var init_fromCognitoIdentityPool = __esm(() => {
- init_fromCognitoIdentity();
- init_localStorage();
- import_property_provider28 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/index.js
-var init_dist_es45 = __esm(() => {
- init_CognitoProviderParameters();
- init_Logins();
- init_Storage();
- init_fromCognitoIdentity();
- init_fromCognitoIdentityPool();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentity.js
-var fromCognitoIdentity3 = (options2) => fromCognitoIdentity({
- ...options2
-});
-var init_fromCognitoIdentity2 = __esm(() => {
- init_dist_es45();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentityPool.js
-var fromCognitoIdentityPool3 = (options2) => fromCognitoIdentityPool({
- ...options2
-});
-var init_fromCognitoIdentityPool2 = __esm(() => {
- init_dist_es45();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromContainerMetadata.js
-var fromContainerMetadata3 = (init) => {
- init?.logger?.debug("@smithy/credential-provider-imds", "fromContainerMetadata");
- return fromContainerMetadata(init);
-};
-var init_fromContainerMetadata2 = __esm(() => {
- init_dist_es2();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromEnv.js
-var fromEnv3 = (init) => fromEnv(init);
-var init_fromEnv2 = __esm(() => {
- init_dist_es();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromIni.js
-var fromIni3 = (init = {}) => fromIni({
- ...init
-});
-var init_fromIni2 = __esm(() => {
- init_dist_es13();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromInstanceMetadata.js
-var import_client19, fromInstanceMetadata3 = (init) => {
- init?.logger?.debug("@smithy/credential-provider-imds", "fromInstanceMetadata");
- return async () => fromInstanceMetadata(init)().then((creds) => import_client19.setCredentialFeature(creds, "CREDENTIALS_IMDS", "0"));
-};
-var init_fromInstanceMetadata2 = __esm(() => {
- init_dist_es2();
- import_client19 = __toESM(require_client(), 1);
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromLoginCredentials.js
-var fromLoginCredentials3 = (init) => fromLoginCredentials({
- ...init
-});
-var init_fromLoginCredentials2 = __esm(() => {
- init_dist_es10();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromNodeProviderChain.js
-var fromNodeProviderChain = (init = {}) => defaultProvider({
- ...init
-});
-var init_fromNodeProviderChain = __esm(() => {
- init_dist_es14();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromProcess.js
-var fromProcess3 = (init) => fromProcess(init);
-var init_fromProcess2 = __esm(() => {
- init_dist_es11();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromSSO.js
-var fromSSO3 = (init = {}) => {
- return fromSSO({ ...init });
-};
-var init_fromSSO2 = __esm(() => {
- init_dist_es8();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/loadSts.js
-var exports_loadSts = {};
-__export(exports_loadSts, {
- STSClient: () => import_sts.STSClient,
- AssumeRoleCommand: () => import_sts.AssumeRoleCommand
-});
-var import_sts;
-var init_loadSts = __esm(() => {
- import_sts = __toESM(require_sts(), 1);
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.base.js
-var import_core47, import_property_provider29, ASSUME_ROLE_DEFAULT_REGION = "us-east-1", fromTemporaryCredentials = (options2, credentialDefaultProvider, regionProvider) => {
- let stsClient;
- return async (awsIdentityProperties = {}) => {
- const { callerClientConfig } = awsIdentityProperties;
- const profile5 = options2.clientConfig?.profile ?? callerClientConfig?.profile;
- const logger5 = options2.logger ?? callerClientConfig?.logger;
- logger5?.debug("@aws-sdk/credential-providers - fromTemporaryCredentials (STS)");
- const params = { ...options2.params, RoleSessionName: options2.params.RoleSessionName ?? "aws-sdk-js-" + Date.now() };
- if (params?.SerialNumber) {
- if (!options2.mfaCodeProvider) {
- throw new import_property_provider29.CredentialsProviderError(`Temporary credential requires multi-factor authentication, but no MFA code callback was provided.`, {
- tryNextLink: false,
- logger: logger5
- });
- }
- params.TokenCode = await options2.mfaCodeProvider(params?.SerialNumber);
- }
- const { AssumeRoleCommand: AssumeRoleCommand4, STSClient: STSClient4 } = await Promise.resolve().then(() => (init_loadSts(), exports_loadSts));
- if (!stsClient) {
- const defaultCredentialsOrError = typeof credentialDefaultProvider === "function" ? credentialDefaultProvider() : undefined;
- const credentialSources = [
- options2.masterCredentials,
- options2.clientConfig?.credentials,
- void callerClientConfig?.credentials,
- callerClientConfig?.credentialDefaultProvider?.(),
- defaultCredentialsOrError
- ];
- let credentialSource = "STS client default credentials";
- if (credentialSources[0]) {
- credentialSource = "options.masterCredentials";
- } else if (credentialSources[1]) {
- credentialSource = "options.clientConfig.credentials";
- } else if (credentialSources[2]) {
- credentialSource = "caller client's credentials";
- throw new Error("fromTemporaryCredentials recursion in callerClientConfig.credentials");
- } else if (credentialSources[3]) {
- credentialSource = "caller client's credentialDefaultProvider";
- } else if (credentialSources[4]) {
- credentialSource = "AWS SDK default credentials";
- }
- const regionSources = [
- options2.clientConfig?.region,
- callerClientConfig?.region,
- await regionProvider?.({
- profile: profile5
- }),
- ASSUME_ROLE_DEFAULT_REGION
- ];
- let regionSource = "default partition's default region";
- if (regionSources[0]) {
- regionSource = "options.clientConfig.region";
- } else if (regionSources[1]) {
- regionSource = "caller client's region";
- } else if (regionSources[2]) {
- regionSource = "file or env region";
- }
- const requestHandlerSources = [
- filterRequestHandler(options2.clientConfig?.requestHandler),
- filterRequestHandler(callerClientConfig?.requestHandler)
- ];
- let requestHandlerSource = "STS default requestHandler";
- if (requestHandlerSources[0]) {
- requestHandlerSource = "options.clientConfig.requestHandler";
- } else if (requestHandlerSources[1]) {
- requestHandlerSource = "caller client's requestHandler";
- }
- logger5?.debug?.(`@aws-sdk/credential-providers - fromTemporaryCredentials STS client init with ${regionSource}=${await import_core47.normalizeProvider(coalesce(regionSources))()}, ${credentialSource}, ${requestHandlerSource}.`);
- stsClient = new STSClient4({
- userAgentAppId: callerClientConfig?.userAgentAppId,
- ...options2.clientConfig,
- credentials: coalesce(credentialSources),
- logger: logger5,
- profile: profile5,
- region: coalesce(regionSources),
- requestHandler: coalesce(requestHandlerSources)
- });
- }
- if (options2.clientPlugins) {
- for (const plugin of options2.clientPlugins) {
- stsClient.middlewareStack.use(plugin);
- }
- }
- const { Credentials } = await stsClient.send(new AssumeRoleCommand4(params));
- if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
- throw new import_property_provider29.CredentialsProviderError(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`, {
- logger: logger5
- });
- }
- return {
- accessKeyId: Credentials.AccessKeyId,
- secretAccessKey: Credentials.SecretAccessKey,
- sessionToken: Credentials.SessionToken,
- expiration: Credentials.Expiration,
- credentialScope: Credentials.CredentialScope
- };
- };
-}, filterRequestHandler = (requestHandler) => {
- return requestHandler?.metadata?.handlerProtocol === "h2" ? undefined : requestHandler;
-}, coalesce = (args) => {
- for (const item of args) {
- if (item !== undefined) {
- return item;
- }
- }
-};
-var init_fromTemporaryCredentials_base = __esm(() => {
- import_core47 = __toESM(require_dist_cjs37(), 1);
- import_property_provider29 = __toESM(require_dist_cjs6(), 1);
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.js
-var import_config_resolver7, import_node_config_provider6, fromTemporaryCredentials2 = (options2) => {
- return fromTemporaryCredentials(options2, fromNodeProviderChain, async ({ profile: profile5 = process.env.AWS_PROFILE }) => import_node_config_provider6.loadConfig({
- environmentVariableSelector: (env4) => env4.AWS_REGION,
- configFileSelector: (profileData) => {
- return profileData.region;
- },
- default: () => {
- return;
- }
- }, { ...import_config_resolver7.NODE_REGION_CONFIG_FILE_OPTIONS, profile: profile5 })());
-};
-var init_fromTemporaryCredentials = __esm(() => {
- init_fromNodeProviderChain();
- init_fromTemporaryCredentials_base();
- import_config_resolver7 = __toESM(require_dist_cjs58(), 1);
- import_node_config_provider6 = __toESM(require_dist_cjs9(), 1);
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromTokenFile.js
-var fromTokenFile3 = (init = {}) => fromTokenFile({
- ...init
-});
-var init_fromTokenFile2 = __esm(() => {
- init_dist_es12();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/fromWebToken.js
-var fromWebToken3 = (init) => fromWebToken({
- ...init
-});
-var init_fromWebToken = __esm(() => {
- init_dist_es12();
-});
-
-// node_modules/@aws-sdk/credential-providers/dist-es/index.js
-var exports_dist_es16 = {};
-__export(exports_dist_es16, {
- propertyProviderChain: () => propertyProviderChain,
- fromWebToken: () => fromWebToken3,
- fromTokenFile: () => fromTokenFile3,
- fromTemporaryCredentials: () => fromTemporaryCredentials2,
- fromSSO: () => fromSSO3,
- fromProcess: () => fromProcess3,
- fromNodeProviderChain: () => fromNodeProviderChain,
- fromLoginCredentials: () => fromLoginCredentials3,
- fromInstanceMetadata: () => fromInstanceMetadata3,
- fromIni: () => fromIni3,
- fromHttp: () => fromHttp,
- fromEnv: () => fromEnv3,
- fromContainerMetadata: () => fromContainerMetadata3,
- fromCognitoIdentityPool: () => fromCognitoIdentityPool3,
- fromCognitoIdentity: () => fromCognitoIdentity3,
- createCredentialChain: () => createCredentialChain
-});
-var init_dist_es46 = __esm(() => {
- init_dist_es6();
- init_createCredentialChain();
- init_fromCognitoIdentity2();
- init_fromCognitoIdentityPool2();
- init_fromContainerMetadata2();
- init_fromEnv2();
- init_fromIni2();
- init_fromInstanceMetadata2();
- init_fromLoginCredentials2();
- init_fromNodeProviderChain();
- init_fromProcess2();
- init_fromSSO2();
- init_fromTemporaryCredentials();
- init_fromTokenFile2();
- init_fromWebToken();
-});
-
-// src/utils/aws.ts
-function isAwsCredentialsProviderError(err) {
- return err?.name === "CredentialsProviderError";
-}
-function isValidAwsStsOutput(obj) {
- if (!obj || typeof obj !== "object") {
- return false;
- }
- const output = obj;
- if (!output.Credentials || typeof output.Credentials !== "object") {
- return false;
- }
- const credentials = output.Credentials;
- return typeof credentials.AccessKeyId === "string" && typeof credentials.SecretAccessKey === "string" && typeof credentials.SessionToken === "string" && credentials.AccessKeyId.length > 0 && credentials.SecretAccessKey.length > 0 && credentials.SessionToken.length > 0;
-}
-async function checkStsCallerIdentity() {
- const { STSClient: STSClient4, GetCallerIdentityCommand: GetCallerIdentityCommand3 } = await Promise.resolve().then(() => (init_dist_es44(), exports_dist_es15));
- await new STSClient4().send(new GetCallerIdentityCommand3({}));
-}
-async function clearAwsIniCache() {
- try {
- logForDebugging("Clearing AWS credential provider cache");
- const { fromIni: fromIni5 } = await Promise.resolve().then(() => (init_dist_es46(), exports_dist_es16));
- const iniProvider = fromIni5({ ignoreCache: true });
- await iniProvider();
- logForDebugging("AWS credential provider cache refreshed");
- } catch (_error) {
- logForDebugging("Failed to clear AWS credential cache (this is expected if no credentials are configured)");
- }
-}
-var init_aws = __esm(() => {
- init_debug();
-});
-
-// src/utils/awsAuthStatusManager.ts
-class AwsAuthStatusManager {
- static instance = null;
- status = {
- isAuthenticating: false,
- output: []
- };
- changed = createSignal();
- static getInstance() {
- if (!AwsAuthStatusManager.instance) {
- AwsAuthStatusManager.instance = new AwsAuthStatusManager;
- }
- return AwsAuthStatusManager.instance;
- }
- getStatus() {
- return {
- ...this.status,
- output: [...this.status.output]
- };
- }
- startAuthentication() {
- this.status = {
- isAuthenticating: true,
- output: []
- };
- this.changed.emit(this.getStatus());
- }
- addOutput(line) {
- this.status.output.push(line);
- this.changed.emit(this.getStatus());
- }
- setError(error40) {
- this.status.error = error40;
- this.changed.emit(this.getStatus());
- }
- endAuthentication(success2) {
- if (success2) {
- this.status = {
- isAuthenticating: false,
- output: []
- };
- } else {
- this.status.isAuthenticating = false;
- }
- this.changed.emit(this.getStatus());
- }
- subscribe = this.changed.subscribe;
- static reset() {
- if (AwsAuthStatusManager.instance) {
- AwsAuthStatusManager.instance.changed.clear();
- AwsAuthStatusManager.instance = null;
- }
- }
-}
-var init_awsAuthStatusManager = () => {};
-
-// src/constants/betas.ts
-var CLAUDE_CODE_20250219_BETA_HEADER = "claude-code-20250219", INTERLEAVED_THINKING_BETA_HEADER = "interleaved-thinking-2025-05-14", CONTEXT_1M_BETA_HEADER = "context-1m-2025-08-07", CONTEXT_MANAGEMENT_BETA_HEADER = "context-management-2025-06-27", STRUCTURED_OUTPUTS_BETA_HEADER = "structured-outputs-2025-12-15", WEB_SEARCH_BETA_HEADER = "web-search-2025-03-05", TOOL_SEARCH_BETA_HEADER_1P = "advanced-tool-use-2025-11-20", TOOL_SEARCH_BETA_HEADER_3P = "tool-search-tool-2025-10-19", EFFORT_BETA_HEADER = "effort-2025-11-24", TASK_BUDGETS_BETA_HEADER = "task-budgets-2026-03-13", PROMPT_CACHING_SCOPE_BETA_HEADER = "prompt-caching-scope-2026-01-05", FAST_MODE_BETA_HEADER = "fast-mode-2026-02-01", REDACT_THINKING_BETA_HEADER = "redact-thinking-2026-02-12", TOKEN_EFFICIENT_TOOLS_BETA_HEADER = "token-efficient-tools-2026-03-28", SUMMARIZE_CONNECTOR_TEXT_BETA_HEADER = "", AFK_MODE_BETA_HEADER = "", CLI_INTERNAL_BETA_HEADER, ADVISOR_BETA_HEADER = "advisor-tool-2026-03-01", BEDROCK_EXTRA_PARAMS_HEADERS, VERTEX_COUNT_TOKENS_ALLOWED_BETAS;
-var init_betas = __esm(() => {
- CLI_INTERNAL_BETA_HEADER = process.env.USER_TYPE === "ant" ? "cli-internal-2026-02-09" : "";
- BEDROCK_EXTRA_PARAMS_HEADERS = new Set([
- INTERLEAVED_THINKING_BETA_HEADER,
- CONTEXT_1M_BETA_HEADER,
- TOOL_SEARCH_BETA_HEADER_3P
- ]);
- VERTEX_COUNT_TOKENS_ALLOWED_BETAS = new Set([
- CLAUDE_CODE_20250219_BETA_HEADER,
- INTERLEAVED_THINKING_BETA_HEADER,
- CONTEXT_MANAGEMENT_BETA_HEADER
- ]);
-});
-
-// src/utils/fastMode.ts
-function isFastModeEnabled() {
- return !isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_FAST_MODE);
-}
-function isFastModeAvailable() {
- if (!isFastModeEnabled()) {
- return false;
- }
- return getFastModeUnavailableReason() === null;
-}
-function getDisabledReasonMessage(disabledReason, authType) {
- switch (disabledReason) {
- case "free":
- return authType === "oauth" ? "Fast mode requires a paid subscription" : "Fast mode unavailable during evaluation. Please purchase credits.";
- case "preference":
- return "Fast mode has been disabled by your organization";
- case "extra_usage_disabled":
- return "Fast mode requires extra usage billing \xB7 /extra-usage to enable";
- case "network_error":
- return "Fast mode unavailable due to network connectivity issues";
- case "unknown":
- return "Fast mode is currently unavailable";
- }
-}
-function getFastModeUnavailableReason() {
- if (!isFastModeEnabled()) {
- return "Fast mode is not available";
- }
- const statigReason = getFeatureValue_CACHED_MAY_BE_STALE("tengu_penguins_off", null);
- if (statigReason !== null) {
- logForDebugging(`Fast mode unavailable: ${statigReason}`);
- return statigReason;
- }
- if (!isInBundledMode() && getFeatureValue_CACHED_MAY_BE_STALE("tengu_marble_sandcastle", false)) {
- return "Fast mode requires the native binary \xB7 Install from: https://claude.com/product/claude-code";
- }
- if (getIsNonInteractiveSession() && preferThirdPartyAuthentication() && !getKairosActive()) {
- const flagFastMode = getSettingsForSource("flagSettings")?.fastMode;
- if (!flagFastMode) {
- const reason = "Fast mode is not available in the Agent SDK";
- logForDebugging(`Fast mode unavailable: ${reason}`);
- return reason;
- }
- }
- if (getAPIProvider() !== "firstParty") {
- const reason = "Fast mode is not available on Bedrock, Vertex, or Foundry";
- logForDebugging(`Fast mode unavailable: ${reason}`);
- return reason;
- }
- if (orgStatus.status === "disabled") {
- if (orgStatus.reason === "network_error" || orgStatus.reason === "unknown") {
- if (isEnvTruthy(process.env.CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS)) {
- return null;
- }
- }
- const authType = getClaudeAIOAuthTokens() !== null ? "oauth" : "api-key";
- const reason = getDisabledReasonMessage(orgStatus.reason, authType);
- logForDebugging(`Fast mode unavailable: ${reason}`);
- return reason;
- }
- return null;
-}
-function getFastModeModel() {
- return "opus" + (isOpus1mMergeEnabled() ? "[1m]" : "");
-}
-function getInitialFastModeSetting(model) {
- if (!isFastModeEnabled()) {
- return false;
- }
- if (!isFastModeAvailable()) {
- return false;
- }
- if (!isFastModeSupportedByModel(model)) {
- return false;
- }
- const settings = getInitialSettings();
- if (settings.fastModePerSessionOptIn) {
- return false;
- }
- return settings.fastMode === true;
-}
-function isFastModeSupportedByModel(modelSetting) {
- if (!isFastModeEnabled()) {
- return false;
- }
- const model = modelSetting ?? getDefaultMainLoopModelSetting();
- const parsedModel = parseUserSpecifiedModel(model);
- return parsedModel.toLowerCase().includes("opus-4-6");
-}
-function getFastModeRuntimeState() {
- if (runtimeState.status === "cooldown" && Date.now() >= runtimeState.resetAt) {
- if (isFastModeEnabled() && !hasLoggedCooldownExpiry) {
- logForDebugging("Fast mode cooldown expired, re-enabling fast mode");
- hasLoggedCooldownExpiry = true;
- cooldownExpired.emit();
- }
- runtimeState = { status: "active" };
- }
- return runtimeState;
-}
-function triggerFastModeCooldown(resetTimestamp, reason) {
- if (!isFastModeEnabled()) {
- return;
- }
- runtimeState = { status: "cooldown", resetAt: resetTimestamp, reason };
- hasLoggedCooldownExpiry = false;
- const cooldownDurationMs = resetTimestamp - Date.now();
- logForDebugging(`Fast mode cooldown triggered (${reason}), duration ${Math.round(cooldownDurationMs / 1000)}s`);
- logEvent("tengu_fast_mode_fallback_triggered", {
- cooldown_duration_ms: cooldownDurationMs,
- cooldown_reason: reason
- });
- cooldownTriggered.emit(resetTimestamp, reason);
-}
-function clearFastModeCooldown() {
- runtimeState = { status: "active" };
-}
-function handleFastModeRejectedByAPI() {
- if (orgStatus.status === "disabled") {
- return;
- }
- orgStatus = { status: "disabled", reason: "preference" };
- updateSettingsForSource("userSettings", { fastMode: undefined });
- saveGlobalConfig((current) => ({
- ...current,
- penguinModeOrgEnabled: false
- }));
- orgFastModeChange.emit(false);
-}
-function getOverageDisabledMessage(reason) {
- switch (reason) {
- case "out_of_credits":
- return "Fast mode disabled \xB7 extra usage credits exhausted";
- case "org_level_disabled":
- case "org_service_level_disabled":
- return "Fast mode disabled \xB7 extra usage disabled by your organization";
- case "org_level_disabled_until":
- return "Fast mode disabled \xB7 extra usage spending cap reached";
- case "member_level_disabled":
- return "Fast mode disabled \xB7 extra usage disabled for your account";
- case "seat_tier_level_disabled":
- case "seat_tier_zero_credit_limit":
- case "member_zero_credit_limit":
- return "Fast mode disabled \xB7 extra usage not available for your plan";
- case "overage_not_provisioned":
- case "no_limits_configured":
- return "Fast mode requires extra usage billing \xB7 /extra-usage to enable";
- default:
- return "Fast mode disabled \xB7 extra usage not available";
- }
-}
-function isOutOfCreditsReason(reason) {
- return reason === "org_level_disabled_until" || reason === "out_of_credits";
-}
-function handleFastModeOverageRejection(reason) {
- const message = getOverageDisabledMessage(reason);
- logForDebugging(`Fast mode overage rejection: ${reason ?? "unknown"} \u2014 ${message}`);
- logEvent("tengu_fast_mode_overage_rejected", {
- overage_disabled_reason: reason ?? "unknown"
- });
- if (!isOutOfCreditsReason(reason)) {
- updateSettingsForSource("userSettings", { fastMode: undefined });
- saveGlobalConfig((current) => ({
- ...current,
- penguinModeOrgEnabled: false
- }));
- }
- overageRejection.emit(message);
-}
-function isFastModeCooldown() {
- return getFastModeRuntimeState().status === "cooldown";
-}
-function getFastModeState(model, fastModeUserEnabled) {
- const enabled = isFastModeEnabled() && isFastModeAvailable() && !!fastModeUserEnabled && isFastModeSupportedByModel(model);
- if (enabled && isFastModeCooldown()) {
- return "cooldown";
- }
- if (enabled) {
- return "on";
- }
- return "off";
-}
-async function fetchFastModeStatus(auth9) {
- const endpoint5 = `${getOauthConfig().BASE_API_URL}/api/claude_code_penguin_mode`;
- const headers = "accessToken" in auth9 ? {
- Authorization: `Bearer ${auth9.accessToken}`,
- "anthropic-beta": OAUTH_BETA_HEADER
- } : { "x-api-key": auth9.apiKey };
- const response5 = await axios_default.get(endpoint5, { headers });
- return response5.data;
-}
-function resolveFastModeStatusFromCache() {
- if (!isFastModeEnabled()) {
- return;
- }
- if (orgStatus.status !== "pending") {
- return;
- }
- const isAnt = process.env.USER_TYPE === "ant";
- const cachedEnabled = getGlobalConfig().penguinModeOrgEnabled === true;
- orgStatus = isAnt || cachedEnabled ? { status: "enabled" } : { status: "disabled", reason: "unknown" };
-}
-async function prefetchFastModeStatus() {
- if (isEssentialTrafficOnly()) {
- return;
- }
- if (!isFastModeEnabled()) {
- return;
- }
- if (inflightPrefetch) {
- logForDebugging("Fast mode prefetch in progress, returning in-flight promise");
- return inflightPrefetch;
- }
- const apiKey = getAnthropicApiKey();
- const hasUsableOAuth = getClaudeAIOAuthTokens()?.accessToken && hasProfileScope();
- if (!hasUsableOAuth && !apiKey) {
- const isAnt = process.env.USER_TYPE === "ant";
- const cachedEnabled = getGlobalConfig().penguinModeOrgEnabled === true;
- orgStatus = isAnt || cachedEnabled ? { status: "enabled" } : { status: "disabled", reason: "preference" };
- return;
- }
- const now = Date.now();
- if (now - lastPrefetchAt < PREFETCH_MIN_INTERVAL_MS) {
- logForDebugging("Skipping fast mode prefetch, fetched recently");
- return;
- }
- lastPrefetchAt = now;
- const fetchWithCurrentAuth = async () => {
- const currentTokens = getClaudeAIOAuthTokens();
- const auth9 = currentTokens?.accessToken && hasProfileScope() ? { accessToken: currentTokens.accessToken } : apiKey ? { apiKey } : null;
- if (!auth9) {
- throw new Error("No auth available");
- }
- return fetchFastModeStatus(auth9);
- };
- async function doFetch() {
- try {
- let status;
- try {
- status = await fetchWithCurrentAuth();
- } catch (err) {
- const isAuthError = axios_default.isAxiosError(err) && (err.response?.status === 401 || err.response?.status === 403 && typeof err.response?.data === "string" && err.response.data.includes("OAuth token has been revoked"));
- if (isAuthError) {
- const failedAccessToken = getClaudeAIOAuthTokens()?.accessToken;
- if (failedAccessToken) {
- await handleOAuth401Error(failedAccessToken);
- status = await fetchWithCurrentAuth();
- } else {
- throw err;
- }
- } else {
- throw err;
- }
- }
- const previousEnabled = orgStatus.status !== "pending" ? orgStatus.status === "enabled" : getGlobalConfig().penguinModeOrgEnabled;
- orgStatus = status.enabled ? { status: "enabled" } : {
- status: "disabled",
- reason: status.disabled_reason ?? "preference"
- };
- if (previousEnabled !== status.enabled) {
- if (!status.enabled) {
- updateSettingsForSource("userSettings", { fastMode: undefined });
- }
- saveGlobalConfig((current) => ({
- ...current,
- penguinModeOrgEnabled: status.enabled
- }));
- orgFastModeChange.emit(status.enabled);
- }
- logForDebugging(`Org fast mode: ${status.enabled ? "enabled" : `disabled (${status.disabled_reason ?? "preference"})`}`);
- } catch (err) {
- const isAnt = process.env.USER_TYPE === "ant";
- const cachedEnabled = getGlobalConfig().penguinModeOrgEnabled === true;
- orgStatus = isAnt || cachedEnabled ? { status: "enabled" } : { status: "disabled", reason: "network_error" };
- logForDebugging(`Failed to fetch org fast mode status, defaulting to ${orgStatus.status === "enabled" ? "enabled (cached)" : "disabled (network_error)"}: ${err}`, { level: "error" });
- logEvent("tengu_org_penguin_mode_fetch_failed", {});
- } finally {
- inflightPrefetch = null;
- }
- }
- inflightPrefetch = doFetch();
- return inflightPrefetch;
-}
-var FAST_MODE_MODEL_DISPLAY = "Opus 4.6", runtimeState, hasLoggedCooldownExpiry = false, cooldownTriggered, cooldownExpired, onCooldownTriggered, onCooldownExpired, overageRejection, onFastModeOverageRejection, orgStatus, orgFastModeChange, onOrgFastModeChanged, PREFETCH_MIN_INTERVAL_MS = 30000, lastPrefetchAt = 0, inflightPrefetch = null;
-var init_fastMode = __esm(() => {
- init_axios2();
- init_oauth();
- init_growthbook();
- init_state();
- init_analytics();
- init_auth14();
- init_config();
- init_debug();
- init_envUtils();
- init_model();
- init_providers();
- init_settings2();
- runtimeState = { status: "active" };
- cooldownTriggered = createSignal();
- cooldownExpired = createSignal();
- onCooldownTriggered = cooldownTriggered.subscribe;
- onCooldownExpired = cooldownExpired.subscribe;
- overageRejection = createSignal();
- onFastModeOverageRejection = overageRejection.subscribe;
- orgStatus = { status: "pending" };
- orgFastModeChange = createSignal();
- onOrgFastModeChanged = orgFastModeChange.subscribe;
-});
-
-// src/utils/modelCost.ts
-function getOpus46CostTier(fastMode) {
- if (isFastModeEnabled() && fastMode) {
- return COST_TIER_30_150;
- }
- return COST_TIER_5_25;
-}
-function tokensToUSDCost(modelCosts, usage) {
- return usage.input_tokens / 1e6 * modelCosts.inputTokens + usage.output_tokens / 1e6 * modelCosts.outputTokens + (usage.cache_read_input_tokens ?? 0) / 1e6 * modelCosts.promptCacheReadTokens + (usage.cache_creation_input_tokens ?? 0) / 1e6 * modelCosts.promptCacheWriteTokens + (usage.server_tool_use?.web_search_requests ?? 0) * modelCosts.webSearchRequests;
-}
-function getModelCosts(model, usage) {
- const shortName = getCanonicalName(model);
- if (shortName === firstPartyNameToCanonical(CLAUDE_OPUS_4_6_CONFIG.firstParty)) {
- const isFastMode = usage.speed === "fast";
- return getOpus46CostTier(isFastMode);
- }
- const costs = MODEL_COSTS[shortName];
- if (!costs) {
- trackUnknownModelCost(model, shortName);
- return MODEL_COSTS[getCanonicalName(getDefaultMainLoopModelSetting())] ?? DEFAULT_UNKNOWN_MODEL_COST;
- }
- return costs;
-}
-function trackUnknownModelCost(model, shortName) {
- logEvent("tengu_unknown_model_cost", {
- model,
- shortName
- });
- setHasUnknownModelCost();
-}
-function calculateUSDCost(resolvedModel, usage) {
- const modelCosts = getModelCosts(resolvedModel, usage);
- return tokensToUSDCost(modelCosts, usage);
-}
-function formatPrice(price) {
- if (Number.isInteger(price)) {
- return `$${price}`;
- }
- return `$${price.toFixed(2)}`;
-}
-function formatModelPricing(costs) {
- return `${formatPrice(costs.inputTokens)}/${formatPrice(costs.outputTokens)} per Mtok`;
-}
-var COST_TIER_3_15, COST_TIER_15_75, COST_TIER_5_25, COST_TIER_30_150, COST_HAIKU_35, COST_HAIKU_45, DEFAULT_UNKNOWN_MODEL_COST, MODEL_COSTS;
-var init_modelCost = __esm(() => {
- init_analytics();
- init_state();
- init_fastMode();
- init_configs();
- init_model();
- COST_TIER_3_15 = {
- inputTokens: 3,
- outputTokens: 15,
- promptCacheWriteTokens: 3.75,
- promptCacheReadTokens: 0.3,
- webSearchRequests: 0.01
- };
- COST_TIER_15_75 = {
- inputTokens: 15,
- outputTokens: 75,
- promptCacheWriteTokens: 18.75,
- promptCacheReadTokens: 1.5,
- webSearchRequests: 0.01
- };
- COST_TIER_5_25 = {
- inputTokens: 5,
- outputTokens: 25,
- promptCacheWriteTokens: 6.25,
- promptCacheReadTokens: 0.5,
- webSearchRequests: 0.01
- };
- COST_TIER_30_150 = {
- inputTokens: 30,
- outputTokens: 150,
- promptCacheWriteTokens: 37.5,
- promptCacheReadTokens: 3,
- webSearchRequests: 0.01
- };
- COST_HAIKU_35 = {
- inputTokens: 0.8,
- outputTokens: 4,
- promptCacheWriteTokens: 1,
- promptCacheReadTokens: 0.08,
- webSearchRequests: 0.01
- };
- COST_HAIKU_45 = {
- inputTokens: 1,
- outputTokens: 5,
- promptCacheWriteTokens: 1.25,
- promptCacheReadTokens: 0.1,
- webSearchRequests: 0.01
- };
- DEFAULT_UNKNOWN_MODEL_COST = COST_TIER_5_25;
- MODEL_COSTS = {
- [firstPartyNameToCanonical(CLAUDE_3_5_HAIKU_CONFIG.firstParty)]: COST_HAIKU_35,
- [firstPartyNameToCanonical(CLAUDE_HAIKU_4_5_CONFIG.firstParty)]: COST_HAIKU_45,
- [firstPartyNameToCanonical(CLAUDE_3_5_V2_SONNET_CONFIG.firstParty)]: COST_TIER_3_15,
- [firstPartyNameToCanonical(CLAUDE_3_7_SONNET_CONFIG.firstParty)]: COST_TIER_3_15,
- [firstPartyNameToCanonical(CLAUDE_SONNET_4_CONFIG.firstParty)]: COST_TIER_3_15,
- [firstPartyNameToCanonical(CLAUDE_SONNET_4_5_CONFIG.firstParty)]: COST_TIER_3_15,
- [firstPartyNameToCanonical(CLAUDE_SONNET_4_6_CONFIG.firstParty)]: COST_TIER_3_15,
- [firstPartyNameToCanonical(CLAUDE_OPUS_4_CONFIG.firstParty)]: COST_TIER_15_75,
- [firstPartyNameToCanonical(CLAUDE_OPUS_4_1_CONFIG.firstParty)]: COST_TIER_15_75,
- [firstPartyNameToCanonical(CLAUDE_OPUS_4_5_CONFIG.firstParty)]: COST_TIER_5_25,
- [firstPartyNameToCanonical(CLAUDE_OPUS_4_6_CONFIG.firstParty)]: COST_TIER_5_25
- };
-});
-
-// src/utils/model/aliases.ts
-function isModelAlias(modelInput) {
- return MODEL_ALIASES.includes(modelInput);
-}
-function isModelFamilyAlias(model) {
- return MODEL_FAMILY_ALIASES.includes(model);
-}
-var MODEL_ALIASES, MODEL_FAMILY_ALIASES;
-var init_aliases = __esm(() => {
- MODEL_ALIASES = [
- "sonnet",
- "opus",
- "haiku",
- "best",
- "sonnet[1m]",
- "opus[1m]",
- "opusplan"
- ];
- MODEL_FAMILY_ALIASES = ["sonnet", "opus", "haiku"];
-});
-
-// src/utils/model/modelAllowlist.ts
-function modelBelongsToFamily(model, family) {
- if (model.includes(family)) {
- return true;
- }
- if (isModelAlias(model)) {
- const resolved = parseUserSpecifiedModel(model).toLowerCase();
- return resolved.includes(family);
- }
- return false;
-}
-function prefixMatchesModel(modelName, prefix) {
- if (!modelName.startsWith(prefix)) {
- return false;
- }
- return modelName.length === prefix.length || modelName[prefix.length] === "-";
-}
-function modelMatchesVersionPrefix(model, entry) {
- const resolvedModel = isModelAlias(model) ? parseUserSpecifiedModel(model).toLowerCase() : model;
- if (prefixMatchesModel(resolvedModel, entry)) {
- return true;
- }
- if (!entry.startsWith("claude-") && prefixMatchesModel(resolvedModel, `claude-${entry}`)) {
- return true;
- }
- return false;
-}
-function familyHasSpecificEntries(family, allowlist) {
- for (const entry of allowlist) {
- if (isModelFamilyAlias(entry)) {
- continue;
- }
- const idx = entry.indexOf(family);
- if (idx === -1) {
- continue;
- }
- const afterFamily = idx + family.length;
- if (afterFamily === entry.length || entry[afterFamily] === "-") {
- return true;
- }
- }
- return false;
-}
-function isModelAllowed(model) {
- const settings = getSettings_DEPRECATED() || {};
- const { availableModels } = settings;
- if (!availableModels) {
- return true;
- }
- if (availableModels.length === 0) {
- return false;
- }
- const resolvedModel = resolveOverriddenModel(model);
- const normalizedModel = resolvedModel.trim().toLowerCase();
- const normalizedAllowlist = availableModels.map((m4) => m4.trim().toLowerCase());
- if (normalizedAllowlist.includes(normalizedModel)) {
- if (!isModelFamilyAlias(normalizedModel) || !familyHasSpecificEntries(normalizedModel, normalizedAllowlist)) {
- return true;
- }
- }
- for (const entry of normalizedAllowlist) {
- if (isModelFamilyAlias(entry) && !familyHasSpecificEntries(entry, normalizedAllowlist) && modelBelongsToFamily(normalizedModel, entry)) {
- return true;
- }
- }
- if (isModelAlias(normalizedModel)) {
- const resolved = parseUserSpecifiedModel(normalizedModel).toLowerCase();
- if (normalizedAllowlist.includes(resolved)) {
- return true;
- }
- }
- for (const entry of normalizedAllowlist) {
- if (!isModelFamilyAlias(entry) && isModelAlias(entry)) {
- const resolved = parseUserSpecifiedModel(entry).toLowerCase();
- if (resolved === normalizedModel) {
- return true;
- }
- }
- }
- for (const entry of normalizedAllowlist) {
- if (!isModelFamilyAlias(entry) && !isModelAlias(entry)) {
- if (modelMatchesVersionPrefix(normalizedModel, entry)) {
- return true;
- }
- }
- }
- return false;
-}
-var init_modelAllowlist = __esm(() => {
- init_settings2();
- init_aliases();
- init_model();
- init_modelStrings();
-});
-
-// src/utils/model/model.ts
-var exports_model = {};
-__export(exports_model, {
- resolveSkillModelOverride: () => resolveSkillModelOverride,
- renderModelSetting: () => renderModelSetting,
- renderModelName: () => renderModelName,
- renderDefaultModelSetting: () => renderDefaultModelSetting,
- parseUserSpecifiedModel: () => parseUserSpecifiedModel,
- normalizeModelStringForAPI: () => normalizeModelStringForAPI,
- modelDisplayString: () => modelDisplayString,
- isOpus1mMergeEnabled: () => isOpus1mMergeEnabled,
- isNonCustomOpusModel: () => isNonCustomOpusModel,
- isLegacyModelRemapEnabled: () => isLegacyModelRemapEnabled,
- getUserSpecifiedModelSetting: () => getUserSpecifiedModelSetting,
- getSmallFastModel: () => getSmallFastModel,
- getRuntimeMainLoopModel: () => getRuntimeMainLoopModel,
- getPublicModelName: () => getPublicModelName,
- getPublicModelDisplayName: () => getPublicModelDisplayName,
- getOpus46PricingSuffix: () => getOpus46PricingSuffix,
- getMarketingNameForModel: () => getMarketingNameForModel,
- getMainLoopModel: () => getMainLoopModel,
- getDefaultSonnetModel: () => getDefaultSonnetModel,
- getDefaultOpusModel: () => getDefaultOpusModel,
- getDefaultMainLoopModelSetting: () => getDefaultMainLoopModelSetting,
- getDefaultMainLoopModel: () => getDefaultMainLoopModel,
- getDefaultHaikuModel: () => getDefaultHaikuModel,
- getClaudeAiUserDefaultModelDescription: () => getClaudeAiUserDefaultModelDescription,
- getCanonicalName: () => getCanonicalName,
- getBestModel: () => getBestModel,
- firstPartyNameToCanonical: () => firstPartyNameToCanonical
-});
-function getSmallFastModel() {
- return process.env.ANTHROPIC_SMALL_FAST_MODEL || getDefaultHaikuModel();
-}
-function isNonCustomOpusModel(model) {
- return model === getModelStrings2().opus40 || model === getModelStrings2().opus41 || model === getModelStrings2().opus45 || model === getModelStrings2().opus46;
-}
-function getUserSpecifiedModelSetting() {
- let specifiedModel;
- const modelOverride = getMainLoopModelOverride();
- if (modelOverride !== undefined) {
- specifiedModel = modelOverride;
- } else {
- const settings = getSettings_DEPRECATED() || {};
- specifiedModel = process.env.ANTHROPIC_MODEL || settings.model || undefined;
- }
- if (specifiedModel && !isModelAllowed(specifiedModel)) {
- return;
- }
- return specifiedModel;
-}
-function getMainLoopModel() {
- const model = getUserSpecifiedModelSetting();
- if (model !== undefined && model !== null) {
- return parseUserSpecifiedModel(model);
- }
- return getDefaultMainLoopModel();
-}
-function getBestModel() {
- return getDefaultOpusModel();
-}
-function getDefaultOpusModel() {
- if (process.env.ANTHROPIC_DEFAULT_OPUS_MODEL) {
- return process.env.ANTHROPIC_DEFAULT_OPUS_MODEL;
- }
- if (getAPIProvider() !== "firstParty") {
- return getModelStrings2().opus46;
- }
- return getModelStrings2().opus46;
-}
-function getDefaultSonnetModel() {
- if (process.env.ANTHROPIC_DEFAULT_SONNET_MODEL) {
- return process.env.ANTHROPIC_DEFAULT_SONNET_MODEL;
- }
- if (getAPIProvider() !== "firstParty") {
- return getModelStrings2().sonnet45;
- }
- return getModelStrings2().sonnet46;
-}
-function getDefaultHaikuModel() {
- if (process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL) {
- return process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL;
- }
- return getModelStrings2().haiku45;
-}
-function getRuntimeMainLoopModel(params) {
- const { permissionMode, mainLoopModel, exceeds200kTokens = false } = params;
- if (getUserSpecifiedModelSetting() === "opusplan" && permissionMode === "plan" && !exceeds200kTokens) {
- return getDefaultOpusModel();
- }
- if (getUserSpecifiedModelSetting() === "haiku" && permissionMode === "plan") {
- return getDefaultSonnetModel();
- }
- return mainLoopModel;
-}
-function getDefaultMainLoopModelSetting() {
- if (process.env.USER_TYPE === "ant") {
- return getAntModelOverrideConfig()?.defaultModel ?? getDefaultOpusModel() + "[1m]";
- }
- if (isMaxSubscriber()) {
- return getDefaultOpusModel() + (isOpus1mMergeEnabled() ? "[1m]" : "");
- }
- if (isTeamPremiumSubscriber()) {
- return getDefaultOpusModel() + (isOpus1mMergeEnabled() ? "[1m]" : "");
- }
- return getDefaultSonnetModel();
-}
-function getDefaultMainLoopModel() {
- return parseUserSpecifiedModel(getDefaultMainLoopModelSetting());
-}
-function firstPartyNameToCanonical(name) {
- name = name.toLowerCase();
- if (name.includes("claude-opus-4-6")) {
- return "claude-opus-4-6";
- }
- if (name.includes("claude-opus-4-5")) {
- return "claude-opus-4-5";
- }
- if (name.includes("claude-opus-4-1")) {
- return "claude-opus-4-1";
- }
- if (name.includes("claude-opus-4")) {
- return "claude-opus-4";
- }
- if (name.includes("claude-sonnet-4-6")) {
- return "claude-sonnet-4-6";
- }
- if (name.includes("claude-sonnet-4-5")) {
- return "claude-sonnet-4-5";
- }
- if (name.includes("claude-sonnet-4")) {
- return "claude-sonnet-4";
- }
- if (name.includes("claude-haiku-4-5")) {
- return "claude-haiku-4-5";
- }
- if (name.includes("claude-3-7-sonnet")) {
- return "claude-3-7-sonnet";
- }
- if (name.includes("claude-3-5-sonnet")) {
- return "claude-3-5-sonnet";
- }
- if (name.includes("claude-3-5-haiku")) {
- return "claude-3-5-haiku";
- }
- if (name.includes("claude-3-opus")) {
- return "claude-3-opus";
- }
- if (name.includes("claude-3-sonnet")) {
- return "claude-3-sonnet";
- }
- if (name.includes("claude-3-haiku")) {
- return "claude-3-haiku";
- }
- const match = name.match(/(claude-(\d+-\d+-)?\w+)/);
- if (match && match[1]) {
- return match[1];
- }
- return name;
-}
-function getCanonicalName(fullModelName) {
- return firstPartyNameToCanonical(resolveOverriddenModel(fullModelName));
-}
-function getClaudeAiUserDefaultModelDescription(fastMode = false) {
- if (isMaxSubscriber() || isTeamPremiumSubscriber()) {
- if (isOpus1mMergeEnabled()) {
- return `Opus 4.6 with 1M context \xB7 Most capable for complex work${fastMode ? getOpus46PricingSuffix(true) : ""}`;
- }
- return `Opus 4.6 \xB7 Most capable for complex work${fastMode ? getOpus46PricingSuffix(true) : ""}`;
- }
- return "Sonnet 4.6 \xB7 Best for everyday tasks";
-}
-function renderDefaultModelSetting(setting) {
- if (setting === "opusplan") {
- return "Opus 4.6 in plan mode, else Sonnet 4.6";
- }
- return renderModelName(parseUserSpecifiedModel(setting));
-}
-function getOpus46PricingSuffix(fastMode) {
- if (getAPIProvider() !== "firstParty")
- return "";
- const pricing = formatModelPricing(getOpus46CostTier(fastMode));
- const fastModeIndicator = fastMode ? ` (${LIGHTNING_BOLT})` : "";
- return ` \xB7${fastModeIndicator} ${pricing}`;
-}
-function isOpus1mMergeEnabled() {
- if (is1mContextDisabled() || isProSubscriber() || getAPIProvider() !== "firstParty") {
- return false;
- }
- if (isClaudeAISubscriber() && getSubscriptionType() === null) {
- return false;
- }
- return true;
-}
-function renderModelSetting(setting) {
- if (setting === "opusplan") {
- return "Opus Plan";
- }
- if (isModelAlias(setting)) {
- return capitalize(setting);
- }
- return renderModelName(setting);
-}
-function getPublicModelDisplayName(model) {
- switch (model) {
- case getModelStrings2().opus46:
- return "Opus 4.6";
- case getModelStrings2().opus46 + "[1m]":
- return "Opus 4.6 (1M context)";
- case getModelStrings2().opus45:
- return "Opus 4.5";
- case getModelStrings2().opus41:
- return "Opus 4.1";
- case getModelStrings2().opus40:
- return "Opus 4";
- case getModelStrings2().sonnet46 + "[1m]":
- return "Sonnet 4.6 (1M context)";
- case getModelStrings2().sonnet46:
- return "Sonnet 4.6";
- case getModelStrings2().sonnet45 + "[1m]":
- return "Sonnet 4.5 (1M context)";
- case getModelStrings2().sonnet45:
- return "Sonnet 4.5";
- case getModelStrings2().sonnet40:
- return "Sonnet 4";
- case getModelStrings2().sonnet40 + "[1m]":
- return "Sonnet 4 (1M context)";
- case getModelStrings2().sonnet37:
- return "Sonnet 3.7";
- case getModelStrings2().sonnet35:
- return "Sonnet 3.5";
- case getModelStrings2().haiku45:
- return "Haiku 4.5";
- case getModelStrings2().haiku35:
- return "Haiku 3.5";
- default:
- return null;
- }
-}
-function maskModelCodename(baseName) {
- const [codename = "", ...rest] = baseName.split("-");
- const masked = codename.slice(0, 3) + "*".repeat(Math.max(0, codename.length - 3));
- return [masked, ...rest].join("-");
-}
-function renderModelName(model) {
- const publicName = getPublicModelDisplayName(model);
- if (publicName) {
- return publicName;
- }
- if (process.env.USER_TYPE === "ant") {
- const resolved = parseUserSpecifiedModel(model);
- const antModel = resolveAntModel(model);
- if (antModel) {
- const baseName = antModel.model.replace(/\[1m\]$/i, "");
- const masked = maskModelCodename(baseName);
- const suffix = has1mContext(resolved) ? "[1m]" : "";
- return masked + suffix;
- }
- if (resolved !== model) {
- return `${model} (${resolved})`;
- }
- return resolved;
- }
- return model;
-}
-function getPublicModelName(model) {
- const publicName = getPublicModelDisplayName(model);
- if (publicName) {
- return `Claude ${publicName}`;
- }
- return `Claude (${model})`;
-}
-function parseUserSpecifiedModel(modelInput) {
- const modelInputTrimmed = modelInput.trim();
- const normalizedModel = modelInputTrimmed.toLowerCase();
- const has1mTag = has1mContext(normalizedModel);
- const modelString = has1mTag ? normalizedModel.replace(/\[1m]$/i, "").trim() : normalizedModel;
- if (isModelAlias(modelString)) {
- switch (modelString) {
- case "opusplan":
- return getDefaultSonnetModel() + (has1mTag ? "[1m]" : "");
- case "sonnet":
- return getDefaultSonnetModel() + (has1mTag ? "[1m]" : "");
- case "haiku":
- return getDefaultHaikuModel() + (has1mTag ? "[1m]" : "");
- case "opus":
- return getDefaultOpusModel() + (has1mTag ? "[1m]" : "");
- case "best":
- return getBestModel();
- default:
- }
- }
- if (getAPIProvider() === "firstParty" && isLegacyOpusFirstParty(modelString) && isLegacyModelRemapEnabled()) {
- return getDefaultOpusModel() + (has1mTag ? "[1m]" : "");
- }
- if (process.env.USER_TYPE === "ant") {
- const has1mAntTag = has1mContext(normalizedModel);
- const baseAntModel = normalizedModel.replace(/\[1m]$/i, "").trim();
- const antModel = resolveAntModel(baseAntModel);
- if (antModel) {
- const suffix = has1mAntTag ? "[1m]" : "";
- return antModel.model + suffix;
- }
- }
- if (has1mTag) {
- return modelInputTrimmed.replace(/\[1m\]$/i, "").trim() + "[1m]";
- }
- return modelInputTrimmed;
-}
-function resolveSkillModelOverride(skillModel, currentModel) {
- if (has1mContext(skillModel) || !has1mContext(currentModel)) {
- return skillModel;
- }
- if (modelSupports1M(parseUserSpecifiedModel(skillModel))) {
- return skillModel + "[1m]";
- }
- return skillModel;
-}
-function isLegacyOpusFirstParty(model) {
- return LEGACY_OPUS_FIRSTPARTY.includes(model);
-}
-function isLegacyModelRemapEnabled() {
- return !isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP);
-}
-function modelDisplayString(model) {
- if (model === null) {
- if (process.env.USER_TYPE === "ant") {
- return `Default for Ants (${renderDefaultModelSetting(getDefaultMainLoopModelSetting())})`;
- } else if (isClaudeAISubscriber()) {
- return `Default (${getClaudeAiUserDefaultModelDescription()})`;
- }
- return `Default (${getDefaultMainLoopModel()})`;
- }
- const resolvedModel = parseUserSpecifiedModel(model);
- return model === resolvedModel ? resolvedModel : `${model} (${resolvedModel})`;
-}
-function getMarketingNameForModel(modelId) {
- if (getAPIProvider() === "foundry") {
- return;
- }
- const has1m = modelId.toLowerCase().includes("[1m]");
- const canonical = getCanonicalName(modelId);
- if (canonical.includes("claude-opus-4-6")) {
- return has1m ? "Opus 4.6 (with 1M context)" : "Opus 4.6";
- }
- if (canonical.includes("claude-opus-4-5")) {
- return "Opus 4.5";
- }
- if (canonical.includes("claude-opus-4-1")) {
- return "Opus 4.1";
- }
- if (canonical.includes("claude-opus-4")) {
- return "Opus 4";
- }
- if (canonical.includes("claude-sonnet-4-6")) {
- return has1m ? "Sonnet 4.6 (with 1M context)" : "Sonnet 4.6";
- }
- if (canonical.includes("claude-sonnet-4-5")) {
- return has1m ? "Sonnet 4.5 (with 1M context)" : "Sonnet 4.5";
- }
- if (canonical.includes("claude-sonnet-4")) {
- return has1m ? "Sonnet 4 (with 1M context)" : "Sonnet 4";
- }
- if (canonical.includes("claude-3-7-sonnet")) {
- return "Claude 3.7 Sonnet";
- }
- if (canonical.includes("claude-3-5-sonnet")) {
- return "Claude 3.5 Sonnet";
- }
- if (canonical.includes("claude-haiku-4-5")) {
- return "Haiku 4.5";
- }
- if (canonical.includes("claude-3-5-haiku")) {
- return "Claude 3.5 Haiku";
- }
- return;
-}
-function normalizeModelStringForAPI(model) {
- return model.replace(/\[(1|2)m\]/gi, "");
-}
-var LEGACY_OPUS_FIRSTPARTY;
-var init_model = __esm(() => {
- init_state();
- init_auth14();
- init_context();
- init_envUtils();
- init_modelStrings();
- init_modelCost();
- init_settings2();
- init_providers();
- init_figures2();
- init_modelAllowlist();
- init_aliases();
- init_stringUtils();
- LEGACY_OPUS_FIRSTPARTY = [
- "claude-opus-4-20250514",
- "claude-opus-4-1-20250805",
- "claude-opus-4-0",
- "claude-opus-4-1"
- ];
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/tslib.mjs
-function __classPrivateFieldSet6(receiver, state, value, kind2, f4) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a setter");
- if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return kind2 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
-}
-function __classPrivateFieldGet6(receiver, state, kind2, f4) {
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a getter");
- if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind2 === "m" ? f4 : kind2 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver);
-}
-var init_tslib = () => {};
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs
-var uuid43 = function() {
- const { crypto: crypto7 } = globalThis;
- if (crypto7?.randomUUID) {
- uuid43 = crypto7.randomUUID.bind(crypto7);
- return crypto7.randomUUID();
- }
- const u8 = new Uint8Array(1);
- const randomByte = crypto7 ? () => crypto7.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
- return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c8) => (+c8 ^ randomByte() & 15 >> +c8 / 4).toString(16));
-};
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/errors.mjs
-function isAbortError3(err) {
- return typeof err === "object" && err !== null && (("name" in err) && err.name === "AbortError" || ("message" in err) && String(err.message).includes("FetchRequestCanceledException"));
-}
-var castToError2 = (err) => {
- if (err instanceof Error)
- return err;
- if (typeof err === "object" && err !== null) {
- try {
- if (Object.prototype.toString.call(err) === "[object Error]") {
- const error40 = new Error(err.message, err.cause ? { cause: err.cause } : {});
- if (err.stack)
- error40.stack = err.stack;
- if (err.cause && !error40.cause)
- error40.cause = err.cause;
- if (err.name)
- error40.name = err.name;
- return error40;
- }
- } catch {}
- try {
- return new Error(JSON.stringify(err));
- } catch {}
- }
- return new Error(err);
-};
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/core/error.mjs
-var AnthropicError2, APIError2, APIUserAbortError2, APIConnectionError2, APIConnectionTimeoutError2, BadRequestError2, AuthenticationError2, PermissionDeniedError2, NotFoundError2, ConflictError2, UnprocessableEntityError2, RateLimitError2, InternalServerError2;
-var init_error3 = __esm(() => {
- AnthropicError2 = class AnthropicError2 extends Error {
- };
- APIError2 = class APIError2 extends AnthropicError2 {
- constructor(status, error40, message, headers) {
- super(`${APIError2.makeMessage(status, error40, message)}`);
- this.status = status;
- this.headers = headers;
- this.requestID = headers?.get("request-id");
- this.error = error40;
- }
- static makeMessage(status, error40, message) {
- const msg = error40?.message ? typeof error40.message === "string" ? error40.message : JSON.stringify(error40.message) : error40 ? JSON.stringify(error40) : message;
- if (status && msg) {
- return `${status} ${msg}`;
- }
- if (status) {
- return `${status} status code (no body)`;
- }
- if (msg) {
- return msg;
- }
- return "(no status code or body)";
- }
- static generate(status, errorResponse, message, headers) {
- if (!status || !headers) {
- return new APIConnectionError2({ message, cause: castToError2(errorResponse) });
- }
- const error40 = errorResponse;
- if (status === 400) {
- return new BadRequestError2(status, error40, message, headers);
- }
- if (status === 401) {
- return new AuthenticationError2(status, error40, message, headers);
- }
- if (status === 403) {
- return new PermissionDeniedError2(status, error40, message, headers);
- }
- if (status === 404) {
- return new NotFoundError2(status, error40, message, headers);
- }
- if (status === 409) {
- return new ConflictError2(status, error40, message, headers);
- }
- if (status === 422) {
- return new UnprocessableEntityError2(status, error40, message, headers);
- }
- if (status === 429) {
- return new RateLimitError2(status, error40, message, headers);
- }
- if (status >= 500) {
- return new InternalServerError2(status, error40, message, headers);
- }
- return new APIError2(status, error40, message, headers);
- }
- };
- APIUserAbortError2 = class APIUserAbortError2 extends APIError2 {
- constructor({ message } = {}) {
- super(undefined, undefined, message || "Request was aborted.", undefined);
- }
- };
- APIConnectionError2 = class APIConnectionError2 extends APIError2 {
- constructor({ message, cause }) {
- super(undefined, undefined, message || "Connection error.", undefined);
- if (cause)
- this.cause = cause;
- }
- };
- APIConnectionTimeoutError2 = class APIConnectionTimeoutError2 extends APIConnectionError2 {
- constructor({ message } = {}) {
- super({ message: message ?? "Request timed out." });
- }
- };
- BadRequestError2 = class BadRequestError2 extends APIError2 {
- };
- AuthenticationError2 = class AuthenticationError2 extends APIError2 {
- };
- PermissionDeniedError2 = class PermissionDeniedError2 extends APIError2 {
- };
- NotFoundError2 = class NotFoundError2 extends APIError2 {
- };
- ConflictError2 = class ConflictError2 extends APIError2 {
- };
- UnprocessableEntityError2 = class UnprocessableEntityError2 extends APIError2 {
- };
- RateLimitError2 = class RateLimitError2 extends APIError2 {
- };
- InternalServerError2 = class InternalServerError2 extends APIError2 {
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs
-function maybeObj(x3) {
- if (typeof x3 !== "object") {
- return {};
- }
- return x3 ?? {};
-}
-function isEmptyObj2(obj) {
- if (!obj)
- return true;
- for (const _k3 in obj)
- return false;
- return true;
-}
-function hasOwn2(obj, key) {
- return Object.prototype.hasOwnProperty.call(obj, key);
-}
-var startsWithSchemeRegexp2, isAbsoluteURL3 = (url3) => {
- return startsWithSchemeRegexp2.test(url3);
-}, isArray3 = (val) => (isArray3 = Array.isArray, isArray3(val)), isReadonlyArray, validatePositiveInteger2 = (name, n5) => {
- if (typeof n5 !== "number" || !Number.isInteger(n5)) {
- throw new AnthropicError2(`${name} must be an integer`);
- }
- if (n5 < 0) {
- throw new AnthropicError2(`${name} must be a positive integer`);
- }
- return n5;
-}, safeJSON2 = (text) => {
- try {
- return JSON.parse(text);
- } catch (err) {
- return;
- }
-};
-var init_values2 = __esm(() => {
- init_error3();
- startsWithSchemeRegexp2 = /^[a-z][a-z0-9+.-]*:/i;
- isReadonlyArray = isArray3;
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs
-var sleep2 = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/version.mjs
-var VERSION4 = "0.80.0";
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs
-function getDetectedPlatform() {
- if (typeof Deno !== "undefined" && Deno.build != null) {
- return "deno";
- }
- if (typeof EdgeRuntime !== "undefined") {
- return "edge";
- }
- if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
- return "node";
- }
- return "unknown";
-}
-function getBrowserInfo2() {
- if (typeof navigator === "undefined" || !navigator) {
- return null;
- }
- const browserPatterns = [
- { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
- ];
- for (const { key, pattern } of browserPatterns) {
- const match = pattern.exec(navigator.userAgent);
- if (match) {
- const major = match[1] || 0;
- const minor = match[2] || 0;
- const patch = match[3] || 0;
- return { browser: key, version: `${major}.${minor}.${patch}` };
- }
- }
- return null;
-}
-var isRunningInBrowser2 = () => {
- return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined";
-}, getPlatformProperties2 = () => {
- const detectedPlatform = getDetectedPlatform();
- if (detectedPlatform === "deno") {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION4,
- "X-Stainless-OS": normalizePlatform2(Deno.build.os),
- "X-Stainless-Arch": normalizeArch2(Deno.build.arch),
- "X-Stainless-Runtime": "deno",
- "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
- };
- }
- if (typeof EdgeRuntime !== "undefined") {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION4,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": `other:${EdgeRuntime}`,
- "X-Stainless-Runtime": "edge",
- "X-Stainless-Runtime-Version": globalThis.process.version
- };
- }
- if (detectedPlatform === "node") {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION4,
- "X-Stainless-OS": normalizePlatform2(globalThis.process.platform ?? "unknown"),
- "X-Stainless-Arch": normalizeArch2(globalThis.process.arch ?? "unknown"),
- "X-Stainless-Runtime": "node",
- "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
- };
- }
- const browserInfo = getBrowserInfo2();
- if (browserInfo) {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION4,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": "unknown",
- "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
- "X-Stainless-Runtime-Version": browserInfo.version
- };
- }
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION4,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": "unknown",
- "X-Stainless-Runtime": "unknown",
- "X-Stainless-Runtime-Version": "unknown"
- };
-}, normalizeArch2 = (arch) => {
- if (arch === "x32")
- return "x32";
- if (arch === "x86_64" || arch === "x64")
- return "x64";
- if (arch === "arm")
- return "arm";
- if (arch === "aarch64" || arch === "arm64")
- return "arm64";
- if (arch)
- return `other:${arch}`;
- return "unknown";
-}, normalizePlatform2 = (platform2) => {
- platform2 = platform2.toLowerCase();
- if (platform2.includes("ios"))
- return "iOS";
- if (platform2 === "android")
- return "Android";
- if (platform2 === "darwin")
- return "MacOS";
- if (platform2 === "win32")
- return "Windows";
- if (platform2 === "freebsd")
- return "FreeBSD";
- if (platform2 === "openbsd")
- return "OpenBSD";
- if (platform2 === "linux")
- return "Linux";
- if (platform2)
- return `Other:${platform2}`;
- return "Unknown";
-}, _platformHeaders2, getPlatformHeaders2 = () => {
- return _platformHeaders2 ?? (_platformHeaders2 = getPlatformProperties2());
-};
-var init_detect_platform = () => {};
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/shims.mjs
-function getDefaultFetch() {
- if (typeof fetch !== "undefined") {
- return fetch;
- }
- throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
-}
-function makeReadableStream(...args) {
- const ReadableStream4 = globalThis.ReadableStream;
- if (typeof ReadableStream4 === "undefined") {
- throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
- }
- return new ReadableStream4(...args);
-}
-function ReadableStreamFrom(iterable) {
- let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
- return makeReadableStream({
- start() {},
- async pull(controller) {
- const { done, value } = await iter.next();
- if (done) {
- controller.close();
- } else {
- controller.enqueue(value);
- }
- },
- async cancel() {
- await iter.return?.();
- }
- });
-}
-function ReadableStreamToAsyncIterable2(stream8) {
- if (stream8[Symbol.asyncIterator])
- return stream8;
- const reader = stream8.getReader();
- return {
- async next() {
- try {
- const result = await reader.read();
- if (result?.done)
- reader.releaseLock();
- return result;
- } catch (e4) {
- reader.releaseLock();
- throw e4;
- }
- },
- async return() {
- const cancelPromise = reader.cancel();
- reader.releaseLock();
- await cancelPromise;
- return { done: true, value: undefined };
- },
- [Symbol.asyncIterator]() {
- return this;
- }
- };
-}
-async function CancelReadableStream(stream8) {
- if (stream8 === null || typeof stream8 !== "object")
- return;
- if (stream8[Symbol.asyncIterator]) {
- await stream8[Symbol.asyncIterator]().return?.();
- return;
- }
- const reader = stream8.getReader();
- const cancelPromise = reader.cancel();
- reader.releaseLock();
- await cancelPromise;
-}
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/request-options.mjs
-var FallbackEncoder = ({ headers, body }) => {
- return {
- bodyHeaders: {
- "content-type": "application/json"
- },
- body: JSON.stringify(body)
- };
-};
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs
-function stringifyQuery(query) {
- return Object.entries(query).filter(([_, value]) => typeof value !== "undefined").map(([key, value]) => {
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
- }
- if (value === null) {
- return `${encodeURIComponent(key)}=`;
- }
- throw new AnthropicError2(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
- }).join("&");
-}
-var init_query = __esm(() => {
- init_error3();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs
-function concatBytes(buffers) {
- let length = 0;
- for (const buffer of buffers) {
- length += buffer.length;
- }
- const output = new Uint8Array(length);
- let index2 = 0;
- for (const buffer of buffers) {
- output.set(buffer, index2);
- index2 += buffer.length;
- }
- return output;
-}
-function encodeUTF8(str) {
- let encoder;
- return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder, encodeUTF8_ = encoder.encode.bind(encoder)))(str);
-}
-function decodeUTF8(bytes) {
- let decoder;
- return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder, decodeUTF8_ = decoder.decode.bind(decoder)))(bytes);
-}
-var encodeUTF8_, decodeUTF8_;
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs
-class LineDecoder2 {
- constructor() {
- _LineDecoder_buffer.set(this, undefined);
- _LineDecoder_carriageReturnIndex2.set(this, undefined);
- __classPrivateFieldSet6(this, _LineDecoder_buffer, new Uint8Array, "f");
- __classPrivateFieldSet6(this, _LineDecoder_carriageReturnIndex2, null, "f");
- }
- decode(chunk) {
- if (chunk == null) {
- return [];
- }
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
- __classPrivateFieldSet6(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet6(this, _LineDecoder_buffer, "f"), binaryChunk]), "f");
- const lines = [];
- let patternIndex;
- while ((patternIndex = findNewlineIndex2(__classPrivateFieldGet6(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet6(this, _LineDecoder_carriageReturnIndex2, "f"))) != null) {
- if (patternIndex.carriage && __classPrivateFieldGet6(this, _LineDecoder_carriageReturnIndex2, "f") == null) {
- __classPrivateFieldSet6(this, _LineDecoder_carriageReturnIndex2, patternIndex.index, "f");
- continue;
- }
- if (__classPrivateFieldGet6(this, _LineDecoder_carriageReturnIndex2, "f") != null && (patternIndex.index !== __classPrivateFieldGet6(this, _LineDecoder_carriageReturnIndex2, "f") + 1 || patternIndex.carriage)) {
- lines.push(decodeUTF8(__classPrivateFieldGet6(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet6(this, _LineDecoder_carriageReturnIndex2, "f") - 1)));
- __classPrivateFieldSet6(this, _LineDecoder_buffer, __classPrivateFieldGet6(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet6(this, _LineDecoder_carriageReturnIndex2, "f")), "f");
- __classPrivateFieldSet6(this, _LineDecoder_carriageReturnIndex2, null, "f");
- continue;
- }
- const endIndex = __classPrivateFieldGet6(this, _LineDecoder_carriageReturnIndex2, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
- const line = decodeUTF8(__classPrivateFieldGet6(this, _LineDecoder_buffer, "f").subarray(0, endIndex));
- lines.push(line);
- __classPrivateFieldSet6(this, _LineDecoder_buffer, __classPrivateFieldGet6(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f");
- __classPrivateFieldSet6(this, _LineDecoder_carriageReturnIndex2, null, "f");
- }
- return lines;
- }
- flush() {
- if (!__classPrivateFieldGet6(this, _LineDecoder_buffer, "f").length) {
- return [];
- }
- return this.decode(`
-`);
- }
-}
-function findNewlineIndex2(buffer, startIndex) {
- const newline2 = 10;
- const carriage = 13;
- for (let i5 = startIndex ?? 0;i5 < buffer.length; i5++) {
- if (buffer[i5] === newline2) {
- return { preceding: i5, index: i5 + 1, carriage: false };
- }
- if (buffer[i5] === carriage) {
- return { preceding: i5, index: i5 + 1, carriage: true };
- }
- }
- return null;
-}
-function findDoubleNewlineIndex2(buffer) {
- const newline2 = 10;
- const carriage = 13;
- for (let i5 = 0;i5 < buffer.length - 1; i5++) {
- if (buffer[i5] === newline2 && buffer[i5 + 1] === newline2) {
- return i5 + 2;
- }
- if (buffer[i5] === carriage && buffer[i5 + 1] === carriage) {
- return i5 + 2;
- }
- if (buffer[i5] === carriage && buffer[i5 + 1] === newline2 && i5 + 3 < buffer.length && buffer[i5 + 2] === carriage && buffer[i5 + 3] === newline2) {
- return i5 + 4;
- }
- }
- return -1;
-}
-var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex2;
-var init_line2 = __esm(() => {
- init_tslib();
- _LineDecoder_buffer = new WeakMap, _LineDecoder_carriageReturnIndex2 = new WeakMap;
- LineDecoder2.NEWLINE_CHARS = new Set([`
-`, "\r"]);
- LineDecoder2.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs
-function noop6() {}
-function makeLogFn(fnLevel, logger5, logLevel) {
- if (!logger5 || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
- return noop6;
- } else {
- return logger5[fnLevel].bind(logger5);
- }
-}
-function loggerFor(client9) {
- const logger5 = client9.logger;
- const logLevel = client9.logLevel ?? "off";
- if (!logger5) {
- return noopLogger;
- }
- const cachedLogger = cachedLoggers.get(logger5);
- if (cachedLogger && cachedLogger[0] === logLevel) {
- return cachedLogger[1];
- }
- const levelLogger = {
- error: makeLogFn("error", logger5, logLevel),
- warn: makeLogFn("warn", logger5, logLevel),
- info: makeLogFn("info", logger5, logLevel),
- debug: makeLogFn("debug", logger5, logLevel)
- };
- cachedLoggers.set(logger5, [logLevel, levelLogger]);
- return levelLogger;
-}
-var levelNumbers, parseLogLevel = (maybeLevel, sourceName, client9) => {
- if (!maybeLevel) {
- return;
- }
- if (hasOwn2(levelNumbers, maybeLevel)) {
- return maybeLevel;
- }
- loggerFor(client9).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
- return;
-}, noopLogger, cachedLoggers, formatRequestDetails = (details) => {
- if (details.options) {
- details.options = { ...details.options };
- delete details.options["headers"];
- }
- if (details.headers) {
- details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
- name,
- name.toLowerCase() === "x-api-key" || name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value
- ]));
- }
- if ("retryOfRequestLogID" in details) {
- if (details.retryOfRequestLogID) {
- details.retryOf = details.retryOfRequestLogID;
- }
- delete details.retryOfRequestLogID;
- }
- return details;
-};
-var init_log3 = __esm(() => {
- init_values2();
- levelNumbers = {
- off: 0,
- error: 200,
- warn: 300,
- info: 400,
- debug: 500
- };
- noopLogger = {
- error: noop6,
- warn: noop6,
- info: noop6,
- debug: noop6
- };
- cachedLoggers = /* @__PURE__ */ new WeakMap;
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/core/streaming.mjs
-async function* _iterSSEMessages2(response5, controller) {
- if (!response5.body) {
- controller.abort();
- if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
- throw new AnthropicError2(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
- }
- throw new AnthropicError2(`Attempted to iterate over a response with no body`);
- }
- const sseDecoder = new SSEDecoder2;
- const lineDecoder = new LineDecoder2;
- const iter = ReadableStreamToAsyncIterable2(response5.body);
- for await (const sseChunk of iterSSEChunks2(iter)) {
- for (const line of lineDecoder.decode(sseChunk)) {
- const sse = sseDecoder.decode(line);
- if (sse)
- yield sse;
- }
- }
- for (const line of lineDecoder.flush()) {
- const sse = sseDecoder.decode(line);
- if (sse)
- yield sse;
- }
-}
-async function* iterSSEChunks2(iterator2) {
- let data = new Uint8Array;
- for await (const chunk of iterator2) {
- if (chunk == null) {
- continue;
- }
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
- let newData = new Uint8Array(data.length + binaryChunk.length);
- newData.set(data);
- newData.set(binaryChunk, data.length);
- data = newData;
- let patternIndex;
- while ((patternIndex = findDoubleNewlineIndex2(data)) !== -1) {
- yield data.slice(0, patternIndex);
- data = data.slice(patternIndex);
- }
- }
- if (data.length > 0) {
- yield data;
- }
-}
-
-class SSEDecoder2 {
- constructor() {
- this.event = null;
- this.data = [];
- this.chunks = [];
- }
- decode(line) {
- if (line.endsWith("\r")) {
- line = line.substring(0, line.length - 1);
- }
- if (!line) {
- if (!this.event && !this.data.length)
- return null;
- const sse = {
- event: this.event,
- data: this.data.join(`
-`),
- raw: this.chunks
- };
- this.event = null;
- this.data = [];
- this.chunks = [];
- return sse;
- }
- this.chunks.push(line);
- if (line.startsWith(":")) {
- return null;
- }
- let [fieldname, _, value] = partition2(line, ":");
- if (value.startsWith(" ")) {
- value = value.substring(1);
- }
- if (fieldname === "event") {
- this.event = value;
- } else if (fieldname === "data") {
- this.data.push(value);
- }
- return null;
- }
-}
-function partition2(str, delimiter) {
- const index2 = str.indexOf(delimiter);
- if (index2 !== -1) {
- return [str.substring(0, index2), delimiter, str.substring(index2 + delimiter.length)];
- }
- return [str, "", ""];
-}
-var _Stream_client, Stream2;
-var init_streaming3 = __esm(() => {
- init_tslib();
- init_error3();
- init_line2();
- init_values2();
- init_log3();
- init_error3();
- Stream2 = class Stream2 {
- constructor(iterator2, controller, client9) {
- this.iterator = iterator2;
- _Stream_client.set(this, undefined);
- this.controller = controller;
- __classPrivateFieldSet6(this, _Stream_client, client9, "f");
- }
- static fromSSEResponse(response5, controller, client9) {
- let consumed = false;
- const logger5 = client9 ? loggerFor(client9) : console;
- async function* iterator2() {
- if (consumed) {
- throw new AnthropicError2("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
- }
- consumed = true;
- let done = false;
- try {
- for await (const sse of _iterSSEMessages2(response5, controller)) {
- if (sse.event === "completion") {
- try {
- yield JSON.parse(sse.data);
- } catch (e4) {
- logger5.error(`Could not parse message into JSON:`, sse.data);
- logger5.error(`From chunk:`, sse.raw);
- throw e4;
- }
- }
- if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
- try {
- yield JSON.parse(sse.data);
- } catch (e4) {
- logger5.error(`Could not parse message into JSON:`, sse.data);
- logger5.error(`From chunk:`, sse.raw);
- throw e4;
- }
- }
- if (sse.event === "ping") {
- continue;
- }
- if (sse.event === "error") {
- throw new APIError2(undefined, safeJSON2(sse.data) ?? sse.data, undefined, response5.headers);
- }
- }
- done = true;
- } catch (e4) {
- if (isAbortError3(e4))
- return;
- throw e4;
- } finally {
- if (!done)
- controller.abort();
- }
- }
- return new Stream2(iterator2, controller, client9);
- }
- static fromReadableStream(readableStream, controller, client9) {
- let consumed = false;
- async function* iterLines() {
- const lineDecoder = new LineDecoder2;
- const iter = ReadableStreamToAsyncIterable2(readableStream);
- for await (const chunk of iter) {
- for (const line of lineDecoder.decode(chunk)) {
- yield line;
- }
- }
- for (const line of lineDecoder.flush()) {
- yield line;
- }
- }
- async function* iterator2() {
- if (consumed) {
- throw new AnthropicError2("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
- }
- consumed = true;
- let done = false;
- try {
- for await (const line of iterLines()) {
- if (done)
- continue;
- if (line)
- yield JSON.parse(line);
- }
- done = true;
- } catch (e4) {
- if (isAbortError3(e4))
- return;
- throw e4;
- } finally {
- if (!done)
- controller.abort();
- }
- }
- return new Stream2(iterator2, controller, client9);
- }
- [(_Stream_client = new WeakMap, Symbol.asyncIterator)]() {
- return this.iterator();
- }
- tee() {
- const left = [];
- const right = [];
- const iterator2 = this.iterator();
- const teeIterator = (queue) => {
- return {
- next: () => {
- if (queue.length === 0) {
- const result = iterator2.next();
- left.push(result);
- right.push(result);
- }
- return queue.shift();
- }
- };
- };
- return [
- new Stream2(() => teeIterator(left), this.controller, __classPrivateFieldGet6(this, _Stream_client, "f")),
- new Stream2(() => teeIterator(right), this.controller, __classPrivateFieldGet6(this, _Stream_client, "f"))
- ];
- }
- toReadableStream() {
- const self2 = this;
- let iter;
- return makeReadableStream({
- async start() {
- iter = self2[Symbol.asyncIterator]();
- },
- async pull(ctrl) {
- try {
- const { value, done } = await iter.next();
- if (done)
- return ctrl.close();
- const bytes = encodeUTF8(JSON.stringify(value) + `
-`);
- ctrl.enqueue(bytes);
- } catch (err) {
- ctrl.error(err);
- }
- },
- async cancel() {
- await iter.return?.();
- }
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/parse.mjs
-async function defaultParseResponse2(client9, props) {
- const { response: response5, requestLogID, retryOfRequestLogID, startTime } = props;
- const body = await (async () => {
- if (props.options.stream) {
- loggerFor(client9).debug("response", response5.status, response5.url, response5.headers, response5.body);
- if (props.options.__streamClass) {
- return props.options.__streamClass.fromSSEResponse(response5, props.controller);
- }
- return Stream2.fromSSEResponse(response5, props.controller);
- }
- if (response5.status === 204) {
- return null;
- }
- if (props.options.__binaryResponse) {
- return response5;
- }
- const contentType = response5.headers.get("content-type");
- const mediaType = contentType?.split(";")[0]?.trim();
- const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
- if (isJSON) {
- const contentLength = response5.headers.get("content-length");
- if (contentLength === "0") {
- return;
- }
- const json2 = await response5.json();
- return addRequestID(json2, response5);
- }
- const text = await response5.text();
- return text;
- })();
- loggerFor(client9).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
- retryOfRequestLogID,
- url: response5.url,
- status: response5.status,
- body,
- durationMs: Date.now() - startTime
- }));
- return body;
-}
-function addRequestID(value, response5) {
- if (!value || typeof value !== "object" || Array.isArray(value)) {
- return value;
- }
- return Object.defineProperty(value, "_request_id", {
- value: response5.headers.get("request-id"),
- enumerable: false
- });
-}
-var init_parse3 = __esm(() => {
- init_streaming3();
- init_log3();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/core/api-promise.mjs
-var _APIPromise_client, APIPromise2;
-var init_api_promise = __esm(() => {
- init_tslib();
- init_parse3();
- APIPromise2 = class APIPromise2 extends Promise {
- constructor(client9, responsePromise, parseResponse = defaultParseResponse2) {
- super((resolve9) => {
- resolve9(null);
- });
- this.responsePromise = responsePromise;
- this.parseResponse = parseResponse;
- _APIPromise_client.set(this, undefined);
- __classPrivateFieldSet6(this, _APIPromise_client, client9, "f");
- }
- _thenUnwrap(transform2) {
- return new APIPromise2(__classPrivateFieldGet6(this, _APIPromise_client, "f"), this.responsePromise, async (client9, props) => addRequestID(transform2(await this.parseResponse(client9, props), props), props.response));
- }
- asResponse() {
- return this.responsePromise.then((p4) => p4.response);
- }
- async withResponse() {
- const [data, response5] = await Promise.all([this.parse(), this.asResponse()]);
- return { data, response: response5, request_id: response5.headers.get("request-id") };
- }
- parse() {
- if (!this.parsedPromise) {
- this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet6(this, _APIPromise_client, "f"), data));
- }
- return this.parsedPromise;
- }
- then(onfulfilled, onrejected) {
- return this.parse().then(onfulfilled, onrejected);
- }
- catch(onrejected) {
- return this.parse().catch(onrejected);
- }
- finally(onfinally) {
- return this.parse().finally(onfinally);
- }
- };
- _APIPromise_client = new WeakMap;
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/core/pagination.mjs
-var _AbstractPage_client2, AbstractPage2, PagePromise2, Page2, PageCursor;
-var init_pagination8 = __esm(() => {
- init_tslib();
- init_error3();
- init_parse3();
- init_api_promise();
- init_values2();
- AbstractPage2 = class AbstractPage2 {
- constructor(client9, response5, body, options2) {
- _AbstractPage_client2.set(this, undefined);
- __classPrivateFieldSet6(this, _AbstractPage_client2, client9, "f");
- this.options = options2;
- this.response = response5;
- this.body = body;
- }
- hasNextPage() {
- const items = this.getPaginatedItems();
- if (!items.length)
- return false;
- return this.nextPageRequestOptions() != null;
- }
- async getNextPage() {
- const nextOptions = this.nextPageRequestOptions();
- if (!nextOptions) {
- throw new AnthropicError2("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
- }
- return await __classPrivateFieldGet6(this, _AbstractPage_client2, "f").requestAPIList(this.constructor, nextOptions);
- }
- async* iterPages() {
- let page = this;
- yield page;
- while (page.hasNextPage()) {
- page = await page.getNextPage();
- yield page;
- }
- }
- async* [(_AbstractPage_client2 = new WeakMap, Symbol.asyncIterator)]() {
- for await (const page of this.iterPages()) {
- for (const item of page.getPaginatedItems()) {
- yield item;
- }
- }
- }
- };
- PagePromise2 = class PagePromise2 extends APIPromise2 {
- constructor(client9, request2, Page2) {
- super(client9, request2, async (client10, props) => new Page2(client10, props.response, await defaultParseResponse2(client10, props), props.options));
- }
- async* [Symbol.asyncIterator]() {
- const page = await this;
- for await (const item of page) {
- yield item;
- }
- }
- };
- Page2 = class Page2 extends AbstractPage2 {
- constructor(client9, response5, body, options2) {
- super(client9, response5, body, options2);
- this.data = body.data || [];
- this.has_more = body.has_more || false;
- this.first_id = body.first_id || null;
- this.last_id = body.last_id || null;
- }
- getPaginatedItems() {
- return this.data ?? [];
- }
- hasNextPage() {
- if (this.has_more === false) {
- return false;
- }
- return super.hasNextPage();
- }
- nextPageRequestOptions() {
- if (this.options.query?.["before_id"]) {
- const first_id = this.first_id;
- if (!first_id) {
- return null;
- }
- return {
- ...this.options,
- query: {
- ...maybeObj(this.options.query),
- before_id: first_id
- }
- };
- }
- const cursor = this.last_id;
- if (!cursor) {
- return null;
- }
- return {
- ...this.options,
- query: {
- ...maybeObj(this.options.query),
- after_id: cursor
- }
- };
- }
- };
- PageCursor = class PageCursor extends AbstractPage2 {
- constructor(client9, response5, body, options2) {
- super(client9, response5, body, options2);
- this.data = body.data || [];
- this.has_more = body.has_more || false;
- this.next_page = body.next_page || null;
- }
- getPaginatedItems() {
- return this.data ?? [];
- }
- hasNextPage() {
- if (this.has_more === false) {
- return false;
- }
- return super.hasNextPage();
- }
- nextPageRequestOptions() {
- const cursor = this.next_page;
- if (!cursor) {
- return null;
- }
- return {
- ...this.options,
- query: {
- ...maybeObj(this.options.query),
- page: cursor
- }
- };
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/uploads.mjs
-function makeFile(fileBits, fileName, options2) {
- checkFileSupport();
- return new File(fileBits, fileName ?? "unknown_file", options2);
-}
-function getName2(value, stripPath) {
- const val = typeof value === "object" && value !== null && (("name" in value) && value.name && String(value.name) || ("url" in value) && value.url && String(value.url) || ("filename" in value) && value.filename && String(value.filename) || ("path" in value) && value.path && String(value.path)) || "";
- return stripPath ? val.split(/[\\/]/).pop() || undefined : val;
-}
-function supportsFormData(fetchObject) {
- const fetch3 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
- const cached2 = supportsFormDataMap.get(fetch3);
- if (cached2)
- return cached2;
- const promise2 = (async () => {
- try {
- const FetchResponse = "Response" in fetch3 ? fetch3.Response : (await fetch3("data:,")).constructor;
- const data = new FormData;
- if (data.toString() === await new FetchResponse(data).text()) {
- return false;
- }
- return true;
- } catch {
- return true;
- }
- })();
- supportsFormDataMap.set(fetch3, promise2);
- return promise2;
-}
-var checkFileSupport = () => {
- if (typeof File === "undefined") {
- const { process: process12 } = globalThis;
- const isOldNode = typeof process12?.versions?.node === "string" && parseInt(process12.versions.node.split(".")) < 20;
- throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
- }
-}, isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", multipartFormRequestOptions = async (opts, fetch3, stripFilenames = true) => {
- return { ...opts, body: await createForm(opts.body, fetch3, stripFilenames) };
-}, supportsFormDataMap, createForm = async (body, fetch3, stripFilenames = true) => {
- if (!await supportsFormData(fetch3)) {
- throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
- }
- const form = new FormData;
- await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value, stripFilenames)));
- return form;
-}, isNamedBlob = (value) => value instanceof Blob && ("name" in value), addFormValue = async (form, key, value, stripFilenames) => {
- if (value === undefined)
- return;
- if (value == null) {
- throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
- }
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
- form.append(key, String(value));
- } else if (value instanceof Response) {
- let options2 = {};
- const contentType = value.headers.get("Content-Type");
- if (contentType) {
- options2 = { type: contentType };
- }
- form.append(key, makeFile([await value.blob()], getName2(value, stripFilenames), options2));
- } else if (isAsyncIterable(value)) {
- form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName2(value, stripFilenames)));
- } else if (isNamedBlob(value)) {
- form.append(key, makeFile([value], getName2(value, stripFilenames), { type: value.type }));
- } else if (Array.isArray(value)) {
- await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry, stripFilenames)));
- } else if (typeof value === "object") {
- await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop, stripFilenames)));
- } else {
- throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
- }
-};
-var init_uploads2 = __esm(() => {
- supportsFormDataMap = /* @__PURE__ */ new WeakMap;
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/to-file.mjs
-async function toFile2(value, name, options2) {
- checkFileSupport();
- value = await value;
- name || (name = getName2(value, true));
- if (isFileLike2(value)) {
- if (value instanceof File && name == null && options2 == null) {
- return value;
- }
- return makeFile([await value.arrayBuffer()], name ?? value.name, {
- type: value.type,
- lastModified: value.lastModified,
- ...options2
- });
- }
- if (isResponseLike2(value)) {
- const blob = await value.blob();
- name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
- return makeFile(await getBytes2(blob), name, options2);
- }
- const parts = await getBytes2(value);
- if (!options2?.type) {
- const type = parts.find((part) => typeof part === "object" && ("type" in part) && part.type);
- if (typeof type === "string") {
- options2 = { ...options2, type };
- }
- }
- return makeFile(parts, name, options2);
-}
-async function getBytes2(value) {
- let parts = [];
- if (typeof value === "string" || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
- parts.push(value);
- } else if (isBlobLike2(value)) {
- parts.push(value instanceof Blob ? value : await value.arrayBuffer());
- } else if (isAsyncIterable(value)) {
- for await (const chunk of value) {
- parts.push(...await getBytes2(chunk));
- }
- } else {
- const constructor = value?.constructor?.name;
- throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError2(value)}`);
- }
- return parts;
-}
-function propsForError2(value) {
- if (typeof value !== "object" || value === null)
- return "";
- const props = Object.getOwnPropertyNames(value);
- return `; props: [${props.map((p4) => `"${p4}"`).join(", ")}]`;
-}
-var isBlobLike2 = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", isFileLike2 = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike2(value), isResponseLike2 = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
-var init_to_file = __esm(() => {
- init_uploads2();
- init_uploads2();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/core/uploads.mjs
-var init_uploads3 = __esm(() => {
- init_to_file();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/shared.mjs
-var init_shared7 = () => {};
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/core/resource.mjs
-class APIResource2 {
- constructor(client9) {
- this._client = client9;
- }
-}
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/headers.mjs
-function* iterateHeaders(headers) {
- if (!headers)
- return;
- if (brand_privateNullableHeaders in headers) {
- const { values, nulls } = headers;
- yield* values.entries();
- for (const name of nulls) {
- yield [name, null];
- }
- return;
- }
- let shouldClear = false;
- let iter;
- if (headers instanceof Headers) {
- iter = headers.entries();
- } else if (isReadonlyArray(headers)) {
- iter = headers;
- } else {
- shouldClear = true;
- iter = Object.entries(headers ?? {});
- }
- for (let row of iter) {
- const name = row[0];
- if (typeof name !== "string")
- throw new TypeError("expected header name to be a string");
- const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
- let didClear = false;
- for (const value of values) {
- if (value === undefined)
- continue;
- if (shouldClear && !didClear) {
- didClear = true;
- yield [name, null];
- }
- yield [name, value];
- }
- }
-}
-var brand_privateNullableHeaders, buildHeaders = (newHeaders) => {
- const targetHeaders = new Headers;
- const nullHeaders = new Set;
- for (const headers of newHeaders) {
- const seenHeaders = new Set;
- for (const [name, value] of iterateHeaders(headers)) {
- const lowerName = name.toLowerCase();
- if (!seenHeaders.has(lowerName)) {
- targetHeaders.delete(name);
- seenHeaders.add(lowerName);
- }
- if (value === null) {
- targetHeaders.delete(name);
- nullHeaders.add(lowerName);
- } else {
- targetHeaders.append(name, value);
- nullHeaders.delete(lowerName);
- }
- }
- }
- return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
-};
-var init_headers = __esm(() => {
- init_values2();
- brand_privateNullableHeaders = Symbol.for("brand.privateNullableHeaders");
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs
-function wasCreatedByStainlessHelper(value) {
- return typeof value === "object" && value !== null && SDK_HELPER_SYMBOL in value;
-}
-function collectStainlessHelpers(tools, messages) {
- const helpers3 = new Set;
- if (tools) {
- for (const tool of tools) {
- if (wasCreatedByStainlessHelper(tool)) {
- helpers3.add(tool[SDK_HELPER_SYMBOL]);
- }
- }
- }
- if (messages) {
- for (const message of messages) {
- if (wasCreatedByStainlessHelper(message)) {
- helpers3.add(message[SDK_HELPER_SYMBOL]);
- }
- if (Array.isArray(message.content)) {
- for (const block2 of message.content) {
- if (wasCreatedByStainlessHelper(block2)) {
- helpers3.add(block2[SDK_HELPER_SYMBOL]);
- }
- }
- }
- }
- }
- return Array.from(helpers3);
-}
-function stainlessHelperHeader(tools, messages) {
- const helpers3 = collectStainlessHelpers(tools, messages);
- if (helpers3.length === 0)
- return {};
- return { "x-stainless-helper": helpers3.join(", ") };
-}
-function stainlessHelperHeaderFromFile(file2) {
- if (wasCreatedByStainlessHelper(file2)) {
- return { "x-stainless-helper": file2[SDK_HELPER_SYMBOL] };
- }
- return {};
-}
-var SDK_HELPER_SYMBOL;
-var init_stainless_helper_header = __esm(() => {
- SDK_HELPER_SYMBOL = Symbol("anthropic.sdk.stainlessHelper");
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs
-function encodeURIPath(str) {
- return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
-}
-var EMPTY, createPathTagFunction = (pathEncoder = encodeURIPath) => function path8(statics, ...params) {
- if (statics.length === 1)
- return statics[0];
- let postPath = false;
- const invalidSegments = [];
- const path9 = statics.reduce((previousValue, currentValue, index2) => {
- if (/[?#]/.test(currentValue)) {
- postPath = true;
- }
- const value = params[index2];
- let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
- if (index2 !== params.length && (value == null || typeof value === "object" && value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) {
- encoded = value + "";
- invalidSegments.push({
- start: previousValue.length + currentValue.length,
- length: encoded.length,
- error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
- });
- }
- return previousValue + currentValue + (index2 === params.length ? "" : encoded);
- }, "");
- const pathOnly = path9.split(/[?#]/, 1)[0];
- const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
- let match;
- while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
- invalidSegments.push({
- start: match.index,
- length: match[0].length,
- error: `Value "${match[0]}" can't be safely passed as a path parameter`
- });
- }
- invalidSegments.sort((a5, b4) => a5.start - b4.start);
- if (invalidSegments.length > 0) {
- let lastEnd = 0;
- const underline2 = invalidSegments.reduce((acc, segment) => {
- const spaces = " ".repeat(segment.start - lastEnd);
- const arrows = "^".repeat(segment.length);
- lastEnd = segment.start + segment.length;
- return acc + spaces + arrows;
- }, "");
- throw new AnthropicError2(`Path parameters result in path with invalid segments:
-${invalidSegments.map((e4) => e4.error).join(`
-`)}
-${path9}
-${underline2}`);
- }
- return path9;
-}, path8;
-var init_path2 = __esm(() => {
- init_error3();
- EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
- path8 = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs
-var Files;
-var init_files2 = __esm(() => {
- init_pagination8();
- init_headers();
- init_stainless_helper_header();
- init_uploads2();
- init_path2();
- Files = class Files extends APIResource2 {
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/files", Page2, {
- query,
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- options2?.headers
- ])
- });
- }
- delete(fileID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.delete(path8`/v1/files/${fileID}`, {
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- options2?.headers
- ])
- });
- }
- download(fileID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path8`/v1/files/${fileID}/content`, {
- ...options2,
- headers: buildHeaders([
- {
- "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString(),
- Accept: "application/binary"
- },
- options2?.headers
- ]),
- __binaryResponse: true
- });
- }
- retrieveMetadata(fileID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path8`/v1/files/${fileID}`, {
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- options2?.headers
- ])
- });
- }
- upload(params, options2) {
- const { betas, ...body } = params;
- return this._client.post("/v1/files", multipartFormRequestOptions({
- body,
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- stainlessHelperHeaderFromFile(body.file),
- options2?.headers
- ])
- }, this._client));
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs
-var Models3;
-var init_models3 = __esm(() => {
- init_pagination8();
- init_headers();
- init_path2();
- Models3 = class Models3 extends APIResource2 {
- retrieve(modelID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path8`/v1/models/${modelID}?beta=true`, {
- ...options2,
- headers: buildHeaders([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/models?beta=true", Page2, {
- query,
- ...options2,
- headers: buildHeaders([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/error.mjs
-var init_error4 = __esm(() => {
- init_error3();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/constants.mjs
-var MODEL_NONSTREAMING_TOKENS;
-var init_constants5 = __esm(() => {
- MODEL_NONSTREAMING_TOKENS = {
- "claude-opus-4-20250514": 8192,
- "claude-opus-4-0": 8192,
- "claude-4-opus-20250514": 8192,
- "anthropic.claude-opus-4-20250514-v1:0": 8192,
- "claude-opus-4@20250514": 8192,
- "claude-opus-4-1-20250805": 8192,
- "anthropic.claude-opus-4-1-20250805-v1:0": 8192,
- "claude-opus-4-1@20250805": 8192
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs
-function getOutputFormat(params) {
- return params?.output_format ?? params?.output_config?.format;
-}
-function maybeParseBetaMessage(message, params, opts) {
- const outputFormat = getOutputFormat(params);
- if (!params || !("parse" in (outputFormat ?? {}))) {
- return {
- ...message,
- content: message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: null,
- enumerable: false
- });
- return Object.defineProperty(parsedBlock, "parsed", {
- get() {
- opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");
- return null;
- },
- enumerable: false
- });
- }
- return block2;
- }),
- parsed_output: null
- };
- }
- return parseBetaMessage(message, params, opts);
-}
-function parseBetaMessage(message, params, opts) {
- let firstParsedOutput = null;
- const content = message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedOutput = parseBetaOutputFormat(params, block2.text);
- if (firstParsedOutput === null) {
- firstParsedOutput = parsedOutput;
- }
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: parsedOutput,
- enumerable: false
- });
- return Object.defineProperty(parsedBlock, "parsed", {
- get() {
- opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");
- return parsedOutput;
- },
- enumerable: false
- });
- }
- return block2;
- });
- return {
- ...message,
- content,
- parsed_output: firstParsedOutput
- };
-}
-function parseBetaOutputFormat(params, content) {
- const outputFormat = getOutputFormat(params);
- if (outputFormat?.type !== "json_schema") {
- return null;
- }
- try {
- if ("parse" in outputFormat) {
- return outputFormat.parse(content);
- }
- return JSON.parse(content);
- } catch (error41) {
- throw new AnthropicError2(`Failed to parse structured output: ${error41}`);
- }
-}
-var init_beta_parser = __esm(() => {
- init_error3();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs
-var tokenize2 = (input) => {
- let current = 0;
- let tokens = [];
- while (current < input.length) {
- let char = input[current];
- if (char === "\\") {
- current++;
- continue;
- }
- if (char === "{") {
- tokens.push({
- type: "brace",
- value: "{"
- });
- current++;
- continue;
- }
- if (char === "}") {
- tokens.push({
- type: "brace",
- value: "}"
- });
- current++;
- continue;
- }
- if (char === "[") {
- tokens.push({
- type: "paren",
- value: "["
- });
- current++;
- continue;
- }
- if (char === "]") {
- tokens.push({
- type: "paren",
- value: "]"
- });
- current++;
- continue;
- }
- if (char === ":") {
- tokens.push({
- type: "separator",
- value: ":"
- });
- current++;
- continue;
- }
- if (char === ",") {
- tokens.push({
- type: "delimiter",
- value: ","
- });
- current++;
- continue;
- }
- if (char === '"') {
- let value = "";
- let danglingQuote = false;
- char = input[++current];
- while (char !== '"') {
- if (current === input.length) {
- danglingQuote = true;
- break;
- }
- if (char === "\\") {
- current++;
- if (current === input.length) {
- danglingQuote = true;
- break;
- }
- value += char + input[current];
- char = input[++current];
- } else {
- value += char;
- char = input[++current];
- }
- }
- char = input[++current];
- if (!danglingQuote) {
- tokens.push({
- type: "string",
- value
- });
- }
- continue;
- }
- let WHITESPACE = /\s/;
- if (char && WHITESPACE.test(char)) {
- current++;
- continue;
- }
- let NUMBERS = /[0-9]/;
- if (char && NUMBERS.test(char) || char === "-" || char === ".") {
- let value = "";
- if (char === "-") {
- value += char;
- char = input[++current];
- }
- while (char && NUMBERS.test(char) || char === ".") {
- value += char;
- char = input[++current];
- }
- tokens.push({
- type: "number",
- value
- });
- continue;
- }
- let LETTERS = /[a-z]/i;
- if (char && LETTERS.test(char)) {
- let value = "";
- while (char && LETTERS.test(char)) {
- if (current === input.length) {
- break;
- }
- value += char;
- char = input[++current];
- }
- if (value == "true" || value == "false" || value === "null") {
- tokens.push({
- type: "name",
- value
- });
- } else {
- current++;
- continue;
- }
- continue;
- }
- current++;
- }
- return tokens;
-}, strip2 = (tokens) => {
- if (tokens.length === 0) {
- return tokens;
- }
- let lastToken = tokens[tokens.length - 1];
- switch (lastToken.type) {
- case "separator":
- tokens = tokens.slice(0, tokens.length - 1);
- return strip2(tokens);
- break;
- case "number":
- let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
- if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip2(tokens);
- }
- case "string":
- let tokenBeforeTheLastToken = tokens[tokens.length - 2];
- if (tokenBeforeTheLastToken?.type === "delimiter") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip2(tokens);
- } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip2(tokens);
- }
- break;
- case "delimiter":
- tokens = tokens.slice(0, tokens.length - 1);
- return strip2(tokens);
- break;
- }
- return tokens;
-}, unstrip2 = (tokens) => {
- let tail = [];
- tokens.map((token) => {
- if (token.type === "brace") {
- if (token.value === "{") {
- tail.push("}");
- } else {
- tail.splice(tail.lastIndexOf("}"), 1);
- }
- }
- if (token.type === "paren") {
- if (token.value === "[") {
- tail.push("]");
- } else {
- tail.splice(tail.lastIndexOf("]"), 1);
- }
- }
- });
- if (tail.length > 0) {
- tail.reverse().map((item) => {
- if (item === "}") {
- tokens.push({
- type: "brace",
- value: "}"
- });
- } else if (item === "]") {
- tokens.push({
- type: "paren",
- value: "]"
- });
- }
- });
- }
- return tokens;
-}, generate2 = (tokens) => {
- let output = "";
- tokens.map((token) => {
- switch (token.type) {
- case "string":
- output += '"' + token.value + '"';
- break;
- default:
- output += token.value;
- break;
- }
- });
- return output;
-}, partialParse2 = (input) => JSON.parse(generate2(unstrip2(strip2(tokenize2(input)))));
-var init_parser3 = () => {};
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/streaming.mjs
-var init_streaming4 = __esm(() => {
- init_streaming3();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs
-function tracksToolInput(content) {
- return content.type === "tool_use" || content.type === "server_tool_use" || content.type === "mcp_tool_use";
-}
-function checkNever3(x3) {}
-var _BetaMessageStream_instances2, _BetaMessageStream_currentMessageSnapshot2, _BetaMessageStream_params, _BetaMessageStream_connectedPromise2, _BetaMessageStream_resolveConnectedPromise2, _BetaMessageStream_rejectConnectedPromise2, _BetaMessageStream_endPromise2, _BetaMessageStream_resolveEndPromise2, _BetaMessageStream_rejectEndPromise2, _BetaMessageStream_listeners2, _BetaMessageStream_ended2, _BetaMessageStream_errored2, _BetaMessageStream_aborted2, _BetaMessageStream_catchingPromiseCreated2, _BetaMessageStream_response2, _BetaMessageStream_request_id2, _BetaMessageStream_logger, _BetaMessageStream_getFinalMessage2, _BetaMessageStream_getFinalText2, _BetaMessageStream_handleError2, _BetaMessageStream_beginRequest2, _BetaMessageStream_addStreamEvent2, _BetaMessageStream_endRequest2, _BetaMessageStream_accumulateMessage2, JSON_BUF_PROPERTY3 = "__json_buf", BetaMessageStream2;
-var init_BetaMessageStream2 = __esm(() => {
- init_tslib();
- init_parser3();
- init_error4();
- init_streaming4();
- init_beta_parser();
- BetaMessageStream2 = class BetaMessageStream2 {
- constructor(params, opts) {
- _BetaMessageStream_instances2.add(this);
- this.messages = [];
- this.receivedMessages = [];
- _BetaMessageStream_currentMessageSnapshot2.set(this, undefined);
- _BetaMessageStream_params.set(this, null);
- this.controller = new AbortController;
- _BetaMessageStream_connectedPromise2.set(this, undefined);
- _BetaMessageStream_resolveConnectedPromise2.set(this, () => {});
- _BetaMessageStream_rejectConnectedPromise2.set(this, () => {});
- _BetaMessageStream_endPromise2.set(this, undefined);
- _BetaMessageStream_resolveEndPromise2.set(this, () => {});
- _BetaMessageStream_rejectEndPromise2.set(this, () => {});
- _BetaMessageStream_listeners2.set(this, {});
- _BetaMessageStream_ended2.set(this, false);
- _BetaMessageStream_errored2.set(this, false);
- _BetaMessageStream_aborted2.set(this, false);
- _BetaMessageStream_catchingPromiseCreated2.set(this, false);
- _BetaMessageStream_response2.set(this, undefined);
- _BetaMessageStream_request_id2.set(this, undefined);
- _BetaMessageStream_logger.set(this, undefined);
- _BetaMessageStream_handleError2.set(this, (error41) => {
- __classPrivateFieldSet6(this, _BetaMessageStream_errored2, true, "f");
- if (isAbortError3(error41)) {
- error41 = new APIUserAbortError2;
- }
- if (error41 instanceof APIUserAbortError2) {
- __classPrivateFieldSet6(this, _BetaMessageStream_aborted2, true, "f");
- return this._emit("abort", error41);
- }
- if (error41 instanceof AnthropicError2) {
- return this._emit("error", error41);
- }
- if (error41 instanceof Error) {
- const anthropicError = new AnthropicError2(error41.message);
- anthropicError.cause = error41;
- return this._emit("error", anthropicError);
- }
- return this._emit("error", new AnthropicError2(String(error41)));
- });
- __classPrivateFieldSet6(this, _BetaMessageStream_connectedPromise2, new Promise((resolve9, reject) => {
- __classPrivateFieldSet6(this, _BetaMessageStream_resolveConnectedPromise2, resolve9, "f");
- __classPrivateFieldSet6(this, _BetaMessageStream_rejectConnectedPromise2, reject, "f");
- }), "f");
- __classPrivateFieldSet6(this, _BetaMessageStream_endPromise2, new Promise((resolve9, reject) => {
- __classPrivateFieldSet6(this, _BetaMessageStream_resolveEndPromise2, resolve9, "f");
- __classPrivateFieldSet6(this, _BetaMessageStream_rejectEndPromise2, reject, "f");
- }), "f");
- __classPrivateFieldGet6(this, _BetaMessageStream_connectedPromise2, "f").catch(() => {});
- __classPrivateFieldGet6(this, _BetaMessageStream_endPromise2, "f").catch(() => {});
- __classPrivateFieldSet6(this, _BetaMessageStream_params, params, "f");
- __classPrivateFieldSet6(this, _BetaMessageStream_logger, opts?.logger ?? console, "f");
- }
- get response() {
- return __classPrivateFieldGet6(this, _BetaMessageStream_response2, "f");
- }
- get request_id() {
- return __classPrivateFieldGet6(this, _BetaMessageStream_request_id2, "f");
- }
- async withResponse() {
- __classPrivateFieldSet6(this, _BetaMessageStream_catchingPromiseCreated2, true, "f");
- const response5 = await __classPrivateFieldGet6(this, _BetaMessageStream_connectedPromise2, "f");
- if (!response5) {
- throw new Error("Could not resolve a `Response` object");
- }
- return {
- data: this,
- response: response5,
- request_id: response5.headers.get("request-id")
- };
- }
- static fromReadableStream(stream8) {
- const runner = new BetaMessageStream2(null);
- runner._run(() => runner._fromReadableStream(stream8));
- return runner;
- }
- static createMessage(messages, params, options2, { logger: logger5 } = {}) {
- const runner = new BetaMessageStream2(params, { logger: logger5 });
- for (const message of params.messages) {
- runner._addMessageParam(message);
- }
- __classPrivateFieldSet6(runner, _BetaMessageStream_params, { ...params, stream: true }, "f");
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options2, headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" } }));
- return runner;
- }
- _run(executor) {
- executor().then(() => {
- this._emitFinal();
- this._emit("end");
- }, __classPrivateFieldGet6(this, _BetaMessageStream_handleError2, "f"));
- }
- _addMessageParam(message) {
- this.messages.push(message);
- }
- _addMessage(message, emit = true) {
- this.receivedMessages.push(message);
- if (emit) {
- this._emit("message", message);
- }
- }
- async _createMessage(messages, params, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet6(this, _BetaMessageStream_instances2, "m", _BetaMessageStream_beginRequest2).call(this);
- const { response: response5, data: stream8 } = await messages.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal }).withResponse();
- this._connected(response5);
- for await (const event of stream8) {
- __classPrivateFieldGet6(this, _BetaMessageStream_instances2, "m", _BetaMessageStream_addStreamEvent2).call(this, event);
- }
- if (stream8.controller.signal?.aborted) {
- throw new APIUserAbortError2;
- }
- __classPrivateFieldGet6(this, _BetaMessageStream_instances2, "m", _BetaMessageStream_endRequest2).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- _connected(response5) {
- if (this.ended)
- return;
- __classPrivateFieldSet6(this, _BetaMessageStream_response2, response5, "f");
- __classPrivateFieldSet6(this, _BetaMessageStream_request_id2, response5?.headers.get("request-id"), "f");
- __classPrivateFieldGet6(this, _BetaMessageStream_resolveConnectedPromise2, "f").call(this, response5);
- this._emit("connect");
- }
- get ended() {
- return __classPrivateFieldGet6(this, _BetaMessageStream_ended2, "f");
- }
- get errored() {
- return __classPrivateFieldGet6(this, _BetaMessageStream_errored2, "f");
- }
- get aborted() {
- return __classPrivateFieldGet6(this, _BetaMessageStream_aborted2, "f");
- }
- abort() {
- this.controller.abort();
- }
- on(event, listener) {
- const listeners = __classPrivateFieldGet6(this, _BetaMessageStream_listeners2, "f")[event] || (__classPrivateFieldGet6(this, _BetaMessageStream_listeners2, "f")[event] = []);
- listeners.push({ listener });
- return this;
- }
- off(event, listener) {
- const listeners = __classPrivateFieldGet6(this, _BetaMessageStream_listeners2, "f")[event];
- if (!listeners)
- return this;
- const index2 = listeners.findIndex((l4) => l4.listener === listener);
- if (index2 >= 0)
- listeners.splice(index2, 1);
- return this;
- }
- once(event, listener) {
- const listeners = __classPrivateFieldGet6(this, _BetaMessageStream_listeners2, "f")[event] || (__classPrivateFieldGet6(this, _BetaMessageStream_listeners2, "f")[event] = []);
- listeners.push({ listener, once: true });
- return this;
- }
- emitted(event) {
- return new Promise((resolve9, reject) => {
- __classPrivateFieldSet6(this, _BetaMessageStream_catchingPromiseCreated2, true, "f");
- if (event !== "error")
- this.once("error", reject);
- this.once(event, resolve9);
- });
- }
- async done() {
- __classPrivateFieldSet6(this, _BetaMessageStream_catchingPromiseCreated2, true, "f");
- await __classPrivateFieldGet6(this, _BetaMessageStream_endPromise2, "f");
- }
- get currentMessage() {
- return __classPrivateFieldGet6(this, _BetaMessageStream_currentMessageSnapshot2, "f");
- }
- async finalMessage() {
- await this.done();
- return __classPrivateFieldGet6(this, _BetaMessageStream_instances2, "m", _BetaMessageStream_getFinalMessage2).call(this);
- }
- async finalText() {
- await this.done();
- return __classPrivateFieldGet6(this, _BetaMessageStream_instances2, "m", _BetaMessageStream_getFinalText2).call(this);
- }
- _emit(event, ...args) {
- if (__classPrivateFieldGet6(this, _BetaMessageStream_ended2, "f"))
- return;
- if (event === "end") {
- __classPrivateFieldSet6(this, _BetaMessageStream_ended2, true, "f");
- __classPrivateFieldGet6(this, _BetaMessageStream_resolveEndPromise2, "f").call(this);
- }
- const listeners = __classPrivateFieldGet6(this, _BetaMessageStream_listeners2, "f")[event];
- if (listeners) {
- __classPrivateFieldGet6(this, _BetaMessageStream_listeners2, "f")[event] = listeners.filter((l4) => !l4.once);
- listeners.forEach(({ listener }) => listener(...args));
- }
- if (event === "abort") {
- const error41 = args[0];
- if (!__classPrivateFieldGet6(this, _BetaMessageStream_catchingPromiseCreated2, "f") && !listeners?.length) {
- Promise.reject(error41);
- }
- __classPrivateFieldGet6(this, _BetaMessageStream_rejectConnectedPromise2, "f").call(this, error41);
- __classPrivateFieldGet6(this, _BetaMessageStream_rejectEndPromise2, "f").call(this, error41);
- this._emit("end");
- return;
- }
- if (event === "error") {
- const error41 = args[0];
- if (!__classPrivateFieldGet6(this, _BetaMessageStream_catchingPromiseCreated2, "f") && !listeners?.length) {
- Promise.reject(error41);
- }
- __classPrivateFieldGet6(this, _BetaMessageStream_rejectConnectedPromise2, "f").call(this, error41);
- __classPrivateFieldGet6(this, _BetaMessageStream_rejectEndPromise2, "f").call(this, error41);
- this._emit("end");
- }
- }
- _emitFinal() {
- const finalMessage = this.receivedMessages.at(-1);
- if (finalMessage) {
- this._emit("finalMessage", __classPrivateFieldGet6(this, _BetaMessageStream_instances2, "m", _BetaMessageStream_getFinalMessage2).call(this));
- }
- }
- async _fromReadableStream(readableStream, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet6(this, _BetaMessageStream_instances2, "m", _BetaMessageStream_beginRequest2).call(this);
- this._connected(null);
- const stream8 = Stream2.fromReadableStream(readableStream, this.controller);
- for await (const event of stream8) {
- __classPrivateFieldGet6(this, _BetaMessageStream_instances2, "m", _BetaMessageStream_addStreamEvent2).call(this, event);
- }
- if (stream8.controller.signal?.aborted) {
- throw new APIUserAbortError2;
- }
- __classPrivateFieldGet6(this, _BetaMessageStream_instances2, "m", _BetaMessageStream_endRequest2).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- [(_BetaMessageStream_currentMessageSnapshot2 = new WeakMap, _BetaMessageStream_params = new WeakMap, _BetaMessageStream_connectedPromise2 = new WeakMap, _BetaMessageStream_resolveConnectedPromise2 = new WeakMap, _BetaMessageStream_rejectConnectedPromise2 = new WeakMap, _BetaMessageStream_endPromise2 = new WeakMap, _BetaMessageStream_resolveEndPromise2 = new WeakMap, _BetaMessageStream_rejectEndPromise2 = new WeakMap, _BetaMessageStream_listeners2 = new WeakMap, _BetaMessageStream_ended2 = new WeakMap, _BetaMessageStream_errored2 = new WeakMap, _BetaMessageStream_aborted2 = new WeakMap, _BetaMessageStream_catchingPromiseCreated2 = new WeakMap, _BetaMessageStream_response2 = new WeakMap, _BetaMessageStream_request_id2 = new WeakMap, _BetaMessageStream_logger = new WeakMap, _BetaMessageStream_handleError2 = new WeakMap, _BetaMessageStream_instances2 = new WeakSet, _BetaMessageStream_getFinalMessage2 = function _BetaMessageStream_getFinalMessage3() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError2("stream ended without producing a Message with role=assistant");
- }
- return this.receivedMessages.at(-1);
- }, _BetaMessageStream_getFinalText2 = function _BetaMessageStream_getFinalText3() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError2("stream ended without producing a Message with role=assistant");
- }
- const textBlocks = this.receivedMessages.at(-1).content.filter((block2) => block2.type === "text").map((block2) => block2.text);
- if (textBlocks.length === 0) {
- throw new AnthropicError2("stream ended without producing a content block with type=text");
- }
- return textBlocks.join(" ");
- }, _BetaMessageStream_beginRequest2 = function _BetaMessageStream_beginRequest3() {
- if (this.ended)
- return;
- __classPrivateFieldSet6(this, _BetaMessageStream_currentMessageSnapshot2, undefined, "f");
- }, _BetaMessageStream_addStreamEvent2 = function _BetaMessageStream_addStreamEvent3(event) {
- if (this.ended)
- return;
- const messageSnapshot = __classPrivateFieldGet6(this, _BetaMessageStream_instances2, "m", _BetaMessageStream_accumulateMessage2).call(this, event);
- this._emit("streamEvent", event, messageSnapshot);
- switch (event.type) {
- case "content_block_delta": {
- const content = messageSnapshot.content.at(-1);
- switch (event.delta.type) {
- case "text_delta": {
- if (content.type === "text") {
- this._emit("text", event.delta.text, content.text || "");
- }
- break;
- }
- case "citations_delta": {
- if (content.type === "text") {
- this._emit("citation", event.delta.citation, content.citations ?? []);
- }
- break;
- }
- case "input_json_delta": {
- if (tracksToolInput(content) && content.input) {
- this._emit("inputJson", event.delta.partial_json, content.input);
- }
- break;
- }
- case "thinking_delta": {
- if (content.type === "thinking") {
- this._emit("thinking", event.delta.thinking, content.thinking);
- }
- break;
- }
- case "signature_delta": {
- if (content.type === "thinking") {
- this._emit("signature", content.signature);
- }
- break;
- }
- case "compaction_delta": {
- if (content.type === "compaction" && content.content) {
- this._emit("compaction", content.content);
- }
- break;
- }
- default:
- checkNever3(event.delta);
- }
- break;
- }
- case "message_stop": {
- this._addMessageParam(messageSnapshot);
- this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet6(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet6(this, _BetaMessageStream_logger, "f") }), true);
- break;
- }
- case "content_block_stop": {
- this._emit("contentBlock", messageSnapshot.content.at(-1));
- break;
- }
- case "message_start": {
- __classPrivateFieldSet6(this, _BetaMessageStream_currentMessageSnapshot2, messageSnapshot, "f");
- break;
- }
- case "content_block_start":
- case "message_delta":
- break;
- }
- }, _BetaMessageStream_endRequest2 = function _BetaMessageStream_endRequest3() {
- if (this.ended) {
- throw new AnthropicError2(`stream has ended, this shouldn't happen`);
- }
- const snapshot = __classPrivateFieldGet6(this, _BetaMessageStream_currentMessageSnapshot2, "f");
- if (!snapshot) {
- throw new AnthropicError2(`request ended without sending any chunks`);
- }
- __classPrivateFieldSet6(this, _BetaMessageStream_currentMessageSnapshot2, undefined, "f");
- return maybeParseBetaMessage(snapshot, __classPrivateFieldGet6(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet6(this, _BetaMessageStream_logger, "f") });
- }, _BetaMessageStream_accumulateMessage2 = function _BetaMessageStream_accumulateMessage3(event) {
- let snapshot = __classPrivateFieldGet6(this, _BetaMessageStream_currentMessageSnapshot2, "f");
- if (event.type === "message_start") {
- if (snapshot) {
- throw new AnthropicError2(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
- }
- return event.message;
- }
- if (!snapshot) {
- throw new AnthropicError2(`Unexpected event order, got ${event.type} before "message_start"`);
- }
- switch (event.type) {
- case "message_stop":
- return snapshot;
- case "message_delta":
- snapshot.container = event.delta.container;
- snapshot.stop_reason = event.delta.stop_reason;
- snapshot.stop_sequence = event.delta.stop_sequence;
- snapshot.usage.output_tokens = event.usage.output_tokens;
- snapshot.context_management = event.context_management;
- if (event.usage.input_tokens != null) {
- snapshot.usage.input_tokens = event.usage.input_tokens;
- }
- if (event.usage.cache_creation_input_tokens != null) {
- snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
- }
- if (event.usage.cache_read_input_tokens != null) {
- snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
- }
- if (event.usage.server_tool_use != null) {
- snapshot.usage.server_tool_use = event.usage.server_tool_use;
- }
- if (event.usage.iterations != null) {
- snapshot.usage.iterations = event.usage.iterations;
- }
- return snapshot;
- case "content_block_start":
- snapshot.content.push(event.content_block);
- return snapshot;
- case "content_block_delta": {
- const snapshotContent = snapshot.content.at(event.index);
- switch (event.delta.type) {
- case "text_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- text: (snapshotContent.text || "") + event.delta.text
- };
- }
- break;
- }
- case "citations_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- citations: [...snapshotContent.citations ?? [], event.delta.citation]
- };
- }
- break;
- }
- case "input_json_delta": {
- if (snapshotContent && tracksToolInput(snapshotContent)) {
- let jsonBuf = snapshotContent[JSON_BUF_PROPERTY3] || "";
- jsonBuf += event.delta.partial_json;
- const newContent = { ...snapshotContent };
- Object.defineProperty(newContent, JSON_BUF_PROPERTY3, {
- value: jsonBuf,
- enumerable: false,
- writable: true
- });
- if (jsonBuf) {
- try {
- newContent.input = partialParse2(jsonBuf);
- } catch (err) {
- const error41 = new AnthropicError2(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`);
- __classPrivateFieldGet6(this, _BetaMessageStream_handleError2, "f").call(this, error41);
- }
- }
- snapshot.content[event.index] = newContent;
- }
- break;
- }
- case "thinking_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- thinking: snapshotContent.thinking + event.delta.thinking
- };
- }
- break;
- }
- case "signature_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- signature: event.delta.signature
- };
- }
- break;
- }
- case "compaction_delta": {
- if (snapshotContent?.type === "compaction") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- content: (snapshotContent.content || "") + event.delta.content
- };
- }
- break;
- }
- default:
- checkNever3(event.delta);
- }
- return snapshot;
- }
- case "content_block_stop":
- return snapshot;
- }
- }, Symbol.asyncIterator)]() {
- const pushQueue = [];
- const readQueue = [];
- let done = false;
- this.on("streamEvent", (event) => {
- const reader = readQueue.shift();
- if (reader) {
- reader.resolve(event);
- } else {
- pushQueue.push(event);
- }
- });
- this.on("end", () => {
- done = true;
- for (const reader of readQueue) {
- reader.resolve(undefined);
- }
- readQueue.length = 0;
- });
- this.on("abort", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- this.on("error", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- return {
- next: async () => {
- if (!pushQueue.length) {
- if (done) {
- return { value: undefined, done: true };
- }
- return new Promise((resolve9, reject) => readQueue.push({ resolve: resolve9, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
- }
- const chunk = pushQueue.shift();
- return { value: chunk, done: false };
- },
- return: async () => {
- this.abort();
- return { value: undefined, done: true };
- }
- };
- }
- toReadableStream() {
- const stream8 = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
- return stream8.toReadableStream();
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs
-var ToolError;
-var init_ToolError = __esm(() => {
- ToolError = class ToolError extends Error {
- constructor(content) {
- const message = typeof content === "string" ? content : content.map((block2) => {
- if (block2.type === "text")
- return block2.text;
- return `[${block2.type}]`;
- }).join(" ");
- super(message);
- this.name = "ToolError";
- this.content = content;
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs
-var DEFAULT_TOKEN_THRESHOLD = 1e5, DEFAULT_SUMMARY_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
-1. Task Overview
-The user's core request and success criteria
-Any clarifications or constraints they specified
-2. Current State
-What has been completed so far
-Files created, modified, or analyzed (with paths if relevant)
-Key outputs or artifacts produced
-3. Important Discoveries
-Technical constraints or requirements uncovered
-Decisions made and their rationale
-Errors encountered and how they were resolved
-What approaches were tried that didn't work (and why)
-4. Next Steps
-Specific actions needed to complete the task
-Any blockers or open questions to resolve
-Priority order if multiple steps remain
-5. Context to Preserve
-User preferences or style requirements
-Domain-specific details that aren't obvious
-Any promises made to the user
-Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
-Wrap your summary in tags.`;
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs
-function promiseWithResolvers() {
- let resolve9;
- let reject;
- const promise2 = new Promise((res, rej) => {
- resolve9 = res;
- reject = rej;
- });
- return { promise: promise2, resolve: resolve9, reject };
-}
-async function generateToolResponse(params, lastMessage = params.messages.at(-1)) {
- if (!lastMessage || lastMessage.role !== "assistant" || !lastMessage.content || typeof lastMessage.content === "string") {
- return null;
- }
- const toolUseBlocks = lastMessage.content.filter((content) => content.type === "tool_use");
- if (toolUseBlocks.length === 0) {
- return null;
- }
- const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => {
- const tool = params.tools.find((t4) => ("name" in t4 ? t4.name : t4.mcp_server_name) === toolUse.name);
- if (!tool || !("run" in tool)) {
- return {
- type: "tool_result",
- tool_use_id: toolUse.id,
- content: `Error: Tool '${toolUse.name}' not found`,
- is_error: true
- };
- }
- try {
- let input = toolUse.input;
- if ("parse" in tool && tool.parse) {
- input = tool.parse(input);
- }
- const result = await tool.run(input);
- return {
- type: "tool_result",
- tool_use_id: toolUse.id,
- content: result
- };
- } catch (error41) {
- return {
- type: "tool_result",
- tool_use_id: toolUse.id,
- content: error41 instanceof ToolError ? error41.content : `Error: ${error41 instanceof Error ? error41.message : String(error41)}`,
- is_error: true
- };
- }
- }));
- return {
- role: "user",
- content: toolResults
- };
-}
-var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_checkAndCompact, _BetaToolRunner_generateToolResponse, BetaToolRunner;
-var init_BetaToolRunner = __esm(() => {
- init_tslib();
- init_ToolError();
- init_error3();
- init_headers();
- init_stainless_helper_header();
- BetaToolRunner = class BetaToolRunner {
- constructor(client9, params, options2) {
- _BetaToolRunner_instances.add(this);
- this.client = client9;
- _BetaToolRunner_consumed.set(this, false);
- _BetaToolRunner_mutated.set(this, false);
- _BetaToolRunner_state.set(this, undefined);
- _BetaToolRunner_options.set(this, undefined);
- _BetaToolRunner_message.set(this, undefined);
- _BetaToolRunner_toolResponse.set(this, undefined);
- _BetaToolRunner_completion.set(this, undefined);
- _BetaToolRunner_iterationCount.set(this, 0);
- __classPrivateFieldSet6(this, _BetaToolRunner_state, {
- params: {
- ...params,
- messages: structuredClone(params.messages)
- }
- }, "f");
- const helpers3 = collectStainlessHelpers(params.tools, params.messages);
- const helperValue = ["BetaToolRunner", ...helpers3].join(", ");
- __classPrivateFieldSet6(this, _BetaToolRunner_options, {
- ...options2,
- headers: buildHeaders([{ "x-stainless-helper": helperValue }, options2?.headers])
- }, "f");
- __classPrivateFieldSet6(this, _BetaToolRunner_completion, promiseWithResolvers(), "f");
- }
- async* [(_BetaToolRunner_consumed = new WeakMap, _BetaToolRunner_mutated = new WeakMap, _BetaToolRunner_state = new WeakMap, _BetaToolRunner_options = new WeakMap, _BetaToolRunner_message = new WeakMap, _BetaToolRunner_toolResponse = new WeakMap, _BetaToolRunner_completion = new WeakMap, _BetaToolRunner_iterationCount = new WeakMap, _BetaToolRunner_instances = new WeakSet, _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact2() {
- const compactionControl = __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params.compactionControl;
- if (!compactionControl || !compactionControl.enabled) {
- return false;
- }
- let tokensUsed = 0;
- if (__classPrivateFieldGet6(this, _BetaToolRunner_message, "f") !== undefined) {
- try {
- const message = await __classPrivateFieldGet6(this, _BetaToolRunner_message, "f");
- const totalInputTokens = message.usage.input_tokens + (message.usage.cache_creation_input_tokens ?? 0) + (message.usage.cache_read_input_tokens ?? 0);
- tokensUsed = totalInputTokens + message.usage.output_tokens;
- } catch {
- return false;
- }
- }
- const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD;
- if (tokensUsed < threshold) {
- return false;
- }
- const model = compactionControl.model ?? __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params.model;
- const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT;
- const messages = __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params.messages;
- if (messages[messages.length - 1].role === "assistant") {
- const lastMessage = messages[messages.length - 1];
- if (Array.isArray(lastMessage.content)) {
- const nonToolBlocks = lastMessage.content.filter((block2) => block2.type !== "tool_use");
- if (nonToolBlocks.length === 0) {
- messages.pop();
- } else {
- lastMessage.content = nonToolBlocks;
- }
- }
- }
- const response5 = await this.client.beta.messages.create({
- model,
- messages: [
- ...messages,
- {
- role: "user",
- content: [
- {
- type: "text",
- text: summaryPrompt
- }
- ]
- }
- ],
- max_tokens: __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params.max_tokens
- }, {
- headers: { "x-stainless-helper": "compaction" }
- });
- if (response5.content[0]?.type !== "text") {
- throw new AnthropicError2("Expected text response for compaction");
- }
- __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params.messages = [
- {
- role: "user",
- content: response5.content
- }
- ];
- return true;
- }, Symbol.asyncIterator)]() {
- var _a5;
- if (__classPrivateFieldGet6(this, _BetaToolRunner_consumed, "f")) {
- throw new AnthropicError2("Cannot iterate over a consumed stream");
- }
- __classPrivateFieldSet6(this, _BetaToolRunner_consumed, true, "f");
- __classPrivateFieldSet6(this, _BetaToolRunner_mutated, true, "f");
- __classPrivateFieldSet6(this, _BetaToolRunner_toolResponse, undefined, "f");
- try {
- while (true) {
- let stream8;
- try {
- if (__classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params.max_iterations && __classPrivateFieldGet6(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params.max_iterations) {
- break;
- }
- __classPrivateFieldSet6(this, _BetaToolRunner_mutated, false, "f");
- __classPrivateFieldSet6(this, _BetaToolRunner_toolResponse, undefined, "f");
- __classPrivateFieldSet6(this, _BetaToolRunner_iterationCount, (_a5 = __classPrivateFieldGet6(this, _BetaToolRunner_iterationCount, "f"), _a5++, _a5), "f");
- __classPrivateFieldSet6(this, _BetaToolRunner_message, undefined, "f");
- const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params;
- if (params.stream) {
- stream8 = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet6(this, _BetaToolRunner_options, "f"));
- __classPrivateFieldSet6(this, _BetaToolRunner_message, stream8.finalMessage(), "f");
- __classPrivateFieldGet6(this, _BetaToolRunner_message, "f").catch(() => {});
- yield stream8;
- } else {
- __classPrivateFieldSet6(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet6(this, _BetaToolRunner_options, "f")), "f");
- yield __classPrivateFieldGet6(this, _BetaToolRunner_message, "f");
- }
- const isCompacted = await __classPrivateFieldGet6(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this);
- if (!isCompacted) {
- if (!__classPrivateFieldGet6(this, _BetaToolRunner_mutated, "f")) {
- const { role, content } = await __classPrivateFieldGet6(this, _BetaToolRunner_message, "f");
- __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params.messages.push({ role, content });
- }
- const toolMessage = await __classPrivateFieldGet6(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params.messages.at(-1));
- if (toolMessage) {
- __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage);
- } else if (!__classPrivateFieldGet6(this, _BetaToolRunner_mutated, "f")) {
- break;
- }
- }
- } finally {
- if (stream8) {
- stream8.abort();
- }
- }
- }
- if (!__classPrivateFieldGet6(this, _BetaToolRunner_message, "f")) {
- throw new AnthropicError2("ToolRunner concluded without a message from the server");
- }
- __classPrivateFieldGet6(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet6(this, _BetaToolRunner_message, "f"));
- } catch (error41) {
- __classPrivateFieldSet6(this, _BetaToolRunner_consumed, false, "f");
- __classPrivateFieldGet6(this, _BetaToolRunner_completion, "f").promise.catch(() => {});
- __classPrivateFieldGet6(this, _BetaToolRunner_completion, "f").reject(error41);
- __classPrivateFieldSet6(this, _BetaToolRunner_completion, promiseWithResolvers(), "f");
- throw error41;
- }
- }
- setMessagesParams(paramsOrMutator) {
- if (typeof paramsOrMutator === "function") {
- __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params);
- } else {
- __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params = paramsOrMutator;
- }
- __classPrivateFieldSet6(this, _BetaToolRunner_mutated, true, "f");
- __classPrivateFieldSet6(this, _BetaToolRunner_toolResponse, undefined, "f");
- }
- async generateToolResponse() {
- const message = await __classPrivateFieldGet6(this, _BetaToolRunner_message, "f") ?? this.params.messages.at(-1);
- if (!message) {
- return null;
- }
- return __classPrivateFieldGet6(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message);
- }
- done() {
- return __classPrivateFieldGet6(this, _BetaToolRunner_completion, "f").promise;
- }
- async runUntilDone() {
- if (!__classPrivateFieldGet6(this, _BetaToolRunner_consumed, "f")) {
- for await (const _ of this) {}
- }
- return this.done();
- }
- get params() {
- return __classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params;
- }
- pushMessages(...messages) {
- this.setMessagesParams((params) => ({
- ...params,
- messages: [...params.messages, ...messages]
- }));
- }
- then(onfulfilled, onrejected) {
- return this.runUntilDone().then(onfulfilled, onrejected);
- }
- };
- _BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse2(lastMessage) {
- if (__classPrivateFieldGet6(this, _BetaToolRunner_toolResponse, "f") !== undefined) {
- return __classPrivateFieldGet6(this, _BetaToolRunner_toolResponse, "f");
- }
- __classPrivateFieldSet6(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet6(this, _BetaToolRunner_state, "f").params, lastMessage), "f");
- return __classPrivateFieldGet6(this, _BetaToolRunner_toolResponse, "f");
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs
-var JSONLDecoder2;
-var init_jsonl2 = __esm(() => {
- init_error3();
- init_line2();
- JSONLDecoder2 = class JSONLDecoder2 {
- constructor(iterator2, controller) {
- this.iterator = iterator2;
- this.controller = controller;
- }
- async* decoder() {
- const lineDecoder = new LineDecoder2;
- for await (const chunk of this.iterator) {
- for (const line of lineDecoder.decode(chunk)) {
- yield JSON.parse(line);
- }
- }
- for (const line of lineDecoder.flush()) {
- yield JSON.parse(line);
- }
- }
- [Symbol.asyncIterator]() {
- return this.decoder();
- }
- static fromResponse(response5, controller) {
- if (!response5.body) {
- controller.abort();
- if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
- throw new AnthropicError2(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
- }
- throw new AnthropicError2(`Attempted to iterate over a response with no body`);
- }
- return new JSONLDecoder2(ReadableStreamToAsyncIterable2(response5.body), controller);
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs
-var Batches3;
-var init_batches3 = __esm(() => {
- init_pagination8();
- init_headers();
- init_jsonl2();
- init_error4();
- init_path2();
- Batches3 = class Batches3 extends APIResource2 {
- create(params, options2) {
- const { betas, ...body } = params;
- return this._client.post("/v1/messages/batches?beta=true", {
- body,
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- retrieve(messageBatchID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path8`/v1/messages/batches/${messageBatchID}?beta=true`, {
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/messages/batches?beta=true", Page2, {
- query,
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- delete(messageBatchID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.delete(path8`/v1/messages/batches/${messageBatchID}?beta=true`, {
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- cancel(messageBatchID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.post(path8`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- async results(messageBatchID, params = {}, options2) {
- const batch = await this.retrieve(messageBatchID);
- if (!batch.results_url) {
- throw new AnthropicError2(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
- }
- const { betas } = params ?? {};
- return this._client.get(batch.results_url, {
- ...options2,
- headers: buildHeaders([
- {
- "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
- Accept: "application/binary"
- },
- options2?.headers
- ]),
- stream: true,
- __binaryResponse: true
- })._thenUnwrap((_, props) => JSONLDecoder2.fromResponse(props.response, props.controller));
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs
-function transformOutputFormat(params) {
- if (!params.output_format) {
- return params;
- }
- if (params.output_config?.format) {
- throw new AnthropicError2("Both output_format and output_config.format were provided. " + "Please use only output_config.format (output_format is deprecated).");
- }
- const { output_format, ...rest } = params;
- return {
- ...rest,
- output_config: {
- ...params.output_config,
- format: output_format
- }
- };
-}
-var DEPRECATED_MODELS3, MODELS_TO_WARN_WITH_THINKING_ENABLED, Messages4;
-var init_messages3 = __esm(() => {
- init_error4();
- init_constants5();
- init_headers();
- init_stainless_helper_header();
- init_beta_parser();
- init_BetaMessageStream2();
- init_BetaToolRunner();
- init_ToolError();
- init_batches3();
- init_batches3();
- init_BetaToolRunner();
- init_ToolError();
- DEPRECATED_MODELS3 = {
- "claude-1.3": "November 6th, 2024",
- "claude-1.3-100k": "November 6th, 2024",
- "claude-instant-1.1": "November 6th, 2024",
- "claude-instant-1.1-100k": "November 6th, 2024",
- "claude-instant-1.2": "November 6th, 2024",
- "claude-3-sonnet-20240229": "July 21st, 2025",
- "claude-3-opus-20240229": "January 5th, 2026",
- "claude-2.1": "July 21st, 2025",
- "claude-2.0": "July 21st, 2025",
- "claude-3-7-sonnet-latest": "February 19th, 2026",
- "claude-3-7-sonnet-20250219": "February 19th, 2026"
- };
- MODELS_TO_WARN_WITH_THINKING_ENABLED = ["claude-opus-4-6"];
- Messages4 = class Messages4 extends APIResource2 {
- constructor() {
- super(...arguments);
- this.batches = new Batches3(this._client);
- }
- create(params, options2) {
- const modifiedParams = transformOutputFormat(params);
- const { betas, ...body } = modifiedParams;
- if (body.model in DEPRECATED_MODELS3) {
- console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS3[body.model]}
-Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
- }
- if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED && body.thinking && body.thinking.type === "enabled") {
- console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
- }
- let timeout = this._client._options.timeout;
- if (!body.stream && timeout == null) {
- const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;
- timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
- }
- const helperHeader = stainlessHelperHeader(body.tools, body.messages);
- return this._client.post("/v1/messages?beta=true", {
- body,
- timeout: timeout ?? 600000,
- ...options2,
- headers: buildHeaders([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- helperHeader,
- options2?.headers
- ]),
- stream: modifiedParams.stream ?? false
- });
- }
- parse(params, options2) {
- options2 = {
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...params.betas ?? [], "structured-outputs-2025-12-15"].toString() },
- options2?.headers
- ])
- };
- return this.create(params, options2).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console }));
- }
- stream(body, options2) {
- return BetaMessageStream2.createMessage(this, body, options2);
- }
- countTokens(params, options2) {
- const modifiedParams = transformOutputFormat(params);
- const { betas, ...body } = modifiedParams;
- return this._client.post("/v1/messages/count_tokens?beta=true", {
- body,
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString() },
- options2?.headers
- ])
- });
- }
- toolRunner(body, options2) {
- return new BetaToolRunner(this._client, body, options2);
- }
- };
- Messages4.Batches = Batches3;
- Messages4.BetaToolRunner = BetaToolRunner;
- Messages4.ToolError = ToolError;
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs
-var Versions;
-var init_versions2 = __esm(() => {
- init_pagination8();
- init_headers();
- init_uploads2();
- init_path2();
- Versions = class Versions extends APIResource2 {
- create(skillID, params = {}, options2) {
- const { betas, ...body } = params ?? {};
- return this._client.post(path8`/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions({
- body,
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- }, this._client));
- }
- retrieve(version2, params, options2) {
- const { skill_id, betas } = params;
- return this._client.get(path8`/v1/skills/${skill_id}/versions/${version2}?beta=true`, {
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- list(skillID, params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList(path8`/v1/skills/${skillID}/versions?beta=true`, PageCursor, {
- query,
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- delete(version2, params, options2) {
- const { skill_id, betas } = params;
- return this._client.delete(path8`/v1/skills/${skill_id}/versions/${version2}?beta=true`, {
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs
-var Skills;
-var init_skills = __esm(() => {
- init_versions2();
- init_versions2();
- init_pagination8();
- init_headers();
- init_uploads2();
- init_path2();
- Skills = class Skills extends APIResource2 {
- constructor() {
- super(...arguments);
- this.versions = new Versions(this._client);
- }
- create(params = {}, options2) {
- const { betas, ...body } = params ?? {};
- return this._client.post("/v1/skills?beta=true", multipartFormRequestOptions({
- body,
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- }, this._client, false));
- }
- retrieve(skillID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path8`/v1/skills/${skillID}?beta=true`, {
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/skills?beta=true", PageCursor, {
- query,
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- delete(skillID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.delete(path8`/v1/skills/${skillID}?beta=true`, {
- ...options2,
- headers: buildHeaders([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- };
- Skills.Versions = Versions;
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs
-var Beta2;
-var init_beta2 = __esm(() => {
- init_files2();
- init_files2();
- init_models3();
- init_models3();
- init_messages3();
- init_messages3();
- init_skills();
- init_skills();
- Beta2 = class Beta2 extends APIResource2 {
- constructor() {
- super(...arguments);
- this.models = new Models3(this._client);
- this.messages = new Messages4(this._client);
- this.files = new Files(this._client);
- this.skills = new Skills(this._client);
- }
- };
- Beta2.Models = Models3;
- Beta2.Messages = Messages4;
- Beta2.Files = Files;
- Beta2.Skills = Skills;
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/completions.mjs
-var Completions2;
-var init_completions2 = __esm(() => {
- init_headers();
- Completions2 = class Completions2 extends APIResource2 {
- create(params, options2) {
- const { betas, ...body } = params;
- return this._client.post("/v1/complete", {
- body,
- timeout: this._client._options.timeout ?? 600000,
- ...options2,
- headers: buildHeaders([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ]),
- stream: params.stream ?? false
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/lib/parser.mjs
-function getOutputFormat2(params) {
- return params?.output_config?.format;
-}
-function maybeParseMessage(message, params, opts) {
- const outputFormat = getOutputFormat2(params);
- if (!params || !("parse" in (outputFormat ?? {}))) {
- return {
- ...message,
- content: message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: null,
- enumerable: false
- });
- return parsedBlock;
- }
- return block2;
- }),
- parsed_output: null
- };
- }
- return parseMessage(message, params, opts);
-}
-function parseMessage(message, params, opts) {
- let firstParsedOutput = null;
- const content = message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedOutput = parseOutputFormat(params, block2.text);
- if (firstParsedOutput === null) {
- firstParsedOutput = parsedOutput;
- }
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: parsedOutput,
- enumerable: false
- });
- return parsedBlock;
- }
- return block2;
- });
- return {
- ...message,
- content,
- parsed_output: firstParsedOutput
- };
-}
-function parseOutputFormat(params, content) {
- const outputFormat = getOutputFormat2(params);
- if (outputFormat?.type !== "json_schema") {
- return null;
- }
- try {
- if ("parse" in outputFormat) {
- return outputFormat.parse(content);
- }
- return JSON.parse(content);
- } catch (error41) {
- throw new AnthropicError2(`Failed to parse structured output: ${error41}`);
- }
-}
-var init_parser4 = __esm(() => {
- init_error3();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs
-function tracksToolInput2(content) {
- return content.type === "tool_use" || content.type === "server_tool_use";
-}
-function checkNever4(x3) {}
-var _MessageStream_instances2, _MessageStream_currentMessageSnapshot2, _MessageStream_params, _MessageStream_connectedPromise2, _MessageStream_resolveConnectedPromise2, _MessageStream_rejectConnectedPromise2, _MessageStream_endPromise2, _MessageStream_resolveEndPromise2, _MessageStream_rejectEndPromise2, _MessageStream_listeners2, _MessageStream_ended2, _MessageStream_errored2, _MessageStream_aborted2, _MessageStream_catchingPromiseCreated2, _MessageStream_response2, _MessageStream_request_id2, _MessageStream_logger, _MessageStream_getFinalMessage2, _MessageStream_getFinalText2, _MessageStream_handleError2, _MessageStream_beginRequest2, _MessageStream_addStreamEvent2, _MessageStream_endRequest2, _MessageStream_accumulateMessage2, JSON_BUF_PROPERTY4 = "__json_buf", MessageStream2;
-var init_MessageStream2 = __esm(() => {
- init_tslib();
- init_error4();
- init_streaming4();
- init_parser3();
- init_parser4();
- MessageStream2 = class MessageStream2 {
- constructor(params, opts) {
- _MessageStream_instances2.add(this);
- this.messages = [];
- this.receivedMessages = [];
- _MessageStream_currentMessageSnapshot2.set(this, undefined);
- _MessageStream_params.set(this, null);
- this.controller = new AbortController;
- _MessageStream_connectedPromise2.set(this, undefined);
- _MessageStream_resolveConnectedPromise2.set(this, () => {});
- _MessageStream_rejectConnectedPromise2.set(this, () => {});
- _MessageStream_endPromise2.set(this, undefined);
- _MessageStream_resolveEndPromise2.set(this, () => {});
- _MessageStream_rejectEndPromise2.set(this, () => {});
- _MessageStream_listeners2.set(this, {});
- _MessageStream_ended2.set(this, false);
- _MessageStream_errored2.set(this, false);
- _MessageStream_aborted2.set(this, false);
- _MessageStream_catchingPromiseCreated2.set(this, false);
- _MessageStream_response2.set(this, undefined);
- _MessageStream_request_id2.set(this, undefined);
- _MessageStream_logger.set(this, undefined);
- _MessageStream_handleError2.set(this, (error41) => {
- __classPrivateFieldSet6(this, _MessageStream_errored2, true, "f");
- if (isAbortError3(error41)) {
- error41 = new APIUserAbortError2;
- }
- if (error41 instanceof APIUserAbortError2) {
- __classPrivateFieldSet6(this, _MessageStream_aborted2, true, "f");
- return this._emit("abort", error41);
- }
- if (error41 instanceof AnthropicError2) {
- return this._emit("error", error41);
- }
- if (error41 instanceof Error) {
- const anthropicError = new AnthropicError2(error41.message);
- anthropicError.cause = error41;
- return this._emit("error", anthropicError);
- }
- return this._emit("error", new AnthropicError2(String(error41)));
- });
- __classPrivateFieldSet6(this, _MessageStream_connectedPromise2, new Promise((resolve9, reject) => {
- __classPrivateFieldSet6(this, _MessageStream_resolveConnectedPromise2, resolve9, "f");
- __classPrivateFieldSet6(this, _MessageStream_rejectConnectedPromise2, reject, "f");
- }), "f");
- __classPrivateFieldSet6(this, _MessageStream_endPromise2, new Promise((resolve9, reject) => {
- __classPrivateFieldSet6(this, _MessageStream_resolveEndPromise2, resolve9, "f");
- __classPrivateFieldSet6(this, _MessageStream_rejectEndPromise2, reject, "f");
- }), "f");
- __classPrivateFieldGet6(this, _MessageStream_connectedPromise2, "f").catch(() => {});
- __classPrivateFieldGet6(this, _MessageStream_endPromise2, "f").catch(() => {});
- __classPrivateFieldSet6(this, _MessageStream_params, params, "f");
- __classPrivateFieldSet6(this, _MessageStream_logger, opts?.logger ?? console, "f");
- }
- get response() {
- return __classPrivateFieldGet6(this, _MessageStream_response2, "f");
- }
- get request_id() {
- return __classPrivateFieldGet6(this, _MessageStream_request_id2, "f");
- }
- async withResponse() {
- __classPrivateFieldSet6(this, _MessageStream_catchingPromiseCreated2, true, "f");
- const response5 = await __classPrivateFieldGet6(this, _MessageStream_connectedPromise2, "f");
- if (!response5) {
- throw new Error("Could not resolve a `Response` object");
- }
- return {
- data: this,
- response: response5,
- request_id: response5.headers.get("request-id")
- };
- }
- static fromReadableStream(stream8) {
- const runner = new MessageStream2(null);
- runner._run(() => runner._fromReadableStream(stream8));
- return runner;
- }
- static createMessage(messages, params, options2, { logger: logger5 } = {}) {
- const runner = new MessageStream2(params, { logger: logger5 });
- for (const message of params.messages) {
- runner._addMessageParam(message);
- }
- __classPrivateFieldSet6(runner, _MessageStream_params, { ...params, stream: true }, "f");
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options2, headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" } }));
- return runner;
- }
- _run(executor) {
- executor().then(() => {
- this._emitFinal();
- this._emit("end");
- }, __classPrivateFieldGet6(this, _MessageStream_handleError2, "f"));
- }
- _addMessageParam(message) {
- this.messages.push(message);
- }
- _addMessage(message, emit = true) {
- this.receivedMessages.push(message);
- if (emit) {
- this._emit("message", message);
- }
- }
- async _createMessage(messages, params, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet6(this, _MessageStream_instances2, "m", _MessageStream_beginRequest2).call(this);
- const { response: response5, data: stream8 } = await messages.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal }).withResponse();
- this._connected(response5);
- for await (const event of stream8) {
- __classPrivateFieldGet6(this, _MessageStream_instances2, "m", _MessageStream_addStreamEvent2).call(this, event);
- }
- if (stream8.controller.signal?.aborted) {
- throw new APIUserAbortError2;
- }
- __classPrivateFieldGet6(this, _MessageStream_instances2, "m", _MessageStream_endRequest2).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- _connected(response5) {
- if (this.ended)
- return;
- __classPrivateFieldSet6(this, _MessageStream_response2, response5, "f");
- __classPrivateFieldSet6(this, _MessageStream_request_id2, response5?.headers.get("request-id"), "f");
- __classPrivateFieldGet6(this, _MessageStream_resolveConnectedPromise2, "f").call(this, response5);
- this._emit("connect");
- }
- get ended() {
- return __classPrivateFieldGet6(this, _MessageStream_ended2, "f");
- }
- get errored() {
- return __classPrivateFieldGet6(this, _MessageStream_errored2, "f");
- }
- get aborted() {
- return __classPrivateFieldGet6(this, _MessageStream_aborted2, "f");
- }
- abort() {
- this.controller.abort();
- }
- on(event, listener) {
- const listeners = __classPrivateFieldGet6(this, _MessageStream_listeners2, "f")[event] || (__classPrivateFieldGet6(this, _MessageStream_listeners2, "f")[event] = []);
- listeners.push({ listener });
- return this;
- }
- off(event, listener) {
- const listeners = __classPrivateFieldGet6(this, _MessageStream_listeners2, "f")[event];
- if (!listeners)
- return this;
- const index2 = listeners.findIndex((l4) => l4.listener === listener);
- if (index2 >= 0)
- listeners.splice(index2, 1);
- return this;
- }
- once(event, listener) {
- const listeners = __classPrivateFieldGet6(this, _MessageStream_listeners2, "f")[event] || (__classPrivateFieldGet6(this, _MessageStream_listeners2, "f")[event] = []);
- listeners.push({ listener, once: true });
- return this;
- }
- emitted(event) {
- return new Promise((resolve9, reject) => {
- __classPrivateFieldSet6(this, _MessageStream_catchingPromiseCreated2, true, "f");
- if (event !== "error")
- this.once("error", reject);
- this.once(event, resolve9);
- });
- }
- async done() {
- __classPrivateFieldSet6(this, _MessageStream_catchingPromiseCreated2, true, "f");
- await __classPrivateFieldGet6(this, _MessageStream_endPromise2, "f");
- }
- get currentMessage() {
- return __classPrivateFieldGet6(this, _MessageStream_currentMessageSnapshot2, "f");
- }
- async finalMessage() {
- await this.done();
- return __classPrivateFieldGet6(this, _MessageStream_instances2, "m", _MessageStream_getFinalMessage2).call(this);
- }
- async finalText() {
- await this.done();
- return __classPrivateFieldGet6(this, _MessageStream_instances2, "m", _MessageStream_getFinalText2).call(this);
- }
- _emit(event, ...args) {
- if (__classPrivateFieldGet6(this, _MessageStream_ended2, "f"))
- return;
- if (event === "end") {
- __classPrivateFieldSet6(this, _MessageStream_ended2, true, "f");
- __classPrivateFieldGet6(this, _MessageStream_resolveEndPromise2, "f").call(this);
- }
- const listeners = __classPrivateFieldGet6(this, _MessageStream_listeners2, "f")[event];
- if (listeners) {
- __classPrivateFieldGet6(this, _MessageStream_listeners2, "f")[event] = listeners.filter((l4) => !l4.once);
- listeners.forEach(({ listener }) => listener(...args));
- }
- if (event === "abort") {
- const error41 = args[0];
- if (!__classPrivateFieldGet6(this, _MessageStream_catchingPromiseCreated2, "f") && !listeners?.length) {
- Promise.reject(error41);
- }
- __classPrivateFieldGet6(this, _MessageStream_rejectConnectedPromise2, "f").call(this, error41);
- __classPrivateFieldGet6(this, _MessageStream_rejectEndPromise2, "f").call(this, error41);
- this._emit("end");
- return;
- }
- if (event === "error") {
- const error41 = args[0];
- if (!__classPrivateFieldGet6(this, _MessageStream_catchingPromiseCreated2, "f") && !listeners?.length) {
- Promise.reject(error41);
- }
- __classPrivateFieldGet6(this, _MessageStream_rejectConnectedPromise2, "f").call(this, error41);
- __classPrivateFieldGet6(this, _MessageStream_rejectEndPromise2, "f").call(this, error41);
- this._emit("end");
- }
- }
- _emitFinal() {
- const finalMessage = this.receivedMessages.at(-1);
- if (finalMessage) {
- this._emit("finalMessage", __classPrivateFieldGet6(this, _MessageStream_instances2, "m", _MessageStream_getFinalMessage2).call(this));
- }
- }
- async _fromReadableStream(readableStream, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet6(this, _MessageStream_instances2, "m", _MessageStream_beginRequest2).call(this);
- this._connected(null);
- const stream8 = Stream2.fromReadableStream(readableStream, this.controller);
- for await (const event of stream8) {
- __classPrivateFieldGet6(this, _MessageStream_instances2, "m", _MessageStream_addStreamEvent2).call(this, event);
- }
- if (stream8.controller.signal?.aborted) {
- throw new APIUserAbortError2;
- }
- __classPrivateFieldGet6(this, _MessageStream_instances2, "m", _MessageStream_endRequest2).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- [(_MessageStream_currentMessageSnapshot2 = new WeakMap, _MessageStream_params = new WeakMap, _MessageStream_connectedPromise2 = new WeakMap, _MessageStream_resolveConnectedPromise2 = new WeakMap, _MessageStream_rejectConnectedPromise2 = new WeakMap, _MessageStream_endPromise2 = new WeakMap, _MessageStream_resolveEndPromise2 = new WeakMap, _MessageStream_rejectEndPromise2 = new WeakMap, _MessageStream_listeners2 = new WeakMap, _MessageStream_ended2 = new WeakMap, _MessageStream_errored2 = new WeakMap, _MessageStream_aborted2 = new WeakMap, _MessageStream_catchingPromiseCreated2 = new WeakMap, _MessageStream_response2 = new WeakMap, _MessageStream_request_id2 = new WeakMap, _MessageStream_logger = new WeakMap, _MessageStream_handleError2 = new WeakMap, _MessageStream_instances2 = new WeakSet, _MessageStream_getFinalMessage2 = function _MessageStream_getFinalMessage3() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError2("stream ended without producing a Message with role=assistant");
- }
- return this.receivedMessages.at(-1);
- }, _MessageStream_getFinalText2 = function _MessageStream_getFinalText3() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError2("stream ended without producing a Message with role=assistant");
- }
- const textBlocks = this.receivedMessages.at(-1).content.filter((block2) => block2.type === "text").map((block2) => block2.text);
- if (textBlocks.length === 0) {
- throw new AnthropicError2("stream ended without producing a content block with type=text");
- }
- return textBlocks.join(" ");
- }, _MessageStream_beginRequest2 = function _MessageStream_beginRequest3() {
- if (this.ended)
- return;
- __classPrivateFieldSet6(this, _MessageStream_currentMessageSnapshot2, undefined, "f");
- }, _MessageStream_addStreamEvent2 = function _MessageStream_addStreamEvent3(event) {
- if (this.ended)
- return;
- const messageSnapshot = __classPrivateFieldGet6(this, _MessageStream_instances2, "m", _MessageStream_accumulateMessage2).call(this, event);
- this._emit("streamEvent", event, messageSnapshot);
- switch (event.type) {
- case "content_block_delta": {
- const content = messageSnapshot.content.at(-1);
- switch (event.delta.type) {
- case "text_delta": {
- if (content.type === "text") {
- this._emit("text", event.delta.text, content.text || "");
- }
- break;
- }
- case "citations_delta": {
- if (content.type === "text") {
- this._emit("citation", event.delta.citation, content.citations ?? []);
- }
- break;
- }
- case "input_json_delta": {
- if (tracksToolInput2(content) && content.input) {
- this._emit("inputJson", event.delta.partial_json, content.input);
- }
- break;
- }
- case "thinking_delta": {
- if (content.type === "thinking") {
- this._emit("thinking", event.delta.thinking, content.thinking);
- }
- break;
- }
- case "signature_delta": {
- if (content.type === "thinking") {
- this._emit("signature", content.signature);
- }
- break;
- }
- default:
- checkNever4(event.delta);
- }
- break;
- }
- case "message_stop": {
- this._addMessageParam(messageSnapshot);
- this._addMessage(maybeParseMessage(messageSnapshot, __classPrivateFieldGet6(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet6(this, _MessageStream_logger, "f") }), true);
- break;
- }
- case "content_block_stop": {
- this._emit("contentBlock", messageSnapshot.content.at(-1));
- break;
- }
- case "message_start": {
- __classPrivateFieldSet6(this, _MessageStream_currentMessageSnapshot2, messageSnapshot, "f");
- break;
- }
- case "content_block_start":
- case "message_delta":
- break;
- }
- }, _MessageStream_endRequest2 = function _MessageStream_endRequest3() {
- if (this.ended) {
- throw new AnthropicError2(`stream has ended, this shouldn't happen`);
- }
- const snapshot = __classPrivateFieldGet6(this, _MessageStream_currentMessageSnapshot2, "f");
- if (!snapshot) {
- throw new AnthropicError2(`request ended without sending any chunks`);
- }
- __classPrivateFieldSet6(this, _MessageStream_currentMessageSnapshot2, undefined, "f");
- return maybeParseMessage(snapshot, __classPrivateFieldGet6(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet6(this, _MessageStream_logger, "f") });
- }, _MessageStream_accumulateMessage2 = function _MessageStream_accumulateMessage3(event) {
- let snapshot = __classPrivateFieldGet6(this, _MessageStream_currentMessageSnapshot2, "f");
- if (event.type === "message_start") {
- if (snapshot) {
- throw new AnthropicError2(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
- }
- return event.message;
- }
- if (!snapshot) {
- throw new AnthropicError2(`Unexpected event order, got ${event.type} before "message_start"`);
- }
- switch (event.type) {
- case "message_stop":
- return snapshot;
- case "message_delta":
- snapshot.stop_reason = event.delta.stop_reason;
- snapshot.stop_sequence = event.delta.stop_sequence;
- snapshot.usage.output_tokens = event.usage.output_tokens;
- if (event.usage.input_tokens != null) {
- snapshot.usage.input_tokens = event.usage.input_tokens;
- }
- if (event.usage.cache_creation_input_tokens != null) {
- snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
- }
- if (event.usage.cache_read_input_tokens != null) {
- snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
- }
- if (event.usage.server_tool_use != null) {
- snapshot.usage.server_tool_use = event.usage.server_tool_use;
- }
- return snapshot;
- case "content_block_start":
- snapshot.content.push({ ...event.content_block });
- return snapshot;
- case "content_block_delta": {
- const snapshotContent = snapshot.content.at(event.index);
- switch (event.delta.type) {
- case "text_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- text: (snapshotContent.text || "") + event.delta.text
- };
- }
- break;
- }
- case "citations_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- citations: [...snapshotContent.citations ?? [], event.delta.citation]
- };
- }
- break;
- }
- case "input_json_delta": {
- if (snapshotContent && tracksToolInput2(snapshotContent)) {
- let jsonBuf = snapshotContent[JSON_BUF_PROPERTY4] || "";
- jsonBuf += event.delta.partial_json;
- const newContent = { ...snapshotContent };
- Object.defineProperty(newContent, JSON_BUF_PROPERTY4, {
- value: jsonBuf,
- enumerable: false,
- writable: true
- });
- if (jsonBuf) {
- newContent.input = partialParse2(jsonBuf);
- }
- snapshot.content[event.index] = newContent;
- }
- break;
- }
- case "thinking_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- thinking: snapshotContent.thinking + event.delta.thinking
- };
- }
- break;
- }
- case "signature_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- signature: event.delta.signature
- };
- }
- break;
- }
- default:
- checkNever4(event.delta);
- }
- return snapshot;
- }
- case "content_block_stop":
- return snapshot;
- }
- }, Symbol.asyncIterator)]() {
- const pushQueue = [];
- const readQueue = [];
- let done = false;
- this.on("streamEvent", (event) => {
- const reader = readQueue.shift();
- if (reader) {
- reader.resolve(event);
- } else {
- pushQueue.push(event);
- }
- });
- this.on("end", () => {
- done = true;
- for (const reader of readQueue) {
- reader.resolve(undefined);
- }
- readQueue.length = 0;
- });
- this.on("abort", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- this.on("error", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- return {
- next: async () => {
- if (!pushQueue.length) {
- if (done) {
- return { value: undefined, done: true };
- }
- return new Promise((resolve9, reject) => readQueue.push({ resolve: resolve9, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
- }
- const chunk = pushQueue.shift();
- return { value: chunk, done: false };
- },
- return: async () => {
- this.abort();
- return { value: undefined, done: true };
- }
- };
- }
- toReadableStream() {
- const stream8 = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
- return stream8.toReadableStream();
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs
-var Batches4;
-var init_batches4 = __esm(() => {
- init_pagination8();
- init_headers();
- init_jsonl2();
- init_error4();
- init_path2();
- Batches4 = class Batches4 extends APIResource2 {
- create(body, options2) {
- return this._client.post("/v1/messages/batches", { body, ...options2 });
- }
- retrieve(messageBatchID, options2) {
- return this._client.get(path8`/v1/messages/batches/${messageBatchID}`, options2);
- }
- list(query = {}, options2) {
- return this._client.getAPIList("/v1/messages/batches", Page2, { query, ...options2 });
- }
- delete(messageBatchID, options2) {
- return this._client.delete(path8`/v1/messages/batches/${messageBatchID}`, options2);
- }
- cancel(messageBatchID, options2) {
- return this._client.post(path8`/v1/messages/batches/${messageBatchID}/cancel`, options2);
- }
- async results(messageBatchID, options2) {
- const batch = await this.retrieve(messageBatchID);
- if (!batch.results_url) {
- throw new AnthropicError2(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
- }
- return this._client.get(batch.results_url, {
- ...options2,
- headers: buildHeaders([{ Accept: "application/binary" }, options2?.headers]),
- stream: true,
- __binaryResponse: true
- })._thenUnwrap((_, props) => JSONLDecoder2.fromResponse(props.response, props.controller));
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs
-var Messages5, DEPRECATED_MODELS4, MODELS_TO_WARN_WITH_THINKING_ENABLED2;
-var init_messages4 = __esm(() => {
- init_headers();
- init_stainless_helper_header();
- init_MessageStream2();
- init_parser4();
- init_batches4();
- init_batches4();
- init_constants5();
- Messages5 = class Messages5 extends APIResource2 {
- constructor() {
- super(...arguments);
- this.batches = new Batches4(this._client);
- }
- create(body, options2) {
- if (body.model in DEPRECATED_MODELS4) {
- console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS4[body.model]}
-Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
- }
- if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED2 && body.thinking && body.thinking.type === "enabled") {
- console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
- }
- let timeout = this._client._options.timeout;
- if (!body.stream && timeout == null) {
- const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;
- timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
- }
- const helperHeader = stainlessHelperHeader(body.tools, body.messages);
- return this._client.post("/v1/messages", {
- body,
- timeout: timeout ?? 600000,
- ...options2,
- headers: buildHeaders([helperHeader, options2?.headers]),
- stream: body.stream ?? false
- });
- }
- parse(params, options2) {
- return this.create(params, options2).then((message) => parseMessage(message, params, { logger: this._client.logger ?? console }));
- }
- stream(body, options2) {
- return MessageStream2.createMessage(this, body, options2, { logger: this._client.logger ?? console });
- }
- countTokens(body, options2) {
- return this._client.post("/v1/messages/count_tokens", { body, ...options2 });
- }
- };
- DEPRECATED_MODELS4 = {
- "claude-1.3": "November 6th, 2024",
- "claude-1.3-100k": "November 6th, 2024",
- "claude-instant-1.1": "November 6th, 2024",
- "claude-instant-1.1-100k": "November 6th, 2024",
- "claude-instant-1.2": "November 6th, 2024",
- "claude-3-sonnet-20240229": "July 21st, 2025",
- "claude-3-opus-20240229": "January 5th, 2026",
- "claude-2.1": "July 21st, 2025",
- "claude-2.0": "July 21st, 2025",
- "claude-3-7-sonnet-latest": "February 19th, 2026",
- "claude-3-7-sonnet-20250219": "February 19th, 2026",
- "claude-3-5-haiku-latest": "February 19th, 2026",
- "claude-3-5-haiku-20241022": "February 19th, 2026"
- };
- MODELS_TO_WARN_WITH_THINKING_ENABLED2 = ["claude-opus-4-6"];
- Messages5.Batches = Batches4;
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/models.mjs
-var Models4;
-var init_models4 = __esm(() => {
- init_pagination8();
- init_headers();
- init_path2();
- Models4 = class Models4 extends APIResource2 {
- retrieve(modelID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path8`/v1/models/${modelID}`, {
- ...options2,
- headers: buildHeaders([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/models", Page2, {
- query,
- ...options2,
- headers: buildHeaders([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/resources/index.mjs
-var init_resources2 = __esm(() => {
- init_beta2();
- init_completions2();
- init_messages4();
- init_models4();
- init_shared7();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs
-var readEnv2 = (env4) => {
- if (typeof globalThis.process !== "undefined") {
- return globalThis.process.env?.[env4]?.trim() ?? undefined;
- }
- if (typeof globalThis.Deno !== "undefined") {
- return globalThis.Deno.env?.get?.(env4)?.trim();
- }
- return;
-};
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/client.mjs
-class BaseAnthropic {
- constructor({ baseURL = readEnv2("ANTHROPIC_BASE_URL"), apiKey = readEnv2("ANTHROPIC_API_KEY") ?? null, authToken = readEnv2("ANTHROPIC_AUTH_TOKEN") ?? null, ...opts } = {}) {
- _BaseAnthropic_instances.add(this);
- _BaseAnthropic_encoder.set(this, undefined);
- const options2 = {
- apiKey,
- authToken,
- ...opts,
- baseURL: baseURL || `https://api.anthropic.com`
- };
- if (!options2.dangerouslyAllowBrowser && isRunningInBrowser2()) {
- throw new AnthropicError2(`It looks like you're running in a browser-like environment.
-
-This is disabled by default, as it risks exposing your secret API credentials to attackers.
-If you understand the risks and have appropriate mitigations in place,
-you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
-
-new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
-`);
- }
- this.baseURL = options2.baseURL;
- this.timeout = options2.timeout ?? _a5.DEFAULT_TIMEOUT;
- this.logger = options2.logger ?? console;
- const defaultLogLevel = "warn";
- this.logLevel = defaultLogLevel;
- this.logLevel = parseLogLevel(options2.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv2("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", this) ?? defaultLogLevel;
- this.fetchOptions = options2.fetchOptions;
- this.maxRetries = options2.maxRetries ?? 2;
- this.fetch = options2.fetch ?? getDefaultFetch();
- __classPrivateFieldSet6(this, _BaseAnthropic_encoder, FallbackEncoder, "f");
- this._options = options2;
- this.apiKey = typeof apiKey === "string" ? apiKey : null;
- this.authToken = authToken;
- }
- withOptions(options2) {
- const client9 = new this.constructor({
- ...this._options,
- baseURL: this.baseURL,
- maxRetries: this.maxRetries,
- timeout: this.timeout,
- logger: this.logger,
- logLevel: this.logLevel,
- fetch: this.fetch,
- fetchOptions: this.fetchOptions,
- apiKey: this.apiKey,
- authToken: this.authToken,
- ...options2
- });
- return client9;
- }
- defaultQuery() {
- return this._options.defaultQuery;
- }
- validateHeaders({ values, nulls }) {
- if (values.get("x-api-key") || values.get("authorization")) {
- return;
- }
- if (this.apiKey && values.get("x-api-key")) {
- return;
- }
- if (nulls.has("x-api-key")) {
- return;
- }
- if (this.authToken && values.get("authorization")) {
- return;
- }
- if (nulls.has("authorization")) {
- return;
- }
- throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
- }
- async authHeaders(opts) {
- return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
- }
- async apiKeyAuth(opts) {
- if (this.apiKey == null) {
- return;
- }
- return buildHeaders([{ "X-Api-Key": this.apiKey }]);
- }
- async bearerAuth(opts) {
- if (this.authToken == null) {
- return;
- }
- return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]);
- }
- stringifyQuery(query) {
- return stringifyQuery(query);
- }
- getUserAgent() {
- return `${this.constructor.name}/JS ${VERSION4}`;
- }
- defaultIdempotencyKey() {
- return `stainless-node-retry-${uuid43()}`;
- }
- makeStatusError(status, error41, message, headers) {
- return APIError2.generate(status, error41, message, headers);
- }
- buildURL(path9, query, defaultBaseURL) {
- const baseURL = !__classPrivateFieldGet6(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
- const url3 = isAbsoluteURL3(path9) ? new URL(path9) : new URL(baseURL + (baseURL.endsWith("/") && path9.startsWith("/") ? path9.slice(1) : path9));
- const defaultQuery = this.defaultQuery();
- const pathQuery = Object.fromEntries(url3.searchParams);
- if (!isEmptyObj2(defaultQuery) || !isEmptyObj2(pathQuery)) {
- query = { ...pathQuery, ...defaultQuery, ...query };
- }
- if (typeof query === "object" && query && !Array.isArray(query)) {
- url3.search = this.stringifyQuery(query);
- }
- return url3.toString();
- }
- _calculateNonstreamingTimeout(maxTokens) {
- const defaultTimeout = 10 * 60;
- const expectedTimeout = 60 * 60 * maxTokens / 128000;
- if (expectedTimeout > defaultTimeout) {
- throw new AnthropicError2("Streaming is required for operations that may take longer than 10 minutes. " + "See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");
- }
- return defaultTimeout * 1000;
- }
- async prepareOptions(options2) {}
- async prepareRequest(request2, { url: url3, options: options2 }) {}
- get(path9, opts) {
- return this.methodRequest("get", path9, opts);
- }
- post(path9, opts) {
- return this.methodRequest("post", path9, opts);
- }
- patch(path9, opts) {
- return this.methodRequest("patch", path9, opts);
- }
- put(path9, opts) {
- return this.methodRequest("put", path9, opts);
- }
- delete(path9, opts) {
- return this.methodRequest("delete", path9, opts);
- }
- methodRequest(method, path9, opts) {
- return this.request(Promise.resolve(opts).then((opts2) => {
- return { method, path: path9, ...opts2 };
- }));
- }
- request(options2, remainingRetries = null) {
- return new APIPromise2(this, this.makeRequest(options2, remainingRetries, undefined));
- }
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
- const options2 = await optionsInput;
- const maxRetries = options2.maxRetries ?? this.maxRetries;
- if (retriesRemaining == null) {
- retriesRemaining = maxRetries;
- }
- await this.prepareOptions(options2);
- const { req, url: url3, timeout } = await this.buildRequest(options2, {
- retryCount: maxRetries - retriesRemaining
- });
- await this.prepareRequest(req, { url: url3, options: options2 });
- const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
- const retryLogStr = retryOfRequestLogID === undefined ? "" : `, retryOf: ${retryOfRequestLogID}`;
- const startTime = Date.now();
- loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
- retryOfRequestLogID,
- method: options2.method,
- url: url3,
- options: options2,
- headers: req.headers
- }));
- if (options2.signal?.aborted) {
- throw new APIUserAbortError2;
- }
- const controller = new AbortController;
- const response5 = await this.fetchWithTimeout(url3, req, timeout, controller).catch(castToError2);
- const headersTime = Date.now();
- if (response5 instanceof globalThis.Error) {
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
- if (options2.signal?.aborted) {
- throw new APIUserAbortError2;
- }
- const isTimeout = isAbortError3(response5) || /timed? ?out/i.test(String(response5) + ("cause" in response5 ? String(response5.cause) : ""));
- if (retriesRemaining) {
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
- retryOfRequestLogID,
- url: url3,
- durationMs: headersTime - startTime,
- message: response5.message
- }));
- return this.retryRequest(options2, retriesRemaining, retryOfRequestLogID ?? requestLogID);
- }
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({
- retryOfRequestLogID,
- url: url3,
- durationMs: headersTime - startTime,
- message: response5.message
- }));
- if (isTimeout) {
- throw new APIConnectionTimeoutError2;
- }
- throw new APIConnectionError2({ cause: response5 });
- }
- const specialHeaders = [...response5.headers.entries()].filter(([name]) => name === "request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("");
- const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url3} ${response5.ok ? "succeeded" : "failed"} with status ${response5.status} in ${headersTime - startTime}ms`;
- if (!response5.ok) {
- const shouldRetry = await this.shouldRetry(response5);
- if (retriesRemaining && shouldRetry) {
- const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
- await CancelReadableStream(response5.body);
- loggerFor(this).info(`${responseInfo} - ${retryMessage2}`);
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({
- retryOfRequestLogID,
- url: response5.url,
- status: response5.status,
- headers: response5.headers,
- durationMs: headersTime - startTime
- }));
- return this.retryRequest(options2, retriesRemaining, retryOfRequestLogID ?? requestLogID, response5.headers);
- }
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
- const errText = await response5.text().catch((err2) => castToError2(err2).message);
- const errJSON = safeJSON2(errText);
- const errMessage = errJSON ? undefined : errText;
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
- retryOfRequestLogID,
- url: response5.url,
- status: response5.status,
- headers: response5.headers,
- message: errMessage,
- durationMs: Date.now() - startTime
- }));
- const err = this.makeStatusError(response5.status, errJSON, errMessage, response5.headers);
- throw err;
- }
- loggerFor(this).info(responseInfo);
- loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
- retryOfRequestLogID,
- url: response5.url,
- status: response5.status,
- headers: response5.headers,
- durationMs: headersTime - startTime
- }));
- return { response: response5, options: options2, controller, requestLogID, retryOfRequestLogID, startTime };
- }
- getAPIList(path9, Page3, opts) {
- return this.requestAPIList(Page3, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path9, ...opts2 })) : { method: "get", path: path9, ...opts });
- }
- requestAPIList(Page3, options2) {
- const request2 = this.makeRequest(options2, null, undefined);
- return new PagePromise2(this, request2, Page3);
- }
- async fetchWithTimeout(url3, init, ms, controller) {
- const { signal, method, ...options2 } = init || {};
- const abort5 = this._makeAbort(controller);
- if (signal)
- signal.addEventListener("abort", abort5, { once: true });
- const timeout = setTimeout(abort5, ms);
- const isReadableBody = globalThis.ReadableStream && options2.body instanceof globalThis.ReadableStream || typeof options2.body === "object" && options2.body !== null && Symbol.asyncIterator in options2.body;
- const fetchOptions = {
- signal: controller.signal,
- ...isReadableBody ? { duplex: "half" } : {},
- method: "GET",
- ...options2
- };
- if (method) {
- fetchOptions.method = method.toUpperCase();
- }
- try {
- return await this.fetch.call(undefined, url3, fetchOptions);
- } finally {
- clearTimeout(timeout);
- }
- }
- async shouldRetry(response5) {
- const shouldRetryHeader = response5.headers.get("x-should-retry");
- if (shouldRetryHeader === "true")
- return true;
- if (shouldRetryHeader === "false")
- return false;
- if (response5.status === 408)
- return true;
- if (response5.status === 409)
- return true;
- if (response5.status === 429)
- return true;
- if (response5.status >= 500)
- return true;
- return false;
- }
- async retryRequest(options2, retriesRemaining, requestLogID, responseHeaders) {
- let timeoutMillis;
- const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
- if (retryAfterMillisHeader) {
- const timeoutMs = parseFloat(retryAfterMillisHeader);
- if (!Number.isNaN(timeoutMs)) {
- timeoutMillis = timeoutMs;
- }
- }
- const retryAfterHeader = responseHeaders?.get("retry-after");
- if (retryAfterHeader && !timeoutMillis) {
- const timeoutSeconds = parseFloat(retryAfterHeader);
- if (!Number.isNaN(timeoutSeconds)) {
- timeoutMillis = timeoutSeconds * 1000;
- } else {
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
- }
- }
- if (timeoutMillis === undefined) {
- const maxRetries = options2.maxRetries ?? this.maxRetries;
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
- }
- await sleep2(timeoutMillis);
- return this.makeRequest(options2, retriesRemaining - 1, requestLogID);
- }
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
- const initialRetryDelay = 0.5;
- const maxRetryDelay = 8;
- const numRetries = maxRetries - retriesRemaining;
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
- const jitter = 1 - Math.random() * 0.25;
- return sleepSeconds * jitter * 1000;
- }
- calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
- const maxTime = 60 * 60 * 1000;
- const defaultTime = 60 * 10 * 1000;
- const expectedTime = maxTime * maxTokens / 128000;
- if (expectedTime > defaultTime || maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens) {
- throw new AnthropicError2("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");
- }
- return defaultTime;
- }
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
- const options2 = { ...inputOptions };
- const { method, path: path9, query, defaultBaseURL } = options2;
- const url3 = this.buildURL(path9, query, defaultBaseURL);
- if ("timeout" in options2)
- validatePositiveInteger2("timeout", options2.timeout);
- options2.timeout = options2.timeout ?? this.timeout;
- const { bodyHeaders, body } = this.buildBody({ options: options2 });
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
- const req = {
- method,
- headers: reqHeaders,
- ...options2.signal && { signal: options2.signal },
- ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
- ...body && { body },
- ...this.fetchOptions ?? {},
- ...options2.fetchOptions ?? {}
- };
- return { req, url: url3, timeout: options2.timeout };
- }
- async buildHeaders({ options: options2, method, bodyHeaders, retryCount }) {
- let idempotencyHeaders = {};
- if (this.idempotencyHeader && method !== "get") {
- if (!options2.idempotencyKey)
- options2.idempotencyKey = this.defaultIdempotencyKey();
- idempotencyHeaders[this.idempotencyHeader] = options2.idempotencyKey;
- }
- const headers = buildHeaders([
- idempotencyHeaders,
- {
- Accept: "application/json",
- "User-Agent": this.getUserAgent(),
- "X-Stainless-Retry-Count": String(retryCount),
- ...options2.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options2.timeout / 1000)) } : {},
- ...getPlatformHeaders2(),
- ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : undefined,
- "anthropic-version": "2023-06-01"
- },
- await this.authHeaders(options2),
- this._options.defaultHeaders,
- bodyHeaders,
- options2.headers
- ]);
- this.validateHeaders(headers);
- return headers.values;
- }
- _makeAbort(controller) {
- return () => controller.abort();
- }
- buildBody({ options: { body, headers: rawHeaders } }) {
- if (!body) {
- return { bodyHeaders: undefined, body: undefined };
- }
- const headers = buildHeaders([rawHeaders]);
- if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && headers.values.has("content-type") || globalThis.Blob && body instanceof globalThis.Blob || body instanceof FormData || body instanceof URLSearchParams || globalThis.ReadableStream && body instanceof globalThis.ReadableStream) {
- return { bodyHeaders: undefined, body };
- } else if (typeof body === "object" && ((Symbol.asyncIterator in body) || (Symbol.iterator in body) && ("next" in body) && typeof body.next === "function")) {
- return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
- } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
- return {
- bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
- body: this.stringifyQuery(body)
- };
- } else {
- return __classPrivateFieldGet6(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
- }
- }
-}
-var _BaseAnthropic_instances, _a5, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden, HUMAN_PROMPT = "\\n\\nHuman:", AI_PROMPT = "\\n\\nAssistant:", Anthropic2;
-var init_client10 = __esm(() => {
- init_tslib();
- init_values2();
- init_detect_platform();
- init_query();
- init_error3();
- init_pagination8();
- init_uploads3();
- init_resources2();
- init_api_promise();
- init_completions2();
- init_models4();
- init_beta2();
- init_messages4();
- init_detect_platform();
- init_headers();
- init_log3();
- init_values2();
- _a5 = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap, _BaseAnthropic_instances = new WeakSet, _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden2() {
- return this.baseURL !== "https://api.anthropic.com";
- };
- BaseAnthropic.Anthropic = _a5;
- BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT;
- BaseAnthropic.AI_PROMPT = AI_PROMPT;
- BaseAnthropic.DEFAULT_TIMEOUT = 600000;
- BaseAnthropic.AnthropicError = AnthropicError2;
- BaseAnthropic.APIError = APIError2;
- BaseAnthropic.APIConnectionError = APIConnectionError2;
- BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError2;
- BaseAnthropic.APIUserAbortError = APIUserAbortError2;
- BaseAnthropic.NotFoundError = NotFoundError2;
- BaseAnthropic.ConflictError = ConflictError2;
- BaseAnthropic.RateLimitError = RateLimitError2;
- BaseAnthropic.BadRequestError = BadRequestError2;
- BaseAnthropic.AuthenticationError = AuthenticationError2;
- BaseAnthropic.InternalServerError = InternalServerError2;
- BaseAnthropic.PermissionDeniedError = PermissionDeniedError2;
- BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError2;
- BaseAnthropic.toFile = toFile2;
- Anthropic2 = class Anthropic2 extends BaseAnthropic {
- constructor() {
- super(...arguments);
- this.completions = new Completions2(this);
- this.messages = new Messages5(this);
- this.models = new Models4(this);
- this.beta = new Beta2(this);
- }
- };
- Anthropic2.Completions = Completions2;
- Anthropic2.Messages = Messages5;
- Anthropic2.Models = Models4;
- Anthropic2.Beta = Beta2;
-});
-
-// node_modules/@aws-crypto/sha256-js/node_modules/tslib/tslib.js
-var require_tslib2 = __commonJS((exports, module) => {
- /*! *****************************************************************************
- Copyright (c) Microsoft Corporation.
-
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- PERFORMANCE OF THIS SOFTWARE.
- ***************************************************************************** */
- var __extends2;
- var __assign2;
- var __rest2;
- var __decorate2;
- var __param2;
- var __metadata2;
- var __awaiter2;
- var __generator2;
- var __exportStar2;
- var __values2;
- var __read2;
- var __spread2;
- var __spreadArrays2;
- var __await2;
- var __asyncGenerator2;
- var __asyncDelegator2;
- var __asyncValues2;
- var __makeTemplateObject2;
- var __importStar2;
- var __importDefault2;
- var __classPrivateFieldGet7;
- var __classPrivateFieldSet7;
- var __createBinding2;
- (function(factory2) {
- var root2 = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
- if (typeof define === "function" && define.amd) {
- define("tslib", ["exports"], function(exports2) {
- factory2(createExporter(root2, createExporter(exports2)));
- });
- } else if (typeof module === "object" && typeof exports === "object") {
- factory2(createExporter(root2, createExporter(exports)));
- } else {
- factory2(createExporter(root2));
- }
- function createExporter(exports2, previous) {
- if (exports2 !== root2) {
- if (typeof Object.create === "function") {
- Object.defineProperty(exports2, "__esModule", { value: true });
- } else {
- exports2.__esModule = true;
- }
- }
- return function(id, v4) {
- return exports2[id] = previous ? previous(id, v4) : v4;
- };
- }
- })(function(exporter) {
- var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
- d4.__proto__ = b4;
- } || function(d4, b4) {
- for (var p4 in b4)
- if (b4.hasOwnProperty(p4))
- d4[p4] = b4[p4];
- };
- __extends2 = function(d4, b4) {
- extendStatics(d4, b4);
- function __() {
- this.constructor = d4;
- }
- d4.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __);
- };
- __assign2 = Object.assign || function(t4) {
- for (var s4, i5 = 1, n5 = arguments.length;i5 < n5; i5++) {
- s4 = arguments[i5];
- for (var p4 in s4)
- if (Object.prototype.hasOwnProperty.call(s4, p4))
- t4[p4] = s4[p4];
- }
- return t4;
- };
- __rest2 = function(s4, e4) {
- var t4 = {};
- for (var p4 in s4)
- if (Object.prototype.hasOwnProperty.call(s4, p4) && e4.indexOf(p4) < 0)
- t4[p4] = s4[p4];
- if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i5 = 0, p4 = Object.getOwnPropertySymbols(s4);i5 < p4.length; i5++) {
- if (e4.indexOf(p4[i5]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p4[i5]))
- t4[p4[i5]] = s4[p4[i5]];
- }
- return t4;
- };
- __decorate2 = function(decorators, target, key, desc) {
- var c8 = arguments.length, r4 = c8 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
- r4 = Reflect.decorate(decorators, target, key, desc);
- else
- for (var i5 = decorators.length - 1;i5 >= 0; i5--)
- if (d4 = decorators[i5])
- r4 = (c8 < 3 ? d4(r4) : c8 > 3 ? d4(target, key, r4) : d4(target, key)) || r4;
- return c8 > 3 && r4 && Object.defineProperty(target, key, r4), r4;
- };
- __param2 = function(paramIndex, decorator) {
- return function(target, key) {
- decorator(target, key, paramIndex);
- };
- };
- __metadata2 = function(metadataKey, metadataValue) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
- return Reflect.metadata(metadataKey, metadataValue);
- };
- __awaiter2 = function(thisArg, _arguments, P, generator) {
- function adopt(value) {
- return value instanceof P ? value : new P(function(resolve9) {
- resolve9(value);
- });
- }
- return new (P || (P = Promise))(function(resolve9, reject) {
- function fulfilled(value) {
- try {
- step(generator.next(value));
- } catch (e4) {
- reject(e4);
- }
- }
- function rejected(value) {
- try {
- step(generator["throw"](value));
- } catch (e4) {
- reject(e4);
- }
- }
- function step(result) {
- result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected);
- }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- __generator2 = function(thisArg, body) {
- var _ = { label: 0, sent: function() {
- if (t4[0] & 1)
- throw t4[1];
- return t4[1];
- }, trys: [], ops: [] }, f4, y3, t4, g4;
- return g4 = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol === "function" && (g4[Symbol.iterator] = function() {
- return this;
- }), g4;
- function verb(n5) {
- return function(v4) {
- return step([n5, v4]);
- };
- }
- function step(op) {
- if (f4)
- throw new TypeError("Generator is already executing.");
- while (_)
- try {
- if (f4 = 1, y3 && (t4 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t4 = y3["return"]) && t4.call(y3), 0) : y3.next) && !(t4 = t4.call(y3, op[1])).done)
- return t4;
- if (y3 = 0, t4)
- op = [op[0] & 2, t4.value];
- switch (op[0]) {
- case 0:
- case 1:
- t4 = op;
- break;
- case 4:
- _.label++;
- return { value: op[1], done: false };
- case 5:
- _.label++;
- y3 = op[1];
- op = [0];
- continue;
- case 7:
- op = _.ops.pop();
- _.trys.pop();
- continue;
- default:
- if (!(t4 = _.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) {
- _ = 0;
- continue;
- }
- if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) {
- _.label = op[1];
- break;
- }
- if (op[0] === 6 && _.label < t4[1]) {
- _.label = t4[1];
- t4 = op;
- break;
- }
- if (t4 && _.label < t4[2]) {
- _.label = t4[2];
- _.ops.push(op);
- break;
- }
- if (t4[2])
- _.ops.pop();
- _.trys.pop();
- continue;
- }
- op = body.call(thisArg, _);
- } catch (e4) {
- op = [6, e4];
- y3 = 0;
- } finally {
- f4 = t4 = 0;
- }
- if (op[0] & 5)
- throw op[1];
- return { value: op[0] ? op[1] : undefined, done: true };
- }
- };
- __createBinding2 = function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- };
- __exportStar2 = function(m4, exports2) {
- for (var p4 in m4)
- if (p4 !== "default" && !exports2.hasOwnProperty(p4))
- exports2[p4] = m4[p4];
- };
- __values2 = function(o5) {
- var s4 = typeof Symbol === "function" && Symbol.iterator, m4 = s4 && o5[s4], i5 = 0;
- if (m4)
- return m4.call(o5);
- if (o5 && typeof o5.length === "number")
- return {
- next: function() {
- if (o5 && i5 >= o5.length)
- o5 = undefined;
- return { value: o5 && o5[i5++], done: !o5 };
- }
- };
- throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
- };
- __read2 = function(o5, n5) {
- var m4 = typeof Symbol === "function" && o5[Symbol.iterator];
- if (!m4)
- return o5;
- var i5 = m4.call(o5), r4, ar = [], e4;
- try {
- while ((n5 === undefined || n5-- > 0) && !(r4 = i5.next()).done)
- ar.push(r4.value);
- } catch (error41) {
- e4 = { error: error41 };
- } finally {
- try {
- if (r4 && !r4.done && (m4 = i5["return"]))
- m4.call(i5);
- } finally {
- if (e4)
- throw e4.error;
- }
- }
- return ar;
- };
- __spread2 = function() {
- for (var ar = [], i5 = 0;i5 < arguments.length; i5++)
- ar = ar.concat(__read2(arguments[i5]));
- return ar;
- };
- __spreadArrays2 = function() {
- for (var s4 = 0, i5 = 0, il = arguments.length;i5 < il; i5++)
- s4 += arguments[i5].length;
- for (var r4 = Array(s4), k4 = 0, i5 = 0;i5 < il; i5++)
- for (var a5 = arguments[i5], j4 = 0, jl = a5.length;j4 < jl; j4++, k4++)
- r4[k4] = a5[j4];
- return r4;
- };
- __await2 = function(v4) {
- return this instanceof __await2 ? (this.v = v4, this) : new __await2(v4);
- };
- __asyncGenerator2 = function(thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator)
- throw new TypeError("Symbol.asyncIterator is not defined.");
- var g4 = generator.apply(thisArg, _arguments || []), i5, q4 = [];
- return i5 = {}, verb("next"), verb("throw"), verb("return"), i5[Symbol.asyncIterator] = function() {
- return this;
- }, i5;
- function verb(n5) {
- if (g4[n5])
- i5[n5] = function(v4) {
- return new Promise(function(a5, b4) {
- q4.push([n5, v4, a5, b4]) > 1 || resume(n5, v4);
- });
- };
- }
- function resume(n5, v4) {
- try {
- step(g4[n5](v4));
- } catch (e4) {
- settle2(q4[0][3], e4);
- }
- }
- function step(r4) {
- r4.value instanceof __await2 ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle2(q4[0][2], r4);
- }
- function fulfill(value) {
- resume("next", value);
- }
- function reject(value) {
- resume("throw", value);
- }
- function settle2(f4, v4) {
- if (f4(v4), q4.shift(), q4.length)
- resume(q4[0][0], q4[0][1]);
- }
- };
- __asyncDelegator2 = function(o5) {
- var i5, p4;
- return i5 = {}, verb("next"), verb("throw", function(e4) {
- throw e4;
- }), verb("return"), i5[Symbol.iterator] = function() {
- return this;
- }, i5;
- function verb(n5, f4) {
- i5[n5] = o5[n5] ? function(v4) {
- return (p4 = !p4) ? { value: __await2(o5[n5](v4)), done: n5 === "return" } : f4 ? f4(v4) : v4;
- } : f4;
- }
- };
- __asyncValues2 = function(o5) {
- if (!Symbol.asyncIterator)
- throw new TypeError("Symbol.asyncIterator is not defined.");
- var m4 = o5[Symbol.asyncIterator], i5;
- return m4 ? m4.call(o5) : (o5 = typeof __values2 === "function" ? __values2(o5) : o5[Symbol.iterator](), i5 = {}, verb("next"), verb("throw"), verb("return"), i5[Symbol.asyncIterator] = function() {
- return this;
- }, i5);
- function verb(n5) {
- i5[n5] = o5[n5] && function(v4) {
- return new Promise(function(resolve9, reject) {
- v4 = o5[n5](v4), settle2(resolve9, reject, v4.done, v4.value);
- });
- };
- }
- function settle2(resolve9, reject, d4, v4) {
- Promise.resolve(v4).then(function(v5) {
- resolve9({ value: v5, done: d4 });
- }, reject);
- }
- };
- __makeTemplateObject2 = function(cooked, raw) {
- if (Object.defineProperty) {
- Object.defineProperty(cooked, "raw", { value: raw });
- } else {
- cooked.raw = raw;
- }
- return cooked;
- };
- __importStar2 = function(mod2) {
- if (mod2 && mod2.__esModule)
- return mod2;
- var result = {};
- if (mod2 != null) {
- for (var k4 in mod2)
- if (Object.hasOwnProperty.call(mod2, k4))
- result[k4] = mod2[k4];
- }
- result["default"] = mod2;
- return result;
- };
- __importDefault2 = function(mod2) {
- return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
- };
- __classPrivateFieldGet7 = function(receiver, privateMap) {
- if (!privateMap.has(receiver)) {
- throw new TypeError("attempted to get private field on non-instance");
- }
- return privateMap.get(receiver);
- };
- __classPrivateFieldSet7 = function(receiver, privateMap, value) {
- if (!privateMap.has(receiver)) {
- throw new TypeError("attempted to set private field on non-instance");
- }
- privateMap.set(receiver, value);
- return value;
- };
- exporter("__extends", __extends2);
- exporter("__assign", __assign2);
- exporter("__rest", __rest2);
- exporter("__decorate", __decorate2);
- exporter("__param", __param2);
- exporter("__metadata", __metadata2);
- exporter("__awaiter", __awaiter2);
- exporter("__generator", __generator2);
- exporter("__exportStar", __exportStar2);
- exporter("__createBinding", __createBinding2);
- exporter("__values", __values2);
- exporter("__read", __read2);
- exporter("__spread", __spread2);
- exporter("__spreadArrays", __spreadArrays2);
- exporter("__await", __await2);
- exporter("__asyncGenerator", __asyncGenerator2);
- exporter("__asyncDelegator", __asyncDelegator2);
- exporter("__asyncValues", __asyncValues2);
- exporter("__makeTemplateObject", __makeTemplateObject2);
- exporter("__importStar", __importStar2);
- exporter("__importDefault", __importDefault2);
- exporter("__classPrivateFieldGet", __classPrivateFieldGet7);
- exporter("__classPrivateFieldSet", __classPrivateFieldSet7);
- });
-});
-
-// node_modules/@aws-crypto/sha256-js/build/constants.js
-var require_constants2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.MAX_HASHABLE_LENGTH = exports.INIT = exports.KEY = exports.DIGEST_LENGTH = exports.BLOCK_SIZE = undefined;
- exports.BLOCK_SIZE = 64;
- exports.DIGEST_LENGTH = 32;
- exports.KEY = new Uint32Array([
- 1116352408,
- 1899447441,
- 3049323471,
- 3921009573,
- 961987163,
- 1508970993,
- 2453635748,
- 2870763221,
- 3624381080,
- 310598401,
- 607225278,
- 1426881987,
- 1925078388,
- 2162078206,
- 2614888103,
- 3248222580,
- 3835390401,
- 4022224774,
- 264347078,
- 604807628,
- 770255983,
- 1249150122,
- 1555081692,
- 1996064986,
- 2554220882,
- 2821834349,
- 2952996808,
- 3210313671,
- 3336571891,
- 3584528711,
- 113926993,
- 338241895,
- 666307205,
- 773529912,
- 1294757372,
- 1396182291,
- 1695183700,
- 1986661051,
- 2177026350,
- 2456956037,
- 2730485921,
- 2820302411,
- 3259730800,
- 3345764771,
- 3516065817,
- 3600352804,
- 4094571909,
- 275423344,
- 430227734,
- 506948616,
- 659060556,
- 883997877,
- 958139571,
- 1322822218,
- 1537002063,
- 1747873779,
- 1955562222,
- 2024104815,
- 2227730452,
- 2361852424,
- 2428436474,
- 2756734187,
- 3204031479,
- 3329325298
- ]);
- exports.INIT = [
- 1779033703,
- 3144134277,
- 1013904242,
- 2773480762,
- 1359893119,
- 2600822924,
- 528734635,
- 1541459225
- ];
- exports.MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1;
-});
-
-// node_modules/@aws-crypto/sha256-js/build/RawSha256.js
-var require_RawSha256 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.RawSha256 = undefined;
- var constants_1 = require_constants2();
- var RawSha256 = function() {
- function RawSha2562() {
- this.state = Int32Array.from(constants_1.INIT);
- this.temp = new Int32Array(64);
- this.buffer = new Uint8Array(64);
- this.bufferLength = 0;
- this.bytesHashed = 0;
- this.finished = false;
- }
- RawSha2562.prototype.update = function(data) {
- if (this.finished) {
- throw new Error("Attempted to update an already finished hash.");
- }
- var position2 = 0;
- var byteLength = data.byteLength;
- this.bytesHashed += byteLength;
- if (this.bytesHashed * 8 > constants_1.MAX_HASHABLE_LENGTH) {
- throw new Error("Cannot hash more than 2^53 - 1 bits");
- }
- while (byteLength > 0) {
- this.buffer[this.bufferLength++] = data[position2++];
- byteLength--;
- if (this.bufferLength === constants_1.BLOCK_SIZE) {
- this.hashBuffer();
- this.bufferLength = 0;
- }
- }
- };
- RawSha2562.prototype.digest = function() {
- if (!this.finished) {
- var bitsHashed = this.bytesHashed * 8;
- var bufferView = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);
- var undecoratedLength = this.bufferLength;
- bufferView.setUint8(this.bufferLength++, 128);
- if (undecoratedLength % constants_1.BLOCK_SIZE >= constants_1.BLOCK_SIZE - 8) {
- for (var i5 = this.bufferLength;i5 < constants_1.BLOCK_SIZE; i5++) {
- bufferView.setUint8(i5, 0);
- }
- this.hashBuffer();
- this.bufferLength = 0;
- }
- for (var i5 = this.bufferLength;i5 < constants_1.BLOCK_SIZE - 8; i5++) {
- bufferView.setUint8(i5, 0);
- }
- bufferView.setUint32(constants_1.BLOCK_SIZE - 8, Math.floor(bitsHashed / 4294967296), true);
- bufferView.setUint32(constants_1.BLOCK_SIZE - 4, bitsHashed);
- this.hashBuffer();
- this.finished = true;
- }
- var out = new Uint8Array(constants_1.DIGEST_LENGTH);
- for (var i5 = 0;i5 < 8; i5++) {
- out[i5 * 4] = this.state[i5] >>> 24 & 255;
- out[i5 * 4 + 1] = this.state[i5] >>> 16 & 255;
- out[i5 * 4 + 2] = this.state[i5] >>> 8 & 255;
- out[i5 * 4 + 3] = this.state[i5] >>> 0 & 255;
- }
- return out;
- };
- RawSha2562.prototype.hashBuffer = function() {
- var _a6 = this, buffer = _a6.buffer, state = _a6.state;
- var state0 = state[0], state1 = state[1], state2 = state[2], state3 = state[3], state4 = state[4], state5 = state[5], state6 = state[6], state7 = state[7];
- for (var i5 = 0;i5 < constants_1.BLOCK_SIZE; i5++) {
- if (i5 < 16) {
- this.temp[i5] = (buffer[i5 * 4] & 255) << 24 | (buffer[i5 * 4 + 1] & 255) << 16 | (buffer[i5 * 4 + 2] & 255) << 8 | buffer[i5 * 4 + 3] & 255;
- } else {
- var u5 = this.temp[i5 - 2];
- var t1_1 = (u5 >>> 17 | u5 << 15) ^ (u5 >>> 19 | u5 << 13) ^ u5 >>> 10;
- u5 = this.temp[i5 - 15];
- var t2_1 = (u5 >>> 7 | u5 << 25) ^ (u5 >>> 18 | u5 << 14) ^ u5 >>> 3;
- this.temp[i5] = (t1_1 + this.temp[i5 - 7] | 0) + (t2_1 + this.temp[i5 - 16] | 0);
- }
- var t1 = (((state4 >>> 6 | state4 << 26) ^ (state4 >>> 11 | state4 << 21) ^ (state4 >>> 25 | state4 << 7)) + (state4 & state5 ^ ~state4 & state6) | 0) + (state7 + (constants_1.KEY[i5] + this.temp[i5] | 0) | 0) | 0;
- var t22 = ((state0 >>> 2 | state0 << 30) ^ (state0 >>> 13 | state0 << 19) ^ (state0 >>> 22 | state0 << 10)) + (state0 & state1 ^ state0 & state2 ^ state1 & state2) | 0;
- state7 = state6;
- state6 = state5;
- state5 = state4;
- state4 = state3 + t1 | 0;
- state3 = state2;
- state2 = state1;
- state1 = state0;
- state0 = t1 + t22 | 0;
- }
- state[0] += state0;
- state[1] += state1;
- state[2] += state2;
- state[3] += state3;
- state[4] += state4;
- state[5] += state5;
- state[6] += state6;
- state[7] += state7;
- };
- return RawSha2562;
- }();
- exports.RawSha256 = RawSha256;
-});
-
-// node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js
-var require_pureJs = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.toUtf8 = exports.fromUtf8 = undefined;
- var fromUtf810 = (input) => {
- const bytes = [];
- for (let i5 = 0, len = input.length;i5 < len; i5++) {
- const value = input.charCodeAt(i5);
- if (value < 128) {
- bytes.push(value);
- } else if (value < 2048) {
- bytes.push(value >> 6 | 192, value & 63 | 128);
- } else if (i5 + 1 < input.length && (value & 64512) === 55296 && (input.charCodeAt(i5 + 1) & 64512) === 56320) {
- const surrogatePair = 65536 + ((value & 1023) << 10) + (input.charCodeAt(++i5) & 1023);
- bytes.push(surrogatePair >> 18 | 240, surrogatePair >> 12 & 63 | 128, surrogatePair >> 6 & 63 | 128, surrogatePair & 63 | 128);
- } else {
- bytes.push(value >> 12 | 224, value >> 6 & 63 | 128, value & 63 | 128);
- }
- }
- return Uint8Array.from(bytes);
- };
- exports.fromUtf8 = fromUtf810;
- var toUtf85 = (input) => {
- let decoded = "";
- for (let i5 = 0, len = input.length;i5 < len; i5++) {
- const byte = input[i5];
- if (byte < 128) {
- decoded += String.fromCharCode(byte);
- } else if (192 <= byte && byte < 224) {
- const nextByte = input[++i5];
- decoded += String.fromCharCode((byte & 31) << 6 | nextByte & 63);
- } else if (240 <= byte && byte < 365) {
- const surrogatePair = [byte, input[++i5], input[++i5], input[++i5]];
- const encoded = "%" + surrogatePair.map((byteValue) => byteValue.toString(16)).join("%");
- decoded += decodeURIComponent(encoded);
- } else {
- decoded += String.fromCharCode((byte & 15) << 12 | (input[++i5] & 63) << 6 | input[++i5] & 63);
- }
- }
- return decoded;
- };
- exports.toUtf8 = toUtf85;
-});
-
-// node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js
-var require_whatwgEncodingApi = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.toUtf8 = exports.fromUtf8 = undefined;
- function fromUtf810(input) {
- return new TextEncoder().encode(input);
- }
- exports.fromUtf8 = fromUtf810;
- function toUtf85(input) {
- return new TextDecoder("utf-8").decode(input);
- }
- exports.toUtf8 = toUtf85;
-});
-
-// node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js
-var require_dist_cjs89 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.toUtf8 = exports.fromUtf8 = undefined;
- var pureJs_1 = require_pureJs();
- var whatwgEncodingApi_1 = require_whatwgEncodingApi();
- var fromUtf810 = (input) => typeof TextEncoder === "function" ? (0, whatwgEncodingApi_1.fromUtf8)(input) : (0, pureJs_1.fromUtf8)(input);
- exports.fromUtf8 = fromUtf810;
- var toUtf85 = (input) => typeof TextDecoder === "function" ? (0, whatwgEncodingApi_1.toUtf8)(input) : (0, pureJs_1.toUtf8)(input);
- exports.toUtf8 = toUtf85;
-});
-
-// node_modules/@aws-crypto/util/build/convertToBuffer.js
-var require_convertToBuffer = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.convertToBuffer = undefined;
- var util_utf8_browser_1 = require_dist_cjs89();
- var fromUtf810 = typeof Buffer !== "undefined" && Buffer.from ? function(input) {
- return Buffer.from(input, "utf8");
- } : util_utf8_browser_1.fromUtf8;
- function convertToBuffer2(data) {
- if (data instanceof Uint8Array)
- return data;
- if (typeof data === "string") {
- return fromUtf810(data);
- }
- if (ArrayBuffer.isView(data)) {
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
- }
- return new Uint8Array(data);
- }
- exports.convertToBuffer = convertToBuffer2;
-});
-
-// node_modules/@aws-crypto/util/build/isEmptyData.js
-var require_isEmptyData = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isEmptyData = undefined;
- function isEmptyData2(data) {
- if (typeof data === "string") {
- return data.length === 0;
- }
- return data.byteLength === 0;
- }
- exports.isEmptyData = isEmptyData2;
-});
-
-// node_modules/@aws-crypto/util/build/numToUint8.js
-var require_numToUint8 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.numToUint8 = undefined;
- function numToUint82(num) {
- return new Uint8Array([
- (num & 4278190080) >> 24,
- (num & 16711680) >> 16,
- (num & 65280) >> 8,
- num & 255
- ]);
- }
- exports.numToUint8 = numToUint82;
-});
-
-// node_modules/@aws-crypto/util/build/uint32ArrayFrom.js
-var require_uint32ArrayFrom = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.uint32ArrayFrom = undefined;
- function uint32ArrayFrom2(a_lookUpTable2) {
- if (!Uint32Array.from) {
- var return_array = new Uint32Array(a_lookUpTable2.length);
- var a_index = 0;
- while (a_index < a_lookUpTable2.length) {
- return_array[a_index] = a_lookUpTable2[a_index];
- a_index += 1;
- }
- return return_array;
- }
- return Uint32Array.from(a_lookUpTable2);
- }
- exports.uint32ArrayFrom = uint32ArrayFrom2;
-});
-
-// node_modules/@aws-crypto/util/build/index.js
-var require_build = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = undefined;
- var convertToBuffer_1 = require_convertToBuffer();
- Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function() {
- return convertToBuffer_1.convertToBuffer;
- } });
- var isEmptyData_1 = require_isEmptyData();
- Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function() {
- return isEmptyData_1.isEmptyData;
- } });
- var numToUint8_1 = require_numToUint8();
- Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function() {
- return numToUint8_1.numToUint8;
- } });
- var uint32ArrayFrom_1 = require_uint32ArrayFrom();
- Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function() {
- return uint32ArrayFrom_1.uint32ArrayFrom;
- } });
-});
-
-// node_modules/@aws-crypto/sha256-js/build/jsSha256.js
-var require_jsSha256 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Sha256 = undefined;
- var tslib_1 = require_tslib2();
- var constants_1 = require_constants2();
- var RawSha256_1 = require_RawSha256();
- var util_1 = require_build();
- var Sha256 = function() {
- function Sha2562(secret) {
- this.secret = secret;
- this.hash = new RawSha256_1.RawSha256;
- this.reset();
- }
- Sha2562.prototype.update = function(toHash) {
- if ((0, util_1.isEmptyData)(toHash) || this.error) {
- return;
- }
- try {
- this.hash.update((0, util_1.convertToBuffer)(toHash));
- } catch (e4) {
- this.error = e4;
- }
- };
- Sha2562.prototype.digestSync = function() {
- if (this.error) {
- throw this.error;
- }
- if (this.outer) {
- if (!this.outer.finished) {
- this.outer.update(this.hash.digest());
- }
- return this.outer.digest();
- }
- return this.hash.digest();
- };
- Sha2562.prototype.digest = function() {
- return tslib_1.__awaiter(this, undefined, undefined, function() {
- return tslib_1.__generator(this, function(_a6) {
- return [2, this.digestSync()];
- });
- });
- };
- Sha2562.prototype.reset = function() {
- this.hash = new RawSha256_1.RawSha256;
- if (this.secret) {
- this.outer = new RawSha256_1.RawSha256;
- var inner = bufferFromSecret(this.secret);
- var outer = new Uint8Array(constants_1.BLOCK_SIZE);
- outer.set(inner);
- for (var i5 = 0;i5 < constants_1.BLOCK_SIZE; i5++) {
- inner[i5] ^= 54;
- outer[i5] ^= 92;
- }
- this.hash.update(inner);
- this.outer.update(outer);
- for (var i5 = 0;i5 < inner.byteLength; i5++) {
- inner[i5] = 0;
- }
- }
- };
- return Sha2562;
- }();
- exports.Sha256 = Sha256;
- function bufferFromSecret(secret) {
- var input = (0, util_1.convertToBuffer)(secret);
- if (input.byteLength > constants_1.BLOCK_SIZE) {
- var bufferHash = new RawSha256_1.RawSha256;
- bufferHash.update(input);
- input = bufferHash.digest();
- }
- var buffer = new Uint8Array(constants_1.BLOCK_SIZE);
- buffer.set(input);
- return buffer;
- }
-});
-
-// node_modules/@aws-crypto/sha256-js/build/index.js
-var require_build2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- var tslib_1 = require_tslib2();
- tslib_1.__exportStar(require_jsSha256(), exports);
-});
-// node_modules/@smithy/protocol-http/dist-es/extensions/index.js
-var init_extensions16 = () => {};
-
-// node_modules/@smithy/types/dist-es/abort.js
-var init_abort6 = () => {};
-
-// node_modules/@smithy/types/dist-es/auth/auth.js
-var HttpAuthLocation5;
-var init_auth9 = __esm(() => {
- (function(HttpAuthLocation6) {
- HttpAuthLocation6["HEADER"] = "header";
- HttpAuthLocation6["QUERY"] = "query";
- })(HttpAuthLocation5 || (HttpAuthLocation5 = {}));
-});
-
-// node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
-var HttpApiKeyAuthLocation5;
-var init_HttpApiKeyAuth5 = __esm(() => {
- (function(HttpApiKeyAuthLocation6) {
- HttpApiKeyAuthLocation6["HEADER"] = "header";
- HttpApiKeyAuthLocation6["QUERY"] = "query";
- })(HttpApiKeyAuthLocation5 || (HttpApiKeyAuthLocation5 = {}));
-});
-
-// node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js
-var init_HttpAuthScheme5 = () => {};
-
-// node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js
-var init_HttpAuthSchemeProvider5 = () => {};
-
-// node_modules/@smithy/types/dist-es/auth/HttpSigner.js
-var init_HttpSigner5 = () => {};
-
-// node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js
-var init_IdentityProviderConfig5 = () => {};
-
-// node_modules/@smithy/types/dist-es/auth/index.js
-var init_auth10 = __esm(() => {
- init_auth9();
- init_HttpApiKeyAuth5();
- init_HttpAuthScheme5();
- init_HttpAuthSchemeProvider5();
- init_HttpSigner5();
- init_IdentityProviderConfig5();
-});
-
-// node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js
-var init_blob_payload_input_types5 = () => {};
-
-// node_modules/@smithy/types/dist-es/checksum.js
-var init_checksum13 = () => {};
-
-// node_modules/@smithy/types/dist-es/client.js
-var init_client11 = () => {};
-
-// node_modules/@smithy/types/dist-es/command.js
-var init_command11 = () => {};
-
-// node_modules/@smithy/types/dist-es/connection/config.js
-var init_config6 = () => {};
-
-// node_modules/@smithy/types/dist-es/connection/manager.js
-var init_manager5 = () => {};
-
-// node_modules/@smithy/types/dist-es/connection/pool.js
-var init_pool5 = () => {};
-
-// node_modules/@smithy/types/dist-es/connection/index.js
-var init_connection5 = __esm(() => {
- init_config6();
- init_manager5();
- init_pool5();
-});
-
-// node_modules/@smithy/types/dist-es/crypto.js
-var init_crypto6 = () => {};
-
-// node_modules/@smithy/types/dist-es/encode.js
-var init_encode5 = () => {};
-
-// node_modules/@smithy/types/dist-es/endpoint.js
-var EndpointURLScheme5;
-var init_endpoint5 = __esm(() => {
- (function(EndpointURLScheme6) {
- EndpointURLScheme6["HTTP"] = "http";
- EndpointURLScheme6["HTTPS"] = "https";
- })(EndpointURLScheme5 || (EndpointURLScheme5 = {}));
-});
-
-// node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js
-var init_EndpointRuleObject5 = () => {};
-
-// node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js
-var init_ErrorRuleObject5 = () => {};
-
-// node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js
-var init_RuleSetObject5 = () => {};
-
-// node_modules/@smithy/types/dist-es/endpoints/shared.js
-var init_shared8 = () => {};
-
-// node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js
-var init_TreeRuleObject5 = () => {};
-
-// node_modules/@smithy/types/dist-es/endpoints/index.js
-var init_endpoints5 = __esm(() => {
- init_EndpointRuleObject5();
- init_ErrorRuleObject5();
- init_RuleSetObject5();
- init_shared8();
- init_TreeRuleObject5();
-});
-
-// node_modules/@smithy/types/dist-es/eventStream.js
-var init_eventStream5 = () => {};
-
-// node_modules/@smithy/types/dist-es/extensions/checksum.js
-var AlgorithmId5;
-var init_checksum14 = __esm(() => {
- (function(AlgorithmId6) {
- AlgorithmId6["MD5"] = "md5";
- AlgorithmId6["CRC32"] = "crc32";
- AlgorithmId6["CRC32C"] = "crc32c";
- AlgorithmId6["SHA1"] = "sha1";
- AlgorithmId6["SHA256"] = "sha256";
- })(AlgorithmId5 || (AlgorithmId5 = {}));
-});
-
-// node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js
-var init_defaultClientConfiguration5 = __esm(() => {
- init_checksum14();
-});
-
-// node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js
-var init_defaultExtensionConfiguration9 = () => {};
-
-// node_modules/@smithy/types/dist-es/extensions/index.js
-var init_extensions17 = __esm(() => {
- init_checksum14();
- init_defaultClientConfiguration5();
- init_defaultExtensionConfiguration9();
-});
-
-// node_modules/@smithy/types/dist-es/http.js
-var FieldPosition5;
-var init_http6 = __esm(() => {
- (function(FieldPosition6) {
- FieldPosition6[FieldPosition6["HEADER"] = 0] = "HEADER";
- FieldPosition6[FieldPosition6["TRAILER"] = 1] = "TRAILER";
- })(FieldPosition5 || (FieldPosition5 = {}));
-});
-
-// node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js
-var init_httpHandlerInitialization5 = () => {};
-
-// node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js
-var init_apiKeyIdentity5 = () => {};
-
-// node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js
-var init_awsCredentialIdentity5 = () => {};
-
-// node_modules/@smithy/types/dist-es/identity/identity.js
-var init_identity10 = () => {};
-
-// node_modules/@smithy/types/dist-es/identity/tokenIdentity.js
-var init_tokenIdentity5 = () => {};
-
-// node_modules/@smithy/types/dist-es/identity/index.js
-var init_identity11 = __esm(() => {
- init_apiKeyIdentity5();
- init_awsCredentialIdentity5();
- init_identity10();
- init_tokenIdentity5();
-});
-
-// node_modules/@smithy/types/dist-es/logger.js
-var init_logger5 = () => {};
-// node_modules/@smithy/types/dist-es/pagination.js
-var init_pagination9 = () => {};
-
-// node_modules/@smithy/types/dist-es/profile.js
-var IniSectionType5;
-var init_profile5 = __esm(() => {
- (function(IniSectionType6) {
- IniSectionType6["PROFILE"] = "profile";
- IniSectionType6["SSO_SESSION"] = "sso-session";
- IniSectionType6["SERVICES"] = "services";
- })(IniSectionType5 || (IniSectionType5 = {}));
-});
-
-// node_modules/@smithy/types/dist-es/response.js
-var init_response5 = () => {};
-
-// node_modules/@smithy/types/dist-es/retry.js
-var init_retry5 = () => {};
-
-// node_modules/@smithy/types/dist-es/serde.js
-var init_serde5 = () => {};
-
-// node_modules/@smithy/types/dist-es/shapes.js
-var init_shapes5 = () => {};
-
-// node_modules/@smithy/types/dist-es/signature.js
-var init_signature5 = () => {};
-
-// node_modules/@smithy/types/dist-es/stream.js
-var init_stream6 = () => {};
-
-// node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js
-var init_streaming_blob_common_types5 = () => {};
-
-// node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js
-var init_streaming_blob_payload_input_types5 = () => {};
-
-// node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js
-var init_streaming_blob_payload_output_types5 = () => {};
-
-// node_modules/@smithy/types/dist-es/transfer.js
-var RequestHandlerProtocol5;
-var init_transfer5 = __esm(() => {
- (function(RequestHandlerProtocol6) {
- RequestHandlerProtocol6["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol6["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol6["TDS_8_0"] = "tds/8.0";
- })(RequestHandlerProtocol5 || (RequestHandlerProtocol5 = {}));
-});
-
-// node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js
-var init_client_payload_blob_type_narrow5 = () => {};
-
-// node_modules/@smithy/types/dist-es/transform/no-undefined.js
-var init_no_undefined5 = () => {};
-
-// node_modules/@smithy/types/dist-es/transform/type-transform.js
-var init_type_transform5 = () => {};
-
-// node_modules/@smithy/types/dist-es/uri.js
-var init_uri5 = () => {};
-
-// node_modules/@smithy/types/dist-es/util.js
-var init_util7 = () => {};
-
-// node_modules/@smithy/types/dist-es/waiter.js
-var init_waiter5 = () => {};
-
-// node_modules/@smithy/types/dist-es/index.js
-var init_dist_es47 = __esm(() => {
- init_abort6();
- init_auth10();
- init_blob_payload_input_types5();
- init_checksum13();
- init_client11();
- init_command11();
- init_connection5();
- init_crypto6();
- init_encode5();
- init_endpoint5();
- init_endpoints5();
- init_eventStream5();
- init_extensions17();
- init_http6();
- init_httpHandlerInitialization5();
- init_identity11();
- init_logger5();
- init_pagination9();
- init_profile5();
- init_response5();
- init_retry5();
- init_serde5();
- init_shapes5();
- init_signature5();
- init_stream6();
- init_streaming_blob_common_types5();
- init_streaming_blob_payload_input_types5();
- init_streaming_blob_payload_output_types5();
- init_transfer5();
- init_client_payload_blob_type_narrow5();
- init_no_undefined5();
- init_type_transform5();
- init_uri5();
- init_util7();
- init_waiter5();
-});
-
-// node_modules/@smithy/protocol-http/dist-es/Field.js
-var init_Field8 = __esm(() => {
- init_dist_es47();
-});
-// node_modules/@smithy/protocol-http/dist-es/httpHandler.js
-var init_httpHandler8 = () => {};
-
-// node_modules/@smithy/protocol-http/dist-es/httpRequest.js
-class HttpRequest5 {
- constructor(options2) {
- this.method = options2.method || "GET";
- this.hostname = options2.hostname || "localhost";
- this.port = options2.port;
- this.query = options2.query || {};
- this.headers = options2.headers || {};
- this.body = options2.body;
- this.protocol = options2.protocol ? options2.protocol.slice(-1) !== ":" ? `${options2.protocol}:` : options2.protocol : "https:";
- this.path = options2.path ? options2.path.charAt(0) !== "/" ? `/${options2.path}` : options2.path : "/";
- this.username = options2.username;
- this.password = options2.password;
- this.fragment = options2.fragment;
- }
- static isInstance(request2) {
- if (!request2)
- return false;
- const req = request2;
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
- }
- clone() {
- const cloned = new HttpRequest5({
- ...this,
- headers: { ...this.headers }
- });
- if (cloned.query)
- cloned.query = cloneQuery5(cloned.query);
- return cloned;
- }
-}
-function cloneQuery5(query) {
- return Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
- }, {});
-}
-// node_modules/@smithy/protocol-http/dist-es/types.js
-var init_types13 = () => {};
-
-// node_modules/@smithy/protocol-http/dist-es/index.js
-var init_dist_es48 = __esm(() => {
- init_extensions16();
- init_Field8();
- init_httpHandler8();
- init_types13();
-});
-
-// node_modules/@smithy/util-hex-encoding/dist-es/index.js
-function fromHex2(encoded) {
- if (encoded.length % 2 !== 0) {
- throw new Error("Hex encoded strings must have an even number length");
- }
- const out = new Uint8Array(encoded.length / 2);
- for (let i5 = 0;i5 < encoded.length; i5 += 2) {
- const encodedByte = encoded.slice(i5, i5 + 2).toLowerCase();
- if (encodedByte in HEX_TO_SHORT2) {
- out[i5 / 2] = HEX_TO_SHORT2[encodedByte];
- } else {
- throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
- }
- }
- return out;
-}
-function toHex2(bytes) {
- let out = "";
- for (let i5 = 0;i5 < bytes.byteLength; i5++) {
- out += SHORT_TO_HEX2[bytes[i5]];
- }
- return out;
-}
-var SHORT_TO_HEX2, HEX_TO_SHORT2;
-var init_dist_es49 = __esm(() => {
- SHORT_TO_HEX2 = {};
- HEX_TO_SHORT2 = {};
- for (let i5 = 0;i5 < 256; i5++) {
- let encodedByte = i5.toString(16).toLowerCase();
- if (encodedByte.length === 1) {
- encodedByte = `0${encodedByte}`;
- }
- SHORT_TO_HEX2[i5] = encodedByte;
- HEX_TO_SHORT2[encodedByte] = i5;
- }
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/abort.js
-var init_abort7 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/auth/auth.js
-var HttpAuthLocation6;
-var init_auth11 = __esm(() => {
- (function(HttpAuthLocation7) {
- HttpAuthLocation7["HEADER"] = "header";
- HttpAuthLocation7["QUERY"] = "query";
- })(HttpAuthLocation6 || (HttpAuthLocation6 = {}));
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
-var HttpApiKeyAuthLocation6;
-var init_HttpApiKeyAuth6 = __esm(() => {
- (function(HttpApiKeyAuthLocation7) {
- HttpApiKeyAuthLocation7["HEADER"] = "header";
- HttpApiKeyAuthLocation7["QUERY"] = "query";
- })(HttpApiKeyAuthLocation6 || (HttpApiKeyAuthLocation6 = {}));
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js
-var init_HttpAuthScheme6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js
-var init_HttpAuthSchemeProvider6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/auth/HttpSigner.js
-var init_HttpSigner6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js
-var init_IdentityProviderConfig6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/auth/index.js
-var init_auth12 = __esm(() => {
- init_auth11();
- init_HttpApiKeyAuth6();
- init_HttpAuthScheme6();
- init_HttpAuthSchemeProvider6();
- init_HttpSigner6();
- init_IdentityProviderConfig6();
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js
-var init_blob_payload_input_types6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/checksum.js
-var init_checksum15 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/client.js
-var init_client12 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/command.js
-var init_command12 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/connection/config.js
-var init_config7 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/connection/manager.js
-var init_manager6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/connection/pool.js
-var init_pool6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/connection/index.js
-var init_connection6 = __esm(() => {
- init_config7();
- init_manager6();
- init_pool6();
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/crypto.js
-var init_crypto7 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/encode.js
-var init_encode6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/endpoint.js
-var EndpointURLScheme6;
-var init_endpoint6 = __esm(() => {
- (function(EndpointURLScheme7) {
- EndpointURLScheme7["HTTP"] = "http";
- EndpointURLScheme7["HTTPS"] = "https";
- })(EndpointURLScheme6 || (EndpointURLScheme6 = {}));
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js
-var init_EndpointRuleObject6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js
-var init_ErrorRuleObject6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js
-var init_RuleSetObject6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/endpoints/shared.js
-var init_shared9 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js
-var init_TreeRuleObject6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/endpoints/index.js
-var init_endpoints6 = __esm(() => {
- init_EndpointRuleObject6();
- init_ErrorRuleObject6();
- init_RuleSetObject6();
- init_shared9();
- init_TreeRuleObject6();
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/eventStream.js
-var init_eventStream6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/extensions/checksum.js
-var AlgorithmId6;
-var init_checksum16 = __esm(() => {
- (function(AlgorithmId7) {
- AlgorithmId7["MD5"] = "md5";
- AlgorithmId7["CRC32"] = "crc32";
- AlgorithmId7["CRC32C"] = "crc32c";
- AlgorithmId7["SHA1"] = "sha1";
- AlgorithmId7["SHA256"] = "sha256";
- })(AlgorithmId6 || (AlgorithmId6 = {}));
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js
-var init_defaultClientConfiguration6 = __esm(() => {
- init_checksum16();
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js
-var init_defaultExtensionConfiguration10 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/extensions/index.js
-var init_extensions18 = __esm(() => {
- init_checksum16();
- init_defaultClientConfiguration6();
- init_defaultExtensionConfiguration10();
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/feature-ids.js
-var init_feature_ids5 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/http.js
-var FieldPosition6;
-var init_http7 = __esm(() => {
- (function(FieldPosition7) {
- FieldPosition7[FieldPosition7["HEADER"] = 0] = "HEADER";
- FieldPosition7[FieldPosition7["TRAILER"] = 1] = "TRAILER";
- })(FieldPosition6 || (FieldPosition6 = {}));
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js
-var init_httpHandlerInitialization6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js
-var init_apiKeyIdentity6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js
-var init_awsCredentialIdentity6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/identity/identity.js
-var init_identity12 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js
-var init_tokenIdentity6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/identity/index.js
-var init_identity13 = __esm(() => {
- init_apiKeyIdentity6();
- init_awsCredentialIdentity6();
- init_identity12();
- init_tokenIdentity6();
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/logger.js
-var init_logger6 = () => {};
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/pagination.js
-var init_pagination10 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/profile.js
-var IniSectionType6;
-var init_profile6 = __esm(() => {
- (function(IniSectionType7) {
- IniSectionType7["PROFILE"] = "profile";
- IniSectionType7["SSO_SESSION"] = "sso-session";
- IniSectionType7["SERVICES"] = "services";
- })(IniSectionType6 || (IniSectionType6 = {}));
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/response.js
-var init_response6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/retry.js
-var init_retry6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/serde.js
-var init_serde6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/shapes.js
-var init_shapes6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/signature.js
-var init_signature6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/stream.js
-var init_stream7 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js
-var init_streaming_blob_common_types6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js
-var init_streaming_blob_payload_input_types6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js
-var init_streaming_blob_payload_output_types6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/transfer.js
-var RequestHandlerProtocol6;
-var init_transfer6 = __esm(() => {
- (function(RequestHandlerProtocol7) {
- RequestHandlerProtocol7["HTTP_0_9"] = "http/0.9";
- RequestHandlerProtocol7["HTTP_1_0"] = "http/1.0";
- RequestHandlerProtocol7["TDS_8_0"] = "tds/8.0";
- })(RequestHandlerProtocol6 || (RequestHandlerProtocol6 = {}));
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js
-var init_client_payload_blob_type_narrow6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/transform/no-undefined.js
-var init_no_undefined6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/transform/type-transform.js
-var init_type_transform6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/uri.js
-var init_uri6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/util.js
-var init_util8 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/waiter.js
-var init_waiter6 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-es/index.js
-var init_dist_es50 = __esm(() => {
- init_abort7();
- init_auth12();
- init_blob_payload_input_types6();
- init_checksum15();
- init_client12();
- init_command12();
- init_connection6();
- init_crypto7();
- init_encode6();
- init_endpoint6();
- init_endpoints6();
- init_eventStream6();
- init_extensions18();
- init_feature_ids5();
- init_http7();
- init_httpHandlerInitialization6();
- init_identity13();
- init_logger6();
- init_pagination10();
- init_profile6();
- init_response6();
- init_retry6();
- init_serde6();
- init_shapes6();
- init_signature6();
- init_stream7();
- init_streaming_blob_common_types6();
- init_streaming_blob_payload_input_types6();
- init_streaming_blob_payload_output_types6();
- init_transfer6();
- init_client_payload_blob_type_narrow6();
- init_no_undefined6();
- init_type_transform6();
- init_uri6();
- init_util8();
- init_waiter6();
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js
-var init_getSmithyContext = __esm(() => {
- init_dist_es50();
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js
-var normalizeProvider5 = (input) => {
- if (typeof input === "function")
- return input;
- const promisified = Promise.resolve(input);
- return () => promisified;
-};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware/dist-es/index.js
-var init_dist_es51 = __esm(() => {
- init_getSmithyContext();
-});
-
-// node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js
-var escapeUri = (uri7) => encodeURIComponent(uri7).replace(/[!'()*]/g, hexEncode), hexEncode = (c8) => `%${c8.charCodeAt(0).toString(16).toUpperCase()}`;
-
-// node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js
-var init_escape_uri_path = () => {};
-
-// node_modules/@smithy/util-uri-escape/dist-es/index.js
-var init_dist_es52 = __esm(() => {
- init_escape_uri_path();
-});
-
-// node_modules/@smithy/is-array-buffer/dist-es/index.js
-var isArrayBuffer7 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-es/index.js
-import { Buffer as Buffer12 } from "buffer";
-var fromString5 = (input, encoding) => {
- if (typeof input !== "string") {
- throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
- }
- return encoding ? Buffer12.from(input, encoding) : Buffer12.from(input);
-};
-var init_dist_es53 = () => {};
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js
-var fromUtf810 = (input) => {
- const buf = fromString5(input, "utf8");
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
-};
-var init_fromUtf82 = __esm(() => {
- init_dist_es53();
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
-var toUint8Array2 = (data) => {
- if (typeof data === "string") {
- return fromUtf810(data);
- }
- if (ArrayBuffer.isView(data)) {
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
- }
- return new Uint8Array(data);
-};
-var init_toUint8Array2 = __esm(() => {
- init_fromUtf82();
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-es/toUtf8.js
-var init_toUtf82 = __esm(() => {
- init_dist_es53();
-});
-
-// node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-es/index.js
-var init_dist_es54 = __esm(() => {
- init_fromUtf82();
- init_toUint8Array2();
- init_toUtf82();
-});
-
-// node_modules/@smithy/signature-v4/dist-es/constants.js
-var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm", CREDENTIAL_QUERY_PARAM = "X-Amz-Credential", AMZ_DATE_QUERY_PARAM = "X-Amz-Date", SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders", EXPIRES_QUERY_PARAM = "X-Amz-Expires", SIGNATURE_QUERY_PARAM = "X-Amz-Signature", TOKEN_QUERY_PARAM = "X-Amz-Security-Token", AUTH_HEADER = "authorization", AMZ_DATE_HEADER, DATE_HEADER = "date", GENERATED_HEADERS, SIGNATURE_HEADER, SHA256_HEADER = "x-amz-content-sha256", TOKEN_HEADER, ALWAYS_UNSIGNABLE_HEADERS, PROXY_HEADER_PATTERN, SEC_HEADER_PATTERN, ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256", EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD", UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD", MAX_CACHE_SIZE = 50, KEY_TYPE_IDENTIFIER = "aws4_request", MAX_PRESIGNED_TTL;
-var init_constants6 = __esm(() => {
- AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();
- GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER];
- SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();
- TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();
- ALWAYS_UNSIGNABLE_HEADERS = {
- authorization: true,
- "cache-control": true,
- connection: true,
- expect: true,
- from: true,
- "keep-alive": true,
- "max-forwards": true,
- pragma: true,
- referer: true,
- te: true,
- trailer: true,
- "transfer-encoding": true,
- upgrade: true,
- "user-agent": true,
- "x-amzn-trace-id": true
- };
- PROXY_HEADER_PATTERN = /^proxy-/;
- SEC_HEADER_PATTERN = /^sec-/;
- MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;
-});
-
-// node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js
-var signingKeyCache, cacheQueue, createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => {
- const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId);
- const cacheKey = `${shortDate}:${region}:${service}:${toHex2(credsHash)}:${credentials.sessionToken}`;
- if (cacheKey in signingKeyCache) {
- return signingKeyCache[cacheKey];
- }
- cacheQueue.push(cacheKey);
- while (cacheQueue.length > MAX_CACHE_SIZE) {
- delete signingKeyCache[cacheQueue.shift()];
- }
- let key = `AWS4${credentials.secretAccessKey}`;
- for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) {
- key = await hmac(sha256Constructor, key, signable);
- }
- return signingKeyCache[cacheKey] = key;
-}, hmac = (ctor, secret, data) => {
- const hash2 = new ctor(secret);
- hash2.update(toUint8Array2(data));
- return hash2.digest();
-};
-var init_credentialDerivation = __esm(() => {
- init_dist_es49();
- init_dist_es54();
- init_constants6();
- signingKeyCache = {};
- cacheQueue = [];
-});
-
-// node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js
-var getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => {
- const canonical = {};
- for (const headerName of Object.keys(headers).sort()) {
- if (headers[headerName] == undefined) {
- continue;
- }
- const canonicalHeaderName = headerName.toLowerCase();
- if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) {
- if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) {
- continue;
- }
- }
- canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " ");
- }
- return canonical;
-};
-var init_getCanonicalHeaders = __esm(() => {
- init_constants6();
-});
-
-// node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js
-var getCanonicalQuery = ({ query = {} }) => {
- const keys2 = [];
- const serialized = {};
- for (const key of Object.keys(query).sort()) {
- if (key.toLowerCase() === SIGNATURE_HEADER) {
- continue;
- }
- keys2.push(key);
- const value = query[key];
- if (typeof value === "string") {
- serialized[key] = `${escapeUri(key)}=${escapeUri(value)}`;
- } else if (Array.isArray(value)) {
- serialized[key] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${escapeUri(key)}=${escapeUri(value2)}`]), []).sort().join("&");
- }
- }
- return keys2.map((key) => serialized[key]).filter((serialized2) => serialized2).join("&");
-};
-var init_getCanonicalQuery = __esm(() => {
- init_dist_es52();
- init_constants6();
-});
-
-// node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js
-var getPayloadHash = async ({ headers, body }, hashConstructor) => {
- for (const headerName of Object.keys(headers)) {
- if (headerName.toLowerCase() === SHA256_HEADER) {
- return headers[headerName];
- }
- }
- if (body == undefined) {
- return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
- } else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer7(body)) {
- const hashCtor = new hashConstructor;
- hashCtor.update(toUint8Array2(body));
- return toHex2(await hashCtor.digest());
- }
- return UNSIGNED_PAYLOAD;
-};
-var init_getPayloadHash = __esm(() => {
- init_dist_es49();
- init_dist_es54();
- init_constants6();
-});
-
-// node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js
-class HeaderFormatter {
- format(headers) {
- const chunks = [];
- for (const headerName of Object.keys(headers)) {
- const bytes = fromUtf810(headerName);
- chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
- }
- const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
- let position2 = 0;
- for (const chunk of chunks) {
- out.set(chunk, position2);
- position2 += chunk.byteLength;
- }
- return out;
- }
- formatHeaderValue(header) {
- switch (header.type) {
- case "boolean":
- return Uint8Array.from([header.value ? 0 : 1]);
- case "byte":
- return Uint8Array.from([2, header.value]);
- case "short":
- const shortView = new DataView(new ArrayBuffer(3));
- shortView.setUint8(0, 3);
- shortView.setInt16(1, header.value, false);
- return new Uint8Array(shortView.buffer);
- case "integer":
- const intView = new DataView(new ArrayBuffer(5));
- intView.setUint8(0, 4);
- intView.setInt32(1, header.value, false);
- return new Uint8Array(intView.buffer);
- case "long":
- const longBytes = new Uint8Array(9);
- longBytes[0] = 5;
- longBytes.set(header.value.bytes, 1);
- return longBytes;
- case "binary":
- const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
- binView.setUint8(0, 6);
- binView.setUint16(1, header.value.byteLength, false);
- const binBytes = new Uint8Array(binView.buffer);
- binBytes.set(header.value, 3);
- return binBytes;
- case "string":
- const utf8Bytes = fromUtf810(header.value);
- const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
- strView.setUint8(0, 7);
- strView.setUint16(1, utf8Bytes.byteLength, false);
- const strBytes = new Uint8Array(strView.buffer);
- strBytes.set(utf8Bytes, 3);
- return strBytes;
- case "timestamp":
- const tsBytes = new Uint8Array(9);
- tsBytes[0] = 8;
- tsBytes.set(Int643.fromNumber(header.value.valueOf()).bytes, 1);
- return tsBytes;
- case "uuid":
- if (!UUID_PATTERN2.test(header.value)) {
- throw new Error(`Invalid UUID received: ${header.value}`);
- }
- const uuidBytes = new Uint8Array(17);
- uuidBytes[0] = 9;
- uuidBytes.set(fromHex2(header.value.replace(/\-/g, "")), 1);
- return uuidBytes;
- }
- }
-}
-
-class Int643 {
- constructor(bytes) {
- this.bytes = bytes;
- if (bytes.byteLength !== 8) {
- throw new Error("Int64 buffers must be exactly 8 bytes");
- }
- }
- static fromNumber(number4) {
- if (number4 > 9223372036854776000 || number4 < -9223372036854776000) {
- throw new Error(`${number4} is too large (or, if negative, too small) to represent as an Int64`);
- }
- const bytes = new Uint8Array(8);
- for (let i5 = 7, remaining = Math.abs(Math.round(number4));i5 > -1 && remaining > 0; i5--, remaining /= 256) {
- bytes[i5] = remaining;
- }
- if (number4 < 0) {
- negate2(bytes);
- }
- return new Int643(bytes);
- }
- valueOf() {
- const bytes = this.bytes.slice(0);
- const negative = bytes[0] & 128;
- if (negative) {
- negate2(bytes);
- }
- return parseInt(toHex2(bytes), 16) * (negative ? -1 : 1);
- }
- toString() {
- return String(this.valueOf());
- }
-}
-function negate2(bytes) {
- for (let i5 = 0;i5 < 8; i5++) {
- bytes[i5] ^= 255;
- }
- for (let i5 = 7;i5 > -1; i5--) {
- bytes[i5]++;
- if (bytes[i5] !== 0)
- break;
- }
-}
-var HEADER_VALUE_TYPE2, UUID_PATTERN2;
-var init_HeaderFormatter = __esm(() => {
- init_dist_es49();
- init_dist_es54();
- (function(HEADER_VALUE_TYPE3) {
- HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolTrue"] = 0] = "boolTrue";
- HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolFalse"] = 1] = "boolFalse";
- HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byte"] = 2] = "byte";
- HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["short"] = 3] = "short";
- HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["integer"] = 4] = "integer";
- HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["long"] = 5] = "long";
- HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byteArray"] = 6] = "byteArray";
- HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["string"] = 7] = "string";
- HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["timestamp"] = 8] = "timestamp";
- HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["uuid"] = 9] = "uuid";
- })(HEADER_VALUE_TYPE2 || (HEADER_VALUE_TYPE2 = {}));
- UUID_PATTERN2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
-});
-
-// node_modules/@smithy/signature-v4/dist-es/headerUtil.js
-var hasHeader = (soughtHeader, headers) => {
- soughtHeader = soughtHeader.toLowerCase();
- for (const headerName of Object.keys(headers)) {
- if (soughtHeader === headerName.toLowerCase()) {
- return true;
- }
- }
- return false;
-};
-
-// node_modules/@smithy/signature-v4/dist-es/cloneRequest.js
-var cloneRequest = ({ headers, query, ...rest }) => ({
- ...rest,
- headers: { ...headers },
- query: query ? cloneQuery6(query) : undefined
-}), cloneQuery6 = (query) => Object.keys(query).reduce((carry, paramName) => {
- const param = query[paramName];
- return {
- ...carry,
- [paramName]: Array.isArray(param) ? [...param] : param
- };
-}, {});
-
-// node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js
-var moveHeadersToQuery = (request2, options2 = {}) => {
- const { headers, query = {} } = typeof request2.clone === "function" ? request2.clone() : cloneRequest(request2);
- for (const name of Object.keys(headers)) {
- const lname = name.toLowerCase();
- if (lname.slice(0, 6) === "x-amz-" && !options2.unhoistableHeaders?.has(lname)) {
- query[name] = headers[name];
- delete headers[name];
- }
- }
- return {
- ...request2,
- headers,
- query
- };
-};
-var init_moveHeadersToQuery = () => {};
-
-// node_modules/@smithy/signature-v4/dist-es/prepareRequest.js
-var prepareRequest = (request2) => {
- request2 = typeof request2.clone === "function" ? request2.clone() : cloneRequest(request2);
- for (const headerName of Object.keys(request2.headers)) {
- if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {
- delete request2.headers[headerName];
- }
- }
- return request2;
-};
-var init_prepareRequest = __esm(() => {
- init_constants6();
-});
-
-// node_modules/@smithy/signature-v4/dist-es/utilDate.js
-var iso8601 = (time3) => toDate(time3).toISOString().replace(/\.\d{3}Z$/, "Z"), toDate = (time3) => {
- if (typeof time3 === "number") {
- return new Date(time3 * 1000);
- }
- if (typeof time3 === "string") {
- if (Number(time3)) {
- return new Date(Number(time3) * 1000);
- }
- return new Date(time3);
- }
- return time3;
-};
-
-// node_modules/@smithy/signature-v4/dist-es/SignatureV4.js
-class SignatureV4 {
- constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true }) {
- this.headerFormatter = new HeaderFormatter;
- this.service = service;
- this.sha256 = sha256;
- this.uriEscapePath = uriEscapePath;
- this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
- this.regionProvider = normalizeProvider5(region);
- this.credentialProvider = normalizeProvider5(credentials);
- }
- async presign(originalRequest, options2 = {}) {
- const { signingDate = new Date, expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, signingRegion, signingService } = options2;
- const credentials = await this.credentialProvider();
- this.validateResolvedCredentials(credentials);
- const region = signingRegion ?? await this.regionProvider();
- const { longDate, shortDate } = formatDate(signingDate);
- if (expiresIn > MAX_PRESIGNED_TTL) {
- return Promise.reject("Signature version 4 presigned URLs" + " must have an expiration date less than one week in" + " the future");
- }
- const scope = createScope(shortDate, region, signingService ?? this.service);
- const request2 = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders });
- if (credentials.sessionToken) {
- request2.query[TOKEN_QUERY_PARAM] = credentials.sessionToken;
- }
- request2.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
- request2.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`;
- request2.query[AMZ_DATE_QUERY_PARAM] = longDate;
- request2.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
- const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders);
- request2.query[SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList(canonicalHeaders);
- request2.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)));
- return request2;
- }
- async sign(toSign, options2) {
- if (typeof toSign === "string") {
- return this.signString(toSign, options2);
- } else if (toSign.headers && toSign.payload) {
- return this.signEvent(toSign, options2);
- } else if (toSign.message) {
- return this.signMessage(toSign, options2);
- } else {
- return this.signRequest(toSign, options2);
- }
- }
- async signEvent({ headers, payload }, { signingDate = new Date, priorSignature, signingRegion, signingService }) {
- const region = signingRegion ?? await this.regionProvider();
- const { shortDate, longDate } = formatDate(signingDate);
- const scope = createScope(shortDate, region, signingService ?? this.service);
- const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256);
- const hash2 = new this.sha256;
- hash2.update(headers);
- const hashedHeaders = toHex2(await hash2.digest());
- const stringToSign = [
- EVENT_ALGORITHM_IDENTIFIER,
- longDate,
- scope,
- priorSignature,
- hashedHeaders,
- hashedPayload
- ].join(`
-`);
- return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
- }
- async signMessage(signableMessage, { signingDate = new Date, signingRegion, signingService }) {
- const promise2 = this.signEvent({
- headers: this.headerFormatter.format(signableMessage.message.headers),
- payload: signableMessage.message.body
- }, {
- signingDate,
- signingRegion,
- signingService,
- priorSignature: signableMessage.priorSignature
- });
- return promise2.then((signature7) => {
- return { message: signableMessage.message, signature: signature7 };
- });
- }
- async signString(stringToSign, { signingDate = new Date, signingRegion, signingService } = {}) {
- const credentials = await this.credentialProvider();
- this.validateResolvedCredentials(credentials);
- const region = signingRegion ?? await this.regionProvider();
- const { shortDate } = formatDate(signingDate);
- const hash2 = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService));
- hash2.update(toUint8Array2(stringToSign));
- return toHex2(await hash2.digest());
- }
- async signRequest(requestToSign, { signingDate = new Date, signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) {
- const credentials = await this.credentialProvider();
- this.validateResolvedCredentials(credentials);
- const region = signingRegion ?? await this.regionProvider();
- const request2 = prepareRequest(requestToSign);
- const { longDate, shortDate } = formatDate(signingDate);
- const scope = createScope(shortDate, region, signingService ?? this.service);
- request2.headers[AMZ_DATE_HEADER] = longDate;
- if (credentials.sessionToken) {
- request2.headers[TOKEN_HEADER] = credentials.sessionToken;
- }
- const payloadHash = await getPayloadHash(request2, this.sha256);
- if (!hasHeader(SHA256_HEADER, request2.headers) && this.applyChecksum) {
- request2.headers[SHA256_HEADER] = payloadHash;
- }
- const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders);
- const signature7 = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, payloadHash));
- request2.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} ` + `Credential=${credentials.accessKeyId}/${scope}, ` + `SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, ` + `Signature=${signature7}`;
- return request2;
- }
- createCanonicalRequest(request2, canonicalHeaders, payloadHash) {
- const sortedHeaders = Object.keys(canonicalHeaders).sort();
- return `${request2.method}
-${this.getCanonicalPath(request2)}
-${getCanonicalQuery(request2)}
-${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join(`
-`)}
-
-${sortedHeaders.join(";")}
-${payloadHash}`;
- }
- async createStringToSign(longDate, credentialScope, canonicalRequest) {
- const hash2 = new this.sha256;
- hash2.update(toUint8Array2(canonicalRequest));
- const hashedRequest = await hash2.digest();
- return `${ALGORITHM_IDENTIFIER}
-${longDate}
-${credentialScope}
-${toHex2(hashedRequest)}`;
- }
- getCanonicalPath({ path: path9 }) {
- if (this.uriEscapePath) {
- const normalizedPathSegments = [];
- for (const pathSegment of path9.split("/")) {
- if (pathSegment?.length === 0)
- continue;
- if (pathSegment === ".")
- continue;
- if (pathSegment === "..") {
- normalizedPathSegments.pop();
- } else {
- normalizedPathSegments.push(pathSegment);
- }
- }
- const normalizedPath = `${path9?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path9?.endsWith("/") ? "/" : ""}`;
- const doubleEncoded = escapeUri(normalizedPath);
- return doubleEncoded.replace(/%2F/g, "/");
- }
- return path9;
- }
- async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {
- const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest);
- const hash2 = new this.sha256(await keyPromise);
- hash2.update(toUint8Array2(stringToSign));
- return toHex2(await hash2.digest());
- }
- getSigningKey(credentials, region, shortDate, service) {
- return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service);
- }
- validateResolvedCredentials(credentials) {
- if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") {
- throw new Error("Resolved credential object is not valid");
- }
- }
-}
-var formatDate = (now) => {
- const longDate = iso8601(now).replace(/[\-:]/g, "");
- return {
- longDate,
- shortDate: longDate.slice(0, 8)
- };
-}, getCanonicalHeaderList = (headers) => Object.keys(headers).sort().join(";");
-var init_SignatureV4 = __esm(() => {
- init_dist_es49();
- init_dist_es51();
- init_dist_es52();
- init_dist_es54();
- init_constants6();
- init_credentialDerivation();
- init_getCanonicalHeaders();
- init_getCanonicalQuery();
- init_getPayloadHash();
- init_HeaderFormatter();
- init_moveHeadersToQuery();
- init_prepareRequest();
-});
-
-// node_modules/@smithy/signature-v4/dist-es/index.js
-var init_dist_es55 = __esm(() => {
- init_getCanonicalHeaders();
- init_getCanonicalQuery();
- init_getPayloadHash();
- init_moveHeadersToQuery();
- init_prepareRequest();
- init_SignatureV4();
- init_credentialDerivation();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/core/auth.mjs
-import assert2 from "assert";
-var import_sha256_js, import_fetch_http_handler, DEFAULT_PROVIDER_CHAIN_RESOLVER = () => Promise.resolve().then(() => (init_dist_es46(), exports_dist_es16)).then(({ fromNodeProviderChain: fromNodeProviderChain3 }) => fromNodeProviderChain3({
- clientConfig: {
- requestHandler: new import_fetch_http_handler.FetchHttpHandler({
- requestInit: (httpRequest10) => {
- return {
- ...httpRequest10
- };
- }
- })
- }
-})).catch((error41) => {
- throw new Error(`Failed to import '@aws-sdk/credential-providers'.You can provide a custom \`providerChainResolver\` in the client options if your runtime does not have access to '@aws-sdk/credential-providers': \`new AnthropicBedrock({ providerChainResolver })\` Original error: ${error41.message}`);
-}), getAuthHeaders = async (req, props) => {
- assert2(req.method, "Expected request method property to be set");
- let credentials;
- if (props.awsAccessKey && props.awsSecretKey) {
- credentials = {
- accessKeyId: props.awsAccessKey,
- secretAccessKey: props.awsSecretKey,
- ...props.awsSessionToken != null && { sessionToken: props.awsSessionToken }
- };
- } else {
- const provider3 = await (props.providerChainResolver ? props.providerChainResolver() : DEFAULT_PROVIDER_CHAIN_RESOLVER());
- credentials = await provider3();
- }
- const signer = new SignatureV4({
- service: "bedrock",
- region: props.regionName,
- credentials,
- sha256: import_sha256_js.Sha256
- });
- const url3 = new URL(props.url);
- const headers = !req.headers ? {} : (Symbol.iterator in req.headers) ? Object.fromEntries(Array.from(req.headers).map((header) => [...header])) : { ...req.headers };
- delete headers["connection"];
- headers["host"] = url3.hostname;
- const request2 = new HttpRequest5({
- method: req.method.toUpperCase(),
- protocol: url3.protocol,
- path: url3.pathname,
- headers,
- body: req.body
- });
- const signed = await signer.sign(request2);
- return signed.headers;
-};
-var init_auth13 = __esm(() => {
- init_dist_es48();
- init_dist_es55();
- import_sha256_js = __toESM(require_build2(), 1);
- import_fetch_http_handler = __toESM(require_dist_cjs24(), 1);
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.js
-var require_tslib3 = __commonJS((exports, module) => {
- /*! *****************************************************************************
- Copyright (c) Microsoft Corporation.
-
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- PERFORMANCE OF THIS SOFTWARE.
- ***************************************************************************** */
- var __extends2;
- var __assign2;
- var __rest2;
- var __decorate2;
- var __param2;
- var __metadata2;
- var __awaiter2;
- var __generator2;
- var __exportStar2;
- var __values2;
- var __read2;
- var __spread2;
- var __spreadArrays2;
- var __await2;
- var __asyncGenerator2;
- var __asyncDelegator2;
- var __asyncValues2;
- var __makeTemplateObject2;
- var __importStar2;
- var __importDefault2;
- var __classPrivateFieldGet7;
- var __classPrivateFieldSet7;
- var __createBinding2;
- (function(factory2) {
- var root2 = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
- if (typeof define === "function" && define.amd) {
- define("tslib", ["exports"], function(exports2) {
- factory2(createExporter(root2, createExporter(exports2)));
- });
- } else if (typeof module === "object" && typeof exports === "object") {
- factory2(createExporter(root2, createExporter(exports)));
- } else {
- factory2(createExporter(root2));
- }
- function createExporter(exports2, previous) {
- if (exports2 !== root2) {
- if (typeof Object.create === "function") {
- Object.defineProperty(exports2, "__esModule", { value: true });
- } else {
- exports2.__esModule = true;
- }
- }
- return function(id, v4) {
- return exports2[id] = previous ? previous(id, v4) : v4;
- };
- }
- })(function(exporter) {
- var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
- d4.__proto__ = b4;
- } || function(d4, b4) {
- for (var p4 in b4)
- if (b4.hasOwnProperty(p4))
- d4[p4] = b4[p4];
- };
- __extends2 = function(d4, b4) {
- extendStatics(d4, b4);
- function __() {
- this.constructor = d4;
- }
- d4.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __);
- };
- __assign2 = Object.assign || function(t4) {
- for (var s4, i5 = 1, n5 = arguments.length;i5 < n5; i5++) {
- s4 = arguments[i5];
- for (var p4 in s4)
- if (Object.prototype.hasOwnProperty.call(s4, p4))
- t4[p4] = s4[p4];
- }
- return t4;
- };
- __rest2 = function(s4, e4) {
- var t4 = {};
- for (var p4 in s4)
- if (Object.prototype.hasOwnProperty.call(s4, p4) && e4.indexOf(p4) < 0)
- t4[p4] = s4[p4];
- if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i5 = 0, p4 = Object.getOwnPropertySymbols(s4);i5 < p4.length; i5++) {
- if (e4.indexOf(p4[i5]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p4[i5]))
- t4[p4[i5]] = s4[p4[i5]];
- }
- return t4;
- };
- __decorate2 = function(decorators, target, key, desc) {
- var c8 = arguments.length, r4 = c8 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
- r4 = Reflect.decorate(decorators, target, key, desc);
- else
- for (var i5 = decorators.length - 1;i5 >= 0; i5--)
- if (d4 = decorators[i5])
- r4 = (c8 < 3 ? d4(r4) : c8 > 3 ? d4(target, key, r4) : d4(target, key)) || r4;
- return c8 > 3 && r4 && Object.defineProperty(target, key, r4), r4;
- };
- __param2 = function(paramIndex, decorator) {
- return function(target, key) {
- decorator(target, key, paramIndex);
- };
- };
- __metadata2 = function(metadataKey, metadataValue) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
- return Reflect.metadata(metadataKey, metadataValue);
- };
- __awaiter2 = function(thisArg, _arguments, P, generator) {
- function adopt(value) {
- return value instanceof P ? value : new P(function(resolve9) {
- resolve9(value);
- });
- }
- return new (P || (P = Promise))(function(resolve9, reject) {
- function fulfilled(value) {
- try {
- step(generator.next(value));
- } catch (e4) {
- reject(e4);
- }
- }
- function rejected(value) {
- try {
- step(generator["throw"](value));
- } catch (e4) {
- reject(e4);
- }
- }
- function step(result) {
- result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected);
- }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- __generator2 = function(thisArg, body) {
- var _ = { label: 0, sent: function() {
- if (t4[0] & 1)
- throw t4[1];
- return t4[1];
- }, trys: [], ops: [] }, f4, y3, t4, g4;
- return g4 = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol === "function" && (g4[Symbol.iterator] = function() {
- return this;
- }), g4;
- function verb(n5) {
- return function(v4) {
- return step([n5, v4]);
- };
- }
- function step(op) {
- if (f4)
- throw new TypeError("Generator is already executing.");
- while (_)
- try {
- if (f4 = 1, y3 && (t4 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t4 = y3["return"]) && t4.call(y3), 0) : y3.next) && !(t4 = t4.call(y3, op[1])).done)
- return t4;
- if (y3 = 0, t4)
- op = [op[0] & 2, t4.value];
- switch (op[0]) {
- case 0:
- case 1:
- t4 = op;
- break;
- case 4:
- _.label++;
- return { value: op[1], done: false };
- case 5:
- _.label++;
- y3 = op[1];
- op = [0];
- continue;
- case 7:
- op = _.ops.pop();
- _.trys.pop();
- continue;
- default:
- if (!(t4 = _.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) {
- _ = 0;
- continue;
- }
- if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) {
- _.label = op[1];
- break;
- }
- if (op[0] === 6 && _.label < t4[1]) {
- _.label = t4[1];
- t4 = op;
- break;
- }
- if (t4 && _.label < t4[2]) {
- _.label = t4[2];
- _.ops.push(op);
- break;
- }
- if (t4[2])
- _.ops.pop();
- _.trys.pop();
- continue;
- }
- op = body.call(thisArg, _);
- } catch (e4) {
- op = [6, e4];
- y3 = 0;
- } finally {
- f4 = t4 = 0;
- }
- if (op[0] & 5)
- throw op[1];
- return { value: op[0] ? op[1] : undefined, done: true };
- }
- };
- __createBinding2 = function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- };
- __exportStar2 = function(m4, exports2) {
- for (var p4 in m4)
- if (p4 !== "default" && !exports2.hasOwnProperty(p4))
- exports2[p4] = m4[p4];
- };
- __values2 = function(o5) {
- var s4 = typeof Symbol === "function" && Symbol.iterator, m4 = s4 && o5[s4], i5 = 0;
- if (m4)
- return m4.call(o5);
- if (o5 && typeof o5.length === "number")
- return {
- next: function() {
- if (o5 && i5 >= o5.length)
- o5 = undefined;
- return { value: o5 && o5[i5++], done: !o5 };
- }
- };
- throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
- };
- __read2 = function(o5, n5) {
- var m4 = typeof Symbol === "function" && o5[Symbol.iterator];
- if (!m4)
- return o5;
- var i5 = m4.call(o5), r4, ar = [], e4;
- try {
- while ((n5 === undefined || n5-- > 0) && !(r4 = i5.next()).done)
- ar.push(r4.value);
- } catch (error41) {
- e4 = { error: error41 };
- } finally {
- try {
- if (r4 && !r4.done && (m4 = i5["return"]))
- m4.call(i5);
- } finally {
- if (e4)
- throw e4.error;
- }
- }
- return ar;
- };
- __spread2 = function() {
- for (var ar = [], i5 = 0;i5 < arguments.length; i5++)
- ar = ar.concat(__read2(arguments[i5]));
- return ar;
- };
- __spreadArrays2 = function() {
- for (var s4 = 0, i5 = 0, il = arguments.length;i5 < il; i5++)
- s4 += arguments[i5].length;
- for (var r4 = Array(s4), k4 = 0, i5 = 0;i5 < il; i5++)
- for (var a5 = arguments[i5], j4 = 0, jl = a5.length;j4 < jl; j4++, k4++)
- r4[k4] = a5[j4];
- return r4;
- };
- __await2 = function(v4) {
- return this instanceof __await2 ? (this.v = v4, this) : new __await2(v4);
- };
- __asyncGenerator2 = function(thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator)
- throw new TypeError("Symbol.asyncIterator is not defined.");
- var g4 = generator.apply(thisArg, _arguments || []), i5, q4 = [];
- return i5 = {}, verb("next"), verb("throw"), verb("return"), i5[Symbol.asyncIterator] = function() {
- return this;
- }, i5;
- function verb(n5) {
- if (g4[n5])
- i5[n5] = function(v4) {
- return new Promise(function(a5, b4) {
- q4.push([n5, v4, a5, b4]) > 1 || resume(n5, v4);
- });
- };
- }
- function resume(n5, v4) {
- try {
- step(g4[n5](v4));
- } catch (e4) {
- settle2(q4[0][3], e4);
- }
- }
- function step(r4) {
- r4.value instanceof __await2 ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle2(q4[0][2], r4);
- }
- function fulfill(value) {
- resume("next", value);
- }
- function reject(value) {
- resume("throw", value);
- }
- function settle2(f4, v4) {
- if (f4(v4), q4.shift(), q4.length)
- resume(q4[0][0], q4[0][1]);
- }
- };
- __asyncDelegator2 = function(o5) {
- var i5, p4;
- return i5 = {}, verb("next"), verb("throw", function(e4) {
- throw e4;
- }), verb("return"), i5[Symbol.iterator] = function() {
- return this;
- }, i5;
- function verb(n5, f4) {
- i5[n5] = o5[n5] ? function(v4) {
- return (p4 = !p4) ? { value: __await2(o5[n5](v4)), done: n5 === "return" } : f4 ? f4(v4) : v4;
- } : f4;
- }
- };
- __asyncValues2 = function(o5) {
- if (!Symbol.asyncIterator)
- throw new TypeError("Symbol.asyncIterator is not defined.");
- var m4 = o5[Symbol.asyncIterator], i5;
- return m4 ? m4.call(o5) : (o5 = typeof __values2 === "function" ? __values2(o5) : o5[Symbol.iterator](), i5 = {}, verb("next"), verb("throw"), verb("return"), i5[Symbol.asyncIterator] = function() {
- return this;
- }, i5);
- function verb(n5) {
- i5[n5] = o5[n5] && function(v4) {
- return new Promise(function(resolve9, reject) {
- v4 = o5[n5](v4), settle2(resolve9, reject, v4.done, v4.value);
- });
- };
- }
- function settle2(resolve9, reject, d4, v4) {
- Promise.resolve(v4).then(function(v5) {
- resolve9({ value: v5, done: d4 });
- }, reject);
- }
- };
- __makeTemplateObject2 = function(cooked, raw) {
- if (Object.defineProperty) {
- Object.defineProperty(cooked, "raw", { value: raw });
- } else {
- cooked.raw = raw;
- }
- return cooked;
- };
- __importStar2 = function(mod2) {
- if (mod2 && mod2.__esModule)
- return mod2;
- var result = {};
- if (mod2 != null) {
- for (var k4 in mod2)
- if (Object.hasOwnProperty.call(mod2, k4))
- result[k4] = mod2[k4];
- }
- result["default"] = mod2;
- return result;
- };
- __importDefault2 = function(mod2) {
- return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
- };
- __classPrivateFieldGet7 = function(receiver, privateMap) {
- if (!privateMap.has(receiver)) {
- throw new TypeError("attempted to get private field on non-instance");
- }
- return privateMap.get(receiver);
- };
- __classPrivateFieldSet7 = function(receiver, privateMap, value) {
- if (!privateMap.has(receiver)) {
- throw new TypeError("attempted to set private field on non-instance");
- }
- privateMap.set(receiver, value);
- return value;
- };
- exporter("__extends", __extends2);
- exporter("__assign", __assign2);
- exporter("__rest", __rest2);
- exporter("__decorate", __decorate2);
- exporter("__param", __param2);
- exporter("__metadata", __metadata2);
- exporter("__awaiter", __awaiter2);
- exporter("__generator", __generator2);
- exporter("__exportStar", __exportStar2);
- exporter("__createBinding", __createBinding2);
- exporter("__values", __values2);
- exporter("__read", __read2);
- exporter("__spread", __spread2);
- exporter("__spreadArrays", __spreadArrays2);
- exporter("__await", __await2);
- exporter("__asyncGenerator", __asyncGenerator2);
- exporter("__asyncDelegator", __asyncDelegator2);
- exporter("__asyncValues", __asyncValues2);
- exporter("__makeTemplateObject", __makeTemplateObject2);
- exporter("__importStar", __importStar2);
- exporter("__importDefault", __importDefault2);
- exporter("__classPrivateFieldGet", __classPrivateFieldGet7);
- exporter("__classPrivateFieldSet", __classPrivateFieldSet7);
- });
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/convertToBuffer.js
-var require_convertToBuffer2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.convertToBuffer = undefined;
- var util_utf8_browser_1 = require_dist_cjs89();
- var fromUtf812 = typeof Buffer !== "undefined" && Buffer.from ? function(input) {
- return Buffer.from(input, "utf8");
- } : util_utf8_browser_1.fromUtf8;
- function convertToBuffer2(data) {
- if (data instanceof Uint8Array)
- return data;
- if (typeof data === "string") {
- return fromUtf812(data);
- }
- if (ArrayBuffer.isView(data)) {
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
- }
- return new Uint8Array(data);
- }
- exports.convertToBuffer = convertToBuffer2;
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/isEmptyData.js
-var require_isEmptyData2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isEmptyData = undefined;
- function isEmptyData2(data) {
- if (typeof data === "string") {
- return data.length === 0;
- }
- return data.byteLength === 0;
- }
- exports.isEmptyData = isEmptyData2;
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/numToUint8.js
-var require_numToUint82 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.numToUint8 = undefined;
- function numToUint82(num) {
- return new Uint8Array([
- (num & 4278190080) >> 24,
- (num & 16711680) >> 16,
- (num & 65280) >> 8,
- num & 255
- ]);
- }
- exports.numToUint8 = numToUint82;
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js
-var require_uint32ArrayFrom2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.uint32ArrayFrom = undefined;
- function uint32ArrayFrom2(a_lookUpTable2) {
- if (!Uint32Array.from) {
- var return_array = new Uint32Array(a_lookUpTable2.length);
- var a_index = 0;
- while (a_index < a_lookUpTable2.length) {
- return_array[a_index] = a_lookUpTable2[a_index];
- a_index += 1;
- }
- return return_array;
- }
- return Uint32Array.from(a_lookUpTable2);
- }
- exports.uint32ArrayFrom = uint32ArrayFrom2;
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/index.js
-var require_build3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = undefined;
- var convertToBuffer_1 = require_convertToBuffer2();
- Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function() {
- return convertToBuffer_1.convertToBuffer;
- } });
- var isEmptyData_1 = require_isEmptyData2();
- Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function() {
- return isEmptyData_1.isEmptyData;
- } });
- var numToUint8_1 = require_numToUint82();
- Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function() {
- return numToUint8_1.numToUint8;
- } });
- var uint32ArrayFrom_1 = require_uint32ArrayFrom2();
- Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function() {
- return uint32ArrayFrom_1.uint32ArrayFrom;
- } });
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/aws_crc32.js
-var require_aws_crc32 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AwsCrc32 = undefined;
- var tslib_1 = require_tslib3();
- var util_1 = require_build3();
- var index_1 = require_build4();
- var AwsCrc322 = function() {
- function AwsCrc323() {
- this.crc32 = new index_1.Crc32;
- }
- AwsCrc323.prototype.update = function(toHash) {
- if ((0, util_1.isEmptyData)(toHash))
- return;
- this.crc32.update((0, util_1.convertToBuffer)(toHash));
- };
- AwsCrc323.prototype.digest = function() {
- return tslib_1.__awaiter(this, undefined, undefined, function() {
- return tslib_1.__generator(this, function(_a6) {
- return [2, (0, util_1.numToUint8)(this.crc32.digest())];
- });
- });
- };
- AwsCrc323.prototype.reset = function() {
- this.crc32 = new index_1.Crc32;
- };
- return AwsCrc323;
- }();
- exports.AwsCrc32 = AwsCrc322;
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/index.js
-var require_build4 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AwsCrc32 = exports.Crc32 = exports.crc32 = undefined;
- var tslib_1 = require_tslib3();
- var util_1 = require_build3();
- function crc32(data) {
- return new Crc322().update(data).digest();
- }
- exports.crc32 = crc32;
- var Crc322 = function() {
- function Crc323() {
- this.checksum = 4294967295;
- }
- Crc323.prototype.update = function(data) {
- var e_1, _a6;
- try {
- for (var data_1 = tslib_1.__values(data), data_1_1 = data_1.next();!data_1_1.done; data_1_1 = data_1.next()) {
- var byte = data_1_1.value;
- this.checksum = this.checksum >>> 8 ^ lookupTable2[(this.checksum ^ byte) & 255];
- }
- } catch (e_1_1) {
- e_1 = { error: e_1_1 };
- } finally {
- try {
- if (data_1_1 && !data_1_1.done && (_a6 = data_1.return))
- _a6.call(data_1);
- } finally {
- if (e_1)
- throw e_1.error;
- }
- }
- return this;
- };
- Crc323.prototype.digest = function() {
- return (this.checksum ^ 4294967295) >>> 0;
- };
- return Crc323;
- }();
- exports.Crc32 = Crc322;
- var a_lookUpTable2 = [
- 0,
- 1996959894,
- 3993919788,
- 2567524794,
- 124634137,
- 1886057615,
- 3915621685,
- 2657392035,
- 249268274,
- 2044508324,
- 3772115230,
- 2547177864,
- 162941995,
- 2125561021,
- 3887607047,
- 2428444049,
- 498536548,
- 1789927666,
- 4089016648,
- 2227061214,
- 450548861,
- 1843258603,
- 4107580753,
- 2211677639,
- 325883990,
- 1684777152,
- 4251122042,
- 2321926636,
- 335633487,
- 1661365465,
- 4195302755,
- 2366115317,
- 997073096,
- 1281953886,
- 3579855332,
- 2724688242,
- 1006888145,
- 1258607687,
- 3524101629,
- 2768942443,
- 901097722,
- 1119000684,
- 3686517206,
- 2898065728,
- 853044451,
- 1172266101,
- 3705015759,
- 2882616665,
- 651767980,
- 1373503546,
- 3369554304,
- 3218104598,
- 565507253,
- 1454621731,
- 3485111705,
- 3099436303,
- 671266974,
- 1594198024,
- 3322730930,
- 2970347812,
- 795835527,
- 1483230225,
- 3244367275,
- 3060149565,
- 1994146192,
- 31158534,
- 2563907772,
- 4023717930,
- 1907459465,
- 112637215,
- 2680153253,
- 3904427059,
- 2013776290,
- 251722036,
- 2517215374,
- 3775830040,
- 2137656763,
- 141376813,
- 2439277719,
- 3865271297,
- 1802195444,
- 476864866,
- 2238001368,
- 4066508878,
- 1812370925,
- 453092731,
- 2181625025,
- 4111451223,
- 1706088902,
- 314042704,
- 2344532202,
- 4240017532,
- 1658658271,
- 366619977,
- 2362670323,
- 4224994405,
- 1303535960,
- 984961486,
- 2747007092,
- 3569037538,
- 1256170817,
- 1037604311,
- 2765210733,
- 3554079995,
- 1131014506,
- 879679996,
- 2909243462,
- 3663771856,
- 1141124467,
- 855842277,
- 2852801631,
- 3708648649,
- 1342533948,
- 654459306,
- 3188396048,
- 3373015174,
- 1466479909,
- 544179635,
- 3110523913,
- 3462522015,
- 1591671054,
- 702138776,
- 2966460450,
- 3352799412,
- 1504918807,
- 783551873,
- 3082640443,
- 3233442989,
- 3988292384,
- 2596254646,
- 62317068,
- 1957810842,
- 3939845945,
- 2647816111,
- 81470997,
- 1943803523,
- 3814918930,
- 2489596804,
- 225274430,
- 2053790376,
- 3826175755,
- 2466906013,
- 167816743,
- 2097651377,
- 4027552580,
- 2265490386,
- 503444072,
- 1762050814,
- 4150417245,
- 2154129355,
- 426522225,
- 1852507879,
- 4275313526,
- 2312317920,
- 282753626,
- 1742555852,
- 4189708143,
- 2394877945,
- 397917763,
- 1622183637,
- 3604390888,
- 2714866558,
- 953729732,
- 1340076626,
- 3518719985,
- 2797360999,
- 1068828381,
- 1219638859,
- 3624741850,
- 2936675148,
- 906185462,
- 1090812512,
- 3747672003,
- 2825379669,
- 829329135,
- 1181335161,
- 3412177804,
- 3160834842,
- 628085408,
- 1382605366,
- 3423369109,
- 3138078467,
- 570562233,
- 1426400815,
- 3317316542,
- 2998733608,
- 733239954,
- 1555261956,
- 3268935591,
- 3050360625,
- 752459403,
- 1541320221,
- 2607071920,
- 3965973030,
- 1969922972,
- 40735498,
- 2617837225,
- 3943577151,
- 1913087877,
- 83908371,
- 2512341634,
- 3803740692,
- 2075208622,
- 213261112,
- 2463272603,
- 3855990285,
- 2094854071,
- 198958881,
- 2262029012,
- 4057260610,
- 1759359992,
- 534414190,
- 2176718541,
- 4139329115,
- 1873836001,
- 414664567,
- 2282248934,
- 4279200368,
- 1711684554,
- 285281116,
- 2405801727,
- 4167216745,
- 1634467795,
- 376229701,
- 2685067896,
- 3608007406,
- 1308918612,
- 956543938,
- 2808555105,
- 3495958263,
- 1231636301,
- 1047427035,
- 2932959818,
- 3654703836,
- 1088359270,
- 936918000,
- 2847714899,
- 3736837829,
- 1202900863,
- 817233897,
- 3183342108,
- 3401237130,
- 1404277552,
- 615818150,
- 3134207493,
- 3453421203,
- 1423857449,
- 601450431,
- 3009837614,
- 3294710456,
- 1567103746,
- 711928724,
- 3020668471,
- 3272380065,
- 1510334235,
- 755167117
- ];
- var lookupTable2 = (0, util_1.uint32ArrayFrom)(a_lookUpTable2);
- var aws_crc32_1 = require_aws_crc32();
- Object.defineProperty(exports, "AwsCrc32", { enumerable: true, get: function() {
- return aws_crc32_1.AwsCrc32;
- } });
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-es/index.js
-function fromHex3(encoded) {
- if (encoded.length % 2 !== 0) {
- throw new Error("Hex encoded strings must have an even number length");
- }
- const out = new Uint8Array(encoded.length / 2);
- for (let i5 = 0;i5 < encoded.length; i5 += 2) {
- const encodedByte = encoded.slice(i5, i5 + 2).toLowerCase();
- if (encodedByte in HEX_TO_SHORT3) {
- out[i5 / 2] = HEX_TO_SHORT3[encodedByte];
- } else {
- throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
- }
- }
- return out;
-}
-function toHex3(bytes) {
- let out = "";
- for (let i5 = 0;i5 < bytes.byteLength; i5++) {
- out += SHORT_TO_HEX3[bytes[i5]];
- }
- return out;
-}
-var SHORT_TO_HEX3, HEX_TO_SHORT3;
-var init_dist_es56 = __esm(() => {
- SHORT_TO_HEX3 = {};
- HEX_TO_SHORT3 = {};
- for (let i5 = 0;i5 < 256; i5++) {
- let encodedByte = i5.toString(16).toLowerCase();
- if (encodedByte.length === 1) {
- encodedByte = `0${encodedByte}`;
- }
- SHORT_TO_HEX3[i5] = encodedByte;
- HEX_TO_SHORT3[encodedByte] = i5;
- }
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-es/Int64.js
-class Int644 {
- constructor(bytes) {
- this.bytes = bytes;
- if (bytes.byteLength !== 8) {
- throw new Error("Int64 buffers must be exactly 8 bytes");
- }
- }
- static fromNumber(number4) {
- if (number4 > 9223372036854776000 || number4 < -9223372036854776000) {
- throw new Error(`${number4} is too large (or, if negative, too small) to represent as an Int64`);
- }
- const bytes = new Uint8Array(8);
- for (let i5 = 7, remaining = Math.abs(Math.round(number4));i5 > -1 && remaining > 0; i5--, remaining /= 256) {
- bytes[i5] = remaining;
- }
- if (number4 < 0) {
- negate3(bytes);
- }
- return new Int644(bytes);
- }
- valueOf() {
- const bytes = this.bytes.slice(0);
- const negative = bytes[0] & 128;
- if (negative) {
- negate3(bytes);
- }
- return parseInt(toHex3(bytes), 16) * (negative ? -1 : 1);
- }
- toString() {
- return String(this.valueOf());
- }
-}
-function negate3(bytes) {
- for (let i5 = 0;i5 < 8; i5++) {
- bytes[i5] ^= 255;
- }
- for (let i5 = 7;i5 > -1; i5--) {
- bytes[i5]++;
- if (bytes[i5] !== 0)
- break;
- }
-}
-var init_Int642 = __esm(() => {
- init_dist_es56();
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-es/HeaderMarshaller.js
-class HeaderMarshaller3 {
- constructor(toUtf86, fromUtf812) {
- this.toUtf8 = toUtf86;
- this.fromUtf8 = fromUtf812;
- }
- format(headers) {
- const chunks = [];
- for (const headerName of Object.keys(headers)) {
- const bytes = this.fromUtf8(headerName);
- chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
- }
- const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
- let position2 = 0;
- for (const chunk of chunks) {
- out.set(chunk, position2);
- position2 += chunk.byteLength;
- }
- return out;
- }
- formatHeaderValue(header) {
- switch (header.type) {
- case "boolean":
- return Uint8Array.from([header.value ? 0 : 1]);
- case "byte":
- return Uint8Array.from([2, header.value]);
- case "short":
- const shortView = new DataView(new ArrayBuffer(3));
- shortView.setUint8(0, 3);
- shortView.setInt16(1, header.value, false);
- return new Uint8Array(shortView.buffer);
- case "integer":
- const intView = new DataView(new ArrayBuffer(5));
- intView.setUint8(0, 4);
- intView.setInt32(1, header.value, false);
- return new Uint8Array(intView.buffer);
- case "long":
- const longBytes = new Uint8Array(9);
- longBytes[0] = 5;
- longBytes.set(header.value.bytes, 1);
- return longBytes;
- case "binary":
- const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
- binView.setUint8(0, 6);
- binView.setUint16(1, header.value.byteLength, false);
- const binBytes = new Uint8Array(binView.buffer);
- binBytes.set(header.value, 3);
- return binBytes;
- case "string":
- const utf8Bytes = this.fromUtf8(header.value);
- const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
- strView.setUint8(0, 7);
- strView.setUint16(1, utf8Bytes.byteLength, false);
- const strBytes = new Uint8Array(strView.buffer);
- strBytes.set(utf8Bytes, 3);
- return strBytes;
- case "timestamp":
- const tsBytes = new Uint8Array(9);
- tsBytes[0] = 8;
- tsBytes.set(Int644.fromNumber(header.value.valueOf()).bytes, 1);
- return tsBytes;
- case "uuid":
- if (!UUID_PATTERN3.test(header.value)) {
- throw new Error(`Invalid UUID received: ${header.value}`);
- }
- const uuidBytes = new Uint8Array(17);
- uuidBytes[0] = 9;
- uuidBytes.set(fromHex3(header.value.replace(/\-/g, "")), 1);
- return uuidBytes;
- }
- }
- parse(headers) {
- const out = {};
- let position2 = 0;
- while (position2 < headers.byteLength) {
- const nameLength = headers.getUint8(position2++);
- const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position2, nameLength));
- position2 += nameLength;
- switch (headers.getUint8(position2++)) {
- case 0:
- out[name] = {
- type: BOOLEAN_TAG2,
- value: true
- };
- break;
- case 1:
- out[name] = {
- type: BOOLEAN_TAG2,
- value: false
- };
- break;
- case 2:
- out[name] = {
- type: BYTE_TAG2,
- value: headers.getInt8(position2++)
- };
- break;
- case 3:
- out[name] = {
- type: SHORT_TAG2,
- value: headers.getInt16(position2, false)
- };
- position2 += 2;
- break;
- case 4:
- out[name] = {
- type: INT_TAG2,
- value: headers.getInt32(position2, false)
- };
- position2 += 4;
- break;
- case 5:
- out[name] = {
- type: LONG_TAG2,
- value: new Int644(new Uint8Array(headers.buffer, headers.byteOffset + position2, 8))
- };
- position2 += 8;
- break;
- case 6:
- const binaryLength = headers.getUint16(position2, false);
- position2 += 2;
- out[name] = {
- type: BINARY_TAG2,
- value: new Uint8Array(headers.buffer, headers.byteOffset + position2, binaryLength)
- };
- position2 += binaryLength;
- break;
- case 7:
- const stringLength = headers.getUint16(position2, false);
- position2 += 2;
- out[name] = {
- type: STRING_TAG2,
- value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position2, stringLength))
- };
- position2 += stringLength;
- break;
- case 8:
- out[name] = {
- type: TIMESTAMP_TAG2,
- value: new Date(new Int644(new Uint8Array(headers.buffer, headers.byteOffset + position2, 8)).valueOf())
- };
- position2 += 8;
- break;
- case 9:
- const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position2, 16);
- position2 += 16;
- out[name] = {
- type: UUID_TAG2,
- value: `${toHex3(uuidBytes.subarray(0, 4))}-${toHex3(uuidBytes.subarray(4, 6))}-${toHex3(uuidBytes.subarray(6, 8))}-${toHex3(uuidBytes.subarray(8, 10))}-${toHex3(uuidBytes.subarray(10))}`
- };
- break;
- default:
- throw new Error(`Unrecognized header type tag`);
- }
- }
- return out;
- }
-}
-var HEADER_VALUE_TYPE3, BOOLEAN_TAG2 = "boolean", BYTE_TAG2 = "byte", SHORT_TAG2 = "short", INT_TAG2 = "integer", LONG_TAG2 = "long", BINARY_TAG2 = "binary", STRING_TAG2 = "string", TIMESTAMP_TAG2 = "timestamp", UUID_TAG2 = "uuid", UUID_PATTERN3;
-var init_HeaderMarshaller2 = __esm(() => {
- init_dist_es56();
- init_Int642();
- (function(HEADER_VALUE_TYPE4) {
- HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4["boolTrue"] = 0] = "boolTrue";
- HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4["boolFalse"] = 1] = "boolFalse";
- HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4["byte"] = 2] = "byte";
- HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4["short"] = 3] = "short";
- HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4["integer"] = 4] = "integer";
- HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4["long"] = 5] = "long";
- HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4["byteArray"] = 6] = "byteArray";
- HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4["string"] = 7] = "string";
- HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4["timestamp"] = 8] = "timestamp";
- HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4["uuid"] = 9] = "uuid";
- })(HEADER_VALUE_TYPE3 || (HEADER_VALUE_TYPE3 = {}));
- UUID_PATTERN3 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-es/splitMessage.js
-function splitMessage2({ byteLength, byteOffset, buffer }) {
- if (byteLength < MINIMUM_MESSAGE_LENGTH2) {
- throw new Error("Provided message too short to accommodate event stream message overhead");
- }
- const view = new DataView(buffer, byteOffset, byteLength);
- const messageLength = view.getUint32(0, false);
- if (byteLength !== messageLength) {
- throw new Error("Reported message length does not match received message length");
- }
- const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH2, false);
- const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH2, false);
- const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH2, false);
- const checksummer = new import_crc323.Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH2));
- if (expectedPreludeChecksum !== checksummer.digest()) {
- throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`);
- }
- checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH2, byteLength - (PRELUDE_LENGTH2 + CHECKSUM_LENGTH2)));
- if (expectedMessageChecksum !== checksummer.digest()) {
- throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`);
- }
- return {
- headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH2 + CHECKSUM_LENGTH2, headerLength),
- body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH2 + CHECKSUM_LENGTH2 + headerLength, messageLength - headerLength - (PRELUDE_LENGTH2 + CHECKSUM_LENGTH2 + CHECKSUM_LENGTH2))
- };
-}
-var import_crc323, PRELUDE_MEMBER_LENGTH2 = 4, PRELUDE_LENGTH2, CHECKSUM_LENGTH2 = 4, MINIMUM_MESSAGE_LENGTH2;
-var init_splitMessage2 = __esm(() => {
- import_crc323 = __toESM(require_build4(), 1);
- PRELUDE_LENGTH2 = PRELUDE_MEMBER_LENGTH2 * 2;
- MINIMUM_MESSAGE_LENGTH2 = PRELUDE_LENGTH2 + CHECKSUM_LENGTH2 * 2;
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-es/EventStreamCodec.js
-class EventStreamCodec3 {
- constructor(toUtf86, fromUtf812) {
- this.headerMarshaller = new HeaderMarshaller3(toUtf86, fromUtf812);
- this.messageBuffer = [];
- this.isEndOfStream = false;
- }
- feed(message) {
- this.messageBuffer.push(this.decode(message));
- }
- endOfStream() {
- this.isEndOfStream = true;
- }
- getMessage() {
- const message = this.messageBuffer.pop();
- const isEndOfStream = this.isEndOfStream;
- return {
- getMessage() {
- return message;
- },
- isEndOfStream() {
- return isEndOfStream;
- }
- };
- }
- getAvailableMessages() {
- const messages = this.messageBuffer;
- this.messageBuffer = [];
- const isEndOfStream = this.isEndOfStream;
- return {
- getMessages() {
- return messages;
- },
- isEndOfStream() {
- return isEndOfStream;
- }
- };
- }
- encode({ headers: rawHeaders, body }) {
- const headers = this.headerMarshaller.format(rawHeaders);
- const length = headers.byteLength + body.byteLength + 16;
- const out = new Uint8Array(length);
- const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
- const checksum7 = new import_crc324.Crc32;
- view.setUint32(0, length, false);
- view.setUint32(4, headers.byteLength, false);
- view.setUint32(8, checksum7.update(out.subarray(0, 8)).digest(), false);
- out.set(headers, 12);
- out.set(body, headers.byteLength + 12);
- view.setUint32(length - 4, checksum7.update(out.subarray(8, length - 4)).digest(), false);
- return out;
- }
- decode(message) {
- const { headers, body } = splitMessage2(message);
- return { headers: this.headerMarshaller.parse(headers), body };
- }
- formatHeaders(rawHeaders) {
- return this.headerMarshaller.format(rawHeaders);
- }
-}
-var import_crc324;
-var init_EventStreamCodec2 = __esm(() => {
- init_HeaderMarshaller2();
- init_splitMessage2();
- import_crc324 = __toESM(require_build4(), 1);
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-es/Message.js
-var init_Message2 = () => {};
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-es/MessageDecoderStream.js
-var MessageDecoderStream3;
-var init_MessageDecoderStream2 = __esm(() => {
- MessageDecoderStream3 = class MessageDecoderStream3 {
- constructor(options2) {
- this.options = options2;
- }
- [Symbol.asyncIterator]() {
- return this.asyncIterator();
- }
- async* asyncIterator() {
- for await (const bytes of this.options.inputStream) {
- const decoded = this.options.decoder.decode(bytes);
- yield decoded;
- }
- }
- };
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-es/MessageEncoderStream.js
-var MessageEncoderStream3;
-var init_MessageEncoderStream2 = __esm(() => {
- MessageEncoderStream3 = class MessageEncoderStream3 {
- constructor(options2) {
- this.options = options2;
- }
- [Symbol.asyncIterator]() {
- return this.asyncIterator();
- }
- async* asyncIterator() {
- for await (const msg of this.options.messageStream) {
- const encoded = this.options.encoder.encode(msg);
- yield encoded;
- }
- if (this.options.includeEndFrame) {
- yield new Uint8Array(0);
- }
- }
- };
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageDecoderStream.js
-var SmithyMessageDecoderStream3;
-var init_SmithyMessageDecoderStream2 = __esm(() => {
- SmithyMessageDecoderStream3 = class SmithyMessageDecoderStream3 {
- constructor(options2) {
- this.options = options2;
- }
- [Symbol.asyncIterator]() {
- return this.asyncIterator();
- }
- async* asyncIterator() {
- for await (const message of this.options.messageStream) {
- const deserialized = await this.options.deserializer(message);
- if (deserialized === undefined)
- continue;
- yield deserialized;
- }
- }
- };
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageEncoderStream.js
-var SmithyMessageEncoderStream3;
-var init_SmithyMessageEncoderStream2 = __esm(() => {
- SmithyMessageEncoderStream3 = class SmithyMessageEncoderStream3 {
- constructor(options2) {
- this.options = options2;
- }
- [Symbol.asyncIterator]() {
- return this.asyncIterator();
- }
- async* asyncIterator() {
- for await (const chunk of this.options.inputStream) {
- const payloadBuf = this.options.serializer(chunk);
- yield payloadBuf;
- }
- }
- };
-});
-
-// node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-es/index.js
-var init_dist_es57 = __esm(() => {
- init_EventStreamCodec2();
- init_HeaderMarshaller2();
- init_Int642();
- init_Message2();
- init_MessageDecoderStream2();
- init_MessageEncoderStream2();
- init_SmithyMessageDecoderStream2();
- init_SmithyMessageEncoderStream2();
-});
-
-// node_modules/@smithy/eventstream-serde-universal/dist-es/getChunkedStream.js
-function getChunkedStream2(source) {
- let currentMessageTotalLength = 0;
- let currentMessagePendingLength = 0;
- let currentMessage = null;
- let messageLengthBuffer = null;
- const allocateMessage = (size) => {
- if (typeof size !== "number") {
- throw new Error("Attempted to allocate an event message where size was not a number: " + size);
- }
- currentMessageTotalLength = size;
- currentMessagePendingLength = 4;
- currentMessage = new Uint8Array(size);
- const currentMessageView = new DataView(currentMessage.buffer);
- currentMessageView.setUint32(0, size, false);
- };
- const iterator2 = async function* () {
- const sourceIterator = source[Symbol.asyncIterator]();
- while (true) {
- const { value, done } = await sourceIterator.next();
- if (done) {
- if (!currentMessageTotalLength) {
- return;
- } else if (currentMessageTotalLength === currentMessagePendingLength) {
- yield currentMessage;
- } else {
- throw new Error("Truncated event message received.");
- }
- return;
- }
- const chunkLength = value.length;
- let currentOffset = 0;
- while (currentOffset < chunkLength) {
- if (!currentMessage) {
- const bytesRemaining = chunkLength - currentOffset;
- if (!messageLengthBuffer) {
- messageLengthBuffer = new Uint8Array(4);
- }
- const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining);
- messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength);
- currentMessagePendingLength += numBytesForTotal;
- currentOffset += numBytesForTotal;
- if (currentMessagePendingLength < 4) {
- break;
- }
- allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false));
- messageLengthBuffer = null;
- }
- const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset);
- currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength);
- currentMessagePendingLength += numBytesToWrite;
- currentOffset += numBytesToWrite;
- if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) {
- yield currentMessage;
- currentMessage = null;
- currentMessageTotalLength = 0;
- currentMessagePendingLength = 0;
- }
- }
- }
- };
- return {
- [Symbol.asyncIterator]: iterator2
- };
-}
-
-// node_modules/@smithy/eventstream-serde-universal/dist-es/getUnmarshalledStream.js
-function getMessageUnmarshaller2(deserializer, toUtf86) {
- return async function(message) {
- const { value: messageType } = message.headers[":message-type"];
- if (messageType === "error") {
- const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError");
- unmodeledError.name = message.headers[":error-code"].value;
- throw unmodeledError;
- } else if (messageType === "exception") {
- const code = message.headers[":exception-type"].value;
- const exception = { [code]: message };
- const deserializedException = await deserializer(exception);
- if (deserializedException.$unknown) {
- const error41 = new Error(toUtf86(message.body));
- error41.name = code;
- throw error41;
- }
- throw deserializedException[code];
- } else if (messageType === "event") {
- const event = {
- [message.headers[":event-type"].value]: message
- };
- const deserialized = await deserializer(event);
- if (deserialized.$unknown)
- return;
- return deserialized;
- } else {
- throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`);
- }
- };
-}
-
-// node_modules/@smithy/eventstream-serde-universal/dist-es/EventStreamMarshaller.js
-class EventStreamMarshaller5 {
- constructor({ utf8Encoder, utf8Decoder }) {
- this.eventStreamCodec = new EventStreamCodec3(utf8Encoder, utf8Decoder);
- this.utfEncoder = utf8Encoder;
- }
- deserialize(body, deserializer) {
- const inputStream = getChunkedStream2(body);
- return new SmithyMessageDecoderStream3({
- messageStream: new MessageDecoderStream3({ inputStream, decoder: this.eventStreamCodec }),
- deserializer: getMessageUnmarshaller2(deserializer, this.utfEncoder)
- });
- }
- serialize(inputStream, serializer) {
- return new MessageEncoderStream3({
- messageStream: new SmithyMessageEncoderStream3({ inputStream, serializer }),
- encoder: this.eventStreamCodec,
- includeEndFrame: true
- });
- }
-}
-var init_EventStreamMarshaller3 = __esm(() => {
- init_dist_es57();
-});
-
-// node_modules/@smithy/eventstream-serde-universal/dist-es/provider.js
-var init_provider3 = __esm(() => {
- init_EventStreamMarshaller3();
-});
-
-// node_modules/@smithy/eventstream-serde-universal/dist-es/index.js
-var init_dist_es58 = __esm(() => {
- init_EventStreamMarshaller3();
- init_provider3();
-});
-
-// node_modules/@smithy/eventstream-serde-node/dist-es/utils.js
-async function* readabletoIterable2(readStream2) {
- let streamEnded = false;
- let generationEnded = false;
- const records = new Array;
- readStream2.on("error", (err) => {
- if (!streamEnded) {
- streamEnded = true;
- }
- if (err) {
- throw err;
- }
- });
- readStream2.on("data", (data) => {
- records.push(data);
- });
- readStream2.on("end", () => {
- streamEnded = true;
- });
- while (!generationEnded) {
- const value = await new Promise((resolve9) => setTimeout(() => resolve9(records.shift()), 0));
- if (value) {
- yield value;
- }
- generationEnded = streamEnded && records.length === 0;
- }
-}
-
-// node_modules/@smithy/eventstream-serde-node/dist-es/EventStreamMarshaller.js
-import { Readable as Readable7 } from "stream";
-
-class EventStreamMarshaller7 {
- constructor({ utf8Encoder, utf8Decoder }) {
- this.universalMarshaller = new EventStreamMarshaller5({
- utf8Decoder,
- utf8Encoder
- });
- }
- deserialize(body, deserializer) {
- const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable2(body);
- return this.universalMarshaller.deserialize(bodyIterable, deserializer);
- }
- serialize(input, serializer) {
- return Readable7.from(this.universalMarshaller.serialize(input, serializer));
- }
-}
-var init_EventStreamMarshaller4 = __esm(() => {
- init_dist_es58();
-});
-
-// node_modules/@smithy/eventstream-serde-node/dist-es/provider.js
-var init_provider4 = __esm(() => {
- init_EventStreamMarshaller4();
-});
-
-// node_modules/@smithy/eventstream-serde-node/dist-es/index.js
-var init_dist_es59 = __esm(() => {
- init_EventStreamMarshaller4();
- init_provider4();
-});
-
-// node_modules/@smithy/util-base64/dist-es/fromBase64.js
-var BASE64_REGEX4, fromBase647 = (input) => {
- if (input.length * 3 % 4 !== 0) {
- throw new TypeError(`Incorrect padding on base64 string.`);
- }
- if (!BASE64_REGEX4.exec(input)) {
- throw new TypeError(`Invalid base64 string.`);
- }
- const buffer = fromString2(input, "base64");
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
-};
-var init_fromBase644 = __esm(() => {
- init_dist_es23();
- BASE64_REGEX4 = /^[A-Za-z0-9+/]*={0,2}$/;
-});
-
-// node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js
-var fromUtf812 = (input) => {
- const buf = fromString2(input, "utf8");
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
-};
-var init_fromUtf83 = __esm(() => {
- init_dist_es23();
-});
-
-// node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
-var init_toUint8Array3 = __esm(() => {
- init_fromUtf83();
-});
-
-// node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/toUtf8.js
-var init_toUtf83 = __esm(() => {
- init_dist_es23();
-});
-
-// node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/index.js
-var init_dist_es60 = __esm(() => {
- init_fromUtf83();
- init_toUint8Array3();
- init_toUtf83();
-});
-
-// node_modules/@smithy/util-base64/dist-es/toBase64.js
-var toBase647 = (_input) => {
- let input;
- if (typeof _input === "string") {
- input = fromUtf812(_input);
- } else {
- input = _input;
- }
- if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
- throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
- }
- return fromArrayBuffer2(input.buffer, input.byteOffset, input.byteLength).toString("base64");
-};
-var init_toBase644 = __esm(() => {
- init_dist_es23();
- init_dist_es60();
-});
-
-// node_modules/@smithy/util-base64/dist-es/index.js
-var init_dist_es61 = __esm(() => {
- init_fromBase644();
- init_toBase644();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/node_modules/@anthropic-ai/sdk/index.mjs
-var init_sdk2 = __esm(() => {
- init_client10();
- init_uploads3();
- init_api_promise();
- init_client10();
- init_pagination8();
- init_error3();
-});
-// node_modules/@smithy/smithy-client/node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js
-var init_MiddlewareStack = () => {};
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/middleware-stack/dist-es/index.js
-var init_dist_es62 = __esm(() => {
- init_MiddlewareStack();
-});
-
-// node_modules/@smithy/smithy-client/dist-es/client.js
-var init_client13 = __esm(() => {
- init_dist_es62();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js
-var fromUtf814 = (input) => {
- const buf = fromString2(input, "utf8");
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
-};
-var init_fromUtf84 = __esm(() => {
- init_dist_es23();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
-var init_toUint8Array4 = __esm(() => {
- init_fromUtf84();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/toUtf8.js
-var toUtf87 = (input) => {
- if (typeof input === "string") {
- return input;
- }
- if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
- throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
- }
- return fromArrayBuffer2(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
-};
-var init_toUtf84 = __esm(() => {
- init_dist_es23();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/index.js
-var init_dist_es63 = __esm(() => {
- init_fromUtf84();
- init_toUint8Array4();
- init_toUtf84();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-es/blob/transforms.js
-function transformToString(payload, encoding = "utf-8") {
- if (encoding === "base64") {
- return toBase647(payload);
- }
- return toUtf87(payload);
-}
-function transformFromString(str, encoding) {
- if (encoding === "base64") {
- return Uint8ArrayBlobAdapter.mutate(fromBase647(str));
- }
- return Uint8ArrayBlobAdapter.mutate(fromUtf814(str));
-}
-var init_transforms = __esm(() => {
- init_dist_es61();
- init_dist_es63();
- init_Uint8ArrayBlobAdapter();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js
-var Uint8ArrayBlobAdapter;
-var init_Uint8ArrayBlobAdapter = __esm(() => {
- init_transforms();
- Uint8ArrayBlobAdapter = class Uint8ArrayBlobAdapter extends Uint8Array {
- static fromString(source, encoding = "utf-8") {
- switch (typeof source) {
- case "string":
- return transformFromString(source, encoding);
- default:
- throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`);
- }
- }
- static mutate(source) {
- Object.setPrototypeOf(source, Uint8ArrayBlobAdapter.prototype);
- return source;
- }
- transformToString(encoding = "utf-8") {
- return transformToString(this, encoding);
- }
- };
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.js
-var init_getAwsChunkedEncodingStream = () => {};
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js
-var init_escape_uri_path2 = () => {};
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-es/index.js
-var init_dist_es64 = __esm(() => {
- init_escape_uri_path2();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-es/index.js
-var init_dist_es65 = __esm(() => {
- init_dist_es64();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-es/constants.js
-var init_constants7 = () => {};
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-es/get-transformed-headers.js
-var init_get_transformed_headers = () => {};
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-es/write-request-body.js
-var init_write_request_body = () => {};
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js
-var init_node_http_handler = __esm(() => {
- init_dist_es48();
- init_dist_es65();
- init_constants7();
- init_get_transformed_headers();
- init_write_request_body();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-pool.js
-var init_node_http2_connection_pool = () => {};
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-manager.js
-var init_node_http2_connection_manager = __esm(() => {
- init_node_http2_connection_pool();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-es/node-http2-handler.js
-var init_node_http2_handler = __esm(() => {
- init_dist_es48();
- init_dist_es65();
- init_get_transformed_headers();
- init_node_http2_connection_manager();
- init_write_request_body();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-es/stream-collector/collector.js
-var init_collector = () => {};
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js
-var init_stream_collector = __esm(() => {
- init_collector();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-es/index.js
-var init_dist_es66 = __esm(() => {
- init_node_http_handler();
- init_node_http2_handler();
- init_stream_collector();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js
-var init_sdk_stream_mixin = __esm(() => {
- init_dist_es66();
- init_dist_es23();
-});
-
-// node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-es/index.js
-var init_dist_es67 = __esm(() => {
- init_Uint8ArrayBlobAdapter();
- init_getAwsChunkedEncodingStream();
- init_sdk_stream_mixin();
-});
-
-// node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js
-var collectBody5 = async (streamBody = new Uint8Array, context) => {
- if (streamBody instanceof Uint8Array) {
- return Uint8ArrayBlobAdapter.mutate(streamBody);
- }
- if (!streamBody) {
- return Uint8ArrayBlobAdapter.mutate(new Uint8Array);
- }
- const fromContext = context.streamCollector(streamBody);
- return Uint8ArrayBlobAdapter.mutate(await fromContext);
-};
-var init_collect_stream_body5 = __esm(() => {
- init_dist_es67();
-});
-
-// node_modules/@smithy/smithy-client/dist-es/command.js
-var init_command13 = __esm(() => {
- init_dist_es62();
- init_dist_es47();
-});
-// node_modules/@smithy/smithy-client/dist-es/parse-utils.js
-var MAX_FLOAT, expectLong = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- if (Number.isInteger(value) && !Number.isNaN(value)) {
- return value;
- }
- throw new TypeError(`Expected integer, got ${typeof value}: ${value}`);
-}, expectInt32 = (value) => expectSizedInt(value, 32), expectSizedInt = (value, size) => {
- const expected = expectLong(value);
- if (expected !== undefined && castInt(expected, size) !== expected) {
- throw new TypeError(`Expected ${size}-bit integer, got ${value}`);
- }
- return expected;
-}, castInt = (value, size) => {
- switch (size) {
- case 32:
- return Int32Array.of(value)[0];
- case 16:
- return Int16Array.of(value)[0];
- case 8:
- return Int8Array.of(value)[0];
- }
-}, expectString = (value) => {
- if (value === null || value === undefined) {
- return;
- }
- if (typeof value === "string") {
- return value;
- }
- if (["boolean", "number", "bigint"].includes(typeof value)) {
- logger7.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));
- return String(value);
- }
- throw new TypeError(`Expected string, got ${typeof value}: ${value}`);
-}, stackTraceWarning = (message) => {
- return String(new TypeError(message).stack || message).split(`
-`).slice(0, 5).filter((s4) => !s4.includes("stackTraceWarning")).join(`
-`);
-}, logger7;
-var init_parse_utils = __esm(() => {
- MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
- logger7 = {
- warn: console.warn
- };
-});
-
-// node_modules/@smithy/smithy-client/dist-es/date-utils.js
-var RFC3339, RFC3339_WITH_OFFSET, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, FIFTY_YEARS_IN_MILLIS;
-var init_date_utils = __esm(() => {
- init_parse_utils();
- RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);
- RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);
- IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
- RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
- ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);
- FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1000;
-});
-
-// node_modules/@smithy/smithy-client/dist-es/exceptions.js
-var decorateServiceException5 = (exception, additions = {}) => {
- Object.entries(additions).filter(([, v4]) => v4 !== undefined).forEach(([k4, v4]) => {
- if (exception[k4] == undefined || exception[k4] === "") {
- exception[k4] = v4;
- }
- });
- const message = exception.message || exception.Message || "UnknownError";
- exception.message = message;
- delete exception.Message;
- return exception;
-};
-var init_exceptions5 = () => {};
-
-// node_modules/@smithy/smithy-client/dist-es/default-error-handler.js
-var init_default_error_handler5 = __esm(() => {
- init_exceptions5();
-});
-// node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js
-var init_checksum17 = __esm(() => {
- init_dist_es47();
-});
-// node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js
-var init_defaultExtensionConfiguration11 = __esm(() => {
- init_checksum17();
-});
-
-// node_modules/@smithy/smithy-client/dist-es/extensions/index.js
-var init_extensions19 = __esm(() => {
- init_defaultExtensionConfiguration11();
-});
-// node_modules/@smithy/smithy-client/dist-es/lazy-json.js
-var StringWrapper = function() {
- const Class2 = Object.getPrototypeOf(this).constructor;
- const Constructor = Function.bind.apply(String, [null, ...arguments]);
- const instance = new Constructor;
- Object.setPrototypeOf(instance, Class2.prototype);
- return instance;
-};
-var init_lazy_json = __esm(() => {
- StringWrapper.prototype = Object.create(String.prototype, {
- constructor: {
- value: StringWrapper,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- Object.setPrototypeOf(StringWrapper, String);
-});
-
-// node_modules/@smithy/smithy-client/dist-es/object-mapping.js
-function map6(arg0, arg1, arg2) {
- let target;
- let filter2;
- let instructions;
- if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
- target = {};
- instructions = arg0;
- } else {
- target = arg0;
- if (typeof arg1 === "function") {
- filter2 = arg1;
- instructions = arg2;
- return mapWithFilter5(target, filter2, instructions);
- } else {
- instructions = arg1;
- }
- }
- for (const key of Object.keys(instructions)) {
- if (!Array.isArray(instructions[key])) {
- target[key] = instructions[key];
- continue;
- }
- applyInstruction5(target, null, instructions, key);
- }
- return target;
-}
-var take5 = (source, instructions) => {
- const out = {};
- for (const key in instructions) {
- applyInstruction5(out, source, instructions, key);
- }
- return out;
-}, mapWithFilter5 = (target, filter2, instructions) => {
- return map6(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
- if (Array.isArray(value)) {
- _instructions[key] = value;
- } else {
- if (typeof value === "function") {
- _instructions[key] = [filter2, value()];
- } else {
- _instructions[key] = [filter2, value];
- }
- }
- return _instructions;
- }, {}));
-}, applyInstruction5 = (target, source, instructions, targetKey) => {
- if (source !== null) {
- let instruction = instructions[targetKey];
- if (typeof instruction === "function") {
- instruction = [, instruction];
- }
- const [filter3 = nonNullish5, valueFn = pass5, sourceKey = targetKey] = instruction;
- if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) {
- target[targetKey] = valueFn(source[sourceKey]);
- }
- return;
- }
- let [filter2, value] = instructions[targetKey];
- if (typeof value === "function") {
- let _value;
- const defaultFilterPassed = filter2 === undefined && (_value = value()) != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(undefined) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed) {
- target[targetKey] = _value;
- } else if (customFilterPassed) {
- target[targetKey] = value();
- }
- } else {
- const defaultFilterPassed = filter2 === undefined && value != null;
- const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
- if (defaultFilterPassed || customFilterPassed) {
- target[targetKey] = value;
- }
- }
-}, nonNullish5 = (_) => _ != null, pass5 = (_) => _;
-
-// node_modules/@smithy/smithy-client/dist-es/resolve-path.js
-var init_resolve_path5 = () => {};
-// node_modules/@smithy/smithy-client/dist-es/index.js
-var init_dist_es68 = __esm(() => {
- init_client13();
- init_collect_stream_body5();
- init_command13();
- init_date_utils();
- init_default_error_handler5();
- init_extensions19();
- init_exceptions5();
- init_lazy_json();
- init_parse_utils();
- init_resolve_path5();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/AWS_restJson1.mjs
-var de_InternalServerExceptionRes = async (parsedOutput, context) => {
- const contents = map6({});
- const data = parsedOutput.body;
- const doc2 = take5(data, {
- message: expectString
- });
- Object.assign(contents, doc2);
- const exception = new InternalServerException2({
- $metadata: deserializeMetadata5(parsedOutput),
- ...contents
- });
- return decorateServiceException5(exception, parsedOutput.body);
-}, de_ModelStreamErrorExceptionRes = async (parsedOutput, context) => {
- const contents = map6({});
- const data = parsedOutput.body;
- const doc2 = take5(data, {
- message: expectString,
- originalMessage: expectString,
- originalStatusCode: expectInt32
- });
- Object.assign(contents, doc2);
- const exception = new ModelStreamErrorException({
- $metadata: deserializeMetadata5(parsedOutput),
- ...contents
- });
- return decorateServiceException5(exception, parsedOutput.body);
-}, de_ThrottlingExceptionRes = async (parsedOutput, context) => {
- const contents = map6({});
- const data = parsedOutput.body;
- const doc2 = take5(data, {
- message: expectString
- });
- Object.assign(contents, doc2);
- const exception = new ThrottlingException2({
- $metadata: deserializeMetadata5(parsedOutput),
- ...contents
- });
- return decorateServiceException5(exception, parsedOutput.body);
-}, de_ValidationExceptionRes = async (parsedOutput, context) => {
- const contents = map6({});
- const data = parsedOutput.body;
- const doc2 = take5(data, {
- message: expectString
- });
- Object.assign(contents, doc2);
- const exception = new ValidationException2({
- $metadata: deserializeMetadata5(parsedOutput),
- ...contents
- });
- return decorateServiceException5(exception, parsedOutput.body);
-}, de_ResponseStream = (output, context) => {
- return context.eventStreamMarshaller.deserialize(output, async (event) => {
- if (event["chunk"] != null) {
- return {
- chunk: await de_PayloadPart_event(event["chunk"], context)
- };
- }
- if (event["internalServerException"] != null) {
- return {
- internalServerException: await de_InternalServerException_event(event["internalServerException"], context)
- };
- }
- if (event["modelStreamErrorException"] != null) {
- return {
- modelStreamErrorException: await de_ModelStreamErrorException_event(event["modelStreamErrorException"], context)
- };
- }
- if (event["validationException"] != null) {
- return {
- validationException: await de_ValidationException_event(event["validationException"], context)
- };
- }
- if (event["throttlingException"] != null) {
- return {
- throttlingException: await de_ThrottlingException_event(event["throttlingException"], context)
- };
- }
- return { $unknown: output };
- });
-}, de_InternalServerException_event = async (output, context) => {
- const parsedOutput = {
- ...output,
- body: await parseBody(output.body, context)
- };
- return de_InternalServerExceptionRes(parsedOutput, context);
-}, de_ModelStreamErrorException_event = async (output, context) => {
- const parsedOutput = {
- ...output,
- body: await parseBody(output.body, context)
- };
- return de_ModelStreamErrorExceptionRes(parsedOutput, context);
-}, de_PayloadPart_event = async (output, context) => {
- const contents = {};
- const data = await parseBody(output.body, context);
- Object.assign(contents, de_PayloadPart(data, context));
- return contents;
-}, de_ThrottlingException_event = async (output, context) => {
- const parsedOutput = {
- ...output,
- body: await parseBody(output.body, context)
- };
- return de_ThrottlingExceptionRes(parsedOutput, context);
-}, de_ValidationException_event = async (output, context) => {
- const parsedOutput = {
- ...output,
- body: await parseBody(output.body, context)
- };
- return de_ValidationExceptionRes(parsedOutput, context);
-}, de_PayloadPart = (output, context) => {
- return take5(output, {
- bytes: context.base64Decoder
- });
-}, deserializeMetadata5 = (output) => ({
- httpStatusCode: output.statusCode,
- requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"] ?? "",
- extendedRequestId: output.headers["x-amz-id-2"] ?? "",
- cfId: output.headers["x-amz-cf-id"] ?? ""
-}), collectBodyString = (streamBody, context) => collectBody5(streamBody, context).then((body) => context.utf8Encoder(body)), parseBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
- if (encoded.length) {
- return JSON.parse(encoded);
- }
- return {};
-});
-var init_AWS_restJson1 = __esm(() => {
- init_dist_es68();
- init_dist_es38();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/internal/shims.mjs
-function ReadableStreamToAsyncIterable3(stream10) {
- if (stream10[Symbol.asyncIterator])
- return stream10;
- const reader = stream10.getReader();
- return {
- async next() {
- try {
- const result = await reader.read();
- if (result?.done)
- reader.releaseLock();
- return result;
- } catch (e4) {
- reader.releaseLock();
- throw e4;
- }
- },
- async return() {
- const cancelPromise = reader.cancel();
- reader.releaseLock();
- await cancelPromise;
- return { done: true, value: undefined };
- },
- [Symbol.asyncIterator]() {
- return this;
- }
- };
-}
-
-// node_modules/@anthropic-ai/bedrock-sdk/core/error.mjs
-var init_error5 = __esm(() => {
- init_error3();
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/internal/utils/values.mjs
-function isObj2(obj) {
- return obj != null && typeof obj === "object" && !Array.isArray(obj);
-}
-var isArray4 = (val) => (isArray4 = Array.isArray, isArray4(val)), isReadonlyArray2, safeJSON3 = (text) => {
- try {
- return JSON.parse(text);
- } catch (err) {
- return;
- }
-};
-var init_values3 = __esm(() => {
- init_error5();
- isReadonlyArray2 = isArray4;
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/internal/utils/log.mjs
-function noop7() {}
-function makeLogFn2(fnLevel, logger8, logLevel) {
- if (!logger8 || levelNumbers2[fnLevel] > levelNumbers2[logLevel]) {
- return noop7;
- } else {
- return logger8[fnLevel].bind(logger8);
- }
-}
-function loggerFor2(client12) {
- const logger8 = client12.logger;
- const logLevel = client12.logLevel ?? "off";
- if (!logger8) {
- return noopLogger2;
- }
- const cachedLogger = cachedLoggers2.get(logger8);
- if (cachedLogger && cachedLogger[0] === logLevel) {
- return cachedLogger[1];
- }
- const levelLogger = {
- error: makeLogFn2("error", logger8, logLevel),
- warn: makeLogFn2("warn", logger8, logLevel),
- info: makeLogFn2("info", logger8, logLevel),
- debug: makeLogFn2("debug", logger8, logLevel)
- };
- cachedLoggers2.set(logger8, [logLevel, levelLogger]);
- return levelLogger;
-}
-var levelNumbers2, noopLogger2, cachedLoggers2;
-var init_log4 = __esm(() => {
- init_values3();
- levelNumbers2 = {
- off: 0,
- error: 200,
- warn: 300,
- info: 400,
- debug: 500
- };
- noopLogger2 = {
- error: noop7,
- warn: noop7,
- info: noop7,
- debug: noop7
- };
- cachedLoggers2 = /* @__PURE__ */ new WeakMap;
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/core/streaming.mjs
-function isAbortError4(err) {
- return typeof err === "object" && err !== null && (("name" in err) && err.name === "AbortError" || ("message" in err) && String(err.message).includes("FetchRequestCanceledException"));
-}
-var import_fetch_http_handler2, toUtf89 = (input) => new TextDecoder("utf-8").decode(input), fromUtf816 = (input) => new TextEncoder().encode(input), getMinimalSerdeContext = () => {
- const marshaller = new EventStreamMarshaller7({ utf8Encoder: toUtf89, utf8Decoder: fromUtf816 });
- return {
- base64Decoder: fromBase647,
- base64Encoder: toBase647,
- utf8Decoder: fromUtf816,
- utf8Encoder: toUtf89,
- eventStreamMarshaller: marshaller,
- streamCollector: import_fetch_http_handler2.streamCollector
- };
-}, Stream3;
-var init_streaming5 = __esm(() => {
- init_dist_es59();
- init_dist_es61();
- init_streaming4();
- init_error4();
- init_sdk2();
- init_AWS_restJson1();
- init_values3();
- init_log4();
- import_fetch_http_handler2 = __toESM(require_dist_cjs24(), 1);
- Stream3 = class Stream3 extends Stream2 {
- static fromSSEResponse(response7, controller, client12) {
- let consumed = false;
- const logger8 = client12 ? loggerFor2(client12) : console;
- async function* iterMessages() {
- if (!response7.body) {
- controller.abort();
- throw new AnthropicError2(`Attempted to iterate over a response with no body`);
- }
- const responseBodyIter = ReadableStreamToAsyncIterable3(response7.body);
- const eventStream7 = de_ResponseStream(responseBodyIter, getMinimalSerdeContext());
- for await (const event of eventStream7) {
- if (event.chunk && event.chunk.bytes) {
- const s4 = toUtf89(event.chunk.bytes);
- yield { event: "chunk", data: s4, raw: [] };
- } else if (event.internalServerException) {
- yield { event: "error", data: "InternalServerException", raw: [] };
- } else if (event.modelStreamErrorException) {
- yield { event: "error", data: "ModelStreamErrorException", raw: [] };
- } else if (event.validationException) {
- yield { event: "error", data: "ValidationException", raw: [] };
- } else if (event.throttlingException) {
- yield { event: "error", data: "ThrottlingException", raw: [] };
- }
- }
- }
- async function* iterator2() {
- if (consumed) {
- throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
- }
- consumed = true;
- let done = false;
- try {
- for await (const sse of iterMessages()) {
- if (sse.event === "chunk") {
- try {
- yield JSON.parse(sse.data);
- } catch (e4) {
- logger8.error(`Could not parse message into JSON:`, sse.data);
- logger8.error(`From chunk:`, sse.raw);
- throw e4;
- }
- }
- if (sse.event === "error") {
- const errText = sse.data;
- const errJSON = safeJSON3(errText);
- const errMessage = errJSON ? undefined : errText;
- throw APIError2.generate(undefined, errJSON, errMessage, response7.headers);
- }
- }
- done = true;
- } catch (e4) {
- if (isAbortError4(e4))
- return;
- throw e4;
- } finally {
- if (!done)
- controller.abort();
- }
- }
- return new Stream3(iterator2, controller);
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/internal/utils/env.mjs
-var readEnv3 = (env4) => {
- if (typeof globalThis.process !== "undefined") {
- return globalThis.process.env?.[env4]?.trim() ?? undefined;
- }
- if (typeof globalThis.Deno !== "undefined") {
- return globalThis.Deno.env?.get?.(env4)?.trim();
- }
- return;
-};
-
-// node_modules/@anthropic-ai/bedrock-sdk/internal/headers.mjs
-function* iterateHeaders2(headers) {
- if (!headers)
- return;
- if (brand_privateNullableHeaders2 in headers) {
- const { values, nulls } = headers;
- yield* values.entries();
- for (const name of nulls) {
- yield [name, null];
- }
- return;
- }
- let shouldClear = false;
- let iter;
- if (headers instanceof Headers) {
- iter = headers.entries();
- } else if (isReadonlyArray2(headers)) {
- iter = headers;
- } else {
- shouldClear = true;
- iter = Object.entries(headers ?? {});
- }
- for (let row of iter) {
- const name = row[0];
- if (typeof name !== "string")
- throw new TypeError("expected header name to be a string");
- const values = isReadonlyArray2(row[1]) ? row[1] : [row[1]];
- let didClear = false;
- for (const value of values) {
- if (value === undefined)
- continue;
- if (shouldClear && !didClear) {
- didClear = true;
- yield [name, null];
- }
- yield [name, value];
- }
- }
-}
-var brand_privateNullableHeaders2, buildHeaders2 = (newHeaders) => {
- const targetHeaders = new Headers;
- const nullHeaders = new Set;
- for (const headers of newHeaders) {
- const seenHeaders = new Set;
- for (const [name, value] of iterateHeaders2(headers)) {
- const lowerName = name.toLowerCase();
- if (!seenHeaders.has(lowerName)) {
- targetHeaders.delete(name);
- seenHeaders.add(lowerName);
- }
- if (value === null) {
- targetHeaders.delete(name);
- nullHeaders.add(lowerName);
- } else {
- targetHeaders.append(name, value);
- nullHeaders.delete(lowerName);
- }
- }
- }
- return { [brand_privateNullableHeaders2]: true, values: targetHeaders, nulls: nullHeaders };
-};
-var init_headers2 = __esm(() => {
- init_values3();
- brand_privateNullableHeaders2 = Symbol.for("brand.privateNullableHeaders");
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/internal/utils/path.mjs
-function encodeURIPath2(str) {
- return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
-}
-var EMPTY2, createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path9(statics, ...params) {
- if (statics.length === 1)
- return statics[0];
- let postPath = false;
- const invalidSegments = [];
- const path10 = statics.reduce((previousValue, currentValue, index2) => {
- if (/[?#]/.test(currentValue)) {
- postPath = true;
- }
- const value = params[index2];
- let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
- if (index2 !== params.length && (value == null || typeof value === "object" && value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY2) ?? EMPTY2)?.toString)) {
- encoded = value + "";
- invalidSegments.push({
- start: previousValue.length + currentValue.length,
- length: encoded.length,
- error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
- });
- }
- return previousValue + currentValue + (index2 === params.length ? "" : encoded);
- }, "");
- const pathOnly = path10.split(/[?#]/, 1)[0];
- const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
- let match;
- while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
- invalidSegments.push({
- start: match.index,
- length: match[0].length,
- error: `Value "${match[0]}" can't be safely passed as a path parameter`
- });
- }
- invalidSegments.sort((a5, b4) => a5.start - b4.start);
- if (invalidSegments.length > 0) {
- let lastEnd = 0;
- const underline2 = invalidSegments.reduce((acc, segment) => {
- const spaces = " ".repeat(segment.start - lastEnd);
- const arrows = "^".repeat(segment.length);
- lastEnd = segment.start + segment.length;
- return acc + spaces + arrows;
- }, "");
- throw new AnthropicError2(`Path parameters result in path with invalid segments:
-${invalidSegments.map((e4) => e4.error).join(`
-`)}
-${path10}
-${underline2}`);
- }
- return path10;
-}, path9;
-var init_path3 = __esm(() => {
- init_error5();
- EMPTY2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
- path9 = /* @__PURE__ */ createPathTagFunction2(encodeURIPath2);
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/client.mjs
-function makeMessagesResource(client12) {
- const resource = new Messages5(client12);
- delete resource.batches;
- delete resource.countTokens;
- return resource;
-}
-function makeBetaResource(client12) {
- const resource = new Beta2(client12);
- delete resource.promptCaching;
- delete resource.messages.batches;
- delete resource.messages.countTokens;
- return resource;
-}
-var DEFAULT_VERSION = "bedrock-2023-05-31", MODEL_ENDPOINTS, AnthropicBedrock;
-var init_client14 = __esm(() => {
- init_client10();
- init_resources2();
- init_auth13();
- init_streaming5();
- init_values3();
- init_headers2();
- init_path3();
- init_log4();
- init_client10();
- MODEL_ENDPOINTS = new Set(["/v1/complete", "/v1/messages", "/v1/messages?beta=true"]);
- AnthropicBedrock = class AnthropicBedrock extends BaseAnthropic {
- constructor({ awsRegion = readEnv3("AWS_REGION") ?? "us-east-1", baseURL = readEnv3("ANTHROPIC_BEDROCK_BASE_URL") ?? `https://bedrock-runtime.${awsRegion}.amazonaws.com`, awsSecretKey = null, awsAccessKey = null, awsSessionToken = null, providerChainResolver = null, ...opts } = {}) {
- super({ baseURL, ...opts });
- this.skipAuth = false;
- this.messages = makeMessagesResource(this);
- this.completions = new Completions2(this);
- this.beta = makeBetaResource(this);
- const hasAccess = awsAccessKey != null;
- const hasSecret = awsSecretKey != null;
- if (hasAccess !== hasSecret) {
- loggerFor2(this).warn("Warning: Passing only one of `awsAccessKey` or `awsSecretKey` is deprecated. " + "Please provide both keys, or provide neither and rely on the AWS credential provider chain.");
- }
- this.awsSecretKey = awsSecretKey;
- this.awsAccessKey = awsAccessKey;
- this.awsRegion = awsRegion;
- this.awsSessionToken = awsSessionToken;
- this.skipAuth = opts.skipAuth ?? false;
- this.providerChainResolver = providerChainResolver;
- }
- validateHeaders() {}
- async prepareRequest(request2, { url: url3, options: options2 }) {
- if (this.skipAuth) {
- return;
- }
- const regionName = this.awsRegion;
- if (!regionName) {
- throw new Error("Expected `awsRegion` option to be passed to the client or the `AWS_REGION` environment variable to be present");
- }
- const headers = await getAuthHeaders(request2, {
- url: url3,
- regionName,
- awsAccessKey: this.awsAccessKey,
- awsSecretKey: this.awsSecretKey,
- awsSessionToken: this.awsSessionToken,
- fetchOptions: this.fetchOptions,
- providerChainResolver: this.providerChainResolver
- });
- request2.headers = buildHeaders2([headers, request2.headers]).values;
- }
- async buildRequest(options2) {
- options2.__streamClass = Stream3;
- if (isObj2(options2.body)) {
- options2.body = { ...options2.body };
- }
- if (isObj2(options2.body)) {
- if (!options2.body["anthropic_version"]) {
- options2.body["anthropic_version"] = DEFAULT_VERSION;
- }
- if (options2.headers && !options2.body["anthropic_beta"]) {
- const betas = buildHeaders2([options2.headers]).values.get("anthropic-beta");
- if (betas != null) {
- options2.body["anthropic_beta"] = betas.split(",");
- }
- }
- }
- if (MODEL_ENDPOINTS.has(options2.path) && options2.method === "post") {
- if (!isObj2(options2.body)) {
- throw new Error("Expected request body to be an object for post /v1/messages");
- }
- const model = options2.body["model"];
- options2.body["model"] = undefined;
- const stream10 = options2.body["stream"];
- options2.body["stream"] = undefined;
- if (stream10) {
- options2.path = path9`/model/${model}/invoke-with-response-stream`;
- } else {
- options2.path = path9`/model/${model}/invoke`;
- }
- }
- return super.buildRequest(options2);
- }
- };
-});
-
-// node_modules/@anthropic-ai/bedrock-sdk/index.mjs
-var exports_bedrock_sdk = {};
-__export(exports_bedrock_sdk, {
- default: () => AnthropicBedrock,
- BaseAnthropic: () => BaseAnthropic,
- AnthropicBedrock: () => AnthropicBedrock
-});
-var init_bedrock_sdk = __esm(() => {
- init_client14();
- init_client14();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/errors.mjs
-function isAbortError5(err) {
- return typeof err === "object" && err !== null && (("name" in err) && err.name === "AbortError" || ("message" in err) && String(err.message).includes("FetchRequestCanceledException"));
-}
-var castToError3 = (err) => {
- if (err instanceof Error)
- return err;
- if (typeof err === "object" && err !== null) {
- try {
- if (Object.prototype.toString.call(err) === "[object Error]") {
- const error42 = new Error(err.message, err.cause ? { cause: err.cause } : {});
- if (err.stack)
- error42.stack = err.stack;
- if (err.cause && !error42.cause)
- error42.cause = err.cause;
- if (err.name)
- error42.name = err.name;
- return error42;
- }
- } catch {}
- try {
- return new Error(JSON.stringify(err));
- } catch {}
- }
- return new Error(err);
-};
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/core/error.mjs
-var AnthropicError3, APIError3, APIUserAbortError3, APIConnectionError3, APIConnectionTimeoutError3, BadRequestError3, AuthenticationError3, PermissionDeniedError3, NotFoundError3, ConflictError3, UnprocessableEntityError3, RateLimitError3, InternalServerError3;
-var init_error6 = __esm(() => {
- AnthropicError3 = class AnthropicError3 extends Error {
- };
- APIError3 = class APIError3 extends AnthropicError3 {
- constructor(status, error42, message, headers) {
- super(`${APIError3.makeMessage(status, error42, message)}`);
- this.status = status;
- this.headers = headers;
- this.requestID = headers?.get("request-id");
- this.error = error42;
- }
- static makeMessage(status, error42, message) {
- const msg = error42?.message ? typeof error42.message === "string" ? error42.message : JSON.stringify(error42.message) : error42 ? JSON.stringify(error42) : message;
- if (status && msg) {
- return `${status} ${msg}`;
- }
- if (status) {
- return `${status} status code (no body)`;
- }
- if (msg) {
- return msg;
- }
- return "(no status code or body)";
- }
- static generate(status, errorResponse, message, headers) {
- if (!status || !headers) {
- return new APIConnectionError3({ message, cause: castToError3(errorResponse) });
- }
- const error42 = errorResponse;
- if (status === 400) {
- return new BadRequestError3(status, error42, message, headers);
- }
- if (status === 401) {
- return new AuthenticationError3(status, error42, message, headers);
- }
- if (status === 403) {
- return new PermissionDeniedError3(status, error42, message, headers);
- }
- if (status === 404) {
- return new NotFoundError3(status, error42, message, headers);
- }
- if (status === 409) {
- return new ConflictError3(status, error42, message, headers);
- }
- if (status === 422) {
- return new UnprocessableEntityError3(status, error42, message, headers);
- }
- if (status === 429) {
- return new RateLimitError3(status, error42, message, headers);
- }
- if (status >= 500) {
- return new InternalServerError3(status, error42, message, headers);
- }
- return new APIError3(status, error42, message, headers);
- }
- };
- APIUserAbortError3 = class APIUserAbortError3 extends APIError3 {
- constructor({ message } = {}) {
- super(undefined, undefined, message || "Request was aborted.", undefined);
- }
- };
- APIConnectionError3 = class APIConnectionError3 extends APIError3 {
- constructor({ message, cause }) {
- super(undefined, undefined, message || "Connection error.", undefined);
- if (cause)
- this.cause = cause;
- }
- };
- APIConnectionTimeoutError3 = class APIConnectionTimeoutError3 extends APIConnectionError3 {
- constructor({ message } = {}) {
- super({ message: message ?? "Request timed out." });
- }
- };
- BadRequestError3 = class BadRequestError3 extends APIError3 {
- };
- AuthenticationError3 = class AuthenticationError3 extends APIError3 {
- };
- PermissionDeniedError3 = class PermissionDeniedError3 extends APIError3 {
- };
- NotFoundError3 = class NotFoundError3 extends APIError3 {
- };
- ConflictError3 = class ConflictError3 extends APIError3 {
- };
- UnprocessableEntityError3 = class UnprocessableEntityError3 extends APIError3 {
- };
- RateLimitError3 = class RateLimitError3 extends APIError3 {
- };
- InternalServerError3 = class InternalServerError3 extends APIError3 {
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/core/error.mjs
-var init_error7 = __esm(() => {
- init_error6();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/internal/utils/values.mjs
-var isArray5 = (val) => (isArray5 = Array.isArray, isArray5(val)), isReadonlyArray3;
-var init_values4 = __esm(() => {
- init_error7();
- isReadonlyArray3 = isArray5;
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/internal/headers.mjs
-function* iterateHeaders3(headers) {
- if (!headers)
- return;
- if (brand_privateNullableHeaders3 in headers) {
- const { values, nulls } = headers;
- yield* values.entries();
- for (const name of nulls) {
- yield [name, null];
- }
- return;
- }
- let shouldClear = false;
- let iter;
- if (headers instanceof Headers) {
- iter = headers.entries();
- } else if (isReadonlyArray3(headers)) {
- iter = headers;
- } else {
- shouldClear = true;
- iter = Object.entries(headers ?? {});
- }
- for (let row of iter) {
- const name = row[0];
- if (typeof name !== "string")
- throw new TypeError("expected header name to be a string");
- const values = isReadonlyArray3(row[1]) ? row[1] : [row[1]];
- let didClear = false;
- for (const value of values) {
- if (value === undefined)
- continue;
- if (shouldClear && !didClear) {
- didClear = true;
- yield [name, null];
- }
- yield [name, value];
- }
- }
-}
-var brand_privateNullableHeaders3, buildHeaders3 = (newHeaders) => {
- const targetHeaders = new Headers;
- const nullHeaders = new Set;
- for (const headers of newHeaders) {
- const seenHeaders = new Set;
- for (const [name, value] of iterateHeaders3(headers)) {
- const lowerName = name.toLowerCase();
- if (!seenHeaders.has(lowerName)) {
- targetHeaders.delete(name);
- seenHeaders.add(lowerName);
- }
- if (value === null) {
- targetHeaders.delete(name);
- nullHeaders.add(lowerName);
- } else {
- targetHeaders.append(name, value);
- nullHeaders.delete(lowerName);
- }
- }
- }
- return { [brand_privateNullableHeaders3]: true, values: targetHeaders, nulls: nullHeaders };
-};
-var init_headers3 = __esm(() => {
- init_values4();
- brand_privateNullableHeaders3 = Symbol.for("brand.privateNullableHeaders");
-});
-// node_modules/@anthropic-ai/foundry-sdk/internal/utils/base64.mjs
-var init_base64 = __esm(() => {
- init_error7();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/internal/utils/env.mjs
-var readEnv4 = (env4) => {
- if (typeof globalThis.process !== "undefined") {
- return globalThis.process.env?.[env4]?.trim() ?? undefined;
- }
- if (typeof globalThis.Deno !== "undefined") {
- return globalThis.Deno.env?.get?.(env4)?.trim();
- }
- return;
-};
-
-// node_modules/@anthropic-ai/foundry-sdk/internal/utils/log.mjs
-var init_log5 = __esm(() => {
- init_values4();
-});
-// node_modules/@anthropic-ai/foundry-sdk/internal/utils.mjs
-var init_utils3 = __esm(() => {
- init_values4();
- init_base64();
- init_log5();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/tslib.mjs
-function __classPrivateFieldSet7(receiver, state, value, kind2, f4) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a setter");
- if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return kind2 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
-}
-function __classPrivateFieldGet7(receiver, state, kind2, f4) {
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a getter");
- if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind2 === "m" ? f4 : kind2 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver);
-}
-var init_tslib2 = () => {};
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs
-var uuid44 = function() {
- const { crypto: crypto9 } = globalThis;
- if (crypto9?.randomUUID) {
- uuid44 = crypto9.randomUUID.bind(crypto9);
- return crypto9.randomUUID();
- }
- const u8 = new Uint8Array(1);
- const randomByte = crypto9 ? () => crypto9.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
- return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c8) => (+c8 ^ randomByte() & 15 >> +c8 / 4).toString(16));
-};
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs
-function maybeObj2(x3) {
- if (typeof x3 !== "object") {
- return {};
- }
- return x3 ?? {};
-}
-function isEmptyObj3(obj) {
- if (!obj)
- return true;
- for (const _k3 in obj)
- return false;
- return true;
-}
-function hasOwn5(obj, key) {
- return Object.prototype.hasOwnProperty.call(obj, key);
-}
-var startsWithSchemeRegexp3, isAbsoluteURL4 = (url3) => {
- return startsWithSchemeRegexp3.test(url3);
-}, isArray6 = (val) => (isArray6 = Array.isArray, isArray6(val)), isReadonlyArray4, validatePositiveInteger3 = (name, n5) => {
- if (typeof n5 !== "number" || !Number.isInteger(n5)) {
- throw new AnthropicError3(`${name} must be an integer`);
- }
- if (n5 < 0) {
- throw new AnthropicError3(`${name} must be a positive integer`);
- }
- return n5;
-}, safeJSON4 = (text) => {
- try {
- return JSON.parse(text);
- } catch (err) {
- return;
- }
-};
-var init_values5 = __esm(() => {
- init_error6();
- startsWithSchemeRegexp3 = /^[a-z][a-z0-9+.-]*:/i;
- isReadonlyArray4 = isArray6;
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs
-var sleep4 = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/version.mjs
-var VERSION5 = "0.80.0";
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs
-function getDetectedPlatform2() {
- if (typeof Deno !== "undefined" && Deno.build != null) {
- return "deno";
- }
- if (typeof EdgeRuntime !== "undefined") {
- return "edge";
- }
- if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
- return "node";
- }
- return "unknown";
-}
-function getBrowserInfo3() {
- if (typeof navigator === "undefined" || !navigator) {
- return null;
- }
- const browserPatterns = [
- { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
- ];
- for (const { key, pattern } of browserPatterns) {
- const match = pattern.exec(navigator.userAgent);
- if (match) {
- const major = match[1] || 0;
- const minor = match[2] || 0;
- const patch = match[3] || 0;
- return { browser: key, version: `${major}.${minor}.${patch}` };
- }
- }
- return null;
-}
-var isRunningInBrowser3 = () => {
- return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined";
-}, getPlatformProperties3 = () => {
- const detectedPlatform = getDetectedPlatform2();
- if (detectedPlatform === "deno") {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION5,
- "X-Stainless-OS": normalizePlatform3(Deno.build.os),
- "X-Stainless-Arch": normalizeArch3(Deno.build.arch),
- "X-Stainless-Runtime": "deno",
- "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
- };
- }
- if (typeof EdgeRuntime !== "undefined") {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION5,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": `other:${EdgeRuntime}`,
- "X-Stainless-Runtime": "edge",
- "X-Stainless-Runtime-Version": globalThis.process.version
- };
- }
- if (detectedPlatform === "node") {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION5,
- "X-Stainless-OS": normalizePlatform3(globalThis.process.platform ?? "unknown"),
- "X-Stainless-Arch": normalizeArch3(globalThis.process.arch ?? "unknown"),
- "X-Stainless-Runtime": "node",
- "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
- };
- }
- const browserInfo = getBrowserInfo3();
- if (browserInfo) {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION5,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": "unknown",
- "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
- "X-Stainless-Runtime-Version": browserInfo.version
- };
- }
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION5,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": "unknown",
- "X-Stainless-Runtime": "unknown",
- "X-Stainless-Runtime-Version": "unknown"
- };
-}, normalizeArch3 = (arch) => {
- if (arch === "x32")
- return "x32";
- if (arch === "x86_64" || arch === "x64")
- return "x64";
- if (arch === "arm")
- return "arm";
- if (arch === "aarch64" || arch === "arm64")
- return "arm64";
- if (arch)
- return `other:${arch}`;
- return "unknown";
-}, normalizePlatform3 = (platform2) => {
- platform2 = platform2.toLowerCase();
- if (platform2.includes("ios"))
- return "iOS";
- if (platform2 === "android")
- return "Android";
- if (platform2 === "darwin")
- return "MacOS";
- if (platform2 === "win32")
- return "Windows";
- if (platform2 === "freebsd")
- return "FreeBSD";
- if (platform2 === "openbsd")
- return "OpenBSD";
- if (platform2 === "linux")
- return "Linux";
- if (platform2)
- return `Other:${platform2}`;
- return "Unknown";
-}, _platformHeaders3, getPlatformHeaders3 = () => {
- return _platformHeaders3 ?? (_platformHeaders3 = getPlatformProperties3());
-};
-var init_detect_platform2 = () => {};
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/shims.mjs
-function getDefaultFetch2() {
- if (typeof fetch !== "undefined") {
- return fetch;
- }
- throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
-}
-function makeReadableStream2(...args) {
- const ReadableStream4 = globalThis.ReadableStream;
- if (typeof ReadableStream4 === "undefined") {
- throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
- }
- return new ReadableStream4(...args);
-}
-function ReadableStreamFrom2(iterable) {
- let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
- return makeReadableStream2({
- start() {},
- async pull(controller) {
- const { done, value } = await iter.next();
- if (done) {
- controller.close();
- } else {
- controller.enqueue(value);
- }
- },
- async cancel() {
- await iter.return?.();
- }
- });
-}
-function ReadableStreamToAsyncIterable4(stream10) {
- if (stream10[Symbol.asyncIterator])
- return stream10;
- const reader = stream10.getReader();
- return {
- async next() {
- try {
- const result = await reader.read();
- if (result?.done)
- reader.releaseLock();
- return result;
- } catch (e4) {
- reader.releaseLock();
- throw e4;
- }
- },
- async return() {
- const cancelPromise = reader.cancel();
- reader.releaseLock();
- await cancelPromise;
- return { done: true, value: undefined };
- },
- [Symbol.asyncIterator]() {
- return this;
- }
- };
-}
-async function CancelReadableStream2(stream10) {
- if (stream10 === null || typeof stream10 !== "object")
- return;
- if (stream10[Symbol.asyncIterator]) {
- await stream10[Symbol.asyncIterator]().return?.();
- return;
- }
- const reader = stream10.getReader();
- const cancelPromise = reader.cancel();
- reader.releaseLock();
- await cancelPromise;
-}
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/request-options.mjs
-var FallbackEncoder2 = ({ headers, body }) => {
- return {
- bodyHeaders: {
- "content-type": "application/json"
- },
- body: JSON.stringify(body)
- };
-};
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs
-function stringifyQuery2(query) {
- return Object.entries(query).filter(([_, value]) => typeof value !== "undefined").map(([key, value]) => {
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
- }
- if (value === null) {
- return `${encodeURIComponent(key)}=`;
- }
- throw new AnthropicError3(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
- }).join("&");
-}
-var init_query2 = __esm(() => {
- init_error6();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs
-function concatBytes2(buffers) {
- let length = 0;
- for (const buffer of buffers) {
- length += buffer.length;
- }
- const output = new Uint8Array(length);
- let index2 = 0;
- for (const buffer of buffers) {
- output.set(buffer, index2);
- index2 += buffer.length;
- }
- return output;
-}
-function encodeUTF83(str) {
- let encoder;
- return (encodeUTF8_2 ?? (encoder = new globalThis.TextEncoder, encodeUTF8_2 = encoder.encode.bind(encoder)))(str);
-}
-function decodeUTF82(bytes) {
- let decoder;
- return (decodeUTF8_2 ?? (decoder = new globalThis.TextDecoder, decodeUTF8_2 = decoder.decode.bind(decoder)))(bytes);
-}
-var encodeUTF8_2, decodeUTF8_2;
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs
-class LineDecoder3 {
- constructor() {
- _LineDecoder_buffer2.set(this, undefined);
- _LineDecoder_carriageReturnIndex3.set(this, undefined);
- __classPrivateFieldSet7(this, _LineDecoder_buffer2, new Uint8Array, "f");
- __classPrivateFieldSet7(this, _LineDecoder_carriageReturnIndex3, null, "f");
- }
- decode(chunk) {
- if (chunk == null) {
- return [];
- }
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF83(chunk) : chunk;
- __classPrivateFieldSet7(this, _LineDecoder_buffer2, concatBytes2([__classPrivateFieldGet7(this, _LineDecoder_buffer2, "f"), binaryChunk]), "f");
- const lines = [];
- let patternIndex;
- while ((patternIndex = findNewlineIndex3(__classPrivateFieldGet7(this, _LineDecoder_buffer2, "f"), __classPrivateFieldGet7(this, _LineDecoder_carriageReturnIndex3, "f"))) != null) {
- if (patternIndex.carriage && __classPrivateFieldGet7(this, _LineDecoder_carriageReturnIndex3, "f") == null) {
- __classPrivateFieldSet7(this, _LineDecoder_carriageReturnIndex3, patternIndex.index, "f");
- continue;
- }
- if (__classPrivateFieldGet7(this, _LineDecoder_carriageReturnIndex3, "f") != null && (patternIndex.index !== __classPrivateFieldGet7(this, _LineDecoder_carriageReturnIndex3, "f") + 1 || patternIndex.carriage)) {
- lines.push(decodeUTF82(__classPrivateFieldGet7(this, _LineDecoder_buffer2, "f").subarray(0, __classPrivateFieldGet7(this, _LineDecoder_carriageReturnIndex3, "f") - 1)));
- __classPrivateFieldSet7(this, _LineDecoder_buffer2, __classPrivateFieldGet7(this, _LineDecoder_buffer2, "f").subarray(__classPrivateFieldGet7(this, _LineDecoder_carriageReturnIndex3, "f")), "f");
- __classPrivateFieldSet7(this, _LineDecoder_carriageReturnIndex3, null, "f");
- continue;
- }
- const endIndex = __classPrivateFieldGet7(this, _LineDecoder_carriageReturnIndex3, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
- const line = decodeUTF82(__classPrivateFieldGet7(this, _LineDecoder_buffer2, "f").subarray(0, endIndex));
- lines.push(line);
- __classPrivateFieldSet7(this, _LineDecoder_buffer2, __classPrivateFieldGet7(this, _LineDecoder_buffer2, "f").subarray(patternIndex.index), "f");
- __classPrivateFieldSet7(this, _LineDecoder_carriageReturnIndex3, null, "f");
- }
- return lines;
- }
- flush() {
- if (!__classPrivateFieldGet7(this, _LineDecoder_buffer2, "f").length) {
- return [];
- }
- return this.decode(`
-`);
- }
-}
-function findNewlineIndex3(buffer, startIndex) {
- const newline2 = 10;
- const carriage = 13;
- for (let i5 = startIndex ?? 0;i5 < buffer.length; i5++) {
- if (buffer[i5] === newline2) {
- return { preceding: i5, index: i5 + 1, carriage: false };
- }
- if (buffer[i5] === carriage) {
- return { preceding: i5, index: i5 + 1, carriage: true };
- }
- }
- return null;
-}
-function findDoubleNewlineIndex3(buffer) {
- const newline2 = 10;
- const carriage = 13;
- for (let i5 = 0;i5 < buffer.length - 1; i5++) {
- if (buffer[i5] === newline2 && buffer[i5 + 1] === newline2) {
- return i5 + 2;
- }
- if (buffer[i5] === carriage && buffer[i5 + 1] === carriage) {
- return i5 + 2;
- }
- if (buffer[i5] === carriage && buffer[i5 + 1] === newline2 && i5 + 3 < buffer.length && buffer[i5 + 2] === carriage && buffer[i5 + 3] === newline2) {
- return i5 + 4;
- }
- }
- return -1;
-}
-var _LineDecoder_buffer2, _LineDecoder_carriageReturnIndex3;
-var init_line3 = __esm(() => {
- init_tslib2();
- _LineDecoder_buffer2 = new WeakMap, _LineDecoder_carriageReturnIndex3 = new WeakMap;
- LineDecoder3.NEWLINE_CHARS = new Set([`
-`, "\r"]);
- LineDecoder3.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs
-function noop8() {}
-function makeLogFn3(fnLevel, logger8, logLevel) {
- if (!logger8 || levelNumbers3[fnLevel] > levelNumbers3[logLevel]) {
- return noop8;
- } else {
- return logger8[fnLevel].bind(logger8);
- }
-}
-function loggerFor3(client13) {
- const logger8 = client13.logger;
- const logLevel = client13.logLevel ?? "off";
- if (!logger8) {
- return noopLogger3;
- }
- const cachedLogger = cachedLoggers3.get(logger8);
- if (cachedLogger && cachedLogger[0] === logLevel) {
- return cachedLogger[1];
- }
- const levelLogger = {
- error: makeLogFn3("error", logger8, logLevel),
- warn: makeLogFn3("warn", logger8, logLevel),
- info: makeLogFn3("info", logger8, logLevel),
- debug: makeLogFn3("debug", logger8, logLevel)
- };
- cachedLoggers3.set(logger8, [logLevel, levelLogger]);
- return levelLogger;
-}
-var levelNumbers3, parseLogLevel2 = (maybeLevel, sourceName, client13) => {
- if (!maybeLevel) {
- return;
- }
- if (hasOwn5(levelNumbers3, maybeLevel)) {
- return maybeLevel;
- }
- loggerFor3(client13).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers3))}`);
- return;
-}, noopLogger3, cachedLoggers3, formatRequestDetails2 = (details) => {
- if (details.options) {
- details.options = { ...details.options };
- delete details.options["headers"];
- }
- if (details.headers) {
- details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
- name,
- name.toLowerCase() === "x-api-key" || name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value
- ]));
- }
- if ("retryOfRequestLogID" in details) {
- if (details.retryOfRequestLogID) {
- details.retryOf = details.retryOfRequestLogID;
- }
- delete details.retryOfRequestLogID;
- }
- return details;
-};
-var init_log6 = __esm(() => {
- init_values5();
- levelNumbers3 = {
- off: 0,
- error: 200,
- warn: 300,
- info: 400,
- debug: 500
- };
- noopLogger3 = {
- error: noop8,
- warn: noop8,
- info: noop8,
- debug: noop8
- };
- cachedLoggers3 = /* @__PURE__ */ new WeakMap;
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/core/streaming.mjs
-async function* _iterSSEMessages3(response7, controller) {
- if (!response7.body) {
- controller.abort();
- if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
- throw new AnthropicError3(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
- }
- throw new AnthropicError3(`Attempted to iterate over a response with no body`);
- }
- const sseDecoder = new SSEDecoder3;
- const lineDecoder = new LineDecoder3;
- const iter = ReadableStreamToAsyncIterable4(response7.body);
- for await (const sseChunk of iterSSEChunks3(iter)) {
- for (const line of lineDecoder.decode(sseChunk)) {
- const sse = sseDecoder.decode(line);
- if (sse)
- yield sse;
- }
- }
- for (const line of lineDecoder.flush()) {
- const sse = sseDecoder.decode(line);
- if (sse)
- yield sse;
- }
-}
-async function* iterSSEChunks3(iterator2) {
- let data = new Uint8Array;
- for await (const chunk of iterator2) {
- if (chunk == null) {
- continue;
- }
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF83(chunk) : chunk;
- let newData = new Uint8Array(data.length + binaryChunk.length);
- newData.set(data);
- newData.set(binaryChunk, data.length);
- data = newData;
- let patternIndex;
- while ((patternIndex = findDoubleNewlineIndex3(data)) !== -1) {
- yield data.slice(0, patternIndex);
- data = data.slice(patternIndex);
- }
- }
- if (data.length > 0) {
- yield data;
- }
-}
-
-class SSEDecoder3 {
- constructor() {
- this.event = null;
- this.data = [];
- this.chunks = [];
- }
- decode(line) {
- if (line.endsWith("\r")) {
- line = line.substring(0, line.length - 1);
- }
- if (!line) {
- if (!this.event && !this.data.length)
- return null;
- const sse = {
- event: this.event,
- data: this.data.join(`
-`),
- raw: this.chunks
- };
- this.event = null;
- this.data = [];
- this.chunks = [];
- return sse;
- }
- this.chunks.push(line);
- if (line.startsWith(":")) {
- return null;
- }
- let [fieldname, _, value] = partition3(line, ":");
- if (value.startsWith(" ")) {
- value = value.substring(1);
- }
- if (fieldname === "event") {
- this.event = value;
- } else if (fieldname === "data") {
- this.data.push(value);
- }
- return null;
- }
-}
-function partition3(str, delimiter) {
- const index2 = str.indexOf(delimiter);
- if (index2 !== -1) {
- return [str.substring(0, index2), delimiter, str.substring(index2 + delimiter.length)];
- }
- return [str, "", ""];
-}
-var _Stream_client2, Stream4;
-var init_streaming6 = __esm(() => {
- init_tslib2();
- init_error6();
- init_line3();
- init_values5();
- init_log6();
- init_error6();
- Stream4 = class Stream4 {
- constructor(iterator2, controller, client13) {
- this.iterator = iterator2;
- _Stream_client2.set(this, undefined);
- this.controller = controller;
- __classPrivateFieldSet7(this, _Stream_client2, client13, "f");
- }
- static fromSSEResponse(response7, controller, client13) {
- let consumed = false;
- const logger8 = client13 ? loggerFor3(client13) : console;
- async function* iterator2() {
- if (consumed) {
- throw new AnthropicError3("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
- }
- consumed = true;
- let done = false;
- try {
- for await (const sse of _iterSSEMessages3(response7, controller)) {
- if (sse.event === "completion") {
- try {
- yield JSON.parse(sse.data);
- } catch (e4) {
- logger8.error(`Could not parse message into JSON:`, sse.data);
- logger8.error(`From chunk:`, sse.raw);
- throw e4;
- }
- }
- if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
- try {
- yield JSON.parse(sse.data);
- } catch (e4) {
- logger8.error(`Could not parse message into JSON:`, sse.data);
- logger8.error(`From chunk:`, sse.raw);
- throw e4;
- }
- }
- if (sse.event === "ping") {
- continue;
- }
- if (sse.event === "error") {
- throw new APIError3(undefined, safeJSON4(sse.data) ?? sse.data, undefined, response7.headers);
- }
- }
- done = true;
- } catch (e4) {
- if (isAbortError5(e4))
- return;
- throw e4;
- } finally {
- if (!done)
- controller.abort();
- }
- }
- return new Stream4(iterator2, controller, client13);
- }
- static fromReadableStream(readableStream, controller, client13) {
- let consumed = false;
- async function* iterLines() {
- const lineDecoder = new LineDecoder3;
- const iter = ReadableStreamToAsyncIterable4(readableStream);
- for await (const chunk of iter) {
- for (const line of lineDecoder.decode(chunk)) {
- yield line;
- }
- }
- for (const line of lineDecoder.flush()) {
- yield line;
- }
- }
- async function* iterator2() {
- if (consumed) {
- throw new AnthropicError3("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
- }
- consumed = true;
- let done = false;
- try {
- for await (const line of iterLines()) {
- if (done)
- continue;
- if (line)
- yield JSON.parse(line);
- }
- done = true;
- } catch (e4) {
- if (isAbortError5(e4))
- return;
- throw e4;
- } finally {
- if (!done)
- controller.abort();
- }
- }
- return new Stream4(iterator2, controller, client13);
- }
- [(_Stream_client2 = new WeakMap, Symbol.asyncIterator)]() {
- return this.iterator();
- }
- tee() {
- const left = [];
- const right = [];
- const iterator2 = this.iterator();
- const teeIterator = (queue) => {
- return {
- next: () => {
- if (queue.length === 0) {
- const result = iterator2.next();
- left.push(result);
- right.push(result);
- }
- return queue.shift();
- }
- };
- };
- return [
- new Stream4(() => teeIterator(left), this.controller, __classPrivateFieldGet7(this, _Stream_client2, "f")),
- new Stream4(() => teeIterator(right), this.controller, __classPrivateFieldGet7(this, _Stream_client2, "f"))
- ];
- }
- toReadableStream() {
- const self2 = this;
- let iter;
- return makeReadableStream2({
- async start() {
- iter = self2[Symbol.asyncIterator]();
- },
- async pull(ctrl) {
- try {
- const { value, done } = await iter.next();
- if (done)
- return ctrl.close();
- const bytes = encodeUTF83(JSON.stringify(value) + `
-`);
- ctrl.enqueue(bytes);
- } catch (err) {
- ctrl.error(err);
- }
- },
- async cancel() {
- await iter.return?.();
- }
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/parse.mjs
-async function defaultParseResponse3(client13, props) {
- const { response: response7, requestLogID, retryOfRequestLogID, startTime } = props;
- const body = await (async () => {
- if (props.options.stream) {
- loggerFor3(client13).debug("response", response7.status, response7.url, response7.headers, response7.body);
- if (props.options.__streamClass) {
- return props.options.__streamClass.fromSSEResponse(response7, props.controller);
- }
- return Stream4.fromSSEResponse(response7, props.controller);
- }
- if (response7.status === 204) {
- return null;
- }
- if (props.options.__binaryResponse) {
- return response7;
- }
- const contentType = response7.headers.get("content-type");
- const mediaType = contentType?.split(";")[0]?.trim();
- const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
- if (isJSON) {
- const contentLength = response7.headers.get("content-length");
- if (contentLength === "0") {
- return;
- }
- const json2 = await response7.json();
- return addRequestID2(json2, response7);
- }
- const text = await response7.text();
- return text;
- })();
- loggerFor3(client13).debug(`[${requestLogID}] response parsed`, formatRequestDetails2({
- retryOfRequestLogID,
- url: response7.url,
- status: response7.status,
- body,
- durationMs: Date.now() - startTime
- }));
- return body;
-}
-function addRequestID2(value, response7) {
- if (!value || typeof value !== "object" || Array.isArray(value)) {
- return value;
- }
- return Object.defineProperty(value, "_request_id", {
- value: response7.headers.get("request-id"),
- enumerable: false
- });
-}
-var init_parse4 = __esm(() => {
- init_streaming6();
- init_log6();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/core/api-promise.mjs
-var _APIPromise_client2, APIPromise3;
-var init_api_promise2 = __esm(() => {
- init_tslib2();
- init_parse4();
- APIPromise3 = class APIPromise3 extends Promise {
- constructor(client13, responsePromise, parseResponse = defaultParseResponse3) {
- super((resolve9) => {
- resolve9(null);
- });
- this.responsePromise = responsePromise;
- this.parseResponse = parseResponse;
- _APIPromise_client2.set(this, undefined);
- __classPrivateFieldSet7(this, _APIPromise_client2, client13, "f");
- }
- _thenUnwrap(transform2) {
- return new APIPromise3(__classPrivateFieldGet7(this, _APIPromise_client2, "f"), this.responsePromise, async (client13, props) => addRequestID2(transform2(await this.parseResponse(client13, props), props), props.response));
- }
- asResponse() {
- return this.responsePromise.then((p4) => p4.response);
- }
- async withResponse() {
- const [data, response7] = await Promise.all([this.parse(), this.asResponse()]);
- return { data, response: response7, request_id: response7.headers.get("request-id") };
- }
- parse() {
- if (!this.parsedPromise) {
- this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet7(this, _APIPromise_client2, "f"), data));
- }
- return this.parsedPromise;
- }
- then(onfulfilled, onrejected) {
- return this.parse().then(onfulfilled, onrejected);
- }
- catch(onrejected) {
- return this.parse().catch(onrejected);
- }
- finally(onfinally) {
- return this.parse().finally(onfinally);
- }
- };
- _APIPromise_client2 = new WeakMap;
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/core/pagination.mjs
-var _AbstractPage_client3, AbstractPage3, PagePromise3, Page3, PageCursor2;
-var init_pagination11 = __esm(() => {
- init_tslib2();
- init_error6();
- init_parse4();
- init_api_promise2();
- init_values5();
- AbstractPage3 = class AbstractPage3 {
- constructor(client13, response7, body, options2) {
- _AbstractPage_client3.set(this, undefined);
- __classPrivateFieldSet7(this, _AbstractPage_client3, client13, "f");
- this.options = options2;
- this.response = response7;
- this.body = body;
- }
- hasNextPage() {
- const items = this.getPaginatedItems();
- if (!items.length)
- return false;
- return this.nextPageRequestOptions() != null;
- }
- async getNextPage() {
- const nextOptions = this.nextPageRequestOptions();
- if (!nextOptions) {
- throw new AnthropicError3("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
- }
- return await __classPrivateFieldGet7(this, _AbstractPage_client3, "f").requestAPIList(this.constructor, nextOptions);
- }
- async* iterPages() {
- let page = this;
- yield page;
- while (page.hasNextPage()) {
- page = await page.getNextPage();
- yield page;
- }
- }
- async* [(_AbstractPage_client3 = new WeakMap, Symbol.asyncIterator)]() {
- for await (const page of this.iterPages()) {
- for (const item of page.getPaginatedItems()) {
- yield item;
- }
- }
- }
- };
- PagePromise3 = class PagePromise3 extends APIPromise3 {
- constructor(client13, request2, Page3) {
- super(client13, request2, async (client14, props) => new Page3(client14, props.response, await defaultParseResponse3(client14, props), props.options));
- }
- async* [Symbol.asyncIterator]() {
- const page = await this;
- for await (const item of page) {
- yield item;
- }
- }
- };
- Page3 = class Page3 extends AbstractPage3 {
- constructor(client13, response7, body, options2) {
- super(client13, response7, body, options2);
- this.data = body.data || [];
- this.has_more = body.has_more || false;
- this.first_id = body.first_id || null;
- this.last_id = body.last_id || null;
- }
- getPaginatedItems() {
- return this.data ?? [];
- }
- hasNextPage() {
- if (this.has_more === false) {
- return false;
- }
- return super.hasNextPage();
- }
- nextPageRequestOptions() {
- if (this.options.query?.["before_id"]) {
- const first_id = this.first_id;
- if (!first_id) {
- return null;
- }
- return {
- ...this.options,
- query: {
- ...maybeObj2(this.options.query),
- before_id: first_id
- }
- };
- }
- const cursor = this.last_id;
- if (!cursor) {
- return null;
- }
- return {
- ...this.options,
- query: {
- ...maybeObj2(this.options.query),
- after_id: cursor
- }
- };
- }
- };
- PageCursor2 = class PageCursor2 extends AbstractPage3 {
- constructor(client13, response7, body, options2) {
- super(client13, response7, body, options2);
- this.data = body.data || [];
- this.has_more = body.has_more || false;
- this.next_page = body.next_page || null;
- }
- getPaginatedItems() {
- return this.data ?? [];
- }
- hasNextPage() {
- if (this.has_more === false) {
- return false;
- }
- return super.hasNextPage();
- }
- nextPageRequestOptions() {
- const cursor = this.next_page;
- if (!cursor) {
- return null;
- }
- return {
- ...this.options,
- query: {
- ...maybeObj2(this.options.query),
- page: cursor
- }
- };
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/uploads.mjs
-function makeFile2(fileBits, fileName, options2) {
- checkFileSupport2();
- return new File(fileBits, fileName ?? "unknown_file", options2);
-}
-function getName3(value, stripPath) {
- const val = typeof value === "object" && value !== null && (("name" in value) && value.name && String(value.name) || ("url" in value) && value.url && String(value.url) || ("filename" in value) && value.filename && String(value.filename) || ("path" in value) && value.path && String(value.path)) || "";
- return stripPath ? val.split(/[\\/]/).pop() || undefined : val;
-}
-function supportsFormData2(fetchObject) {
- const fetch3 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
- const cached2 = supportsFormDataMap2.get(fetch3);
- if (cached2)
- return cached2;
- const promise2 = (async () => {
- try {
- const FetchResponse = "Response" in fetch3 ? fetch3.Response : (await fetch3("data:,")).constructor;
- const data = new FormData;
- if (data.toString() === await new FetchResponse(data).text()) {
- return false;
- }
- return true;
- } catch {
- return true;
- }
- })();
- supportsFormDataMap2.set(fetch3, promise2);
- return promise2;
-}
-var checkFileSupport2 = () => {
- if (typeof File === "undefined") {
- const { process: process12 } = globalThis;
- const isOldNode = typeof process12?.versions?.node === "string" && parseInt(process12.versions.node.split(".")) < 20;
- throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
- }
-}, isAsyncIterable2 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", multipartFormRequestOptions2 = async (opts, fetch3, stripFilenames = true) => {
- return { ...opts, body: await createForm2(opts.body, fetch3, stripFilenames) };
-}, supportsFormDataMap2, createForm2 = async (body, fetch3, stripFilenames = true) => {
- if (!await supportsFormData2(fetch3)) {
- throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
- }
- const form = new FormData;
- await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue2(form, key, value, stripFilenames)));
- return form;
-}, isNamedBlob2 = (value) => value instanceof Blob && ("name" in value), addFormValue2 = async (form, key, value, stripFilenames) => {
- if (value === undefined)
- return;
- if (value == null) {
- throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
- }
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
- form.append(key, String(value));
- } else if (value instanceof Response) {
- let options2 = {};
- const contentType = value.headers.get("Content-Type");
- if (contentType) {
- options2 = { type: contentType };
- }
- form.append(key, makeFile2([await value.blob()], getName3(value, stripFilenames), options2));
- } else if (isAsyncIterable2(value)) {
- form.append(key, makeFile2([await new Response(ReadableStreamFrom2(value)).blob()], getName3(value, stripFilenames)));
- } else if (isNamedBlob2(value)) {
- form.append(key, makeFile2([value], getName3(value, stripFilenames), { type: value.type }));
- } else if (Array.isArray(value)) {
- await Promise.all(value.map((entry) => addFormValue2(form, key + "[]", entry, stripFilenames)));
- } else if (typeof value === "object") {
- await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue2(form, `${key}[${name}]`, prop, stripFilenames)));
- } else {
- throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
- }
-};
-var init_uploads4 = __esm(() => {
- supportsFormDataMap2 = /* @__PURE__ */ new WeakMap;
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/to-file.mjs
-async function toFile3(value, name, options2) {
- checkFileSupport2();
- value = await value;
- name || (name = getName3(value, true));
- if (isFileLike3(value)) {
- if (value instanceof File && name == null && options2 == null) {
- return value;
- }
- return makeFile2([await value.arrayBuffer()], name ?? value.name, {
- type: value.type,
- lastModified: value.lastModified,
- ...options2
- });
- }
- if (isResponseLike3(value)) {
- const blob = await value.blob();
- name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
- return makeFile2(await getBytes3(blob), name, options2);
- }
- const parts = await getBytes3(value);
- if (!options2?.type) {
- const type = parts.find((part) => typeof part === "object" && ("type" in part) && part.type);
- if (typeof type === "string") {
- options2 = { ...options2, type };
- }
- }
- return makeFile2(parts, name, options2);
-}
-async function getBytes3(value) {
- let parts = [];
- if (typeof value === "string" || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
- parts.push(value);
- } else if (isBlobLike3(value)) {
- parts.push(value instanceof Blob ? value : await value.arrayBuffer());
- } else if (isAsyncIterable2(value)) {
- for await (const chunk of value) {
- parts.push(...await getBytes3(chunk));
- }
- } else {
- const constructor = value?.constructor?.name;
- throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError3(value)}`);
- }
- return parts;
-}
-function propsForError3(value) {
- if (typeof value !== "object" || value === null)
- return "";
- const props = Object.getOwnPropertyNames(value);
- return `; props: [${props.map((p4) => `"${p4}"`).join(", ")}]`;
-}
-var isBlobLike3 = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", isFileLike3 = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike3(value), isResponseLike3 = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
-var init_to_file2 = __esm(() => {
- init_uploads4();
- init_uploads4();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/core/uploads.mjs
-var init_uploads5 = __esm(() => {
- init_to_file2();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/shared.mjs
-var init_shared10 = () => {};
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/core/resource.mjs
-class APIResource3 {
- constructor(client13) {
- this._client = client13;
- }
-}
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/headers.mjs
-function* iterateHeaders4(headers) {
- if (!headers)
- return;
- if (brand_privateNullableHeaders4 in headers) {
- const { values: values2, nulls } = headers;
- yield* values2.entries();
- for (const name of nulls) {
- yield [name, null];
- }
- return;
- }
- let shouldClear = false;
- let iter;
- if (headers instanceof Headers) {
- iter = headers.entries();
- } else if (isReadonlyArray4(headers)) {
- iter = headers;
- } else {
- shouldClear = true;
- iter = Object.entries(headers ?? {});
- }
- for (let row of iter) {
- const name = row[0];
- if (typeof name !== "string")
- throw new TypeError("expected header name to be a string");
- const values2 = isReadonlyArray4(row[1]) ? row[1] : [row[1]];
- let didClear = false;
- for (const value of values2) {
- if (value === undefined)
- continue;
- if (shouldClear && !didClear) {
- didClear = true;
- yield [name, null];
- }
- yield [name, value];
- }
- }
-}
-var brand_privateNullableHeaders4, buildHeaders4 = (newHeaders) => {
- const targetHeaders = new Headers;
- const nullHeaders = new Set;
- for (const headers of newHeaders) {
- const seenHeaders = new Set;
- for (const [name, value] of iterateHeaders4(headers)) {
- const lowerName = name.toLowerCase();
- if (!seenHeaders.has(lowerName)) {
- targetHeaders.delete(name);
- seenHeaders.add(lowerName);
- }
- if (value === null) {
- targetHeaders.delete(name);
- nullHeaders.add(lowerName);
- } else {
- targetHeaders.append(name, value);
- nullHeaders.delete(lowerName);
- }
- }
- }
- return { [brand_privateNullableHeaders4]: true, values: targetHeaders, nulls: nullHeaders };
-};
-var init_headers4 = __esm(() => {
- init_values5();
- brand_privateNullableHeaders4 = Symbol.for("brand.privateNullableHeaders");
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs
-function wasCreatedByStainlessHelper2(value) {
- return typeof value === "object" && value !== null && SDK_HELPER_SYMBOL2 in value;
-}
-function collectStainlessHelpers2(tools, messages) {
- const helpers3 = new Set;
- if (tools) {
- for (const tool of tools) {
- if (wasCreatedByStainlessHelper2(tool)) {
- helpers3.add(tool[SDK_HELPER_SYMBOL2]);
- }
- }
- }
- if (messages) {
- for (const message of messages) {
- if (wasCreatedByStainlessHelper2(message)) {
- helpers3.add(message[SDK_HELPER_SYMBOL2]);
- }
- if (Array.isArray(message.content)) {
- for (const block2 of message.content) {
- if (wasCreatedByStainlessHelper2(block2)) {
- helpers3.add(block2[SDK_HELPER_SYMBOL2]);
- }
- }
- }
- }
- }
- return Array.from(helpers3);
-}
-function stainlessHelperHeader2(tools, messages) {
- const helpers3 = collectStainlessHelpers2(tools, messages);
- if (helpers3.length === 0)
- return {};
- return { "x-stainless-helper": helpers3.join(", ") };
-}
-function stainlessHelperHeaderFromFile2(file2) {
- if (wasCreatedByStainlessHelper2(file2)) {
- return { "x-stainless-helper": file2[SDK_HELPER_SYMBOL2] };
- }
- return {};
-}
-var SDK_HELPER_SYMBOL2;
-var init_stainless_helper_header2 = __esm(() => {
- SDK_HELPER_SYMBOL2 = Symbol("anthropic.sdk.stainlessHelper");
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs
-function encodeURIPath3(str) {
- return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
-}
-var EMPTY3, createPathTagFunction3 = (pathEncoder = encodeURIPath3) => function path10(statics, ...params) {
- if (statics.length === 1)
- return statics[0];
- let postPath = false;
- const invalidSegments = [];
- const path11 = statics.reduce((previousValue, currentValue, index2) => {
- if (/[?#]/.test(currentValue)) {
- postPath = true;
- }
- const value = params[index2];
- let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
- if (index2 !== params.length && (value == null || typeof value === "object" && value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY3) ?? EMPTY3)?.toString)) {
- encoded = value + "";
- invalidSegments.push({
- start: previousValue.length + currentValue.length,
- length: encoded.length,
- error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
- });
- }
- return previousValue + currentValue + (index2 === params.length ? "" : encoded);
- }, "");
- const pathOnly = path11.split(/[?#]/, 1)[0];
- const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
- let match;
- while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
- invalidSegments.push({
- start: match.index,
- length: match[0].length,
- error: `Value "${match[0]}" can't be safely passed as a path parameter`
- });
- }
- invalidSegments.sort((a5, b4) => a5.start - b4.start);
- if (invalidSegments.length > 0) {
- let lastEnd = 0;
- const underline2 = invalidSegments.reduce((acc, segment) => {
- const spaces = " ".repeat(segment.start - lastEnd);
- const arrows = "^".repeat(segment.length);
- lastEnd = segment.start + segment.length;
- return acc + spaces + arrows;
- }, "");
- throw new AnthropicError3(`Path parameters result in path with invalid segments:
-${invalidSegments.map((e4) => e4.error).join(`
-`)}
-${path11}
-${underline2}`);
- }
- return path11;
-}, path10;
-var init_path4 = __esm(() => {
- init_error6();
- EMPTY3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
- path10 = /* @__PURE__ */ createPathTagFunction3(encodeURIPath3);
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs
-var Files2;
-var init_files3 = __esm(() => {
- init_pagination11();
- init_headers4();
- init_stainless_helper_header2();
- init_uploads4();
- init_path4();
- Files2 = class Files2 extends APIResource3 {
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/files", Page3, {
- query,
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- options2?.headers
- ])
- });
- }
- delete(fileID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.delete(path10`/v1/files/${fileID}`, {
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- options2?.headers
- ])
- });
- }
- download(fileID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path10`/v1/files/${fileID}/content`, {
- ...options2,
- headers: buildHeaders4([
- {
- "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString(),
- Accept: "application/binary"
- },
- options2?.headers
- ]),
- __binaryResponse: true
- });
- }
- retrieveMetadata(fileID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path10`/v1/files/${fileID}`, {
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- options2?.headers
- ])
- });
- }
- upload(params, options2) {
- const { betas, ...body } = params;
- return this._client.post("/v1/files", multipartFormRequestOptions2({
- body,
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- stainlessHelperHeaderFromFile2(body.file),
- options2?.headers
- ])
- }, this._client));
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs
-var Models5;
-var init_models5 = __esm(() => {
- init_pagination11();
- init_headers4();
- init_path4();
- Models5 = class Models5 extends APIResource3 {
- retrieve(modelID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path10`/v1/models/${modelID}?beta=true`, {
- ...options2,
- headers: buildHeaders4([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/models?beta=true", Page3, {
- query,
- ...options2,
- headers: buildHeaders4([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/error.mjs
-var init_error8 = __esm(() => {
- init_error6();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/constants.mjs
-var MODEL_NONSTREAMING_TOKENS2;
-var init_constants8 = __esm(() => {
- MODEL_NONSTREAMING_TOKENS2 = {
- "claude-opus-4-20250514": 8192,
- "claude-opus-4-0": 8192,
- "claude-4-opus-20250514": 8192,
- "anthropic.claude-opus-4-20250514-v1:0": 8192,
- "claude-opus-4@20250514": 8192,
- "claude-opus-4-1-20250805": 8192,
- "anthropic.claude-opus-4-1-20250805-v1:0": 8192,
- "claude-opus-4-1@20250805": 8192
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs
-function getOutputFormat3(params) {
- return params?.output_format ?? params?.output_config?.format;
-}
-function maybeParseBetaMessage2(message, params, opts) {
- const outputFormat = getOutputFormat3(params);
- if (!params || !("parse" in (outputFormat ?? {}))) {
- return {
- ...message,
- content: message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: null,
- enumerable: false
- });
- return Object.defineProperty(parsedBlock, "parsed", {
- get() {
- opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");
- return null;
- },
- enumerable: false
- });
- }
- return block2;
- }),
- parsed_output: null
- };
- }
- return parseBetaMessage2(message, params, opts);
-}
-function parseBetaMessage2(message, params, opts) {
- let firstParsedOutput = null;
- const content = message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedOutput = parseBetaOutputFormat2(params, block2.text);
- if (firstParsedOutput === null) {
- firstParsedOutput = parsedOutput;
- }
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: parsedOutput,
- enumerable: false
- });
- return Object.defineProperty(parsedBlock, "parsed", {
- get() {
- opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");
- return parsedOutput;
- },
- enumerable: false
- });
- }
- return block2;
- });
- return {
- ...message,
- content,
- parsed_output: firstParsedOutput
- };
-}
-function parseBetaOutputFormat2(params, content) {
- const outputFormat = getOutputFormat3(params);
- if (outputFormat?.type !== "json_schema") {
- return null;
- }
- try {
- if ("parse" in outputFormat) {
- return outputFormat.parse(content);
- }
- return JSON.parse(content);
- } catch (error44) {
- throw new AnthropicError3(`Failed to parse structured output: ${error44}`);
- }
-}
-var init_beta_parser2 = __esm(() => {
- init_error6();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs
-var tokenize3 = (input) => {
- let current = 0;
- let tokens = [];
- while (current < input.length) {
- let char = input[current];
- if (char === "\\") {
- current++;
- continue;
- }
- if (char === "{") {
- tokens.push({
- type: "brace",
- value: "{"
- });
- current++;
- continue;
- }
- if (char === "}") {
- tokens.push({
- type: "brace",
- value: "}"
- });
- current++;
- continue;
- }
- if (char === "[") {
- tokens.push({
- type: "paren",
- value: "["
- });
- current++;
- continue;
- }
- if (char === "]") {
- tokens.push({
- type: "paren",
- value: "]"
- });
- current++;
- continue;
- }
- if (char === ":") {
- tokens.push({
- type: "separator",
- value: ":"
- });
- current++;
- continue;
- }
- if (char === ",") {
- tokens.push({
- type: "delimiter",
- value: ","
- });
- current++;
- continue;
- }
- if (char === '"') {
- let value = "";
- let danglingQuote = false;
- char = input[++current];
- while (char !== '"') {
- if (current === input.length) {
- danglingQuote = true;
- break;
- }
- if (char === "\\") {
- current++;
- if (current === input.length) {
- danglingQuote = true;
- break;
- }
- value += char + input[current];
- char = input[++current];
- } else {
- value += char;
- char = input[++current];
- }
- }
- char = input[++current];
- if (!danglingQuote) {
- tokens.push({
- type: "string",
- value
- });
- }
- continue;
- }
- let WHITESPACE = /\s/;
- if (char && WHITESPACE.test(char)) {
- current++;
- continue;
- }
- let NUMBERS = /[0-9]/;
- if (char && NUMBERS.test(char) || char === "-" || char === ".") {
- let value = "";
- if (char === "-") {
- value += char;
- char = input[++current];
- }
- while (char && NUMBERS.test(char) || char === ".") {
- value += char;
- char = input[++current];
- }
- tokens.push({
- type: "number",
- value
- });
- continue;
- }
- let LETTERS = /[a-z]/i;
- if (char && LETTERS.test(char)) {
- let value = "";
- while (char && LETTERS.test(char)) {
- if (current === input.length) {
- break;
- }
- value += char;
- char = input[++current];
- }
- if (value == "true" || value == "false" || value === "null") {
- tokens.push({
- type: "name",
- value
- });
- } else {
- current++;
- continue;
- }
- continue;
- }
- current++;
- }
- return tokens;
-}, strip3 = (tokens) => {
- if (tokens.length === 0) {
- return tokens;
- }
- let lastToken = tokens[tokens.length - 1];
- switch (lastToken.type) {
- case "separator":
- tokens = tokens.slice(0, tokens.length - 1);
- return strip3(tokens);
- break;
- case "number":
- let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
- if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip3(tokens);
- }
- case "string":
- let tokenBeforeTheLastToken = tokens[tokens.length - 2];
- if (tokenBeforeTheLastToken?.type === "delimiter") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip3(tokens);
- } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip3(tokens);
- }
- break;
- case "delimiter":
- tokens = tokens.slice(0, tokens.length - 1);
- return strip3(tokens);
- break;
- }
- return tokens;
-}, unstrip3 = (tokens) => {
- let tail = [];
- tokens.map((token) => {
- if (token.type === "brace") {
- if (token.value === "{") {
- tail.push("}");
- } else {
- tail.splice(tail.lastIndexOf("}"), 1);
- }
- }
- if (token.type === "paren") {
- if (token.value === "[") {
- tail.push("]");
- } else {
- tail.splice(tail.lastIndexOf("]"), 1);
- }
- }
- });
- if (tail.length > 0) {
- tail.reverse().map((item) => {
- if (item === "}") {
- tokens.push({
- type: "brace",
- value: "}"
- });
- } else if (item === "]") {
- tokens.push({
- type: "paren",
- value: "]"
- });
- }
- });
- }
- return tokens;
-}, generate3 = (tokens) => {
- let output = "";
- tokens.map((token) => {
- switch (token.type) {
- case "string":
- output += '"' + token.value + '"';
- break;
- default:
- output += token.value;
- break;
- }
- });
- return output;
-}, partialParse3 = (input) => JSON.parse(generate3(unstrip3(strip3(tokenize3(input)))));
-var init_parser5 = () => {};
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/streaming.mjs
-var init_streaming7 = __esm(() => {
- init_streaming6();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs
-function tracksToolInput3(content) {
- return content.type === "tool_use" || content.type === "server_tool_use" || content.type === "mcp_tool_use";
-}
-function checkNever5(x3) {}
-var _BetaMessageStream_instances3, _BetaMessageStream_currentMessageSnapshot3, _BetaMessageStream_params2, _BetaMessageStream_connectedPromise3, _BetaMessageStream_resolveConnectedPromise3, _BetaMessageStream_rejectConnectedPromise3, _BetaMessageStream_endPromise3, _BetaMessageStream_resolveEndPromise3, _BetaMessageStream_rejectEndPromise3, _BetaMessageStream_listeners3, _BetaMessageStream_ended3, _BetaMessageStream_errored3, _BetaMessageStream_aborted3, _BetaMessageStream_catchingPromiseCreated3, _BetaMessageStream_response3, _BetaMessageStream_request_id3, _BetaMessageStream_logger2, _BetaMessageStream_getFinalMessage3, _BetaMessageStream_getFinalText3, _BetaMessageStream_handleError3, _BetaMessageStream_beginRequest3, _BetaMessageStream_addStreamEvent3, _BetaMessageStream_endRequest3, _BetaMessageStream_accumulateMessage3, JSON_BUF_PROPERTY5 = "__json_buf", BetaMessageStream3;
-var init_BetaMessageStream3 = __esm(() => {
- init_tslib2();
- init_parser5();
- init_error8();
- init_streaming7();
- init_beta_parser2();
- BetaMessageStream3 = class BetaMessageStream3 {
- constructor(params, opts) {
- _BetaMessageStream_instances3.add(this);
- this.messages = [];
- this.receivedMessages = [];
- _BetaMessageStream_currentMessageSnapshot3.set(this, undefined);
- _BetaMessageStream_params2.set(this, null);
- this.controller = new AbortController;
- _BetaMessageStream_connectedPromise3.set(this, undefined);
- _BetaMessageStream_resolveConnectedPromise3.set(this, () => {});
- _BetaMessageStream_rejectConnectedPromise3.set(this, () => {});
- _BetaMessageStream_endPromise3.set(this, undefined);
- _BetaMessageStream_resolveEndPromise3.set(this, () => {});
- _BetaMessageStream_rejectEndPromise3.set(this, () => {});
- _BetaMessageStream_listeners3.set(this, {});
- _BetaMessageStream_ended3.set(this, false);
- _BetaMessageStream_errored3.set(this, false);
- _BetaMessageStream_aborted3.set(this, false);
- _BetaMessageStream_catchingPromiseCreated3.set(this, false);
- _BetaMessageStream_response3.set(this, undefined);
- _BetaMessageStream_request_id3.set(this, undefined);
- _BetaMessageStream_logger2.set(this, undefined);
- _BetaMessageStream_handleError3.set(this, (error44) => {
- __classPrivateFieldSet7(this, _BetaMessageStream_errored3, true, "f");
- if (isAbortError5(error44)) {
- error44 = new APIUserAbortError3;
- }
- if (error44 instanceof APIUserAbortError3) {
- __classPrivateFieldSet7(this, _BetaMessageStream_aborted3, true, "f");
- return this._emit("abort", error44);
- }
- if (error44 instanceof AnthropicError3) {
- return this._emit("error", error44);
- }
- if (error44 instanceof Error) {
- const anthropicError = new AnthropicError3(error44.message);
- anthropicError.cause = error44;
- return this._emit("error", anthropicError);
- }
- return this._emit("error", new AnthropicError3(String(error44)));
- });
- __classPrivateFieldSet7(this, _BetaMessageStream_connectedPromise3, new Promise((resolve9, reject) => {
- __classPrivateFieldSet7(this, _BetaMessageStream_resolveConnectedPromise3, resolve9, "f");
- __classPrivateFieldSet7(this, _BetaMessageStream_rejectConnectedPromise3, reject, "f");
- }), "f");
- __classPrivateFieldSet7(this, _BetaMessageStream_endPromise3, new Promise((resolve9, reject) => {
- __classPrivateFieldSet7(this, _BetaMessageStream_resolveEndPromise3, resolve9, "f");
- __classPrivateFieldSet7(this, _BetaMessageStream_rejectEndPromise3, reject, "f");
- }), "f");
- __classPrivateFieldGet7(this, _BetaMessageStream_connectedPromise3, "f").catch(() => {});
- __classPrivateFieldGet7(this, _BetaMessageStream_endPromise3, "f").catch(() => {});
- __classPrivateFieldSet7(this, _BetaMessageStream_params2, params, "f");
- __classPrivateFieldSet7(this, _BetaMessageStream_logger2, opts?.logger ?? console, "f");
- }
- get response() {
- return __classPrivateFieldGet7(this, _BetaMessageStream_response3, "f");
- }
- get request_id() {
- return __classPrivateFieldGet7(this, _BetaMessageStream_request_id3, "f");
- }
- async withResponse() {
- __classPrivateFieldSet7(this, _BetaMessageStream_catchingPromiseCreated3, true, "f");
- const response7 = await __classPrivateFieldGet7(this, _BetaMessageStream_connectedPromise3, "f");
- if (!response7) {
- throw new Error("Could not resolve a `Response` object");
- }
- return {
- data: this,
- response: response7,
- request_id: response7.headers.get("request-id")
- };
- }
- static fromReadableStream(stream10) {
- const runner = new BetaMessageStream3(null);
- runner._run(() => runner._fromReadableStream(stream10));
- return runner;
- }
- static createMessage(messages, params, options2, { logger: logger8 } = {}) {
- const runner = new BetaMessageStream3(params, { logger: logger8 });
- for (const message of params.messages) {
- runner._addMessageParam(message);
- }
- __classPrivateFieldSet7(runner, _BetaMessageStream_params2, { ...params, stream: true }, "f");
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options2, headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" } }));
- return runner;
- }
- _run(executor) {
- executor().then(() => {
- this._emitFinal();
- this._emit("end");
- }, __classPrivateFieldGet7(this, _BetaMessageStream_handleError3, "f"));
- }
- _addMessageParam(message) {
- this.messages.push(message);
- }
- _addMessage(message, emit = true) {
- this.receivedMessages.push(message);
- if (emit) {
- this._emit("message", message);
- }
- }
- async _createMessage(messages, params, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet7(this, _BetaMessageStream_instances3, "m", _BetaMessageStream_beginRequest3).call(this);
- const { response: response7, data: stream10 } = await messages.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal }).withResponse();
- this._connected(response7);
- for await (const event of stream10) {
- __classPrivateFieldGet7(this, _BetaMessageStream_instances3, "m", _BetaMessageStream_addStreamEvent3).call(this, event);
- }
- if (stream10.controller.signal?.aborted) {
- throw new APIUserAbortError3;
- }
- __classPrivateFieldGet7(this, _BetaMessageStream_instances3, "m", _BetaMessageStream_endRequest3).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- _connected(response7) {
- if (this.ended)
- return;
- __classPrivateFieldSet7(this, _BetaMessageStream_response3, response7, "f");
- __classPrivateFieldSet7(this, _BetaMessageStream_request_id3, response7?.headers.get("request-id"), "f");
- __classPrivateFieldGet7(this, _BetaMessageStream_resolveConnectedPromise3, "f").call(this, response7);
- this._emit("connect");
- }
- get ended() {
- return __classPrivateFieldGet7(this, _BetaMessageStream_ended3, "f");
- }
- get errored() {
- return __classPrivateFieldGet7(this, _BetaMessageStream_errored3, "f");
- }
- get aborted() {
- return __classPrivateFieldGet7(this, _BetaMessageStream_aborted3, "f");
- }
- abort() {
- this.controller.abort();
- }
- on(event, listener) {
- const listeners = __classPrivateFieldGet7(this, _BetaMessageStream_listeners3, "f")[event] || (__classPrivateFieldGet7(this, _BetaMessageStream_listeners3, "f")[event] = []);
- listeners.push({ listener });
- return this;
- }
- off(event, listener) {
- const listeners = __classPrivateFieldGet7(this, _BetaMessageStream_listeners3, "f")[event];
- if (!listeners)
- return this;
- const index2 = listeners.findIndex((l4) => l4.listener === listener);
- if (index2 >= 0)
- listeners.splice(index2, 1);
- return this;
- }
- once(event, listener) {
- const listeners = __classPrivateFieldGet7(this, _BetaMessageStream_listeners3, "f")[event] || (__classPrivateFieldGet7(this, _BetaMessageStream_listeners3, "f")[event] = []);
- listeners.push({ listener, once: true });
- return this;
- }
- emitted(event) {
- return new Promise((resolve9, reject) => {
- __classPrivateFieldSet7(this, _BetaMessageStream_catchingPromiseCreated3, true, "f");
- if (event !== "error")
- this.once("error", reject);
- this.once(event, resolve9);
- });
- }
- async done() {
- __classPrivateFieldSet7(this, _BetaMessageStream_catchingPromiseCreated3, true, "f");
- await __classPrivateFieldGet7(this, _BetaMessageStream_endPromise3, "f");
- }
- get currentMessage() {
- return __classPrivateFieldGet7(this, _BetaMessageStream_currentMessageSnapshot3, "f");
- }
- async finalMessage() {
- await this.done();
- return __classPrivateFieldGet7(this, _BetaMessageStream_instances3, "m", _BetaMessageStream_getFinalMessage3).call(this);
- }
- async finalText() {
- await this.done();
- return __classPrivateFieldGet7(this, _BetaMessageStream_instances3, "m", _BetaMessageStream_getFinalText3).call(this);
- }
- _emit(event, ...args) {
- if (__classPrivateFieldGet7(this, _BetaMessageStream_ended3, "f"))
- return;
- if (event === "end") {
- __classPrivateFieldSet7(this, _BetaMessageStream_ended3, true, "f");
- __classPrivateFieldGet7(this, _BetaMessageStream_resolveEndPromise3, "f").call(this);
- }
- const listeners = __classPrivateFieldGet7(this, _BetaMessageStream_listeners3, "f")[event];
- if (listeners) {
- __classPrivateFieldGet7(this, _BetaMessageStream_listeners3, "f")[event] = listeners.filter((l4) => !l4.once);
- listeners.forEach(({ listener }) => listener(...args));
- }
- if (event === "abort") {
- const error44 = args[0];
- if (!__classPrivateFieldGet7(this, _BetaMessageStream_catchingPromiseCreated3, "f") && !listeners?.length) {
- Promise.reject(error44);
- }
- __classPrivateFieldGet7(this, _BetaMessageStream_rejectConnectedPromise3, "f").call(this, error44);
- __classPrivateFieldGet7(this, _BetaMessageStream_rejectEndPromise3, "f").call(this, error44);
- this._emit("end");
- return;
- }
- if (event === "error") {
- const error44 = args[0];
- if (!__classPrivateFieldGet7(this, _BetaMessageStream_catchingPromiseCreated3, "f") && !listeners?.length) {
- Promise.reject(error44);
- }
- __classPrivateFieldGet7(this, _BetaMessageStream_rejectConnectedPromise3, "f").call(this, error44);
- __classPrivateFieldGet7(this, _BetaMessageStream_rejectEndPromise3, "f").call(this, error44);
- this._emit("end");
- }
- }
- _emitFinal() {
- const finalMessage = this.receivedMessages.at(-1);
- if (finalMessage) {
- this._emit("finalMessage", __classPrivateFieldGet7(this, _BetaMessageStream_instances3, "m", _BetaMessageStream_getFinalMessage3).call(this));
- }
- }
- async _fromReadableStream(readableStream, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet7(this, _BetaMessageStream_instances3, "m", _BetaMessageStream_beginRequest3).call(this);
- this._connected(null);
- const stream10 = Stream4.fromReadableStream(readableStream, this.controller);
- for await (const event of stream10) {
- __classPrivateFieldGet7(this, _BetaMessageStream_instances3, "m", _BetaMessageStream_addStreamEvent3).call(this, event);
- }
- if (stream10.controller.signal?.aborted) {
- throw new APIUserAbortError3;
- }
- __classPrivateFieldGet7(this, _BetaMessageStream_instances3, "m", _BetaMessageStream_endRequest3).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- [(_BetaMessageStream_currentMessageSnapshot3 = new WeakMap, _BetaMessageStream_params2 = new WeakMap, _BetaMessageStream_connectedPromise3 = new WeakMap, _BetaMessageStream_resolveConnectedPromise3 = new WeakMap, _BetaMessageStream_rejectConnectedPromise3 = new WeakMap, _BetaMessageStream_endPromise3 = new WeakMap, _BetaMessageStream_resolveEndPromise3 = new WeakMap, _BetaMessageStream_rejectEndPromise3 = new WeakMap, _BetaMessageStream_listeners3 = new WeakMap, _BetaMessageStream_ended3 = new WeakMap, _BetaMessageStream_errored3 = new WeakMap, _BetaMessageStream_aborted3 = new WeakMap, _BetaMessageStream_catchingPromiseCreated3 = new WeakMap, _BetaMessageStream_response3 = new WeakMap, _BetaMessageStream_request_id3 = new WeakMap, _BetaMessageStream_logger2 = new WeakMap, _BetaMessageStream_handleError3 = new WeakMap, _BetaMessageStream_instances3 = new WeakSet, _BetaMessageStream_getFinalMessage3 = function _BetaMessageStream_getFinalMessage4() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError3("stream ended without producing a Message with role=assistant");
- }
- return this.receivedMessages.at(-1);
- }, _BetaMessageStream_getFinalText3 = function _BetaMessageStream_getFinalText4() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError3("stream ended without producing a Message with role=assistant");
- }
- const textBlocks = this.receivedMessages.at(-1).content.filter((block2) => block2.type === "text").map((block2) => block2.text);
- if (textBlocks.length === 0) {
- throw new AnthropicError3("stream ended without producing a content block with type=text");
- }
- return textBlocks.join(" ");
- }, _BetaMessageStream_beginRequest3 = function _BetaMessageStream_beginRequest4() {
- if (this.ended)
- return;
- __classPrivateFieldSet7(this, _BetaMessageStream_currentMessageSnapshot3, undefined, "f");
- }, _BetaMessageStream_addStreamEvent3 = function _BetaMessageStream_addStreamEvent4(event) {
- if (this.ended)
- return;
- const messageSnapshot = __classPrivateFieldGet7(this, _BetaMessageStream_instances3, "m", _BetaMessageStream_accumulateMessage3).call(this, event);
- this._emit("streamEvent", event, messageSnapshot);
- switch (event.type) {
- case "content_block_delta": {
- const content = messageSnapshot.content.at(-1);
- switch (event.delta.type) {
- case "text_delta": {
- if (content.type === "text") {
- this._emit("text", event.delta.text, content.text || "");
- }
- break;
- }
- case "citations_delta": {
- if (content.type === "text") {
- this._emit("citation", event.delta.citation, content.citations ?? []);
- }
- break;
- }
- case "input_json_delta": {
- if (tracksToolInput3(content) && content.input) {
- this._emit("inputJson", event.delta.partial_json, content.input);
- }
- break;
- }
- case "thinking_delta": {
- if (content.type === "thinking") {
- this._emit("thinking", event.delta.thinking, content.thinking);
- }
- break;
- }
- case "signature_delta": {
- if (content.type === "thinking") {
- this._emit("signature", content.signature);
- }
- break;
- }
- case "compaction_delta": {
- if (content.type === "compaction" && content.content) {
- this._emit("compaction", content.content);
- }
- break;
- }
- default:
- checkNever5(event.delta);
- }
- break;
- }
- case "message_stop": {
- this._addMessageParam(messageSnapshot);
- this._addMessage(maybeParseBetaMessage2(messageSnapshot, __classPrivateFieldGet7(this, _BetaMessageStream_params2, "f"), { logger: __classPrivateFieldGet7(this, _BetaMessageStream_logger2, "f") }), true);
- break;
- }
- case "content_block_stop": {
- this._emit("contentBlock", messageSnapshot.content.at(-1));
- break;
- }
- case "message_start": {
- __classPrivateFieldSet7(this, _BetaMessageStream_currentMessageSnapshot3, messageSnapshot, "f");
- break;
- }
- case "content_block_start":
- case "message_delta":
- break;
- }
- }, _BetaMessageStream_endRequest3 = function _BetaMessageStream_endRequest4() {
- if (this.ended) {
- throw new AnthropicError3(`stream has ended, this shouldn't happen`);
- }
- const snapshot = __classPrivateFieldGet7(this, _BetaMessageStream_currentMessageSnapshot3, "f");
- if (!snapshot) {
- throw new AnthropicError3(`request ended without sending any chunks`);
- }
- __classPrivateFieldSet7(this, _BetaMessageStream_currentMessageSnapshot3, undefined, "f");
- return maybeParseBetaMessage2(snapshot, __classPrivateFieldGet7(this, _BetaMessageStream_params2, "f"), { logger: __classPrivateFieldGet7(this, _BetaMessageStream_logger2, "f") });
- }, _BetaMessageStream_accumulateMessage3 = function _BetaMessageStream_accumulateMessage4(event) {
- let snapshot = __classPrivateFieldGet7(this, _BetaMessageStream_currentMessageSnapshot3, "f");
- if (event.type === "message_start") {
- if (snapshot) {
- throw new AnthropicError3(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
- }
- return event.message;
- }
- if (!snapshot) {
- throw new AnthropicError3(`Unexpected event order, got ${event.type} before "message_start"`);
- }
- switch (event.type) {
- case "message_stop":
- return snapshot;
- case "message_delta":
- snapshot.container = event.delta.container;
- snapshot.stop_reason = event.delta.stop_reason;
- snapshot.stop_sequence = event.delta.stop_sequence;
- snapshot.usage.output_tokens = event.usage.output_tokens;
- snapshot.context_management = event.context_management;
- if (event.usage.input_tokens != null) {
- snapshot.usage.input_tokens = event.usage.input_tokens;
- }
- if (event.usage.cache_creation_input_tokens != null) {
- snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
- }
- if (event.usage.cache_read_input_tokens != null) {
- snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
- }
- if (event.usage.server_tool_use != null) {
- snapshot.usage.server_tool_use = event.usage.server_tool_use;
- }
- if (event.usage.iterations != null) {
- snapshot.usage.iterations = event.usage.iterations;
- }
- return snapshot;
- case "content_block_start":
- snapshot.content.push(event.content_block);
- return snapshot;
- case "content_block_delta": {
- const snapshotContent = snapshot.content.at(event.index);
- switch (event.delta.type) {
- case "text_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- text: (snapshotContent.text || "") + event.delta.text
- };
- }
- break;
- }
- case "citations_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- citations: [...snapshotContent.citations ?? [], event.delta.citation]
- };
- }
- break;
- }
- case "input_json_delta": {
- if (snapshotContent && tracksToolInput3(snapshotContent)) {
- let jsonBuf = snapshotContent[JSON_BUF_PROPERTY5] || "";
- jsonBuf += event.delta.partial_json;
- const newContent = { ...snapshotContent };
- Object.defineProperty(newContent, JSON_BUF_PROPERTY5, {
- value: jsonBuf,
- enumerable: false,
- writable: true
- });
- if (jsonBuf) {
- try {
- newContent.input = partialParse3(jsonBuf);
- } catch (err) {
- const error44 = new AnthropicError3(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`);
- __classPrivateFieldGet7(this, _BetaMessageStream_handleError3, "f").call(this, error44);
- }
- }
- snapshot.content[event.index] = newContent;
- }
- break;
- }
- case "thinking_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- thinking: snapshotContent.thinking + event.delta.thinking
- };
- }
- break;
- }
- case "signature_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- signature: event.delta.signature
- };
- }
- break;
- }
- case "compaction_delta": {
- if (snapshotContent?.type === "compaction") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- content: (snapshotContent.content || "") + event.delta.content
- };
- }
- break;
- }
- default:
- checkNever5(event.delta);
- }
- return snapshot;
- }
- case "content_block_stop":
- return snapshot;
- }
- }, Symbol.asyncIterator)]() {
- const pushQueue = [];
- const readQueue = [];
- let done = false;
- this.on("streamEvent", (event) => {
- const reader = readQueue.shift();
- if (reader) {
- reader.resolve(event);
- } else {
- pushQueue.push(event);
- }
- });
- this.on("end", () => {
- done = true;
- for (const reader of readQueue) {
- reader.resolve(undefined);
- }
- readQueue.length = 0;
- });
- this.on("abort", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- this.on("error", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- return {
- next: async () => {
- if (!pushQueue.length) {
- if (done) {
- return { value: undefined, done: true };
- }
- return new Promise((resolve9, reject) => readQueue.push({ resolve: resolve9, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
- }
- const chunk = pushQueue.shift();
- return { value: chunk, done: false };
- },
- return: async () => {
- this.abort();
- return { value: undefined, done: true };
- }
- };
- }
- toReadableStream() {
- const stream10 = new Stream4(this[Symbol.asyncIterator].bind(this), this.controller);
- return stream10.toReadableStream();
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs
-var ToolError2;
-var init_ToolError2 = __esm(() => {
- ToolError2 = class ToolError2 extends Error {
- constructor(content) {
- const message = typeof content === "string" ? content : content.map((block2) => {
- if (block2.type === "text")
- return block2.text;
- return `[${block2.type}]`;
- }).join(" ");
- super(message);
- this.name = "ToolError";
- this.content = content;
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs
-var DEFAULT_TOKEN_THRESHOLD2 = 1e5, DEFAULT_SUMMARY_PROMPT2 = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
-1. Task Overview
-The user's core request and success criteria
-Any clarifications or constraints they specified
-2. Current State
-What has been completed so far
-Files created, modified, or analyzed (with paths if relevant)
-Key outputs or artifacts produced
-3. Important Discoveries
-Technical constraints or requirements uncovered
-Decisions made and their rationale
-Errors encountered and how they were resolved
-What approaches were tried that didn't work (and why)
-4. Next Steps
-Specific actions needed to complete the task
-Any blockers or open questions to resolve
-Priority order if multiple steps remain
-5. Context to Preserve
-User preferences or style requirements
-Domain-specific details that aren't obvious
-Any promises made to the user
-Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
-Wrap your summary in tags.`;
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs
-function promiseWithResolvers2() {
- let resolve9;
- let reject;
- const promise2 = new Promise((res, rej) => {
- resolve9 = res;
- reject = rej;
- });
- return { promise: promise2, resolve: resolve9, reject };
-}
-async function generateToolResponse2(params, lastMessage = params.messages.at(-1)) {
- if (!lastMessage || lastMessage.role !== "assistant" || !lastMessage.content || typeof lastMessage.content === "string") {
- return null;
- }
- const toolUseBlocks = lastMessage.content.filter((content) => content.type === "tool_use");
- if (toolUseBlocks.length === 0) {
- return null;
- }
- const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => {
- const tool = params.tools.find((t4) => ("name" in t4 ? t4.name : t4.mcp_server_name) === toolUse.name);
- if (!tool || !("run" in tool)) {
- return {
- type: "tool_result",
- tool_use_id: toolUse.id,
- content: `Error: Tool '${toolUse.name}' not found`,
- is_error: true
- };
- }
- try {
- let input = toolUse.input;
- if ("parse" in tool && tool.parse) {
- input = tool.parse(input);
- }
- const result = await tool.run(input);
- return {
- type: "tool_result",
- tool_use_id: toolUse.id,
- content: result
- };
- } catch (error44) {
- return {
- type: "tool_result",
- tool_use_id: toolUse.id,
- content: error44 instanceof ToolError2 ? error44.content : `Error: ${error44 instanceof Error ? error44.message : String(error44)}`,
- is_error: true
- };
- }
- }));
- return {
- role: "user",
- content: toolResults
- };
-}
-var _BetaToolRunner_instances2, _BetaToolRunner_consumed2, _BetaToolRunner_mutated2, _BetaToolRunner_state2, _BetaToolRunner_options2, _BetaToolRunner_message2, _BetaToolRunner_toolResponse2, _BetaToolRunner_completion2, _BetaToolRunner_iterationCount2, _BetaToolRunner_checkAndCompact2, _BetaToolRunner_generateToolResponse3, BetaToolRunner2;
-var init_BetaToolRunner2 = __esm(() => {
- init_tslib2();
- init_ToolError2();
- init_error6();
- init_headers4();
- init_stainless_helper_header2();
- BetaToolRunner2 = class BetaToolRunner2 {
- constructor(client13, params, options2) {
- _BetaToolRunner_instances2.add(this);
- this.client = client13;
- _BetaToolRunner_consumed2.set(this, false);
- _BetaToolRunner_mutated2.set(this, false);
- _BetaToolRunner_state2.set(this, undefined);
- _BetaToolRunner_options2.set(this, undefined);
- _BetaToolRunner_message2.set(this, undefined);
- _BetaToolRunner_toolResponse2.set(this, undefined);
- _BetaToolRunner_completion2.set(this, undefined);
- _BetaToolRunner_iterationCount2.set(this, 0);
- __classPrivateFieldSet7(this, _BetaToolRunner_state2, {
- params: {
- ...params,
- messages: structuredClone(params.messages)
- }
- }, "f");
- const helpers3 = collectStainlessHelpers2(params.tools, params.messages);
- const helperValue = ["BetaToolRunner", ...helpers3].join(", ");
- __classPrivateFieldSet7(this, _BetaToolRunner_options2, {
- ...options2,
- headers: buildHeaders4([{ "x-stainless-helper": helperValue }, options2?.headers])
- }, "f");
- __classPrivateFieldSet7(this, _BetaToolRunner_completion2, promiseWithResolvers2(), "f");
- }
- async* [(_BetaToolRunner_consumed2 = new WeakMap, _BetaToolRunner_mutated2 = new WeakMap, _BetaToolRunner_state2 = new WeakMap, _BetaToolRunner_options2 = new WeakMap, _BetaToolRunner_message2 = new WeakMap, _BetaToolRunner_toolResponse2 = new WeakMap, _BetaToolRunner_completion2 = new WeakMap, _BetaToolRunner_iterationCount2 = new WeakMap, _BetaToolRunner_instances2 = new WeakSet, _BetaToolRunner_checkAndCompact2 = async function _BetaToolRunner_checkAndCompact3() {
- const compactionControl = __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params.compactionControl;
- if (!compactionControl || !compactionControl.enabled) {
- return false;
- }
- let tokensUsed = 0;
- if (__classPrivateFieldGet7(this, _BetaToolRunner_message2, "f") !== undefined) {
- try {
- const message = await __classPrivateFieldGet7(this, _BetaToolRunner_message2, "f");
- const totalInputTokens = message.usage.input_tokens + (message.usage.cache_creation_input_tokens ?? 0) + (message.usage.cache_read_input_tokens ?? 0);
- tokensUsed = totalInputTokens + message.usage.output_tokens;
- } catch {
- return false;
- }
- }
- const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD2;
- if (tokensUsed < threshold) {
- return false;
- }
- const model = compactionControl.model ?? __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params.model;
- const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT2;
- const messages = __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params.messages;
- if (messages[messages.length - 1].role === "assistant") {
- const lastMessage = messages[messages.length - 1];
- if (Array.isArray(lastMessage.content)) {
- const nonToolBlocks = lastMessage.content.filter((block2) => block2.type !== "tool_use");
- if (nonToolBlocks.length === 0) {
- messages.pop();
- } else {
- lastMessage.content = nonToolBlocks;
- }
- }
- }
- const response7 = await this.client.beta.messages.create({
- model,
- messages: [
- ...messages,
- {
- role: "user",
- content: [
- {
- type: "text",
- text: summaryPrompt
- }
- ]
- }
- ],
- max_tokens: __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params.max_tokens
- }, {
- headers: { "x-stainless-helper": "compaction" }
- });
- if (response7.content[0]?.type !== "text") {
- throw new AnthropicError3("Expected text response for compaction");
- }
- __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params.messages = [
- {
- role: "user",
- content: response7.content
- }
- ];
- return true;
- }, Symbol.asyncIterator)]() {
- var _a6;
- if (__classPrivateFieldGet7(this, _BetaToolRunner_consumed2, "f")) {
- throw new AnthropicError3("Cannot iterate over a consumed stream");
- }
- __classPrivateFieldSet7(this, _BetaToolRunner_consumed2, true, "f");
- __classPrivateFieldSet7(this, _BetaToolRunner_mutated2, true, "f");
- __classPrivateFieldSet7(this, _BetaToolRunner_toolResponse2, undefined, "f");
- try {
- while (true) {
- let stream10;
- try {
- if (__classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params.max_iterations && __classPrivateFieldGet7(this, _BetaToolRunner_iterationCount2, "f") >= __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params.max_iterations) {
- break;
- }
- __classPrivateFieldSet7(this, _BetaToolRunner_mutated2, false, "f");
- __classPrivateFieldSet7(this, _BetaToolRunner_toolResponse2, undefined, "f");
- __classPrivateFieldSet7(this, _BetaToolRunner_iterationCount2, (_a6 = __classPrivateFieldGet7(this, _BetaToolRunner_iterationCount2, "f"), _a6++, _a6), "f");
- __classPrivateFieldSet7(this, _BetaToolRunner_message2, undefined, "f");
- const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params;
- if (params.stream) {
- stream10 = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet7(this, _BetaToolRunner_options2, "f"));
- __classPrivateFieldSet7(this, _BetaToolRunner_message2, stream10.finalMessage(), "f");
- __classPrivateFieldGet7(this, _BetaToolRunner_message2, "f").catch(() => {});
- yield stream10;
- } else {
- __classPrivateFieldSet7(this, _BetaToolRunner_message2, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet7(this, _BetaToolRunner_options2, "f")), "f");
- yield __classPrivateFieldGet7(this, _BetaToolRunner_message2, "f");
- }
- const isCompacted = await __classPrivateFieldGet7(this, _BetaToolRunner_instances2, "m", _BetaToolRunner_checkAndCompact2).call(this);
- if (!isCompacted) {
- if (!__classPrivateFieldGet7(this, _BetaToolRunner_mutated2, "f")) {
- const { role, content } = await __classPrivateFieldGet7(this, _BetaToolRunner_message2, "f");
- __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params.messages.push({ role, content });
- }
- const toolMessage = await __classPrivateFieldGet7(this, _BetaToolRunner_instances2, "m", _BetaToolRunner_generateToolResponse3).call(this, __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params.messages.at(-1));
- if (toolMessage) {
- __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params.messages.push(toolMessage);
- } else if (!__classPrivateFieldGet7(this, _BetaToolRunner_mutated2, "f")) {
- break;
- }
- }
- } finally {
- if (stream10) {
- stream10.abort();
- }
- }
- }
- if (!__classPrivateFieldGet7(this, _BetaToolRunner_message2, "f")) {
- throw new AnthropicError3("ToolRunner concluded without a message from the server");
- }
- __classPrivateFieldGet7(this, _BetaToolRunner_completion2, "f").resolve(await __classPrivateFieldGet7(this, _BetaToolRunner_message2, "f"));
- } catch (error44) {
- __classPrivateFieldSet7(this, _BetaToolRunner_consumed2, false, "f");
- __classPrivateFieldGet7(this, _BetaToolRunner_completion2, "f").promise.catch(() => {});
- __classPrivateFieldGet7(this, _BetaToolRunner_completion2, "f").reject(error44);
- __classPrivateFieldSet7(this, _BetaToolRunner_completion2, promiseWithResolvers2(), "f");
- throw error44;
- }
- }
- setMessagesParams(paramsOrMutator) {
- if (typeof paramsOrMutator === "function") {
- __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params = paramsOrMutator(__classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params);
- } else {
- __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params = paramsOrMutator;
- }
- __classPrivateFieldSet7(this, _BetaToolRunner_mutated2, true, "f");
- __classPrivateFieldSet7(this, _BetaToolRunner_toolResponse2, undefined, "f");
- }
- async generateToolResponse() {
- const message = await __classPrivateFieldGet7(this, _BetaToolRunner_message2, "f") ?? this.params.messages.at(-1);
- if (!message) {
- return null;
- }
- return __classPrivateFieldGet7(this, _BetaToolRunner_instances2, "m", _BetaToolRunner_generateToolResponse3).call(this, message);
- }
- done() {
- return __classPrivateFieldGet7(this, _BetaToolRunner_completion2, "f").promise;
- }
- async runUntilDone() {
- if (!__classPrivateFieldGet7(this, _BetaToolRunner_consumed2, "f")) {
- for await (const _ of this) {}
- }
- return this.done();
- }
- get params() {
- return __classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params;
- }
- pushMessages(...messages) {
- this.setMessagesParams((params) => ({
- ...params,
- messages: [...params.messages, ...messages]
- }));
- }
- then(onfulfilled, onrejected) {
- return this.runUntilDone().then(onfulfilled, onrejected);
- }
- };
- _BetaToolRunner_generateToolResponse3 = async function _BetaToolRunner_generateToolResponse4(lastMessage) {
- if (__classPrivateFieldGet7(this, _BetaToolRunner_toolResponse2, "f") !== undefined) {
- return __classPrivateFieldGet7(this, _BetaToolRunner_toolResponse2, "f");
- }
- __classPrivateFieldSet7(this, _BetaToolRunner_toolResponse2, generateToolResponse2(__classPrivateFieldGet7(this, _BetaToolRunner_state2, "f").params, lastMessage), "f");
- return __classPrivateFieldGet7(this, _BetaToolRunner_toolResponse2, "f");
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs
-var JSONLDecoder3;
-var init_jsonl3 = __esm(() => {
- init_error6();
- init_line3();
- JSONLDecoder3 = class JSONLDecoder3 {
- constructor(iterator2, controller) {
- this.iterator = iterator2;
- this.controller = controller;
- }
- async* decoder() {
- const lineDecoder = new LineDecoder3;
- for await (const chunk of this.iterator) {
- for (const line of lineDecoder.decode(chunk)) {
- yield JSON.parse(line);
- }
- }
- for (const line of lineDecoder.flush()) {
- yield JSON.parse(line);
- }
- }
- [Symbol.asyncIterator]() {
- return this.decoder();
- }
- static fromResponse(response7, controller) {
- if (!response7.body) {
- controller.abort();
- if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
- throw new AnthropicError3(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
- }
- throw new AnthropicError3(`Attempted to iterate over a response with no body`);
- }
- return new JSONLDecoder3(ReadableStreamToAsyncIterable4(response7.body), controller);
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs
-var Batches5;
-var init_batches5 = __esm(() => {
- init_pagination11();
- init_headers4();
- init_jsonl3();
- init_error8();
- init_path4();
- Batches5 = class Batches5 extends APIResource3 {
- create(params, options2) {
- const { betas, ...body } = params;
- return this._client.post("/v1/messages/batches?beta=true", {
- body,
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- retrieve(messageBatchID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path10`/v1/messages/batches/${messageBatchID}?beta=true`, {
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/messages/batches?beta=true", Page3, {
- query,
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- delete(messageBatchID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.delete(path10`/v1/messages/batches/${messageBatchID}?beta=true`, {
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- cancel(messageBatchID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.post(path10`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- async results(messageBatchID, params = {}, options2) {
- const batch = await this.retrieve(messageBatchID);
- if (!batch.results_url) {
- throw new AnthropicError3(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
- }
- const { betas } = params ?? {};
- return this._client.get(batch.results_url, {
- ...options2,
- headers: buildHeaders4([
- {
- "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
- Accept: "application/binary"
- },
- options2?.headers
- ]),
- stream: true,
- __binaryResponse: true
- })._thenUnwrap((_, props) => JSONLDecoder3.fromResponse(props.response, props.controller));
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs
-function transformOutputFormat2(params) {
- if (!params.output_format) {
- return params;
- }
- if (params.output_config?.format) {
- throw new AnthropicError3("Both output_format and output_config.format were provided. " + "Please use only output_config.format (output_format is deprecated).");
- }
- const { output_format, ...rest } = params;
- return {
- ...rest,
- output_config: {
- ...params.output_config,
- format: output_format
- }
- };
-}
-var DEPRECATED_MODELS5, MODELS_TO_WARN_WITH_THINKING_ENABLED3, Messages6;
-var init_messages5 = __esm(() => {
- init_error8();
- init_constants8();
- init_headers4();
- init_stainless_helper_header2();
- init_beta_parser2();
- init_BetaMessageStream3();
- init_BetaToolRunner2();
- init_ToolError2();
- init_batches5();
- init_batches5();
- init_BetaToolRunner2();
- init_ToolError2();
- DEPRECATED_MODELS5 = {
- "claude-1.3": "November 6th, 2024",
- "claude-1.3-100k": "November 6th, 2024",
- "claude-instant-1.1": "November 6th, 2024",
- "claude-instant-1.1-100k": "November 6th, 2024",
- "claude-instant-1.2": "November 6th, 2024",
- "claude-3-sonnet-20240229": "July 21st, 2025",
- "claude-3-opus-20240229": "January 5th, 2026",
- "claude-2.1": "July 21st, 2025",
- "claude-2.0": "July 21st, 2025",
- "claude-3-7-sonnet-latest": "February 19th, 2026",
- "claude-3-7-sonnet-20250219": "February 19th, 2026"
- };
- MODELS_TO_WARN_WITH_THINKING_ENABLED3 = ["claude-opus-4-6"];
- Messages6 = class Messages6 extends APIResource3 {
- constructor() {
- super(...arguments);
- this.batches = new Batches5(this._client);
- }
- create(params, options2) {
- const modifiedParams = transformOutputFormat2(params);
- const { betas, ...body } = modifiedParams;
- if (body.model in DEPRECATED_MODELS5) {
- console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS5[body.model]}
-Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
- }
- if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED3 && body.thinking && body.thinking.type === "enabled") {
- console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
- }
- let timeout = this._client._options.timeout;
- if (!body.stream && timeout == null) {
- const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS2[body.model] ?? undefined;
- timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
- }
- const helperHeader = stainlessHelperHeader2(body.tools, body.messages);
- return this._client.post("/v1/messages?beta=true", {
- body,
- timeout: timeout ?? 600000,
- ...options2,
- headers: buildHeaders4([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- helperHeader,
- options2?.headers
- ]),
- stream: modifiedParams.stream ?? false
- });
- }
- parse(params, options2) {
- options2 = {
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...params.betas ?? [], "structured-outputs-2025-12-15"].toString() },
- options2?.headers
- ])
- };
- return this.create(params, options2).then((message) => parseBetaMessage2(message, params, { logger: this._client.logger ?? console }));
- }
- stream(body, options2) {
- return BetaMessageStream3.createMessage(this, body, options2);
- }
- countTokens(params, options2) {
- const modifiedParams = transformOutputFormat2(params);
- const { betas, ...body } = modifiedParams;
- return this._client.post("/v1/messages/count_tokens?beta=true", {
- body,
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString() },
- options2?.headers
- ])
- });
- }
- toolRunner(body, options2) {
- return new BetaToolRunner2(this._client, body, options2);
- }
- };
- Messages6.Batches = Batches5;
- Messages6.BetaToolRunner = BetaToolRunner2;
- Messages6.ToolError = ToolError2;
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs
-var Versions2;
-var init_versions3 = __esm(() => {
- init_pagination11();
- init_headers4();
- init_uploads4();
- init_path4();
- Versions2 = class Versions2 extends APIResource3 {
- create(skillID, params = {}, options2) {
- const { betas, ...body } = params ?? {};
- return this._client.post(path10`/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions2({
- body,
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- }, this._client));
- }
- retrieve(version2, params, options2) {
- const { skill_id, betas } = params;
- return this._client.get(path10`/v1/skills/${skill_id}/versions/${version2}?beta=true`, {
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- list(skillID, params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList(path10`/v1/skills/${skillID}/versions?beta=true`, PageCursor2, {
- query,
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- delete(version2, params, options2) {
- const { skill_id, betas } = params;
- return this._client.delete(path10`/v1/skills/${skill_id}/versions/${version2}?beta=true`, {
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs
-var Skills2;
-var init_skills2 = __esm(() => {
- init_versions3();
- init_versions3();
- init_pagination11();
- init_headers4();
- init_uploads4();
- init_path4();
- Skills2 = class Skills2 extends APIResource3 {
- constructor() {
- super(...arguments);
- this.versions = new Versions2(this._client);
- }
- create(params = {}, options2) {
- const { betas, ...body } = params ?? {};
- return this._client.post("/v1/skills?beta=true", multipartFormRequestOptions2({
- body,
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- }, this._client, false));
- }
- retrieve(skillID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path10`/v1/skills/${skillID}?beta=true`, {
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/skills?beta=true", PageCursor2, {
- query,
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- delete(skillID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.delete(path10`/v1/skills/${skillID}?beta=true`, {
- ...options2,
- headers: buildHeaders4([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- };
- Skills2.Versions = Versions2;
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs
-var Beta3;
-var init_beta3 = __esm(() => {
- init_files3();
- init_files3();
- init_models5();
- init_models5();
- init_messages5();
- init_messages5();
- init_skills2();
- init_skills2();
- Beta3 = class Beta3 extends APIResource3 {
- constructor() {
- super(...arguments);
- this.models = new Models5(this._client);
- this.messages = new Messages6(this._client);
- this.files = new Files2(this._client);
- this.skills = new Skills2(this._client);
- }
- };
- Beta3.Models = Models5;
- Beta3.Messages = Messages6;
- Beta3.Files = Files2;
- Beta3.Skills = Skills2;
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/completions.mjs
-var Completions3;
-var init_completions3 = __esm(() => {
- init_headers4();
- Completions3 = class Completions3 extends APIResource3 {
- create(params, options2) {
- const { betas, ...body } = params;
- return this._client.post("/v1/complete", {
- body,
- timeout: this._client._options.timeout ?? 600000,
- ...options2,
- headers: buildHeaders4([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ]),
- stream: params.stream ?? false
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/lib/parser.mjs
-function getOutputFormat4(params) {
- return params?.output_config?.format;
-}
-function maybeParseMessage2(message, params, opts) {
- const outputFormat = getOutputFormat4(params);
- if (!params || !("parse" in (outputFormat ?? {}))) {
- return {
- ...message,
- content: message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: null,
- enumerable: false
- });
- return parsedBlock;
- }
- return block2;
- }),
- parsed_output: null
- };
- }
- return parseMessage2(message, params, opts);
-}
-function parseMessage2(message, params, opts) {
- let firstParsedOutput = null;
- const content = message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedOutput = parseOutputFormat2(params, block2.text);
- if (firstParsedOutput === null) {
- firstParsedOutput = parsedOutput;
- }
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: parsedOutput,
- enumerable: false
- });
- return parsedBlock;
- }
- return block2;
- });
- return {
- ...message,
- content,
- parsed_output: firstParsedOutput
- };
-}
-function parseOutputFormat2(params, content) {
- const outputFormat = getOutputFormat4(params);
- if (outputFormat?.type !== "json_schema") {
- return null;
- }
- try {
- if ("parse" in outputFormat) {
- return outputFormat.parse(content);
- }
- return JSON.parse(content);
- } catch (error44) {
- throw new AnthropicError3(`Failed to parse structured output: ${error44}`);
- }
-}
-var init_parser6 = __esm(() => {
- init_error6();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs
-function tracksToolInput4(content) {
- return content.type === "tool_use" || content.type === "server_tool_use";
-}
-function checkNever6(x3) {}
-var _MessageStream_instances3, _MessageStream_currentMessageSnapshot3, _MessageStream_params2, _MessageStream_connectedPromise3, _MessageStream_resolveConnectedPromise3, _MessageStream_rejectConnectedPromise3, _MessageStream_endPromise3, _MessageStream_resolveEndPromise3, _MessageStream_rejectEndPromise3, _MessageStream_listeners3, _MessageStream_ended3, _MessageStream_errored3, _MessageStream_aborted3, _MessageStream_catchingPromiseCreated3, _MessageStream_response3, _MessageStream_request_id3, _MessageStream_logger2, _MessageStream_getFinalMessage3, _MessageStream_getFinalText3, _MessageStream_handleError3, _MessageStream_beginRequest3, _MessageStream_addStreamEvent3, _MessageStream_endRequest3, _MessageStream_accumulateMessage3, JSON_BUF_PROPERTY6 = "__json_buf", MessageStream3;
-var init_MessageStream3 = __esm(() => {
- init_tslib2();
- init_error8();
- init_streaming7();
- init_parser5();
- init_parser6();
- MessageStream3 = class MessageStream3 {
- constructor(params, opts) {
- _MessageStream_instances3.add(this);
- this.messages = [];
- this.receivedMessages = [];
- _MessageStream_currentMessageSnapshot3.set(this, undefined);
- _MessageStream_params2.set(this, null);
- this.controller = new AbortController;
- _MessageStream_connectedPromise3.set(this, undefined);
- _MessageStream_resolveConnectedPromise3.set(this, () => {});
- _MessageStream_rejectConnectedPromise3.set(this, () => {});
- _MessageStream_endPromise3.set(this, undefined);
- _MessageStream_resolveEndPromise3.set(this, () => {});
- _MessageStream_rejectEndPromise3.set(this, () => {});
- _MessageStream_listeners3.set(this, {});
- _MessageStream_ended3.set(this, false);
- _MessageStream_errored3.set(this, false);
- _MessageStream_aborted3.set(this, false);
- _MessageStream_catchingPromiseCreated3.set(this, false);
- _MessageStream_response3.set(this, undefined);
- _MessageStream_request_id3.set(this, undefined);
- _MessageStream_logger2.set(this, undefined);
- _MessageStream_handleError3.set(this, (error44) => {
- __classPrivateFieldSet7(this, _MessageStream_errored3, true, "f");
- if (isAbortError5(error44)) {
- error44 = new APIUserAbortError3;
- }
- if (error44 instanceof APIUserAbortError3) {
- __classPrivateFieldSet7(this, _MessageStream_aborted3, true, "f");
- return this._emit("abort", error44);
- }
- if (error44 instanceof AnthropicError3) {
- return this._emit("error", error44);
- }
- if (error44 instanceof Error) {
- const anthropicError = new AnthropicError3(error44.message);
- anthropicError.cause = error44;
- return this._emit("error", anthropicError);
- }
- return this._emit("error", new AnthropicError3(String(error44)));
- });
- __classPrivateFieldSet7(this, _MessageStream_connectedPromise3, new Promise((resolve9, reject) => {
- __classPrivateFieldSet7(this, _MessageStream_resolveConnectedPromise3, resolve9, "f");
- __classPrivateFieldSet7(this, _MessageStream_rejectConnectedPromise3, reject, "f");
- }), "f");
- __classPrivateFieldSet7(this, _MessageStream_endPromise3, new Promise((resolve9, reject) => {
- __classPrivateFieldSet7(this, _MessageStream_resolveEndPromise3, resolve9, "f");
- __classPrivateFieldSet7(this, _MessageStream_rejectEndPromise3, reject, "f");
- }), "f");
- __classPrivateFieldGet7(this, _MessageStream_connectedPromise3, "f").catch(() => {});
- __classPrivateFieldGet7(this, _MessageStream_endPromise3, "f").catch(() => {});
- __classPrivateFieldSet7(this, _MessageStream_params2, params, "f");
- __classPrivateFieldSet7(this, _MessageStream_logger2, opts?.logger ?? console, "f");
- }
- get response() {
- return __classPrivateFieldGet7(this, _MessageStream_response3, "f");
- }
- get request_id() {
- return __classPrivateFieldGet7(this, _MessageStream_request_id3, "f");
- }
- async withResponse() {
- __classPrivateFieldSet7(this, _MessageStream_catchingPromiseCreated3, true, "f");
- const response7 = await __classPrivateFieldGet7(this, _MessageStream_connectedPromise3, "f");
- if (!response7) {
- throw new Error("Could not resolve a `Response` object");
- }
- return {
- data: this,
- response: response7,
- request_id: response7.headers.get("request-id")
- };
- }
- static fromReadableStream(stream10) {
- const runner = new MessageStream3(null);
- runner._run(() => runner._fromReadableStream(stream10));
- return runner;
- }
- static createMessage(messages, params, options2, { logger: logger8 } = {}) {
- const runner = new MessageStream3(params, { logger: logger8 });
- for (const message of params.messages) {
- runner._addMessageParam(message);
- }
- __classPrivateFieldSet7(runner, _MessageStream_params2, { ...params, stream: true }, "f");
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options2, headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" } }));
- return runner;
- }
- _run(executor) {
- executor().then(() => {
- this._emitFinal();
- this._emit("end");
- }, __classPrivateFieldGet7(this, _MessageStream_handleError3, "f"));
- }
- _addMessageParam(message) {
- this.messages.push(message);
- }
- _addMessage(message, emit = true) {
- this.receivedMessages.push(message);
- if (emit) {
- this._emit("message", message);
- }
- }
- async _createMessage(messages, params, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet7(this, _MessageStream_instances3, "m", _MessageStream_beginRequest3).call(this);
- const { response: response7, data: stream10 } = await messages.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal }).withResponse();
- this._connected(response7);
- for await (const event of stream10) {
- __classPrivateFieldGet7(this, _MessageStream_instances3, "m", _MessageStream_addStreamEvent3).call(this, event);
- }
- if (stream10.controller.signal?.aborted) {
- throw new APIUserAbortError3;
- }
- __classPrivateFieldGet7(this, _MessageStream_instances3, "m", _MessageStream_endRequest3).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- _connected(response7) {
- if (this.ended)
- return;
- __classPrivateFieldSet7(this, _MessageStream_response3, response7, "f");
- __classPrivateFieldSet7(this, _MessageStream_request_id3, response7?.headers.get("request-id"), "f");
- __classPrivateFieldGet7(this, _MessageStream_resolveConnectedPromise3, "f").call(this, response7);
- this._emit("connect");
- }
- get ended() {
- return __classPrivateFieldGet7(this, _MessageStream_ended3, "f");
- }
- get errored() {
- return __classPrivateFieldGet7(this, _MessageStream_errored3, "f");
- }
- get aborted() {
- return __classPrivateFieldGet7(this, _MessageStream_aborted3, "f");
- }
- abort() {
- this.controller.abort();
- }
- on(event, listener) {
- const listeners = __classPrivateFieldGet7(this, _MessageStream_listeners3, "f")[event] || (__classPrivateFieldGet7(this, _MessageStream_listeners3, "f")[event] = []);
- listeners.push({ listener });
- return this;
- }
- off(event, listener) {
- const listeners = __classPrivateFieldGet7(this, _MessageStream_listeners3, "f")[event];
- if (!listeners)
- return this;
- const index2 = listeners.findIndex((l4) => l4.listener === listener);
- if (index2 >= 0)
- listeners.splice(index2, 1);
- return this;
- }
- once(event, listener) {
- const listeners = __classPrivateFieldGet7(this, _MessageStream_listeners3, "f")[event] || (__classPrivateFieldGet7(this, _MessageStream_listeners3, "f")[event] = []);
- listeners.push({ listener, once: true });
- return this;
- }
- emitted(event) {
- return new Promise((resolve9, reject) => {
- __classPrivateFieldSet7(this, _MessageStream_catchingPromiseCreated3, true, "f");
- if (event !== "error")
- this.once("error", reject);
- this.once(event, resolve9);
- });
- }
- async done() {
- __classPrivateFieldSet7(this, _MessageStream_catchingPromiseCreated3, true, "f");
- await __classPrivateFieldGet7(this, _MessageStream_endPromise3, "f");
- }
- get currentMessage() {
- return __classPrivateFieldGet7(this, _MessageStream_currentMessageSnapshot3, "f");
- }
- async finalMessage() {
- await this.done();
- return __classPrivateFieldGet7(this, _MessageStream_instances3, "m", _MessageStream_getFinalMessage3).call(this);
- }
- async finalText() {
- await this.done();
- return __classPrivateFieldGet7(this, _MessageStream_instances3, "m", _MessageStream_getFinalText3).call(this);
- }
- _emit(event, ...args) {
- if (__classPrivateFieldGet7(this, _MessageStream_ended3, "f"))
- return;
- if (event === "end") {
- __classPrivateFieldSet7(this, _MessageStream_ended3, true, "f");
- __classPrivateFieldGet7(this, _MessageStream_resolveEndPromise3, "f").call(this);
- }
- const listeners = __classPrivateFieldGet7(this, _MessageStream_listeners3, "f")[event];
- if (listeners) {
- __classPrivateFieldGet7(this, _MessageStream_listeners3, "f")[event] = listeners.filter((l4) => !l4.once);
- listeners.forEach(({ listener }) => listener(...args));
- }
- if (event === "abort") {
- const error44 = args[0];
- if (!__classPrivateFieldGet7(this, _MessageStream_catchingPromiseCreated3, "f") && !listeners?.length) {
- Promise.reject(error44);
- }
- __classPrivateFieldGet7(this, _MessageStream_rejectConnectedPromise3, "f").call(this, error44);
- __classPrivateFieldGet7(this, _MessageStream_rejectEndPromise3, "f").call(this, error44);
- this._emit("end");
- return;
- }
- if (event === "error") {
- const error44 = args[0];
- if (!__classPrivateFieldGet7(this, _MessageStream_catchingPromiseCreated3, "f") && !listeners?.length) {
- Promise.reject(error44);
- }
- __classPrivateFieldGet7(this, _MessageStream_rejectConnectedPromise3, "f").call(this, error44);
- __classPrivateFieldGet7(this, _MessageStream_rejectEndPromise3, "f").call(this, error44);
- this._emit("end");
- }
- }
- _emitFinal() {
- const finalMessage = this.receivedMessages.at(-1);
- if (finalMessage) {
- this._emit("finalMessage", __classPrivateFieldGet7(this, _MessageStream_instances3, "m", _MessageStream_getFinalMessage3).call(this));
- }
- }
- async _fromReadableStream(readableStream, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet7(this, _MessageStream_instances3, "m", _MessageStream_beginRequest3).call(this);
- this._connected(null);
- const stream10 = Stream4.fromReadableStream(readableStream, this.controller);
- for await (const event of stream10) {
- __classPrivateFieldGet7(this, _MessageStream_instances3, "m", _MessageStream_addStreamEvent3).call(this, event);
- }
- if (stream10.controller.signal?.aborted) {
- throw new APIUserAbortError3;
- }
- __classPrivateFieldGet7(this, _MessageStream_instances3, "m", _MessageStream_endRequest3).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- [(_MessageStream_currentMessageSnapshot3 = new WeakMap, _MessageStream_params2 = new WeakMap, _MessageStream_connectedPromise3 = new WeakMap, _MessageStream_resolveConnectedPromise3 = new WeakMap, _MessageStream_rejectConnectedPromise3 = new WeakMap, _MessageStream_endPromise3 = new WeakMap, _MessageStream_resolveEndPromise3 = new WeakMap, _MessageStream_rejectEndPromise3 = new WeakMap, _MessageStream_listeners3 = new WeakMap, _MessageStream_ended3 = new WeakMap, _MessageStream_errored3 = new WeakMap, _MessageStream_aborted3 = new WeakMap, _MessageStream_catchingPromiseCreated3 = new WeakMap, _MessageStream_response3 = new WeakMap, _MessageStream_request_id3 = new WeakMap, _MessageStream_logger2 = new WeakMap, _MessageStream_handleError3 = new WeakMap, _MessageStream_instances3 = new WeakSet, _MessageStream_getFinalMessage3 = function _MessageStream_getFinalMessage4() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError3("stream ended without producing a Message with role=assistant");
- }
- return this.receivedMessages.at(-1);
- }, _MessageStream_getFinalText3 = function _MessageStream_getFinalText4() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError3("stream ended without producing a Message with role=assistant");
- }
- const textBlocks = this.receivedMessages.at(-1).content.filter((block2) => block2.type === "text").map((block2) => block2.text);
- if (textBlocks.length === 0) {
- throw new AnthropicError3("stream ended without producing a content block with type=text");
- }
- return textBlocks.join(" ");
- }, _MessageStream_beginRequest3 = function _MessageStream_beginRequest4() {
- if (this.ended)
- return;
- __classPrivateFieldSet7(this, _MessageStream_currentMessageSnapshot3, undefined, "f");
- }, _MessageStream_addStreamEvent3 = function _MessageStream_addStreamEvent4(event) {
- if (this.ended)
- return;
- const messageSnapshot = __classPrivateFieldGet7(this, _MessageStream_instances3, "m", _MessageStream_accumulateMessage3).call(this, event);
- this._emit("streamEvent", event, messageSnapshot);
- switch (event.type) {
- case "content_block_delta": {
- const content = messageSnapshot.content.at(-1);
- switch (event.delta.type) {
- case "text_delta": {
- if (content.type === "text") {
- this._emit("text", event.delta.text, content.text || "");
- }
- break;
- }
- case "citations_delta": {
- if (content.type === "text") {
- this._emit("citation", event.delta.citation, content.citations ?? []);
- }
- break;
- }
- case "input_json_delta": {
- if (tracksToolInput4(content) && content.input) {
- this._emit("inputJson", event.delta.partial_json, content.input);
- }
- break;
- }
- case "thinking_delta": {
- if (content.type === "thinking") {
- this._emit("thinking", event.delta.thinking, content.thinking);
- }
- break;
- }
- case "signature_delta": {
- if (content.type === "thinking") {
- this._emit("signature", content.signature);
- }
- break;
- }
- default:
- checkNever6(event.delta);
- }
- break;
- }
- case "message_stop": {
- this._addMessageParam(messageSnapshot);
- this._addMessage(maybeParseMessage2(messageSnapshot, __classPrivateFieldGet7(this, _MessageStream_params2, "f"), { logger: __classPrivateFieldGet7(this, _MessageStream_logger2, "f") }), true);
- break;
- }
- case "content_block_stop": {
- this._emit("contentBlock", messageSnapshot.content.at(-1));
- break;
- }
- case "message_start": {
- __classPrivateFieldSet7(this, _MessageStream_currentMessageSnapshot3, messageSnapshot, "f");
- break;
- }
- case "content_block_start":
- case "message_delta":
- break;
- }
- }, _MessageStream_endRequest3 = function _MessageStream_endRequest4() {
- if (this.ended) {
- throw new AnthropicError3(`stream has ended, this shouldn't happen`);
- }
- const snapshot = __classPrivateFieldGet7(this, _MessageStream_currentMessageSnapshot3, "f");
- if (!snapshot) {
- throw new AnthropicError3(`request ended without sending any chunks`);
- }
- __classPrivateFieldSet7(this, _MessageStream_currentMessageSnapshot3, undefined, "f");
- return maybeParseMessage2(snapshot, __classPrivateFieldGet7(this, _MessageStream_params2, "f"), { logger: __classPrivateFieldGet7(this, _MessageStream_logger2, "f") });
- }, _MessageStream_accumulateMessage3 = function _MessageStream_accumulateMessage4(event) {
- let snapshot = __classPrivateFieldGet7(this, _MessageStream_currentMessageSnapshot3, "f");
- if (event.type === "message_start") {
- if (snapshot) {
- throw new AnthropicError3(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
- }
- return event.message;
- }
- if (!snapshot) {
- throw new AnthropicError3(`Unexpected event order, got ${event.type} before "message_start"`);
- }
- switch (event.type) {
- case "message_stop":
- return snapshot;
- case "message_delta":
- snapshot.stop_reason = event.delta.stop_reason;
- snapshot.stop_sequence = event.delta.stop_sequence;
- snapshot.usage.output_tokens = event.usage.output_tokens;
- if (event.usage.input_tokens != null) {
- snapshot.usage.input_tokens = event.usage.input_tokens;
- }
- if (event.usage.cache_creation_input_tokens != null) {
- snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
- }
- if (event.usage.cache_read_input_tokens != null) {
- snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
- }
- if (event.usage.server_tool_use != null) {
- snapshot.usage.server_tool_use = event.usage.server_tool_use;
- }
- return snapshot;
- case "content_block_start":
- snapshot.content.push({ ...event.content_block });
- return snapshot;
- case "content_block_delta": {
- const snapshotContent = snapshot.content.at(event.index);
- switch (event.delta.type) {
- case "text_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- text: (snapshotContent.text || "") + event.delta.text
- };
- }
- break;
- }
- case "citations_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- citations: [...snapshotContent.citations ?? [], event.delta.citation]
- };
- }
- break;
- }
- case "input_json_delta": {
- if (snapshotContent && tracksToolInput4(snapshotContent)) {
- let jsonBuf = snapshotContent[JSON_BUF_PROPERTY6] || "";
- jsonBuf += event.delta.partial_json;
- const newContent = { ...snapshotContent };
- Object.defineProperty(newContent, JSON_BUF_PROPERTY6, {
- value: jsonBuf,
- enumerable: false,
- writable: true
- });
- if (jsonBuf) {
- newContent.input = partialParse3(jsonBuf);
- }
- snapshot.content[event.index] = newContent;
- }
- break;
- }
- case "thinking_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- thinking: snapshotContent.thinking + event.delta.thinking
- };
- }
- break;
- }
- case "signature_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- signature: event.delta.signature
- };
- }
- break;
- }
- default:
- checkNever6(event.delta);
- }
- return snapshot;
- }
- case "content_block_stop":
- return snapshot;
- }
- }, Symbol.asyncIterator)]() {
- const pushQueue = [];
- const readQueue = [];
- let done = false;
- this.on("streamEvent", (event) => {
- const reader = readQueue.shift();
- if (reader) {
- reader.resolve(event);
- } else {
- pushQueue.push(event);
- }
- });
- this.on("end", () => {
- done = true;
- for (const reader of readQueue) {
- reader.resolve(undefined);
- }
- readQueue.length = 0;
- });
- this.on("abort", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- this.on("error", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- return {
- next: async () => {
- if (!pushQueue.length) {
- if (done) {
- return { value: undefined, done: true };
- }
- return new Promise((resolve9, reject) => readQueue.push({ resolve: resolve9, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
- }
- const chunk = pushQueue.shift();
- return { value: chunk, done: false };
- },
- return: async () => {
- this.abort();
- return { value: undefined, done: true };
- }
- };
- }
- toReadableStream() {
- const stream10 = new Stream4(this[Symbol.asyncIterator].bind(this), this.controller);
- return stream10.toReadableStream();
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs
-var Batches6;
-var init_batches6 = __esm(() => {
- init_pagination11();
- init_headers4();
- init_jsonl3();
- init_error8();
- init_path4();
- Batches6 = class Batches6 extends APIResource3 {
- create(body, options2) {
- return this._client.post("/v1/messages/batches", { body, ...options2 });
- }
- retrieve(messageBatchID, options2) {
- return this._client.get(path10`/v1/messages/batches/${messageBatchID}`, options2);
- }
- list(query = {}, options2) {
- return this._client.getAPIList("/v1/messages/batches", Page3, { query, ...options2 });
- }
- delete(messageBatchID, options2) {
- return this._client.delete(path10`/v1/messages/batches/${messageBatchID}`, options2);
- }
- cancel(messageBatchID, options2) {
- return this._client.post(path10`/v1/messages/batches/${messageBatchID}/cancel`, options2);
- }
- async results(messageBatchID, options2) {
- const batch = await this.retrieve(messageBatchID);
- if (!batch.results_url) {
- throw new AnthropicError3(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
- }
- return this._client.get(batch.results_url, {
- ...options2,
- headers: buildHeaders4([{ Accept: "application/binary" }, options2?.headers]),
- stream: true,
- __binaryResponse: true
- })._thenUnwrap((_, props) => JSONLDecoder3.fromResponse(props.response, props.controller));
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs
-var Messages7, DEPRECATED_MODELS6, MODELS_TO_WARN_WITH_THINKING_ENABLED4;
-var init_messages6 = __esm(() => {
- init_headers4();
- init_stainless_helper_header2();
- init_MessageStream3();
- init_parser6();
- init_batches6();
- init_batches6();
- init_constants8();
- Messages7 = class Messages7 extends APIResource3 {
- constructor() {
- super(...arguments);
- this.batches = new Batches6(this._client);
- }
- create(body, options2) {
- if (body.model in DEPRECATED_MODELS6) {
- console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS6[body.model]}
-Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
- }
- if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED4 && body.thinking && body.thinking.type === "enabled") {
- console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
- }
- let timeout = this._client._options.timeout;
- if (!body.stream && timeout == null) {
- const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS2[body.model] ?? undefined;
- timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
- }
- const helperHeader = stainlessHelperHeader2(body.tools, body.messages);
- return this._client.post("/v1/messages", {
- body,
- timeout: timeout ?? 600000,
- ...options2,
- headers: buildHeaders4([helperHeader, options2?.headers]),
- stream: body.stream ?? false
- });
- }
- parse(params, options2) {
- return this.create(params, options2).then((message) => parseMessage2(message, params, { logger: this._client.logger ?? console }));
- }
- stream(body, options2) {
- return MessageStream3.createMessage(this, body, options2, { logger: this._client.logger ?? console });
- }
- countTokens(body, options2) {
- return this._client.post("/v1/messages/count_tokens", { body, ...options2 });
- }
- };
- DEPRECATED_MODELS6 = {
- "claude-1.3": "November 6th, 2024",
- "claude-1.3-100k": "November 6th, 2024",
- "claude-instant-1.1": "November 6th, 2024",
- "claude-instant-1.1-100k": "November 6th, 2024",
- "claude-instant-1.2": "November 6th, 2024",
- "claude-3-sonnet-20240229": "July 21st, 2025",
- "claude-3-opus-20240229": "January 5th, 2026",
- "claude-2.1": "July 21st, 2025",
- "claude-2.0": "July 21st, 2025",
- "claude-3-7-sonnet-latest": "February 19th, 2026",
- "claude-3-7-sonnet-20250219": "February 19th, 2026",
- "claude-3-5-haiku-latest": "February 19th, 2026",
- "claude-3-5-haiku-20241022": "February 19th, 2026"
- };
- MODELS_TO_WARN_WITH_THINKING_ENABLED4 = ["claude-opus-4-6"];
- Messages7.Batches = Batches6;
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/models.mjs
-var Models6;
-var init_models6 = __esm(() => {
- init_pagination11();
- init_headers4();
- init_path4();
- Models6 = class Models6 extends APIResource3 {
- retrieve(modelID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path10`/v1/models/${modelID}`, {
- ...options2,
- headers: buildHeaders4([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/models", Page3, {
- query,
- ...options2,
- headers: buildHeaders4([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/resources/index.mjs
-var init_resources3 = __esm(() => {
- init_beta3();
- init_completions3();
- init_messages6();
- init_models6();
- init_shared10();
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs
-var readEnv5 = (env5) => {
- if (typeof globalThis.process !== "undefined") {
- return globalThis.process.env?.[env5]?.trim() ?? undefined;
- }
- if (typeof globalThis.Deno !== "undefined") {
- return globalThis.Deno.env?.get?.(env5)?.trim();
- }
- return;
-};
-
-// node_modules/@anthropic-ai/foundry-sdk/node_modules/@anthropic-ai/sdk/client.mjs
-class BaseAnthropic2 {
- constructor({ baseURL = readEnv5("ANTHROPIC_BASE_URL"), apiKey = readEnv5("ANTHROPIC_API_KEY") ?? null, authToken = readEnv5("ANTHROPIC_AUTH_TOKEN") ?? null, ...opts } = {}) {
- _BaseAnthropic_instances2.add(this);
- _BaseAnthropic_encoder2.set(this, undefined);
- const options2 = {
- apiKey,
- authToken,
- ...opts,
- baseURL: baseURL || `https://api.anthropic.com`
- };
- if (!options2.dangerouslyAllowBrowser && isRunningInBrowser3()) {
- throw new AnthropicError3(`It looks like you're running in a browser-like environment.
-
-This is disabled by default, as it risks exposing your secret API credentials to attackers.
-If you understand the risks and have appropriate mitigations in place,
-you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
-
-new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
-`);
- }
- this.baseURL = options2.baseURL;
- this.timeout = options2.timeout ?? _a6.DEFAULT_TIMEOUT;
- this.logger = options2.logger ?? console;
- const defaultLogLevel = "warn";
- this.logLevel = defaultLogLevel;
- this.logLevel = parseLogLevel2(options2.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel2(readEnv5("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", this) ?? defaultLogLevel;
- this.fetchOptions = options2.fetchOptions;
- this.maxRetries = options2.maxRetries ?? 2;
- this.fetch = options2.fetch ?? getDefaultFetch2();
- __classPrivateFieldSet7(this, _BaseAnthropic_encoder2, FallbackEncoder2, "f");
- this._options = options2;
- this.apiKey = typeof apiKey === "string" ? apiKey : null;
- this.authToken = authToken;
- }
- withOptions(options2) {
- const client13 = new this.constructor({
- ...this._options,
- baseURL: this.baseURL,
- maxRetries: this.maxRetries,
- timeout: this.timeout,
- logger: this.logger,
- logLevel: this.logLevel,
- fetch: this.fetch,
- fetchOptions: this.fetchOptions,
- apiKey: this.apiKey,
- authToken: this.authToken,
- ...options2
- });
- return client13;
- }
- defaultQuery() {
- return this._options.defaultQuery;
- }
- validateHeaders({ values: values2, nulls }) {
- if (values2.get("x-api-key") || values2.get("authorization")) {
- return;
- }
- if (this.apiKey && values2.get("x-api-key")) {
- return;
- }
- if (nulls.has("x-api-key")) {
- return;
- }
- if (this.authToken && values2.get("authorization")) {
- return;
- }
- if (nulls.has("authorization")) {
- return;
- }
- throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
- }
- async authHeaders(opts) {
- return buildHeaders4([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
- }
- async apiKeyAuth(opts) {
- if (this.apiKey == null) {
- return;
- }
- return buildHeaders4([{ "X-Api-Key": this.apiKey }]);
- }
- async bearerAuth(opts) {
- if (this.authToken == null) {
- return;
- }
- return buildHeaders4([{ Authorization: `Bearer ${this.authToken}` }]);
- }
- stringifyQuery(query) {
- return stringifyQuery2(query);
- }
- getUserAgent() {
- return `${this.constructor.name}/JS ${VERSION5}`;
- }
- defaultIdempotencyKey() {
- return `stainless-node-retry-${uuid44()}`;
- }
- makeStatusError(status, error44, message, headers) {
- return APIError3.generate(status, error44, message, headers);
- }
- buildURL(path11, query, defaultBaseURL) {
- const baseURL = !__classPrivateFieldGet7(this, _BaseAnthropic_instances2, "m", _BaseAnthropic_baseURLOverridden3).call(this) && defaultBaseURL || this.baseURL;
- const url3 = isAbsoluteURL4(path11) ? new URL(path11) : new URL(baseURL + (baseURL.endsWith("/") && path11.startsWith("/") ? path11.slice(1) : path11));
- const defaultQuery = this.defaultQuery();
- const pathQuery = Object.fromEntries(url3.searchParams);
- if (!isEmptyObj3(defaultQuery) || !isEmptyObj3(pathQuery)) {
- query = { ...pathQuery, ...defaultQuery, ...query };
- }
- if (typeof query === "object" && query && !Array.isArray(query)) {
- url3.search = this.stringifyQuery(query);
- }
- return url3.toString();
- }
- _calculateNonstreamingTimeout(maxTokens) {
- const defaultTimeout = 10 * 60;
- const expectedTimeout = 60 * 60 * maxTokens / 128000;
- if (expectedTimeout > defaultTimeout) {
- throw new AnthropicError3("Streaming is required for operations that may take longer than 10 minutes. " + "See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");
- }
- return defaultTimeout * 1000;
- }
- async prepareOptions(options2) {}
- async prepareRequest(request2, { url: url3, options: options2 }) {}
- get(path11, opts) {
- return this.methodRequest("get", path11, opts);
- }
- post(path11, opts) {
- return this.methodRequest("post", path11, opts);
- }
- patch(path11, opts) {
- return this.methodRequest("patch", path11, opts);
- }
- put(path11, opts) {
- return this.methodRequest("put", path11, opts);
- }
- delete(path11, opts) {
- return this.methodRequest("delete", path11, opts);
- }
- methodRequest(method, path11, opts) {
- return this.request(Promise.resolve(opts).then((opts2) => {
- return { method, path: path11, ...opts2 };
- }));
- }
- request(options2, remainingRetries = null) {
- return new APIPromise3(this, this.makeRequest(options2, remainingRetries, undefined));
- }
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
- const options2 = await optionsInput;
- const maxRetries = options2.maxRetries ?? this.maxRetries;
- if (retriesRemaining == null) {
- retriesRemaining = maxRetries;
- }
- await this.prepareOptions(options2);
- const { req, url: url3, timeout } = await this.buildRequest(options2, {
- retryCount: maxRetries - retriesRemaining
- });
- await this.prepareRequest(req, { url: url3, options: options2 });
- const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
- const retryLogStr = retryOfRequestLogID === undefined ? "" : `, retryOf: ${retryOfRequestLogID}`;
- const startTime = Date.now();
- loggerFor3(this).debug(`[${requestLogID}] sending request`, formatRequestDetails2({
- retryOfRequestLogID,
- method: options2.method,
- url: url3,
- options: options2,
- headers: req.headers
- }));
- if (options2.signal?.aborted) {
- throw new APIUserAbortError3;
- }
- const controller = new AbortController;
- const response7 = await this.fetchWithTimeout(url3, req, timeout, controller).catch(castToError3);
- const headersTime = Date.now();
- if (response7 instanceof globalThis.Error) {
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
- if (options2.signal?.aborted) {
- throw new APIUserAbortError3;
- }
- const isTimeout = isAbortError5(response7) || /timed? ?out/i.test(String(response7) + ("cause" in response7 ? String(response7.cause) : ""));
- if (retriesRemaining) {
- loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
- loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails2({
- retryOfRequestLogID,
- url: url3,
- durationMs: headersTime - startTime,
- message: response7.message
- }));
- return this.retryRequest(options2, retriesRemaining, retryOfRequestLogID ?? requestLogID);
- }
- loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
- loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails2({
- retryOfRequestLogID,
- url: url3,
- durationMs: headersTime - startTime,
- message: response7.message
- }));
- if (isTimeout) {
- throw new APIConnectionTimeoutError3;
- }
- throw new APIConnectionError3({ cause: response7 });
- }
- const specialHeaders = [...response7.headers.entries()].filter(([name]) => name === "request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("");
- const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url3} ${response7.ok ? "succeeded" : "failed"} with status ${response7.status} in ${headersTime - startTime}ms`;
- if (!response7.ok) {
- const shouldRetry = await this.shouldRetry(response7);
- if (retriesRemaining && shouldRetry) {
- const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
- await CancelReadableStream2(response7.body);
- loggerFor3(this).info(`${responseInfo} - ${retryMessage2}`);
- loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails2({
- retryOfRequestLogID,
- url: response7.url,
- status: response7.status,
- headers: response7.headers,
- durationMs: headersTime - startTime
- }));
- return this.retryRequest(options2, retriesRemaining, retryOfRequestLogID ?? requestLogID, response7.headers);
- }
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
- loggerFor3(this).info(`${responseInfo} - ${retryMessage}`);
- const errText = await response7.text().catch((err2) => castToError3(err2).message);
- const errJSON = safeJSON4(errText);
- const errMessage = errJSON ? undefined : errText;
- loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails2({
- retryOfRequestLogID,
- url: response7.url,
- status: response7.status,
- headers: response7.headers,
- message: errMessage,
- durationMs: Date.now() - startTime
- }));
- const err = this.makeStatusError(response7.status, errJSON, errMessage, response7.headers);
- throw err;
- }
- loggerFor3(this).info(responseInfo);
- loggerFor3(this).debug(`[${requestLogID}] response start`, formatRequestDetails2({
- retryOfRequestLogID,
- url: response7.url,
- status: response7.status,
- headers: response7.headers,
- durationMs: headersTime - startTime
- }));
- return { response: response7, options: options2, controller, requestLogID, retryOfRequestLogID, startTime };
- }
- getAPIList(path11, Page4, opts) {
- return this.requestAPIList(Page4, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path11, ...opts2 })) : { method: "get", path: path11, ...opts });
- }
- requestAPIList(Page4, options2) {
- const request2 = this.makeRequest(options2, null, undefined);
- return new PagePromise3(this, request2, Page4);
- }
- async fetchWithTimeout(url3, init, ms, controller) {
- const { signal, method, ...options2 } = init || {};
- const abort7 = this._makeAbort(controller);
- if (signal)
- signal.addEventListener("abort", abort7, { once: true });
- const timeout = setTimeout(abort7, ms);
- const isReadableBody = globalThis.ReadableStream && options2.body instanceof globalThis.ReadableStream || typeof options2.body === "object" && options2.body !== null && Symbol.asyncIterator in options2.body;
- const fetchOptions = {
- signal: controller.signal,
- ...isReadableBody ? { duplex: "half" } : {},
- method: "GET",
- ...options2
- };
- if (method) {
- fetchOptions.method = method.toUpperCase();
- }
- try {
- return await this.fetch.call(undefined, url3, fetchOptions);
- } finally {
- clearTimeout(timeout);
- }
- }
- async shouldRetry(response7) {
- const shouldRetryHeader = response7.headers.get("x-should-retry");
- if (shouldRetryHeader === "true")
- return true;
- if (shouldRetryHeader === "false")
- return false;
- if (response7.status === 408)
- return true;
- if (response7.status === 409)
- return true;
- if (response7.status === 429)
- return true;
- if (response7.status >= 500)
- return true;
- return false;
- }
- async retryRequest(options2, retriesRemaining, requestLogID, responseHeaders) {
- let timeoutMillis;
- const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
- if (retryAfterMillisHeader) {
- const timeoutMs = parseFloat(retryAfterMillisHeader);
- if (!Number.isNaN(timeoutMs)) {
- timeoutMillis = timeoutMs;
- }
- }
- const retryAfterHeader = responseHeaders?.get("retry-after");
- if (retryAfterHeader && !timeoutMillis) {
- const timeoutSeconds = parseFloat(retryAfterHeader);
- if (!Number.isNaN(timeoutSeconds)) {
- timeoutMillis = timeoutSeconds * 1000;
- } else {
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
- }
- }
- if (timeoutMillis === undefined) {
- const maxRetries = options2.maxRetries ?? this.maxRetries;
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
- }
- await sleep4(timeoutMillis);
- return this.makeRequest(options2, retriesRemaining - 1, requestLogID);
- }
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
- const initialRetryDelay = 0.5;
- const maxRetryDelay = 8;
- const numRetries = maxRetries - retriesRemaining;
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
- const jitter = 1 - Math.random() * 0.25;
- return sleepSeconds * jitter * 1000;
- }
- calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
- const maxTime = 60 * 60 * 1000;
- const defaultTime = 60 * 10 * 1000;
- const expectedTime = maxTime * maxTokens / 128000;
- if (expectedTime > defaultTime || maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens) {
- throw new AnthropicError3("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");
- }
- return defaultTime;
- }
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
- const options2 = { ...inputOptions };
- const { method, path: path11, query, defaultBaseURL } = options2;
- const url3 = this.buildURL(path11, query, defaultBaseURL);
- if ("timeout" in options2)
- validatePositiveInteger3("timeout", options2.timeout);
- options2.timeout = options2.timeout ?? this.timeout;
- const { bodyHeaders, body } = this.buildBody({ options: options2 });
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
- const req = {
- method,
- headers: reqHeaders,
- ...options2.signal && { signal: options2.signal },
- ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
- ...body && { body },
- ...this.fetchOptions ?? {},
- ...options2.fetchOptions ?? {}
- };
- return { req, url: url3, timeout: options2.timeout };
- }
- async buildHeaders({ options: options2, method, bodyHeaders, retryCount }) {
- let idempotencyHeaders = {};
- if (this.idempotencyHeader && method !== "get") {
- if (!options2.idempotencyKey)
- options2.idempotencyKey = this.defaultIdempotencyKey();
- idempotencyHeaders[this.idempotencyHeader] = options2.idempotencyKey;
- }
- const headers = buildHeaders4([
- idempotencyHeaders,
- {
- Accept: "application/json",
- "User-Agent": this.getUserAgent(),
- "X-Stainless-Retry-Count": String(retryCount),
- ...options2.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options2.timeout / 1000)) } : {},
- ...getPlatformHeaders3(),
- ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : undefined,
- "anthropic-version": "2023-06-01"
- },
- await this.authHeaders(options2),
- this._options.defaultHeaders,
- bodyHeaders,
- options2.headers
- ]);
- this.validateHeaders(headers);
- return headers.values;
- }
- _makeAbort(controller) {
- return () => controller.abort();
- }
- buildBody({ options: { body, headers: rawHeaders } }) {
- if (!body) {
- return { bodyHeaders: undefined, body: undefined };
- }
- const headers = buildHeaders4([rawHeaders]);
- if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && headers.values.has("content-type") || globalThis.Blob && body instanceof globalThis.Blob || body instanceof FormData || body instanceof URLSearchParams || globalThis.ReadableStream && body instanceof globalThis.ReadableStream) {
- return { bodyHeaders: undefined, body };
- } else if (typeof body === "object" && ((Symbol.asyncIterator in body) || (Symbol.iterator in body) && ("next" in body) && typeof body.next === "function")) {
- return { bodyHeaders: undefined, body: ReadableStreamFrom2(body) };
- } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
- return {
- bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
- body: this.stringifyQuery(body)
- };
- } else {
- return __classPrivateFieldGet7(this, _BaseAnthropic_encoder2, "f").call(this, { body, headers });
- }
- }
-}
-var _BaseAnthropic_instances2, _a6, _BaseAnthropic_encoder2, _BaseAnthropic_baseURLOverridden3, HUMAN_PROMPT2 = "\\n\\nHuman:", AI_PROMPT2 = "\\n\\nAssistant:", Anthropic3;
-var init_client15 = __esm(() => {
- init_tslib2();
- init_values5();
- init_detect_platform2();
- init_query2();
- init_error6();
- init_pagination11();
- init_uploads5();
- init_resources3();
- init_api_promise2();
- init_completions3();
- init_models6();
- init_beta3();
- init_messages6();
- init_detect_platform2();
- init_headers4();
- init_log6();
- init_values5();
- _a6 = BaseAnthropic2, _BaseAnthropic_encoder2 = new WeakMap, _BaseAnthropic_instances2 = new WeakSet, _BaseAnthropic_baseURLOverridden3 = function _BaseAnthropic_baseURLOverridden4() {
- return this.baseURL !== "https://api.anthropic.com";
- };
- BaseAnthropic2.Anthropic = _a6;
- BaseAnthropic2.HUMAN_PROMPT = HUMAN_PROMPT2;
- BaseAnthropic2.AI_PROMPT = AI_PROMPT2;
- BaseAnthropic2.DEFAULT_TIMEOUT = 600000;
- BaseAnthropic2.AnthropicError = AnthropicError3;
- BaseAnthropic2.APIError = APIError3;
- BaseAnthropic2.APIConnectionError = APIConnectionError3;
- BaseAnthropic2.APIConnectionTimeoutError = APIConnectionTimeoutError3;
- BaseAnthropic2.APIUserAbortError = APIUserAbortError3;
- BaseAnthropic2.NotFoundError = NotFoundError3;
- BaseAnthropic2.ConflictError = ConflictError3;
- BaseAnthropic2.RateLimitError = RateLimitError3;
- BaseAnthropic2.BadRequestError = BadRequestError3;
- BaseAnthropic2.AuthenticationError = AuthenticationError3;
- BaseAnthropic2.InternalServerError = InternalServerError3;
- BaseAnthropic2.PermissionDeniedError = PermissionDeniedError3;
- BaseAnthropic2.UnprocessableEntityError = UnprocessableEntityError3;
- BaseAnthropic2.toFile = toFile3;
- Anthropic3 = class Anthropic3 extends BaseAnthropic2 {
- constructor() {
- super(...arguments);
- this.completions = new Completions3(this);
- this.messages = new Messages7(this);
- this.models = new Models6(this);
- this.beta = new Beta3(this);
- }
- };
- Anthropic3.Completions = Completions3;
- Anthropic3.Messages = Messages7;
- Anthropic3.Models = Models6;
- Anthropic3.Beta = Beta3;
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/client.mjs
-function makeMessagesResource2(client13) {
- const resource = new Messages7(client13);
- delete resource.batches;
- return resource;
-}
-function makeBetaResource2(client13) {
- const resource = new Beta3(client13);
- delete resource.messages.batches;
- return resource;
-}
-var AnthropicFoundry;
-var init_client16 = __esm(() => {
- init_headers3();
- init_error7();
- init_utils3();
- init_client15();
- init_client15();
- init_resources3();
- AnthropicFoundry = class AnthropicFoundry extends Anthropic3 {
- constructor({ baseURL = readEnv4("ANTHROPIC_FOUNDRY_BASE_URL"), apiKey = readEnv4("ANTHROPIC_FOUNDRY_API_KEY"), resource = readEnv4("ANTHROPIC_FOUNDRY_RESOURCE"), azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) {
- if (typeof azureADTokenProvider === "function") {
- dangerouslyAllowBrowser = true;
- }
- if (!azureADTokenProvider && !apiKey) {
- throw new AnthropicError3("Missing credentials. Please pass one of `apiKey` and `azureTokenProvider`, or set the `ANTHROPIC_FOUNDRY_API_KEY` environment variable.");
- }
- if (azureADTokenProvider && apiKey) {
- throw new AnthropicError3("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");
- }
- if (!baseURL) {
- if (!resource) {
- throw new AnthropicError3("Must provide one of the `baseURL` or `resource` arguments, or the `ANTHROPIC_FOUNDRY_RESOURCE` environment variable");
- }
- baseURL = `https://${resource}.services.ai.azure.com/anthropic/`;
- } else {
- if (resource) {
- throw new AnthropicError3("baseURL and resource are mutually exclusive");
- }
- }
- super({
- apiKey: azureADTokenProvider ?? apiKey,
- baseURL,
- ...opts,
- ...dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}
- });
- this.resource = null;
- this.messages = makeMessagesResource2(this);
- this.beta = makeBetaResource2(this);
- this.models = undefined;
- }
- async authHeaders() {
- if (typeof this._options.apiKey === "function") {
- let token;
- try {
- token = await this._options.apiKey();
- } catch (err) {
- if (err instanceof AnthropicError3)
- throw err;
- throw new AnthropicError3(`Failed to get token from azureADTokenProvider: ${err.message}`, { cause: err });
- }
- if (typeof token !== "string" || !token) {
- throw new AnthropicError3(`Expected azureADTokenProvider function argument to return a string but it returned ${token}`);
- }
- return buildHeaders3([{ Authorization: `Bearer ${token}` }]);
- }
- if (typeof this._options.apiKey === "string") {
- return buildHeaders3([{ "x-api-key": this.apiKey }]);
- }
- return;
- }
- validateHeaders() {
- return;
- }
- };
-});
-
-// node_modules/@anthropic-ai/foundry-sdk/index.mjs
-var exports_foundry_sdk = {};
-__export(exports_foundry_sdk, {
- default: () => AnthropicFoundry,
- BaseAnthropic: () => BaseAnthropic2,
- AnthropicFoundry: () => AnthropicFoundry
-});
-var init_foundry_sdk = __esm(() => {
- init_client16();
- init_client16();
-});
-
-// node_modules/@azure/identity/dist/esm/constants.js
-var SDK_VERSION2 = `4.13.1`, DeveloperSignOnClientId = "04b07795-8ddb-461a-bbee-02f9e1bf7b46", DefaultTenantId = "common", AzureAuthorityHosts, DefaultAuthorityHost, DefaultAuthority = "login.microsoftonline.com", ALL_TENANTS, CACHE_CAE_SUFFIX = "cae", CACHE_NON_CAE_SUFFIX = "nocae", DEFAULT_TOKEN_CACHE_NAME = "msal.cache";
-var init_constants9 = __esm(() => {
- (function(AzureAuthorityHosts2) {
- AzureAuthorityHosts2["AzureChina"] = "https://login.chinacloudapi.cn";
- AzureAuthorityHosts2["AzureGermany"] = "https://login.microsoftonline.de";
- AzureAuthorityHosts2["AzureGovernment"] = "https://login.microsoftonline.us";
- AzureAuthorityHosts2["AzurePublicCloud"] = "https://login.microsoftonline.com";
- })(AzureAuthorityHosts || (AzureAuthorityHosts = {}));
- DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud;
- ALL_TENANTS = ["*"];
-});
-
-// node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalPlugins.js
-function hasVSCodePlugin() {
- return vsCodeAuthRecordPath !== undefined && vsCodeBrokerInfo !== undefined;
-}
-function generatePluginConfiguration(options2) {
- const config8 = {
- cache: {},
- broker: {
- ...options2.brokerOptions,
- isEnabled: options2.brokerOptions?.enabled ?? false,
- enableMsaPassthrough: options2.brokerOptions?.legacyEnableMsaPassthrough ?? false
- }
- };
- if (options2.tokenCachePersistenceOptions?.enabled) {
- if (persistenceProvider === undefined) {
- throw new Error([
- "Persistent token caching was requested, but no persistence provider was configured.",
- "You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)",
- "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling",
- "`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`."
- ].join(" "));
- }
- const cacheBaseName = options2.tokenCachePersistenceOptions.name || DEFAULT_TOKEN_CACHE_NAME;
- config8.cache.cachePlugin = persistenceProvider({
- name: `${cacheBaseName}.${CACHE_NON_CAE_SUFFIX}`,
- ...options2.tokenCachePersistenceOptions
- });
- config8.cache.cachePluginCae = persistenceProvider({
- name: `${cacheBaseName}.${CACHE_CAE_SUFFIX}`,
- ...options2.tokenCachePersistenceOptions
- });
- }
- if (options2.brokerOptions?.enabled) {
- config8.broker.nativeBrokerPlugin = getBrokerPlugin(options2.isVSCodeCredential || false);
- }
- return config8;
-}
-function getBrokerPlugin(isVSCodePlugin) {
- const { credentialName, packageName, pluginVar, brokerInfo } = brokerConfig[isVSCodePlugin ? "vsCode" : "native"];
- if (brokerInfo === undefined) {
- throw new Error(brokerErrorTemplates.missing(credentialName, packageName, pluginVar));
- }
- if (brokerInfo.broker.isBrokerAvailable === false) {
- throw new Error(brokerErrorTemplates.unavailable(credentialName, packageName));
- }
- return brokerInfo.broker;
-}
-var persistenceProvider = undefined, msalNodeFlowCacheControl, nativeBrokerInfo = undefined, vsCodeAuthRecordPath = undefined, vsCodeBrokerInfo = undefined, msalNodeFlowNativeBrokerControl, msalNodeFlowVSCodeCredentialControl, brokerErrorTemplates, brokerConfig, msalPlugins;
-var init_msalPlugins = __esm(() => {
- init_constants9();
- msalNodeFlowCacheControl = {
- setPersistence(pluginProvider) {
- persistenceProvider = pluginProvider;
- }
- };
- msalNodeFlowNativeBrokerControl = {
- setNativeBroker(broker) {
- nativeBrokerInfo = {
- broker
- };
- }
- };
- msalNodeFlowVSCodeCredentialControl = {
- setVSCodeAuthRecordPath(path11) {
- vsCodeAuthRecordPath = path11;
- },
- setVSCodeBroker(broker) {
- vsCodeBrokerInfo = {
- broker
- };
- }
- };
- brokerErrorTemplates = {
- missing: (credentialName, packageName, pluginVar) => [
- `${credentialName} was requested, but no plugin was configured or no authentication record was found.`,
- `You must install the ${packageName} plugin package (npm install --save ${packageName})`,
- "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling",
- `useIdentityPlugin(${pluginVar}) before using enableBroker.`
- ].join(" "),
- unavailable: (credentialName, packageName) => [
- `${credentialName} was requested, and the plugin is configured, but the broker is unavailable.`,
- `Ensure the ${credentialName} plugin is properly installed and configured.`,
- "Check for missing native dependencies and ensure the package is properly installed.",
- `See the README for prerequisites on installing and using ${packageName}.`
- ].join(" ")
- };
- brokerConfig = {
- vsCode: {
- credentialName: "Visual Studio Code Credential",
- packageName: "@azure/identity-vscode",
- pluginVar: "vsCodePlugin",
- get brokerInfo() {
- return vsCodeBrokerInfo;
- }
- },
- native: {
- credentialName: "Broker for WAM",
- packageName: "@azure/identity-broker",
- pluginVar: "nativeBrokerPlugin",
- get brokerInfo() {
- return nativeBrokerInfo;
- }
- }
- };
- msalPlugins = {
- generatePluginConfiguration
- };
-});
-
-// node_modules/@azure/identity/dist/esm/plugins/consumer.js
-function useIdentityPlugin(plugin) {
- plugin(pluginContext);
-}
-var pluginContext;
-var init_consumer = __esm(() => {
- init_msalPlugins();
- pluginContext = {
- cachePluginControl: msalNodeFlowCacheControl,
- nativeBrokerPluginControl: msalNodeFlowNativeBrokerControl,
- vsCodeCredentialControl: msalNodeFlowVSCodeCredentialControl
- };
-});
-
-// node_modules/@azure/identity/dist/esm/errors.js
-function isErrorResponse(errorResponse) {
- return errorResponse && typeof errorResponse.error === "string" && typeof errorResponse.error_description === "string";
-}
-function convertOAuthErrorResponseToErrorResponse(errorBody) {
- return {
- error: errorBody.error,
- errorDescription: errorBody.error_description,
- correlationId: errorBody.correlation_id,
- errorCodes: errorBody.error_codes,
- timestamp: errorBody.timestamp,
- traceId: errorBody.trace_id
- };
-}
-var CredentialUnavailableErrorName = "CredentialUnavailableError", CredentialUnavailableError, AuthenticationErrorName = "AuthenticationError", AuthenticationError4, AggregateAuthenticationErrorName = "AggregateAuthenticationError", AggregateAuthenticationError, AuthenticationRequiredError;
-var init_errors7 = __esm(() => {
- CredentialUnavailableError = class CredentialUnavailableError extends Error {
- constructor(message, options2) {
- super(message, options2);
- this.name = CredentialUnavailableErrorName;
- }
- };
- AuthenticationError4 = class AuthenticationError4 extends Error {
- statusCode;
- errorResponse;
- constructor(statusCode, errorBody, options2) {
- let errorResponse = {
- error: "unknown",
- errorDescription: "An unknown error occurred and no additional details are available."
- };
- if (isErrorResponse(errorBody)) {
- errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody);
- } else if (typeof errorBody === "string") {
- try {
- const oauthErrorResponse = JSON.parse(errorBody);
- errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse);
- } catch (e4) {
- if (statusCode === 400) {
- errorResponse = {
- error: "invalid_request",
- errorDescription: `The service indicated that the request was invalid.
-
-${errorBody}`
- };
- } else {
- errorResponse = {
- error: "unknown_error",
- errorDescription: `An unknown error has occurred. Response body:
-
-${errorBody}`
- };
- }
- }
- } else {
- errorResponse = {
- error: "unknown_error",
- errorDescription: "An unknown error occurred and no additional details are available."
- };
- }
- super(`${errorResponse.error} Status code: ${statusCode}
-More details:
-${errorResponse.errorDescription},`, options2);
- this.statusCode = statusCode;
- this.errorResponse = errorResponse;
- this.name = AuthenticationErrorName;
- }
- };
- AggregateAuthenticationError = class AggregateAuthenticationError extends Error {
- errors;
- constructor(errors6, errorMessage2) {
- const errorDetail = errors6.join(`
-`);
- super(`${errorMessage2}
-${errorDetail}`);
- this.errors = errors6;
- this.name = AggregateAuthenticationErrorName;
- }
- };
- AuthenticationRequiredError = class AuthenticationRequiredError extends Error {
- scopes;
- getTokenOptions;
- constructor(options2) {
- super(options2.message, options2.cause ? { cause: options2.cause } : undefined);
- this.scopes = options2.scopes;
- this.getTokenOptions = options2.getTokenOptions;
- this.name = "AuthenticationRequiredError";
- }
- };
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js
-import { EOL } from "os";
-import util9 from "util";
-import process12 from "process";
-function log2(message, ...args) {
- process12.stderr.write(`${util9.format(message, ...args)}${EOL}`);
-}
-var init_log7 = () => {};
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js
-function enable(namespaces) {
- enabledString = namespaces;
- enabledNamespaces = [];
- skippedNamespaces = [];
- const namespaceList = namespaces.split(",").map((ns) => ns.trim());
- for (const ns of namespaceList) {
- if (ns.startsWith("-")) {
- skippedNamespaces.push(ns.substring(1));
- } else {
- enabledNamespaces.push(ns);
- }
- }
- for (const instance of debuggers) {
- instance.enabled = enabled(instance.namespace);
- }
-}
-function enabled(namespace) {
- if (namespace.endsWith("*")) {
- return true;
- }
- for (const skipped of skippedNamespaces) {
- if (namespaceMatches(namespace, skipped)) {
- return false;
- }
- }
- for (const enabledNamespace of enabledNamespaces) {
- if (namespaceMatches(namespace, enabledNamespace)) {
- return true;
- }
- }
- return false;
-}
-function namespaceMatches(namespace, patternToMatch) {
- if (patternToMatch.indexOf("*") === -1) {
- return namespace === patternToMatch;
- }
- let pattern = patternToMatch;
- if (patternToMatch.indexOf("**") !== -1) {
- const patternParts = [];
- let lastCharacter = "";
- for (const character of patternToMatch) {
- if (character === "*" && lastCharacter === "*") {
- continue;
- } else {
- lastCharacter = character;
- patternParts.push(character);
- }
- }
- pattern = patternParts.join("");
- }
- let namespaceIndex = 0;
- let patternIndex = 0;
- const patternLength = pattern.length;
- const namespaceLength = namespace.length;
- let lastWildcard = -1;
- let lastWildcardNamespace = -1;
- while (namespaceIndex < namespaceLength && patternIndex < patternLength) {
- if (pattern[patternIndex] === "*") {
- lastWildcard = patternIndex;
- patternIndex++;
- if (patternIndex === patternLength) {
- return true;
- }
- while (namespace[namespaceIndex] !== pattern[patternIndex]) {
- namespaceIndex++;
- if (namespaceIndex === namespaceLength) {
- return false;
- }
- }
- lastWildcardNamespace = namespaceIndex;
- namespaceIndex++;
- patternIndex++;
- continue;
- } else if (pattern[patternIndex] === namespace[namespaceIndex]) {
- patternIndex++;
- namespaceIndex++;
- } else if (lastWildcard >= 0) {
- patternIndex = lastWildcard + 1;
- namespaceIndex = lastWildcardNamespace + 1;
- if (namespaceIndex === namespaceLength) {
- return false;
- }
- while (namespace[namespaceIndex] !== pattern[patternIndex]) {
- namespaceIndex++;
- if (namespaceIndex === namespaceLength) {
- return false;
- }
- }
- lastWildcardNamespace = namespaceIndex;
- namespaceIndex++;
- patternIndex++;
- continue;
- } else {
- return false;
- }
- }
- const namespaceDone = namespaceIndex === namespace.length;
- const patternDone = patternIndex === pattern.length;
- const trailingWildCard = patternIndex === pattern.length - 1 && pattern[patternIndex] === "*";
- return namespaceDone && (patternDone || trailingWildCard);
-}
-function disable() {
- const result = enabledString || "";
- enable("");
- return result;
-}
-function createDebugger(namespace) {
- const newDebugger = Object.assign(debug2, {
- enabled: enabled(namespace),
- destroy,
- log: debugObj.log,
- namespace,
- extend: extend3
- });
- function debug2(...args) {
- if (!newDebugger.enabled) {
- return;
- }
- if (args.length > 0) {
- args[0] = `${namespace} ${args[0]}`;
- }
- newDebugger.log(...args);
- }
- debuggers.push(newDebugger);
- return newDebugger;
-}
-function destroy() {
- const index2 = debuggers.indexOf(this);
- if (index2 >= 0) {
- debuggers.splice(index2, 1);
- return true;
- }
- return false;
-}
-function extend3(namespace) {
- const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
- newDebugger.log = this.log;
- return newDebugger;
-}
-var debugEnvVariable, enabledString, enabledNamespaces, skippedNamespaces, debuggers, debugObj, debug_default;
-var init_debug2 = __esm(() => {
- init_log7();
- debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || undefined;
- enabledNamespaces = [];
- skippedNamespaces = [];
- debuggers = [];
- if (debugEnvVariable) {
- enable(debugEnvVariable);
- }
- debugObj = Object.assign((namespace) => {
- return createDebugger(namespace);
- }, {
- enable,
- enabled,
- disable,
- log: log2
- });
- debug_default = debugObj;
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js
-function patchLogMethod(parent, child) {
- child.log = (...args) => {
- parent.log(...args);
- };
-}
-function isTypeSpecRuntimeLogLevel(level) {
- return TYPESPEC_RUNTIME_LOG_LEVELS.includes(level);
-}
-function createLoggerContext(options2) {
- const registeredLoggers = new Set;
- const logLevelFromEnv = typeof process !== "undefined" && process.env && process.env[options2.logLevelEnvVarName] || undefined;
- let logLevel;
- const clientLogger = debug_default(options2.namespace);
- clientLogger.log = (...args) => {
- debug_default.log(...args);
- };
- function contextSetLogLevel(level) {
- if (level && !isTypeSpecRuntimeLogLevel(level)) {
- throw new Error(`Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`);
- }
- logLevel = level;
- const enabledNamespaces2 = [];
- for (const logger8 of registeredLoggers) {
- if (shouldEnable(logger8)) {
- enabledNamespaces2.push(logger8.namespace);
- }
- }
- debug_default.enable(enabledNamespaces2.join(","));
- }
- if (logLevelFromEnv) {
- if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) {
- contextSetLogLevel(logLevelFromEnv);
- } else {
- console.error(`${options2.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`);
- }
- }
- function shouldEnable(logger8) {
- return Boolean(logLevel && levelMap[logger8.level] <= levelMap[logLevel]);
- }
- function createLogger(parent, level) {
- const logger8 = Object.assign(parent.extend(level), {
- level
- });
- patchLogMethod(parent, logger8);
- if (shouldEnable(logger8)) {
- const enabledNamespaces2 = debug_default.disable();
- debug_default.enable(enabledNamespaces2 + "," + logger8.namespace);
- }
- registeredLoggers.add(logger8);
- return logger8;
- }
- function contextGetLogLevel() {
- return logLevel;
- }
- function contextCreateClientLogger(namespace) {
- const clientRootLogger = clientLogger.extend(namespace);
- patchLogMethod(clientLogger, clientRootLogger);
- return {
- error: createLogger(clientRootLogger, "error"),
- warning: createLogger(clientRootLogger, "warning"),
- info: createLogger(clientRootLogger, "info"),
- verbose: createLogger(clientRootLogger, "verbose")
- };
- }
- return {
- setLogLevel: contextSetLogLevel,
- getLogLevel: contextGetLogLevel,
- createClientLogger: contextCreateClientLogger,
- logger: clientLogger
- };
-}
-function createClientLogger(namespace) {
- return context.createClientLogger(namespace);
-}
-var TYPESPEC_RUNTIME_LOG_LEVELS, levelMap, context, TypeSpecRuntimeLogger;
-var init_logger7 = __esm(() => {
- init_debug2();
- TYPESPEC_RUNTIME_LOG_LEVELS = ["verbose", "info", "warning", "error"];
- levelMap = {
- verbose: 400,
- info: 300,
- warning: 200,
- error: 100
- };
- context = createLoggerContext({
- logLevelEnvVarName: "TYPESPEC_RUNTIME_LOG_LEVEL",
- namespace: "typeSpecRuntime"
- });
- TypeSpecRuntimeLogger = context.logger;
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/logger/internal.js
-var init_internal = __esm(() => {
- init_logger7();
-});
-
-// node_modules/@azure/logger/dist/esm/index.js
-function getLogLevel() {
- return context2.getLogLevel();
-}
-function createClientLogger2(namespace) {
- return context2.createClientLogger(namespace);
-}
-var context2, AzureLogger;
-var init_esm2 = __esm(() => {
- init_internal();
- context2 = createLoggerContext({
- logLevelEnvVarName: "AZURE_LOG_LEVEL",
- namespace: "azure"
- });
- AzureLogger = context2.logger;
-});
-
-// node_modules/@azure/identity/dist/esm/util/logging.js
-function processEnvVars(supportedEnvVars) {
- return supportedEnvVars.reduce((acc, envVariable) => {
- if (process.env[envVariable]) {
- acc.assigned.push(envVariable);
- } else {
- acc.missing.push(envVariable);
- }
- return acc;
- }, { missing: [], assigned: [] });
-}
-function formatSuccess(scope) {
- return `SUCCESS. Scopes: ${Array.isArray(scope) ? scope.join(", ") : scope}.`;
-}
-function formatError2(scope, error44) {
- let message = "ERROR.";
- if (scope?.length) {
- message += ` Scopes: ${Array.isArray(scope) ? scope.join(", ") : scope}.`;
- }
- return `${message} Error message: ${typeof error44 === "string" ? error44 : error44.message}.`;
-}
-function credentialLoggerInstance(title, parent, log3 = logger8) {
- const fullTitle = parent ? `${parent.fullTitle} ${title}` : title;
- function info(message) {
- log3.info(`${fullTitle} =>`, message);
- }
- function warning(message) {
- log3.warning(`${fullTitle} =>`, message);
- }
- function verbose(message) {
- log3.verbose(`${fullTitle} =>`, message);
- }
- function error44(message) {
- log3.error(`${fullTitle} =>`, message);
- }
- return {
- title,
- fullTitle,
- info,
- warning,
- verbose,
- error: error44
- };
-}
-function credentialLogger(title, log3 = logger8) {
- const credLogger = credentialLoggerInstance(title, undefined, log3);
- return {
- ...credLogger,
- parent: log3,
- getToken: credentialLoggerInstance("=> getToken()", credLogger, log3)
- };
-}
-var logger8;
-var init_logging = __esm(() => {
- init_esm2();
- logger8 = createClientLogger2("identity");
-});
-
-// node_modules/@azure/core-tracing/dist/esm/tracingContext.js
-function createTracingContext(options2 = {}) {
- let context3 = new TracingContextImpl(options2.parentContext);
- if (options2.span) {
- context3 = context3.setValue(knownContextKeys.span, options2.span);
- }
- if (options2.namespace) {
- context3 = context3.setValue(knownContextKeys.namespace, options2.namespace);
- }
- return context3;
-}
-
-class TracingContextImpl {
- _contextMap;
- constructor(initialContext) {
- this._contextMap = initialContext instanceof TracingContextImpl ? new Map(initialContext._contextMap) : new Map;
- }
- 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;
- }
-}
-var knownContextKeys;
-var init_tracingContext = __esm(() => {
- knownContextKeys = {
- span: Symbol.for("@azure/core-tracing span"),
- namespace: Symbol.for("@azure/core-tracing namespace")
- };
-});
-
-// node_modules/@azure/core-tracing/dist/commonjs/state.js
-var require_state2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.state = undefined;
- exports.state = {
- instrumenterImplementation: undefined
- };
-});
-
-// node_modules/@azure/core-tracing/dist/esm/state.js
-var import_state15, state;
-var init_state2 = __esm(() => {
- import_state15 = __toESM(require_state2(), 1);
- state = import_state15.state;
-});
-
-// node_modules/@azure/core-tracing/dist/esm/instrumenter.js
-function createDefaultTracingSpan() {
- return {
- end: () => {},
- isRecording: () => false,
- recordException: () => {},
- setAttribute: () => {},
- setStatus: () => {},
- addEvent: () => {}
- };
-}
-function createDefaultInstrumenter() {
- return {
- createRequestHeaders: () => {
- return {};
- },
- parseTraceparentHeader: () => {
- return;
- },
- startSpan: (_name, spanOptions) => {
- return {
- span: createDefaultTracingSpan(),
- tracingContext: createTracingContext({ parentContext: spanOptions.tracingContext })
- };
- },
- withContext(_context, callback, ...callbackArgs) {
- return callback(...callbackArgs);
- }
- };
-}
-function getInstrumenter() {
- if (!state.instrumenterImplementation) {
- state.instrumenterImplementation = createDefaultInstrumenter();
- }
- return state.instrumenterImplementation;
-}
-var init_instrumenter = __esm(() => {
- init_tracingContext();
- init_state2();
-});
-
-// node_modules/@azure/core-tracing/dist/esm/tracingClient.js
-function createTracingClient(options2) {
- const { namespace, packageName, packageVersion } = options2;
- function startSpan(name, operationOptions, spanOptions) {
- const startSpanResult = getInstrumenter().startSpan(name, {
- ...spanOptions,
- packageName,
- packageVersion,
- tracingContext: operationOptions?.tracingOptions?.tracingContext
- });
- let tracingContext = startSpanResult.tracingContext;
- const span = startSpanResult.span;
- if (!tracingContext.getValue(knownContextKeys.namespace)) {
- tracingContext = tracingContext.setValue(knownContextKeys.namespace, namespace);
- }
- span.setAttribute("az.namespace", tracingContext.getValue(knownContextKeys.namespace));
- const updatedOptions = Object.assign({}, operationOptions, {
- tracingOptions: { ...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(context3, callback, ...callbackArgs) {
- return getInstrumenter().withContext(context3, callback, ...callbackArgs);
- }
- function parseTraceparentHeader(traceparentHeader) {
- return getInstrumenter().parseTraceparentHeader(traceparentHeader);
- }
- function createRequestHeaders(tracingContext) {
- return getInstrumenter().createRequestHeaders(tracingContext);
- }
- return {
- startSpan,
- withSpan,
- withContext,
- parseTraceparentHeader,
- createRequestHeaders
- };
-}
-var init_tracingClient = __esm(() => {
- init_instrumenter();
- init_tracingContext();
-});
-
-// node_modules/@azure/core-tracing/dist/esm/index.js
-var init_esm3 = __esm(() => {
- init_tracingClient();
-});
-
-// node_modules/@azure/identity/dist/esm/util/tracing.js
-var tracingClient;
-var init_tracing = __esm(() => {
- init_constants9();
- init_esm3();
- tracingClient = createTracingClient({
- namespace: "Microsoft.AAD",
- packageName: "@azure/identity",
- packageVersion: SDK_VERSION2
- });
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/chainedTokenCredential.js
-class ChainedTokenCredential {
- _sources = [];
- constructor(...sources) {
- this._sources = sources;
- }
- async getToken(scopes, options2 = {}) {
- const { token } = await this.getTokenInternal(scopes, options2);
- return token;
- }
- async getTokenInternal(scopes, options2 = {}) {
- let token = null;
- let successfulCredential;
- const errors6 = [];
- return tracingClient.withSpan("ChainedTokenCredential.getToken", options2, async (updatedOptions) => {
- for (let i5 = 0;i5 < this._sources.length && token === null; i5++) {
- try {
- token = await this._sources[i5].getToken(scopes, updatedOptions);
- successfulCredential = this._sources[i5];
- } catch (err) {
- if (err.name === "CredentialUnavailableError" || err.name === "AuthenticationRequiredError") {
- errors6.push(err);
- } else {
- logger9.getToken.info(formatError2(scopes, err));
- throw err;
- }
- }
- }
- if (!token && errors6.length > 0) {
- const err = new AggregateAuthenticationError(errors6, "ChainedTokenCredential authentication failed.");
- logger9.getToken.info(formatError2(scopes, err));
- throw err;
- }
- logger9.getToken.info(`Result for ${successfulCredential.constructor.name}: ${formatSuccess(scopes)}`);
- if (token === null) {
- throw new CredentialUnavailableError("Failed to retrieve a valid token");
- }
- return { token, successfulCredential };
- });
- }
-}
-var logger9;
-var init_chainedTokenCredential = __esm(() => {
- init_errors7();
- init_logging();
- init_tracing();
- logger9 = credentialLogger("ChainedTokenCredential");
-});
-
-// node_modules/@azure/msal-node/dist/cache/serializer/Serializer.mjs
-class Serializer {
- static serializeJSONBlob(data) {
- return JSON.stringify(data);
- }
- static serializeAccounts(accCache) {
- const accounts = {};
- Object.keys(accCache).map(function(key) {
- const accountEntity = accCache[key];
- accounts[key] = {
- home_account_id: accountEntity.homeAccountId,
- environment: accountEntity.environment,
- realm: accountEntity.realm,
- local_account_id: accountEntity.localAccountId,
- username: accountEntity.username,
- authority_type: accountEntity.authorityType,
- name: accountEntity.name,
- client_info: accountEntity.clientInfo,
- last_modification_time: accountEntity.lastModificationTime,
- last_modification_app: accountEntity.lastModificationApp,
- tenantProfiles: accountEntity.tenantProfiles?.map((tenantProfile) => {
- return JSON.stringify(tenantProfile);
- })
- };
- });
- return accounts;
- }
- static serializeIdTokens(idTCache) {
- const idTokens = {};
- Object.keys(idTCache).map(function(key) {
- const idTEntity = idTCache[key];
- idTokens[key] = {
- home_account_id: idTEntity.homeAccountId,
- environment: idTEntity.environment,
- credential_type: idTEntity.credentialType,
- client_id: idTEntity.clientId,
- secret: idTEntity.secret,
- realm: idTEntity.realm
- };
- });
- return idTokens;
- }
- static serializeAccessTokens(atCache) {
- const accessTokens = {};
- Object.keys(atCache).map(function(key) {
- const atEntity = atCache[key];
- accessTokens[key] = {
- home_account_id: atEntity.homeAccountId,
- environment: atEntity.environment,
- credential_type: atEntity.credentialType,
- client_id: atEntity.clientId,
- secret: atEntity.secret,
- realm: atEntity.realm,
- target: atEntity.target,
- cached_at: atEntity.cachedAt,
- expires_on: atEntity.expiresOn,
- extended_expires_on: atEntity.extendedExpiresOn,
- refresh_on: atEntity.refreshOn,
- key_id: atEntity.keyId,
- token_type: atEntity.tokenType,
- userAssertionHash: atEntity.userAssertionHash,
- resource: atEntity.resource
- };
- });
- return accessTokens;
- }
- static serializeRefreshTokens(rtCache) {
- const refreshTokens = {};
- Object.keys(rtCache).map(function(key) {
- const rtEntity = rtCache[key];
- refreshTokens[key] = {
- home_account_id: rtEntity.homeAccountId,
- environment: rtEntity.environment,
- credential_type: rtEntity.credentialType,
- client_id: rtEntity.clientId,
- secret: rtEntity.secret,
- family_id: rtEntity.familyId,
- target: rtEntity.target,
- realm: rtEntity.realm
- };
- });
- return refreshTokens;
- }
- static serializeAppMetadata(amdtCache) {
- const appMetadata = {};
- Object.keys(amdtCache).map(function(key) {
- const amdtEntity = amdtCache[key];
- appMetadata[key] = {
- client_id: amdtEntity.clientId,
- environment: amdtEntity.environment,
- family_id: amdtEntity.familyId
- };
- });
- return appMetadata;
- }
- static serializeAllCache(inMemCache) {
- return {
- Account: this.serializeAccounts(inMemCache.accounts),
- IdToken: this.serializeIdTokens(inMemCache.idTokens),
- AccessToken: this.serializeAccessTokens(inMemCache.accessTokens),
- RefreshToken: this.serializeRefreshTokens(inMemCache.refreshTokens),
- AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata)
- };
- }
-}
-var init_Serializer = __esm(() => {
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/utils/Constants.mjs
-var exports_Constants = {};
-__export(exports_Constants, {
- X_MS_LIB_CAPABILITY_VALUE: () => X_MS_LIB_CAPABILITY_VALUE,
- URL_FORM_CONTENT_TYPE: () => URL_FORM_CONTENT_TYPE,
- THROTTLING_PREFIX: () => THROTTLING_PREFIX,
- THE_FAMILY_ID: () => THE_FAMILY_ID,
- SKU: () => SKU,
- SHR_NONCE_VALIDITY: () => SHR_NONCE_VALIDITY,
- SERVER_TELEM_VALUE_SEPARATOR: () => SERVER_TELEM_VALUE_SEPARATOR,
- SERVER_TELEM_UNKNOWN_ERROR: () => SERVER_TELEM_UNKNOWN_ERROR,
- SERVER_TELEM_SCHEMA_VERSION: () => SERVER_TELEM_SCHEMA_VERSION,
- SERVER_TELEM_OVERFLOW_TRUE: () => SERVER_TELEM_OVERFLOW_TRUE,
- SERVER_TELEM_OVERFLOW_FALSE: () => SERVER_TELEM_OVERFLOW_FALSE,
- SERVER_TELEM_MAX_LAST_HEADER_BYTES: () => SERVER_TELEM_MAX_LAST_HEADER_BYTES,
- SERVER_TELEM_MAX_CUR_HEADER_BYTES: () => SERVER_TELEM_MAX_CUR_HEADER_BYTES,
- SERVER_TELEM_MAX_CACHED_ERRORS: () => SERVER_TELEM_MAX_CACHED_ERRORS,
- SERVER_TELEM_CATEGORY_SEPARATOR: () => SERVER_TELEM_CATEGORY_SEPARATOR,
- SERVER_TELEM_CACHE_KEY: () => SERVER_TELEM_CACHE_KEY,
- S256_CODE_CHALLENGE_METHOD: () => S256_CODE_CHALLENGE_METHOD,
- ResponseMode: () => ResponseMode,
- RegionDiscoverySources: () => RegionDiscoverySources,
- RegionDiscoveryOutcomes: () => RegionDiscoveryOutcomes,
- RESOURCE_DELIM: () => RESOURCE_DELIM,
- REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX: () => REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX,
- PromptValue: () => PromptValue,
- PersistentCacheKeys: () => PersistentCacheKeys,
- PasswordGrantConstants: () => PasswordGrantConstants,
- PROFILE_SCOPE: () => PROFILE_SCOPE,
- OPENID_SCOPE: () => OPENID_SCOPE,
- ONE_DAY_IN_MS: () => ONE_DAY_IN_MS,
- OIDC_SCOPES: () => OIDC_SCOPES,
- OIDC_DEFAULT_SCOPES: () => OIDC_DEFAULT_SCOPES,
- OFFLINE_ACCESS_SCOPE: () => OFFLINE_ACCESS_SCOPE,
- OAuthResponseType: () => OAuthResponseType,
- NOT_AVAILABLE: () => NOT_AVAILABLE,
- NOT_APPLICABLE: () => NOT_APPLICABLE,
- KNOWN_PUBLIC_CLOUDS: () => KNOWN_PUBLIC_CLOUDS,
- JsonWebTokenTypes: () => JsonWebTokenTypes,
- INVALID_INSTANCE: () => INVALID_INSTANCE,
- INVALID_GRANT_ERROR: () => INVALID_GRANT_ERROR,
- IMDS_VERSION: () => IMDS_VERSION,
- IMDS_TIMEOUT: () => IMDS_TIMEOUT,
- IMDS_ENDPOINT: () => IMDS_ENDPOINT,
- HttpMethod: () => HttpMethod,
- HeaderNames: () => HeaderNames,
- HTTP_UNAUTHORIZED: () => HTTP_UNAUTHORIZED,
- HTTP_TOO_MANY_REQUESTS: () => HTTP_TOO_MANY_REQUESTS,
- HTTP_SUCCESS_RANGE_START: () => HTTP_SUCCESS_RANGE_START,
- HTTP_SUCCESS_RANGE_END: () => HTTP_SUCCESS_RANGE_END,
- HTTP_SUCCESS: () => HTTP_SUCCESS,
- HTTP_SERVICE_UNAVAILABLE: () => HTTP_SERVICE_UNAVAILABLE,
- HTTP_SERVER_ERROR_RANGE_START: () => HTTP_SERVER_ERROR_RANGE_START,
- HTTP_SERVER_ERROR_RANGE_END: () => HTTP_SERVER_ERROR_RANGE_END,
- HTTP_SERVER_ERROR: () => HTTP_SERVER_ERROR,
- HTTP_REQUEST_TIMEOUT: () => HTTP_REQUEST_TIMEOUT,
- HTTP_REDIRECT: () => HTTP_REDIRECT,
- HTTP_NOT_FOUND: () => HTTP_NOT_FOUND,
- HTTP_MULTI_SIDED_ERROR: () => HTTP_MULTI_SIDED_ERROR,
- HTTP_GONE: () => HTTP_GONE,
- HTTP_GATEWAY_TIMEOUT: () => HTTP_GATEWAY_TIMEOUT,
- HTTP_CLIENT_ERROR_RANGE_START: () => HTTP_CLIENT_ERROR_RANGE_START,
- HTTP_CLIENT_ERROR_RANGE_END: () => HTTP_CLIENT_ERROR_RANGE_END,
- HTTP_CLIENT_ERROR: () => HTTP_CLIENT_ERROR,
- HTTP_BAD_REQUEST: () => HTTP_BAD_REQUEST,
- GrantType: () => GrantType,
- FORWARD_SLASH: () => FORWARD_SLASH,
- EncodingTypes: () => EncodingTypes,
- EMAIL_SCOPE: () => EMAIL_SCOPE,
- DSTS: () => DSTS,
- DEFAULT_TOKEN_RENEWAL_OFFSET_SEC: () => DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,
- DEFAULT_THROTTLE_TIME_SECONDS: () => DEFAULT_THROTTLE_TIME_SECONDS,
- DEFAULT_MAX_THROTTLE_TIME_SECONDS: () => DEFAULT_MAX_THROTTLE_TIME_SECONDS,
- DEFAULT_COMMON_TENANT: () => DEFAULT_COMMON_TENANT,
- DEFAULT_AUTHORITY_HOST: () => DEFAULT_AUTHORITY_HOST,
- DEFAULT_AUTHORITY: () => DEFAULT_AUTHORITY,
- CredentialType: () => CredentialType,
- CodeChallengeMethodValues: () => CodeChallengeMethodValues,
- ClaimsRequestKeys: () => ClaimsRequestKeys,
- CacheType: () => CacheType,
- CacheOutcome: () => CacheOutcome,
- CONSUMER_UTID: () => CONSUMER_UTID,
- CODE_GRANT_TYPE: () => CODE_GRANT_TYPE,
- CLIENT_MISMATCH_ERROR: () => CLIENT_MISMATCH_ERROR,
- CLIENT_INFO_SEPARATOR: () => CLIENT_INFO_SEPARATOR,
- CLIENT_INFO: () => CLIENT_INFO,
- CIAM_AUTH_URL: () => CIAM_AUTH_URL,
- CACHE_KEY_SEPARATOR: () => CACHE_KEY_SEPARATOR,
- CACHE_ACCOUNT_TYPE_MSSTS: () => CACHE_ACCOUNT_TYPE_MSSTS,
- CACHE_ACCOUNT_TYPE_MSAV1: () => CACHE_ACCOUNT_TYPE_MSAV1,
- CACHE_ACCOUNT_TYPE_GENERIC: () => CACHE_ACCOUNT_TYPE_GENERIC,
- CACHE_ACCOUNT_TYPE_ADFS: () => CACHE_ACCOUNT_TYPE_ADFS,
- AuthorityMetadataSource: () => AuthorityMetadataSource,
- AuthenticationScheme: () => AuthenticationScheme,
- AZURE_REGION_AUTO_DISCOVER_FLAG: () => AZURE_REGION_AUTO_DISCOVER_FLAG,
- AUTHORIZATION_PENDING: () => AUTHORIZATION_PENDING,
- AUTHORITY_METADATA_REFRESH_TIME_SECONDS: () => AUTHORITY_METADATA_REFRESH_TIME_SECONDS,
- AUTHORITY_METADATA_CACHE_KEY: () => AUTHORITY_METADATA_CACHE_KEY,
- APP_METADATA: () => APP_METADATA,
- ADFS: () => ADFS,
- AAD_TENANT_DOMAIN_SUFFIX: () => AAD_TENANT_DOMAIN_SUFFIX,
- AAD_INSTANCE_DISCOVERY_ENDPT: () => AAD_INSTANCE_DISCOVERY_ENDPT,
- AADAuthority: () => AADAuthority
-});
-var SKU = "msal.js.common", DEFAULT_AUTHORITY = "https://login.microsoftonline.com/common/", DEFAULT_AUTHORITY_HOST = "login.microsoftonline.com", DEFAULT_COMMON_TENANT = "common", ADFS = "adfs", DSTS = "dstsv2", AAD_INSTANCE_DISCOVERY_ENDPT, CIAM_AUTH_URL = ".ciamlogin.com", AAD_TENANT_DOMAIN_SUFFIX = ".onmicrosoft.com", RESOURCE_DELIM = "|", CONSUMER_UTID = "9188040d-6c67-4c5b-b112-36a304b66dad", OPENID_SCOPE = "openid", PROFILE_SCOPE = "profile", OFFLINE_ACCESS_SCOPE = "offline_access", EMAIL_SCOPE = "email", CODE_GRANT_TYPE = "authorization_code", S256_CODE_CHALLENGE_METHOD = "S256", URL_FORM_CONTENT_TYPE = "application/x-www-form-urlencoded;charset=utf-8", AUTHORIZATION_PENDING = "authorization_pending", NOT_APPLICABLE = "N/A", NOT_AVAILABLE = "Not Available", FORWARD_SLASH = "/", IMDS_ENDPOINT = "http://169.254.169.254/metadata/instance/compute/location", IMDS_VERSION = "2020-06-01", IMDS_TIMEOUT = 2000, AZURE_REGION_AUTO_DISCOVER_FLAG = "TryAutoDetect", REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX = "login.microsoft.com", KNOWN_PUBLIC_CLOUDS, SHR_NONCE_VALIDITY = 240, INVALID_INSTANCE = "invalid_instance", HTTP_SUCCESS = 200, HTTP_SUCCESS_RANGE_START = 200, HTTP_SUCCESS_RANGE_END = 299, HTTP_REDIRECT = 302, HTTP_CLIENT_ERROR = 400, HTTP_CLIENT_ERROR_RANGE_START = 400, HTTP_BAD_REQUEST = 400, HTTP_UNAUTHORIZED = 401, HTTP_NOT_FOUND = 404, HTTP_REQUEST_TIMEOUT = 408, HTTP_GONE = 410, HTTP_TOO_MANY_REQUESTS = 429, HTTP_CLIENT_ERROR_RANGE_END = 499, HTTP_SERVER_ERROR = 500, HTTP_SERVER_ERROR_RANGE_START = 500, HTTP_SERVICE_UNAVAILABLE = 503, HTTP_GATEWAY_TIMEOUT = 504, HTTP_SERVER_ERROR_RANGE_END = 599, HTTP_MULTI_SIDED_ERROR = 600, HttpMethod, OIDC_DEFAULT_SCOPES, OIDC_SCOPES, HeaderNames, PersistentCacheKeys, AADAuthority, ClaimsRequestKeys, PromptValue, CodeChallengeMethodValues, OAuthResponseType, ResponseMode, GrantType, CACHE_ACCOUNT_TYPE_MSSTS = "MSSTS", CACHE_ACCOUNT_TYPE_ADFS = "ADFS", CACHE_ACCOUNT_TYPE_MSAV1 = "MSA", CACHE_ACCOUNT_TYPE_GENERIC = "Generic", CACHE_KEY_SEPARATOR = "-", CLIENT_INFO_SEPARATOR = ".", CredentialType, CacheType, APP_METADATA = "appmetadata", CLIENT_INFO = "client_info", THE_FAMILY_ID = "1", AUTHORITY_METADATA_CACHE_KEY = "authority-metadata", AUTHORITY_METADATA_REFRESH_TIME_SECONDS, AuthorityMetadataSource, SERVER_TELEM_SCHEMA_VERSION = 5, SERVER_TELEM_MAX_CUR_HEADER_BYTES = 80, SERVER_TELEM_MAX_LAST_HEADER_BYTES = 330, SERVER_TELEM_MAX_CACHED_ERRORS = 50, SERVER_TELEM_CACHE_KEY = "server-telemetry", SERVER_TELEM_CATEGORY_SEPARATOR = "|", SERVER_TELEM_VALUE_SEPARATOR = ",", SERVER_TELEM_OVERFLOW_TRUE = "1", SERVER_TELEM_OVERFLOW_FALSE = "0", SERVER_TELEM_UNKNOWN_ERROR = "unknown_error", AuthenticationScheme, DEFAULT_THROTTLE_TIME_SECONDS = 60, DEFAULT_MAX_THROTTLE_TIME_SECONDS = 3600, THROTTLING_PREFIX = "throttling", X_MS_LIB_CAPABILITY_VALUE = "retry-after, h429", INVALID_GRANT_ERROR = "invalid_grant", CLIENT_MISMATCH_ERROR = "client_mismatch", PasswordGrantConstants, RegionDiscoverySources, RegionDiscoveryOutcomes, CacheOutcome, JsonWebTokenTypes, ONE_DAY_IN_MS = 86400000, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300, EncodingTypes;
-var init_Constants = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- AAD_INSTANCE_DISCOVERY_ENDPT = `${DEFAULT_AUTHORITY}discovery/instance?api-version=1.1&authorization_endpoint=`;
- KNOWN_PUBLIC_CLOUDS = [
- "login.microsoftonline.com",
- "login.windows.net",
- "login.microsoft.com",
- "sts.windows.net"
- ];
- HttpMethod = {
- GET: "GET",
- POST: "POST"
- };
- OIDC_DEFAULT_SCOPES = [
- OPENID_SCOPE,
- PROFILE_SCOPE,
- OFFLINE_ACCESS_SCOPE
- ];
- OIDC_SCOPES = [...OIDC_DEFAULT_SCOPES, EMAIL_SCOPE];
- HeaderNames = {
- CONTENT_TYPE: "Content-Type",
- CONTENT_LENGTH: "Content-Length",
- RETRY_AFTER: "Retry-After",
- CCS_HEADER: "X-AnchorMailbox",
- WWWAuthenticate: "WWW-Authenticate",
- AuthenticationInfo: "Authentication-Info",
- X_MS_REQUEST_ID: "x-ms-request-id",
- X_MS_HTTP_VERSION: "x-ms-httpver"
- };
- PersistentCacheKeys = {
- ACTIVE_ACCOUNT_FILTERS: "active-account-filters"
- };
- AADAuthority = {
- COMMON: "common",
- ORGANIZATIONS: "organizations",
- CONSUMERS: "consumers"
- };
- ClaimsRequestKeys = {
- ACCESS_TOKEN: "access_token",
- XMS_CC: "xms_cc"
- };
- PromptValue = {
- LOGIN: "login",
- SELECT_ACCOUNT: "select_account",
- CONSENT: "consent",
- NONE: "none",
- CREATE: "create",
- NO_SESSION: "no_session"
- };
- CodeChallengeMethodValues = {
- PLAIN: "plain",
- S256: "S256"
- };
- OAuthResponseType = {
- CODE: "code",
- IDTOKEN_TOKEN: "id_token token",
- IDTOKEN_TOKEN_REFRESHTOKEN: "id_token token refresh_token"
- };
- ResponseMode = {
- QUERY: "query",
- FRAGMENT: "fragment",
- FORM_POST: "form_post"
- };
- GrantType = {
- IMPLICIT_GRANT: "implicit",
- AUTHORIZATION_CODE_GRANT: "authorization_code",
- CLIENT_CREDENTIALS_GRANT: "client_credentials",
- RESOURCE_OWNER_PASSWORD_GRANT: "password",
- REFRESH_TOKEN_GRANT: "refresh_token",
- DEVICE_CODE_GRANT: "device_code",
- JWT_BEARER: "urn:ietf:params:oauth:grant-type:jwt-bearer"
- };
- CredentialType = {
- ID_TOKEN: "IdToken",
- ACCESS_TOKEN: "AccessToken",
- ACCESS_TOKEN_WITH_AUTH_SCHEME: "AccessToken_With_AuthScheme",
- REFRESH_TOKEN: "RefreshToken"
- };
- CacheType = {
- ADFS: 1001,
- MSA: 1002,
- MSSTS: 1003,
- GENERIC: 1004,
- ACCESS_TOKEN: 2001,
- REFRESH_TOKEN: 2002,
- ID_TOKEN: 2003,
- APP_METADATA: 3001,
- UNDEFINED: 9999
- };
- AUTHORITY_METADATA_REFRESH_TIME_SECONDS = 3600 * 24;
- AuthorityMetadataSource = {
- CONFIG: "config",
- CACHE: "cache",
- NETWORK: "network",
- HARDCODED_VALUES: "hardcoded_values"
- };
- AuthenticationScheme = {
- BEARER: "Bearer",
- POP: "pop",
- SSH: "ssh-cert"
- };
- PasswordGrantConstants = {
- username: "username",
- password: "password"
- };
- RegionDiscoverySources = {
- FAILED_AUTO_DETECTION: "1",
- INTERNAL_CACHE: "2",
- ENVIRONMENT_VARIABLE: "3",
- IMDS: "4"
- };
- RegionDiscoveryOutcomes = {
- CONFIGURED_MATCHES_DETECTED: "1",
- CONFIGURED_NO_AUTO_DETECTION: "2",
- CONFIGURED_NOT_DETECTED: "3",
- AUTO_DETECTION_REQUESTED_SUCCESSFUL: "4",
- AUTO_DETECTION_REQUESTED_FAILED: "5"
- };
- CacheOutcome = {
- NOT_APPLICABLE: "0",
- FORCE_REFRESH_OR_CLAIMS: "1",
- NO_CACHED_ACCESS_TOKEN: "2",
- CACHED_ACCESS_TOKEN_EXPIRED: "3",
- PROACTIVELY_REFRESHED: "4"
- };
- JsonWebTokenTypes = {
- Jwt: "JWT",
- Jwk: "JWK",
- Pop: "pop"
- };
- EncodingTypes = {
- BASE64: "base64",
- HEX: "hex",
- UTF8: "utf-8"
- };
-});
-
-// node_modules/@azure/msal-common/dist/constants/AADServerParamKeys.mjs
-var exports_AADServerParamKeys = {};
-__export(exports_AADServerParamKeys, {
- X_MS_LIB_CAPABILITY: () => X_MS_LIB_CAPABILITY,
- X_CLIENT_VER: () => X_CLIENT_VER,
- X_CLIENT_SKU: () => X_CLIENT_SKU,
- X_CLIENT_OS: () => X_CLIENT_OS,
- X_CLIENT_LAST_TELEM: () => X_CLIENT_LAST_TELEM,
- X_CLIENT_EXTRA_SKU: () => X_CLIENT_EXTRA_SKU,
- X_CLIENT_CURR_TELEM: () => X_CLIENT_CURR_TELEM,
- X_CLIENT_CPU: () => X_CLIENT_CPU,
- X_APP_VER: () => X_APP_VER,
- X_APP_NAME: () => X_APP_NAME,
- TOKEN_TYPE: () => TOKEN_TYPE,
- STATE: () => STATE2,
- SID: () => SID,
- SESSION_STATE: () => SESSION_STATE,
- SCOPE: () => SCOPE,
- RETURN_SPA_CODE: () => RETURN_SPA_CODE,
- RESPONSE_TYPE: () => RESPONSE_TYPE2,
- RESPONSE_MODE: () => RESPONSE_MODE,
- RESOURCE: () => RESOURCE,
- REQ_CNF: () => REQ_CNF,
- REQUESTED_TOKEN_USE: () => REQUESTED_TOKEN_USE,
- REFRESH_TOKEN_EXPIRES_IN: () => REFRESH_TOKEN_EXPIRES_IN,
- REFRESH_TOKEN: () => REFRESH_TOKEN,
- REDIRECT_URI: () => REDIRECT_URI,
- PROMPT: () => PROMPT,
- POST_LOGOUT_URI: () => POST_LOGOUT_URI,
- ON_BEHALF_OF: () => ON_BEHALF_OF,
- OBO_ASSERTION: () => OBO_ASSERTION,
- NONCE: () => NONCE,
- NATIVE_BROKER: () => NATIVE_BROKER,
- LOGOUT_HINT: () => LOGOUT_HINT,
- LOGIN_HINT: () => LOGIN_HINT,
- INSTANCE_AWARE: () => INSTANCE_AWARE,
- ID_TOKEN_HINT: () => ID_TOKEN_HINT,
- ID_TOKEN: () => ID_TOKEN,
- GRANT_TYPE: () => GRANT_TYPE,
- FOCI: () => FOCI,
- EXPIRES_IN: () => EXPIRES_IN,
- ERROR_DESCRIPTION: () => ERROR_DESCRIPTION,
- ERROR: () => ERROR,
- EAR_JWK: () => EAR_JWK,
- EAR_JWE_CRYPTO: () => EAR_JWE_CRYPTO,
- DOMAIN_HINT: () => DOMAIN_HINT,
- DEVICE_CODE: () => DEVICE_CODE,
- CODE_VERIFIER: () => CODE_VERIFIER,
- CODE_CHALLENGE_METHOD: () => CODE_CHALLENGE_METHOD,
- CODE_CHALLENGE: () => CODE_CHALLENGE,
- CODE: () => CODE,
- CLI_DATA: () => CLI_DATA,
- CLIENT_SECRET: () => CLIENT_SECRET,
- CLIENT_REQUEST_ID: () => CLIENT_REQUEST_ID,
- CLIENT_INFO: () => CLIENT_INFO2,
- CLIENT_ID: () => CLIENT_ID,
- CLIENT_ASSERTION_TYPE: () => CLIENT_ASSERTION_TYPE,
- CLIENT_ASSERTION: () => CLIENT_ASSERTION,
- CLAIMS: () => CLAIMS,
- CCS_HEADER: () => CCS_HEADER,
- BROKER_REDIRECT_URI: () => BROKER_REDIRECT_URI,
- BROKER_CLIENT_ID: () => BROKER_CLIENT_ID,
- ACCESS_TOKEN: () => ACCESS_TOKEN
-});
-var CLIENT_ID = "client_id", REDIRECT_URI = "redirect_uri", RESPONSE_TYPE2 = "response_type", RESPONSE_MODE = "response_mode", GRANT_TYPE = "grant_type", CLAIMS = "claims", SCOPE = "scope", ERROR = "error", ERROR_DESCRIPTION = "error_description", ACCESS_TOKEN = "access_token", ID_TOKEN = "id_token", REFRESH_TOKEN = "refresh_token", EXPIRES_IN = "expires_in", REFRESH_TOKEN_EXPIRES_IN = "refresh_token_expires_in", STATE2 = "state", NONCE = "nonce", PROMPT = "prompt", SESSION_STATE = "session_state", CLIENT_INFO2 = "client_info", CODE = "code", CODE_CHALLENGE = "code_challenge", CODE_CHALLENGE_METHOD = "code_challenge_method", CODE_VERIFIER = "code_verifier", CLIENT_REQUEST_ID = "client-request-id", X_CLIENT_SKU = "x-client-SKU", X_CLIENT_VER = "x-client-VER", X_CLIENT_OS = "x-client-OS", X_CLIENT_CPU = "x-client-CPU", X_CLIENT_CURR_TELEM = "x-client-current-telemetry", X_CLIENT_LAST_TELEM = "x-client-last-telemetry", X_MS_LIB_CAPABILITY = "x-ms-lib-capability", X_APP_NAME = "x-app-name", X_APP_VER = "x-app-ver", POST_LOGOUT_URI = "post_logout_redirect_uri", ID_TOKEN_HINT = "id_token_hint", DEVICE_CODE = "device_code", CLIENT_SECRET = "client_secret", CLIENT_ASSERTION = "client_assertion", CLIENT_ASSERTION_TYPE = "client_assertion_type", TOKEN_TYPE = "token_type", REQ_CNF = "req_cnf", OBO_ASSERTION = "assertion", REQUESTED_TOKEN_USE = "requested_token_use", ON_BEHALF_OF = "on_behalf_of", FOCI = "foci", CCS_HEADER = "X-AnchorMailbox", RETURN_SPA_CODE = "return_spa_code", NATIVE_BROKER = "nativebroker", LOGOUT_HINT = "logout_hint", SID = "sid", LOGIN_HINT = "login_hint", DOMAIN_HINT = "domain_hint", X_CLIENT_EXTRA_SKU = "x-client-xtra-sku", BROKER_CLIENT_ID = "brk_client_id", BROKER_REDIRECT_URI = "brk_redirect_uri", INSTANCE_AWARE = "instance_aware", EAR_JWK = "ear_jwk", EAR_JWE_CRYPTO = "ear_jwe_crypto", RESOURCE = "resource", CLI_DATA = "clidata";
-var init_AADServerParamKeys = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/error/AuthError.mjs
-function getDefaultErrorMessage(code) {
- return `See https://aka.ms/msal.js.errors#${code} for details`;
-}
-function createAuthError(code, additionalMessage) {
- return new AuthError(code, additionalMessage || getDefaultErrorMessage(code));
-}
-var AuthError;
-var init_AuthError = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- AuthError = class AuthError extends Error {
- constructor(errorCode, errorMessage2, suberror) {
- const message = errorMessage2 || (errorCode ? getDefaultErrorMessage(errorCode) : "");
- const errorString = message ? `${errorCode}: ${message}` : errorCode;
- super(errorString);
- Object.setPrototypeOf(this, AuthError.prototype);
- this.errorCode = errorCode || "";
- this.errorMessage = message || "";
- this.subError = suberror || "";
- this.name = "AuthError";
- }
- setCorrelationId(correlationId) {
- this.correlationId = correlationId;
- }
- };
-});
-
-// node_modules/@azure/msal-common/dist/error/ClientConfigurationError.mjs
-function createClientConfigurationError(errorCode) {
- return new ClientConfigurationError(errorCode);
-}
-var ClientConfigurationError;
-var init_ClientConfigurationError = __esm(() => {
- init_AuthError();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- ClientConfigurationError = class ClientConfigurationError extends AuthError {
- constructor(errorCode) {
- super(errorCode);
- this.name = "ClientConfigurationError";
- Object.setPrototypeOf(this, ClientConfigurationError.prototype);
- }
- };
-});
-
-// node_modules/@azure/msal-common/dist/utils/StringUtils.mjs
-class StringUtils {
- static isEmptyObj(strObj) {
- if (strObj) {
- try {
- const obj = JSON.parse(strObj);
- return Object.keys(obj).length === 0;
- } catch (e4) {}
- }
- return true;
- }
- static startsWith(str, search) {
- return str.indexOf(search) === 0;
- }
- static endsWith(str, search) {
- return str.length >= search.length && str.lastIndexOf(search) === str.length - search.length;
- }
- static queryStringToObject(query) {
- const obj = {};
- const params = query.split("&");
- const decode = (s4) => decodeURIComponent(s4.replace(/\+/g, " "));
- params.forEach((pair) => {
- if (pair.trim()) {
- const [key, value] = pair.split(/=(.+)/g, 2);
- if (key && value) {
- obj[decode(key)] = decode(value);
- }
- }
- });
- return obj;
- }
- static trimArrayEntries(arr) {
- return arr.map((entry) => entry.trim());
- }
- static removeEmptyStringsFromArray(arr) {
- return arr.filter((entry) => {
- return !!entry;
- });
- }
- static jsonParseHelper(str) {
- try {
- return JSON.parse(str);
- } catch (e4) {
- return null;
- }
- }
-}
-var init_StringUtils = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/error/ClientAuthError.mjs
-function createClientAuthError(errorCode, additionalMessage) {
- return new ClientAuthError(errorCode, additionalMessage);
-}
-var ClientAuthError;
-var init_ClientAuthError = __esm(() => {
- init_AuthError();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- ClientAuthError = class ClientAuthError extends AuthError {
- constructor(errorCode, additionalMessage) {
- super(errorCode, additionalMessage);
- this.name = "ClientAuthError";
- Object.setPrototypeOf(this, ClientAuthError.prototype);
- }
- };
-});
-
-// node_modules/@azure/msal-common/dist/error/ClientConfigurationErrorCodes.mjs
-var exports_ClientConfigurationErrorCodes = {};
-__export(exports_ClientConfigurationErrorCodes, {
- urlParseError: () => urlParseError,
- urlEmptyError: () => urlEmptyError,
- untrustedAuthority: () => untrustedAuthority,
- tokenRequestEmpty: () => tokenRequestEmpty,
- redirectUriEmpty: () => redirectUriEmpty,
- pkceParamsMissing: () => pkceParamsMissing,
- missingSshKid: () => missingSshKid,
- missingSshJwk: () => missingSshJwk,
- missingNonceAuthenticationHeader: () => missingNonceAuthenticationHeader,
- logoutRequestEmpty: () => logoutRequestEmpty,
- invalidRequestMethodForEAR: () => invalidRequestMethodForEAR,
- invalidCodeChallengeMethod: () => invalidCodeChallengeMethod,
- invalidCloudDiscoveryMetadata: () => invalidCloudDiscoveryMetadata,
- invalidClaims: () => invalidClaims,
- invalidAuthorityMetadata: () => invalidAuthorityMetadata,
- invalidAuthenticationHeader: () => invalidAuthenticationHeader,
- emptyInputScopesError: () => emptyInputScopesError,
- claimsRequestParsingError: () => claimsRequestParsingError,
- cannotSetOIDCOptions: () => cannotSetOIDCOptions,
- cannotAllowPlatformBroker: () => cannotAllowPlatformBroker,
- authorityUriInsecure: () => authorityUriInsecure,
- authorityMismatch: () => authorityMismatch
-});
-var redirectUriEmpty = "redirect_uri_empty", claimsRequestParsingError = "claims_request_parsing_error", authorityUriInsecure = "authority_uri_insecure", urlParseError = "url_parse_error", urlEmptyError = "empty_url_error", emptyInputScopesError = "empty_input_scopes_error", invalidClaims = "invalid_claims", tokenRequestEmpty = "token_request_empty", logoutRequestEmpty = "logout_request_empty", invalidCodeChallengeMethod = "invalid_code_challenge_method", pkceParamsMissing = "pkce_params_missing", invalidCloudDiscoveryMetadata = "invalid_cloud_discovery_metadata", invalidAuthorityMetadata = "invalid_authority_metadata", untrustedAuthority = "untrusted_authority", missingSshJwk = "missing_ssh_jwk", missingSshKid = "missing_ssh_kid", missingNonceAuthenticationHeader = "missing_nonce_authentication_header", invalidAuthenticationHeader = "invalid_authentication_header", cannotSetOIDCOptions = "cannot_set_OIDCOptions", cannotAllowPlatformBroker = "cannot_allow_platform_broker", authorityMismatch = "authority_mismatch", invalidRequestMethodForEAR = "invalid_request_method_for_EAR";
-var init_ClientConfigurationErrorCodes = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/error/ClientAuthErrorCodes.mjs
-var exports_ClientAuthErrorCodes = {};
-__export(exports_ClientAuthErrorCodes, {
- userCanceled: () => userCanceled,
- unexpectedCredentialType: () => unexpectedCredentialType,
- tokenRefreshRequired: () => tokenRefreshRequired,
- tokenParsingError: () => tokenParsingError,
- tokenClaimsCnfRequiredForSignedJwt: () => tokenClaimsCnfRequiredForSignedJwt,
- stateNotFound: () => stateNotFound,
- stateMismatch: () => stateMismatch,
- resourceParameterRequired: () => resourceParameterRequired,
- requestCannotBeMade: () => requestCannotBeMade,
- platformBrokerError: () => platformBrokerError,
- openIdConfigError: () => openIdConfigError,
- nullOrEmptyToken: () => nullOrEmptyToken,
- nonceMismatch: () => nonceMismatch,
- noNetworkConnectivity: () => noNetworkConnectivity,
- noCryptoObject: () => noCryptoObject,
- noAccountInSilentRequest: () => noAccountInSilentRequest,
- noAccountFound: () => noAccountFound,
- networkError: () => networkError,
- nestedAppAuthBridgeDisabled: () => nestedAppAuthBridgeDisabled,
- multipleMatchingTokens: () => multipleMatchingTokens,
- multipleMatchingAppMetadata: () => multipleMatchingAppMetadata,
- misplacedResourceParam: () => misplacedResourceParam,
- methodNotImplemented: () => methodNotImplemented,
- maxAgeTranspired: () => maxAgeTranspired,
- keyIdMissing: () => keyIdMissing,
- invalidState: () => invalidState,
- invalidCacheRecord: () => invalidCacheRecord,
- invalidCacheEnvironment: () => invalidCacheEnvironment,
- hashNotDeserialized: () => hashNotDeserialized,
- endpointResolutionError: () => endpointResolutionError,
- endSessionEndpointNotSupported: () => endSessionEndpointNotSupported,
- emptyInputScopeSet: () => emptyInputScopeSet,
- clientInfoEmptyError: () => clientInfoEmptyError,
- clientInfoDecodingError: () => clientInfoDecodingError,
- cannotRemoveEmptyScope: () => cannotRemoveEmptyScope,
- cannotAppendScopeSet: () => cannotAppendScopeSet,
- bindingKeyNotRemoved: () => bindingKeyNotRemoved,
- authorizationCodeMissingFromServerResponse: () => authorizationCodeMissingFromServerResponse,
- authTimeNotFound: () => authTimeNotFound
-});
-var clientInfoDecodingError = "client_info_decoding_error", clientInfoEmptyError = "client_info_empty_error", tokenParsingError = "token_parsing_error", nullOrEmptyToken = "null_or_empty_token", endpointResolutionError = "endpoints_resolution_error", networkError = "network_error", openIdConfigError = "openid_config_error", hashNotDeserialized = "hash_not_deserialized", invalidState = "invalid_state", stateMismatch = "state_mismatch", stateNotFound = "state_not_found", nonceMismatch = "nonce_mismatch", authTimeNotFound = "auth_time_not_found", maxAgeTranspired = "max_age_transpired", multipleMatchingTokens = "multiple_matching_tokens", multipleMatchingAppMetadata = "multiple_matching_appMetadata", requestCannotBeMade = "request_cannot_be_made", cannotRemoveEmptyScope = "cannot_remove_empty_scope", cannotAppendScopeSet = "cannot_append_scopeset", emptyInputScopeSet = "empty_input_scopeset", noAccountInSilentRequest = "no_account_in_silent_request", invalidCacheRecord = "invalid_cache_record", invalidCacheEnvironment = "invalid_cache_environment", noAccountFound = "no_account_found", noCryptoObject = "no_crypto_object", unexpectedCredentialType = "unexpected_credential_type", tokenRefreshRequired = "token_refresh_required", tokenClaimsCnfRequiredForSignedJwt = "token_claims_cnf_required_for_signedjwt", authorizationCodeMissingFromServerResponse = "authorization_code_missing_from_server_response", bindingKeyNotRemoved = "binding_key_not_removed", endSessionEndpointNotSupported = "end_session_endpoint_not_supported", keyIdMissing = "key_id_missing", noNetworkConnectivity = "no_network_connectivity", userCanceled = "user_canceled", methodNotImplemented = "method_not_implemented", nestedAppAuthBridgeDisabled = "nested_app_auth_bridge_disabled", platformBrokerError = "platform_broker_error", resourceParameterRequired = "resource_parameter_required", misplacedResourceParam = "misplaced_resource_parameter";
-var init_ClientAuthErrorCodes = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/request/ScopeSet.mjs
-class ScopeSet {
- constructor(inputScopes) {
- const scopeArr = inputScopes ? StringUtils.trimArrayEntries([...inputScopes]) : [];
- const filteredInput = scopeArr ? StringUtils.removeEmptyStringsFromArray(scopeArr) : [];
- if (!filteredInput || !filteredInput.length) {
- throw createClientConfigurationError(emptyInputScopesError);
- }
- this.scopes = new Set;
- filteredInput.forEach((scope) => this.scopes.add(scope));
- }
- static fromString(inputScopeString) {
- const scopeString = inputScopeString || "";
- const inputScopes = scopeString.split(" ");
- return new ScopeSet(inputScopes);
- }
- static createSearchScopes(inputScopeString) {
- const scopesToUse = inputScopeString && inputScopeString.length > 0 ? inputScopeString : [...OIDC_DEFAULT_SCOPES];
- const scopeSet = new ScopeSet(scopesToUse);
- if (!scopeSet.containsOnlyOIDCScopes()) {
- scopeSet.removeOIDCScopes();
- } else {
- scopeSet.removeScope(OFFLINE_ACCESS_SCOPE);
- }
- return scopeSet;
- }
- containsScope(scope) {
- const lowerCaseScopes = this.printScopesLowerCase().split(" ");
- const lowerCaseScopesSet = new ScopeSet(lowerCaseScopes);
- return scope ? lowerCaseScopesSet.scopes.has(scope.toLowerCase()) : false;
- }
- containsScopeSet(scopeSet) {
- if (!scopeSet || scopeSet.scopes.size <= 0) {
- return false;
- }
- return this.scopes.size >= scopeSet.scopes.size && scopeSet.asArray().every((scope) => this.containsScope(scope));
- }
- containsOnlyOIDCScopes() {
- let defaultScopeCount = 0;
- OIDC_SCOPES.forEach((defaultScope) => {
- if (this.containsScope(defaultScope)) {
- defaultScopeCount += 1;
- }
- });
- return this.scopes.size === defaultScopeCount;
- }
- appendScope(newScope) {
- if (newScope) {
- this.scopes.add(newScope.trim());
- }
- }
- appendScopes(newScopes) {
- try {
- newScopes.forEach((newScope) => this.appendScope(newScope));
- } catch (e4) {
- throw createClientAuthError(cannotAppendScopeSet);
- }
- }
- removeScope(scope) {
- if (!scope) {
- throw createClientAuthError(cannotRemoveEmptyScope);
- }
- this.scopes.delete(scope.trim());
- }
- removeOIDCScopes() {
- OIDC_SCOPES.forEach((defaultScope) => {
- this.scopes.delete(defaultScope);
- });
- }
- unionScopeSets(otherScopes) {
- if (!otherScopes) {
- throw createClientAuthError(emptyInputScopeSet);
- }
- const unionScopes = new Set;
- otherScopes.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));
- this.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));
- return unionScopes;
- }
- intersectingScopeSets(otherScopes) {
- if (!otherScopes) {
- throw createClientAuthError(emptyInputScopeSet);
- }
- if (!otherScopes.containsOnlyOIDCScopes()) {
- otherScopes.removeOIDCScopes();
- }
- const unionScopes = this.unionScopeSets(otherScopes);
- const sizeOtherScopes = otherScopes.getScopeCount();
- const sizeThisScopes = this.getScopeCount();
- const sizeUnionScopes = unionScopes.size;
- return sizeUnionScopes < sizeThisScopes + sizeOtherScopes;
- }
- getScopeCount() {
- return this.scopes.size;
- }
- asArray() {
- const array2 = [];
- this.scopes.forEach((val) => array2.push(val));
- return array2;
- }
- printScopes() {
- if (this.scopes) {
- const scopeArr = this.asArray();
- return scopeArr.join(" ");
- }
- return "";
- }
- printScopesLowerCase() {
- return this.printScopes().toLowerCase();
- }
-}
-var init_ScopeSet = __esm(() => {
- init_ClientConfigurationError();
- init_StringUtils();
- init_ClientAuthError();
- init_Constants();
- init_ClientConfigurationErrorCodes();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.mjs
-var exports_RequestParameterBuilder = {};
-__export(exports_RequestParameterBuilder, {
- instrumentBrokerParams: () => instrumentBrokerParams,
- addUsername: () => addUsername,
- addThrottling: () => addThrottling,
- addState: () => addState,
- addSshJwk: () => addSshJwk,
- addSid: () => addSid,
- addServerTelemetry: () => addServerTelemetry,
- addScopes: () => addScopes,
- addResponseType: () => addResponseType,
- addResponseMode: () => addResponseMode,
- addResource: () => addResource,
- addRequestTokenUse: () => addRequestTokenUse,
- addRefreshToken: () => addRefreshToken,
- addRedirectUri: () => addRedirectUri,
- addPrompt: () => addPrompt,
- addPostLogoutRedirectUri: () => addPostLogoutRedirectUri,
- addPopToken: () => addPopToken,
- addPassword: () => addPassword,
- addOboAssertion: () => addOboAssertion,
- addNonce: () => addNonce,
- addNativeBroker: () => addNativeBroker,
- addLogoutHint: () => addLogoutHint,
- addLoginHint: () => addLoginHint,
- addLibraryInfo: () => addLibraryInfo,
- addInstanceAware: () => addInstanceAware,
- addIdTokenHint: () => addIdTokenHint,
- addGrantType: () => addGrantType,
- addExtraParameters: () => addExtraParameters,
- addEARParameters: () => addEARParameters,
- addDomainHint: () => addDomainHint,
- addDeviceCode: () => addDeviceCode,
- addCorrelationId: () => addCorrelationId,
- addCodeVerifier: () => addCodeVerifier,
- addCodeChallengeParams: () => addCodeChallengeParams,
- addClientSecret: () => addClientSecret,
- addClientInfo: () => addClientInfo,
- addClientId: () => addClientId,
- addClientCapabilitiesToClaims: () => addClientCapabilitiesToClaims,
- addClientAssertionType: () => addClientAssertionType,
- addClientAssertion: () => addClientAssertion,
- addCliData: () => addCliData,
- addClaims: () => addClaims,
- addCcsUpn: () => addCcsUpn,
- addCcsOid: () => addCcsOid,
- addBrokerParameters: () => addBrokerParameters,
- addAuthorizationCode: () => addAuthorizationCode,
- addApplicationTelemetry: () => addApplicationTelemetry
-});
-function instrumentBrokerParams(parameters, correlationId, performanceClient) {
- if (!correlationId) {
- return;
- }
- const clientId = parameters.get(CLIENT_ID);
- if (clientId && parameters.has(BROKER_CLIENT_ID)) {
- performanceClient?.addFields({
- embeddedClientId: clientId,
- embeddedRedirectUri: parameters.get(REDIRECT_URI)
- }, correlationId);
- }
-}
-function addResponseType(parameters, responseType) {
- parameters.set(RESPONSE_TYPE2, responseType);
-}
-function addResponseMode(parameters, responseMode) {
- parameters.set(RESPONSE_MODE, responseMode ? responseMode : ResponseMode.QUERY);
-}
-function addNativeBroker(parameters) {
- parameters.set(NATIVE_BROKER, "1");
-}
-function addScopes(parameters, scopes, addOidcScopes = true, defaultScopes = OIDC_DEFAULT_SCOPES) {
- if (addOidcScopes && !defaultScopes.includes("openid") && !scopes.includes("openid")) {
- defaultScopes.push("openid");
- }
- const requestScopes = addOidcScopes ? [...scopes || [], ...defaultScopes] : scopes || [];
- const scopeSet = new ScopeSet(requestScopes);
- parameters.set(SCOPE, scopeSet.printScopes());
-}
-function addClientId(parameters, clientId) {
- parameters.set(CLIENT_ID, clientId);
-}
-function addRedirectUri(parameters, redirectUri) {
- parameters.set(REDIRECT_URI, redirectUri);
-}
-function addPostLogoutRedirectUri(parameters, redirectUri) {
- parameters.set(POST_LOGOUT_URI, redirectUri);
-}
-function addIdTokenHint(parameters, idTokenHint) {
- parameters.set(ID_TOKEN_HINT, idTokenHint);
-}
-function addDomainHint(parameters, domainHint) {
- parameters.set(DOMAIN_HINT, domainHint);
-}
-function addLoginHint(parameters, loginHint) {
- parameters.set(LOGIN_HINT, loginHint);
-}
-function addCcsUpn(parameters, loginHint) {
- parameters.set(HeaderNames.CCS_HEADER, `UPN:${loginHint}`);
-}
-function addCcsOid(parameters, clientInfo) {
- parameters.set(HeaderNames.CCS_HEADER, `Oid:${clientInfo.uid}@${clientInfo.utid}`);
-}
-function addSid(parameters, sid) {
- parameters.set(SID, sid);
-}
-function addClaims(parameters, claims, clientCapabilities) {
- const mergedClaims = addClientCapabilitiesToClaims(claims, clientCapabilities);
- try {
- JSON.parse(mergedClaims);
- } catch (e4) {
- throw createClientConfigurationError(invalidClaims);
- }
- parameters.set(CLAIMS, mergedClaims);
-}
-function addCorrelationId(parameters, correlationId) {
- parameters.set(CLIENT_REQUEST_ID, correlationId);
-}
-function addLibraryInfo(parameters, libraryInfo) {
- parameters.set(X_CLIENT_SKU, libraryInfo.sku);
- parameters.set(X_CLIENT_VER, libraryInfo.version);
- if (libraryInfo.os) {
- parameters.set(X_CLIENT_OS, libraryInfo.os);
- }
- if (libraryInfo.cpu) {
- parameters.set(X_CLIENT_CPU, libraryInfo.cpu);
- }
-}
-function addApplicationTelemetry(parameters, appTelemetry) {
- if (appTelemetry?.appName) {
- parameters.set(X_APP_NAME, appTelemetry.appName);
- }
- if (appTelemetry?.appVersion) {
- parameters.set(X_APP_VER, appTelemetry.appVersion);
- }
-}
-function addPrompt(parameters, prompt) {
- parameters.set(PROMPT, prompt);
-}
-function addState(parameters, state2) {
- if (state2) {
- parameters.set(STATE2, state2);
- }
-}
-function addNonce(parameters, nonce) {
- parameters.set(NONCE, nonce);
-}
-function addCodeChallengeParams(parameters, codeChallenge, codeChallengeMethod) {
- if (codeChallenge && codeChallengeMethod) {
- parameters.set(CODE_CHALLENGE, codeChallenge);
- parameters.set(CODE_CHALLENGE_METHOD, codeChallengeMethod);
- } else {
- throw createClientConfigurationError(pkceParamsMissing);
- }
-}
-function addAuthorizationCode(parameters, code) {
- parameters.set(CODE, code);
-}
-function addDeviceCode(parameters, code) {
- parameters.set(DEVICE_CODE, code);
-}
-function addRefreshToken(parameters, refreshToken) {
- parameters.set(REFRESH_TOKEN, refreshToken);
-}
-function addCodeVerifier(parameters, codeVerifier) {
- parameters.set(CODE_VERIFIER, codeVerifier);
-}
-function addClientSecret(parameters, clientSecret) {
- parameters.set(CLIENT_SECRET, clientSecret);
-}
-function addClientAssertion(parameters, clientAssertion) {
- if (clientAssertion) {
- parameters.set(CLIENT_ASSERTION, clientAssertion);
- }
-}
-function addClientAssertionType(parameters, clientAssertionType) {
- if (clientAssertionType) {
- parameters.set(CLIENT_ASSERTION_TYPE, clientAssertionType);
- }
-}
-function addOboAssertion(parameters, oboAssertion) {
- parameters.set(OBO_ASSERTION, oboAssertion);
-}
-function addRequestTokenUse(parameters, tokenUse) {
- parameters.set(REQUESTED_TOKEN_USE, tokenUse);
-}
-function addGrantType(parameters, grantType) {
- parameters.set(GRANT_TYPE, grantType);
-}
-function addClientInfo(parameters) {
- parameters.set(CLIENT_INFO, "1");
-}
-function addCliData(parameters) {
- parameters.set(CLI_DATA, "1");
-}
-function addInstanceAware(parameters) {
- if (!parameters.has(INSTANCE_AWARE)) {
- parameters.set(INSTANCE_AWARE, "true");
- }
-}
-function addExtraParameters(parameters, extraParams) {
- Object.entries(extraParams).forEach(([key, value]) => {
- if (!parameters.has(key) && value) {
- parameters.set(key, value);
- }
- });
-}
-function addClientCapabilitiesToClaims(claims, clientCapabilities) {
- let mergedClaims;
- if (!claims) {
- mergedClaims = {};
- } else {
- try {
- mergedClaims = JSON.parse(claims);
- } catch (e4) {
- throw createClientConfigurationError(invalidClaims);
- }
- }
- if (clientCapabilities && clientCapabilities.length > 0) {
- if (!mergedClaims.hasOwnProperty(ClaimsRequestKeys.ACCESS_TOKEN)) {
- mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN] = {};
- }
- mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN][ClaimsRequestKeys.XMS_CC] = {
- values: clientCapabilities
- };
- }
- return JSON.stringify(mergedClaims);
-}
-function addUsername(parameters, username) {
- parameters.set(PasswordGrantConstants.username, username);
-}
-function addPassword(parameters, password) {
- parameters.set(PasswordGrantConstants.password, password);
-}
-function addPopToken(parameters, cnfString) {
- if (cnfString) {
- parameters.set(TOKEN_TYPE, AuthenticationScheme.POP);
- parameters.set(REQ_CNF, cnfString);
- }
-}
-function addSshJwk(parameters, sshJwkString) {
- if (sshJwkString) {
- parameters.set(TOKEN_TYPE, AuthenticationScheme.SSH);
- parameters.set(REQ_CNF, sshJwkString);
- }
-}
-function addServerTelemetry(parameters, serverTelemetryManager) {
- parameters.set(X_CLIENT_CURR_TELEM, serverTelemetryManager.generateCurrentRequestHeaderValue());
- parameters.set(X_CLIENT_LAST_TELEM, serverTelemetryManager.generateLastRequestHeaderValue());
-}
-function addThrottling(parameters) {
- parameters.set(X_MS_LIB_CAPABILITY, X_MS_LIB_CAPABILITY_VALUE);
-}
-function addLogoutHint(parameters, logoutHint) {
- parameters.set(LOGOUT_HINT, logoutHint);
-}
-function addBrokerParameters(parameters, brokerClientId, brokerRedirectUri) {
- if (!parameters.has(BROKER_CLIENT_ID)) {
- parameters.set(BROKER_CLIENT_ID, brokerClientId);
- }
- if (!parameters.has(BROKER_REDIRECT_URI)) {
- parameters.set(BROKER_REDIRECT_URI, brokerRedirectUri);
- }
-}
-function addEARParameters(parameters, jwk) {
- parameters.set(EAR_JWK, encodeURIComponent(jwk));
- const jweCryptoB64Encoded = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0";
- parameters.set(EAR_JWE_CRYPTO, jweCryptoB64Encoded);
-}
-function addResource(parameters, resource) {
- if (resource) {
- parameters.set(RESOURCE, resource);
- }
-}
-var init_RequestParameterBuilder = __esm(() => {
- init_Constants();
- init_AADServerParamKeys();
- init_ScopeSet();
- init_ClientConfigurationError();
- init_ClientConfigurationErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/utils/UrlUtils.mjs
-var exports_UrlUtils = {};
-__export(exports_UrlUtils, {
- stripLeadingHashOrQuery: () => stripLeadingHashOrQuery,
- normalizeUrlForComparison: () => normalizeUrlForComparison,
- mapToQueryString: () => mapToQueryString,
- getDeserializedResponse: () => getDeserializedResponse
-});
-function canonicalizeUrl(url3) {
- if (!url3) {
- return url3;
- }
- let lowerCaseUrl = url3.toLowerCase();
- if (StringUtils.endsWith(lowerCaseUrl, "?")) {
- lowerCaseUrl = lowerCaseUrl.slice(0, -1);
- } else if (StringUtils.endsWith(lowerCaseUrl, "?/")) {
- lowerCaseUrl = lowerCaseUrl.slice(0, -2);
- }
- if (!StringUtils.endsWith(lowerCaseUrl, "/")) {
- lowerCaseUrl += "/";
- }
- return lowerCaseUrl;
-}
-function stripLeadingHashOrQuery(responseString) {
- if (responseString.startsWith("#/")) {
- return responseString.substring(2);
- } else if (responseString.startsWith("#") || responseString.startsWith("?")) {
- return responseString.substring(1);
- }
- return responseString;
-}
-function getDeserializedResponse(responseString) {
- if (!responseString || responseString.indexOf("=") < 0) {
- return null;
- }
- try {
- const normalizedResponse = stripLeadingHashOrQuery(responseString);
- const deserializedHash = Object.fromEntries(new URLSearchParams(normalizedResponse));
- if (deserializedHash.code || deserializedHash.ear_jwe || deserializedHash.error || deserializedHash.error_description || deserializedHash.state) {
- return deserializedHash;
- }
- } catch (e4) {
- throw createClientAuthError(hashNotDeserialized);
- }
- return null;
-}
-function mapToQueryString(parameters) {
- const queryParameterArray = new Array;
- parameters.forEach((value, key) => {
- queryParameterArray.push(`${key}=${encodeURIComponent(value)}`);
- });
- return queryParameterArray.join("&");
-}
-function normalizeUrlForComparison(url3) {
- if (!url3) {
- return url3;
- }
- const urlWithoutHash = url3.split("#")[0];
- try {
- const urlObj = new URL(urlWithoutHash);
- const normalizedUrl = urlObj.origin + urlObj.pathname + urlObj.search;
- return canonicalizeUrl(normalizedUrl);
- } catch (e4) {
- return canonicalizeUrl(urlWithoutHash);
- }
-}
-var init_UrlUtils = __esm(() => {
- init_ClientAuthError();
- init_StringUtils();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/crypto/ICrypto.mjs
-var DEFAULT_CRYPTO_IMPLEMENTATION;
-var init_ICrypto = __esm(() => {
- init_ClientAuthError();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- DEFAULT_CRYPTO_IMPLEMENTATION = {
- createNewGuid: () => {
- throw createClientAuthError(methodNotImplemented);
- },
- base64Decode: () => {
- throw createClientAuthError(methodNotImplemented);
- },
- base64Encode: () => {
- throw createClientAuthError(methodNotImplemented);
- },
- base64UrlEncode: () => {
- throw createClientAuthError(methodNotImplemented);
- },
- encodeKid: () => {
- throw createClientAuthError(methodNotImplemented);
- },
- async getPublicKeyThumbprint() {
- throw createClientAuthError(methodNotImplemented);
- },
- async removeTokenBindingKey() {
- throw createClientAuthError(methodNotImplemented);
- },
- async clearKeystore() {
- throw createClientAuthError(methodNotImplemented);
- },
- async signJwt() {
- throw createClientAuthError(methodNotImplemented);
- },
- async hashString() {
- throw createClientAuthError(methodNotImplemented);
- }
- };
-});
-
-// node_modules/@azure/msal-common/dist/logger/Logger.mjs
-function markAsRecentlyUsed(correlationId, data) {
- correlationCache.delete(correlationId);
- correlationCache.set(correlationId, data);
-}
-function addLogToCache(correlationId, loggedMessage) {
- const currentTime = Date.now();
- let data = correlationCache.get(correlationId);
- if (data) {
- markAsRecentlyUsed(correlationId, data);
- } else {
- data = { logs: [], firstEventTime: currentTime };
- correlationCache.set(correlationId, data);
- if (correlationCache.size > CACHE_CAPACITY) {
- const firstKey = correlationCache.keys().next().value;
- if (firstKey) {
- correlationCache.delete(firstKey);
- }
- }
- }
- data.logs.push({
- ...loggedMessage,
- milliseconds: currentTime - data.firstEventTime
- });
- if (data.logs.length > MAX_LOGS_PER_CORRELATION) {
- data.logs.shift();
- }
-}
-function isHashedString(str) {
- if (str.length !== 6) {
- return false;
- }
- for (let i5 = 0;i5 < str.length; i5++) {
- const char = str[i5];
- const isAlphaNumeric = char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char >= "0" && char <= "9";
- if (!isAlphaNumeric) {
- return false;
- }
- }
- return true;
-}
-
-class Logger {
- constructor(loggerOptions, packageName, packageVersion) {
- this.level = LogLevel.Info;
- const defaultLoggerCallback = () => {
- return;
- };
- const setLoggerOptions = loggerOptions || Logger.createDefaultLoggerOptions();
- this.localCallback = setLoggerOptions.loggerCallback || defaultLoggerCallback;
- this.piiLoggingEnabled = setLoggerOptions.piiLoggingEnabled || false;
- this.level = typeof setLoggerOptions.logLevel === "number" ? setLoggerOptions.logLevel : LogLevel.Info;
- this.packageName = packageName || "";
- this.packageVersion = packageVersion || "";
- }
- static createDefaultLoggerOptions() {
- return {
- loggerCallback: () => {},
- piiLoggingEnabled: false,
- logLevel: LogLevel.Info
- };
- }
- clone(packageName, packageVersion) {
- return new Logger({
- loggerCallback: this.localCallback,
- piiLoggingEnabled: this.piiLoggingEnabled,
- logLevel: this.level
- }, packageName, packageVersion);
- }
- logMessage(logMessage, options2) {
- const correlationId = options2.correlationId;
- const isHashedInput = isHashedString(logMessage);
- if (isHashedInput) {
- const loggedMessage = {
- hash: logMessage,
- level: options2.logLevel,
- containsPii: options2.containsPii || false,
- milliseconds: 0
- };
- addLogToCache(correlationId, loggedMessage);
- }
- if (options2.logLevel > this.level || !this.piiLoggingEnabled && options2.containsPii) {
- return;
- }
- const timestamp = new Date().toUTCString();
- const logHeader = `[${timestamp}] : [${correlationId}]`;
- const log3 = `${logHeader} : ${this.packageName}@${this.packageVersion} : ${LogLevel[options2.logLevel]} - ${logMessage}`;
- this.executeCallback(options2.logLevel, log3, options2.containsPii || false);
- }
- executeCallback(level, message, containsPii) {
- if (this.localCallback) {
- this.localCallback(level, message, containsPii);
- }
- }
- error(message, correlationId) {
- this.logMessage(message, {
- logLevel: LogLevel.Error,
- containsPii: false,
- correlationId
- });
- }
- errorPii(message, correlationId) {
- this.logMessage(message, {
- logLevel: LogLevel.Error,
- containsPii: true,
- correlationId
- });
- }
- warning(message, correlationId) {
- this.logMessage(message, {
- logLevel: LogLevel.Warning,
- containsPii: false,
- correlationId
- });
- }
- warningPii(message, correlationId) {
- this.logMessage(message, {
- logLevel: LogLevel.Warning,
- containsPii: true,
- correlationId
- });
- }
- info(message, correlationId) {
- this.logMessage(message, {
- logLevel: LogLevel.Info,
- containsPii: false,
- correlationId
- });
- }
- infoPii(message, correlationId) {
- this.logMessage(message, {
- logLevel: LogLevel.Info,
- containsPii: true,
- correlationId
- });
- }
- verbose(message, correlationId) {
- this.logMessage(message, {
- logLevel: LogLevel.Verbose,
- containsPii: false,
- correlationId
- });
- }
- verbosePii(message, correlationId) {
- this.logMessage(message, {
- logLevel: LogLevel.Verbose,
- containsPii: true,
- correlationId
- });
- }
- trace(message, correlationId) {
- this.logMessage(message, {
- logLevel: LogLevel.Trace,
- containsPii: false,
- correlationId
- });
- }
- tracePii(message, correlationId) {
- this.logMessage(message, {
- logLevel: LogLevel.Trace,
- containsPii: true,
- correlationId
- });
- }
- isPiiLoggingEnabled() {
- return this.piiLoggingEnabled || false;
- }
-}
-var LogLevel, CACHE_CAPACITY = 50, MAX_LOGS_PER_CORRELATION = 500, correlationCache;
-var init_Logger = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- (function(LogLevel2) {
- LogLevel2[LogLevel2["Error"] = 0] = "Error";
- LogLevel2[LogLevel2["Warning"] = 1] = "Warning";
- LogLevel2[LogLevel2["Info"] = 2] = "Info";
- LogLevel2[LogLevel2["Verbose"] = 3] = "Verbose";
- LogLevel2[LogLevel2["Trace"] = 4] = "Trace";
- })(LogLevel || (LogLevel = {}));
- correlationCache = new Map;
-});
-
-// node_modules/@azure/msal-common/dist/packageMetadata.mjs
-var name = "@azure/msal-common", version2 = "16.4.0";
-var init_packageMetadata = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/authority/AuthorityOptions.mjs
-var AzureCloudInstance;
-var init_AuthorityOptions = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- AzureCloudInstance = {
- None: "none",
- AzurePublic: "https://login.microsoftonline.com",
- AzurePpe: "https://login.windows-ppe.net",
- AzureChina: "https://login.chinacloudapi.cn",
- AzureGermany: "https://login.microsoftonline.de",
- AzureUsGovernment: "https://login.microsoftonline.us"
- };
-});
-
-// node_modules/@azure/msal-common/dist/account/AccountInfo.mjs
-function tenantIdMatchesHomeTenant(tenantId, homeAccountId) {
- return !!tenantId && !!homeAccountId && tenantId === homeAccountId.split(".")[1];
-}
-function buildTenantProfile(homeAccountId, localAccountId, tenantId, idTokenClaims) {
- if (idTokenClaims) {
- const { oid, sub, tid, name: name2, tfp, acr, preferred_username, upn, login_hint } = idTokenClaims;
- const tenantId2 = tid || tfp || acr || "";
- return {
- tenantId: tenantId2,
- localAccountId: oid || sub || "",
- name: name2,
- username: preferred_username || upn || "",
- loginHint: login_hint,
- isHomeTenant: tenantIdMatchesHomeTenant(tenantId2, homeAccountId)
- };
- } else {
- return {
- tenantId,
- localAccountId,
- username: "",
- isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId)
- };
- }
-}
-function updateAccountTenantProfileData(baseAccountInfo, tenantProfile, idTokenClaims, idTokenSecret) {
- let updatedAccountInfo = baseAccountInfo;
- if (tenantProfile) {
- const { isHomeTenant, ...tenantProfileOverride } = tenantProfile;
- updatedAccountInfo = { ...baseAccountInfo, ...tenantProfileOverride };
- }
- if (idTokenClaims) {
- const { isHomeTenant, ...claimsSourcedTenantProfile } = buildTenantProfile(baseAccountInfo.homeAccountId, baseAccountInfo.localAccountId, baseAccountInfo.tenantId, idTokenClaims);
- updatedAccountInfo = {
- ...updatedAccountInfo,
- ...claimsSourcedTenantProfile,
- idTokenClaims,
- idToken: idTokenSecret
- };
- return updatedAccountInfo;
- }
- return updatedAccountInfo;
-}
-var init_AccountInfo = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/account/AuthToken.mjs
-var exports_AuthToken = {};
-__export(exports_AuthToken, {
- isKmsi: () => isKmsi,
- getJWSPayload: () => getJWSPayload,
- extractTokenClaims: () => extractTokenClaims,
- checkMaxAge: () => checkMaxAge
-});
-function extractTokenClaims(encodedToken, base64Decode) {
- const jswPayload = getJWSPayload(encodedToken);
- try {
- const base64Decoded = base64Decode(jswPayload);
- return JSON.parse(base64Decoded);
- } catch (err) {
- throw createClientAuthError(tokenParsingError);
- }
-}
-function isKmsi(idTokenClaims) {
- if (!idTokenClaims.signin_state) {
- return false;
- }
- const kmsiClaims = ["kmsi", "dvc_dmjd"];
- return idTokenClaims.signin_state.some((value) => kmsiClaims.includes(value.trim().toLowerCase()));
-}
-function getJWSPayload(authToken) {
- if (!authToken) {
- throw createClientAuthError(nullOrEmptyToken);
- }
- const tokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/;
- const matches = tokenPartsRegex.exec(authToken);
- if (!matches || matches.length < 4) {
- throw createClientAuthError(tokenParsingError);
- }
- return matches[2];
-}
-function checkMaxAge(authTime, maxAge) {
- const fiveMinuteSkew = 300000;
- if (maxAge === 0 || Date.now() - fiveMinuteSkew > authTime + maxAge) {
- throw createClientAuthError(maxAgeTranspired);
- }
-}
-var init_AuthToken = __esm(() => {
- init_ClientAuthError();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/url/UrlString.mjs
-class UrlString {
- get urlString() {
- return this._urlString;
- }
- constructor(url3) {
- this._urlString = url3;
- if (!this._urlString) {
- throw createClientConfigurationError(urlEmptyError);
- }
- if (!url3.includes("#")) {
- this._urlString = UrlString.canonicalizeUri(url3);
- }
- }
- static canonicalizeUri(url3) {
- if (url3) {
- let lowerCaseUrl = url3.toLowerCase();
- if (StringUtils.endsWith(lowerCaseUrl, "?")) {
- lowerCaseUrl = lowerCaseUrl.slice(0, -1);
- } else if (StringUtils.endsWith(lowerCaseUrl, "?/")) {
- lowerCaseUrl = lowerCaseUrl.slice(0, -2);
- }
- if (!StringUtils.endsWith(lowerCaseUrl, "/")) {
- lowerCaseUrl += "/";
- }
- return lowerCaseUrl;
- }
- return url3;
- }
- validateAsUri() {
- let components;
- try {
- components = this.getUrlComponents();
- } catch (e4) {
- throw createClientConfigurationError(urlParseError);
- }
- if (!components.HostNameAndPort || !components.PathSegments) {
- throw createClientConfigurationError(urlParseError);
- }
- if (!components.Protocol || components.Protocol.toLowerCase() !== "https:") {
- throw createClientConfigurationError(authorityUriInsecure);
- }
- }
- static appendQueryString(url3, queryString) {
- if (!queryString) {
- return url3;
- }
- return url3.indexOf("?") < 0 ? `${url3}?${queryString}` : `${url3}&${queryString}`;
- }
- static removeHashFromUrl(url3) {
- return UrlString.canonicalizeUri(url3.split("#")[0]);
- }
- replaceTenantPath(tenantId) {
- const urlObject = this.getUrlComponents();
- const pathArray = urlObject.PathSegments;
- if (tenantId && pathArray.length !== 0 && (pathArray[0] === AADAuthority.COMMON || pathArray[0] === AADAuthority.ORGANIZATIONS)) {
- pathArray[0] = tenantId;
- }
- return UrlString.constructAuthorityUriFromObject(urlObject);
- }
- getUrlComponents() {
- const regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
- const match = this.urlString.match(regEx);
- if (!match) {
- throw createClientConfigurationError(urlParseError);
- }
- const urlComponents = {
- Protocol: match[1],
- HostNameAndPort: match[4],
- AbsolutePath: match[5],
- QueryString: match[7]
- };
- let pathSegments = urlComponents.AbsolutePath.split("/");
- pathSegments = pathSegments.filter((val) => val && val.length > 0);
- urlComponents.PathSegments = pathSegments;
- if (urlComponents.QueryString && urlComponents.QueryString.endsWith("/")) {
- urlComponents.QueryString = urlComponents.QueryString.substring(0, urlComponents.QueryString.length - 1);
- }
- return urlComponents;
- }
- static getDomainFromUrl(url3) {
- const regEx = RegExp("^([^:/?#]+://)?([^/?#]*)");
- const match = url3.match(regEx);
- if (!match) {
- throw createClientConfigurationError(urlParseError);
- }
- return match[2];
- }
- static getAbsoluteUrl(relativeUrl, baseUrl) {
- if (relativeUrl[0] === FORWARD_SLASH) {
- const url3 = new UrlString(baseUrl);
- const baseComponents = url3.getUrlComponents();
- return baseComponents.Protocol + "//" + baseComponents.HostNameAndPort + relativeUrl;
- }
- return relativeUrl;
- }
- static constructAuthorityUriFromObject(urlObject) {
- return new UrlString(urlObject.Protocol + "//" + urlObject.HostNameAndPort + "/" + urlObject.PathSegments.join("/"));
- }
-}
-var init_UrlString = __esm(() => {
- init_ClientConfigurationError();
- init_StringUtils();
- init_Constants();
- init_ClientConfigurationErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.mjs
-function buildOpenIdConfig(host, issuerHost) {
- return {
- token_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/token`,
- jwks_uri: `https://${host}/{tenantid}/discovery/v2.0/keys`,
- issuer: `https://${issuerHost}/{tenantid}/v2.0`,
- authorization_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/authorize`,
- end_session_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/logout`
- };
-}
-function getAliasesFromStaticSources(staticAuthorityOptions, logger10, correlationId) {
- let staticAliases;
- const canonicalAuthority = staticAuthorityOptions.canonicalAuthority;
- if (canonicalAuthority) {
- const authorityHost = new UrlString(canonicalAuthority).getUrlComponents().HostNameAndPort;
- staticAliases = getAliasesFromMetadata(logger10, correlationId, authorityHost, staticAuthorityOptions.cloudDiscoveryMetadata?.metadata, AuthorityMetadataSource.CONFIG) || getAliasesFromMetadata(logger10, correlationId, authorityHost, InstanceDiscoveryMetadata.metadata, AuthorityMetadataSource.HARDCODED_VALUES) || staticAuthorityOptions.knownAuthorities;
- }
- return staticAliases || [];
-}
-function getAliasesFromMetadata(logger10, correlationId, authorityHost, cloudDiscoveryMetadata, source) {
- logger10.trace(`getAliasesFromMetadata called with source: '${source}'`, correlationId);
- if (authorityHost && cloudDiscoveryMetadata) {
- const metadata = getCloudDiscoveryMetadataFromNetworkResponse(cloudDiscoveryMetadata, authorityHost);
- if (metadata) {
- logger10.trace(`getAliasesFromMetadata: found cloud discovery metadata in '${source}', returning aliases`, correlationId);
- return metadata.aliases;
- } else {
- logger10.trace(`getAliasesFromMetadata: did not find cloud discovery metadata in '${source}'`, correlationId);
- }
- }
- return null;
-}
-function getCloudDiscoveryMetadataFromHardcodedValues(authorityHost) {
- const metadata = getCloudDiscoveryMetadataFromNetworkResponse(InstanceDiscoveryMetadata.metadata, authorityHost);
- return metadata;
-}
-function getCloudDiscoveryMetadataFromNetworkResponse(response7, authorityHost) {
- for (let i5 = 0;i5 < response7.length; i5++) {
- const metadata = response7[i5];
- if (metadata.aliases.includes(authorityHost)) {
- return metadata;
- }
- }
- return null;
-}
-var endpointHosts, dynamicEndpointMetadata, rawMetdataJSON, EndpointMetadata, InstanceDiscoveryMetadata, InstanceDiscoveryMetadataAliases;
-var init_AuthorityMetadata = __esm(() => {
- init_UrlString();
- init_Constants();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- endpointHosts = [
- { host: "login.microsoftonline.com" },
- {
- host: "login.chinacloudapi.cn",
- issuerHost: "login.partner.microsoftonline.cn"
- },
- { host: "login.microsoftonline.us" },
- { host: "login.sovcloud-identity.fr" },
- { host: "login.sovcloud-identity.de" },
- { host: "login.sovcloud-identity.sg" }
- ];
- dynamicEndpointMetadata = endpointHosts.reduce((acc, { host, issuerHost }) => {
- acc[host] = buildOpenIdConfig(host, issuerHost || host);
- return acc;
- }, {});
- rawMetdataJSON = {
- endpointMetadata: dynamicEndpointMetadata,
- instanceDiscoveryMetadata: {
- metadata: [
- {
- preferred_network: "login.microsoftonline.com",
- preferred_cache: "login.windows.net",
- aliases: [
- "login.microsoftonline.com",
- "login.windows.net",
- "login.microsoft.com",
- "sts.windows.net"
- ]
- },
- {
- preferred_network: "login.partner.microsoftonline.cn",
- preferred_cache: "login.partner.microsoftonline.cn",
- aliases: [
- "login.partner.microsoftonline.cn",
- "login.chinacloudapi.cn"
- ]
- },
- {
- preferred_network: "login.microsoftonline.de",
- preferred_cache: "login.microsoftonline.de",
- aliases: ["login.microsoftonline.de"]
- },
- {
- preferred_network: "login.microsoftonline.us",
- preferred_cache: "login.microsoftonline.us",
- aliases: [
- "login.microsoftonline.us",
- "login.usgovcloudapi.net"
- ]
- },
- {
- preferred_network: "login-us.microsoftonline.com",
- preferred_cache: "login-us.microsoftonline.com",
- aliases: ["login-us.microsoftonline.com"]
- },
- {
- preferred_network: "login.sovcloud-identity.fr",
- preferred_cache: "login.sovcloud-identity.fr",
- aliases: ["login.sovcloud-identity.fr"]
- },
- {
- preferred_network: "login.sovcloud-identity.de",
- preferred_cache: "login.sovcloud-identity.de",
- aliases: ["login.sovcloud-identity.de"]
- },
- {
- preferred_network: "login.sovcloud-identity.sg",
- preferred_cache: "login.sovcloud-identity.sg",
- aliases: ["login.sovcloud-identity.sg"]
- }
- ]
- }
- };
- EndpointMetadata = rawMetdataJSON.endpointMetadata;
- InstanceDiscoveryMetadata = rawMetdataJSON.instanceDiscoveryMetadata;
- InstanceDiscoveryMetadataAliases = new Set;
- InstanceDiscoveryMetadata.metadata.forEach((metadataEntry) => {
- metadataEntry.aliases.forEach((alias) => {
- InstanceDiscoveryMetadataAliases.add(alias);
- });
- });
-});
-
-// node_modules/@azure/msal-common/dist/error/CacheErrorCodes.mjs
-var cacheQuotaExceeded = "cache_quota_exceeded", cacheErrorUnknown = "cache_error_unknown";
-var init_CacheErrorCodes = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/error/CacheError.mjs
-function createCacheError(e4) {
- if (!(e4 instanceof Error)) {
- return new CacheError(cacheErrorUnknown);
- }
- if (e4.name === "QuotaExceededError" || e4.name === "NS_ERROR_DOM_QUOTA_REACHED" || e4.message.includes("exceeded the quota")) {
- return new CacheError(cacheQuotaExceeded);
- } else {
- return new CacheError(e4.name, e4.message);
- }
-}
-var CacheError;
-var init_CacheError = __esm(() => {
- init_CacheErrorCodes();
- init_AuthError();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- CacheError = class CacheError extends Error {
- constructor(errorCode, errorMessage2) {
- const message = errorMessage2 || getDefaultErrorMessage(errorCode);
- super(message);
- Object.setPrototypeOf(this, CacheError.prototype);
- this.name = "CacheError";
- this.errorCode = errorCode;
- this.errorMessage = message;
- }
- };
-});
-
-// node_modules/@azure/msal-common/dist/account/ClientInfo.mjs
-function buildClientInfo(rawClientInfo, base64Decode) {
- if (!rawClientInfo) {
- throw createClientAuthError(clientInfoEmptyError);
- }
- try {
- const decodedClientInfo = base64Decode(rawClientInfo);
- return JSON.parse(decodedClientInfo);
- } catch (e4) {
- throw createClientAuthError(clientInfoDecodingError);
- }
-}
-function buildClientInfoFromHomeAccountId(homeAccountId) {
- if (!homeAccountId) {
- throw createClientAuthError(clientInfoDecodingError);
- }
- const clientInfoParts = homeAccountId.split(CLIENT_INFO_SEPARATOR, 2);
- return {
- uid: clientInfoParts[0],
- utid: clientInfoParts.length < 2 ? "" : clientInfoParts[1]
- };
-}
-var init_ClientInfo = __esm(() => {
- init_ClientAuthError();
- init_Constants();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/authority/AuthorityType.mjs
-var AuthorityType;
-var init_AuthorityType = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- AuthorityType = {
- Default: 0,
- Adfs: 1,
- Dsts: 2,
- Ciam: 3
- };
-});
-
-// node_modules/@azure/msal-common/dist/account/TokenClaims.mjs
-function getTenantIdFromIdTokenClaims(idTokenClaims) {
- if (idTokenClaims) {
- const tenantId = idTokenClaims.tid || idTokenClaims.tfp || idTokenClaims.acr;
- return tenantId || null;
- }
- return null;
-}
-var init_TokenClaims = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/authority/ProtocolMode.mjs
-var ProtocolMode;
-var init_ProtocolMode = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- ProtocolMode = {
- AAD: "AAD",
- OIDC: "OIDC",
- EAR: "EAR"
- };
-});
-
-// node_modules/@azure/msal-common/dist/cache/utils/AccountEntityUtils.mjs
-var exports_AccountEntityUtils = {};
-__export(exports_AccountEntityUtils, {
- isSingleTenant: () => isSingleTenant,
- isAccountEntity: () => isAccountEntity,
- getAccountInfo: () => getAccountInfo,
- generateHomeAccountId: () => generateHomeAccountId,
- generateAccountId: () => generateAccountId,
- createAccountEntityFromAccountInfo: () => createAccountEntityFromAccountInfo,
- createAccountEntity: () => createAccountEntity
-});
-function generateAccountId(accountEntity) {
- const accountId = [
- accountEntity.homeAccountId,
- accountEntity.environment
- ];
- return accountId.join(CACHE_KEY_SEPARATOR).toLowerCase();
-}
-function getAccountInfo(accountEntity) {
- const tenantProfiles = accountEntity.tenantProfiles || [];
- if (tenantProfiles.length === 0 && accountEntity.realm && accountEntity.localAccountId) {
- tenantProfiles.push(buildTenantProfile(accountEntity.homeAccountId, accountEntity.localAccountId, accountEntity.realm));
- }
- return {
- homeAccountId: accountEntity.homeAccountId,
- environment: accountEntity.environment,
- tenantId: accountEntity.realm,
- username: accountEntity.username,
- localAccountId: accountEntity.localAccountId,
- loginHint: accountEntity.loginHint,
- name: accountEntity.name,
- nativeAccountId: accountEntity.nativeAccountId,
- authorityType: accountEntity.authorityType,
- tenantProfiles: new Map(tenantProfiles.map((tenantProfile) => {
- return [tenantProfile.tenantId, tenantProfile];
- })),
- dataBoundary: accountEntity.dataBoundary
- };
-}
-function isSingleTenant(accountEntity) {
- return !accountEntity.tenantProfiles;
-}
-function createAccountEntity(accountDetails, authority, base64Decode) {
- let authorityType;
- if (authority.authorityType === AuthorityType.Adfs) {
- authorityType = CACHE_ACCOUNT_TYPE_ADFS;
- } else if (authority.protocolMode === ProtocolMode.OIDC) {
- authorityType = CACHE_ACCOUNT_TYPE_GENERIC;
- } else {
- authorityType = CACHE_ACCOUNT_TYPE_MSSTS;
- }
- let clientInfo;
- let dataBoundary;
- if (accountDetails.clientInfo && base64Decode) {
- clientInfo = buildClientInfo(accountDetails.clientInfo, base64Decode);
- if (clientInfo.xms_tdbr) {
- dataBoundary = clientInfo.xms_tdbr === "EU" ? "EU" : "None";
- }
- }
- const env5 = accountDetails.environment || authority && authority.getPreferredCache();
- if (!env5) {
- throw createClientAuthError(invalidCacheEnvironment);
- }
- const preferredUsername = accountDetails.idTokenClaims?.preferred_username || accountDetails.idTokenClaims?.upn;
- const email3 = accountDetails.idTokenClaims?.emails ? accountDetails.idTokenClaims.emails[0] : null;
- const username = preferredUsername || email3 || "";
- const loginHint = accountDetails.idTokenClaims?.login_hint;
- const realm = clientInfo?.utid || getTenantIdFromIdTokenClaims(accountDetails.idTokenClaims) || "";
- const localAccountId = clientInfo?.uid || accountDetails.idTokenClaims?.oid || accountDetails.idTokenClaims?.sub || "";
- let tenantProfiles;
- if (accountDetails.tenantProfiles) {
- tenantProfiles = accountDetails.tenantProfiles;
- } else {
- const tenantProfile = buildTenantProfile(accountDetails.homeAccountId, localAccountId, realm, accountDetails.idTokenClaims);
- tenantProfiles = [tenantProfile];
- }
- return {
- homeAccountId: accountDetails.homeAccountId,
- environment: env5,
- realm,
- localAccountId,
- username,
- authorityType,
- loginHint,
- clientInfo: accountDetails.clientInfo,
- name: accountDetails.idTokenClaims?.name || "",
- lastModificationTime: undefined,
- lastModificationApp: undefined,
- cloudGraphHostName: accountDetails.cloudGraphHostName,
- msGraphHost: accountDetails.msGraphHost,
- nativeAccountId: accountDetails.nativeAccountId,
- tenantProfiles,
- dataBoundary
- };
-}
-function createAccountEntityFromAccountInfo(accountInfo, cloudGraphHostName, msGraphHost) {
- const tenantProfiles = Array.from(accountInfo.tenantProfiles?.values() || []);
- if (tenantProfiles.length === 0 && accountInfo.tenantId && accountInfo.localAccountId) {
- tenantProfiles.push(buildTenantProfile(accountInfo.homeAccountId, accountInfo.localAccountId, accountInfo.tenantId, accountInfo.idTokenClaims));
- }
- return {
- authorityType: accountInfo.authorityType || CACHE_ACCOUNT_TYPE_GENERIC,
- homeAccountId: accountInfo.homeAccountId,
- localAccountId: accountInfo.localAccountId,
- nativeAccountId: accountInfo.nativeAccountId,
- realm: accountInfo.tenantId,
- environment: accountInfo.environment,
- username: accountInfo.username,
- loginHint: accountInfo.loginHint,
- name: accountInfo.name,
- cloudGraphHostName,
- msGraphHost,
- tenantProfiles,
- dataBoundary: accountInfo.dataBoundary
- };
-}
-function generateHomeAccountId(serverClientInfo, authType, logger10, cryptoObj, correlationId, idTokenClaims) {
- if (!(authType === AuthorityType.Adfs || authType === AuthorityType.Dsts)) {
- if (serverClientInfo) {
- try {
- const clientInfo = buildClientInfo(serverClientInfo, cryptoObj.base64Decode);
- if (clientInfo.uid && clientInfo.utid) {
- return `${clientInfo.uid}.${clientInfo.utid}`;
- }
- } catch (e4) {}
- }
- logger10.warning("No client info in response", correlationId);
- }
- return idTokenClaims?.sub || "";
-}
-function isAccountEntity(entity) {
- if (!entity) {
- return false;
- }
- return entity.hasOwnProperty("homeAccountId") && entity.hasOwnProperty("environment") && entity.hasOwnProperty("realm") && entity.hasOwnProperty("localAccountId") && entity.hasOwnProperty("username") && entity.hasOwnProperty("authorityType");
-}
-var init_AccountEntityUtils = __esm(() => {
- init_Constants();
- init_ClientInfo();
- init_AccountInfo();
- init_ClientAuthError();
- init_AuthorityType();
- init_TokenClaims();
- init_ProtocolMode();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/cache/CacheManager.mjs
-class CacheManager {
- constructor(clientId, cryptoImpl, logger10, performanceClient, staticAuthorityOptions) {
- this.clientId = clientId;
- this.cryptoImpl = cryptoImpl;
- this.commonLogger = logger10.clone(name, version2);
- this.staticAuthorityOptions = staticAuthorityOptions;
- this.performanceClient = performanceClient;
- }
- getAllAccounts(accountFilter = {}, correlationId) {
- return this.buildTenantProfiles(this.getAccountsFilteredBy(accountFilter, correlationId), correlationId, accountFilter);
- }
- getAccountInfoFilteredBy(accountFilter, correlationId) {
- if (Object.keys(accountFilter).length === 0 || Object.values(accountFilter).every((value) => value === null || value === undefined || value === "")) {
- this.commonLogger.warning("getAccountInfoFilteredBy: Account filter is empty or invalid, returning null", correlationId);
- return null;
- }
- const allAccounts = this.getAllAccounts(accountFilter, correlationId);
- if (allAccounts.length > 1) {
- const sortedAccounts = allAccounts.sort((account) => {
- return account.idTokenClaims ? -1 : 1;
- });
- return sortedAccounts[0];
- } else if (allAccounts.length === 1) {
- return allAccounts[0];
- } else {
- return null;
- }
- }
- getBaseAccountInfo(accountFilter, correlationId) {
- const accountEntities = this.getAccountsFilteredBy(accountFilter, correlationId);
- if (accountEntities.length > 0) {
- return getAccountInfo(accountEntities[0]);
- } else {
- return null;
- }
- }
- buildTenantProfiles(cachedAccounts, correlationId, accountFilter) {
- return cachedAccounts.flatMap((accountEntity) => {
- return this.getTenantProfilesFromAccountEntity(accountEntity, correlationId, accountFilter?.tenantId, accountFilter);
- });
- }
- getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter) {
- let tenantedAccountInfo = null;
- let idTokenClaims;
- if (tenantProfileFilter) {
- if (!this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter)) {
- return null;
- }
- }
- const idToken = this.getIdToken(accountInfo, correlationId, tokenKeys, tenantProfile.tenantId);
- if (idToken) {
- idTokenClaims = extractTokenClaims(idToken.secret, this.cryptoImpl.base64Decode);
- if (!this.idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter)) {
- return null;
- }
- }
- tenantedAccountInfo = updateAccountTenantProfileData(accountInfo, tenantProfile, idTokenClaims, idToken?.secret);
- return tenantedAccountInfo;
- }
- getTenantProfilesFromAccountEntity(accountEntity, correlationId, targetTenantId, tenantProfileFilter) {
- const accountInfo = getAccountInfo(accountEntity);
- let searchTenantProfiles = accountInfo.tenantProfiles || new Map;
- const tokenKeys = this.getTokenKeys();
- if (targetTenantId) {
- const tenantProfile = searchTenantProfiles.get(targetTenantId);
- if (tenantProfile) {
- searchTenantProfiles = new Map([
- [targetTenantId, tenantProfile]
- ]);
- } else {
- return [];
- }
- }
- const matchingTenantProfiles = [];
- searchTenantProfiles.forEach((tenantProfile) => {
- const tenantedAccountInfo = this.getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter);
- if (tenantedAccountInfo) {
- matchingTenantProfiles.push(tenantedAccountInfo);
- }
- });
- return matchingTenantProfiles;
- }
- tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter) {
- if (!!tenantProfileFilter.localAccountId && !this.matchLocalAccountIdFromTenantProfile(tenantProfile, tenantProfileFilter.localAccountId)) {
- return false;
- }
- if (!!tenantProfileFilter.name && !(tenantProfile.name === tenantProfileFilter.name)) {
- return false;
- }
- if (tenantProfileFilter.isHomeTenant !== undefined && !(tenantProfile.isHomeTenant === tenantProfileFilter.isHomeTenant)) {
- return false;
- }
- return true;
- }
- idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter) {
- if (tenantProfileFilter) {
- if (!!tenantProfileFilter.localAccountId && !this.matchLocalAccountIdFromTokenClaims(idTokenClaims, tenantProfileFilter.localAccountId)) {
- return false;
- }
- if (!!tenantProfileFilter.loginHint && !this.matchLoginHintFromTokenClaims(idTokenClaims, tenantProfileFilter.loginHint)) {
- return false;
- }
- if (!!tenantProfileFilter.username && !this.matchUsername(idTokenClaims.preferred_username, tenantProfileFilter.username)) {
- return false;
- }
- if (!!tenantProfileFilter.name && !this.matchName(idTokenClaims, tenantProfileFilter.name)) {
- return false;
- }
- if (!!tenantProfileFilter.sid && !this.matchSid(idTokenClaims, tenantProfileFilter.sid)) {
- return false;
- }
- }
- return true;
- }
- async saveCacheRecord(cacheRecord, correlationId, kmsi, apiId, storeInCache) {
- if (!cacheRecord) {
- throw createClientAuthError(invalidCacheRecord);
- }
- try {
- if (!!cacheRecord.account) {
- await this.setAccount(cacheRecord.account, correlationId, kmsi, apiId);
- }
- if (!!cacheRecord.idToken && storeInCache?.idToken !== false) {
- await this.setIdTokenCredential(cacheRecord.idToken, correlationId, kmsi);
- }
- if (!!cacheRecord.accessToken && storeInCache?.accessToken !== false) {
- await this.saveAccessToken(cacheRecord.accessToken, correlationId, kmsi);
- }
- if (!!cacheRecord.refreshToken && storeInCache?.refreshToken !== false) {
- await this.setRefreshTokenCredential(cacheRecord.refreshToken, correlationId, kmsi);
- }
- if (!!cacheRecord.appMetadata) {
- this.setAppMetadata(cacheRecord.appMetadata, correlationId);
- }
- } catch (e4) {
- this.commonLogger?.error(`CacheManager.saveCacheRecord: failed`, correlationId);
- if (e4 instanceof AuthError) {
- throw e4;
- } else {
- throw createCacheError(e4);
- }
- }
- }
- async saveAccessToken(credential, correlationId, kmsi) {
- const accessTokenFilter = {
- clientId: credential.clientId,
- credentialType: credential.credentialType,
- environment: credential.environment,
- homeAccountId: credential.homeAccountId,
- realm: credential.realm,
- tokenType: credential.tokenType
- };
- const tokenKeys = this.getTokenKeys();
- const currentScopes = ScopeSet.fromString(credential.target);
- tokenKeys.accessToken.forEach((key) => {
- if (!this.accessTokenKeyMatchesFilter(key, accessTokenFilter, false)) {
- return;
- }
- const tokenEntity = this.getAccessTokenCredential(key, correlationId);
- if (tokenEntity && this.credentialMatchesFilter(tokenEntity, accessTokenFilter, correlationId)) {
- const tokenScopeSet = ScopeSet.fromString(tokenEntity.target);
- if (tokenScopeSet.intersectingScopeSets(currentScopes)) {
- this.removeAccessToken(key, correlationId);
- }
- }
- });
- await this.setAccessTokenCredential(credential, correlationId, kmsi);
- }
- getAccountsFilteredBy(accountFilter, correlationId) {
- const allAccountKeys = this.getAccountKeys();
- const matchingAccounts = [];
- allAccountKeys.forEach((cacheKey) => {
- const entity = this.getAccount(cacheKey, correlationId);
- if (!entity) {
- return;
- }
- if (!!accountFilter.homeAccountId && !this.matchHomeAccountId(entity, accountFilter.homeAccountId)) {
- return;
- }
- if (!!accountFilter.username && !this.matchUsername(entity.username, accountFilter.username)) {
- return;
- }
- if (!!accountFilter.environment && !this.matchEnvironment(entity, accountFilter.environment, correlationId)) {
- return;
- }
- if (!!accountFilter.realm && !this.matchRealm(entity, accountFilter.realm)) {
- return;
- }
- if (!!accountFilter.nativeAccountId && !this.matchNativeAccountId(entity, accountFilter.nativeAccountId)) {
- return;
- }
- if (!!accountFilter.authorityType && !this.matchAuthorityType(entity, accountFilter.authorityType)) {
- return;
- }
- const tenantProfileFilter = {
- localAccountId: accountFilter?.localAccountId,
- name: accountFilter?.name
- };
- const matchingTenantProfiles = entity.tenantProfiles?.filter((tenantProfile) => {
- return this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter);
- });
- if (matchingTenantProfiles && matchingTenantProfiles.length === 0) {
- return;
- }
- matchingAccounts.push(entity);
- });
- return matchingAccounts;
- }
- credentialMatchesFilter(entity, filter2, correlationId) {
- if (!!filter2.clientId && !this.matchClientId(entity, filter2.clientId)) {
- return false;
- }
- if (!!filter2.userAssertionHash && !this.matchUserAssertionHash(entity, filter2.userAssertionHash)) {
- return false;
- }
- if (typeof filter2.homeAccountId === "string" && !this.matchHomeAccountId(entity, filter2.homeAccountId)) {
- return false;
- }
- if (!!filter2.environment && !this.matchEnvironment(entity, filter2.environment, correlationId)) {
- return false;
- }
- if (!!filter2.realm && !this.matchRealm(entity, filter2.realm)) {
- return false;
- }
- if (!!filter2.credentialType && !this.matchCredentialType(entity, filter2.credentialType)) {
- return false;
- }
- if (!!filter2.familyId && !this.matchFamilyId(entity, filter2.familyId)) {
- return false;
- }
- if (!!filter2.target && !this.matchTarget(entity, filter2.target)) {
- return false;
- }
- if (entity.credentialType === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME) {
- if (!!filter2.tokenType && !this.matchTokenType(entity, filter2.tokenType)) {
- return false;
- }
- if (filter2.tokenType === AuthenticationScheme.SSH) {
- if (filter2.keyId && !this.matchKeyId(entity, filter2.keyId)) {
- return false;
- }
- }
- }
- return true;
- }
- getAppMetadataFilteredBy(filter2, correlationId) {
- const allCacheKeys = this.getKeys();
- const matchingAppMetadata = {};
- allCacheKeys.forEach((cacheKey) => {
- if (!this.isAppMetadata(cacheKey)) {
- return;
- }
- const entity = this.getAppMetadata(cacheKey, correlationId);
- if (!entity) {
- return;
- }
- if (!!filter2.environment && !this.matchEnvironment(entity, filter2.environment, correlationId)) {
- return;
- }
- if (!!filter2.clientId && !this.matchClientId(entity, filter2.clientId)) {
- return;
- }
- matchingAppMetadata[cacheKey] = entity;
- });
- return matchingAppMetadata;
- }
- getAuthorityMetadataByAlias(host, correlationId) {
- const allCacheKeys = this.getAuthorityMetadataKeys();
- let matchedEntity = null;
- allCacheKeys.forEach((cacheKey) => {
- if (!this.isAuthorityMetadata(cacheKey) || cacheKey.indexOf(this.clientId) === -1) {
- return;
- }
- const entity = this.getAuthorityMetadata(cacheKey, correlationId);
- if (!entity) {
- return;
- }
- if (entity.aliases.indexOf(host) === -1) {
- return;
- }
- matchedEntity = entity;
- });
- return matchedEntity;
- }
- removeAllAccounts(correlationId) {
- const accounts = this.getAllAccounts({}, correlationId);
- accounts.forEach((account) => {
- this.removeAccount(account, correlationId);
- });
- }
- removeAccount(account, correlationId) {
- this.removeAccountContext(account, correlationId);
- const accountKeys = this.getAccountKeys();
- const keyFilter = (key) => {
- return key.includes(account.homeAccountId) && key.includes(account.environment);
- };
- accountKeys.filter(keyFilter).forEach((key) => {
- this.removeItem(key, correlationId);
- this.performanceClient.incrementFields({ accountsRemoved: 1 }, correlationId);
- });
- }
- removeAccountContext(account, correlationId) {
- const allTokenKeys = this.getTokenKeys();
- const keyFilter = (key) => {
- return key.includes(account.homeAccountId) && key.includes(account.environment);
- };
- allTokenKeys.idToken.filter(keyFilter).forEach((key) => {
- this.removeIdToken(key, correlationId);
- });
- allTokenKeys.accessToken.filter(keyFilter).forEach((key) => {
- this.removeAccessToken(key, correlationId);
- });
- allTokenKeys.refreshToken.filter(keyFilter).forEach((key) => {
- this.removeRefreshToken(key, correlationId);
- });
- }
- removeAccessToken(key, correlationId) {
- const credential = this.getAccessTokenCredential(key, correlationId);
- if (!credential) {
- return;
- }
- this.removeItem(key, correlationId);
- this.performanceClient.incrementFields({ accessTokensRemoved: 1 }, correlationId);
- if (credential.credentialType.toLowerCase() === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()) {
- if (credential.tokenType === AuthenticationScheme.POP) {
- const accessTokenWithAuthSchemeEntity = credential;
- const kid = accessTokenWithAuthSchemeEntity.keyId;
- if (kid) {
- this.cryptoImpl.removeTokenBindingKey(kid, correlationId).catch(() => {
- this.commonLogger.error(`Failed to remove token binding key '${kid}'`, correlationId);
- this.performanceClient?.incrementFields({ removeTokenBindingKeyFailure: 1 }, correlationId);
- });
- }
- }
- }
- }
- removeAppMetadata(correlationId) {
- const allCacheKeys = this.getKeys();
- allCacheKeys.forEach((cacheKey) => {
- if (this.isAppMetadata(cacheKey)) {
- this.removeItem(cacheKey, correlationId);
- }
- });
- return true;
- }
- getIdToken(account, correlationId, tokenKeys, targetRealm) {
- this.commonLogger.trace("CacheManager - getIdToken called", correlationId);
- const idTokenFilter = {
- homeAccountId: account.homeAccountId,
- environment: account.environment,
- credentialType: CredentialType.ID_TOKEN,
- clientId: this.clientId,
- realm: targetRealm
- };
- const idTokenMap = this.getIdTokensByFilter(idTokenFilter, correlationId, tokenKeys);
- const numIdTokens = idTokenMap.size;
- if (numIdTokens < 1) {
- this.commonLogger.info("CacheManager:getIdToken - No token found", correlationId);
- return null;
- } else if (numIdTokens > 1) {
- let tokensToBeRemoved = idTokenMap;
- if (!targetRealm) {
- const homeIdTokenMap = new Map;
- idTokenMap.forEach((idToken, key) => {
- if (idToken.realm === account.tenantId) {
- homeIdTokenMap.set(key, idToken);
- }
- });
- const numHomeIdTokens = homeIdTokenMap.size;
- if (numHomeIdTokens < 1) {
- this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account but none match account entity tenant id, returning first result", correlationId);
- return idTokenMap.values().next().value;
- } else if (numHomeIdTokens === 1) {
- this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account, defaulting to home tenant profile", correlationId);
- return homeIdTokenMap.values().next().value;
- } else {
- tokensToBeRemoved = homeIdTokenMap;
- }
- }
- this.commonLogger.info("CacheManager:getIdToken - Multiple matching ID tokens found, clearing them", correlationId);
- tokensToBeRemoved.forEach((idToken, key) => {
- this.removeIdToken(key, correlationId);
- });
- this.performanceClient.addFields({ multiMatchedID: idTokenMap.size }, correlationId);
- return null;
- }
- this.commonLogger.info("CacheManager:getIdToken - Returning ID token", correlationId);
- return idTokenMap.values().next().value;
- }
- getIdTokensByFilter(filter2, correlationId, tokenKeys) {
- const idTokenKeys = tokenKeys && tokenKeys.idToken || this.getTokenKeys().idToken;
- const idTokens = new Map;
- idTokenKeys.forEach((key) => {
- if (!this.idTokenKeyMatchesFilter(key, {
- clientId: this.clientId,
- ...filter2
- })) {
- return;
- }
- const idToken = this.getIdTokenCredential(key, correlationId);
- if (idToken && this.credentialMatchesFilter(idToken, filter2, correlationId)) {
- idTokens.set(key, idToken);
- }
- });
- return idTokens;
- }
- idTokenKeyMatchesFilter(inputKey, filter2) {
- const key = inputKey.toLowerCase();
- if (filter2.clientId && key.indexOf(filter2.clientId.toLowerCase()) === -1) {
- return false;
- }
- if (filter2.homeAccountId && key.indexOf(filter2.homeAccountId.toLowerCase()) === -1) {
- return false;
- }
- return true;
- }
- removeIdToken(key, correlationId) {
- this.removeItem(key, correlationId);
- }
- removeRefreshToken(key, correlationId) {
- this.removeItem(key, correlationId);
- }
- getAccessToken(account, request2, tokenKeys, targetRealm) {
- const correlationId = request2.correlationId;
- this.commonLogger.trace("CacheManager - getAccessToken called", correlationId);
- const scopes = ScopeSet.createSearchScopes(request2.scopes);
- const authScheme = request2.authenticationScheme || AuthenticationScheme.BEARER;
- const credentialType = authScheme && authScheme.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase() ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME : CredentialType.ACCESS_TOKEN;
- const accessTokenFilter = {
- homeAccountId: account.homeAccountId,
- environment: account.environment,
- credentialType,
- clientId: this.clientId,
- realm: targetRealm || account.tenantId,
- target: scopes,
- tokenType: authScheme,
- keyId: request2.sshKid
- };
- const accessTokenKeys = tokenKeys && tokenKeys.accessToken || this.getTokenKeys().accessToken;
- const accessTokens = [];
- accessTokenKeys.forEach((key) => {
- if (this.accessTokenKeyMatchesFilter(key, accessTokenFilter, true)) {
- const accessToken = this.getAccessTokenCredential(key, correlationId);
- if (accessToken && this.credentialMatchesFilter(accessToken, accessTokenFilter, correlationId)) {
- accessTokens.push(accessToken);
- }
- }
- });
- const numAccessTokens = accessTokens.length;
- if (numAccessTokens < 1) {
- this.commonLogger.info("CacheManager:getAccessToken - No token found", correlationId);
- return null;
- } else if (numAccessTokens > 1) {
- this.commonLogger.info("CacheManager:getAccessToken - Multiple access tokens found, clearing them", correlationId);
- accessTokens.forEach((accessToken) => {
- this.removeAccessToken(this.generateCredentialKey(accessToken), correlationId);
- });
- this.performanceClient.addFields({ multiMatchedAT: accessTokens.length }, correlationId);
- return null;
- }
- this.commonLogger.info("CacheManager:getAccessToken - Returning access token", correlationId);
- return accessTokens[0];
- }
- accessTokenKeyMatchesFilter(inputKey, filter2, keyMustContainAllScopes) {
- const key = inputKey.toLowerCase();
- if (filter2.clientId && key.indexOf(filter2.clientId.toLowerCase()) === -1) {
- return false;
- }
- if (filter2.homeAccountId && key.indexOf(filter2.homeAccountId.toLowerCase()) === -1) {
- return false;
- }
- if (filter2.realm && key.indexOf(filter2.realm.toLowerCase()) === -1) {
- return false;
- }
- if (filter2.target) {
- const scopes = filter2.target.asArray();
- for (let i5 = 0;i5 < scopes.length; i5++) {
- if (keyMustContainAllScopes && !key.includes(scopes[i5].toLowerCase())) {
- return false;
- } else if (!keyMustContainAllScopes && key.includes(scopes[i5].toLowerCase())) {
- return true;
- }
- }
- }
- return true;
- }
- getAccessTokensByFilter(filter2, correlationId) {
- const tokenKeys = this.getTokenKeys();
- const accessTokens = [];
- tokenKeys.accessToken.forEach((key) => {
- if (!this.accessTokenKeyMatchesFilter(key, filter2, true)) {
- return;
- }
- const accessToken = this.getAccessTokenCredential(key, correlationId);
- if (accessToken && this.credentialMatchesFilter(accessToken, filter2, correlationId)) {
- accessTokens.push(accessToken);
- }
- });
- return accessTokens;
- }
- getRefreshToken(account, familyRT, correlationId, tokenKeys) {
- this.commonLogger.trace("CacheManager - getRefreshToken called", correlationId);
- const id = familyRT ? THE_FAMILY_ID : undefined;
- const refreshTokenFilter = {
- homeAccountId: account.homeAccountId,
- environment: account.environment,
- credentialType: CredentialType.REFRESH_TOKEN,
- clientId: this.clientId,
- familyId: id
- };
- const refreshTokenKeys = tokenKeys && tokenKeys.refreshToken || this.getTokenKeys().refreshToken;
- const refreshTokens = [];
- refreshTokenKeys.forEach((key) => {
- if (this.refreshTokenKeyMatchesFilter(key, refreshTokenFilter)) {
- const refreshToken = this.getRefreshTokenCredential(key, correlationId);
- if (refreshToken && this.credentialMatchesFilter(refreshToken, refreshTokenFilter, correlationId)) {
- refreshTokens.push(refreshToken);
- }
- }
- });
- const numRefreshTokens = refreshTokens.length;
- if (numRefreshTokens < 1) {
- this.commonLogger.info("CacheManager:getRefreshToken - No refresh token found.", correlationId);
- return null;
- }
- if (numRefreshTokens > 1) {
- this.performanceClient.addFields({ multiMatchedRT: numRefreshTokens }, correlationId);
- }
- this.commonLogger.info("CacheManager:getRefreshToken - returning refresh token", correlationId);
- return refreshTokens[0];
- }
- refreshTokenKeyMatchesFilter(inputKey, filter2) {
- const key = inputKey.toLowerCase();
- if (filter2.familyId && key.indexOf(filter2.familyId.toLowerCase()) === -1) {
- return false;
- }
- if (!filter2.familyId && filter2.clientId && key.indexOf(filter2.clientId.toLowerCase()) === -1) {
- return false;
- }
- if (filter2.homeAccountId && key.indexOf(filter2.homeAccountId.toLowerCase()) === -1) {
- return false;
- }
- return true;
- }
- readAppMetadataFromCache(environment, correlationId) {
- const appMetadataFilter = {
- environment,
- clientId: this.clientId
- };
- const appMetadata = this.getAppMetadataFilteredBy(appMetadataFilter, correlationId);
- const appMetadataEntries = Object.keys(appMetadata).map((key) => appMetadata[key]);
- const numAppMetadata = appMetadataEntries.length;
- if (numAppMetadata < 1) {
- return null;
- } else if (numAppMetadata > 1) {
- throw createClientAuthError(multipleMatchingAppMetadata);
- }
- return appMetadataEntries[0];
- }
- isAppMetadataFOCI(environment, correlationId) {
- const appMetadata = this.readAppMetadataFromCache(environment, correlationId);
- return !!(appMetadata && appMetadata.familyId === THE_FAMILY_ID);
- }
- matchHomeAccountId(entity, homeAccountId) {
- return !!(typeof entity.homeAccountId === "string" && homeAccountId === entity.homeAccountId);
- }
- matchLocalAccountIdFromTokenClaims(tokenClaims, localAccountId) {
- const idTokenLocalAccountId = tokenClaims.oid || tokenClaims.sub;
- return localAccountId === idTokenLocalAccountId;
- }
- matchLocalAccountIdFromTenantProfile(tenantProfile, localAccountId) {
- return tenantProfile.localAccountId === localAccountId;
- }
- matchName(claims, name2) {
- return !!(name2.toLowerCase() === claims.name?.toLowerCase());
- }
- matchUsername(cachedUsername, filterUsername) {
- return !!(cachedUsername && typeof cachedUsername === "string" && filterUsername?.toLowerCase() === cachedUsername.toLowerCase());
- }
- matchUserAssertionHash(entity, userAssertionHash) {
- return !!(entity.userAssertionHash && userAssertionHash === entity.userAssertionHash);
- }
- matchEnvironment(entity, environment, correlationId) {
- if (this.staticAuthorityOptions) {
- const staticAliases = getAliasesFromStaticSources(this.staticAuthorityOptions, this.commonLogger, correlationId);
- if (staticAliases.includes(environment) && staticAliases.includes(entity.environment)) {
- return true;
- }
- }
- const cloudMetadata = this.getAuthorityMetadataByAlias(environment, correlationId);
- if (cloudMetadata && cloudMetadata.aliases.indexOf(entity.environment) > -1) {
- return true;
- }
- return false;
- }
- matchCredentialType(entity, credentialType) {
- return entity.credentialType && credentialType.toLowerCase() === entity.credentialType.toLowerCase();
- }
- matchClientId(entity, clientId) {
- return !!(entity.clientId && clientId === entity.clientId);
- }
- matchFamilyId(entity, familyId) {
- return !!(entity.familyId && familyId === entity.familyId);
- }
- matchRealm(entity, realm) {
- return !!(entity.realm?.toLowerCase() === realm.toLowerCase());
- }
- matchNativeAccountId(entity, nativeAccountId) {
- return !!(entity.nativeAccountId && nativeAccountId === entity.nativeAccountId);
- }
- matchLoginHintFromTokenClaims(tokenClaims, loginHint) {
- if (tokenClaims.login_hint === loginHint) {
- return true;
- }
- if (tokenClaims.preferred_username === loginHint) {
- return true;
- }
- if (tokenClaims.upn === loginHint) {
- return true;
- }
- return false;
- }
- matchSid(idTokenClaims, sid) {
- return idTokenClaims.sid === sid;
- }
- matchAuthorityType(entity, authorityType) {
- return !!(entity.authorityType && authorityType.toLowerCase() === entity.authorityType.toLowerCase());
- }
- matchTarget(entity, target) {
- const isNotAccessTokenCredential = entity.credentialType !== CredentialType.ACCESS_TOKEN && entity.credentialType !== CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;
- if (isNotAccessTokenCredential || !entity.target) {
- return false;
- }
- const entityScopeSet = ScopeSet.fromString(entity.target);
- return entityScopeSet.containsScopeSet(target);
- }
- matchTokenType(entity, tokenType) {
- return !!(entity.tokenType && entity.tokenType === tokenType);
- }
- matchKeyId(entity, keyId) {
- return !!(entity.keyId && entity.keyId === keyId);
- }
- isAppMetadata(key) {
- return key.indexOf(APP_METADATA) !== -1;
- }
- isAuthorityMetadata(key) {
- return key.indexOf(AUTHORITY_METADATA_CACHE_KEY) !== -1;
- }
- generateAuthorityMetadataCacheKey(authority) {
- return `${AUTHORITY_METADATA_CACHE_KEY}-${this.clientId}-${authority}`;
- }
- static toObject(obj, json2) {
- for (const propertyName in json2) {
- obj[propertyName] = json2[propertyName];
- }
- return obj;
- }
-}
-var DefaultStorageClass;
-var init_CacheManager = __esm(() => {
- init_Constants();
- init_ScopeSet();
- init_ClientAuthError();
- init_AccountInfo();
- init_AuthToken();
- init_packageMetadata();
- init_AuthorityMetadata();
- init_CacheError();
- init_AccountEntityUtils();
- init_AuthError();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- DefaultStorageClass = class DefaultStorageClass extends CacheManager {
- async setAccount() {
- throw createClientAuthError(methodNotImplemented);
- }
- getAccount() {
- throw createClientAuthError(methodNotImplemented);
- }
- async setIdTokenCredential() {
- throw createClientAuthError(methodNotImplemented);
- }
- getIdTokenCredential() {
- throw createClientAuthError(methodNotImplemented);
- }
- async setAccessTokenCredential() {
- throw createClientAuthError(methodNotImplemented);
- }
- getAccessTokenCredential() {
- throw createClientAuthError(methodNotImplemented);
- }
- async setRefreshTokenCredential() {
- throw createClientAuthError(methodNotImplemented);
- }
- getRefreshTokenCredential() {
- throw createClientAuthError(methodNotImplemented);
- }
- setAppMetadata() {
- throw createClientAuthError(methodNotImplemented);
- }
- getAppMetadata() {
- throw createClientAuthError(methodNotImplemented);
- }
- setServerTelemetry() {
- throw createClientAuthError(methodNotImplemented);
- }
- getServerTelemetry() {
- throw createClientAuthError(methodNotImplemented);
- }
- setAuthorityMetadata() {
- throw createClientAuthError(methodNotImplemented);
- }
- getAuthorityMetadata() {
- throw createClientAuthError(methodNotImplemented);
- }
- getAuthorityMetadataKeys() {
- throw createClientAuthError(methodNotImplemented);
- }
- setThrottlingCache() {
- throw createClientAuthError(methodNotImplemented);
- }
- getThrottlingCache() {
- throw createClientAuthError(methodNotImplemented);
- }
- removeItem() {
- throw createClientAuthError(methodNotImplemented);
- }
- getKeys() {
- throw createClientAuthError(methodNotImplemented);
- }
- getAccountKeys() {
- throw createClientAuthError(methodNotImplemented);
- }
- getTokenKeys() {
- throw createClientAuthError(methodNotImplemented);
- }
- generateCredentialKey() {
- throw createClientAuthError(methodNotImplemented);
- }
- generateAccountKey() {
- throw createClientAuthError(methodNotImplemented);
- }
- };
-});
-
-// node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.mjs
-var PerformanceEventStatus, IntFields;
-var init_PerformanceEvent = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- PerformanceEventStatus = {
- NotStarted: 0,
- InProgress: 1,
- Completed: 2
- };
- IntFields = new Set([
- "accessTokenSize",
- "durationMs",
- "idTokenSize",
- "matsSilentStatus",
- "matsHttpStatus",
- "refreshTokenSize",
- "startTimeMs",
- "status",
- "multiMatchedAT",
- "multiMatchedID",
- "multiMatchedRT",
- "unencryptedCacheCount",
- "encryptedCacheExpiredCount",
- "oldAccountCount",
- "oldAccessCount",
- "oldIdCount",
- "oldRefreshCount",
- "currAccountCount",
- "currAccessCount",
- "currIdCount",
- "currRefreshCount",
- "expiredCacheRemovedCount",
- "upgradedCacheCount",
- "networkRtt",
- "redirectBridgeTimeoutMs",
- "redirectBridgeMessageVersion"
- ]);
-});
-
-// node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.mjs
-class StubPerformanceClient {
- generateId() {
- return "callback-id";
- }
- startMeasurement(measureName, correlationId) {
- return {
- end: () => null,
- discard: () => {},
- add: () => {},
- increment: () => {},
- event: {
- eventId: this.generateId(),
- status: PerformanceEventStatus.InProgress,
- authority: "",
- libraryName: "",
- libraryVersion: "",
- clientId: "",
- name: measureName,
- startTimeMs: Date.now(),
- correlationId: correlationId || ""
- }
- };
- }
- endMeasurement() {
- return null;
- }
- discardMeasurements() {
- return;
- }
- removePerformanceCallback() {
- return true;
- }
- addPerformanceCallback() {
- return "";
- }
- emitEvents() {
- return;
- }
- addFields() {
- return;
- }
- incrementFields() {
- return;
- }
- cacheEventByCorrelationId() {
- return;
- }
-}
-var init_StubPerformanceClient = __esm(() => {
- init_PerformanceEvent();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/config/ClientConfiguration.mjs
-function buildClientConfiguration({ authOptions: userAuthOptions, systemOptions: userSystemOptions, loggerOptions: userLoggerOption, storageInterface: storageImplementation, networkInterface: networkImplementation, cryptoInterface: cryptoImplementation, clientCredentials, libraryInfo, telemetry, serverTelemetryManager, persistencePlugin, serializableCache }) {
- const loggerOptions = {
- ...DEFAULT_LOGGER_IMPLEMENTATION,
- ...userLoggerOption
- };
- return {
- authOptions: buildAuthOptions(userAuthOptions),
- systemOptions: { ...DEFAULT_SYSTEM_OPTIONS, ...userSystemOptions },
- loggerOptions,
- storageInterface: storageImplementation || new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION, new Logger(loggerOptions), new StubPerformanceClient),
- networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION,
- cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION,
- clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS,
- libraryInfo: { ...DEFAULT_LIBRARY_INFO, ...libraryInfo },
- telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry },
- serverTelemetryManager: serverTelemetryManager || null,
- persistencePlugin: persistencePlugin || null,
- serializableCache: serializableCache || null
- };
-}
-function buildAuthOptions(authOptions) {
- return {
- clientCapabilities: [],
- azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS,
- instanceAware: false,
- isMcp: false,
- ...authOptions
- };
-}
-function isOidcProtocolMode(config8) {
- return config8.authOptions.authority.options.protocolMode === ProtocolMode.OIDC;
-}
-var DEFAULT_SYSTEM_OPTIONS, DEFAULT_LOGGER_IMPLEMENTATION, DEFAULT_NETWORK_IMPLEMENTATION, DEFAULT_LIBRARY_INFO, DEFAULT_CLIENT_CREDENTIALS, DEFAULT_AZURE_CLOUD_OPTIONS, DEFAULT_TELEMETRY_OPTIONS;
-var init_ClientConfiguration = __esm(() => {
- init_ICrypto();
- init_Logger();
- init_Constants();
- init_packageMetadata();
- init_AuthorityOptions();
- init_CacheManager();
- init_ProtocolMode();
- init_ClientAuthError();
- init_StubPerformanceClient();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- DEFAULT_SYSTEM_OPTIONS = {
- tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,
- preventCorsPreflight: false
- };
- DEFAULT_LOGGER_IMPLEMENTATION = {
- loggerCallback: () => {},
- piiLoggingEnabled: false,
- logLevel: LogLevel.Info,
- correlationId: ""
- };
- DEFAULT_NETWORK_IMPLEMENTATION = {
- async sendGetRequestAsync() {
- throw createClientAuthError(methodNotImplemented);
- },
- async sendPostRequestAsync() {
- throw createClientAuthError(methodNotImplemented);
- }
- };
- DEFAULT_LIBRARY_INFO = {
- sku: SKU,
- version: version2,
- cpu: "",
- os: ""
- };
- DEFAULT_CLIENT_CREDENTIALS = {
- clientSecret: "",
- clientAssertion: undefined
- };
- DEFAULT_AZURE_CLOUD_OPTIONS = {
- azureCloudInstance: AzureCloudInstance.None,
- tenant: `${DEFAULT_COMMON_TENANT}`
- };
- DEFAULT_TELEMETRY_OPTIONS = {
- application: {
- appName: "",
- appVersion: ""
- }
- };
-});
-
-// node_modules/@azure/msal-common/dist/error/ServerError.mjs
-var ServerError;
-var init_ServerError = __esm(() => {
- init_AuthError();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- ServerError = class ServerError extends AuthError {
- constructor(errorCode, errorMessage2, subError, errorNo, status) {
- super(errorCode, errorMessage2, subError);
- this.name = "ServerError";
- this.errorNo = errorNo;
- this.status = status;
- Object.setPrototypeOf(this, ServerError.prototype);
- }
- };
-});
-
-// node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthErrorCodes.mjs
-var exports_InteractionRequiredAuthErrorCodes = {};
-__export(exports_InteractionRequiredAuthErrorCodes, {
- uxNotAllowed: () => uxNotAllowed,
- refreshTokenExpired: () => refreshTokenExpired,
- noTokensFound: () => noTokensFound,
- nativeAccountUnavailable: () => nativeAccountUnavailable,
- loginRequired: () => loginRequired,
- interruptedUser: () => interruptedUser,
- interactionRequired: () => interactionRequired,
- consentRequired: () => consentRequired,
- badToken: () => badToken
-});
-var noTokensFound = "no_tokens_found", nativeAccountUnavailable = "native_account_unavailable", refreshTokenExpired = "refresh_token_expired", uxNotAllowed = "ux_not_allowed", interactionRequired = "interaction_required", consentRequired = "consent_required", loginRequired = "login_required", badToken = "bad_token", interruptedUser = "interrupted_user";
-var init_InteractionRequiredAuthErrorCodes = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.mjs
-function isInteractionRequiredError(errorCode, errorString, subError) {
- const isInteractionRequiredErrorCode = !!errorCode && InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1;
- const isInteractionRequiredSubError = !!subError && InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1;
- const isInteractionRequiredErrorDesc = !!errorString && InteractionRequiredServerErrorMessage.some((irErrorCode) => {
- return errorString.indexOf(irErrorCode) > -1;
- });
- return isInteractionRequiredErrorCode || isInteractionRequiredErrorDesc || isInteractionRequiredSubError;
-}
-function createInteractionRequiredAuthError(errorCode, errorMessage2) {
- return new InteractionRequiredAuthError(errorCode, errorMessage2);
-}
-var InteractionRequiredServerErrorMessage, InteractionRequiredAuthSubErrorMessage, InteractionRequiredAuthError;
-var init_InteractionRequiredAuthError = __esm(() => {
- init_AuthError();
- init_InteractionRequiredAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- InteractionRequiredServerErrorMessage = [
- interactionRequired,
- consentRequired,
- loginRequired,
- badToken,
- uxNotAllowed,
- interruptedUser
- ];
- InteractionRequiredAuthSubErrorMessage = [
- "message_only",
- "additional_action",
- "basic_action",
- "user_password_expired",
- "consent_required",
- "bad_token",
- "ux_not_allowed",
- "interrupted_user"
- ];
- InteractionRequiredAuthError = class InteractionRequiredAuthError extends AuthError {
- constructor(errorCode, errorMessage2, subError, timestamp, traceId, correlationId, claims, errorNo) {
- super(errorCode, errorMessage2, subError);
- Object.setPrototypeOf(this, InteractionRequiredAuthError.prototype);
- this.timestamp = timestamp || "";
- this.traceId = traceId || "";
- this.correlationId = correlationId || "";
- this.claims = claims || "";
- this.name = "InteractionRequiredAuthError";
- this.errorNo = errorNo;
- }
- };
-});
-
-// node_modules/@azure/msal-common/dist/utils/ProtocolUtils.mjs
-function parseRequestState(base64Decode, state2) {
- if (!base64Decode) {
- throw createClientAuthError(noCryptoObject);
- }
- if (!state2) {
- throw createClientAuthError(invalidState);
- }
- try {
- const splitState = state2.split(RESOURCE_DELIM);
- const libraryState = splitState[0];
- const userState = splitState.length > 1 ? splitState.slice(1).join(RESOURCE_DELIM) : "";
- const libraryStateString = base64Decode(libraryState);
- const libraryStateObj = JSON.parse(libraryStateString);
- return {
- userRequestState: userState || "",
- libraryState: libraryStateObj
- };
- } catch (e4) {
- throw createClientAuthError(invalidState);
- }
-}
-var init_ProtocolUtils = __esm(() => {
- init_Constants();
- init_ClientAuthError();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/utils/TimeUtils.mjs
-var exports_TimeUtils = {};
-__export(exports_TimeUtils, {
- wasClockTurnedBack: () => wasClockTurnedBack,
- toSecondsFromDate: () => toSecondsFromDate,
- toDateFromSeconds: () => toDateFromSeconds,
- nowSeconds: () => nowSeconds,
- isTokenExpired: () => isTokenExpired,
- isCacheExpired: () => isCacheExpired,
- delay: () => delay
-});
-function nowSeconds() {
- return Math.round(new Date().getTime() / 1000);
-}
-function toSecondsFromDate(date5) {
- return date5.getTime() / 1000;
-}
-function toDateFromSeconds(seconds) {
- if (seconds) {
- return new Date(Number(seconds) * 1000);
- }
- return new Date;
-}
-function isTokenExpired(expiresOn, offset) {
- const expirationSec = Number(expiresOn) || 0;
- const offsetCurrentTimeSec = nowSeconds() + offset;
- return offsetCurrentTimeSec > expirationSec;
-}
-function isCacheExpired(lastUpdatedAt, cacheRetentionDays) {
- const cacheExpirationTimestamp = Number(lastUpdatedAt) + cacheRetentionDays * 24 * 60 * 60 * 1000;
- return Date.now() > cacheExpirationTimestamp;
-}
-function wasClockTurnedBack(cachedAt) {
- const cachedAtSec = Number(cachedAt);
- return cachedAtSec > nowSeconds();
-}
-function delay(t4, value) {
- return new Promise((resolve9) => setTimeout(() => resolve9(value), t4));
-}
-var init_TimeUtils = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvents.mjs
-var NetworkClientSendPostRequestAsync = "networkClientSendPostRequestAsync", RefreshTokenClientExecutePostToTokenEndpoint = "refreshTokenClientExecutePostToTokenEndpoint", AuthorizationCodeClientExecutePostToTokenEndpoint = "authorizationCodeClientExecutePostToTokenEndpoint", RefreshTokenClientExecuteTokenRequest = "refreshTokenClientExecuteTokenRequest", RefreshTokenClientAcquireToken = "refreshTokenClientAcquireToken", RefreshTokenClientAcquireTokenWithCachedRefreshToken = "refreshTokenClientAcquireTokenWithCachedRefreshToken", RefreshTokenClientCreateTokenRequestBody = "refreshTokenClientCreateTokenRequestBody", SilentFlowClientGenerateResultFromCacheRecord = "silentFlowClientGenerateResultFromCacheRecord", AuthClientExecuteTokenRequest = "authClientExecuteTokenRequest", AuthClientCreateTokenRequestBody = "authClientCreateTokenRequestBody", UpdateTokenEndpointAuthority = "updateTokenEndpointAuthority", PopTokenGenerateCnf = "popTokenGenerateCnf", HandleServerTokenResponse = "handleServerTokenResponse", AuthorityResolveEndpointsAsync = "authorityResolveEndpointsAsync", AuthorityGetCloudDiscoveryMetadataFromNetwork = "authorityGetCloudDiscoveryMetadataFromNetwork", AuthorityUpdateCloudDiscoveryMetadata = "authorityUpdateCloudDiscoveryMetadata", AuthorityGetEndpointMetadataFromNetwork = "authorityGetEndpointMetadataFromNetwork", AuthorityUpdateEndpointMetadata = "authorityUpdateEndpointMetadata", AuthorityUpdateMetadataWithRegionalInformation = "authorityUpdateMetadataWithRegionalInformation", RegionDiscoveryDetectRegion = "regionDiscoveryDetectRegion", RegionDiscoveryGetRegionFromIMDS = "regionDiscoveryGetRegionFromIMDS", RegionDiscoveryGetCurrentVersion = "regionDiscoveryGetCurrentVersion", CacheManagerGetRefreshToken = "cacheManagerGetRefreshToken";
-var init_PerformanceEvents = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/utils/FunctionWrappers.mjs
-var invoke = (callback, eventName, logger10, telemetryClient, correlationId) => {
- return (...args) => {
- logger10.trace(`Executing function '${eventName}'`, correlationId);
- const inProgressEvent = telemetryClient.startMeasurement(eventName, correlationId);
- if (correlationId) {
- telemetryClient.incrementFields({ [`ext.${eventName}CallCount`]: 1 }, correlationId);
- }
- try {
- const result = callback(...args);
- inProgressEvent.end({
- success: true
- });
- logger10.trace(`Returning result from '${eventName}'`, correlationId);
- return result;
- } catch (e4) {
- logger10.trace(`Error occurred in '${eventName}'`, correlationId);
- try {
- logger10.trace(JSON.stringify(e4), correlationId);
- } catch (e5) {
- logger10.trace("Unable to print error message.", correlationId);
- }
- inProgressEvent.end({
- success: false
- }, e4);
- throw e4;
- }
- };
-}, invokeAsync = (callback, eventName, logger10, telemetryClient, correlationId) => {
- return (...args) => {
- logger10.trace(`Executing function '${eventName}'`, correlationId);
- const inProgressEvent = telemetryClient.startMeasurement(eventName, correlationId);
- if (correlationId) {
- telemetryClient.incrementFields({ [`ext.${eventName}CallCount`]: 1 }, correlationId);
- }
- return callback(...args).then((response7) => {
- logger10.trace(`Returning result from '${eventName}'`, correlationId);
- inProgressEvent.end({
- success: true
- });
- return response7;
- }).catch((e4) => {
- logger10.trace(`Error occurred in '${eventName}'`, correlationId);
- try {
- logger10.trace(JSON.stringify(e4), correlationId);
- } catch (e5) {
- logger10.trace("Unable to print error message.", correlationId);
- }
- inProgressEvent.end({
- success: false
- }, e4);
- throw e4;
- });
- };
-};
-var init_FunctionWrappers = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.mjs
-class PopTokenGenerator {
- constructor(cryptoUtils, performanceClient) {
- this.cryptoUtils = cryptoUtils;
- this.performanceClient = performanceClient;
- }
- async generateCnf(request2, logger10) {
- const reqCnf = await invokeAsync(this.generateKid.bind(this), PopTokenGenerateCnf, logger10, this.performanceClient, request2.correlationId)(request2);
- const reqCnfString = this.cryptoUtils.base64UrlEncode(JSON.stringify(reqCnf));
- return {
- kid: reqCnf.kid,
- reqCnfString
- };
- }
- async generateKid(request2) {
- const kidThumbprint = await this.cryptoUtils.getPublicKeyThumbprint(request2);
- return {
- kid: kidThumbprint,
- xms_ksl: KeyLocation.SW
- };
- }
- async signPopToken(accessToken, keyId, request2) {
- return this.signPayload(accessToken, keyId, request2);
- }
- async signPayload(payload, keyId, request2, claims) {
- const { resourceRequestMethod, resourceRequestUri, shrClaims, shrNonce, shrOptions } = request2;
- const resourceUrlString = resourceRequestUri ? new UrlString(resourceRequestUri) : undefined;
- const resourceUrlComponents = resourceUrlString?.getUrlComponents();
- return this.cryptoUtils.signJwt({
- at: payload,
- ts: nowSeconds(),
- m: resourceRequestMethod?.toUpperCase(),
- u: resourceUrlComponents?.HostNameAndPort,
- nonce: shrNonce || this.cryptoUtils.createNewGuid(),
- p: resourceUrlComponents?.AbsolutePath,
- q: resourceUrlComponents?.QueryString ? [[], resourceUrlComponents.QueryString] : undefined,
- client_claims: shrClaims || undefined,
- ...claims
- }, keyId, shrOptions, request2.correlationId);
- }
-}
-var KeyLocation;
-var init_PopTokenGenerator = __esm(() => {
- init_TimeUtils();
- init_UrlString();
- init_PerformanceEvents();
- init_FunctionWrappers();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- KeyLocation = {
- SW: "sw"
- };
-});
-
-// node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.mjs
-class TokenCacheContext {
- constructor(tokenCache, hasChanged) {
- this.cache = tokenCache;
- this.hasChanged = hasChanged;
- }
- get cacheHasChanged() {
- return this.hasChanged;
- }
- get tokenCache() {
- return this.cache;
- }
-}
-var init_TokenCacheContext = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/cache/utils/CacheHelpers.mjs
-var exports_CacheHelpers = {};
-__export(exports_CacheHelpers, {
- updateCloudDiscoveryMetadata: () => updateCloudDiscoveryMetadata,
- updateAuthorityEndpointMetadata: () => updateAuthorityEndpointMetadata,
- isThrottlingEntity: () => isThrottlingEntity,
- isServerTelemetryEntity: () => isServerTelemetryEntity,
- isRefreshTokenEntity: () => isRefreshTokenEntity,
- isIdTokenEntity: () => isIdTokenEntity,
- isCredentialEntity: () => isCredentialEntity,
- isAuthorityMetadataExpired: () => isAuthorityMetadataExpired,
- isAuthorityMetadataEntity: () => isAuthorityMetadataEntity,
- isAppMetadataEntity: () => isAppMetadataEntity,
- isAccessTokenEntity: () => isAccessTokenEntity,
- generateAuthorityMetadataExpiresAt: () => generateAuthorityMetadataExpiresAt,
- generateAppMetadataKey: () => generateAppMetadataKey,
- createRefreshTokenEntity: () => createRefreshTokenEntity,
- createIdTokenEntity: () => createIdTokenEntity,
- createAccessTokenEntity: () => createAccessTokenEntity
-});
-function createIdTokenEntity(homeAccountId, environment, idToken, clientId, tenantId) {
- const idTokenEntity = {
- credentialType: CredentialType.ID_TOKEN,
- homeAccountId,
- environment,
- clientId,
- secret: idToken,
- realm: tenantId,
- lastUpdatedAt: Date.now().toString()
- };
- return idTokenEntity;
-}
-function createAccessTokenEntity(homeAccountId, environment, accessToken, clientId, tenantId, scopes, expiresOn, extExpiresOn, base64Decode, refreshOn, tokenType, userAssertionHash, keyId) {
- const atEntity = {
- homeAccountId,
- credentialType: CredentialType.ACCESS_TOKEN,
- secret: accessToken,
- cachedAt: nowSeconds().toString(),
- expiresOn: expiresOn.toString(),
- extendedExpiresOn: extExpiresOn.toString(),
- environment,
- clientId,
- realm: tenantId,
- target: scopes,
- tokenType: tokenType || AuthenticationScheme.BEARER,
- lastUpdatedAt: Date.now().toString()
- };
- if (userAssertionHash) {
- atEntity.userAssertionHash = userAssertionHash;
- }
- if (refreshOn) {
- atEntity.refreshOn = refreshOn.toString();
- }
- if (atEntity.tokenType?.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase()) {
- atEntity.credentialType = CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;
- switch (atEntity.tokenType) {
- case AuthenticationScheme.POP:
- const tokenClaims = extractTokenClaims(accessToken, base64Decode);
- if (!tokenClaims?.cnf?.kid) {
- throw createClientAuthError(tokenClaimsCnfRequiredForSignedJwt);
- }
- atEntity.keyId = tokenClaims.cnf.kid;
- break;
- case AuthenticationScheme.SSH:
- atEntity.keyId = keyId;
- }
- }
- return atEntity;
-}
-function createRefreshTokenEntity(homeAccountId, environment, refreshToken, clientId, familyId, userAssertionHash, expiresOn) {
- const rtEntity = {
- credentialType: CredentialType.REFRESH_TOKEN,
- homeAccountId,
- environment,
- clientId,
- secret: refreshToken,
- lastUpdatedAt: Date.now().toString()
- };
- if (userAssertionHash) {
- rtEntity.userAssertionHash = userAssertionHash;
- }
- if (familyId) {
- rtEntity.familyId = familyId;
- }
- if (expiresOn) {
- rtEntity.expiresOn = expiresOn.toString();
- }
- return rtEntity;
-}
-function isCredentialEntity(entity) {
- return entity.hasOwnProperty("homeAccountId") && entity.hasOwnProperty("environment") && entity.hasOwnProperty("credentialType") && entity.hasOwnProperty("clientId") && entity.hasOwnProperty("secret");
-}
-function isAccessTokenEntity(entity) {
- if (!entity) {
- return false;
- }
- return isCredentialEntity(entity) && entity.hasOwnProperty("realm") && entity.hasOwnProperty("target") && (entity["credentialType"] === CredentialType.ACCESS_TOKEN || entity["credentialType"] === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME);
-}
-function isIdTokenEntity(entity) {
- if (!entity) {
- return false;
- }
- return isCredentialEntity(entity) && entity.hasOwnProperty("realm") && entity["credentialType"] === CredentialType.ID_TOKEN;
-}
-function isRefreshTokenEntity(entity) {
- if (!entity) {
- return false;
- }
- return isCredentialEntity(entity) && entity["credentialType"] === CredentialType.REFRESH_TOKEN;
-}
-function isServerTelemetryEntity(key, entity) {
- const validateKey = key.indexOf(SERVER_TELEM_CACHE_KEY) === 0;
- let validateEntity = true;
- if (entity) {
- validateEntity = entity.hasOwnProperty("failedRequests") && entity.hasOwnProperty("errors") && entity.hasOwnProperty("cacheHits");
- }
- return validateKey && validateEntity;
-}
-function isThrottlingEntity(key, entity) {
- let validateKey = false;
- if (key) {
- validateKey = key.indexOf(THROTTLING_PREFIX) === 0;
- }
- let validateEntity = true;
- if (entity) {
- validateEntity = entity.hasOwnProperty("throttleTime");
- }
- return validateKey && validateEntity;
-}
-function generateAppMetadataKey({ environment, clientId }) {
- const appMetaDataKeyArray = [
- APP_METADATA,
- environment,
- clientId
- ];
- return appMetaDataKeyArray.join(CACHE_KEY_SEPARATOR).toLowerCase();
-}
-function isAppMetadataEntity(key, entity) {
- if (!entity) {
- return false;
- }
- return key.indexOf(APP_METADATA) === 0 && entity.hasOwnProperty("clientId") && entity.hasOwnProperty("environment");
-}
-function isAuthorityMetadataEntity(key, entity) {
- if (!entity) {
- return false;
- }
- return key.indexOf(AUTHORITY_METADATA_CACHE_KEY) === 0 && entity.hasOwnProperty("aliases") && entity.hasOwnProperty("preferred_cache") && entity.hasOwnProperty("preferred_network") && entity.hasOwnProperty("canonical_authority") && entity.hasOwnProperty("authorization_endpoint") && entity.hasOwnProperty("token_endpoint") && entity.hasOwnProperty("issuer") && entity.hasOwnProperty("aliasesFromNetwork") && entity.hasOwnProperty("endpointsFromNetwork") && entity.hasOwnProperty("expiresAt") && entity.hasOwnProperty("jwks_uri");
-}
-function generateAuthorityMetadataExpiresAt() {
- return nowSeconds() + AUTHORITY_METADATA_REFRESH_TIME_SECONDS;
-}
-function updateAuthorityEndpointMetadata(authorityMetadata, updatedValues, fromNetwork) {
- authorityMetadata.authorization_endpoint = updatedValues.authorization_endpoint;
- authorityMetadata.token_endpoint = updatedValues.token_endpoint;
- authorityMetadata.end_session_endpoint = updatedValues.end_session_endpoint;
- authorityMetadata.issuer = updatedValues.issuer;
- authorityMetadata.endpointsFromNetwork = fromNetwork;
- authorityMetadata.jwks_uri = updatedValues.jwks_uri;
-}
-function updateCloudDiscoveryMetadata(authorityMetadata, updatedValues, fromNetwork) {
- authorityMetadata.aliases = updatedValues.aliases;
- authorityMetadata.preferred_cache = updatedValues.preferred_cache;
- authorityMetadata.preferred_network = updatedValues.preferred_network;
- authorityMetadata.aliasesFromNetwork = fromNetwork;
-}
-function isAuthorityMetadataExpired(metadata) {
- return metadata.expiresAt <= nowSeconds();
-}
-var init_CacheHelpers = __esm(() => {
- init_AuthToken();
- init_ClientAuthError();
- init_Constants();
- init_TimeUtils();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/response/ResponseHandler.mjs
-class ResponseHandler {
- constructor(clientId, cacheStorage, cryptoObj, logger10, performanceClient, serializableCache, persistencePlugin) {
- this.clientId = clientId;
- this.cacheStorage = cacheStorage;
- this.cryptoObj = cryptoObj;
- this.logger = logger10;
- this.performanceClient = performanceClient;
- this.serializableCache = serializableCache;
- this.persistencePlugin = persistencePlugin;
- }
- validateTokenResponse(serverResponse, correlationId, refreshAccessToken) {
- if (serverResponse.error || serverResponse.error_description || serverResponse.suberror) {
- const errString = `Error(s): ${serverResponse.error_codes || NOT_AVAILABLE} - Timestamp: ${serverResponse.timestamp || NOT_AVAILABLE} - Description: ${serverResponse.error_description || NOT_AVAILABLE} - Correlation ID: ${serverResponse.correlation_id || NOT_AVAILABLE} - Trace ID: ${serverResponse.trace_id || NOT_AVAILABLE}`;
- const serverErrorNo = serverResponse.error_codes?.length ? serverResponse.error_codes[0] : undefined;
- const serverError = new ServerError(serverResponse.error, errString, serverResponse.suberror, serverErrorNo, serverResponse.status);
- if (refreshAccessToken && serverResponse.status && serverResponse.status >= HTTP_SERVER_ERROR_RANGE_START && serverResponse.status <= HTTP_SERVER_ERROR_RANGE_END) {
- this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently unavailable and the access token is unable to be refreshed.
-${serverError}`, correlationId);
- return;
- } else if (refreshAccessToken && serverResponse.status && serverResponse.status >= HTTP_CLIENT_ERROR_RANGE_START && serverResponse.status <= HTTP_CLIENT_ERROR_RANGE_END) {
- this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently available but is unable to refresh the access token.
-${serverError}`, correlationId);
- return;
- }
- if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {
- throw new InteractionRequiredAuthError(serverResponse.error, serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || "", serverResponse.trace_id || "", serverResponse.correlation_id || "", serverResponse.claims || "", serverErrorNo);
- }
- throw serverError;
- }
- }
- async handleServerTokenResponse(serverTokenResponse, authority, reqTimestamp, request2, apiId, authCodePayload, userAssertionHash, handlingRefreshTokenResponse, forceCacheRefreshTokenResponse, serverRequestId) {
- let idTokenClaims;
- if (serverTokenResponse.id_token) {
- idTokenClaims = extractTokenClaims(serverTokenResponse.id_token || "", this.cryptoObj.base64Decode);
- if (authCodePayload && authCodePayload.nonce) {
- if (idTokenClaims.nonce !== authCodePayload.nonce) {
- throw createClientAuthError(nonceMismatch);
- }
- }
- if (request2.maxAge || request2.maxAge === 0) {
- const authTime = idTokenClaims.auth_time;
- if (!authTime) {
- throw createClientAuthError(authTimeNotFound);
- }
- checkMaxAge(authTime, request2.maxAge);
- }
- }
- this.homeAccountIdentifier = generateHomeAccountId(serverTokenResponse.client_info || "", authority.authorityType, this.logger, this.cryptoObj, request2.correlationId, idTokenClaims);
- let requestStateObj;
- if (!!authCodePayload && !!authCodePayload.state) {
- requestStateObj = parseRequestState(this.cryptoObj.base64Decode, authCodePayload.state);
- }
- serverTokenResponse.key_id = serverTokenResponse.key_id || request2.sshKid || undefined;
- const cacheRecord = this.generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request2, idTokenClaims, userAssertionHash, authCodePayload);
- let cacheContext;
- try {
- if (this.persistencePlugin && this.serializableCache) {
- this.logger.verbose("Persistence enabled, calling beforeCacheAccess", request2.correlationId);
- cacheContext = new TokenCacheContext(this.serializableCache, true);
- await this.persistencePlugin.beforeCacheAccess(cacheContext);
- }
- if (handlingRefreshTokenResponse && !forceCacheRefreshTokenResponse && cacheRecord.account) {
- const cachedAccounts = this.cacheStorage.getAllAccounts({
- homeAccountId: cacheRecord.account.homeAccountId,
- environment: cacheRecord.account.environment
- }, request2.correlationId);
- if (cachedAccounts.length < 1) {
- this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache", request2.correlationId);
- this.performanceClient?.addFields({
- acntLoggedOut: true
- }, request2.correlationId);
- return await ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request2, this.performanceClient, idTokenClaims, requestStateObj, undefined, serverRequestId);
- }
- }
- await this.cacheStorage.saveCacheRecord(cacheRecord, request2.correlationId, isKmsi(idTokenClaims || {}), apiId, request2.storeInCache);
- } finally {
- if (this.persistencePlugin && this.serializableCache && cacheContext) {
- this.logger.verbose("Persistence enabled, calling afterCacheAccess", request2.correlationId);
- await this.persistencePlugin.afterCacheAccess(cacheContext);
- }
- }
- return ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request2, this.performanceClient, idTokenClaims, requestStateObj, serverTokenResponse, serverRequestId);
- }
- generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request2, idTokenClaims, userAssertionHash, authCodePayload) {
- const env5 = authority.getPreferredCache();
- if (!env5) {
- throw createClientAuthError(invalidCacheEnvironment);
- }
- const claimsTenantId = getTenantIdFromIdTokenClaims(idTokenClaims);
- let cachedIdToken;
- let cachedAccount;
- if (serverTokenResponse.id_token && !!idTokenClaims) {
- cachedIdToken = createIdTokenEntity(this.homeAccountIdentifier, env5, serverTokenResponse.id_token, this.clientId, claimsTenantId || "");
- cachedAccount = buildAccountToCache(this.cacheStorage, authority, this.homeAccountIdentifier, this.cryptoObj.base64Decode, request2.correlationId, idTokenClaims, serverTokenResponse.client_info, env5, claimsTenantId, authCodePayload, undefined, this.logger);
- }
- let cachedAccessToken = null;
- if (serverTokenResponse.access_token) {
- const responseScopes = serverTokenResponse.scope ? ScopeSet.fromString(serverTokenResponse.scope) : new ScopeSet(request2.scopes || []);
- const expiresIn = (typeof serverTokenResponse.expires_in === "string" ? parseInt(serverTokenResponse.expires_in, 10) : serverTokenResponse.expires_in) || 0;
- const extExpiresIn = (typeof serverTokenResponse.ext_expires_in === "string" ? parseInt(serverTokenResponse.ext_expires_in, 10) : serverTokenResponse.ext_expires_in) || 0;
- const refreshIn = (typeof serverTokenResponse.refresh_in === "string" ? parseInt(serverTokenResponse.refresh_in, 10) : serverTokenResponse.refresh_in) || undefined;
- const tokenExpirationSeconds = reqTimestamp + expiresIn;
- const extendedTokenExpirationSeconds = tokenExpirationSeconds + extExpiresIn;
- const refreshOnSeconds = refreshIn && refreshIn > 0 ? reqTimestamp + refreshIn : undefined;
- cachedAccessToken = createAccessTokenEntity(this.homeAccountIdentifier, env5, serverTokenResponse.access_token, this.clientId, claimsTenantId || authority.tenant || "", responseScopes.printScopes(), tokenExpirationSeconds, extendedTokenExpirationSeconds, this.cryptoObj.base64Decode, refreshOnSeconds, serverTokenResponse.token_type, userAssertionHash, serverTokenResponse.key_id);
- const resource = request2.resource || null;
- if (resource) {
- cachedAccessToken.resource = resource;
- }
- }
- let cachedRefreshToken = null;
- if (serverTokenResponse.refresh_token) {
- let rtExpiresOn;
- if (serverTokenResponse.refresh_token_expires_in) {
- const rtExpiresIn = typeof serverTokenResponse.refresh_token_expires_in === "string" ? parseInt(serverTokenResponse.refresh_token_expires_in, 10) : serverTokenResponse.refresh_token_expires_in;
- rtExpiresOn = reqTimestamp + rtExpiresIn;
- this.performanceClient?.addFields({ ntwkRtExpiresOnSeconds: rtExpiresOn }, request2.correlationId);
- }
- cachedRefreshToken = createRefreshTokenEntity(this.homeAccountIdentifier, env5, serverTokenResponse.refresh_token, this.clientId, serverTokenResponse.foci, userAssertionHash, rtExpiresOn);
- }
- let cachedAppMetadata = null;
- if (serverTokenResponse.foci) {
- cachedAppMetadata = {
- clientId: this.clientId,
- environment: env5,
- familyId: serverTokenResponse.foci
- };
- }
- return {
- account: cachedAccount,
- idToken: cachedIdToken,
- accessToken: cachedAccessToken,
- refreshToken: cachedRefreshToken,
- appMetadata: cachedAppMetadata
- };
- }
- static async generateAuthenticationResult(cryptoObj, authority, cacheRecord, fromTokenCache, request2, performanceClient, idTokenClaims, requestState, serverTokenResponse, requestId) {
- let accessToken = "";
- let responseScopes = [];
- let expiresOn = null;
- let extExpiresOn;
- let refreshOn;
- let familyId = "";
- if (cacheRecord.accessToken) {
- if (cacheRecord.accessToken.tokenType === AuthenticationScheme.POP && !request2.popKid) {
- const popTokenGenerator = new PopTokenGenerator(cryptoObj, performanceClient);
- const { secret, keyId } = cacheRecord.accessToken;
- if (!keyId) {
- throw createClientAuthError(keyIdMissing);
- }
- accessToken = await popTokenGenerator.signPopToken(secret, keyId, request2);
- } else {
- accessToken = cacheRecord.accessToken.secret;
- }
- responseScopes = ScopeSet.fromString(cacheRecord.accessToken.target).asArray();
- expiresOn = toDateFromSeconds(cacheRecord.accessToken.expiresOn);
- extExpiresOn = toDateFromSeconds(cacheRecord.accessToken.extendedExpiresOn);
- if (cacheRecord.accessToken.refreshOn) {
- refreshOn = toDateFromSeconds(cacheRecord.accessToken.refreshOn);
- }
- }
- if (cacheRecord.appMetadata) {
- familyId = cacheRecord.appMetadata.familyId === THE_FAMILY_ID ? THE_FAMILY_ID : "";
- }
- const uid = idTokenClaims?.oid || idTokenClaims?.sub || "";
- const tid = idTokenClaims?.tid || "";
- if (serverTokenResponse?.spa_accountid && !!cacheRecord.account) {
- cacheRecord.account.nativeAccountId = serverTokenResponse?.spa_accountid;
- }
- const accountInfo = cacheRecord.account ? updateAccountTenantProfileData(getAccountInfo(cacheRecord.account), undefined, idTokenClaims, cacheRecord.idToken?.secret) : null;
- return {
- authority: authority.canonicalAuthority,
- uniqueId: uid,
- tenantId: tid,
- scopes: responseScopes,
- account: accountInfo,
- idToken: cacheRecord?.idToken?.secret || "",
- idTokenClaims: idTokenClaims || {},
- accessToken,
- fromCache: fromTokenCache,
- expiresOn,
- extExpiresOn,
- refreshOn,
- correlationId: request2.correlationId,
- requestId: requestId || "",
- familyId,
- tokenType: cacheRecord.accessToken?.tokenType || "",
- state: requestState ? requestState.userRequestState : "",
- cloudGraphHostName: cacheRecord.account?.cloudGraphHostName || "",
- msGraphHost: cacheRecord.account?.msGraphHost || "",
- code: serverTokenResponse?.spa_code,
- fromPlatformBroker: false
- };
- }
-}
-function buildAccountToCache(cacheStorage, authority, homeAccountId, base64Decode, correlationId, idTokenClaims, clientInfo, environment, claimsTenantId, authCodePayload, nativeAccountId, logger10) {
- logger10?.verbose("setCachedAccount called", correlationId);
- const accountKeys = cacheStorage.getAccountKeys();
- const baseAccountKey = accountKeys.find((accountKey) => {
- return accountKey.startsWith(homeAccountId);
- });
- let cachedAccount = null;
- if (baseAccountKey) {
- cachedAccount = cacheStorage.getAccount(baseAccountKey, correlationId);
- }
- const baseAccount = cachedAccount || createAccountEntity({
- homeAccountId,
- idTokenClaims,
- clientInfo,
- environment,
- cloudGraphHostName: authCodePayload?.cloud_graph_host_name,
- msGraphHost: authCodePayload?.msgraph_host,
- nativeAccountId
- }, authority, base64Decode);
- const tenantProfiles = baseAccount.tenantProfiles || [];
- const tenantId = claimsTenantId || baseAccount.realm;
- if (tenantId && !tenantProfiles.find((tenantProfile) => {
- return tenantProfile.tenantId === tenantId;
- })) {
- const newTenantProfile = buildTenantProfile(homeAccountId, baseAccount.localAccountId, tenantId, idTokenClaims);
- tenantProfiles.push(newTenantProfile);
- }
- baseAccount.tenantProfiles = tenantProfiles;
- return baseAccount;
-}
-var init_ResponseHandler = __esm(() => {
- init_ClientAuthError();
- init_ServerError();
- init_ScopeSet();
- init_InteractionRequiredAuthError();
- init_ProtocolUtils();
- init_Constants();
- init_PopTokenGenerator();
- init_TokenCacheContext();
- init_AuthToken();
- init_TokenClaims();
- init_AccountInfo();
- init_CacheHelpers();
- init_TimeUtils();
- init_AccountEntityUtils();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/account/CcsCredential.mjs
-var CcsCredentialType;
-var init_CcsCredential = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- CcsCredentialType = {
- HOME_ACCOUNT_ID: "home_account_id",
- UPN: "UPN"
- };
-});
-
-// node_modules/@azure/msal-common/dist/utils/ClientAssertionUtils.mjs
-async function getClientAssertion(clientAssertion, clientId, tokenEndpoint) {
- if (typeof clientAssertion === "string") {
- return clientAssertion;
- } else {
- const config8 = {
- clientId,
- tokenEndpoint
- };
- return clientAssertion(config8);
- }
-}
-var init_ClientAssertionUtils = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/network/RequestThumbprint.mjs
-function getRequestThumbprint(clientId, request2, homeAccountId) {
- return {
- clientId,
- authority: request2.authority,
- scopes: request2.scopes,
- homeAccountIdentifier: homeAccountId,
- claims: request2.claims,
- authenticationScheme: request2.authenticationScheme,
- resourceRequestMethod: request2.resourceRequestMethod,
- resourceRequestUri: request2.resourceRequestUri,
- shrClaims: request2.shrClaims,
- sshKid: request2.sshKid,
- embeddedClientId: request2.embeddedClientId || request2.extraParameters?.clientId
- };
-}
-var init_RequestThumbprint = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/network/ThrottlingUtils.mjs
-class ThrottlingUtils {
- static generateThrottlingStorageKey(thumbprint) {
- return `${THROTTLING_PREFIX}.${JSON.stringify(thumbprint)}`;
- }
- static preProcess(cacheManager, thumbprint, correlationId) {
- const key = ThrottlingUtils.generateThrottlingStorageKey(thumbprint);
- const value = cacheManager.getThrottlingCache(key, correlationId);
- if (value) {
- if (value.throttleTime < Date.now()) {
- cacheManager.removeItem(key, correlationId);
- return;
- }
- throw new ServerError(value.errorCodes?.join(" ") || "", value.errorMessage, value.subError);
- }
- }
- static postProcess(cacheManager, thumbprint, response7, correlationId) {
- if (ThrottlingUtils.checkResponseStatus(response7) || ThrottlingUtils.checkResponseForRetryAfter(response7)) {
- const thumbprintValue = {
- throttleTime: ThrottlingUtils.calculateThrottleTime(parseInt(response7.headers[HeaderNames.RETRY_AFTER])),
- error: response7.body.error,
- errorCodes: response7.body.error_codes,
- errorMessage: response7.body.error_description,
- subError: response7.body.suberror
- };
- cacheManager.setThrottlingCache(ThrottlingUtils.generateThrottlingStorageKey(thumbprint), thumbprintValue, correlationId);
- }
- }
- static checkResponseStatus(response7) {
- return response7.status === 429 || response7.status >= 500 && response7.status < 600;
- }
- static checkResponseForRetryAfter(response7) {
- if (response7.headers) {
- return response7.headers.hasOwnProperty(HeaderNames.RETRY_AFTER) && (response7.status < 200 || response7.status >= 300);
- }
- return false;
- }
- static calculateThrottleTime(throttleTime) {
- const time3 = throttleTime <= 0 ? 0 : throttleTime;
- const currentSeconds = Date.now() / 1000;
- return Math.floor(Math.min(currentSeconds + (time3 || DEFAULT_THROTTLE_TIME_SECONDS), currentSeconds + DEFAULT_MAX_THROTTLE_TIME_SECONDS) * 1000);
- }
- static removeThrottle(cacheManager, clientId, request2, homeAccountIdentifier) {
- const thumbprint = getRequestThumbprint(clientId, request2, homeAccountIdentifier);
- const key = this.generateThrottlingStorageKey(thumbprint);
- cacheManager.removeItem(key, request2.correlationId);
- }
-}
-var init_ThrottlingUtils = __esm(() => {
- init_Constants();
- init_ServerError();
- init_RequestThumbprint();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/error/NetworkError.mjs
-function createNetworkError(error44, httpStatus, responseHeaders, additionalError) {
- error44.errorMessage = `${error44.errorMessage}, additionalErrorInfo: error.name:${additionalError?.name}, error.message:${additionalError?.message}`;
- return new NetworkError(error44, httpStatus, responseHeaders);
-}
-var NetworkError;
-var init_NetworkError = __esm(() => {
- init_AuthError();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- NetworkError = class NetworkError extends AuthError {
- constructor(error44, httpStatus, responseHeaders) {
- super(error44.errorCode, error44.errorMessage, error44.subError);
- Object.setPrototypeOf(this, NetworkError.prototype);
- this.name = "NetworkError";
- this.error = error44;
- this.httpStatus = httpStatus;
- this.responseHeaders = responseHeaders;
- }
- };
-});
-
-// node_modules/@azure/msal-common/dist/protocol/Token.mjs
-var exports_Token = {};
-__export(exports_Token, {
- sendPostRequest: () => sendPostRequest,
- executePostToTokenEndpoint: () => executePostToTokenEndpoint,
- createTokenRequestHeaders: () => createTokenRequestHeaders,
- createTokenQueryParameters: () => createTokenQueryParameters
-});
-function createTokenRequestHeaders(logger10, preventCorsPreflight, ccsCred) {
- const headers = {};
- headers[HeaderNames.CONTENT_TYPE] = URL_FORM_CONTENT_TYPE;
- if (!preventCorsPreflight && ccsCred) {
- switch (ccsCred.type) {
- case CcsCredentialType.HOME_ACCOUNT_ID:
- try {
- const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
- headers[HeaderNames.CCS_HEADER] = `Oid:${clientInfo.uid}@${clientInfo.utid}`;
- } catch (e4) {
- logger10.verbose(`Could not parse home account ID for CCS Header: '${e4}'`, "");
- }
- break;
- case CcsCredentialType.UPN:
- headers[HeaderNames.CCS_HEADER] = `UPN: ${ccsCred.credential}`;
- break;
- }
- }
- return headers;
-}
-function createTokenQueryParameters(request2, clientId, redirectUri, performanceClient) {
- const parameters = new Map;
- if (request2.embeddedClientId) {
- addBrokerParameters(parameters, clientId, redirectUri);
- }
- if (request2.extraQueryParameters) {
- addExtraParameters(parameters, request2.extraQueryParameters);
- }
- addCorrelationId(parameters, request2.correlationId);
- instrumentBrokerParams(parameters, request2.correlationId, performanceClient);
- return mapToQueryString(parameters);
-}
-async function executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, cacheManager, networkClient, logger10, performanceClient, serverTelemetryManager) {
- const response7 = await sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers }, correlationId, cacheManager, networkClient, logger10, performanceClient);
- if (serverTelemetryManager && response7.status < 500 && response7.status !== 429) {
- serverTelemetryManager.clearTelemetryCache();
- }
- return response7;
-}
-async function sendPostRequest(thumbprint, tokenEndpoint, options2, correlationId, cacheManager, networkClient, logger10, performanceClient) {
- ThrottlingUtils.preProcess(cacheManager, thumbprint, correlationId);
- let response7;
- try {
- response7 = await invokeAsync(networkClient.sendPostRequestAsync.bind(networkClient), NetworkClientSendPostRequestAsync, logger10, performanceClient, correlationId)(tokenEndpoint, options2);
- const responseHeaders = response7.headers || {};
- performanceClient?.addFields({
- refreshTokenSize: response7.body.refresh_token?.length || 0,
- httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "",
- requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || ""
- }, correlationId);
- } catch (e4) {
- if (e4 instanceof NetworkError) {
- const responseHeaders = e4.responseHeaders;
- if (responseHeaders) {
- performanceClient?.addFields({
- httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "",
- requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "",
- contentTypeHeader: responseHeaders[HeaderNames.CONTENT_TYPE] || undefined,
- contentLengthHeader: responseHeaders[HeaderNames.CONTENT_LENGTH] || undefined,
- httpStatus: e4.httpStatus
- }, correlationId);
- }
- throw e4.error;
- }
- if (e4 instanceof AuthError) {
- throw e4;
- } else {
- throw createClientAuthError(networkError);
- }
- }
- ThrottlingUtils.postProcess(cacheManager, thumbprint, response7, correlationId);
- return response7;
-}
-var init_Token = __esm(() => {
- init_CcsCredential();
- init_ClientInfo();
- init_Constants();
- init_RequestParameterBuilder();
- init_UrlUtils();
- init_ThrottlingUtils();
- init_NetworkError();
- init_AuthError();
- init_ClientAuthError();
- init_FunctionWrappers();
- init_PerformanceEvents();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.mjs
-function isOpenIdConfigResponse(response7) {
- return response7.hasOwnProperty("authorization_endpoint") && response7.hasOwnProperty("token_endpoint") && response7.hasOwnProperty("issuer") && response7.hasOwnProperty("jwks_uri");
-}
-var init_OpenIdConfigResponse = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.mjs
-function isCloudInstanceDiscoveryResponse(response7) {
- return response7.hasOwnProperty("tenant_discovery_endpoint") && response7.hasOwnProperty("metadata");
-}
-var init_CloudInstanceDiscoveryResponse = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs
-function isCloudInstanceDiscoveryErrorResponse(response7) {
- return response7.hasOwnProperty("error") && response7.hasOwnProperty("error_description");
-}
-var init_CloudInstanceDiscoveryErrorResponse = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/authority/RegionDiscovery.mjs
-class RegionDiscovery {
- constructor(networkInterface, logger10, performanceClient, correlationId) {
- this.networkInterface = networkInterface;
- this.logger = logger10;
- this.performanceClient = performanceClient;
- this.correlationId = correlationId;
- }
- async detectRegion(environmentRegion, regionDiscoveryMetadata) {
- let autodetectedRegionName = environmentRegion;
- if (!autodetectedRegionName) {
- const options2 = RegionDiscovery.IMDS_OPTIONS;
- try {
- const localIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(IMDS_VERSION, options2);
- if (localIMDSVersionResponse.status === HTTP_SUCCESS) {
- autodetectedRegionName = localIMDSVersionResponse.body;
- regionDiscoveryMetadata.region_source = RegionDiscoverySources.IMDS;
- }
- if (localIMDSVersionResponse.status === HTTP_BAD_REQUEST) {
- const currentIMDSVersion = await invokeAsync(this.getCurrentVersion.bind(this), RegionDiscoveryGetCurrentVersion, this.logger, this.performanceClient, this.correlationId)(options2);
- if (!currentIMDSVersion) {
- regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
- return null;
- }
- const currentIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(currentIMDSVersion, options2);
- if (currentIMDSVersionResponse.status === HTTP_SUCCESS) {
- autodetectedRegionName = currentIMDSVersionResponse.body;
- regionDiscoveryMetadata.region_source = RegionDiscoverySources.IMDS;
- }
- }
- } catch (e4) {
- regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
- return null;
- }
- } else {
- regionDiscoveryMetadata.region_source = RegionDiscoverySources.ENVIRONMENT_VARIABLE;
- }
- if (!autodetectedRegionName) {
- regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
- }
- return autodetectedRegionName || null;
- }
- async getRegionFromIMDS(version3, options2) {
- return this.networkInterface.sendGetRequestAsync(`${IMDS_ENDPOINT}?api-version=${version3}&format=text`, options2, IMDS_TIMEOUT);
- }
- async getCurrentVersion(options2) {
- try {
- const response7 = await this.networkInterface.sendGetRequestAsync(`${IMDS_ENDPOINT}?format=json`, options2);
- if (response7.status === HTTP_BAD_REQUEST && response7.body && response7.body["newest-versions"] && response7.body["newest-versions"].length > 0) {
- return response7.body["newest-versions"][0];
- }
- return null;
- } catch (e4) {
- return null;
- }
- }
-}
-var init_RegionDiscovery = __esm(() => {
- init_Constants();
- init_PerformanceEvents();
- init_FunctionWrappers();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- RegionDiscovery.IMDS_OPTIONS = {
- headers: {
- Metadata: "true"
- }
- };
-});
-
-// node_modules/@azure/msal-common/dist/authority/Authority.mjs
-class Authority {
- constructor(authority, networkInterface, cacheManager, authorityOptions, logger10, correlationId, performanceClient, managedIdentity) {
- this.canonicalAuthority = authority;
- this._canonicalAuthority.validateAsUri();
- this.networkInterface = networkInterface;
- this.cacheManager = cacheManager;
- this.authorityOptions = authorityOptions;
- this.regionDiscoveryMetadata = {
- region_used: undefined,
- region_source: undefined,
- region_outcome: undefined
- };
- this.logger = logger10;
- this.performanceClient = performanceClient;
- this.correlationId = correlationId;
- this.managedIdentity = managedIdentity || false;
- this.regionDiscovery = new RegionDiscovery(networkInterface, this.logger, this.performanceClient, this.correlationId);
- }
- getAuthorityType(authorityUri) {
- if (authorityUri.HostNameAndPort.endsWith(CIAM_AUTH_URL)) {
- return AuthorityType.Ciam;
- }
- const pathSegments = authorityUri.PathSegments;
- if (pathSegments.length) {
- switch (pathSegments[0].toLowerCase()) {
- case ADFS:
- return AuthorityType.Adfs;
- case DSTS:
- return AuthorityType.Dsts;
- }
- }
- return AuthorityType.Default;
- }
- get authorityType() {
- return this.getAuthorityType(this.canonicalAuthorityUrlComponents);
- }
- get protocolMode() {
- return this.authorityOptions.protocolMode;
- }
- get options() {
- return this.authorityOptions;
- }
- get canonicalAuthority() {
- return this._canonicalAuthority.urlString;
- }
- set canonicalAuthority(url3) {
- this._canonicalAuthority = new UrlString(url3);
- this._canonicalAuthority.validateAsUri();
- this._canonicalAuthorityUrlComponents = null;
- }
- get canonicalAuthorityUrlComponents() {
- if (!this._canonicalAuthorityUrlComponents) {
- this._canonicalAuthorityUrlComponents = this._canonicalAuthority.getUrlComponents();
- }
- return this._canonicalAuthorityUrlComponents;
- }
- get hostnameAndPort() {
- return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase();
- }
- get tenant() {
- return this.canonicalAuthorityUrlComponents.PathSegments[0];
- }
- get authorizationEndpoint() {
- if (this.discoveryComplete()) {
- return this.replacePath(this.metadata.authorization_endpoint);
- } else {
- throw createClientAuthError(endpointResolutionError);
- }
- }
- get tokenEndpoint() {
- if (this.discoveryComplete()) {
- return this.replacePath(this.metadata.token_endpoint);
- } else {
- throw createClientAuthError(endpointResolutionError);
- }
- }
- get deviceCodeEndpoint() {
- if (this.discoveryComplete()) {
- return this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode"));
- } else {
- throw createClientAuthError(endpointResolutionError);
- }
- }
- get endSessionEndpoint() {
- if (this.discoveryComplete()) {
- if (!this.metadata.end_session_endpoint) {
- throw createClientAuthError(endSessionEndpointNotSupported);
- }
- return this.replacePath(this.metadata.end_session_endpoint);
- } else {
- throw createClientAuthError(endpointResolutionError);
- }
- }
- get selfSignedJwtAudience() {
- if (this.discoveryComplete()) {
- return this.replacePath(this.metadata.issuer);
- } else {
- throw createClientAuthError(endpointResolutionError);
- }
- }
- get jwksUri() {
- if (this.discoveryComplete()) {
- return this.replacePath(this.metadata.jwks_uri);
- } else {
- throw createClientAuthError(endpointResolutionError);
- }
- }
- canReplaceTenant(authorityUri) {
- return authorityUri.PathSegments.length === 1 && !Authority.reservedTenantDomains.has(authorityUri.PathSegments[0]) && this.getAuthorityType(authorityUri) === AuthorityType.Default && this.protocolMode !== ProtocolMode.OIDC;
- }
- replaceTenant(urlString) {
- return urlString.replace(/{tenant}|{tenantid}/g, this.tenant);
- }
- replacePath(urlString) {
- let endpoint7 = urlString;
- const cachedAuthorityUrl = new UrlString(this.metadata.canonical_authority);
- const cachedAuthorityUrlComponents = cachedAuthorityUrl.getUrlComponents();
- const cachedAuthorityParts = cachedAuthorityUrlComponents.PathSegments;
- const currentAuthorityParts = this.canonicalAuthorityUrlComponents.PathSegments;
- currentAuthorityParts.forEach((currentPart, index2) => {
- let cachedPart = cachedAuthorityParts[index2];
- if (index2 === 0 && this.canReplaceTenant(cachedAuthorityUrlComponents)) {
- const tenantId = new UrlString(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];
- if (cachedPart !== tenantId) {
- this.logger.verbose(`Replacing tenant domain name '${cachedPart}' with id '${tenantId}'`, this.correlationId);
- cachedPart = tenantId;
- }
- }
- if (currentPart !== cachedPart) {
- endpoint7 = endpoint7.replace(`/${cachedPart}/`, `/${currentPart}/`);
- }
- });
- return this.replaceTenant(endpoint7);
- }
- get defaultOpenIdConfigurationEndpoint() {
- const canonicalAuthorityHost = this.hostnameAndPort;
- if (this.canonicalAuthority.endsWith("v2.0/") || this.authorityType === AuthorityType.Adfs || this.protocolMode === ProtocolMode.OIDC && !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost)) {
- return `${this.canonicalAuthority}.well-known/openid-configuration`;
- }
- return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`;
- }
- discoveryComplete() {
- return !!this.metadata;
- }
- async resolveEndpointsAsync() {
- const metadataEntity = this.getCurrentMetadataEntity();
- const cloudDiscoverySource = await invokeAsync(this.updateCloudDiscoveryMetadata.bind(this), AuthorityUpdateCloudDiscoveryMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
- this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network);
- const endpointSource = await invokeAsync(this.updateEndpointMetadata.bind(this), AuthorityUpdateEndpointMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
- this.updateCachedMetadata(metadataEntity, cloudDiscoverySource, {
- source: endpointSource
- });
- this.performanceClient?.addFields({
- cloudDiscoverySource,
- authorityEndpointSource: endpointSource
- }, this.correlationId);
- }
- getCurrentMetadataEntity() {
- let metadataEntity = this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort, this.correlationId);
- if (!metadataEntity) {
- metadataEntity = {
- aliases: [],
- preferred_cache: this.hostnameAndPort,
- preferred_network: this.hostnameAndPort,
- canonical_authority: this.canonicalAuthority,
- authorization_endpoint: "",
- token_endpoint: "",
- end_session_endpoint: "",
- issuer: "",
- aliasesFromNetwork: false,
- endpointsFromNetwork: false,
- expiresAt: generateAuthorityMetadataExpiresAt(),
- jwks_uri: ""
- };
- }
- return metadataEntity;
- }
- updateCachedMetadata(metadataEntity, cloudDiscoverySource, endpointMetadataResult) {
- if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE && endpointMetadataResult?.source !== AuthorityMetadataSource.CACHE) {
- metadataEntity.expiresAt = generateAuthorityMetadataExpiresAt();
- metadataEntity.canonical_authority = this.canonicalAuthority;
- }
- const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache, this.correlationId);
- this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity, this.correlationId);
- this.metadata = metadataEntity;
- }
- async updateEndpointMetadata(metadataEntity) {
- const localMetadata = this.updateEndpointMetadataFromLocalSources(metadataEntity);
- if (localMetadata) {
- if (localMetadata.source === AuthorityMetadataSource.HARDCODED_VALUES) {
- if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
- if (localMetadata.metadata) {
- const hardcodedMetadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(localMetadata.metadata);
- updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false);
- metadataEntity.canonical_authority = this.canonicalAuthority;
- }
- }
- }
- return localMetadata.source;
- }
- let metadata = await invokeAsync(this.getEndpointMetadataFromNetwork.bind(this), AuthorityGetEndpointMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
- if (metadata) {
- if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
- metadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(metadata);
- }
- updateAuthorityEndpointMetadata(metadataEntity, metadata, true);
- return AuthorityMetadataSource.NETWORK;
- } else {
- throw createClientAuthError(openIdConfigError, this.defaultOpenIdConfigurationEndpoint);
- }
- }
- updateEndpointMetadataFromLocalSources(metadataEntity) {
- this.logger.verbose("Attempting to get endpoint metadata from authority configuration", this.correlationId);
- const configMetadata = this.getEndpointMetadataFromConfig();
- if (configMetadata) {
- this.logger.verbose("Found endpoint metadata in authority configuration", this.correlationId);
- updateAuthorityEndpointMetadata(metadataEntity, configMetadata, false);
- return {
- source: AuthorityMetadataSource.CONFIG
- };
- }
- this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values.", this.correlationId);
- const hardcodedMetadata = this.getEndpointMetadataFromHardcodedValues();
- if (hardcodedMetadata) {
- updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false);
- return {
- source: AuthorityMetadataSource.HARDCODED_VALUES,
- metadata: hardcodedMetadata
- };
- } else {
- this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.", this.correlationId);
- }
- const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity);
- if (this.isAuthoritySameType(metadataEntity) && metadataEntity.endpointsFromNetwork && !metadataEntityExpired) {
- this.logger.verbose("Found endpoint metadata in the cache.", "");
- return { source: AuthorityMetadataSource.CACHE };
- } else if (metadataEntityExpired) {
- this.logger.verbose("The metadata entity is expired.", "");
- }
- return null;
- }
- isAuthoritySameType(metadataEntity) {
- const cachedAuthorityUrl = new UrlString(metadataEntity.canonical_authority);
- const cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments;
- return cachedParts.length === this.canonicalAuthorityUrlComponents.PathSegments.length;
- }
- getEndpointMetadataFromConfig() {
- if (this.authorityOptions.authorityMetadata) {
- try {
- return JSON.parse(this.authorityOptions.authorityMetadata);
- } catch (e4) {
- throw createClientConfigurationError(invalidAuthorityMetadata);
- }
- }
- return null;
- }
- async getEndpointMetadataFromNetwork() {
- const options2 = {};
- const openIdConfigurationEndpoint = this.defaultOpenIdConfigurationEndpoint;
- this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from '${openIdConfigurationEndpoint}'`, this.correlationId);
- try {
- const response7 = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options2);
- const isValidResponse = isOpenIdConfigResponse(response7.body);
- if (isValidResponse) {
- return response7.body;
- } else {
- this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`, this.correlationId);
- return null;
- }
- } catch (e4) {
- this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: '${e4}'`, this.correlationId);
- return null;
- }
- }
- getEndpointMetadataFromHardcodedValues() {
- if (this.hostnameAndPort in EndpointMetadata) {
- return EndpointMetadata[this.hostnameAndPort];
- }
- return null;
- }
- async updateMetadataWithRegionalInformation(metadata) {
- const userConfiguredAzureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion;
- if (userConfiguredAzureRegion) {
- if (userConfiguredAzureRegion !== AZURE_REGION_AUTO_DISCOVER_FLAG) {
- this.regionDiscoveryMetadata.region_outcome = RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;
- this.regionDiscoveryMetadata.region_used = userConfiguredAzureRegion;
- return Authority.replaceWithRegionalInformation(metadata, userConfiguredAzureRegion);
- }
- const autodetectedRegionName = await invokeAsync(this.regionDiscovery.detectRegion.bind(this.regionDiscovery), RegionDiscoveryDetectRegion, this.logger, this.performanceClient, this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion, this.regionDiscoveryMetadata);
- if (autodetectedRegionName) {
- this.regionDiscoveryMetadata.region_outcome = RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL;
- this.regionDiscoveryMetadata.region_used = autodetectedRegionName;
- return Authority.replaceWithRegionalInformation(metadata, autodetectedRegionName);
- }
- this.regionDiscoveryMetadata.region_outcome = RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;
- }
- return metadata;
- }
- async updateCloudDiscoveryMetadata(metadataEntity) {
- const localMetadataSource = this.updateCloudDiscoveryMetadataFromLocalSources(metadataEntity);
- if (localMetadataSource) {
- return localMetadataSource;
- }
- const metadata = await invokeAsync(this.getCloudDiscoveryMetadataFromNetwork.bind(this), AuthorityGetCloudDiscoveryMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
- if (metadata) {
- updateCloudDiscoveryMetadata(metadataEntity, metadata, true);
- return AuthorityMetadataSource.NETWORK;
- }
- throw createClientConfigurationError(untrustedAuthority);
- }
- updateCloudDiscoveryMetadataFromLocalSources(metadataEntity) {
- this.logger.verbose("Attempting to get cloud discovery metadata from authority configuration", this.correlationId);
- this.logger.verbosePii(`Known Authorities: '${this.authorityOptions.knownAuthorities || NOT_APPLICABLE}'`, this.correlationId);
- this.logger.verbosePii(`Authority Metadata: '${this.authorityOptions.authorityMetadata || NOT_APPLICABLE}'`, this.correlationId);
- this.logger.verbosePii(`Canonical Authority: '${metadataEntity.canonical_authority || NOT_APPLICABLE}'`, this.correlationId);
- const metadata = this.getCloudDiscoveryMetadataFromConfig();
- if (metadata) {
- this.logger.verbose("Found cloud discovery metadata in authority configuration", this.correlationId);
- updateCloudDiscoveryMetadata(metadataEntity, metadata, false);
- return AuthorityMetadataSource.CONFIG;
- }
- this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values.", this.correlationId);
- const hardcodedMetadata = getCloudDiscoveryMetadataFromHardcodedValues(this.hostnameAndPort);
- if (hardcodedMetadata) {
- this.logger.verbose("Found cloud discovery metadata from hardcoded values.", this.correlationId);
- updateCloudDiscoveryMetadata(metadataEntity, hardcodedMetadata, false);
- return AuthorityMetadataSource.HARDCODED_VALUES;
- }
- this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.", this.correlationId);
- const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity);
- if (this.isAuthoritySameType(metadataEntity) && metadataEntity.aliasesFromNetwork && !metadataEntityExpired) {
- this.logger.verbose("Found cloud discovery metadata in the cache.", "");
- return AuthorityMetadataSource.CACHE;
- } else if (metadataEntityExpired) {
- this.logger.verbose("The metadata entity is expired.", "");
- }
- return null;
- }
- getCloudDiscoveryMetadataFromConfig() {
- if (this.authorityType === AuthorityType.Ciam) {
- this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host.", this.correlationId);
- return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
- }
- if (this.authorityOptions.cloudDiscoveryMetadata) {
- this.logger.verbose("The cloud discovery metadata has been provided as a network response, in the config.", this.correlationId);
- try {
- this.logger.verbose("Attempting to parse the cloud discovery metadata.", this.correlationId);
- const parsedResponse = JSON.parse(this.authorityOptions.cloudDiscoveryMetadata);
- const metadata = getCloudDiscoveryMetadataFromNetworkResponse(parsedResponse.metadata, this.hostnameAndPort);
- this.logger.verbose("Parsed the cloud discovery metadata.", "");
- if (metadata) {
- this.logger.verbose("There is returnable metadata attached to the parsed cloud discovery metadata.", this.correlationId);
- return metadata;
- } else {
- this.logger.verbose("There is no metadata attached to the parsed cloud discovery metadata.", this.correlationId);
- }
- } catch (e4) {
- this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error.", this.correlationId);
- throw createClientConfigurationError(invalidCloudDiscoveryMetadata);
- }
- }
- if (this.isInKnownAuthorities()) {
- this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host.", this.correlationId);
- return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
- }
- return null;
- }
- async getCloudDiscoveryMetadataFromNetwork() {
- const instanceDiscoveryEndpoint = `${AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`;
- const options2 = {};
- let match = null;
- try {
- const response7 = await this.networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint, options2);
- let typedResponseBody;
- let metadata;
- if (isCloudInstanceDiscoveryResponse(response7.body)) {
- typedResponseBody = response7.body;
- metadata = typedResponseBody.metadata;
- this.logger.verbosePii(`tenant_discovery_endpoint is: '${typedResponseBody.tenant_discovery_endpoint}'`, this.correlationId);
- } else if (isCloudInstanceDiscoveryErrorResponse(response7.body)) {
- this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: '${response7.status}'`, this.correlationId);
- typedResponseBody = response7.body;
- if (typedResponseBody.error === INVALID_INSTANCE) {
- this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance.", this.correlationId);
- return null;
- }
- this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is '${typedResponseBody.error}'`, this.correlationId);
- this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is '${typedResponseBody.error_description}'`, this.correlationId);
- this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network, correlationId) to []", this.correlationId);
- metadata = [];
- } else {
- this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse", this.correlationId);
- return null;
- }
- this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request.", this.correlationId);
- match = getCloudDiscoveryMetadataFromNetworkResponse(metadata, this.hostnameAndPort);
- } catch (error44) {
- if (error44 instanceof AuthError) {
- this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.
-Error: '${error44.errorCode}'
-Error Description: '${error44.errorMessage}'`, this.correlationId);
- } else {
- const typedError = error44;
- this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.
-Error: '${typedError.name}'
-Error Description: '${typedError.message}'`, this.correlationId);
- }
- return null;
- }
- if (!match) {
- this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request.", this.correlationId);
- this.logger.verbose("Creating custom Authority for custom domain scenario.", this.correlationId);
- match = Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
- }
- return match;
- }
- isInKnownAuthorities() {
- const matches = this.authorityOptions.knownAuthorities.filter((authority) => {
- return authority && UrlString.getDomainFromUrl(authority).toLowerCase() === this.hostnameAndPort;
- });
- return matches.length > 0;
- }
- static generateAuthority(authorityString, azureCloudOptions) {
- let authorityAzureCloudInstance;
- if (azureCloudOptions && azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None) {
- const tenant = azureCloudOptions.tenant ? azureCloudOptions.tenant : DEFAULT_COMMON_TENANT;
- authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`;
- }
- return authorityAzureCloudInstance ? authorityAzureCloudInstance : authorityString;
- }
- static createCloudDiscoveryMetadataFromHost(host) {
- return {
- preferred_network: host,
- preferred_cache: host,
- aliases: [host]
- };
- }
- getPreferredCache() {
- if (this.managedIdentity) {
- return DEFAULT_AUTHORITY_HOST;
- } else if (this.discoveryComplete()) {
- return this.metadata.preferred_cache;
- } else {
- throw createClientAuthError(endpointResolutionError);
- }
- }
- isAlias(host) {
- return this.metadata.aliases.indexOf(host) > -1;
- }
- isAliasOfKnownMicrosoftAuthority(host) {
- return InstanceDiscoveryMetadataAliases.has(host);
- }
- static isPublicCloudAuthority(host) {
- return KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0;
- }
- static buildRegionalAuthorityString(host, region, queryString) {
- const authorityUrlInstance = new UrlString(host);
- authorityUrlInstance.validateAsUri();
- const authorityUrlParts = authorityUrlInstance.getUrlComponents();
- let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`;
- if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) {
- hostNameAndPort = `${region}.${REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`;
- }
- const url3 = UrlString.constructAuthorityUriFromObject({
- ...authorityUrlInstance.getUrlComponents(),
- HostNameAndPort: hostNameAndPort
- }).urlString;
- if (queryString)
- return `${url3}?${queryString}`;
- return url3;
- }
- static replaceWithRegionalInformation(metadata, azureRegion) {
- const regionalMetadata = { ...metadata };
- regionalMetadata.authorization_endpoint = Authority.buildRegionalAuthorityString(regionalMetadata.authorization_endpoint, azureRegion);
- regionalMetadata.token_endpoint = Authority.buildRegionalAuthorityString(regionalMetadata.token_endpoint, azureRegion);
- if (regionalMetadata.end_session_endpoint) {
- regionalMetadata.end_session_endpoint = Authority.buildRegionalAuthorityString(regionalMetadata.end_session_endpoint, azureRegion);
- }
- return regionalMetadata;
- }
- static transformCIAMAuthority(authority) {
- let ciamAuthority = authority;
- const authorityUrl = new UrlString(authority);
- const authorityUrlComponents = authorityUrl.getUrlComponents();
- if (authorityUrlComponents.PathSegments.length === 0 && authorityUrlComponents.HostNameAndPort.endsWith(CIAM_AUTH_URL)) {
- const tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0];
- ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${AAD_TENANT_DOMAIN_SUFFIX}`;
- }
- return ciamAuthority;
- }
-}
-function getTenantFromAuthorityString(authority) {
- const authorityUrl = new UrlString(authority);
- const authorityUrlComponents = authorityUrl.getUrlComponents();
- const tenantId = authorityUrlComponents.PathSegments.slice(-1)[0]?.toLowerCase();
- switch (tenantId) {
- case AADAuthority.COMMON:
- case AADAuthority.ORGANIZATIONS:
- case AADAuthority.CONSUMERS:
- return;
- default:
- return tenantId;
- }
-}
-function formatAuthorityUri(authorityUri) {
- return authorityUri.endsWith(FORWARD_SLASH) ? authorityUri : `${authorityUri}${FORWARD_SLASH}`;
-}
-function buildStaticAuthorityOptions(authOptions) {
- const rawCloudDiscoveryMetadata = authOptions.cloudDiscoveryMetadata;
- let cloudDiscoveryMetadata = undefined;
- if (rawCloudDiscoveryMetadata) {
- try {
- cloudDiscoveryMetadata = JSON.parse(rawCloudDiscoveryMetadata);
- } catch (e4) {
- throw createClientConfigurationError(invalidCloudDiscoveryMetadata);
- }
- }
- return {
- canonicalAuthority: authOptions.authority ? formatAuthorityUri(authOptions.authority) : undefined,
- knownAuthorities: authOptions.knownAuthorities,
- cloudDiscoveryMetadata
- };
-}
-var init_Authority = __esm(() => {
- init_AuthorityType();
- init_OpenIdConfigResponse();
- init_UrlString();
- init_ClientAuthError();
- init_Constants();
- init_AuthorityMetadata();
- init_ClientConfigurationError();
- init_ProtocolMode();
- init_AuthorityOptions();
- init_CloudInstanceDiscoveryResponse();
- init_CloudInstanceDiscoveryErrorResponse();
- init_RegionDiscovery();
- init_AuthError();
- init_PerformanceEvents();
- init_FunctionWrappers();
- init_CacheHelpers();
- init_ClientAuthErrorCodes();
- init_ClientConfigurationErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
- Authority.reservedTenantDomains = new Set([
- "{tenant}",
- "{tenantid}",
- AADAuthority.COMMON,
- AADAuthority.CONSUMERS,
- AADAuthority.ORGANIZATIONS
- ]);
-});
-
-// node_modules/@azure/msal-common/dist/authority/AuthorityFactory.mjs
-var exports_AuthorityFactory = {};
-__export(exports_AuthorityFactory, {
- createDiscoveredInstance: () => createDiscoveredInstance
-});
-async function createDiscoveredInstance(authorityUri, networkClient, cacheManager, authorityOptions, logger10, correlationId, performanceClient) {
- const authorityUriFinal = Authority.transformCIAMAuthority(formatAuthorityUri(authorityUri));
- const acquireTokenAuthority = new Authority(authorityUriFinal, networkClient, cacheManager, authorityOptions, logger10, correlationId, performanceClient);
- try {
- await invokeAsync(acquireTokenAuthority.resolveEndpointsAsync.bind(acquireTokenAuthority), AuthorityResolveEndpointsAsync, logger10, performanceClient, correlationId)();
- return acquireTokenAuthority;
- } catch (e4) {
- throw createClientAuthError(endpointResolutionError);
- }
-}
-var init_AuthorityFactory = __esm(() => {
- init_Authority();
- init_ClientAuthError();
- init_PerformanceEvents();
- init_FunctionWrappers();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.mjs
-class AuthorizationCodeClient {
- constructor(configuration, performanceClient) {
- this.includeRedirectUri = true;
- this.config = buildClientConfiguration(configuration);
- this.logger = new Logger(this.config.loggerOptions, name, version2);
- this.cryptoUtils = this.config.cryptoInterface;
- this.cacheManager = this.config.storageInterface;
- this.networkClient = this.config.networkInterface;
- this.serverTelemetryManager = this.config.serverTelemetryManager;
- this.authority = this.config.authOptions.authority;
- this.performanceClient = performanceClient;
- this.oidcDefaultScopes = this.config.authOptions.authority.options.OIDCOptions?.defaultScopes;
- }
- async acquireToken(request2, apiId, authCodePayload) {
- if (!request2.code) {
- throw createClientAuthError(requestCannotBeMade);
- }
- if (authCodePayload && authCodePayload.cloud_instance_host_name) {
- await invokeAsync(this.updateTokenEndpointAuthority.bind(this), UpdateTokenEndpointAuthority, this.logger, this.performanceClient, request2.correlationId)(authCodePayload.cloud_instance_host_name, request2.correlationId);
- }
- const reqTimestamp = nowSeconds();
- const response7 = await invokeAsync(this.executeTokenRequest.bind(this), AuthClientExecuteTokenRequest, this.logger, this.performanceClient, request2.correlationId)(this.authority, request2, this.serverTelemetryManager);
- const requestId = response7.headers?.[HeaderNames.X_MS_REQUEST_ID];
- const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
- responseHandler.validateTokenResponse(response7.body, request2.correlationId);
- return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, this.logger, this.performanceClient, request2.correlationId)(response7.body, this.authority, reqTimestamp, request2, apiId, authCodePayload, undefined, undefined, undefined, requestId);
- }
- getLogoutUri(logoutRequest) {
- if (!logoutRequest) {
- throw createClientConfigurationError(logoutRequestEmpty);
- }
- const queryString = this.createLogoutUrlQueryString(logoutRequest);
- return UrlString.appendQueryString(this.authority.endSessionEndpoint, queryString);
- }
- async executeTokenRequest(authority, request2, serverTelemetryManager) {
- const queryParametersString = createTokenQueryParameters(request2, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);
- const endpoint7 = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
- const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), AuthClientCreateTokenRequestBody, this.logger, this.performanceClient, request2.correlationId)(request2);
- let ccsCredential = undefined;
- if (request2.clientInfo) {
- try {
- const clientInfo = buildClientInfo(request2.clientInfo, this.cryptoUtils.base64Decode);
- ccsCredential = {
- credential: `${clientInfo.uid}${CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
- type: CcsCredentialType.HOME_ACCOUNT_ID
- };
- } catch (e4) {
- this.logger.verbose(`Could not parse client info for CCS Header: '${e4}'`, request2.correlationId);
- }
- }
- const headers = createTokenRequestHeaders(this.logger, this.config.systemOptions.preventCorsPreflight, ccsCredential || request2.ccsCredential);
- const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request2);
- return invokeAsync(executePostToTokenEndpoint, AuthorizationCodeClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request2.correlationId)(endpoint7, requestBody, headers, thumbprint, request2.correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, serverTelemetryManager);
- }
- async createTokenRequestBody(request2) {
- const parameters = new Map;
- addClientId(parameters, request2.embeddedClientId || request2.extraParameters?.[CLIENT_ID] || this.config.authOptions.clientId);
- if (!this.includeRedirectUri) {
- if (!request2.redirectUri) {
- throw createClientConfigurationError(redirectUriEmpty);
- }
- } else {
- addRedirectUri(parameters, request2.redirectUri);
- }
- addScopes(parameters, request2.scopes, true, this.oidcDefaultScopes);
- addResource(parameters, request2.resource);
- addAuthorizationCode(parameters, request2.code);
- addLibraryInfo(parameters, this.config.libraryInfo);
- addApplicationTelemetry(parameters, this.config.telemetry.application);
- addThrottling(parameters);
- if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {
- addServerTelemetry(parameters, this.serverTelemetryManager);
- }
- if (request2.codeVerifier) {
- addCodeVerifier(parameters, request2.codeVerifier);
- }
- if (this.config.clientCredentials.clientSecret) {
- addClientSecret(parameters, this.config.clientCredentials.clientSecret);
- }
- if (this.config.clientCredentials.clientAssertion) {
- const clientAssertion = this.config.clientCredentials.clientAssertion;
- addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request2.resourceRequestUri));
- addClientAssertionType(parameters, clientAssertion.assertionType);
- }
- addGrantType(parameters, GrantType.AUTHORIZATION_CODE_GRANT);
- addClientInfo(parameters);
- if (request2.authenticationScheme === AuthenticationScheme.POP) {
- const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
- let reqCnfData;
- if (!request2.popKid) {
- const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, request2.correlationId)(request2, this.logger);
- reqCnfData = generatedReqCnfData.reqCnfString;
- } else {
- reqCnfData = this.cryptoUtils.encodeKid(request2.popKid);
- }
- addPopToken(parameters, reqCnfData);
- } else if (request2.authenticationScheme === AuthenticationScheme.SSH) {
- if (request2.sshJwk) {
- addSshJwk(parameters, request2.sshJwk);
- } else {
- throw createClientConfigurationError(missingSshJwk);
- }
- }
- if (!StringUtils.isEmptyObj(request2.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
- addClaims(parameters, request2.claims, this.config.authOptions.clientCapabilities);
- }
- let ccsCred = undefined;
- if (request2.clientInfo) {
- try {
- const clientInfo = buildClientInfo(request2.clientInfo, this.cryptoUtils.base64Decode);
- ccsCred = {
- credential: `${clientInfo.uid}${CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
- type: CcsCredentialType.HOME_ACCOUNT_ID
- };
- } catch (e4) {
- this.logger.verbose(`Could not parse client info for CCS Header: '${e4}'`, request2.correlationId);
- }
- } else {
- ccsCred = request2.ccsCredential;
- }
- if (this.config.systemOptions.preventCorsPreflight && ccsCred) {
- switch (ccsCred.type) {
- case CcsCredentialType.HOME_ACCOUNT_ID:
- try {
- const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
- addCcsOid(parameters, clientInfo);
- } catch (e4) {
- this.logger.verbose(`Could not parse home account ID for CCS Header: '${e4}'`, request2.correlationId);
- }
- break;
- case CcsCredentialType.UPN:
- addCcsUpn(parameters, ccsCred.credential);
- break;
- }
- }
- if (request2.embeddedClientId) {
- addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri);
- }
- if (request2.extraParameters) {
- addExtraParameters(parameters, request2.extraParameters);
- }
- if (request2.enableSpaAuthorizationCode && (!request2.extraParameters || !request2.extraParameters[RETURN_SPA_CODE])) {
- addExtraParameters(parameters, {
- [RETURN_SPA_CODE]: "1"
- });
- }
- instrumentBrokerParams(parameters, request2.correlationId, this.performanceClient);
- return mapToQueryString(parameters);
- }
- createLogoutUrlQueryString(request2) {
- const parameters = new Map;
- if (request2.postLogoutRedirectUri) {
- addPostLogoutRedirectUri(parameters, request2.postLogoutRedirectUri);
- }
- if (request2.correlationId) {
- addCorrelationId(parameters, request2.correlationId);
- }
- if (request2.idTokenHint) {
- addIdTokenHint(parameters, request2.idTokenHint);
- }
- if (request2.state) {
- addState(parameters, request2.state);
- }
- if (request2.logoutHint) {
- addLogoutHint(parameters, request2.logoutHint);
- }
- if (request2.extraQueryParameters) {
- addExtraParameters(parameters, request2.extraQueryParameters);
- }
- if (this.config.authOptions.instanceAware) {
- addInstanceAware(parameters);
- }
- return mapToQueryString(parameters);
- }
- async updateTokenEndpointAuthority(cloudInstanceHostName, correlationId) {
- const cloudInstanceAuthorityUri = `https://${cloudInstanceHostName}/${this.authority.tenant}/`;
- const cloudInstanceAuthority = await createDiscoveredInstance(cloudInstanceAuthorityUri, this.networkClient, this.cacheManager, this.authority.options, this.logger, correlationId, this.performanceClient);
- this.authority = cloudInstanceAuthority;
- }
-}
-var init_AuthorizationCodeClient = __esm(() => {
- init_RequestParameterBuilder();
- init_UrlUtils();
- init_Constants();
- init_AADServerParamKeys();
- init_ClientConfiguration();
- init_ResponseHandler();
- init_StringUtils();
- init_ClientAuthError();
- init_UrlString();
- init_PopTokenGenerator();
- init_TimeUtils();
- init_ClientInfo();
- init_CcsCredential();
- init_ClientConfigurationError();
- init_PerformanceEvents();
- init_FunctionWrappers();
- init_ClientAssertionUtils();
- init_RequestThumbprint();
- init_Token();
- init_AuthorityFactory();
- init_Logger();
- init_packageMetadata();
- init_ClientAuthErrorCodes();
- init_ClientConfigurationErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/client/RefreshTokenClient.mjs
-class RefreshTokenClient {
- constructor(configuration, performanceClient) {
- this.config = buildClientConfiguration(configuration);
- this.logger = new Logger(this.config.loggerOptions, name, version2);
- this.cryptoUtils = this.config.cryptoInterface;
- this.cacheManager = this.config.storageInterface;
- this.networkClient = this.config.networkInterface;
- this.serverTelemetryManager = this.config.serverTelemetryManager;
- this.authority = this.config.authOptions.authority;
- this.performanceClient = performanceClient;
- }
- async acquireToken(request2, apiId) {
- const reqTimestamp = nowSeconds();
- const response7 = await invokeAsync(this.executeTokenRequest.bind(this), RefreshTokenClientExecuteTokenRequest, this.logger, this.performanceClient, request2.correlationId)(request2, this.authority);
- const requestId = response7.headers?.[HeaderNames.X_MS_REQUEST_ID];
- const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
- responseHandler.validateTokenResponse(response7.body, request2.correlationId);
- return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, this.logger, this.performanceClient, request2.correlationId)(response7.body, this.authority, reqTimestamp, request2, apiId, undefined, undefined, true, request2.forceCache, requestId);
- }
- async acquireTokenByRefreshToken(request2, apiId) {
- if (!request2) {
- throw createClientConfigurationError(tokenRequestEmpty);
- }
- if (!request2.account) {
- throw createClientAuthError(noAccountInSilentRequest);
- }
- const isFOCI = this.cacheManager.isAppMetadataFOCI(request2.account.environment, request2.correlationId);
- if (isFOCI) {
- try {
- return await invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request2.correlationId)(request2, true, apiId);
- } catch (e4) {
- const noFamilyRTInCache = e4 instanceof InteractionRequiredAuthError && e4.errorCode === noTokensFound;
- const clientMismatchErrorWithFamilyRT = e4 instanceof ServerError && e4.errorCode === INVALID_GRANT_ERROR && e4.subError === CLIENT_MISMATCH_ERROR;
- if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) {
- return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request2.correlationId)(request2, false, apiId);
- } else {
- throw e4;
- }
- }
- }
- return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request2.correlationId)(request2, false, apiId);
- }
- async acquireTokenWithCachedRefreshToken(request2, foci, apiId) {
- const refreshToken = invoke(this.cacheManager.getRefreshToken.bind(this.cacheManager), CacheManagerGetRefreshToken, this.logger, this.performanceClient, request2.correlationId)(request2.account, foci, request2.correlationId, undefined);
- if (!refreshToken) {
- throw createInteractionRequiredAuthError(noTokensFound);
- }
- if (refreshToken.expiresOn) {
- const offset = request2.refreshTokenExpirationOffsetSeconds || DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS;
- this.performanceClient?.addFields({
- cacheRtExpiresOnSeconds: Number(refreshToken.expiresOn),
- rtOffsetSeconds: offset
- }, request2.correlationId);
- if (isTokenExpired(refreshToken.expiresOn, offset)) {
- throw createInteractionRequiredAuthError(refreshTokenExpired);
- }
- }
- const refreshTokenRequest = {
- ...request2,
- refreshToken: refreshToken.secret,
- authenticationScheme: request2.authenticationScheme || AuthenticationScheme.BEARER,
- ccsCredential: {
- credential: request2.account.homeAccountId,
- type: CcsCredentialType.HOME_ACCOUNT_ID
- }
- };
- try {
- return await invokeAsync(this.acquireToken.bind(this), RefreshTokenClientAcquireToken, this.logger, this.performanceClient, request2.correlationId)(refreshTokenRequest, apiId);
- } catch (e4) {
- if (e4 instanceof InteractionRequiredAuthError) {
- if (e4.subError === badToken) {
- this.logger.verbose("acquireTokenWithRefreshToken: bad refresh token, removing from cache", request2.correlationId);
- const badRefreshTokenKey = this.cacheManager.generateCredentialKey(refreshToken);
- this.cacheManager.removeRefreshToken(badRefreshTokenKey, request2.correlationId);
- }
- }
- throw e4;
- }
- }
- async executeTokenRequest(request2, authority) {
- const queryParametersString = createTokenQueryParameters(request2, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);
- const endpoint7 = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
- const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), RefreshTokenClientCreateTokenRequestBody, this.logger, this.performanceClient, request2.correlationId)(request2);
- const headers = createTokenRequestHeaders(this.logger, this.config.systemOptions.preventCorsPreflight, request2.ccsCredential);
- const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request2);
- return invokeAsync(executePostToTokenEndpoint, RefreshTokenClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request2.correlationId)(endpoint7, requestBody, headers, thumbprint, request2.correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, this.serverTelemetryManager);
- }
- async createTokenRequestBody(request2) {
- const parameters = new Map;
- addClientId(parameters, request2.embeddedClientId || request2.extraParameters?.[CLIENT_ID] || this.config.authOptions.clientId);
- if (request2.redirectUri) {
- addRedirectUri(parameters, request2.redirectUri);
- }
- addScopes(parameters, request2.scopes, true, this.config.authOptions.authority.options.OIDCOptions?.defaultScopes);
- addGrantType(parameters, GrantType.REFRESH_TOKEN_GRANT);
- addClientInfo(parameters);
- addLibraryInfo(parameters, this.config.libraryInfo);
- addApplicationTelemetry(parameters, this.config.telemetry.application);
- addThrottling(parameters);
- if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {
- addServerTelemetry(parameters, this.serverTelemetryManager);
- }
- addRefreshToken(parameters, request2.refreshToken);
- if (this.config.clientCredentials.clientSecret) {
- addClientSecret(parameters, this.config.clientCredentials.clientSecret);
- }
- if (this.config.clientCredentials.clientAssertion) {
- const clientAssertion = this.config.clientCredentials.clientAssertion;
- addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request2.resourceRequestUri));
- addClientAssertionType(parameters, clientAssertion.assertionType);
- }
- if (request2.authenticationScheme === AuthenticationScheme.POP) {
- const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
- let reqCnfData;
- if (!request2.popKid) {
- const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, request2.correlationId)(request2, this.logger);
- reqCnfData = generatedReqCnfData.reqCnfString;
- } else {
- reqCnfData = this.cryptoUtils.encodeKid(request2.popKid);
- }
- addPopToken(parameters, reqCnfData);
- } else if (request2.authenticationScheme === AuthenticationScheme.SSH) {
- if (request2.sshJwk) {
- addSshJwk(parameters, request2.sshJwk);
- } else {
- throw createClientConfigurationError(missingSshJwk);
- }
- }
- if (!StringUtils.isEmptyObj(request2.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
- addClaims(parameters, request2.claims, this.config.authOptions.clientCapabilities);
- }
- if (this.config.systemOptions.preventCorsPreflight && request2.ccsCredential) {
- switch (request2.ccsCredential.type) {
- case CcsCredentialType.HOME_ACCOUNT_ID:
- try {
- const clientInfo = buildClientInfoFromHomeAccountId(request2.ccsCredential.credential);
- addCcsOid(parameters, clientInfo);
- } catch (e4) {
- this.logger.verbose(`Could not parse home account ID for CCS Header: '${e4}'`, request2.correlationId);
- }
- break;
- case CcsCredentialType.UPN:
- addCcsUpn(parameters, request2.ccsCredential.credential);
- break;
- }
- }
- if (request2.embeddedClientId) {
- addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri);
- }
- if (request2.extraParameters) {
- addExtraParameters(parameters, {
- ...request2.extraParameters
- });
- }
- instrumentBrokerParams(parameters, request2.correlationId, this.performanceClient);
- return mapToQueryString(parameters);
- }
-}
-var DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS = 300;
-var init_RefreshTokenClient = __esm(() => {
- init_ClientConfiguration();
- init_RequestParameterBuilder();
- init_UrlUtils();
- init_Constants();
- init_AADServerParamKeys();
- init_ResponseHandler();
- init_PopTokenGenerator();
- init_StringUtils();
- init_ClientConfigurationError();
- init_ClientAuthError();
- init_ServerError();
- init_TimeUtils();
- init_UrlString();
- init_CcsCredential();
- init_ClientInfo();
- init_InteractionRequiredAuthError();
- init_PerformanceEvents();
- init_FunctionWrappers();
- init_ClientAssertionUtils();
- init_RequestThumbprint();
- init_Token();
- init_Logger();
- init_packageMetadata();
- init_InteractionRequiredAuthErrorCodes();
- init_ClientConfigurationErrorCodes();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/client/SilentFlowClient.mjs
-class SilentFlowClient {
- constructor(configuration, performanceClient) {
- this.config = buildClientConfiguration(configuration);
- this.logger = new Logger(this.config.loggerOptions, name, version2);
- this.cryptoUtils = this.config.cryptoInterface;
- this.cacheManager = this.config.storageInterface;
- this.networkClient = this.config.networkInterface;
- this.serverTelemetryManager = this.config.serverTelemetryManager;
- this.authority = this.config.authOptions.authority;
- this.performanceClient = performanceClient;
- }
- async acquireCachedToken(request2) {
- let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE;
- if (request2.forceRefresh || !StringUtils.isEmptyObj(request2.claims)) {
- this.setCacheOutcome(CacheOutcome.FORCE_REFRESH_OR_CLAIMS, request2.correlationId);
- throw createClientAuthError(tokenRefreshRequired);
- }
- if (!request2.account) {
- throw createClientAuthError(noAccountInSilentRequest);
- }
- const requestTenantId = request2.account.tenantId || getTenantFromAuthorityString(request2.authority);
- const tokenKeys = this.cacheManager.getTokenKeys();
- const cachedAccessToken = this.cacheManager.getAccessToken(request2.account, request2, tokenKeys, requestTenantId);
- if (!cachedAccessToken) {
- this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request2.correlationId);
- throw createClientAuthError(tokenRefreshRequired);
- } else if (wasClockTurnedBack(cachedAccessToken.cachedAt) || isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
- this.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED, request2.correlationId);
- throw createClientAuthError(tokenRefreshRequired);
- } else if (request2.resource) {
- if (cachedAccessToken.resource !== request2.resource) {
- this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request2.correlationId);
- throw createClientAuthError(tokenRefreshRequired);
- }
- } else if (cachedAccessToken.refreshOn && isTokenExpired(cachedAccessToken.refreshOn, 0)) {
- lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;
- }
- const environment = request2.authority || this.authority.getPreferredCache();
- const cacheRecord = {
- account: this.cacheManager.getAccount(this.cacheManager.generateAccountKey(request2.account), request2.correlationId),
- accessToken: cachedAccessToken,
- idToken: this.cacheManager.getIdToken(request2.account, request2.correlationId, tokenKeys, requestTenantId),
- refreshToken: null,
- appMetadata: this.cacheManager.readAppMetadataFromCache(environment, request2.correlationId)
- };
- this.setCacheOutcome(lastCacheOutcome, request2.correlationId);
- if (this.config.serverTelemetryManager) {
- this.config.serverTelemetryManager.incrementCacheHits();
- }
- return [
- await invokeAsync(this.generateResultFromCacheRecord.bind(this), SilentFlowClientGenerateResultFromCacheRecord, this.logger, this.performanceClient, request2.correlationId)(cacheRecord, request2),
- lastCacheOutcome
- ];
- }
- setCacheOutcome(cacheOutcome, correlationId) {
- this.serverTelemetryManager?.setCacheOutcome(cacheOutcome);
- this.performanceClient?.addFields({
- cacheOutcome
- }, correlationId);
- if (cacheOutcome !== CacheOutcome.NOT_APPLICABLE) {
- this.logger.info(`Token refresh is required due to cache outcome: '${cacheOutcome}'`, correlationId);
- }
- }
- async generateResultFromCacheRecord(cacheRecord, request2) {
- let idTokenClaims;
- if (cacheRecord.idToken) {
- idTokenClaims = extractTokenClaims(cacheRecord.idToken.secret, this.config.cryptoInterface.base64Decode);
- }
- if (request2.maxAge || request2.maxAge === 0) {
- const authTime = idTokenClaims?.auth_time;
- if (!authTime) {
- throw createClientAuthError(authTimeNotFound);
- }
- checkMaxAge(authTime, request2.maxAge);
- }
- return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request2, this.performanceClient, idTokenClaims);
- }
-}
-var init_SilentFlowClient = __esm(() => {
- init_ClientConfiguration();
- init_TimeUtils();
- init_ClientAuthError();
- init_ResponseHandler();
- init_Constants();
- init_StringUtils();
- init_AuthToken();
- init_PerformanceEvents();
- init_FunctionWrappers();
- init_Authority();
- init_Logger();
- init_packageMetadata();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/protocol/Authorize.mjs
-var exports_Authorize = {};
-__export(exports_Authorize, {
- validateAuthorizationResponse: () => validateAuthorizationResponse,
- getStandardAuthorizeRequestParameters: () => getStandardAuthorizeRequestParameters,
- getAuthorizeUrl: () => getAuthorizeUrl,
- getAuthorizationCodePayload: () => getAuthorizationCodePayload
-});
-function getStandardAuthorizeRequestParameters(authOptions, request2, logger10, performanceClient) {
- const correlationId = request2.correlationId;
- const parameters = new Map;
- addClientId(parameters, request2.embeddedClientId || request2.extraQueryParameters?.[CLIENT_ID] || authOptions.clientId);
- const requestScopes = [
- ...request2.scopes || [],
- ...request2.extraScopesToConsent || []
- ];
- addScopes(parameters, requestScopes, true, authOptions.authority.options.OIDCOptions?.defaultScopes);
- addResource(parameters, request2.resource);
- addRedirectUri(parameters, request2.redirectUri);
- addCorrelationId(parameters, correlationId);
- addResponseMode(parameters, request2.responseMode);
- addClientInfo(parameters);
- addCliData(parameters);
- if (request2.prompt) {
- addPrompt(parameters, request2.prompt);
- performanceClient?.addFields({ prompt: request2.prompt }, correlationId);
- }
- if (request2.domainHint) {
- addDomainHint(parameters, request2.domainHint);
- performanceClient?.addFields({ domainHintFromRequest: true }, correlationId);
- }
- if (request2.prompt !== PromptValue.SELECT_ACCOUNT) {
- if (request2.sid && request2.prompt === PromptValue.NONE) {
- logger10.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request", request2.correlationId);
- addSid(parameters, request2.sid);
- performanceClient?.addFields({ sidFromRequest: true }, correlationId);
- } else if (request2.account) {
- const accountSid = extractAccountSid(request2.account);
- let accountLoginHintClaim = extractLoginHint(request2.account);
- if (accountLoginHintClaim && request2.domainHint) {
- logger10.warning(`AuthorizationCodeClient.createAuthCodeUrlQueryString: "domainHint" param is set, skipping opaque "login_hint" claim. Please consider not passing domainHint`, request2.correlationId);
- accountLoginHintClaim = null;
- }
- if (accountLoginHintClaim) {
- logger10.verbose("createAuthCodeUrlQueryString: login_hint claim present on account", request2.correlationId);
- addLoginHint(parameters, accountLoginHintClaim);
- performanceClient?.addFields({ loginHintFromClaim: true }, correlationId);
- try {
- const clientInfo = buildClientInfoFromHomeAccountId(request2.account.homeAccountId);
- addCcsOid(parameters, clientInfo);
- } catch (e4) {
- logger10.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header", request2.correlationId);
- }
- } else if (accountSid && request2.prompt === PromptValue.NONE) {
- logger10.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account", request2.correlationId);
- addSid(parameters, accountSid);
- performanceClient?.addFields({ sidFromClaim: true }, correlationId);
- try {
- const clientInfo = buildClientInfoFromHomeAccountId(request2.account.homeAccountId);
- addCcsOid(parameters, clientInfo);
- } catch (e4) {
- logger10.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header", request2.correlationId);
- }
- } else if (request2.loginHint) {
- logger10.verbose("createAuthCodeUrlQueryString: Adding login_hint from request", request2.correlationId);
- addLoginHint(parameters, request2.loginHint);
- addCcsUpn(parameters, request2.loginHint);
- performanceClient?.addFields({ loginHintFromRequest: true }, correlationId);
- } else if (request2.account.username) {
- logger10.verbose("createAuthCodeUrlQueryString: Adding login_hint from account", request2.correlationId);
- addLoginHint(parameters, request2.account.username);
- performanceClient?.addFields({ loginHintFromUpn: true }, correlationId);
- try {
- const clientInfo = buildClientInfoFromHomeAccountId(request2.account.homeAccountId);
- addCcsOid(parameters, clientInfo);
- } catch (e4) {
- logger10.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header", request2.correlationId);
- }
- }
- } else if (request2.loginHint) {
- logger10.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request", request2.correlationId);
- addLoginHint(parameters, request2.loginHint);
- addCcsUpn(parameters, request2.loginHint);
- performanceClient?.addFields({ loginHintFromRequest: true }, correlationId);
- }
- } else {
- logger10.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints", request2.correlationId);
- }
- if (request2.nonce) {
- addNonce(parameters, request2.nonce);
- }
- if (request2.state) {
- addState(parameters, request2.state);
- }
- if (request2.claims || authOptions.clientCapabilities && authOptions.clientCapabilities.length > 0) {
- addClaims(parameters, request2.claims, authOptions.clientCapabilities);
- }
- if (request2.embeddedClientId) {
- addBrokerParameters(parameters, authOptions.clientId, authOptions.redirectUri);
- }
- if (authOptions.instanceAware && (!request2.extraQueryParameters || !Object.keys(request2.extraQueryParameters).includes(INSTANCE_AWARE))) {
- addInstanceAware(parameters);
- }
- return parameters;
-}
-function getAuthorizeUrl(authority, requestParameters) {
- const queryString = mapToQueryString(requestParameters);
- return UrlString.appendQueryString(authority.authorizationEndpoint, queryString);
-}
-function getAuthorizationCodePayload(serverParams, cachedState) {
- validateAuthorizationResponse(serverParams, cachedState);
- if (!serverParams.code) {
- throw createClientAuthError(authorizationCodeMissingFromServerResponse);
- }
- return serverParams;
-}
-function validateAuthorizationResponse(serverResponse, requestState) {
- if (!serverResponse.state || !requestState) {
- throw serverResponse.state ? createClientAuthError(stateNotFound, "Cached State") : createClientAuthError(stateNotFound, "Server State");
- }
- let decodedServerResponseState;
- let decodedRequestState;
- try {
- decodedServerResponseState = decodeURIComponent(serverResponse.state);
- } catch (e4) {
- throw createClientAuthError(invalidState, serverResponse.state);
- }
- try {
- decodedRequestState = decodeURIComponent(requestState);
- } catch (e4) {
- throw createClientAuthError(invalidState, serverResponse.state);
- }
- if (decodedServerResponseState !== decodedRequestState) {
- throw createClientAuthError(stateMismatch);
- }
- if (serverResponse.error || serverResponse.error_description || serverResponse.suberror) {
- const serverErrorNo = parseServerErrorNo(serverResponse);
- if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {
- throw new InteractionRequiredAuthError(serverResponse.error || "", serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || "", serverResponse.trace_id || "", serverResponse.correlation_id || "", serverResponse.claims || "", serverErrorNo);
- }
- throw new ServerError(serverResponse.error || "", serverResponse.error_description, serverResponse.suberror, serverErrorNo);
- }
-}
-function parseServerErrorNo(serverResponse) {
- const errorCodePrefix = "code=";
- const errorCodePrefixIndex = serverResponse.error_uri?.lastIndexOf(errorCodePrefix);
- return errorCodePrefixIndex && errorCodePrefixIndex >= 0 ? serverResponse.error_uri?.substring(errorCodePrefixIndex + errorCodePrefix.length) : undefined;
-}
-function extractAccountSid(account) {
- return account.idTokenClaims?.sid || null;
-}
-function extractLoginHint(account) {
- return account.loginHint || account.idTokenClaims?.login_hint || null;
-}
-var init_Authorize = __esm(() => {
- init_RequestParameterBuilder();
- init_AADServerParamKeys();
- init_Constants();
- init_ClientInfo();
- init_UrlUtils();
- init_UrlString();
- init_ClientAuthError();
- init_InteractionRequiredAuthError();
- init_ServerError();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/request/BaseAuthRequest.mjs
-function enforceResourceParameter(isMcp, request2) {
- if (!isMcp) {
- return;
- }
- if (request2.resource && (containsResourceParam(request2.extraParameters) || containsResourceParam(request2.extraQueryParameters))) {
- throw createClientAuthError(misplacedResourceParam);
- }
- if (!request2.resource) {
- throw createClientAuthError(resourceParameterRequired);
- }
-}
-function containsResourceParam(params) {
- if (!params) {
- return false;
- }
- return Object.prototype.hasOwnProperty.call(params, "resource");
-}
-var init_BaseAuthRequest = __esm(() => {
- init_ClientAuthError();
- init_ClientAuthErrorCodes();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/error/AuthErrorCodes.mjs
-var exports_AuthErrorCodes = {};
-__export(exports_AuthErrorCodes, {
- unexpectedError: () => unexpectedError,
- postRequestFailed: () => postRequestFailed
-});
-var unexpectedError = "unexpected_error", postRequestFailed = "post_request_failed";
-var init_AuthErrorCodes = __esm(() => {
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs
-function makeExtraSkuString(params) {
- const { skus, libraryName, libraryVersion, extensionName, extensionVersion } = params;
- const skuMap = new Map([
- [0, [libraryName, libraryVersion]],
- [2, [extensionName, extensionVersion]]
- ]);
- let skuArr = [];
- if (skus?.length) {
- skuArr = skus.split(skuGroupSeparator);
- if (skuArr.length < 4) {
- return skus;
- }
- } else {
- skuArr = Array.from({ length: 4 }, () => skuValueSeparator);
- }
- skuMap.forEach((value, key) => {
- if (value.length === 2 && value[0]?.length && value[1]?.length) {
- setSku({
- skuArr,
- index: key,
- skuName: value[0],
- skuVersion: value[1]
- });
- }
- });
- return skuArr.join(skuGroupSeparator);
-}
-function setSku(params) {
- const { skuArr, index: index2, skuName, skuVersion } = params;
- if (index2 >= skuArr.length) {
- return;
- }
- skuArr[index2] = [skuName, skuVersion].join(skuValueSeparator);
-}
-
-class ServerTelemetryManager {
- constructor(telemetryRequest, cacheManager) {
- this.cacheOutcome = CacheOutcome.NOT_APPLICABLE;
- this.cacheManager = cacheManager;
- this.apiId = telemetryRequest.apiId;
- this.correlationId = telemetryRequest.correlationId;
- this.wrapperSKU = telemetryRequest.wrapperSKU || "";
- this.wrapperVer = telemetryRequest.wrapperVer || "";
- this.telemetryCacheKey = SERVER_TELEM_CACHE_KEY + CACHE_KEY_SEPARATOR + telemetryRequest.clientId;
- }
- generateCurrentRequestHeaderValue() {
- const request2 = `${this.apiId}${SERVER_TELEM_VALUE_SEPARATOR}${this.cacheOutcome}`;
- const platformFieldsArr = [this.wrapperSKU, this.wrapperVer];
- const nativeBrokerErrorCode = this.getNativeBrokerErrorCode();
- if (nativeBrokerErrorCode?.length) {
- platformFieldsArr.push(`broker_error=${nativeBrokerErrorCode}`);
- }
- const platformFields = platformFieldsArr.join(SERVER_TELEM_VALUE_SEPARATOR);
- const regionDiscoveryFields = this.getRegionDiscoveryFields();
- const requestWithRegionDiscoveryFields = [
- request2,
- regionDiscoveryFields
- ].join(SERVER_TELEM_VALUE_SEPARATOR);
- return [
- SERVER_TELEM_SCHEMA_VERSION,
- requestWithRegionDiscoveryFields,
- platformFields
- ].join(SERVER_TELEM_CATEGORY_SEPARATOR);
- }
- generateLastRequestHeaderValue() {
- const lastRequests = this.getLastRequests();
- const maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests);
- const failedRequests = lastRequests.failedRequests.slice(0, 2 * maxErrors).join(SERVER_TELEM_VALUE_SEPARATOR);
- const errors6 = lastRequests.errors.slice(0, maxErrors).join(SERVER_TELEM_VALUE_SEPARATOR);
- const errorCount = lastRequests.errors.length;
- const overflow = maxErrors < errorCount ? SERVER_TELEM_OVERFLOW_TRUE : SERVER_TELEM_OVERFLOW_FALSE;
- const platformFields = [errorCount, overflow].join(SERVER_TELEM_VALUE_SEPARATOR);
- return [
- SERVER_TELEM_SCHEMA_VERSION,
- lastRequests.cacheHits,
- failedRequests,
- errors6,
- platformFields
- ].join(SERVER_TELEM_CATEGORY_SEPARATOR);
- }
- cacheFailedRequest(error44) {
- const lastRequests = this.getLastRequests();
- if (lastRequests.errors.length >= SERVER_TELEM_MAX_CACHED_ERRORS) {
- lastRequests.failedRequests.shift();
- lastRequests.failedRequests.shift();
- lastRequests.errors.shift();
- }
- lastRequests.failedRequests.push(this.apiId, this.correlationId);
- if (error44 instanceof Error && !!error44 && error44.toString()) {
- if (error44 instanceof AuthError) {
- if (error44.subError) {
- lastRequests.errors.push(error44.subError);
- } else if (error44.errorCode) {
- lastRequests.errors.push(error44.errorCode);
- } else {
- lastRequests.errors.push(error44.toString());
- }
- } else {
- lastRequests.errors.push(error44.toString());
- }
- } else {
- lastRequests.errors.push(SERVER_TELEM_UNKNOWN_ERROR);
- }
- this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
- return;
- }
- incrementCacheHits() {
- const lastRequests = this.getLastRequests();
- lastRequests.cacheHits += 1;
- this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
- return lastRequests.cacheHits;
- }
- getLastRequests() {
- const initialValue = {
- failedRequests: [],
- errors: [],
- cacheHits: 0
- };
- const lastRequests = this.cacheManager.getServerTelemetry(this.telemetryCacheKey, this.correlationId);
- return lastRequests || initialValue;
- }
- clearTelemetryCache() {
- const lastRequests = this.getLastRequests();
- const numErrorsFlushed = ServerTelemetryManager.maxErrorsToSend(lastRequests);
- const errorCount = lastRequests.errors.length;
- if (numErrorsFlushed === errorCount) {
- this.cacheManager.removeItem(this.telemetryCacheKey, this.correlationId);
- } else {
- const serverTelemEntity = {
- failedRequests: lastRequests.failedRequests.slice(numErrorsFlushed * 2),
- errors: lastRequests.errors.slice(numErrorsFlushed),
- cacheHits: 0
- };
- this.cacheManager.setServerTelemetry(this.telemetryCacheKey, serverTelemEntity, this.correlationId);
- }
- }
- static maxErrorsToSend(serverTelemetryEntity) {
- let i5;
- let maxErrors = 0;
- let dataSize = 0;
- const errorCount = serverTelemetryEntity.errors.length;
- for (i5 = 0;i5 < errorCount; i5++) {
- const apiId = serverTelemetryEntity.failedRequests[2 * i5] || "";
- const correlationId = serverTelemetryEntity.failedRequests[2 * i5 + 1] || "";
- const errorCode = serverTelemetryEntity.errors[i5] || "";
- dataSize += apiId.toString().length + correlationId.toString().length + errorCode.length + 3;
- if (dataSize < SERVER_TELEM_MAX_LAST_HEADER_BYTES) {
- maxErrors += 1;
- } else {
- break;
- }
- }
- return maxErrors;
- }
- getRegionDiscoveryFields() {
- const regionDiscoveryFields = [];
- regionDiscoveryFields.push(this.regionUsed || "");
- regionDiscoveryFields.push(this.regionSource || "");
- regionDiscoveryFields.push(this.regionOutcome || "");
- return regionDiscoveryFields.join(",");
- }
- updateRegionDiscoveryMetadata(regionDiscoveryMetadata) {
- this.regionUsed = regionDiscoveryMetadata.region_used;
- this.regionSource = regionDiscoveryMetadata.region_source;
- this.regionOutcome = regionDiscoveryMetadata.region_outcome;
- }
- setCacheOutcome(cacheOutcome) {
- this.cacheOutcome = cacheOutcome;
- }
- setNativeBrokerErrorCode(errorCode) {
- const lastRequests = this.getLastRequests();
- lastRequests.nativeBrokerErrorCode = errorCode;
- this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
- }
- getNativeBrokerErrorCode() {
- return this.getLastRequests().nativeBrokerErrorCode;
- }
- clearNativeBrokerErrorCode() {
- const lastRequests = this.getLastRequests();
- delete lastRequests.nativeBrokerErrorCode;
- this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
- }
- static makeExtraSkuString(params) {
- return makeExtraSkuString(params);
- }
-}
-var skuGroupSeparator = ",", skuValueSeparator = "|";
-var init_ServerTelemetryManager = __esm(() => {
- init_Constants();
- init_AuthError();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-common/dist/index-node.mjs
-var init_index_node = __esm(() => {
- init_AuthorizationCodeClient();
- init_RefreshTokenClient();
- init_SilentFlowClient();
- init_ClientConfiguration();
- init_CcsCredential();
- init_Authority();
- init_AuthorityOptions();
- init_ProtocolMode();
- init_CacheManager();
- init_UrlString();
- init_ICrypto();
- init_Authorize();
- init_Token();
- init_BaseAuthRequest();
- init_RequestParameterBuilder();
- init_ResponseHandler();
- init_ScopeSet();
- init_Logger();
- init_InteractionRequiredAuthError();
- init_InteractionRequiredAuthErrorCodes();
- init_AuthError();
- init_AuthErrorCodes();
- init_ServerError();
- init_NetworkError();
- init_ClientAuthError();
- init_ClientAuthErrorCodes();
- init_ClientConfigurationError();
- init_ClientConfigurationErrorCodes();
- init_Constants();
- init_StringUtils();
- init_ServerTelemetryManager();
- init_AuthToken();
- init_AuthorityFactory();
- init_CacheHelpers();
- init_TimeUtils();
- init_UrlUtils();
- init_AADServerParamKeys();
- init_AccountEntityUtils();
- init_TokenCacheContext();
- init_ClientAssertionUtils();
- init_StubPerformanceClient();
- /*! @azure/msal-common v16.4.0 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/cache/serializer/Deserializer.mjs
-class Deserializer {
- static deserializeJSONBlob(jsonFile) {
- const deserializedCache = !jsonFile ? {} : JSON.parse(jsonFile);
- return deserializedCache;
- }
- static deserializeAccounts(accounts) {
- const accountObjects = {};
- if (accounts) {
- Object.keys(accounts).map(function(key) {
- const serializedAcc = accounts[key];
- const mappedAcc = {
- homeAccountId: serializedAcc.home_account_id,
- environment: serializedAcc.environment,
- realm: serializedAcc.realm,
- localAccountId: serializedAcc.local_account_id,
- username: serializedAcc.username,
- authorityType: serializedAcc.authority_type,
- name: serializedAcc.name,
- clientInfo: serializedAcc.client_info,
- lastModificationTime: serializedAcc.last_modification_time,
- lastModificationApp: serializedAcc.last_modification_app,
- tenantProfiles: serializedAcc.tenantProfiles?.map((serializedTenantProfile) => {
- return JSON.parse(serializedTenantProfile);
- }),
- lastUpdatedAt: Date.now().toString()
- };
- const account = {};
- CacheManager.toObject(account, mappedAcc);
- accountObjects[key] = account;
- });
- }
- return accountObjects;
- }
- static deserializeIdTokens(idTokens) {
- const idObjects = {};
- if (idTokens) {
- Object.keys(idTokens).map(function(key) {
- const serializedIdT = idTokens[key];
- const idToken = {
- homeAccountId: serializedIdT.home_account_id,
- environment: serializedIdT.environment,
- credentialType: serializedIdT.credential_type,
- clientId: serializedIdT.client_id,
- secret: serializedIdT.secret,
- realm: serializedIdT.realm,
- lastUpdatedAt: Date.now().toString()
- };
- idObjects[key] = idToken;
- });
- }
- return idObjects;
- }
- static deserializeAccessTokens(accessTokens) {
- const atObjects = {};
- if (accessTokens) {
- Object.keys(accessTokens).map(function(key) {
- const serializedAT = accessTokens[key];
- const accessToken = {
- homeAccountId: serializedAT.home_account_id,
- environment: serializedAT.environment,
- credentialType: serializedAT.credential_type,
- clientId: serializedAT.client_id,
- secret: serializedAT.secret,
- realm: serializedAT.realm,
- target: serializedAT.target,
- cachedAt: serializedAT.cached_at,
- expiresOn: serializedAT.expires_on,
- extendedExpiresOn: serializedAT.extended_expires_on,
- refreshOn: serializedAT.refresh_on,
- keyId: serializedAT.key_id,
- tokenType: serializedAT.token_type,
- userAssertionHash: serializedAT.userAssertionHash,
- resource: serializedAT.resource,
- lastUpdatedAt: Date.now().toString()
- };
- atObjects[key] = accessToken;
- });
- }
- return atObjects;
- }
- static deserializeRefreshTokens(refreshTokens) {
- const rtObjects = {};
- if (refreshTokens) {
- Object.keys(refreshTokens).map(function(key) {
- const serializedRT = refreshTokens[key];
- const refreshToken = {
- homeAccountId: serializedRT.home_account_id,
- environment: serializedRT.environment,
- credentialType: serializedRT.credential_type,
- clientId: serializedRT.client_id,
- secret: serializedRT.secret,
- familyId: serializedRT.family_id,
- target: serializedRT.target,
- realm: serializedRT.realm,
- lastUpdatedAt: Date.now().toString()
- };
- rtObjects[key] = refreshToken;
- });
- }
- return rtObjects;
- }
- static deserializeAppMetadata(appMetadata) {
- const appMetadataObjects = {};
- if (appMetadata) {
- Object.keys(appMetadata).map(function(key) {
- const serializedAmdt = appMetadata[key];
- appMetadataObjects[key] = {
- clientId: serializedAmdt.client_id,
- environment: serializedAmdt.environment,
- familyId: serializedAmdt.family_id
- };
- });
- }
- return appMetadataObjects;
- }
- static deserializeAllCache(jsonCache) {
- return {
- accounts: jsonCache.Account ? this.deserializeAccounts(jsonCache.Account) : {},
- idTokens: jsonCache.IdToken ? this.deserializeIdTokens(jsonCache.IdToken) : {},
- accessTokens: jsonCache.AccessToken ? this.deserializeAccessTokens(jsonCache.AccessToken) : {},
- refreshTokens: jsonCache.RefreshToken ? this.deserializeRefreshTokens(jsonCache.RefreshToken) : {},
- appMetadata: jsonCache.AppMetadata ? this.deserializeAppMetadata(jsonCache.AppMetadata) : {}
- };
- }
-}
-var init_Deserializer = __esm(() => {
- init_index_node();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/internals.mjs
-var exports_internals = {};
-__export(exports_internals, {
- Serializer: () => Serializer,
- Deserializer: () => Deserializer
-});
-var init_internals = __esm(() => {
- init_Serializer();
- init_Deserializer();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/utils/Constants.mjs
-var DEFAULT_MANAGED_IDENTITY_ID = "system_assigned_managed_identity", MANAGED_IDENTITY_DEFAULT_TENANT = "managed_identity", DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY, ManagedIdentityHeaders, ManagedIdentityQueryParameters, ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, HttpMethod2, REGION_ENVIRONMENT_VARIABLE = "REGION_NAME", MSAL_FORCE_REGION = "MSAL_FORCE_REGION", RANDOM_OCTET_SIZE = 32, Hash5, CharSet, CACHE, Constants, ApiId, JwtConstants, LOOPBACK_SERVER_CONSTANTS, AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES = 4096;
-var init_Constants2 = __esm(() => {
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY = `https://login.microsoftonline.com/${MANAGED_IDENTITY_DEFAULT_TENANT}/`;
- ManagedIdentityHeaders = {
- AUTHORIZATION_HEADER_NAME: "Authorization",
- METADATA_HEADER_NAME: "Metadata",
- APP_SERVICE_SECRET_HEADER_NAME: "X-IDENTITY-HEADER",
- ML_AND_SF_SECRET_HEADER_NAME: "secret"
- };
- ManagedIdentityQueryParameters = {
- API_VERSION: "api-version",
- RESOURCE: "resource",
- SHA256_TOKEN_TO_REFRESH: "token_sha256_to_refresh",
- XMS_CC: "xms_cc"
- };
- ManagedIdentityEnvironmentVariableNames = {
- AZURE_POD_IDENTITY_AUTHORITY_HOST: "AZURE_POD_IDENTITY_AUTHORITY_HOST",
- DEFAULT_IDENTITY_CLIENT_ID: "DEFAULT_IDENTITY_CLIENT_ID",
- IDENTITY_ENDPOINT: "IDENTITY_ENDPOINT",
- IDENTITY_HEADER: "IDENTITY_HEADER",
- IDENTITY_SERVER_THUMBPRINT: "IDENTITY_SERVER_THUMBPRINT",
- IMDS_ENDPOINT: "IMDS_ENDPOINT",
- MSI_ENDPOINT: "MSI_ENDPOINT",
- MSI_SECRET: "MSI_SECRET"
- };
- ManagedIdentitySourceNames = {
- APP_SERVICE: "AppService",
- AZURE_ARC: "AzureArc",
- CLOUD_SHELL: "CloudShell",
- DEFAULT_TO_IMDS: "DefaultToImds",
- IMDS: "Imds",
- MACHINE_LEARNING: "MachineLearning",
- SERVICE_FABRIC: "ServiceFabric"
- };
- ManagedIdentityIdType = {
- SYSTEM_ASSIGNED: "system-assigned",
- USER_ASSIGNED_CLIENT_ID: "user-assigned-client-id",
- USER_ASSIGNED_RESOURCE_ID: "user-assigned-resource-id",
- USER_ASSIGNED_OBJECT_ID: "user-assigned-object-id"
- };
- HttpMethod2 = {
- GET: "GET",
- POST: "POST"
- };
- Hash5 = {
- SHA256: "sha256"
- };
- CharSet = {
- CV_CHARSET: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
- };
- CACHE = {
- KEY_SEPARATOR: "-"
- };
- Constants = {
- MSAL_SKU: "msal.js.node",
- JWT_BEARER_ASSERTION_TYPE: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
- HTTP_PROTOCOL: "http://",
- LOCALHOST: "localhost"
- };
- ApiId = {
- acquireTokenSilent: 62,
- acquireTokenByUsernamePassword: 371,
- acquireTokenByDeviceCode: 671,
- acquireTokenByClientCredential: 771,
- acquireTokenByOBO: 772,
- acquireTokenWithManagedIdentity: 773,
- acquireTokenByCode: 871,
- acquireTokenByRefreshToken: 872
- };
- JwtConstants = {
- RSA_256: "RS256",
- PSS_256: "PS256",
- X5T_256: "x5t#S256",
- X5T: "x5t",
- X5C: "x5c",
- AUDIENCE: "aud",
- EXPIRATION_TIME: "exp",
- ISSUER: "iss",
- SUBJECT: "sub",
- NOT_BEFORE: "nbf",
- JWT_ID: "jti"
- };
- LOOPBACK_SERVER_CONSTANTS = {
- INTERVAL_MS: 100,
- TIMEOUT_MS: 5000
- };
-});
-
-// node_modules/@azure/msal-node/dist/network/HttpClient.mjs
-class HttpClient {
- async sendGetRequestAsync(url3, options2, timeout) {
- return this.sendRequest(url3, HttpMethod2.GET, options2, timeout);
- }
- async sendPostRequestAsync(url3, options2) {
- return this.sendRequest(url3, HttpMethod2.POST, options2);
- }
- async sendRequest(url3, method, options2, timeout) {
- const controller = new AbortController;
- let timeoutId;
- if (timeout) {
- timeoutId = setTimeout(() => {
- controller.abort();
- }, timeout);
- }
- const fetchOptions = {
- method,
- headers: getFetchHeaders(options2),
- signal: controller.signal
- };
- if (method === HttpMethod2.POST) {
- fetchOptions.body = options2?.body || "";
- }
- let response7;
- try {
- response7 = await fetch(url3, fetchOptions);
- } catch (error44) {
- if (timeoutId) {
- clearTimeout(timeoutId);
- }
- if (error44 instanceof Error && error44.name === "AbortError") {
- throw createAuthError(exports_ClientAuthErrorCodes.networkError, "Request timeout");
- }
- const baseAuthError = createAuthError(exports_ClientAuthErrorCodes.networkError, `Network request failed: ${error44 instanceof Error ? error44.message : "unknown"}`);
- throw createNetworkError(baseAuthError, undefined, undefined, error44 instanceof Error ? error44 : undefined);
- }
- if (timeoutId) {
- clearTimeout(timeoutId);
- }
- try {
- return {
- headers: getHeaderDict(response7.headers),
- body: await response7.json(),
- status: response7.status
- };
- } catch (error44) {
- throw createAuthError(exports_ClientAuthErrorCodes.tokenParsingError, `Failed to parse response: ${error44 instanceof Error ? error44.message : "unknown"}`);
- }
- }
-}
-function getHeaderDict(headers) {
- const headerDict = {};
- headers.forEach((value, key) => {
- headerDict[key] = value;
- });
- return headerDict;
-}
-function getFetchHeaders(options2) {
- const headers = new Headers;
- if (!(options2 && options2.headers)) {
- return headers;
- }
- Object.entries(options2.headers).forEach(([key, value]) => {
- headers.append(key, value);
- });
- return headers;
-}
-var init_HttpClient = __esm(() => {
- init_index_node();
- init_Constants2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/error/ManagedIdentityErrorCodes.mjs
-var invalidFileExtension = "invalid_file_extension", invalidFilePath = "invalid_file_path", invalidManagedIdentityIdType = "invalid_managed_identity_id_type", invalidSecret = "invalid_secret", missingId = "missing_client_id", networkUnavailable = "network_unavailable", platformNotSupported = "platform_not_supported", unableToCreateAzureArc = "unable_to_create_azure_arc", unableToCreateCloudShell = "unable_to_create_cloud_shell", unableToCreateSource = "unable_to_create_source", unableToReadSecretFile = "unable_to_read_secret_file", userAssignedNotAvailableAtRuntime = "user_assigned_not_available_at_runtime", wwwAuthenticateHeaderMissing = "www_authenticate_header_missing", wwwAuthenticateHeaderUnsupportedFormat = "www_authenticate_header_unsupported_format", MsiEnvironmentVariableUrlMalformedErrorCodes;
-var init_ManagedIdentityErrorCodes = __esm(() => {
- init_Constants2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- MsiEnvironmentVariableUrlMalformedErrorCodes = {
- [ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST]: "azure_pod_identity_authority_host_url_malformed",
- [ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT]: "identity_endpoint_url_malformed",
- [ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT]: "imds_endpoint_url_malformed",
- [ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT]: "msi_endpoint_url_malformed"
- };
-});
-
-// node_modules/@azure/msal-node/dist/error/ManagedIdentityError.mjs
-function createManagedIdentityError(errorCode) {
- return new ManagedIdentityError(errorCode);
-}
-var ManagedIdentityErrorMessages, ManagedIdentityError;
-var init_ManagedIdentityError = __esm(() => {
- init_index_node();
- init_ManagedIdentityErrorCodes();
- init_Constants2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- ManagedIdentityErrorMessages = {
- [invalidFileExtension]: "The file path in the WWW-Authenticate header does not contain a .key file.",
- [invalidFilePath]: "The file path in the WWW-Authenticate header is not in a valid Windows or Linux Format.",
- [invalidManagedIdentityIdType]: "More than one ManagedIdentityIdType was provided.",
- [invalidSecret]: "The secret in the file on the file path in the WWW-Authenticate header is greater than 4096 bytes.",
- [platformNotSupported]: "The platform is not supported by Azure Arc. Azure Arc only supports Windows and Linux.",
- [missingId]: "A ManagedIdentityId id was not provided.",
- [MsiEnvironmentVariableUrlMalformedErrorCodes.AZURE_POD_IDENTITY_AUTHORITY_HOST]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST}' environment variable is malformed.`,
- [MsiEnvironmentVariableUrlMalformedErrorCodes.IDENTITY_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' environment variable is malformed.`,
- [MsiEnvironmentVariableUrlMalformedErrorCodes.IMDS_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT}' environment variable is malformed.`,
- [MsiEnvironmentVariableUrlMalformedErrorCodes.MSI_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT}' environment variable is malformed.`,
- [networkUnavailable]: "Authentication unavailable. The request to the managed identity endpoint timed out.",
- [unableToCreateAzureArc]: "Azure Arc Managed Identities can only be system assigned.",
- [unableToCreateCloudShell]: "Cloud Shell Managed Identities can only be system assigned.",
- [unableToCreateSource]: "Unable to create a Managed Identity source based on environment variables.",
- [unableToReadSecretFile]: "Unable to read the secret file.",
- [userAssignedNotAvailableAtRuntime]: "Service Fabric user assigned managed identity ClientId or ResourceId is not configurable at runtime.",
- [wwwAuthenticateHeaderMissing]: "A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is missing.",
- [wwwAuthenticateHeaderUnsupportedFormat]: "A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is in an unsupported format."
- };
- ManagedIdentityError = class ManagedIdentityError extends AuthError {
- constructor(errorCode) {
- super(errorCode, ManagedIdentityErrorMessages[errorCode]);
- this.name = "ManagedIdentityError";
- Object.setPrototypeOf(this, ManagedIdentityError.prototype);
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/config/ManagedIdentityId.mjs
-class ManagedIdentityId {
- get id() {
- return this._id;
- }
- set id(value) {
- this._id = value;
- }
- get idType() {
- return this._idType;
- }
- set idType(value) {
- this._idType = value;
- }
- constructor(managedIdentityIdParams) {
- const userAssignedClientId = managedIdentityIdParams?.userAssignedClientId;
- const userAssignedResourceId = managedIdentityIdParams?.userAssignedResourceId;
- const userAssignedObjectId = managedIdentityIdParams?.userAssignedObjectId;
- if (userAssignedClientId) {
- if (userAssignedResourceId || userAssignedObjectId) {
- throw createManagedIdentityError(invalidManagedIdentityIdType);
- }
- this.id = userAssignedClientId;
- this.idType = ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID;
- } else if (userAssignedResourceId) {
- if (userAssignedClientId || userAssignedObjectId) {
- throw createManagedIdentityError(invalidManagedIdentityIdType);
- }
- this.id = userAssignedResourceId;
- this.idType = ManagedIdentityIdType.USER_ASSIGNED_RESOURCE_ID;
- } else if (userAssignedObjectId) {
- if (userAssignedClientId || userAssignedResourceId) {
- throw createManagedIdentityError(invalidManagedIdentityIdType);
- }
- this.id = userAssignedObjectId;
- this.idType = ManagedIdentityIdType.USER_ASSIGNED_OBJECT_ID;
- } else {
- this.id = DEFAULT_MANAGED_IDENTITY_ID;
- this.idType = ManagedIdentityIdType.SYSTEM_ASSIGNED;
- }
- }
-}
-var init_ManagedIdentityId = __esm(() => {
- init_ManagedIdentityError();
- init_Constants2();
- init_ManagedIdentityErrorCodes();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/error/NodeAuthError.mjs
-var NodeAuthErrorMessage, NodeAuthError;
-var init_NodeAuthError = __esm(() => {
- init_index_node();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- NodeAuthErrorMessage = {
- invalidLoopbackAddressType: {
- code: "invalid_loopback_server_address_type",
- desc: "Loopback server address is not type string. This is unexpected."
- },
- unableToLoadRedirectUri: {
- code: "unable_to_load_redirectUrl",
- desc: "Loopback server callback was invoked without a url. This is unexpected."
- },
- noAuthCodeInResponse: {
- code: "no_auth_code_in_response",
- desc: "No auth code found in the server response. Please check your network trace to determine what happened."
- },
- noLoopbackServerExists: {
- code: "no_loopback_server_exists",
- desc: "No loopback server exists yet."
- },
- loopbackServerAlreadyExists: {
- code: "loopback_server_already_exists",
- desc: "Loopback server already exists. Cannot create another."
- },
- loopbackServerTimeout: {
- code: "loopback_server_timeout",
- desc: "Timed out waiting for auth code listener to be registered."
- },
- stateNotFoundError: {
- code: "state_not_found",
- desc: "State not found. Please verify that the request originated from msal."
- },
- thumbprintMissing: {
- code: "thumbprint_missing_from_client_certificate",
- desc: "Client certificate does not contain a SHA-1 or SHA-256 thumbprint."
- },
- redirectUriNotSupported: {
- code: "redirect_uri_not_supported",
- desc: "RedirectUri is not supported in this scenario. Please remove redirectUri from the request."
- }
- };
- NodeAuthError = class NodeAuthError extends AuthError {
- constructor(errorCode, errorMessage2) {
- super(errorCode, errorMessage2);
- this.name = "NodeAuthError";
- }
- static createInvalidLoopbackAddressTypeError() {
- return new NodeAuthError(NodeAuthErrorMessage.invalidLoopbackAddressType.code, `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`);
- }
- static createUnableToLoadRedirectUrlError() {
- return new NodeAuthError(NodeAuthErrorMessage.unableToLoadRedirectUri.code, `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`);
- }
- static createNoAuthCodeInResponseError() {
- return new NodeAuthError(NodeAuthErrorMessage.noAuthCodeInResponse.code, `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`);
- }
- static createNoLoopbackServerExistsError() {
- return new NodeAuthError(NodeAuthErrorMessage.noLoopbackServerExists.code, `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`);
- }
- static createLoopbackServerAlreadyExistsError() {
- return new NodeAuthError(NodeAuthErrorMessage.loopbackServerAlreadyExists.code, `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`);
- }
- static createLoopbackServerTimeoutError() {
- return new NodeAuthError(NodeAuthErrorMessage.loopbackServerTimeout.code, `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`);
- }
- static createStateNotFoundError() {
- return new NodeAuthError(NodeAuthErrorMessage.stateNotFoundError.code, NodeAuthErrorMessage.stateNotFoundError.desc);
- }
- static createThumbprintMissingError() {
- return new NodeAuthError(NodeAuthErrorMessage.thumbprintMissing.code, NodeAuthErrorMessage.thumbprintMissing.desc);
- }
- static createRedirectUriNotSupportedError() {
- return new NodeAuthError(NodeAuthErrorMessage.redirectUriNotSupported.code, NodeAuthErrorMessage.redirectUriNotSupported.desc);
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/config/Configuration.mjs
-function buildAppConfiguration({ auth: auth13, broker, cache: cache5, system, telemetry }) {
- const systemOptions = {
- ...DEFAULT_SYSTEM_OPTIONS2,
- networkClient: new HttpClient,
- loggerOptions: system?.loggerOptions || DEFAULT_LOGGER_OPTIONS,
- disableInternalRetries: system?.disableInternalRetries || false
- };
- if (!!auth13.clientCertificate && !!!auth13.clientCertificate.thumbprint && !!!auth13.clientCertificate.thumbprintSha256) {
- throw NodeAuthError.createStateNotFoundError();
- }
- return {
- auth: { ...DEFAULT_AUTH_OPTIONS, ...auth13 },
- broker: { ...broker },
- cache: { ...cache5 },
- system: { ...systemOptions, ...system },
- telemetry: { ...DEFAULT_TELEMETRY_OPTIONS2, ...telemetry }
- };
-}
-function buildManagedIdentityConfiguration({ clientCapabilities, managedIdentityIdParams, system }) {
- const managedIdentityId = new ManagedIdentityId(managedIdentityIdParams);
- const loggerOptions = system?.loggerOptions || DEFAULT_LOGGER_OPTIONS;
- let networkClient;
- if (system?.networkClient) {
- networkClient = system.networkClient;
- } else {
- networkClient = new HttpClient;
- }
- return {
- clientCapabilities: clientCapabilities || [],
- managedIdentityId,
- system: {
- loggerOptions,
- networkClient
- },
- disableInternalRetries: system?.disableInternalRetries || false
- };
-}
-var DEFAULT_AUTH_OPTIONS, DEFAULT_LOGGER_OPTIONS, DEFAULT_SYSTEM_OPTIONS2, DEFAULT_TELEMETRY_OPTIONS2;
-var init_Configuration = __esm(() => {
- init_index_node();
- init_HttpClient();
- init_ManagedIdentityId();
- init_NodeAuthError();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- DEFAULT_AUTH_OPTIONS = {
- clientId: "",
- authority: exports_Constants.DEFAULT_AUTHORITY,
- clientSecret: "",
- clientAssertion: "",
- clientCertificate: {
- thumbprint: "",
- thumbprintSha256: "",
- privateKey: "",
- x5c: ""
- },
- knownAuthorities: [],
- cloudDiscoveryMetadata: "",
- authorityMetadata: "",
- clientCapabilities: [],
- azureCloudOptions: {
- azureCloudInstance: AzureCloudInstance.None,
- tenant: ""
- },
- isMcp: false
- };
- DEFAULT_LOGGER_OPTIONS = {
- loggerCallback: () => {},
- piiLoggingEnabled: false,
- logLevel: LogLevel.Info
- };
- DEFAULT_SYSTEM_OPTIONS2 = {
- loggerOptions: DEFAULT_LOGGER_OPTIONS,
- networkClient: new HttpClient,
- disableInternalRetries: false,
- protocolMode: ProtocolMode.AAD
- };
- DEFAULT_TELEMETRY_OPTIONS2 = {
- application: {
- appName: "",
- appVersion: ""
- }
- };
-});
-
-// node_modules/uuid/dist/rng.js
-var require_rng = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = rng;
- var _crypto = _interopRequireDefault(__require("crypto"));
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var rnds8Pool = new Uint8Array(256);
- var poolPtr = rnds8Pool.length;
- function rng() {
- if (poolPtr > rnds8Pool.length - 16) {
- _crypto.default.randomFillSync(rnds8Pool);
- poolPtr = 0;
- }
- return rnds8Pool.slice(poolPtr, poolPtr += 16);
- }
-});
-
-// node_modules/uuid/dist/regex.js
-var require_regex = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _default3 = /^(?:[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 = _default3;
-});
-
-// node_modules/uuid/dist/validate.js
-var require_validate = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _regex2 = _interopRequireDefault(require_regex());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- function validate2(uuid5) {
- return typeof uuid5 === "string" && _regex2.default.test(uuid5);
- }
- var _default3 = validate2;
- exports.default = _default3;
-});
-
-// node_modules/uuid/dist/stringify.js
-var require_stringify = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _validate = _interopRequireDefault(require_validate());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var byteToHex = [];
- for (let i5 = 0;i5 < 256; ++i5) {
- byteToHex.push((i5 + 256).toString(16).substr(1));
- }
- function stringify(arr, offset = 0) {
- const uuid5 = (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]]).toLowerCase();
- if (!(0, _validate.default)(uuid5)) {
- throw TypeError("Stringified UUID is invalid");
- }
- return uuid5;
- }
- var _default3 = stringify;
- exports.default = _default3;
-});
-
-// node_modules/uuid/dist/v1.js
-var require_v1 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _rng = _interopRequireDefault(require_rng());
- var _stringify = _interopRequireDefault(require_stringify());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var _nodeId;
- var _clockseq;
- var _lastMSecs = 0;
- var _lastNSecs = 0;
- function v1(options2, buf, offset) {
- let i5 = buf && offset || 0;
- const b4 = buf || new Array(16);
- options2 = options2 || {};
- let node = options2.node || _nodeId;
- let clockseq = options2.clockseq !== undefined ? options2.clockseq : _clockseq;
- if (node == null || clockseq == null) {
- const seedBytes = options2.random || (options2.rng || _rng.default)();
- if (node == null) {
- node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
- }
- if (clockseq == null) {
- clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383;
- }
- }
- let msecs = options2.msecs !== undefined ? options2.msecs : Date.now();
- let nsecs = options2.nsecs !== undefined ? options2.nsecs : _lastNSecs + 1;
- const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4;
- if (dt < 0 && options2.clockseq === undefined) {
- clockseq = clockseq + 1 & 16383;
- }
- if ((dt < 0 || msecs > _lastMSecs) && options2.nsecs === undefined) {
- nsecs = 0;
- }
- if (nsecs >= 1e4) {
- throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
- }
- _lastMSecs = msecs;
- _lastNSecs = nsecs;
- _clockseq = clockseq;
- msecs += 12219292800000;
- const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;
- b4[i5++] = tl >>> 24 & 255;
- b4[i5++] = tl >>> 16 & 255;
- b4[i5++] = tl >>> 8 & 255;
- b4[i5++] = tl & 255;
- const tmh = msecs / 4294967296 * 1e4 & 268435455;
- b4[i5++] = tmh >>> 8 & 255;
- b4[i5++] = tmh & 255;
- b4[i5++] = tmh >>> 24 & 15 | 16;
- b4[i5++] = tmh >>> 16 & 255;
- b4[i5++] = clockseq >>> 8 | 128;
- b4[i5++] = clockseq & 255;
- for (let n5 = 0;n5 < 6; ++n5) {
- b4[i5 + n5] = node[n5];
- }
- return buf || (0, _stringify.default)(b4);
- }
- var _default3 = v1;
- exports.default = _default3;
-});
-
-// node_modules/uuid/dist/parse.js
-var require_parse3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _validate = _interopRequireDefault(require_validate());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- function parse8(uuid5) {
- if (!(0, _validate.default)(uuid5)) {
- throw TypeError("Invalid UUID");
- }
- let v4;
- const arr = new Uint8Array(16);
- arr[0] = (v4 = parseInt(uuid5.slice(0, 8), 16)) >>> 24;
- arr[1] = v4 >>> 16 & 255;
- arr[2] = v4 >>> 8 & 255;
- arr[3] = v4 & 255;
- arr[4] = (v4 = parseInt(uuid5.slice(9, 13), 16)) >>> 8;
- arr[5] = v4 & 255;
- arr[6] = (v4 = parseInt(uuid5.slice(14, 18), 16)) >>> 8;
- arr[7] = v4 & 255;
- arr[8] = (v4 = parseInt(uuid5.slice(19, 23), 16)) >>> 8;
- arr[9] = v4 & 255;
- arr[10] = (v4 = parseInt(uuid5.slice(24, 36), 16)) / 1099511627776 & 255;
- arr[11] = v4 / 4294967296 & 255;
- arr[12] = v4 >>> 24 & 255;
- arr[13] = v4 >>> 16 & 255;
- arr[14] = v4 >>> 8 & 255;
- arr[15] = v4 & 255;
- return arr;
- }
- var _default3 = parse8;
- exports.default = _default3;
-});
-
-// node_modules/uuid/dist/v35.js
-var require_v35 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = _default3;
- exports.URL = exports.DNS = undefined;
- var _stringify = _interopRequireDefault(require_stringify());
- var _parse2 = _interopRequireDefault(require_parse3());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- function stringToBytes(str) {
- str = unescape(encodeURIComponent(str));
- const bytes = [];
- for (let i5 = 0;i5 < str.length; ++i5) {
- bytes.push(str.charCodeAt(i5));
- }
- return bytes;
- }
- var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
- exports.DNS = DNS;
- var URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
- exports.URL = URL2;
- function _default3(name2, version4, hashfunc) {
- function generateUUID(value, namespace, buf, offset) {
- if (typeof value === "string") {
- value = stringToBytes(value);
- }
- if (typeof namespace === "string") {
- namespace = (0, _parse2.default)(namespace);
- }
- if (namespace.length !== 16) {
- throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
- }
- let bytes = new Uint8Array(16 + value.length);
- bytes.set(namespace);
- bytes.set(value, namespace.length);
- bytes = hashfunc(bytes);
- bytes[6] = bytes[6] & 15 | version4;
- bytes[8] = bytes[8] & 63 | 128;
- if (buf) {
- offset = offset || 0;
- for (let i5 = 0;i5 < 16; ++i5) {
- buf[offset + i5] = bytes[i5];
- }
- return buf;
- }
- return (0, _stringify.default)(bytes);
- }
- try {
- generateUUID.name = name2;
- } catch (err) {}
- generateUUID.DNS = DNS;
- generateUUID.URL = URL2;
- return generateUUID;
- }
-});
-
-// node_modules/uuid/dist/md5.js
-var require_md5 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _crypto = _interopRequireDefault(__require("crypto"));
- 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 _default3 = md5;
- exports.default = _default3;
-});
-
-// node_modules/uuid/dist/v3.js
-var require_v3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _v3 = _interopRequireDefault(require_v35());
- var _md = _interopRequireDefault(require_md5());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var v32 = (0, _v3.default)("v3", 48, _md.default);
- var _default3 = v32;
- exports.default = _default3;
-});
-
-// node_modules/uuid/dist/v4.js
-var require_v4 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _rng = _interopRequireDefault(require_rng());
- var _stringify = _interopRequireDefault(require_stringify());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- function v4(options2, buf, offset) {
- options2 = options2 || {};
- const rnds = options2.random || (options2.rng || _rng.default)();
- rnds[6] = rnds[6] & 15 | 64;
- rnds[8] = rnds[8] & 63 | 128;
- if (buf) {
- offset = offset || 0;
- for (let i5 = 0;i5 < 16; ++i5) {
- buf[offset + i5] = rnds[i5];
- }
- return buf;
- }
- return (0, _stringify.default)(rnds);
- }
- var _default3 = v4;
- exports.default = _default3;
-});
-
-// node_modules/uuid/dist/sha1.js
-var require_sha1 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _crypto = _interopRequireDefault(__require("crypto"));
- 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();
- }
- var _default3 = sha1;
- exports.default = _default3;
-});
-
-// node_modules/uuid/dist/v5.js
-var require_v5 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _v3 = _interopRequireDefault(require_v35());
- var _sha = _interopRequireDefault(require_sha1());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var v5 = (0, _v3.default)("v5", 80, _sha.default);
- var _default3 = v5;
- exports.default = _default3;
-});
-
-// node_modules/uuid/dist/nil.js
-var require_nil = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _default3 = "00000000-0000-0000-0000-000000000000";
- exports.default = _default3;
-});
-
-// node_modules/uuid/dist/version.js
-var require_version = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _validate = _interopRequireDefault(require_validate());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- function version4(uuid5) {
- if (!(0, _validate.default)(uuid5)) {
- throw TypeError("Invalid UUID");
- }
- return parseInt(uuid5.substr(14, 1), 16);
- }
- var _default3 = version4;
- exports.default = _default3;
-});
-
-// node_modules/uuid/dist/index.js
-var require_dist3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "v1", {
- enumerable: true,
- get: function() {
- return _v3.default;
- }
- });
- Object.defineProperty(exports, "v3", {
- enumerable: true,
- get: function() {
- return _v22.default;
- }
- });
- Object.defineProperty(exports, "v4", {
- enumerable: true,
- get: function() {
- return _v32.default;
- }
- });
- Object.defineProperty(exports, "v5", {
- enumerable: true,
- get: function() {
- return _v4.default;
- }
- });
- Object.defineProperty(exports, "NIL", {
- enumerable: true,
- get: function() {
- return _nil.default;
- }
- });
- Object.defineProperty(exports, "version", {
- enumerable: true,
- get: function() {
- return _version.default;
- }
- });
- Object.defineProperty(exports, "validate", {
- enumerable: true,
- get: function() {
- return _validate.default;
- }
- });
- Object.defineProperty(exports, "stringify", {
- enumerable: true,
- get: function() {
- return _stringify.default;
- }
- });
- Object.defineProperty(exports, "parse", {
- enumerable: true,
- get: function() {
- return _parse2.default;
- }
- });
- var _v3 = _interopRequireDefault(require_v1());
- var _v22 = _interopRequireDefault(require_v3());
- var _v32 = _interopRequireDefault(require_v4());
- var _v4 = _interopRequireDefault(require_v5());
- var _nil = _interopRequireDefault(require_nil());
- var _version = _interopRequireDefault(require_version());
- var _validate = _interopRequireDefault(require_validate());
- var _stringify = _interopRequireDefault(require_stringify());
- var _parse2 = _interopRequireDefault(require_parse3());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
-});
-
-// node_modules/uuid/wrapper.mjs
-var import_dist, v1, v32, v4, v5, NIL, version4, validate2, stringify, parse8;
-var init_wrapper = __esm(() => {
- import_dist = __toESM(require_dist3(), 1);
- v1 = import_dist.default.v1;
- v32 = import_dist.default.v3;
- v4 = import_dist.default.v4;
- v5 = import_dist.default.v5;
- NIL = import_dist.default.NIL;
- version4 = import_dist.default.version;
- validate2 = import_dist.default.validate;
- stringify = import_dist.default.stringify;
- parse8 = import_dist.default.parse;
-});
-
-// node_modules/@azure/msal-node/dist/crypto/GuidGenerator.mjs
-class GuidGenerator {
- generateGuid() {
- return v4();
- }
- isGuid(guid3) {
- const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
- return regexGuid.test(guid3);
- }
-}
-var init_GuidGenerator = __esm(() => {
- init_wrapper();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/utils/EncodingUtils.mjs
-class EncodingUtils {
- static base64Encode(str, encoding) {
- return Buffer.from(str, encoding).toString(exports_Constants.EncodingTypes.BASE64);
- }
- static base64EncodeUrl(str, encoding) {
- return EncodingUtils.base64Encode(str, encoding).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
- }
- static base64Decode(base64Str) {
- return Buffer.from(base64Str, exports_Constants.EncodingTypes.BASE64).toString("utf8");
- }
- static base64DecodeUrl(base64Str) {
- let str = base64Str.replace(/-/g, "+").replace(/_/g, "/");
- while (str.length % 4) {
- str += "=";
- }
- return EncodingUtils.base64Decode(str);
- }
-}
-var init_EncodingUtils = __esm(() => {
- init_index_node();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/crypto/HashUtils.mjs
-import crypto9 from "crypto";
-
-class HashUtils {
- sha256(buffer) {
- return crypto9.createHash(Hash5.SHA256).update(buffer).digest();
- }
-}
-var init_HashUtils = __esm(() => {
- init_Constants2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/crypto/PkceGenerator.mjs
-import crypto10 from "crypto";
-
-class PkceGenerator {
- constructor() {
- this.hashUtils = new HashUtils;
- }
- async generatePkceCodes() {
- const verifier = this.generateCodeVerifier();
- const challenge = this.generateCodeChallengeFromVerifier(verifier);
- return { verifier, challenge };
- }
- generateCodeVerifier() {
- const charArr = [];
- const maxNumber = 256 - 256 % CharSet.CV_CHARSET.length;
- while (charArr.length <= RANDOM_OCTET_SIZE) {
- const byte = crypto10.randomBytes(1)[0];
- if (byte >= maxNumber) {
- continue;
- }
- const index2 = byte % CharSet.CV_CHARSET.length;
- charArr.push(CharSet.CV_CHARSET[index2]);
- }
- const verifier = charArr.join("");
- return EncodingUtils.base64EncodeUrl(verifier);
- }
- generateCodeChallengeFromVerifier(codeVerifier) {
- return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(codeVerifier).toString(exports_Constants.EncodingTypes.BASE64), exports_Constants.EncodingTypes.BASE64);
- }
-}
-var init_PkceGenerator = __esm(() => {
- init_index_node();
- init_Constants2();
- init_EncodingUtils();
- init_HashUtils();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/crypto/CryptoProvider.mjs
-class CryptoProvider {
- constructor() {
- this.pkceGenerator = new PkceGenerator;
- this.guidGenerator = new GuidGenerator;
- this.hashUtils = new HashUtils;
- }
- base64UrlEncode() {
- throw new Error("Method not implemented.");
- }
- encodeKid() {
- throw new Error("Method not implemented.");
- }
- createNewGuid() {
- return this.guidGenerator.generateGuid();
- }
- base64Encode(input) {
- return EncodingUtils.base64Encode(input);
- }
- base64Decode(input) {
- return EncodingUtils.base64Decode(input);
- }
- generatePkceCodes() {
- return this.pkceGenerator.generatePkceCodes();
- }
- getPublicKeyThumbprint() {
- throw new Error("Method not implemented.");
- }
- removeTokenBindingKey() {
- throw new Error("Method not implemented.");
- }
- clearKeystore() {
- throw new Error("Method not implemented.");
- }
- signJwt() {
- throw new Error("Method not implemented.");
- }
- async hashString(plainText) {
- return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(plainText).toString(exports_Constants.EncodingTypes.BASE64), exports_Constants.EncodingTypes.BASE64);
- }
-}
-var init_CryptoProvider = __esm(() => {
- init_index_node();
- init_GuidGenerator();
- init_EncodingUtils();
- init_PkceGenerator();
- init_HashUtils();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/cache/CacheHelpers.mjs
-function generateCredentialKey(credential) {
- const familyId = credential.credentialType === exports_Constants.CredentialType.REFRESH_TOKEN && credential.familyId || credential.clientId;
- const scheme = credential.tokenType && credential.tokenType.toLowerCase() !== exports_Constants.AuthenticationScheme.BEARER.toLowerCase() ? credential.tokenType.toLowerCase() : "";
- const credentialKey = [
- credential.homeAccountId,
- credential.environment,
- credential.credentialType,
- familyId,
- credential.realm || "",
- credential.target || "",
- scheme
- ];
- return credentialKey.join(CACHE.KEY_SEPARATOR).toLowerCase();
-}
-function generateAccountKey(account) {
- const homeTenantId = account.homeAccountId.split(".")[1];
- const accountKey = [
- account.homeAccountId,
- account.environment,
- homeTenantId || account.tenantId || ""
- ];
- return accountKey.join(CACHE.KEY_SEPARATOR).toLowerCase();
-}
-var init_CacheHelpers2 = __esm(() => {
- init_index_node();
- init_Constants2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/cache/NodeStorage.mjs
-var NodeStorage;
-var init_NodeStorage = __esm(() => {
- init_index_node();
- init_Deserializer();
- init_Serializer();
- init_CacheHelpers2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- NodeStorage = class NodeStorage extends CacheManager {
- constructor(logger10, clientId, cryptoImpl, staticAuthorityOptions) {
- super(clientId, cryptoImpl, logger10, new StubPerformanceClient, staticAuthorityOptions);
- this.cache = {};
- this.changeEmitters = [];
- this.logger = logger10;
- }
- registerChangeEmitter(func) {
- this.changeEmitters.push(func);
- }
- emitChange() {
- this.changeEmitters.forEach((func) => func.call(null));
- }
- cacheToInMemoryCache(cache5) {
- const inMemoryCache = {
- accounts: {},
- idTokens: {},
- accessTokens: {},
- refreshTokens: {},
- appMetadata: {}
- };
- for (const key in cache5) {
- const value = cache5[key];
- if (typeof value !== "object") {
- continue;
- }
- if (exports_AccountEntityUtils.isAccountEntity(value)) {
- inMemoryCache.accounts[key] = value;
- } else if (exports_CacheHelpers.isIdTokenEntity(value)) {
- inMemoryCache.idTokens[key] = value;
- } else if (exports_CacheHelpers.isAccessTokenEntity(value)) {
- inMemoryCache.accessTokens[key] = value;
- } else if (exports_CacheHelpers.isRefreshTokenEntity(value)) {
- inMemoryCache.refreshTokens[key] = value;
- } else if (exports_CacheHelpers.isAppMetadataEntity(key, value)) {
- inMemoryCache.appMetadata[key] = value;
- } else {
- continue;
- }
- }
- return inMemoryCache;
- }
- inMemoryCacheToCache(inMemoryCache) {
- let cache5 = this.getCache();
- cache5 = {
- ...cache5,
- ...inMemoryCache.accounts,
- ...inMemoryCache.idTokens,
- ...inMemoryCache.accessTokens,
- ...inMemoryCache.refreshTokens,
- ...inMemoryCache.appMetadata
- };
- return cache5;
- }
- getInMemoryCache() {
- this.logger.trace("Getting in-memory cache", "");
- const inMemoryCache = this.cacheToInMemoryCache(this.getCache());
- return inMemoryCache;
- }
- setInMemoryCache(inMemoryCache) {
- this.logger.trace("Setting in-memory cache", "");
- const cache5 = this.inMemoryCacheToCache(inMemoryCache);
- this.setCache(cache5);
- this.emitChange();
- }
- getCache() {
- this.logger.trace("Getting cache key-value store", "");
- return this.cache;
- }
- setCache(cache5) {
- this.logger.trace("Setting cache key value store", "");
- this.cache = cache5;
- this.emitChange();
- }
- getItem(key) {
- this.logger.tracePii(`Item key: ${key}`, "");
- const cache5 = this.getCache();
- return cache5[key];
- }
- setItem(key, value) {
- this.logger.tracePii(`Item key: ${key}`, "");
- const cache5 = this.getCache();
- cache5[key] = value;
- this.setCache(cache5);
- }
- generateCredentialKey(credential) {
- return generateCredentialKey(credential);
- }
- generateAccountKey(account) {
- return generateAccountKey(account);
- }
- getAccountKeys() {
- const inMemoryCache = this.getInMemoryCache();
- const accountKeys = Object.keys(inMemoryCache.accounts);
- return accountKeys;
- }
- getTokenKeys() {
- const inMemoryCache = this.getInMemoryCache();
- const tokenKeys = {
- idToken: Object.keys(inMemoryCache.idTokens),
- accessToken: Object.keys(inMemoryCache.accessTokens),
- refreshToken: Object.keys(inMemoryCache.refreshTokens)
- };
- return tokenKeys;
- }
- getAccount(accountKey) {
- const cachedAccount = this.getItem(accountKey);
- return cachedAccount && typeof cachedAccount === "object" ? { ...cachedAccount } : null;
- }
- async setAccount(account) {
- const accountKey = this.generateAccountKey(exports_AccountEntityUtils.getAccountInfo(account));
- this.setItem(accountKey, account);
- }
- getIdTokenCredential(idTokenKey) {
- const idToken = this.getItem(idTokenKey);
- if (exports_CacheHelpers.isIdTokenEntity(idToken)) {
- return idToken;
- }
- return null;
- }
- async setIdTokenCredential(idToken) {
- const idTokenKey = this.generateCredentialKey(idToken);
- this.setItem(idTokenKey, idToken);
- }
- getAccessTokenCredential(accessTokenKey) {
- const accessToken = this.getItem(accessTokenKey);
- if (exports_CacheHelpers.isAccessTokenEntity(accessToken)) {
- return accessToken;
- }
- return null;
- }
- async setAccessTokenCredential(accessToken) {
- const accessTokenKey = this.generateCredentialKey(accessToken);
- this.setItem(accessTokenKey, accessToken);
- }
- getRefreshTokenCredential(refreshTokenKey) {
- const refreshToken = this.getItem(refreshTokenKey);
- if (exports_CacheHelpers.isRefreshTokenEntity(refreshToken)) {
- return refreshToken;
- }
- return null;
- }
- async setRefreshTokenCredential(refreshToken) {
- const refreshTokenKey = this.generateCredentialKey(refreshToken);
- this.setItem(refreshTokenKey, refreshToken);
- }
- getAppMetadata(appMetadataKey) {
- const appMetadata = this.getItem(appMetadataKey);
- if (exports_CacheHelpers.isAppMetadataEntity(appMetadataKey, appMetadata)) {
- return appMetadata;
- }
- return null;
- }
- setAppMetadata(appMetadata) {
- const appMetadataKey = exports_CacheHelpers.generateAppMetadataKey(appMetadata);
- this.setItem(appMetadataKey, appMetadata);
- }
- getServerTelemetry(serverTelemetrykey) {
- const serverTelemetryEntity = this.getItem(serverTelemetrykey);
- if (serverTelemetryEntity && exports_CacheHelpers.isServerTelemetryEntity(serverTelemetrykey, serverTelemetryEntity)) {
- return serverTelemetryEntity;
- }
- return null;
- }
- setServerTelemetry(serverTelemetryKey, serverTelemetry) {
- this.setItem(serverTelemetryKey, serverTelemetry);
- }
- getAuthorityMetadata(key) {
- const authorityMetadataEntity = this.getItem(key);
- if (authorityMetadataEntity && exports_CacheHelpers.isAuthorityMetadataEntity(key, authorityMetadataEntity)) {
- return authorityMetadataEntity;
- }
- return null;
- }
- getAuthorityMetadataKeys() {
- return this.getKeys().filter((key) => {
- return this.isAuthorityMetadata(key);
- });
- }
- setAuthorityMetadata(key, metadata) {
- this.setItem(key, metadata);
- }
- getThrottlingCache(throttlingCacheKey) {
- const throttlingCache = this.getItem(throttlingCacheKey);
- if (throttlingCache && exports_CacheHelpers.isThrottlingEntity(throttlingCacheKey, throttlingCache)) {
- return throttlingCache;
- }
- return null;
- }
- setThrottlingCache(throttlingCacheKey, throttlingCache) {
- this.setItem(throttlingCacheKey, throttlingCache);
- }
- removeItem(key) {
- this.logger.tracePii(`Item key: ${key}`, "");
- let result = false;
- const cache5 = this.getCache();
- if (!!cache5[key]) {
- delete cache5[key];
- result = true;
- }
- if (result) {
- this.setCache(cache5);
- this.emitChange();
- }
- return result;
- }
- removeOutdatedAccount(accountKey) {
- this.removeItem(accountKey);
- }
- containsKey(key) {
- return this.getKeys().includes(key);
- }
- getKeys() {
- this.logger.trace("Retrieving all cache keys", "");
- const cache5 = this.getCache();
- return [...Object.keys(cache5)];
- }
- clear() {
- this.logger.trace("Clearing cache entries created by MSAL", "");
- const cacheKeys = this.getKeys();
- cacheKeys.forEach((key) => {
- this.removeItem(key);
- });
- this.emitChange();
- }
- static generateInMemoryCache(cache5) {
- return Deserializer.deserializeAllCache(Deserializer.deserializeJSONBlob(cache5));
- }
- static generateJsonCache(inMemoryCache) {
- return Serializer.serializeAllCache(inMemoryCache);
- }
- updateCredentialCacheKey(currentCacheKey, credential) {
- const updatedCacheKey = this.generateCredentialKey(credential);
- if (currentCacheKey !== updatedCacheKey) {
- const cacheItem = this.getItem(currentCacheKey);
- if (cacheItem) {
- this.removeItem(currentCacheKey);
- this.setItem(updatedCacheKey, cacheItem);
- this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`, "");
- return updatedCacheKey;
- } else {
- this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`, "");
- }
- }
- return currentCacheKey;
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/cache/TokenCache.mjs
-class TokenCache {
- constructor(storage, logger10, cachePlugin) {
- this.cacheHasChanged = false;
- this.storage = storage;
- this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this));
- if (cachePlugin) {
- this.persistence = cachePlugin;
- }
- this.logger = logger10;
- }
- hasChanged() {
- return this.cacheHasChanged;
- }
- serialize() {
- this.logger.trace("Serializing in-memory cache", "");
- let finalState = Serializer.serializeAllCache(this.storage.getInMemoryCache());
- if (this.cacheSnapshot) {
- this.logger.trace("Reading cache snapshot from disk", "");
- finalState = this.mergeState(JSON.parse(this.cacheSnapshot), finalState);
- } else {
- this.logger.trace("No cache snapshot to merge", "");
- }
- this.cacheHasChanged = false;
- return JSON.stringify(finalState);
- }
- deserialize(cache5) {
- this.logger.trace("Deserializing JSON to in-memory cache", "");
- this.cacheSnapshot = cache5;
- if (this.cacheSnapshot) {
- this.logger.trace("Reading cache snapshot from disk", "");
- const deserializedCache = Deserializer.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));
- this.storage.setInMemoryCache(deserializedCache);
- } else {
- this.logger.trace("No cache snapshot to deserialize", "");
- }
- }
- getKVStore() {
- return this.storage.getCache();
- }
- getCacheSnapshot() {
- const deserializedPersistentStorage = NodeStorage.generateInMemoryCache(this.cacheSnapshot);
- return this.storage.inMemoryCacheToCache(deserializedPersistentStorage);
- }
- async getAllAccounts(correlationId = new CryptoProvider().createNewGuid()) {
- this.logger.trace("getAllAccounts called", correlationId);
- let cacheContext;
- try {
- if (this.persistence) {
- cacheContext = new TokenCacheContext(this, false);
- await this.persistence.beforeCacheAccess(cacheContext);
- }
- return this.storage.getAllAccounts({}, correlationId);
- } finally {
- if (this.persistence && cacheContext) {
- await this.persistence.afterCacheAccess(cacheContext);
- }
- }
- }
- async getAccountByHomeId(homeAccountId) {
- const allAccounts = await this.getAllAccounts();
- if (homeAccountId && allAccounts && allAccounts.length) {
- return allAccounts.filter((accountObj) => accountObj.homeAccountId === homeAccountId)[0] || null;
- } else {
- return null;
- }
- }
- async getAccountByLocalId(localAccountId) {
- const allAccounts = await this.getAllAccounts();
- if (localAccountId && allAccounts && allAccounts.length) {
- return allAccounts.filter((accountObj) => accountObj.localAccountId === localAccountId)[0] || null;
- } else {
- return null;
- }
- }
- async removeAccount(account, correlationId) {
- this.logger.trace("removeAccount called", correlationId || "");
- let cacheContext;
- try {
- if (this.persistence) {
- cacheContext = new TokenCacheContext(this, true);
- await this.persistence.beforeCacheAccess(cacheContext);
- }
- this.storage.removeAccount(account, correlationId || new GuidGenerator().generateGuid());
- } finally {
- if (this.persistence && cacheContext) {
- await this.persistence.afterCacheAccess(cacheContext);
- }
- }
- }
- async overwriteCache() {
- if (!this.persistence) {
- this.logger.info("No persistence layer specified, cache cannot be overwritten", "");
- return;
- }
- this.logger.info("Overwriting in-memory cache with persistent cache", "");
- this.storage.clear();
- const cacheContext = new TokenCacheContext(this, false);
- await this.persistence.beforeCacheAccess(cacheContext);
- const cacheSnapshot = this.getCacheSnapshot();
- this.storage.setCache(cacheSnapshot);
- await this.persistence.afterCacheAccess(cacheContext);
- }
- handleChangeEvent() {
- this.cacheHasChanged = true;
- }
- mergeState(oldState, currentState) {
- this.logger.trace("Merging in-memory cache with cache snapshot", "");
- const stateAfterRemoval = this.mergeRemovals(oldState, currentState);
- return this.mergeUpdates(stateAfterRemoval, currentState);
- }
- mergeUpdates(oldState, newState) {
- Object.keys(newState).forEach((newKey) => {
- const newValue = newState[newKey];
- if (!oldState.hasOwnProperty(newKey)) {
- if (newValue !== null) {
- oldState[newKey] = newValue;
- }
- } else {
- const newValueNotNull = newValue !== null;
- const newValueIsObject = typeof newValue === "object";
- const newValueIsNotArray = !Array.isArray(newValue);
- const oldStateNotUndefinedOrNull = typeof oldState[newKey] !== "undefined" && oldState[newKey] !== null;
- if (newValueNotNull && newValueIsObject && newValueIsNotArray && oldStateNotUndefinedOrNull) {
- this.mergeUpdates(oldState[newKey], newValue);
- } else {
- oldState[newKey] = newValue;
- }
- }
- });
- return oldState;
- }
- mergeRemovals(oldState, newState) {
- this.logger.trace("Remove updated entries in cache", "");
- const accounts = oldState.Account ? this.mergeRemovalsDict(oldState.Account, newState.Account) : oldState.Account;
- const accessTokens = oldState.AccessToken ? this.mergeRemovalsDict(oldState.AccessToken, newState.AccessToken) : oldState.AccessToken;
- const refreshTokens = oldState.RefreshToken ? this.mergeRemovalsDict(oldState.RefreshToken, newState.RefreshToken) : oldState.RefreshToken;
- const idTokens = oldState.IdToken ? this.mergeRemovalsDict(oldState.IdToken, newState.IdToken) : oldState.IdToken;
- const appMetadata = oldState.AppMetadata ? this.mergeRemovalsDict(oldState.AppMetadata, newState.AppMetadata) : oldState.AppMetadata;
- return {
- ...oldState,
- Account: accounts,
- AccessToken: accessTokens,
- RefreshToken: refreshTokens,
- IdToken: idTokens,
- AppMetadata: appMetadata
- };
- }
- mergeRemovalsDict(oldState, newState) {
- const finalState = { ...oldState };
- Object.keys(oldState).forEach((oldKey) => {
- if (!newState || !newState.hasOwnProperty(oldKey)) {
- delete finalState[oldKey];
- }
- });
- return finalState;
- }
- overlayDefaults(passedInCache) {
- this.logger.trace("Overlaying input cache with the default cache", "");
- return {
- Account: {
- ...defaultSerializedCache.Account,
- ...passedInCache.Account
- },
- IdToken: {
- ...defaultSerializedCache.IdToken,
- ...passedInCache.IdToken
- },
- AccessToken: {
- ...defaultSerializedCache.AccessToken,
- ...passedInCache.AccessToken
- },
- RefreshToken: {
- ...defaultSerializedCache.RefreshToken,
- ...passedInCache.RefreshToken
- },
- AppMetadata: {
- ...defaultSerializedCache.AppMetadata,
- ...passedInCache.AppMetadata
- }
- };
- }
-}
-var defaultSerializedCache;
-var init_TokenCache = __esm(() => {
- init_NodeStorage();
- init_index_node();
- init_Deserializer();
- init_Serializer();
- init_GuidGenerator();
- init_CryptoProvider();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- defaultSerializedCache = {
- Account: {},
- IdToken: {},
- AccessToken: {},
- RefreshToken: {},
- AppMetadata: {}
- };
-});
-
-// node_modules/safe-buffer/index.js
-var require_safe_buffer = __commonJS((exports, module) => {
- /*! safe-buffer. MIT License. Feross Aboukhadijeh */
- var buffer = __require("buffer");
- var Buffer13 = buffer.Buffer;
- function copyProps(src, dst) {
- for (var key in src) {
- dst[key] = src[key];
- }
- }
- if (Buffer13.from && Buffer13.alloc && Buffer13.allocUnsafe && Buffer13.allocUnsafeSlow) {
- module.exports = buffer;
- } else {
- copyProps(buffer, exports);
- exports.Buffer = SafeBuffer;
- }
- function SafeBuffer(arg, encodingOrOffset, length) {
- return Buffer13(arg, encodingOrOffset, length);
- }
- SafeBuffer.prototype = Object.create(Buffer13.prototype);
- copyProps(Buffer13, SafeBuffer);
- SafeBuffer.from = function(arg, encodingOrOffset, length) {
- if (typeof arg === "number") {
- throw new TypeError("Argument must not be a number");
- }
- return Buffer13(arg, encodingOrOffset, length);
- };
- SafeBuffer.alloc = function(size, fill, encoding) {
- if (typeof size !== "number") {
- throw new TypeError("Argument must be a number");
- }
- var buf = Buffer13(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 Buffer13(size);
- };
- SafeBuffer.allocUnsafeSlow = function(size) {
- if (typeof size !== "number") {
- throw new TypeError("Argument must be a number");
- }
- return buffer.SlowBuffer(size);
- };
-});
-
-// node_modules/jws/lib/data-stream.js
-var require_data_stream = __commonJS((exports, module) => {
- var Buffer13 = require_safe_buffer().Buffer;
- var Stream5 = __require("stream");
- var util10 = __require("util");
- function DataStream(data) {
- this.buffer = null;
- this.writable = true;
- this.readable = true;
- if (!data) {
- this.buffer = Buffer13.alloc(0);
- return this;
- }
- if (typeof data.pipe === "function") {
- this.buffer = Buffer13.alloc(0);
- data.pipe(this);
- return this;
- }
- 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 + ")");
- }
- util10.inherits(DataStream, Stream5);
- DataStream.prototype.write = function write(data) {
- this.buffer = Buffer13.concat([this.buffer, Buffer13.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;
-});
-
-// node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js
-var require_param_bytes_for_alg = __commonJS((exports, module) => {
- function getParamSize(keySize) {
- var result = (keySize / 8 | 0) + (keySize % 8 === 0 ? 0 : 1);
- return result;
- }
- var paramBytesForAlg = {
- ES256: getParamSize(256),
- ES384: getParamSize(384),
- ES512: getParamSize(521)
- };
- function getParamBytesForAlg(alg) {
- var paramBytes = paramBytesForAlg[alg];
- if (paramBytes) {
- return paramBytes;
- }
- throw new Error('Unknown algorithm "' + alg + '"');
- }
- module.exports = getParamBytesForAlg;
-});
-
-// node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js
-var require_ecdsa_sig_formatter = __commonJS((exports, module) => {
- var Buffer13 = require_safe_buffer().Buffer;
- var getParamBytesForAlg = require_param_bytes_for_alg();
- var MAX_OCTET = 128;
- var CLASS_UNIVERSAL = 0;
- var PRIMITIVE_BIT = 32;
- var TAG_SEQ = 16;
- var TAG_INT = 2;
- var ENCODED_TAG_SEQ = TAG_SEQ | PRIMITIVE_BIT | CLASS_UNIVERSAL << 6;
- var ENCODED_TAG_INT = TAG_INT | CLASS_UNIVERSAL << 6;
- function base64Url(base644) {
- return base644.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
- }
- function signatureAsBuffer(signature7) {
- if (Buffer13.isBuffer(signature7)) {
- return signature7;
- } else if (typeof signature7 === "string") {
- return Buffer13.from(signature7, "base64");
- }
- throw new TypeError("ECDSA signature must be a Base64 string or a Buffer");
- }
- function derToJose(signature7, alg) {
- signature7 = signatureAsBuffer(signature7);
- var paramBytes = getParamBytesForAlg(alg);
- var maxEncodedParamLength = paramBytes + 1;
- var inputLength = signature7.length;
- var offset = 0;
- if (signature7[offset++] !== ENCODED_TAG_SEQ) {
- throw new Error('Could not find expected "seq"');
- }
- var seqLength = signature7[offset++];
- if (seqLength === (MAX_OCTET | 1)) {
- seqLength = signature7[offset++];
- }
- if (inputLength - offset < seqLength) {
- throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining');
- }
- if (signature7[offset++] !== ENCODED_TAG_INT) {
- throw new Error('Could not find expected "int" for "r"');
- }
- var rLength = signature7[offset++];
- if (inputLength - offset - 2 < rLength) {
- throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available');
- }
- if (maxEncodedParamLength < rLength) {
- throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
- }
- var rOffset = offset;
- offset += rLength;
- if (signature7[offset++] !== ENCODED_TAG_INT) {
- throw new Error('Could not find expected "int" for "s"');
- }
- var sLength = signature7[offset++];
- if (inputLength - offset !== sLength) {
- throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"');
- }
- if (maxEncodedParamLength < sLength) {
- throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
- }
- var sOffset = offset;
- offset += sLength;
- if (offset !== inputLength) {
- throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain');
- }
- var rPadding = paramBytes - rLength, sPadding = paramBytes - sLength;
- var dst = Buffer13.allocUnsafe(rPadding + rLength + sPadding + sLength);
- for (offset = 0;offset < rPadding; ++offset) {
- dst[offset] = 0;
- }
- signature7.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);
- offset = paramBytes;
- for (var o5 = offset;offset < o5 + sPadding; ++offset) {
- dst[offset] = 0;
- }
- signature7.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);
- dst = dst.toString("base64");
- dst = base64Url(dst);
- return dst;
- }
- function countPadding(buf, start, stop) {
- var padding = 0;
- while (start + padding < stop && buf[start + padding] === 0) {
- ++padding;
- }
- var needsSign = buf[start + padding] >= MAX_OCTET;
- if (needsSign) {
- --padding;
- }
- return padding;
- }
- function joseToDer(signature7, alg) {
- signature7 = signatureAsBuffer(signature7);
- var paramBytes = getParamBytesForAlg(alg);
- var signatureBytes = signature7.length;
- if (signatureBytes !== paramBytes * 2) {
- throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"');
- }
- var rPadding = countPadding(signature7, 0, paramBytes);
- var sPadding = countPadding(signature7, paramBytes, signature7.length);
- var rLength = paramBytes - rPadding;
- var sLength = paramBytes - sPadding;
- var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;
- var shortLength = rsBytes < MAX_OCTET;
- var dst = Buffer13.allocUnsafe((shortLength ? 2 : 3) + rsBytes);
- var offset = 0;
- dst[offset++] = ENCODED_TAG_SEQ;
- if (shortLength) {
- dst[offset++] = rsBytes;
- } else {
- dst[offset++] = MAX_OCTET | 1;
- dst[offset++] = rsBytes & 255;
- }
- dst[offset++] = ENCODED_TAG_INT;
- dst[offset++] = rLength;
- if (rPadding < 0) {
- dst[offset++] = 0;
- offset += signature7.copy(dst, offset, 0, paramBytes);
- } else {
- offset += signature7.copy(dst, offset, rPadding, paramBytes);
- }
- dst[offset++] = ENCODED_TAG_INT;
- dst[offset++] = sLength;
- if (sPadding < 0) {
- dst[offset++] = 0;
- signature7.copy(dst, offset, paramBytes);
- } else {
- signature7.copy(dst, offset, paramBytes + sPadding);
- }
- return dst;
- }
- module.exports = {
- derToJose,
- joseToDer
- };
-});
-
-// node_modules/buffer-equal-constant-time/index.js
-var require_buffer_equal_constant_time = __commonJS((exports, module) => {
- var Buffer13 = __require("buffer").Buffer;
- var SlowBuffer = __require("buffer").SlowBuffer;
- module.exports = bufferEq;
- function bufferEq(a5, b4) {
- if (!Buffer13.isBuffer(a5) || !Buffer13.isBuffer(b4)) {
- return false;
- }
- if (a5.length !== b4.length) {
- return false;
- }
- var c8 = 0;
- for (var i5 = 0;i5 < a5.length; i5++) {
- c8 |= a5[i5] ^ b4[i5];
- }
- return c8 === 0;
- }
- bufferEq.install = function() {
- Buffer13.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {
- return bufferEq(this, that);
- };
- };
- var origBufEqual = Buffer13.prototype.equal;
- var origSlowBufEqual = SlowBuffer.prototype.equal;
- bufferEq.restore = function() {
- Buffer13.prototype.equal = origBufEqual;
- SlowBuffer.prototype.equal = origSlowBufEqual;
- };
-});
-
-// node_modules/jwa/index.js
-var require_jwa = __commonJS((exports, module) => {
- var Buffer13 = require_safe_buffer().Buffer;
- var crypto11 = __require("crypto");
- var formatEcdsa = require_ecdsa_sig_formatter();
- var util10 = __require("util");
- var MSG_INVALID_ALGORITHM = `"%s" is not a valid algorithm.
- Supported algorithms are:
- "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 crypto11.createPublicKey === "function";
- if (supportsKeyObjects) {
- MSG_INVALID_VERIFIER_KEY += " or a KeyObject";
- MSG_INVALID_SECRET += "or a KeyObject";
- }
- function checkIsPublicKey(key) {
- if (Buffer13.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 (Buffer13.isBuffer(key)) {
- return;
- }
- if (typeof key === "string") {
- return;
- }
- if (typeof key === "object") {
- return;
- }
- throw typeError(MSG_INVALID_SIGNER_KEY);
- }
- function checkIsSecretKey(key) {
- if (Buffer13.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 fromBase649(base644) {
- return base644.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
- }
- function toBase649(base64url3) {
- base64url3 = base64url3.toString();
- var padding = 4 - base64url3.length % 4;
- if (padding !== 4) {
- for (var i5 = 0;i5 < padding; ++i5) {
- base64url3 += "=";
- }
- }
- return base64url3.replace(/\-/g, "+").replace(/_/g, "/");
- }
- function typeError(template) {
- var args = [].slice.call(arguments, 1);
- var errMsg = util10.format.bind(util10, template).apply(null, args);
- return new TypeError(errMsg);
- }
- function bufferOrString(obj) {
- return Buffer13.isBuffer(obj) || typeof obj === "string";
- }
- function normalizeInput(thing) {
- if (!bufferOrString(thing))
- thing = JSON.stringify(thing);
- return thing;
- }
- function createHmacSigner(bits) {
- return function sign2(thing, secret) {
- checkIsSecretKey(secret);
- thing = normalizeInput(thing);
- var hmac2 = crypto11.createHmac("sha" + bits, secret);
- var sig = (hmac2.update(thing), hmac2.digest("base64"));
- return fromBase649(sig);
- };
- }
- var bufferEqual;
- var timingSafeEqual = "timingSafeEqual" in crypto11 ? function timingSafeEqual2(a5, b4) {
- if (a5.byteLength !== b4.byteLength) {
- return false;
- }
- return crypto11.timingSafeEqual(a5, b4);
- } : function timingSafeEqual2(a5, b4) {
- if (!bufferEqual) {
- bufferEqual = require_buffer_equal_constant_time();
- }
- return bufferEqual(a5, b4);
- };
- function createHmacVerifier(bits) {
- return function verify(thing, signature7, secret) {
- var computedSig = createHmacSigner(bits)(thing, secret);
- return timingSafeEqual(Buffer13.from(signature7), Buffer13.from(computedSig));
- };
- }
- function createKeySigner(bits) {
- return function sign2(thing, privateKey) {
- checkIsPrivateKey(privateKey);
- thing = normalizeInput(thing);
- var signer = crypto11.createSign("RSA-SHA" + bits);
- var sig = (signer.update(thing), signer.sign(privateKey, "base64"));
- return fromBase649(sig);
- };
- }
- function createKeyVerifier(bits) {
- return function verify(thing, signature7, publicKey) {
- checkIsPublicKey(publicKey);
- thing = normalizeInput(thing);
- signature7 = toBase649(signature7);
- var verifier = crypto11.createVerify("RSA-SHA" + bits);
- verifier.update(thing);
- return verifier.verify(publicKey, signature7, "base64");
- };
- }
- function createPSSKeySigner(bits) {
- return function sign2(thing, privateKey) {
- checkIsPrivateKey(privateKey);
- thing = normalizeInput(thing);
- var signer = crypto11.createSign("RSA-SHA" + bits);
- var sig = (signer.update(thing), signer.sign({
- key: privateKey,
- padding: crypto11.constants.RSA_PKCS1_PSS_PADDING,
- saltLength: crypto11.constants.RSA_PSS_SALTLEN_DIGEST
- }, "base64"));
- return fromBase649(sig);
- };
- }
- function createPSSKeyVerifier(bits) {
- return function verify(thing, signature7, publicKey) {
- checkIsPublicKey(publicKey);
- thing = normalizeInput(thing);
- signature7 = toBase649(signature7);
- var verifier = crypto11.createVerify("RSA-SHA" + bits);
- verifier.update(thing);
- return verifier.verify({
- key: publicKey,
- padding: crypto11.constants.RSA_PKCS1_PSS_PADDING,
- saltLength: crypto11.constants.RSA_PSS_SALTLEN_DIGEST
- }, signature7, "base64");
- };
- }
- function createECDSASigner(bits) {
- var inner = createKeySigner(bits);
- return function sign2() {
- var signature7 = inner.apply(null, arguments);
- signature7 = formatEcdsa.derToJose(signature7, "ES" + bits);
- return signature7;
- };
- }
- function createECDSAVerifer(bits) {
- var inner = createKeyVerifier(bits);
- return function verify(thing, signature7, publicKey) {
- signature7 = formatEcdsa.joseToDer(signature7, "ES" + bits).toString("base64");
- var result = inner(thing, signature7, publicKey);
- return result;
- };
- }
- function createNoneSigner() {
- return function sign2() {
- return "";
- };
- }
- function createNoneVerifier() {
- return function verify(thing, signature7) {
- return signature7 === "";
- };
- }
- 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)
- };
- };
-});
-
-// node_modules/jws/lib/tostring.js
-var require_tostring = __commonJS((exports, module) => {
- var Buffer13 = __require("buffer").Buffer;
- module.exports = function toString6(obj) {
- if (typeof obj === "string")
- return obj;
- if (typeof obj === "number" || Buffer13.isBuffer(obj))
- return obj.toString();
- return JSON.stringify(obj);
- };
-});
-
-// node_modules/jws/lib/sign-stream.js
-var require_sign_stream = __commonJS((exports, module) => {
- var Buffer13 = require_safe_buffer().Buffer;
- var DataStream = require_data_stream();
- var jwa = require_jwa();
- var Stream5 = __require("stream");
- var toString6 = require_tostring();
- var util10 = __require("util");
- function base64url3(string4, encoding) {
- return Buffer13.from(string4, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
- }
- function jwsSecuredInput(header, payload, encoding) {
- encoding = encoding || "utf8";
- var encodedHeader = base64url3(toString6(header), "binary");
- var encodedPayload = base64url3(toString6(payload), encoding);
- return util10.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 signature7 = algo.sign(securedInput, secretOrKey);
- return util10.format("%s.%s", securedInput, signature7);
- }
- function SignStream(opts) {
- var secret = opts.secret;
- secret = secret == null ? opts.privateKey : secret;
- secret = secret == null ? opts.key : secret;
- if (/^hs/i.test(opts.header.alg) === true && secret == null) {
- throw new TypeError("secret must be a string or buffer or a KeyObject");
- }
- 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));
- }
- util10.inherits(SignStream, Stream5);
- SignStream.prototype.sign = function sign2() {
- try {
- var signature7 = jwsSign({
- header: this.header,
- payload: this.payload.buffer,
- secret: this.secret.buffer,
- encoding: this.encoding
- });
- this.emit("done", signature7);
- this.emit("data", signature7);
- this.emit("end");
- this.readable = false;
- return signature7;
- } catch (e4) {
- this.readable = false;
- this.emit("error", e4);
- this.emit("close");
- }
- };
- SignStream.sign = jwsSign;
- module.exports = SignStream;
-});
-
-// node_modules/jws/lib/verify-stream.js
-var require_verify_stream = __commonJS((exports, module) => {
- var Buffer13 = require_safe_buffer().Buffer;
- var DataStream = require_data_stream();
- var jwa = require_jwa();
- var Stream5 = __require("stream");
- var toString6 = require_tostring();
- var util10 = __require("util");
- var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;
- function isObject5(thing) {
- return Object.prototype.toString.call(thing) === "[object Object]";
- }
- function safeJsonParse(thing) {
- if (isObject5(thing))
- return thing;
- try {
- return JSON.parse(thing);
- } catch (e4) {
- return;
- }
- }
- function headerFromJWS(jwsSig) {
- var encodedHeader = jwsSig.split(".", 1)[0];
- return safeJsonParse(Buffer13.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 Buffer13.from(payload, "base64").toString(encoding);
- }
- function isValidJws(string4) {
- return JWS_REGEX.test(string4) && !!headerFromJWS(string4);
- }
- function jwsVerify(jwsSig, algorithm, secretOrKey) {
- if (!algorithm) {
- var err = new Error("Missing algorithm parameter for jws.verify");
- err.code = "MISSING_ALGORITHM";
- throw err;
- }
- jwsSig = toString6(jwsSig);
- var signature7 = signatureFromJWS(jwsSig);
- var securedInput = securedInputFromJWS(jwsSig);
- var algo = jwa(algorithm);
- return algo.verify(securedInput, signature7, secretOrKey);
- }
- function jwsDecode(jwsSig, opts) {
- opts = opts || {};
- jwsSig = toString6(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,
- payload,
- signature: signatureFromJWS(jwsSig)
- };
- }
- function VerifyStream(opts) {
- opts = opts || {};
- var secretOrKey = opts.secret;
- secretOrKey = secretOrKey == null ? opts.publicKey : secretOrKey;
- secretOrKey = secretOrKey == null ? opts.key : secretOrKey;
- if (/^hs/i.test(opts.algorithm) === true && secretOrKey == null) {
- throw new TypeError("secret must be a string or buffer or a KeyObject");
- }
- 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));
- }
- util10.inherits(VerifyStream, Stream5);
- 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 (e4) {
- this.readable = false;
- this.emit("error", e4);
- this.emit("close");
- }
- };
- VerifyStream.decode = jwsDecode;
- VerifyStream.isValid = isValidJws;
- VerifyStream.verify = jwsVerify;
- module.exports = VerifyStream;
-});
-
-// node_modules/jws/index.js
-var require_jws = __commonJS((exports) => {
- var SignStream = require_sign_stream();
- var VerifyStream = require_verify_stream();
- 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);
- };
-});
-
-// node_modules/jsonwebtoken/decode.js
-var require_decode = __commonJS((exports, module) => {
- var jws = require_jws();
- module.exports = function(jwt2, options2) {
- options2 = options2 || {};
- var decoded = jws.decode(jwt2, options2);
- if (!decoded) {
- return null;
- }
- var payload = decoded.payload;
- if (typeof payload === "string") {
- try {
- var obj = JSON.parse(payload);
- if (obj !== null && typeof obj === "object") {
- payload = obj;
- }
- } catch (e4) {}
- }
- if (options2.complete === true) {
- return {
- header: decoded.header,
- payload,
- signature: decoded.signature
- };
- }
- return payload;
- };
-});
-
-// node_modules/jsonwebtoken/lib/JsonWebTokenError.js
-var require_JsonWebTokenError = __commonJS((exports, module) => {
- var JsonWebTokenError = function(message, error44) {
- Error.call(this, message);
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- }
- this.name = "JsonWebTokenError";
- this.message = message;
- if (error44)
- this.inner = error44;
- };
- JsonWebTokenError.prototype = Object.create(Error.prototype);
- JsonWebTokenError.prototype.constructor = JsonWebTokenError;
- module.exports = JsonWebTokenError;
-});
-
-// node_modules/jsonwebtoken/lib/NotBeforeError.js
-var require_NotBeforeError = __commonJS((exports, module) => {
- var JsonWebTokenError = require_JsonWebTokenError();
- var NotBeforeError = function(message, date5) {
- JsonWebTokenError.call(this, message);
- this.name = "NotBeforeError";
- this.date = date5;
- };
- NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype);
- NotBeforeError.prototype.constructor = NotBeforeError;
- module.exports = NotBeforeError;
-});
-
-// node_modules/jsonwebtoken/lib/TokenExpiredError.js
-var require_TokenExpiredError = __commonJS((exports, module) => {
- var JsonWebTokenError = require_JsonWebTokenError();
- var TokenExpiredError = function(message, expiredAt) {
- JsonWebTokenError.call(this, message);
- this.name = "TokenExpiredError";
- this.expiredAt = expiredAt;
- };
- TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype);
- TokenExpiredError.prototype.constructor = TokenExpiredError;
- module.exports = TokenExpiredError;
-});
-
-// node_modules/jsonwebtoken/lib/timespan.js
-var require_timespan = __commonJS((exports, module) => {
- var ms = require_ms();
- module.exports = function(time3, iat) {
- var timestamp = iat || Math.floor(Date.now() / 1000);
- if (typeof time3 === "string") {
- var milliseconds = ms(time3);
- if (typeof milliseconds === "undefined") {
- return;
- }
- return Math.floor(timestamp + milliseconds / 1000);
- } else if (typeof time3 === "number") {
- return timestamp + time3;
- } else {
- return;
- }
- };
-});
-
-// node_modules/semver/internal/constants.js
-var require_constants3 = __commonJS((exports, module) => {
- var SEMVER_SPEC_VERSION = "2.0.0";
- var MAX_LENGTH = 256;
- var MAX_SAFE_INTEGER3 = Number.MAX_SAFE_INTEGER || 9007199254740991;
- var MAX_SAFE_COMPONENT_LENGTH = 16;
- var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
- var RELEASE_TYPES = [
- "major",
- "premajor",
- "minor",
- "preminor",
- "patch",
- "prepatch",
- "prerelease"
- ];
- module.exports = {
- MAX_LENGTH,
- MAX_SAFE_COMPONENT_LENGTH,
- MAX_SAFE_BUILD_LENGTH,
- MAX_SAFE_INTEGER: MAX_SAFE_INTEGER3,
- RELEASE_TYPES,
- SEMVER_SPEC_VERSION,
- FLAG_INCLUDE_PRERELEASE: 1,
- FLAG_LOOSE: 2
- };
-});
-
-// node_modules/semver/internal/debug.js
-var require_debug2 = __commonJS((exports, module) => {
- var debug2 = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {};
- module.exports = debug2;
-});
-
-// node_modules/semver/internal/re.js
-var require_re = __commonJS((exports, module) => {
- var {
- MAX_SAFE_COMPONENT_LENGTH,
- MAX_SAFE_BUILD_LENGTH,
- MAX_LENGTH
- } = require_constants3();
- var debug2 = require_debug2();
- exports = module.exports = {};
- var re = exports.re = [];
- var safeRe = exports.safeRe = [];
- var src = exports.src = [];
- var safeSrc = exports.safeSrc = [];
- var t4 = exports.t = {};
- var R2 = 0;
- var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
- var safeRegexReplacements = [
- ["\\s", 1],
- ["\\d", MAX_LENGTH],
- [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
- ];
- var makeSafeRegex = (value) => {
- for (const [token, max] of safeRegexReplacements) {
- value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
- }
- return value;
- };
- var createToken = (name2, value, isGlobal) => {
- const safe = makeSafeRegex(value);
- const index2 = R2++;
- debug2(name2, index2, value);
- t4[name2] = index2;
- src[index2] = value;
- safeSrc[index2] = safe;
- re[index2] = new RegExp(value, isGlobal ? "g" : undefined);
- safeRe[index2] = new RegExp(safe, isGlobal ? "g" : undefined);
- };
- createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
- createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
- createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
- createToken("MAINVERSION", `(${src[t4.NUMERICIDENTIFIER]})\\.` + `(${src[t4.NUMERICIDENTIFIER]})\\.` + `(${src[t4.NUMERICIDENTIFIER]})`);
- createToken("MAINVERSIONLOOSE", `(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t4.NUMERICIDENTIFIERLOOSE]})`);
- createToken("PRERELEASEIDENTIFIER", `(?:${src[t4.NONNUMERICIDENTIFIER]}|${src[t4.NUMERICIDENTIFIER]})`);
- createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t4.NONNUMERICIDENTIFIER]}|${src[t4.NUMERICIDENTIFIERLOOSE]})`);
- createToken("PRERELEASE", `(?:-(${src[t4.PRERELEASEIDENTIFIER]}(?:\\.${src[t4.PRERELEASEIDENTIFIER]})*))`);
- createToken("PRERELEASELOOSE", `(?:-?(${src[t4.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t4.PRERELEASEIDENTIFIERLOOSE]})*))`);
- createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
- createToken("BUILD", `(?:\\+(${src[t4.BUILDIDENTIFIER]}(?:\\.${src[t4.BUILDIDENTIFIER]})*))`);
- createToken("FULLPLAIN", `v?${src[t4.MAINVERSION]}${src[t4.PRERELEASE]}?${src[t4.BUILD]}?`);
- createToken("FULL", `^${src[t4.FULLPLAIN]}$`);
- createToken("LOOSEPLAIN", `[v=\\s]*${src[t4.MAINVERSIONLOOSE]}${src[t4.PRERELEASELOOSE]}?${src[t4.BUILD]}?`);
- createToken("LOOSE", `^${src[t4.LOOSEPLAIN]}$`);
- createToken("GTLT", "((?:<|>)?=?)");
- createToken("XRANGEIDENTIFIERLOOSE", `${src[t4.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
- createToken("XRANGEIDENTIFIER", `${src[t4.NUMERICIDENTIFIER]}|x|X|\\*`);
- createToken("XRANGEPLAIN", `[v=\\s]*(${src[t4.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t4.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t4.XRANGEIDENTIFIER]})` + `(?:${src[t4.PRERELEASE]})?${src[t4.BUILD]}?` + `)?)?`);
- createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t4.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t4.PRERELEASELOOSE]})?${src[t4.BUILD]}?` + `)?)?`);
- createToken("XRANGE", `^${src[t4.GTLT]}\\s*${src[t4.XRANGEPLAIN]}$`);
- createToken("XRANGELOOSE", `^${src[t4.GTLT]}\\s*${src[t4.XRANGEPLAINLOOSE]}$`);
- createToken("COERCEPLAIN", `${"(^|[^\\d])" + "(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
- createToken("COERCE", `${src[t4.COERCEPLAIN]}(?:$|[^\\d])`);
- createToken("COERCEFULL", src[t4.COERCEPLAIN] + `(?:${src[t4.PRERELEASE]})?` + `(?:${src[t4.BUILD]})?` + `(?:$|[^\\d])`);
- createToken("COERCERTL", src[t4.COERCE], true);
- createToken("COERCERTLFULL", src[t4.COERCEFULL], true);
- createToken("LONETILDE", "(?:~>?)");
- createToken("TILDETRIM", `(\\s*)${src[t4.LONETILDE]}\\s+`, true);
- exports.tildeTrimReplace = "$1~";
- createToken("TILDE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAIN]}$`);
- createToken("TILDELOOSE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAINLOOSE]}$`);
- createToken("LONECARET", "(?:\\^)");
- createToken("CARETTRIM", `(\\s*)${src[t4.LONECARET]}\\s+`, true);
- exports.caretTrimReplace = "$1^";
- createToken("CARET", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAIN]}$`);
- createToken("CARETLOOSE", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAINLOOSE]}$`);
- createToken("COMPARATORLOOSE", `^${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]})$|^$`);
- createToken("COMPARATOR", `^${src[t4.GTLT]}\\s*(${src[t4.FULLPLAIN]})$|^$`);
- createToken("COMPARATORTRIM", `(\\s*)${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]}|${src[t4.XRANGEPLAIN]})`, true);
- exports.comparatorTrimReplace = "$1$2$3";
- createToken("HYPHENRANGE", `^\\s*(${src[t4.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t4.XRANGEPLAIN]})` + `\\s*$`);
- createToken("HYPHENRANGELOOSE", `^\\s*(${src[t4.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t4.XRANGEPLAINLOOSE]})` + `\\s*$`);
- createToken("STAR", "(<|>)?=?\\s*\\*");
- createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
- createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
-});
-
-// node_modules/semver/internal/parse-options.js
-var require_parse_options = __commonJS((exports, module) => {
- var looseOption = Object.freeze({ loose: true });
- var emptyOpts = Object.freeze({});
- var parseOptions = (options2) => {
- if (!options2) {
- return emptyOpts;
- }
- if (typeof options2 !== "object") {
- return looseOption;
- }
- return options2;
- };
- module.exports = parseOptions;
-});
-
-// node_modules/semver/internal/identifiers.js
-var require_identifiers = __commonJS((exports, module) => {
- var numeric = /^[0-9]+$/;
- var compareIdentifiers = (a5, b4) => {
- if (typeof a5 === "number" && typeof b4 === "number") {
- return a5 === b4 ? 0 : a5 < b4 ? -1 : 1;
- }
- const anum = numeric.test(a5);
- const bnum = numeric.test(b4);
- if (anum && bnum) {
- a5 = +a5;
- b4 = +b4;
- }
- return a5 === b4 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a5 < b4 ? -1 : 1;
- };
- var rcompareIdentifiers = (a5, b4) => compareIdentifiers(b4, a5);
- module.exports = {
- compareIdentifiers,
- rcompareIdentifiers
- };
-});
-
-// node_modules/semver/classes/semver.js
-var require_semver = __commonJS((exports, module) => {
- var debug2 = require_debug2();
- var { MAX_LENGTH, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER3 } = require_constants3();
- var { safeRe: re, t: t4 } = require_re();
- var parseOptions = require_parse_options();
- var { compareIdentifiers } = require_identifiers();
-
- class SemVer {
- constructor(version5, options2) {
- options2 = parseOptions(options2);
- if (version5 instanceof SemVer) {
- if (version5.loose === !!options2.loose && version5.includePrerelease === !!options2.includePrerelease) {
- return version5;
- } else {
- version5 = version5.version;
- }
- } else if (typeof version5 !== "string") {
- throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version5}".`);
- }
- if (version5.length > MAX_LENGTH) {
- throw new TypeError(`version is longer than ${MAX_LENGTH} characters`);
- }
- debug2("SemVer", version5, options2);
- this.options = options2;
- this.loose = !!options2.loose;
- this.includePrerelease = !!options2.includePrerelease;
- const m4 = version5.trim().match(options2.loose ? re[t4.LOOSE] : re[t4.FULL]);
- if (!m4) {
- throw new TypeError(`Invalid Version: ${version5}`);
- }
- this.raw = version5;
- this.major = +m4[1];
- this.minor = +m4[2];
- this.patch = +m4[3];
- if (this.major > MAX_SAFE_INTEGER3 || this.major < 0) {
- throw new TypeError("Invalid major version");
- }
- if (this.minor > MAX_SAFE_INTEGER3 || this.minor < 0) {
- throw new TypeError("Invalid minor version");
- }
- if (this.patch > MAX_SAFE_INTEGER3 || this.patch < 0) {
- throw new TypeError("Invalid patch version");
- }
- if (!m4[4]) {
- this.prerelease = [];
- } else {
- this.prerelease = m4[4].split(".").map((id) => {
- if (/^[0-9]+$/.test(id)) {
- const num = +id;
- if (num >= 0 && num < MAX_SAFE_INTEGER3) {
- return num;
- }
- }
- return id;
- });
- }
- this.build = m4[5] ? m4[5].split(".") : [];
- this.format();
- }
- format() {
- this.version = `${this.major}.${this.minor}.${this.patch}`;
- if (this.prerelease.length) {
- this.version += `-${this.prerelease.join(".")}`;
- }
- return this.version;
- }
- toString() {
- return this.version;
- }
- compare(other2) {
- debug2("SemVer.compare", this.version, this.options, other2);
- if (!(other2 instanceof SemVer)) {
- if (typeof other2 === "string" && other2 === this.version) {
- return 0;
- }
- other2 = new SemVer(other2, this.options);
- }
- if (other2.version === this.version) {
- return 0;
- }
- return this.compareMain(other2) || this.comparePre(other2);
- }
- compareMain(other2) {
- if (!(other2 instanceof SemVer)) {
- other2 = new SemVer(other2, this.options);
- }
- if (this.major < other2.major) {
- return -1;
- }
- if (this.major > other2.major) {
- return 1;
- }
- if (this.minor < other2.minor) {
- return -1;
- }
- if (this.minor > other2.minor) {
- return 1;
- }
- if (this.patch < other2.patch) {
- return -1;
- }
- if (this.patch > other2.patch) {
- return 1;
- }
- return 0;
- }
- comparePre(other2) {
- if (!(other2 instanceof SemVer)) {
- other2 = new SemVer(other2, this.options);
- }
- if (this.prerelease.length && !other2.prerelease.length) {
- return -1;
- } else if (!this.prerelease.length && other2.prerelease.length) {
- return 1;
- } else if (!this.prerelease.length && !other2.prerelease.length) {
- return 0;
- }
- let i5 = 0;
- do {
- const a5 = this.prerelease[i5];
- const b4 = other2.prerelease[i5];
- debug2("prerelease compare", i5, a5, b4);
- if (a5 === undefined && b4 === undefined) {
- return 0;
- } else if (b4 === undefined) {
- return 1;
- } else if (a5 === undefined) {
- return -1;
- } else if (a5 === b4) {
- continue;
- } else {
- return compareIdentifiers(a5, b4);
- }
- } while (++i5);
- }
- compareBuild(other2) {
- if (!(other2 instanceof SemVer)) {
- other2 = new SemVer(other2, this.options);
- }
- let i5 = 0;
- do {
- const a5 = this.build[i5];
- const b4 = other2.build[i5];
- debug2("build compare", i5, a5, b4);
- if (a5 === undefined && b4 === undefined) {
- return 0;
- } else if (b4 === undefined) {
- return 1;
- } else if (a5 === undefined) {
- return -1;
- } else if (a5 === b4) {
- continue;
- } else {
- return compareIdentifiers(a5, b4);
- }
- } while (++i5);
- }
- inc(release, identifier, identifierBase) {
- if (release.startsWith("pre")) {
- if (!identifier && identifierBase === false) {
- throw new Error("invalid increment argument: identifier is empty");
- }
- if (identifier) {
- const match = `-${identifier}`.match(this.options.loose ? re[t4.PRERELEASELOOSE] : re[t4.PRERELEASE]);
- if (!match || match[1] !== identifier) {
- throw new Error(`invalid identifier: ${identifier}`);
- }
- }
- }
- switch (release) {
- case "premajor":
- this.prerelease.length = 0;
- this.patch = 0;
- this.minor = 0;
- this.major++;
- this.inc("pre", identifier, identifierBase);
- break;
- case "preminor":
- this.prerelease.length = 0;
- this.patch = 0;
- this.minor++;
- this.inc("pre", identifier, identifierBase);
- break;
- case "prepatch":
- this.prerelease.length = 0;
- this.inc("patch", identifier, identifierBase);
- this.inc("pre", identifier, identifierBase);
- break;
- case "prerelease":
- if (this.prerelease.length === 0) {
- this.inc("patch", identifier, identifierBase);
- }
- this.inc("pre", identifier, identifierBase);
- break;
- case "release":
- if (this.prerelease.length === 0) {
- throw new Error(`version ${this.raw} is not a prerelease`);
- }
- this.prerelease.length = 0;
- break;
- case "major":
- 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.patch !== 0 || this.prerelease.length === 0) {
- this.minor++;
- }
- this.patch = 0;
- this.prerelease = [];
- break;
- case "patch":
- if (this.prerelease.length === 0) {
- this.patch++;
- }
- this.prerelease = [];
- break;
- case "pre": {
- const base2 = Number(identifierBase) ? 1 : 0;
- if (this.prerelease.length === 0) {
- this.prerelease = [base2];
- } else {
- let i5 = this.prerelease.length;
- while (--i5 >= 0) {
- if (typeof this.prerelease[i5] === "number") {
- this.prerelease[i5]++;
- i5 = -2;
- }
- }
- if (i5 === -1) {
- if (identifier === this.prerelease.join(".") && identifierBase === false) {
- throw new Error("invalid increment argument: identifier already exists");
- }
- this.prerelease.push(base2);
- }
- }
- if (identifier) {
- let prerelease = [identifier, base2];
- if (identifierBase === false) {
- prerelease = [identifier];
- }
- if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
- if (isNaN(this.prerelease[1])) {
- this.prerelease = prerelease;
- }
- } else {
- this.prerelease = prerelease;
- }
- }
- break;
- }
- default:
- throw new Error(`invalid increment argument: ${release}`);
- }
- this.raw = this.format();
- if (this.build.length) {
- this.raw += `+${this.build.join(".")}`;
- }
- return this;
- }
- }
- module.exports = SemVer;
-});
-
-// node_modules/semver/functions/parse.js
-var require_parse4 = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var parse9 = (version5, options2, throwErrors = false) => {
- if (version5 instanceof SemVer) {
- return version5;
- }
- try {
- return new SemVer(version5, options2);
- } catch (er) {
- if (!throwErrors) {
- return null;
- }
- throw er;
- }
- };
- module.exports = parse9;
-});
-
-// node_modules/semver/functions/valid.js
-var require_valid = __commonJS((exports, module) => {
- var parse9 = require_parse4();
- var valid = (version5, options2) => {
- const v6 = parse9(version5, options2);
- return v6 ? v6.version : null;
- };
- module.exports = valid;
-});
-
-// node_modules/semver/functions/clean.js
-var require_clean = __commonJS((exports, module) => {
- var parse9 = require_parse4();
- var clean = (version5, options2) => {
- const s4 = parse9(version5.trim().replace(/^[=v]+/, ""), options2);
- return s4 ? s4.version : null;
- };
- module.exports = clean;
-});
-
-// node_modules/semver/functions/inc.js
-var require_inc = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var inc = (version5, release, options2, identifier, identifierBase) => {
- if (typeof options2 === "string") {
- identifierBase = identifier;
- identifier = options2;
- options2 = undefined;
- }
- try {
- return new SemVer(version5 instanceof SemVer ? version5.version : version5, options2).inc(release, identifier, identifierBase).version;
- } catch (er) {
- return null;
- }
- };
- module.exports = inc;
-});
-
-// node_modules/semver/functions/diff.js
-var require_diff = __commonJS((exports, module) => {
- var parse9 = require_parse4();
- var diff = (version1, version22) => {
- const v12 = parse9(version1, null, true);
- const v22 = parse9(version22, null, true);
- const comparison = v12.compare(v22);
- if (comparison === 0) {
- return null;
- }
- const v1Higher = comparison > 0;
- const highVersion = v1Higher ? v12 : v22;
- const lowVersion = v1Higher ? v22 : v12;
- const highHasPre = !!highVersion.prerelease.length;
- const lowHasPre = !!lowVersion.prerelease.length;
- if (lowHasPre && !highHasPre) {
- if (!lowVersion.patch && !lowVersion.minor) {
- return "major";
- }
- if (lowVersion.compareMain(highVersion) === 0) {
- if (lowVersion.minor && !lowVersion.patch) {
- return "minor";
- }
- return "patch";
- }
- }
- const prefix = highHasPre ? "pre" : "";
- if (v12.major !== v22.major) {
- return prefix + "major";
- }
- if (v12.minor !== v22.minor) {
- return prefix + "minor";
- }
- if (v12.patch !== v22.patch) {
- return prefix + "patch";
- }
- return "prerelease";
- };
- module.exports = diff;
-});
-
-// node_modules/semver/functions/major.js
-var require_major = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var major = (a5, loose) => new SemVer(a5, loose).major;
- module.exports = major;
-});
-
-// node_modules/semver/functions/minor.js
-var require_minor = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var minor = (a5, loose) => new SemVer(a5, loose).minor;
- module.exports = minor;
-});
-
-// node_modules/semver/functions/patch.js
-var require_patch = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var patch = (a5, loose) => new SemVer(a5, loose).patch;
- module.exports = patch;
-});
-
-// node_modules/semver/functions/prerelease.js
-var require_prerelease = __commonJS((exports, module) => {
- var parse9 = require_parse4();
- var prerelease = (version5, options2) => {
- const parsed = parse9(version5, options2);
- return parsed && parsed.prerelease.length ? parsed.prerelease : null;
- };
- module.exports = prerelease;
-});
-
-// node_modules/semver/functions/compare.js
-var require_compare = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var compare = (a5, b4, loose) => new SemVer(a5, loose).compare(new SemVer(b4, loose));
- module.exports = compare;
-});
-
-// node_modules/semver/functions/rcompare.js
-var require_rcompare = __commonJS((exports, module) => {
- var compare = require_compare();
- var rcompare = (a5, b4, loose) => compare(b4, a5, loose);
- module.exports = rcompare;
-});
-
-// node_modules/semver/functions/compare-loose.js
-var require_compare_loose = __commonJS((exports, module) => {
- var compare = require_compare();
- var compareLoose = (a5, b4) => compare(a5, b4, true);
- module.exports = compareLoose;
-});
-
-// node_modules/semver/functions/compare-build.js
-var require_compare_build = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var compareBuild = (a5, b4, loose) => {
- const versionA = new SemVer(a5, loose);
- const versionB = new SemVer(b4, loose);
- return versionA.compare(versionB) || versionA.compareBuild(versionB);
- };
- module.exports = compareBuild;
-});
-
-// node_modules/semver/functions/sort.js
-var require_sort = __commonJS((exports, module) => {
- var compareBuild = require_compare_build();
- var sort = (list2, loose) => list2.sort((a5, b4) => compareBuild(a5, b4, loose));
- module.exports = sort;
-});
-
-// node_modules/semver/functions/rsort.js
-var require_rsort = __commonJS((exports, module) => {
- var compareBuild = require_compare_build();
- var rsort = (list2, loose) => list2.sort((a5, b4) => compareBuild(b4, a5, loose));
- module.exports = rsort;
-});
-
-// node_modules/semver/functions/gt.js
-var require_gt = __commonJS((exports, module) => {
- var compare = require_compare();
- var gt = (a5, b4, loose) => compare(a5, b4, loose) > 0;
- module.exports = gt;
-});
-
-// node_modules/semver/functions/lt.js
-var require_lt = __commonJS((exports, module) => {
- var compare = require_compare();
- var lt = (a5, b4, loose) => compare(a5, b4, loose) < 0;
- module.exports = lt;
-});
-
-// node_modules/semver/functions/eq.js
-var require_eq = __commonJS((exports, module) => {
- var compare = require_compare();
- var eq2 = (a5, b4, loose) => compare(a5, b4, loose) === 0;
- module.exports = eq2;
-});
-
-// node_modules/semver/functions/neq.js
-var require_neq = __commonJS((exports, module) => {
- var compare = require_compare();
- var neq = (a5, b4, loose) => compare(a5, b4, loose) !== 0;
- module.exports = neq;
-});
-
-// node_modules/semver/functions/gte.js
-var require_gte = __commonJS((exports, module) => {
- var compare = require_compare();
- var gte = (a5, b4, loose) => compare(a5, b4, loose) >= 0;
- module.exports = gte;
-});
-
-// node_modules/semver/functions/lte.js
-var require_lte = __commonJS((exports, module) => {
- var compare = require_compare();
- var lte = (a5, b4, loose) => compare(a5, b4, loose) <= 0;
- module.exports = lte;
-});
-
-// node_modules/semver/functions/cmp.js
-var require_cmp = __commonJS((exports, module) => {
- var eq2 = require_eq();
- var neq = require_neq();
- var gt = require_gt();
- var gte = require_gte();
- var lt = require_lt();
- var lte = require_lte();
- var cmp = (a5, op, b4, loose) => {
- switch (op) {
- case "===":
- if (typeof a5 === "object") {
- a5 = a5.version;
- }
- if (typeof b4 === "object") {
- b4 = b4.version;
- }
- return a5 === b4;
- case "!==":
- if (typeof a5 === "object") {
- a5 = a5.version;
- }
- if (typeof b4 === "object") {
- b4 = b4.version;
- }
- return a5 !== b4;
- case "":
- case "=":
- case "==":
- return eq2(a5, b4, loose);
- case "!=":
- return neq(a5, b4, loose);
- case ">":
- return gt(a5, b4, loose);
- case ">=":
- return gte(a5, b4, loose);
- case "<":
- return lt(a5, b4, loose);
- case "<=":
- return lte(a5, b4, loose);
- default:
- throw new TypeError(`Invalid operator: ${op}`);
- }
- };
- module.exports = cmp;
-});
-
-// node_modules/semver/functions/coerce.js
-var require_coerce = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var parse9 = require_parse4();
- var { safeRe: re, t: t4 } = require_re();
- var coerce = (version5, options2) => {
- if (version5 instanceof SemVer) {
- return version5;
- }
- if (typeof version5 === "number") {
- version5 = String(version5);
- }
- if (typeof version5 !== "string") {
- return null;
- }
- options2 = options2 || {};
- let match = null;
- if (!options2.rtl) {
- match = version5.match(options2.includePrerelease ? re[t4.COERCEFULL] : re[t4.COERCE]);
- } else {
- const coerceRtlRegex = options2.includePrerelease ? re[t4.COERCERTLFULL] : re[t4.COERCERTL];
- let next;
- while ((next = coerceRtlRegex.exec(version5)) && (!match || match.index + match[0].length !== version5.length)) {
- if (!match || next.index + next[0].length !== match.index + match[0].length) {
- match = next;
- }
- coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
- }
- coerceRtlRegex.lastIndex = -1;
- }
- if (match === null) {
- return null;
- }
- const major = match[2];
- const minor = match[3] || "0";
- const patch = match[4] || "0";
- const prerelease = options2.includePrerelease && match[5] ? `-${match[5]}` : "";
- const build = options2.includePrerelease && match[6] ? `+${match[6]}` : "";
- return parse9(`${major}.${minor}.${patch}${prerelease}${build}`, options2);
- };
- module.exports = coerce;
-});
-
-// node_modules/semver/internal/lrucache.js
-var require_lrucache = __commonJS((exports, module) => {
- class LRUCache {
- constructor() {
- this.max = 1000;
- this.map = new Map;
- }
- get(key) {
- const value = this.map.get(key);
- if (value === undefined) {
- return;
- } else {
- this.map.delete(key);
- this.map.set(key, value);
- return value;
- }
- }
- delete(key) {
- return this.map.delete(key);
- }
- set(key, value) {
- const deleted = this.delete(key);
- if (!deleted && value !== undefined) {
- if (this.map.size >= this.max) {
- const firstKey = this.map.keys().next().value;
- this.delete(firstKey);
- }
- this.map.set(key, value);
- }
- return this;
- }
- }
- module.exports = LRUCache;
-});
-
-// node_modules/semver/classes/range.js
-var require_range2 = __commonJS((exports, module) => {
- var SPACE_CHARACTERS = /\s+/g;
-
- class Range {
- constructor(range, options2) {
- options2 = parseOptions(options2);
- if (range instanceof Range) {
- if (range.loose === !!options2.loose && range.includePrerelease === !!options2.includePrerelease) {
- return range;
- } else {
- return new Range(range.raw, options2);
- }
- }
- if (range instanceof Comparator) {
- this.raw = range.value;
- this.set = [[range]];
- this.formatted = undefined;
- return this;
- }
- this.options = options2;
- this.loose = !!options2.loose;
- this.includePrerelease = !!options2.includePrerelease;
- this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
- this.set = this.raw.split("||").map((r4) => this.parseRange(r4.trim())).filter((c8) => c8.length);
- if (!this.set.length) {
- throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
- }
- if (this.set.length > 1) {
- const first = this.set[0];
- this.set = this.set.filter((c8) => !isNullSet(c8[0]));
- if (this.set.length === 0) {
- this.set = [first];
- } else if (this.set.length > 1) {
- for (const c8 of this.set) {
- if (c8.length === 1 && isAny(c8[0])) {
- this.set = [c8];
- break;
- }
- }
- }
- }
- this.formatted = undefined;
- }
- get range() {
- if (this.formatted === undefined) {
- this.formatted = "";
- for (let i5 = 0;i5 < this.set.length; i5++) {
- if (i5 > 0) {
- this.formatted += "||";
- }
- const comps = this.set[i5];
- for (let k4 = 0;k4 < comps.length; k4++) {
- if (k4 > 0) {
- this.formatted += " ";
- }
- this.formatted += comps[k4].toString().trim();
- }
- }
- }
- return this.formatted;
- }
- format() {
- return this.range;
- }
- toString() {
- return this.range;
- }
- parseRange(range) {
- const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
- const memoKey = memoOpts + ":" + range;
- const cached2 = cache5.get(memoKey);
- if (cached2) {
- return cached2;
- }
- const loose = this.options.loose;
- const hr2 = loose ? re[t4.HYPHENRANGELOOSE] : re[t4.HYPHENRANGE];
- range = range.replace(hr2, hyphenReplace(this.options.includePrerelease));
- debug2("hyphen replace", range);
- range = range.replace(re[t4.COMPARATORTRIM], comparatorTrimReplace);
- debug2("comparator trim", range);
- range = range.replace(re[t4.TILDETRIM], tildeTrimReplace);
- debug2("tilde trim", range);
- range = range.replace(re[t4.CARETTRIM], caretTrimReplace);
- debug2("caret trim", range);
- let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
- if (loose) {
- rangeList = rangeList.filter((comp) => {
- debug2("loose invalid filter", comp, this.options);
- return !!comp.match(re[t4.COMPARATORLOOSE]);
- });
- }
- debug2("range list", rangeList);
- const rangeMap = new Map;
- const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
- for (const comp of comparators) {
- if (isNullSet(comp)) {
- return [comp];
- }
- rangeMap.set(comp.value, comp);
- }
- if (rangeMap.size > 1 && rangeMap.has("")) {
- rangeMap.delete("");
- }
- const result = [...rangeMap.values()];
- cache5.set(memoKey, result);
- return result;
- }
- intersects(range, options2) {
- if (!(range instanceof Range)) {
- throw new TypeError("a Range is required");
- }
- return this.set.some((thisComparators) => {
- return isSatisfiable(thisComparators, options2) && range.set.some((rangeComparators) => {
- return isSatisfiable(rangeComparators, options2) && thisComparators.every((thisComparator) => {
- return rangeComparators.every((rangeComparator) => {
- return thisComparator.intersects(rangeComparator, options2);
- });
- });
- });
- });
- }
- test(version5) {
- if (!version5) {
- return false;
- }
- if (typeof version5 === "string") {
- try {
- version5 = new SemVer(version5, this.options);
- } catch (er) {
- return false;
- }
- }
- for (let i5 = 0;i5 < this.set.length; i5++) {
- if (testSet(this.set[i5], version5, this.options)) {
- return true;
- }
- }
- return false;
- }
- }
- module.exports = Range;
- var LRU = require_lrucache();
- var cache5 = new LRU;
- var parseOptions = require_parse_options();
- var Comparator = require_comparator();
- var debug2 = require_debug2();
- var SemVer = require_semver();
- var {
- safeRe: re,
- t: t4,
- comparatorTrimReplace,
- tildeTrimReplace,
- caretTrimReplace
- } = require_re();
- var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants3();
- var isNullSet = (c8) => c8.value === "<0.0.0-0";
- var isAny = (c8) => c8.value === "";
- var isSatisfiable = (comparators, options2) => {
- let result = true;
- const remainingComparators = comparators.slice();
- let testComparator = remainingComparators.pop();
- while (result && remainingComparators.length) {
- result = remainingComparators.every((otherComparator) => {
- return testComparator.intersects(otherComparator, options2);
- });
- testComparator = remainingComparators.pop();
- }
- return result;
- };
- var parseComparator = (comp, options2) => {
- comp = comp.replace(re[t4.BUILD], "");
- debug2("comp", comp, options2);
- comp = replaceCarets(comp, options2);
- debug2("caret", comp);
- comp = replaceTildes(comp, options2);
- debug2("tildes", comp);
- comp = replaceXRanges(comp, options2);
- debug2("xrange", comp);
- comp = replaceStars(comp, options2);
- debug2("stars", comp);
- return comp;
- };
- var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
- var replaceTildes = (comp, options2) => {
- return comp.trim().split(/\s+/).map((c8) => replaceTilde(c8, options2)).join(" ");
- };
- var replaceTilde = (comp, options2) => {
- const r4 = options2.loose ? re[t4.TILDELOOSE] : re[t4.TILDE];
- return comp.replace(r4, (_, M2, m4, p4, pr) => {
- debug2("tilde", comp, _, M2, m4, p4, pr);
- let ret;
- if (isX(M2)) {
- ret = "";
- } else if (isX(m4)) {
- ret = `>=${M2}.0.0 <${+M2 + 1}.0.0-0`;
- } else if (isX(p4)) {
- ret = `>=${M2}.${m4}.0 <${M2}.${+m4 + 1}.0-0`;
- } else if (pr) {
- debug2("replaceTilde pr", pr);
- ret = `>=${M2}.${m4}.${p4}-${pr} <${M2}.${+m4 + 1}.0-0`;
- } else {
- ret = `>=${M2}.${m4}.${p4} <${M2}.${+m4 + 1}.0-0`;
- }
- debug2("tilde return", ret);
- return ret;
- });
- };
- var replaceCarets = (comp, options2) => {
- return comp.trim().split(/\s+/).map((c8) => replaceCaret(c8, options2)).join(" ");
- };
- var replaceCaret = (comp, options2) => {
- debug2("caret", comp, options2);
- const r4 = options2.loose ? re[t4.CARETLOOSE] : re[t4.CARET];
- const z3 = options2.includePrerelease ? "-0" : "";
- return comp.replace(r4, (_, M2, m4, p4, pr) => {
- debug2("caret", comp, _, M2, m4, p4, pr);
- let ret;
- if (isX(M2)) {
- ret = "";
- } else if (isX(m4)) {
- ret = `>=${M2}.0.0${z3} <${+M2 + 1}.0.0-0`;
- } else if (isX(p4)) {
- if (M2 === "0") {
- ret = `>=${M2}.${m4}.0${z3} <${M2}.${+m4 + 1}.0-0`;
- } else {
- ret = `>=${M2}.${m4}.0${z3} <${+M2 + 1}.0.0-0`;
- }
- } else if (pr) {
- debug2("replaceCaret pr", pr);
- if (M2 === "0") {
- if (m4 === "0") {
- ret = `>=${M2}.${m4}.${p4}-${pr} <${M2}.${m4}.${+p4 + 1}-0`;
- } else {
- ret = `>=${M2}.${m4}.${p4}-${pr} <${M2}.${+m4 + 1}.0-0`;
- }
- } else {
- ret = `>=${M2}.${m4}.${p4}-${pr} <${+M2 + 1}.0.0-0`;
- }
- } else {
- debug2("no pr");
- if (M2 === "0") {
- if (m4 === "0") {
- ret = `>=${M2}.${m4}.${p4}${z3} <${M2}.${m4}.${+p4 + 1}-0`;
- } else {
- ret = `>=${M2}.${m4}.${p4}${z3} <${M2}.${+m4 + 1}.0-0`;
- }
- } else {
- ret = `>=${M2}.${m4}.${p4} <${+M2 + 1}.0.0-0`;
- }
- }
- debug2("caret return", ret);
- return ret;
- });
- };
- var replaceXRanges = (comp, options2) => {
- debug2("replaceXRanges", comp, options2);
- return comp.split(/\s+/).map((c8) => replaceXRange(c8, options2)).join(" ");
- };
- var replaceXRange = (comp, options2) => {
- comp = comp.trim();
- const r4 = options2.loose ? re[t4.XRANGELOOSE] : re[t4.XRANGE];
- return comp.replace(r4, (ret, gtlt, M2, m4, p4, pr) => {
- debug2("xRange", comp, ret, gtlt, M2, m4, p4, pr);
- const xM = isX(M2);
- const xm = xM || isX(m4);
- const xp = xm || isX(p4);
- const anyX = xp;
- if (gtlt === "=" && anyX) {
- gtlt = "";
- }
- pr = options2.includePrerelease ? "-0" : "";
- if (xM) {
- if (gtlt === ">" || gtlt === "<") {
- ret = "<0.0.0-0";
- } else {
- ret = "*";
- }
- } else if (gtlt && anyX) {
- if (xm) {
- m4 = 0;
- }
- p4 = 0;
- if (gtlt === ">") {
- gtlt = ">=";
- if (xm) {
- M2 = +M2 + 1;
- m4 = 0;
- p4 = 0;
- } else {
- m4 = +m4 + 1;
- p4 = 0;
- }
- } else if (gtlt === "<=") {
- gtlt = "<";
- if (xm) {
- M2 = +M2 + 1;
- } else {
- m4 = +m4 + 1;
- }
- }
- if (gtlt === "<") {
- pr = "-0";
- }
- ret = `${gtlt + M2}.${m4}.${p4}${pr}`;
- } else if (xm) {
- ret = `>=${M2}.0.0${pr} <${+M2 + 1}.0.0-0`;
- } else if (xp) {
- ret = `>=${M2}.${m4}.0${pr} <${M2}.${+m4 + 1}.0-0`;
- }
- debug2("xRange return", ret);
- return ret;
- });
- };
- var replaceStars = (comp, options2) => {
- debug2("replaceStars", comp, options2);
- return comp.trim().replace(re[t4.STAR], "");
- };
- var replaceGTE0 = (comp, options2) => {
- debug2("replaceGTE0", comp, options2);
- return comp.trim().replace(re[options2.includePrerelease ? t4.GTE0PRE : t4.GTE0], "");
- };
- var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
- if (isX(fM)) {
- from = "";
- } else if (isX(fm)) {
- from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
- } else if (isX(fp)) {
- from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
- } else if (fpr) {
- from = `>=${from}`;
- } else {
- from = `>=${from}${incPr ? "-0" : ""}`;
- }
- if (isX(tM)) {
- to = "";
- } else if (isX(tm)) {
- to = `<${+tM + 1}.0.0-0`;
- } else if (isX(tp)) {
- to = `<${tM}.${+tm + 1}.0-0`;
- } else if (tpr) {
- to = `<=${tM}.${tm}.${tp}-${tpr}`;
- } else if (incPr) {
- to = `<${tM}.${tm}.${+tp + 1}-0`;
- } else {
- to = `<=${to}`;
- }
- return `${from} ${to}`.trim();
- };
- var testSet = (set2, version5, options2) => {
- for (let i5 = 0;i5 < set2.length; i5++) {
- if (!set2[i5].test(version5)) {
- return false;
- }
- }
- if (version5.prerelease.length && !options2.includePrerelease) {
- for (let i5 = 0;i5 < set2.length; i5++) {
- debug2(set2[i5].semver);
- if (set2[i5].semver === Comparator.ANY) {
- continue;
- }
- if (set2[i5].semver.prerelease.length > 0) {
- const allowed = set2[i5].semver;
- if (allowed.major === version5.major && allowed.minor === version5.minor && allowed.patch === version5.patch) {
- return true;
- }
- }
- }
- return false;
- }
- return true;
- };
-});
-
-// node_modules/semver/classes/comparator.js
-var require_comparator = __commonJS((exports, module) => {
- var ANY = Symbol("SemVer ANY");
-
- class Comparator {
- static get ANY() {
- return ANY;
- }
- constructor(comp, options2) {
- options2 = parseOptions(options2);
- if (comp instanceof Comparator) {
- if (comp.loose === !!options2.loose) {
- return comp;
- } else {
- comp = comp.value;
- }
- }
- comp = comp.trim().split(/\s+/).join(" ");
- debug2("comparator", comp, options2);
- this.options = options2;
- this.loose = !!options2.loose;
- this.parse(comp);
- if (this.semver === ANY) {
- this.value = "";
- } else {
- this.value = this.operator + this.semver.version;
- }
- debug2("comp", this);
- }
- parse(comp) {
- const r4 = this.options.loose ? re[t4.COMPARATORLOOSE] : re[t4.COMPARATOR];
- const m4 = comp.match(r4);
- if (!m4) {
- throw new TypeError(`Invalid comparator: ${comp}`);
- }
- this.operator = m4[1] !== undefined ? m4[1] : "";
- if (this.operator === "=") {
- this.operator = "";
- }
- if (!m4[2]) {
- this.semver = ANY;
- } else {
- this.semver = new SemVer(m4[2], this.options.loose);
- }
- }
- toString() {
- return this.value;
- }
- test(version5) {
- debug2("Comparator.test", version5, this.options.loose);
- if (this.semver === ANY || version5 === ANY) {
- return true;
- }
- if (typeof version5 === "string") {
- try {
- version5 = new SemVer(version5, this.options);
- } catch (er) {
- return false;
- }
- }
- return cmp(version5, this.operator, this.semver, this.options);
- }
- intersects(comp, options2) {
- if (!(comp instanceof Comparator)) {
- throw new TypeError("a Comparator is required");
- }
- if (this.operator === "") {
- if (this.value === "") {
- return true;
- }
- return new Range(comp.value, options2).test(this.value);
- } else if (comp.operator === "") {
- if (comp.value === "") {
- return true;
- }
- return new Range(this.value, options2).test(comp.semver);
- }
- options2 = parseOptions(options2);
- if (options2.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
- return false;
- }
- if (!options2.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
- return false;
- }
- if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
- return true;
- }
- if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
- return true;
- }
- if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
- return true;
- }
- if (cmp(this.semver, "<", comp.semver, options2) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
- return true;
- }
- if (cmp(this.semver, ">", comp.semver, options2) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
- return true;
- }
- return false;
- }
- }
- module.exports = Comparator;
- var parseOptions = require_parse_options();
- var { safeRe: re, t: t4 } = require_re();
- var cmp = require_cmp();
- var debug2 = require_debug2();
- var SemVer = require_semver();
- var Range = require_range2();
-});
-
-// node_modules/semver/functions/satisfies.js
-var require_satisfies = __commonJS((exports, module) => {
- var Range = require_range2();
- var satisfies = (version5, range, options2) => {
- try {
- range = new Range(range, options2);
- } catch (er) {
- return false;
- }
- return range.test(version5);
- };
- module.exports = satisfies;
-});
-
-// node_modules/semver/ranges/to-comparators.js
-var require_to_comparators = __commonJS((exports, module) => {
- var Range = require_range2();
- var toComparators = (range, options2) => new Range(range, options2).set.map((comp) => comp.map((c8) => c8.value).join(" ").trim().split(" "));
- module.exports = toComparators;
-});
-
-// node_modules/semver/ranges/max-satisfying.js
-var require_max_satisfying = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var Range = require_range2();
- var maxSatisfying = (versions2, range, options2) => {
- let max = null;
- let maxSV = null;
- let rangeObj = null;
- try {
- rangeObj = new Range(range, options2);
- } catch (er) {
- return null;
- }
- versions2.forEach((v6) => {
- if (rangeObj.test(v6)) {
- if (!max || maxSV.compare(v6) === -1) {
- max = v6;
- maxSV = new SemVer(max, options2);
- }
- }
- });
- return max;
- };
- module.exports = maxSatisfying;
-});
-
-// node_modules/semver/ranges/min-satisfying.js
-var require_min_satisfying = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var Range = require_range2();
- var minSatisfying = (versions2, range, options2) => {
- let min = null;
- let minSV = null;
- let rangeObj = null;
- try {
- rangeObj = new Range(range, options2);
- } catch (er) {
- return null;
- }
- versions2.forEach((v6) => {
- if (rangeObj.test(v6)) {
- if (!min || minSV.compare(v6) === 1) {
- min = v6;
- minSV = new SemVer(min, options2);
- }
- }
- });
- return min;
- };
- module.exports = minSatisfying;
-});
-
-// node_modules/semver/ranges/min-version.js
-var require_min_version = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var Range = require_range2();
- var gt = require_gt();
- var minVersion = (range, loose) => {
- range = new Range(range, loose);
- let 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 (let i5 = 0;i5 < range.set.length; ++i5) {
- const comparators = range.set[i5];
- let setMin = null;
- comparators.forEach((comparator) => {
- const 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();
- case "":
- case ">=":
- if (!setMin || gt(compver, setMin)) {
- setMin = compver;
- }
- break;
- case "<":
- case "<=":
- break;
- default:
- throw new Error(`Unexpected operation: ${comparator.operator}`);
- }
- });
- if (setMin && (!minver || gt(minver, setMin))) {
- minver = setMin;
- }
- }
- if (minver && range.test(minver)) {
- return minver;
- }
- return null;
- };
- module.exports = minVersion;
-});
-
-// node_modules/semver/ranges/valid.js
-var require_valid2 = __commonJS((exports, module) => {
- var Range = require_range2();
- var validRange = (range, options2) => {
- try {
- return new Range(range, options2).range || "*";
- } catch (er) {
- return null;
- }
- };
- module.exports = validRange;
-});
-
-// node_modules/semver/ranges/outside.js
-var require_outside = __commonJS((exports, module) => {
- var SemVer = require_semver();
- var Comparator = require_comparator();
- var { ANY } = Comparator;
- var Range = require_range2();
- var satisfies = require_satisfies();
- var gt = require_gt();
- var lt = require_lt();
- var lte = require_lte();
- var gte = require_gte();
- var outside = (version5, range, hilo, options2) => {
- version5 = new SemVer(version5, options2);
- range = new Range(range, options2);
- let gtfn, ltefn, ltfn, comp, ecomp;
- switch (hilo) {
- case ">":
- gtfn = gt;
- ltefn = lte;
- ltfn = lt;
- comp = ">";
- ecomp = ">=";
- break;
- case "<":
- gtfn = lt;
- ltefn = gte;
- ltfn = gt;
- comp = "<";
- ecomp = "<=";
- break;
- default:
- throw new TypeError('Must provide a hilo val of "<" or ">"');
- }
- if (satisfies(version5, range, options2)) {
- return false;
- }
- for (let i5 = 0;i5 < range.set.length; ++i5) {
- const comparators = range.set[i5];
- let high = null;
- let low = null;
- comparators.forEach((comparator) => {
- if (comparator.semver === ANY) {
- comparator = new Comparator(">=0.0.0");
- }
- high = high || comparator;
- low = low || comparator;
- if (gtfn(comparator.semver, high.semver, options2)) {
- high = comparator;
- } else if (ltfn(comparator.semver, low.semver, options2)) {
- low = comparator;
- }
- });
- if (high.operator === comp || high.operator === ecomp) {
- return false;
- }
- if ((!low.operator || low.operator === comp) && ltefn(version5, low.semver)) {
- return false;
- } else if (low.operator === ecomp && ltfn(version5, low.semver)) {
- return false;
- }
- }
- return true;
- };
- module.exports = outside;
-});
-
-// node_modules/semver/ranges/gtr.js
-var require_gtr = __commonJS((exports, module) => {
- var outside = require_outside();
- var gtr = (version5, range, options2) => outside(version5, range, ">", options2);
- module.exports = gtr;
-});
-
-// node_modules/semver/ranges/ltr.js
-var require_ltr = __commonJS((exports, module) => {
- var outside = require_outside();
- var ltr = (version5, range, options2) => outside(version5, range, "<", options2);
- module.exports = ltr;
-});
-
-// node_modules/semver/ranges/intersects.js
-var require_intersects = __commonJS((exports, module) => {
- var Range = require_range2();
- var intersects = (r1, r22, options2) => {
- r1 = new Range(r1, options2);
- r22 = new Range(r22, options2);
- return r1.intersects(r22, options2);
- };
- module.exports = intersects;
-});
-
-// node_modules/semver/ranges/simplify.js
-var require_simplify = __commonJS((exports, module) => {
- var satisfies = require_satisfies();
- var compare = require_compare();
- module.exports = (versions2, range, options2) => {
- const set2 = [];
- let first = null;
- let prev = null;
- const v6 = versions2.sort((a5, b4) => compare(a5, b4, options2));
- for (const version5 of v6) {
- const included = satisfies(version5, range, options2);
- if (included) {
- prev = version5;
- if (!first) {
- first = version5;
- }
- } else {
- if (prev) {
- set2.push([first, prev]);
- }
- prev = null;
- first = null;
- }
- }
- if (first) {
- set2.push([first, null]);
- }
- const ranges = [];
- for (const [min, max] of set2) {
- if (min === max) {
- ranges.push(min);
- } else if (!max && min === v6[0]) {
- ranges.push("*");
- } else if (!max) {
- ranges.push(`>=${min}`);
- } else if (min === v6[0]) {
- ranges.push(`<=${max}`);
- } else {
- ranges.push(`${min} - ${max}`);
- }
- }
- const simplified = ranges.join(" || ");
- const original = typeof range.raw === "string" ? range.raw : String(range);
- return simplified.length < original.length ? simplified : range;
- };
-});
-
-// node_modules/semver/ranges/subset.js
-var require_subset = __commonJS((exports, module) => {
- var Range = require_range2();
- var Comparator = require_comparator();
- var { ANY } = Comparator;
- var satisfies = require_satisfies();
- var compare = require_compare();
- var subset = (sub, dom, options2 = {}) => {
- if (sub === dom) {
- return true;
- }
- sub = new Range(sub, options2);
- dom = new Range(dom, options2);
- let sawNonNull = false;
- OUTER:
- for (const simpleSub of sub.set) {
- for (const simpleDom of dom.set) {
- const isSub = simpleSubset(simpleSub, simpleDom, options2);
- sawNonNull = sawNonNull || isSub !== null;
- if (isSub) {
- continue OUTER;
- }
- }
- if (sawNonNull) {
- return false;
- }
- }
- return true;
- };
- var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
- var minimumVersion = [new Comparator(">=0.0.0")];
- var simpleSubset = (sub, dom, options2) => {
- if (sub === dom) {
- return true;
- }
- if (sub.length === 1 && sub[0].semver === ANY) {
- if (dom.length === 1 && dom[0].semver === ANY) {
- return true;
- } else if (options2.includePrerelease) {
- sub = minimumVersionWithPreRelease;
- } else {
- sub = minimumVersion;
- }
- }
- if (dom.length === 1 && dom[0].semver === ANY) {
- if (options2.includePrerelease) {
- return true;
- } else {
- dom = minimumVersion;
- }
- }
- const eqSet = new Set;
- let gt, lt;
- for (const c8 of sub) {
- if (c8.operator === ">" || c8.operator === ">=") {
- gt = higherGT(gt, c8, options2);
- } else if (c8.operator === "<" || c8.operator === "<=") {
- lt = lowerLT(lt, c8, options2);
- } else {
- eqSet.add(c8.semver);
- }
- }
- if (eqSet.size > 1) {
- return null;
- }
- let gtltComp;
- if (gt && lt) {
- gtltComp = compare(gt.semver, lt.semver, options2);
- if (gtltComp > 0) {
- return null;
- } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
- return null;
- }
- }
- for (const eq2 of eqSet) {
- if (gt && !satisfies(eq2, String(gt), options2)) {
- return null;
- }
- if (lt && !satisfies(eq2, String(lt), options2)) {
- return null;
- }
- for (const c8 of dom) {
- if (!satisfies(eq2, String(c8), options2)) {
- return false;
- }
- }
- return true;
- }
- let higher, lower;
- let hasDomLT, hasDomGT;
- let needDomLTPre = lt && !options2.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
- let needDomGTPre = gt && !options2.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
- if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
- needDomLTPre = false;
- }
- for (const c8 of dom) {
- hasDomGT = hasDomGT || c8.operator === ">" || c8.operator === ">=";
- hasDomLT = hasDomLT || c8.operator === "<" || c8.operator === "<=";
- if (gt) {
- if (needDomGTPre) {
- if (c8.semver.prerelease && c8.semver.prerelease.length && c8.semver.major === needDomGTPre.major && c8.semver.minor === needDomGTPre.minor && c8.semver.patch === needDomGTPre.patch) {
- needDomGTPre = false;
- }
- }
- if (c8.operator === ">" || c8.operator === ">=") {
- higher = higherGT(gt, c8, options2);
- if (higher === c8 && higher !== gt) {
- return false;
- }
- } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c8), options2)) {
- return false;
- }
- }
- if (lt) {
- if (needDomLTPre) {
- if (c8.semver.prerelease && c8.semver.prerelease.length && c8.semver.major === needDomLTPre.major && c8.semver.minor === needDomLTPre.minor && c8.semver.patch === needDomLTPre.patch) {
- needDomLTPre = false;
- }
- }
- if (c8.operator === "<" || c8.operator === "<=") {
- lower = lowerLT(lt, c8, options2);
- if (lower === c8 && lower !== lt) {
- return false;
- }
- } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c8), options2)) {
- return false;
- }
- }
- if (!c8.operator && (lt || gt) && gtltComp !== 0) {
- return false;
- }
- }
- if (gt && hasDomLT && !lt && gtltComp !== 0) {
- return false;
- }
- if (lt && hasDomGT && !gt && gtltComp !== 0) {
- return false;
- }
- if (needDomGTPre || needDomLTPre) {
- return false;
- }
- return true;
- };
- var higherGT = (a5, b4, options2) => {
- if (!a5) {
- return b4;
- }
- const comp = compare(a5.semver, b4.semver, options2);
- return comp > 0 ? a5 : comp < 0 ? b4 : b4.operator === ">" && a5.operator === ">=" ? b4 : a5;
- };
- var lowerLT = (a5, b4, options2) => {
- if (!a5) {
- return b4;
- }
- const comp = compare(a5.semver, b4.semver, options2);
- return comp < 0 ? a5 : comp > 0 ? b4 : b4.operator === "<" && a5.operator === "<=" ? b4 : a5;
- };
- module.exports = subset;
-});
-
-// node_modules/semver/index.js
-var require_semver2 = __commonJS((exports, module) => {
- var internalRe = require_re();
- var constants9 = require_constants3();
- var SemVer = require_semver();
- var identifiers = require_identifiers();
- var parse9 = require_parse4();
- var valid = require_valid();
- var clean = require_clean();
- var inc = require_inc();
- var diff = require_diff();
- var major = require_major();
- var minor = require_minor();
- var patch = require_patch();
- var prerelease = require_prerelease();
- var compare = require_compare();
- var rcompare = require_rcompare();
- var compareLoose = require_compare_loose();
- var compareBuild = require_compare_build();
- var sort = require_sort();
- var rsort = require_rsort();
- var gt = require_gt();
- var lt = require_lt();
- var eq2 = require_eq();
- var neq = require_neq();
- var gte = require_gte();
- var lte = require_lte();
- var cmp = require_cmp();
- var coerce = require_coerce();
- var Comparator = require_comparator();
- var Range = require_range2();
- var satisfies = require_satisfies();
- var toComparators = require_to_comparators();
- var maxSatisfying = require_max_satisfying();
- var minSatisfying = require_min_satisfying();
- var minVersion = require_min_version();
- var validRange = require_valid2();
- var outside = require_outside();
- var gtr = require_gtr();
- var ltr = require_ltr();
- var intersects = require_intersects();
- var simplifyRange = require_simplify();
- var subset = require_subset();
- module.exports = {
- parse: parse9,
- valid,
- clean,
- inc,
- diff,
- major,
- minor,
- patch,
- prerelease,
- compare,
- rcompare,
- compareLoose,
- compareBuild,
- sort,
- rsort,
- gt,
- lt,
- eq: eq2,
- neq,
- gte,
- lte,
- cmp,
- coerce,
- Comparator,
- Range,
- satisfies,
- toComparators,
- maxSatisfying,
- minSatisfying,
- minVersion,
- validRange,
- outside,
- gtr,
- ltr,
- intersects,
- simplifyRange,
- subset,
- SemVer,
- re: internalRe.re,
- src: internalRe.src,
- tokens: internalRe.t,
- SEMVER_SPEC_VERSION: constants9.SEMVER_SPEC_VERSION,
- RELEASE_TYPES: constants9.RELEASE_TYPES,
- compareIdentifiers: identifiers.compareIdentifiers,
- rcompareIdentifiers: identifiers.rcompareIdentifiers
- };
-});
-
-// node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js
-var require_asymmetricKeyDetailsSupported = __commonJS((exports, module) => {
- var semver = require_semver2();
- module.exports = semver.satisfies(process.version, ">=15.7.0");
-});
-
-// node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js
-var require_rsaPssKeyDetailsSupported = __commonJS((exports, module) => {
- var semver = require_semver2();
- module.exports = semver.satisfies(process.version, ">=16.9.0");
-});
-
-// node_modules/jsonwebtoken/lib/validateAsymmetricKey.js
-var require_validateAsymmetricKey = __commonJS((exports, module) => {
- var ASYMMETRIC_KEY_DETAILS_SUPPORTED = require_asymmetricKeyDetailsSupported();
- var RSA_PSS_KEY_DETAILS_SUPPORTED = require_rsaPssKeyDetailsSupported();
- var allowedAlgorithmsForKeys = {
- ec: ["ES256", "ES384", "ES512"],
- rsa: ["RS256", "PS256", "RS384", "PS384", "RS512", "PS512"],
- "rsa-pss": ["PS256", "PS384", "PS512"]
- };
- var allowedCurves = {
- ES256: "prime256v1",
- ES384: "secp384r1",
- ES512: "secp521r1"
- };
- module.exports = function(algorithm, key) {
- if (!algorithm || !key)
- return;
- const keyType = key.asymmetricKeyType;
- if (!keyType)
- return;
- const allowedAlgorithms = allowedAlgorithmsForKeys[keyType];
- if (!allowedAlgorithms) {
- throw new Error(`Unknown key type "${keyType}".`);
- }
- if (!allowedAlgorithms.includes(algorithm)) {
- throw new Error(`"alg" parameter for "${keyType}" key type must be one of: ${allowedAlgorithms.join(", ")}.`);
- }
- if (ASYMMETRIC_KEY_DETAILS_SUPPORTED) {
- switch (keyType) {
- case "ec":
- const keyCurve = key.asymmetricKeyDetails.namedCurve;
- const allowedCurve = allowedCurves[algorithm];
- if (keyCurve !== allowedCurve) {
- throw new Error(`"alg" parameter "${algorithm}" requires curve "${allowedCurve}".`);
- }
- break;
- case "rsa-pss":
- if (RSA_PSS_KEY_DETAILS_SUPPORTED) {
- const length = parseInt(algorithm.slice(-3), 10);
- const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails;
- if (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm) {
- throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${algorithm}.`);
- }
- if (saltLength !== undefined && saltLength > length >> 3) {
- throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${algorithm}.`);
- }
- }
- break;
- }
- }
- };
-});
-
-// node_modules/jsonwebtoken/lib/psSupported.js
-var require_psSupported = __commonJS((exports, module) => {
- var semver = require_semver2();
- module.exports = semver.satisfies(process.version, "^6.12.0 || >=8.0.0");
-});
-
-// node_modules/jsonwebtoken/verify.js
-var require_verify = __commonJS((exports, module) => {
- var JsonWebTokenError = require_JsonWebTokenError();
- var NotBeforeError = require_NotBeforeError();
- var TokenExpiredError = require_TokenExpiredError();
- var decode = require_decode();
- var timespan = require_timespan();
- var validateAsymmetricKey = require_validateAsymmetricKey();
- var PS_SUPPORTED = require_psSupported();
- var jws = require_jws();
- var { KeyObject, createSecretKey, createPublicKey: createPublicKey2 } = __require("crypto");
- var PUB_KEY_ALGS = ["RS256", "RS384", "RS512"];
- var EC_KEY_ALGS = ["ES256", "ES384", "ES512"];
- var RSA_KEY_ALGS = ["RS256", "RS384", "RS512"];
- var HS_ALGS = ["HS256", "HS384", "HS512"];
- if (PS_SUPPORTED) {
- PUB_KEY_ALGS.splice(PUB_KEY_ALGS.length, 0, "PS256", "PS384", "PS512");
- RSA_KEY_ALGS.splice(RSA_KEY_ALGS.length, 0, "PS256", "PS384", "PS512");
- }
- module.exports = function(jwtString, secretOrPublicKey, options2, callback) {
- if (typeof options2 === "function" && !callback) {
- callback = options2;
- options2 = {};
- }
- if (!options2) {
- options2 = {};
- }
- options2 = Object.assign({}, options2);
- let done;
- if (callback) {
- done = callback;
- } else {
- done = function(err, data) {
- if (err)
- throw err;
- return data;
- };
- }
- if (options2.clockTimestamp && typeof options2.clockTimestamp !== "number") {
- return done(new JsonWebTokenError("clockTimestamp must be a number"));
- }
- if (options2.nonce !== undefined && (typeof options2.nonce !== "string" || options2.nonce.trim() === "")) {
- return done(new JsonWebTokenError("nonce must be a non-empty string"));
- }
- if (options2.allowInvalidAsymmetricKeyTypes !== undefined && typeof options2.allowInvalidAsymmetricKeyTypes !== "boolean") {
- return done(new JsonWebTokenError("allowInvalidAsymmetricKeyTypes must be a boolean"));
- }
- const clockTimestamp = options2.clockTimestamp || Math.floor(Date.now() / 1000);
- if (!jwtString) {
- return done(new JsonWebTokenError("jwt must be provided"));
- }
- if (typeof jwtString !== "string") {
- return done(new JsonWebTokenError("jwt must be a string"));
- }
- const parts = jwtString.split(".");
- if (parts.length !== 3) {
- return done(new JsonWebTokenError("jwt malformed"));
- }
- let decodedToken;
- try {
- decodedToken = decode(jwtString, { complete: true });
- } catch (err) {
- return done(err);
- }
- if (!decodedToken) {
- return done(new JsonWebTokenError("invalid token"));
- }
- const header = decodedToken.header;
- let getSecret;
- if (typeof secretOrPublicKey === "function") {
- if (!callback) {
- return done(new JsonWebTokenError("verify must be called asynchronous if secret or public key is provided as a callback"));
- }
- getSecret = secretOrPublicKey;
- } else {
- getSecret = function(header2, secretCallback) {
- return secretCallback(null, secretOrPublicKey);
- };
- }
- return getSecret(header, function(err, secretOrPublicKey2) {
- if (err) {
- return done(new JsonWebTokenError("error in secret or public key callback: " + err.message));
- }
- const hasSignature = parts[2].trim() !== "";
- if (!hasSignature && secretOrPublicKey2) {
- return done(new JsonWebTokenError("jwt signature is required"));
- }
- if (hasSignature && !secretOrPublicKey2) {
- return done(new JsonWebTokenError("secret or public key must be provided"));
- }
- if (!hasSignature && !options2.algorithms) {
- return done(new JsonWebTokenError('please specify "none" in "algorithms" to verify unsigned tokens'));
- }
- if (secretOrPublicKey2 != null && !(secretOrPublicKey2 instanceof KeyObject)) {
- try {
- secretOrPublicKey2 = createPublicKey2(secretOrPublicKey2);
- } catch (_) {
- try {
- secretOrPublicKey2 = createSecretKey(typeof secretOrPublicKey2 === "string" ? Buffer.from(secretOrPublicKey2) : secretOrPublicKey2);
- } catch (_2) {
- return done(new JsonWebTokenError("secretOrPublicKey is not valid key material"));
- }
- }
- }
- if (!options2.algorithms) {
- if (secretOrPublicKey2.type === "secret") {
- options2.algorithms = HS_ALGS;
- } else if (["rsa", "rsa-pss"].includes(secretOrPublicKey2.asymmetricKeyType)) {
- options2.algorithms = RSA_KEY_ALGS;
- } else if (secretOrPublicKey2.asymmetricKeyType === "ec") {
- options2.algorithms = EC_KEY_ALGS;
- } else {
- options2.algorithms = PUB_KEY_ALGS;
- }
- }
- if (options2.algorithms.indexOf(decodedToken.header.alg) === -1) {
- return done(new JsonWebTokenError("invalid algorithm"));
- }
- if (header.alg.startsWith("HS") && secretOrPublicKey2.type !== "secret") {
- return done(new JsonWebTokenError(`secretOrPublicKey must be a symmetric key when using ${header.alg}`));
- } else if (/^(?:RS|PS|ES)/.test(header.alg) && secretOrPublicKey2.type !== "public") {
- return done(new JsonWebTokenError(`secretOrPublicKey must be an asymmetric key when using ${header.alg}`));
- }
- if (!options2.allowInvalidAsymmetricKeyTypes) {
- try {
- validateAsymmetricKey(header.alg, secretOrPublicKey2);
- } catch (e4) {
- return done(e4);
- }
- }
- let valid;
- try {
- valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey2);
- } catch (e4) {
- return done(e4);
- }
- if (!valid) {
- return done(new JsonWebTokenError("invalid signature"));
- }
- const payload = decodedToken.payload;
- if (typeof payload.nbf !== "undefined" && !options2.ignoreNotBefore) {
- if (typeof payload.nbf !== "number") {
- return done(new JsonWebTokenError("invalid nbf value"));
- }
- if (payload.nbf > clockTimestamp + (options2.clockTolerance || 0)) {
- return done(new NotBeforeError("jwt not active", new Date(payload.nbf * 1000)));
- }
- }
- if (typeof payload.exp !== "undefined" && !options2.ignoreExpiration) {
- if (typeof payload.exp !== "number") {
- return done(new JsonWebTokenError("invalid exp value"));
- }
- if (clockTimestamp >= payload.exp + (options2.clockTolerance || 0)) {
- return done(new TokenExpiredError("jwt expired", new Date(payload.exp * 1000)));
- }
- }
- if (options2.audience) {
- const audiences = Array.isArray(options2.audience) ? options2.audience : [options2.audience];
- const target = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
- const match = target.some(function(targetAudience) {
- return audiences.some(function(audience) {
- return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience;
- });
- });
- if (!match) {
- return done(new JsonWebTokenError("jwt audience invalid. expected: " + audiences.join(" or ")));
- }
- }
- if (options2.issuer) {
- const invalid_issuer = typeof options2.issuer === "string" && payload.iss !== options2.issuer || Array.isArray(options2.issuer) && options2.issuer.indexOf(payload.iss) === -1;
- if (invalid_issuer) {
- return done(new JsonWebTokenError("jwt issuer invalid. expected: " + options2.issuer));
- }
- }
- if (options2.subject) {
- if (payload.sub !== options2.subject) {
- return done(new JsonWebTokenError("jwt subject invalid. expected: " + options2.subject));
- }
- }
- if (options2.jwtid) {
- if (payload.jti !== options2.jwtid) {
- return done(new JsonWebTokenError("jwt jwtid invalid. expected: " + options2.jwtid));
- }
- }
- if (options2.nonce) {
- if (payload.nonce !== options2.nonce) {
- return done(new JsonWebTokenError("jwt nonce invalid. expected: " + options2.nonce));
- }
- }
- if (options2.maxAge) {
- if (typeof payload.iat !== "number") {
- return done(new JsonWebTokenError("iat required when maxAge is specified"));
- }
- const maxAgeTimestamp = timespan(options2.maxAge, payload.iat);
- if (typeof maxAgeTimestamp === "undefined") {
- return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
- }
- if (clockTimestamp >= maxAgeTimestamp + (options2.clockTolerance || 0)) {
- return done(new TokenExpiredError("maxAge exceeded", new Date(maxAgeTimestamp * 1000)));
- }
- }
- if (options2.complete === true) {
- const signature7 = decodedToken.signature;
- return done(null, {
- header,
- payload,
- signature: signature7
- });
- }
- return done(null, payload);
- });
- };
-});
-
-// node_modules/lodash.includes/index.js
-var require_lodash = __commonJS((exports, module) => {
- var INFINITY4 = 1 / 0;
- var MAX_SAFE_INTEGER3 = 9007199254740991;
- var MAX_INTEGER = 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000;
- var NAN = 0 / 0;
- var argsTag5 = "[object Arguments]";
- var funcTag4 = "[object Function]";
- var genTag3 = "[object GeneratorFunction]";
- var stringTag5 = "[object String]";
- var symbolTag5 = "[object Symbol]";
- var reTrim = /^\s+|\s+$/g;
- var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
- var reIsBinary = /^0b[01]+$/i;
- var reIsOctal = /^0o[0-7]+$/i;
- var reIsUint2 = /^(?:0|[1-9]\d*)$/;
- var freeParseInt = parseInt;
- function arrayMap2(array2, iteratee) {
- var index2 = -1, length = array2 ? array2.length : 0, result = Array(length);
- while (++index2 < length) {
- result[index2] = iteratee(array2[index2], index2, array2);
- }
- return result;
- }
- function baseFindIndex2(array2, predicate, fromIndex, fromRight) {
- var length = array2.length, index2 = fromIndex + (fromRight ? 1 : -1);
- while (fromRight ? index2-- : ++index2 < length) {
- if (predicate(array2[index2], index2, array2)) {
- return index2;
- }
- }
- return -1;
- }
- function baseIndexOf2(array2, value, fromIndex) {
- if (value !== value) {
- return baseFindIndex2(array2, baseIsNaN2, fromIndex);
- }
- var index2 = fromIndex - 1, length = array2.length;
- while (++index2 < length) {
- if (array2[index2] === value) {
- return index2;
- }
- }
- return -1;
- }
- function baseIsNaN2(value) {
- return value !== value;
- }
- function baseTimes2(n5, iteratee) {
- var index2 = -1, result = Array(n5);
- while (++index2 < n5) {
- result[index2] = iteratee(index2);
- }
- return result;
- }
- function baseValues(object2, props) {
- return arrayMap2(props, function(key) {
- return object2[key];
- });
- }
- function overArg2(func, transform2) {
- return function(arg) {
- return func(transform2(arg));
- };
- }
- var objectProto17 = Object.prototype;
- var hasOwnProperty15 = objectProto17.hasOwnProperty;
- var objectToString4 = objectProto17.toString;
- var propertyIsEnumerable3 = objectProto17.propertyIsEnumerable;
- var nativeKeys2 = overArg2(Object.keys, Object);
- var nativeMax2 = Math.max;
- function arrayLikeKeys2(value, inherited) {
- var result = isArray7(value) || isArguments2(value) ? baseTimes2(value.length, String) : [];
- var length = result.length, skipIndexes = !!length;
- for (var key in value) {
- if ((inherited || hasOwnProperty15.call(value, key)) && !(skipIndexes && (key == "length" || isIndex2(key, length)))) {
- result.push(key);
- }
- }
- return result;
- }
- function baseKeys2(object2) {
- if (!isPrototype2(object2)) {
- return nativeKeys2(object2);
- }
- var result = [];
- for (var key in Object(object2)) {
- if (hasOwnProperty15.call(object2, key) && key != "constructor") {
- result.push(key);
- }
- }
- return result;
- }
- function isIndex2(value, length) {
- length = length == null ? MAX_SAFE_INTEGER3 : length;
- return !!length && (typeof value == "number" || reIsUint2.test(value)) && (value > -1 && value % 1 == 0 && value < length);
- }
- function isPrototype2(value) {
- var Ctor = value && value.constructor, proto2 = typeof Ctor == "function" && Ctor.prototype || objectProto17;
- return value === proto2;
- }
- function includes(collection, value, fromIndex, guard) {
- collection = isArrayLike2(collection) ? collection : values2(collection);
- fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0;
- var length = collection.length;
- if (fromIndex < 0) {
- fromIndex = nativeMax2(length + fromIndex, 0);
- }
- return isString2(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf2(collection, value, fromIndex) > -1;
- }
- function isArguments2(value) {
- return isArrayLikeObject2(value) && hasOwnProperty15.call(value, "callee") && (!propertyIsEnumerable3.call(value, "callee") || objectToString4.call(value) == argsTag5);
- }
- var isArray7 = Array.isArray;
- function isArrayLike2(value) {
- return value != null && isLength2(value.length) && !isFunction4(value);
- }
- function isArrayLikeObject2(value) {
- return isObjectLike2(value) && isArrayLike2(value);
- }
- function isFunction4(value) {
- var tag2 = isObject5(value) ? objectToString4.call(value) : "";
- return tag2 == funcTag4 || tag2 == genTag3;
- }
- function isLength2(value) {
- return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER3;
- }
- function isObject5(value) {
- var type = typeof value;
- return !!value && (type == "object" || type == "function");
- }
- function isObjectLike2(value) {
- return !!value && typeof value == "object";
- }
- function isString2(value) {
- return typeof value == "string" || !isArray7(value) && isObjectLike2(value) && objectToString4.call(value) == stringTag5;
- }
- function isSymbol2(value) {
- return typeof value == "symbol" || isObjectLike2(value) && objectToString4.call(value) == symbolTag5;
- }
- function toFinite(value) {
- if (!value) {
- return value === 0 ? value : 0;
- }
- value = toNumber(value);
- if (value === INFINITY4 || value === -INFINITY4) {
- var sign2 = value < 0 ? -1 : 1;
- return sign2 * MAX_INTEGER;
- }
- return value === value ? value : 0;
- }
- function toInteger(value) {
- var result = toFinite(value), remainder = result % 1;
- return result === result ? remainder ? result - remainder : result : 0;
- }
- function toNumber(value) {
- if (typeof value == "number") {
- return value;
- }
- if (isSymbol2(value)) {
- return NAN;
- }
- if (isObject5(value)) {
- var other2 = typeof value.valueOf == "function" ? value.valueOf() : value;
- value = isObject5(other2) ? other2 + "" : other2;
- }
- if (typeof value != "string") {
- return value === 0 ? value : +value;
- }
- value = value.replace(reTrim, "");
- var isBinary = reIsBinary.test(value);
- return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
- }
- function keys2(object2) {
- return isArrayLike2(object2) ? arrayLikeKeys2(object2) : baseKeys2(object2);
- }
- function values2(object2) {
- return object2 ? baseValues(object2, keys2(object2)) : [];
- }
- module.exports = includes;
-});
-
-// node_modules/lodash.isboolean/index.js
-var require_lodash2 = __commonJS((exports, module) => {
- var boolTag5 = "[object Boolean]";
- var objectProto17 = Object.prototype;
- var objectToString4 = objectProto17.toString;
- function isBoolean2(value) {
- return value === true || value === false || isObjectLike2(value) && objectToString4.call(value) == boolTag5;
- }
- function isObjectLike2(value) {
- return !!value && typeof value == "object";
- }
- module.exports = isBoolean2;
-});
-
-// node_modules/lodash.isinteger/index.js
-var require_lodash3 = __commonJS((exports, module) => {
- var INFINITY4 = 1 / 0;
- var MAX_INTEGER = 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000;
- var NAN = 0 / 0;
- var symbolTag5 = "[object Symbol]";
- var reTrim = /^\s+|\s+$/g;
- var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
- var reIsBinary = /^0b[01]+$/i;
- var reIsOctal = /^0o[0-7]+$/i;
- var freeParseInt = parseInt;
- var objectProto17 = Object.prototype;
- var objectToString4 = objectProto17.toString;
- function isInteger(value) {
- return typeof value == "number" && value == toInteger(value);
- }
- function isObject5(value) {
- var type = typeof value;
- return !!value && (type == "object" || type == "function");
- }
- function isObjectLike2(value) {
- return !!value && typeof value == "object";
- }
- function isSymbol2(value) {
- return typeof value == "symbol" || isObjectLike2(value) && objectToString4.call(value) == symbolTag5;
- }
- function toFinite(value) {
- if (!value) {
- return value === 0 ? value : 0;
- }
- value = toNumber(value);
- if (value === INFINITY4 || value === -INFINITY4) {
- var sign2 = value < 0 ? -1 : 1;
- return sign2 * MAX_INTEGER;
- }
- return value === value ? value : 0;
- }
- function toInteger(value) {
- var result = toFinite(value), remainder = result % 1;
- return result === result ? remainder ? result - remainder : result : 0;
- }
- function toNumber(value) {
- if (typeof value == "number") {
- return value;
- }
- if (isSymbol2(value)) {
- return NAN;
- }
- if (isObject5(value)) {
- var other2 = typeof value.valueOf == "function" ? value.valueOf() : value;
- value = isObject5(other2) ? other2 + "" : other2;
- }
- if (typeof value != "string") {
- return value === 0 ? value : +value;
- }
- value = value.replace(reTrim, "");
- var isBinary = reIsBinary.test(value);
- return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
- }
- module.exports = isInteger;
-});
-
-// node_modules/lodash.isnumber/index.js
-var require_lodash4 = __commonJS((exports, module) => {
- var numberTag5 = "[object Number]";
- var objectProto17 = Object.prototype;
- var objectToString4 = objectProto17.toString;
- function isObjectLike2(value) {
- return !!value && typeof value == "object";
- }
- function isNumber2(value) {
- return typeof value == "number" || isObjectLike2(value) && objectToString4.call(value) == numberTag5;
- }
- module.exports = isNumber2;
-});
-
-// node_modules/lodash.isplainobject/index.js
-var require_lodash5 = __commonJS((exports, module) => {
- var objectTag6 = "[object Object]";
- function isHostObject(value) {
- var result = false;
- if (value != null && typeof value.toString != "function") {
- try {
- result = !!(value + "");
- } catch (e4) {}
- }
- return result;
- }
- function overArg2(func, transform2) {
- return function(arg) {
- return func(transform2(arg));
- };
- }
- var funcProto4 = Function.prototype;
- var objectProto17 = Object.prototype;
- var funcToString4 = funcProto4.toString;
- var hasOwnProperty15 = objectProto17.hasOwnProperty;
- var objectCtorString2 = funcToString4.call(Object);
- var objectToString4 = objectProto17.toString;
- var getPrototype2 = overArg2(Object.getPrototypeOf, Object);
- function isObjectLike2(value) {
- return !!value && typeof value == "object";
- }
- function isPlainObject5(value) {
- if (!isObjectLike2(value) || objectToString4.call(value) != objectTag6 || isHostObject(value)) {
- return false;
- }
- var proto2 = getPrototype2(value);
- if (proto2 === null) {
- return true;
- }
- var Ctor = hasOwnProperty15.call(proto2, "constructor") && proto2.constructor;
- return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString4.call(Ctor) == objectCtorString2;
- }
- module.exports = isPlainObject5;
-});
-
-// node_modules/lodash.isstring/index.js
-var require_lodash6 = __commonJS((exports, module) => {
- var stringTag5 = "[object String]";
- var objectProto17 = Object.prototype;
- var objectToString4 = objectProto17.toString;
- var isArray7 = Array.isArray;
- function isObjectLike2(value) {
- return !!value && typeof value == "object";
- }
- function isString2(value) {
- return typeof value == "string" || !isArray7(value) && isObjectLike2(value) && objectToString4.call(value) == stringTag5;
- }
- module.exports = isString2;
-});
-
-// node_modules/lodash.once/index.js
-var require_lodash7 = __commonJS((exports, module) => {
- var FUNC_ERROR_TEXT2 = "Expected a function";
- var INFINITY4 = 1 / 0;
- var MAX_INTEGER = 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000;
- var NAN = 0 / 0;
- var symbolTag5 = "[object Symbol]";
- var reTrim = /^\s+|\s+$/g;
- var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
- var reIsBinary = /^0b[01]+$/i;
- var reIsOctal = /^0o[0-7]+$/i;
- var freeParseInt = parseInt;
- var objectProto17 = Object.prototype;
- var objectToString4 = objectProto17.toString;
- function before(n5, func) {
- var result;
- if (typeof func != "function") {
- throw new TypeError(FUNC_ERROR_TEXT2);
- }
- n5 = toInteger(n5);
- return function() {
- if (--n5 > 0) {
- result = func.apply(this, arguments);
- }
- if (n5 <= 1) {
- func = undefined;
- }
- return result;
- };
- }
- function once9(func) {
- return before(2, func);
- }
- function isObject5(value) {
- var type = typeof value;
- return !!value && (type == "object" || type == "function");
- }
- function isObjectLike2(value) {
- return !!value && typeof value == "object";
- }
- function isSymbol2(value) {
- return typeof value == "symbol" || isObjectLike2(value) && objectToString4.call(value) == symbolTag5;
- }
- function toFinite(value) {
- if (!value) {
- return value === 0 ? value : 0;
- }
- value = toNumber(value);
- if (value === INFINITY4 || value === -INFINITY4) {
- var sign2 = value < 0 ? -1 : 1;
- return sign2 * MAX_INTEGER;
- }
- return value === value ? value : 0;
- }
- function toInteger(value) {
- var result = toFinite(value), remainder = result % 1;
- return result === result ? remainder ? result - remainder : result : 0;
- }
- function toNumber(value) {
- if (typeof value == "number") {
- return value;
- }
- if (isSymbol2(value)) {
- return NAN;
- }
- if (isObject5(value)) {
- var other2 = typeof value.valueOf == "function" ? value.valueOf() : value;
- value = isObject5(other2) ? other2 + "" : other2;
- }
- if (typeof value != "string") {
- return value === 0 ? value : +value;
- }
- value = value.replace(reTrim, "");
- var isBinary = reIsBinary.test(value);
- return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
- }
- module.exports = once9;
-});
-
-// node_modules/jsonwebtoken/sign.js
-var require_sign2 = __commonJS((exports, module) => {
- var timespan = require_timespan();
- var PS_SUPPORTED = require_psSupported();
- var validateAsymmetricKey = require_validateAsymmetricKey();
- var jws = require_jws();
- var includes = require_lodash();
- var isBoolean2 = require_lodash2();
- var isInteger = require_lodash3();
- var isNumber2 = require_lodash4();
- var isPlainObject5 = require_lodash5();
- var isString2 = require_lodash6();
- var once9 = require_lodash7();
- var { KeyObject, createSecretKey, createPrivateKey: createPrivateKey2 } = __require("crypto");
- var SUPPORTED_ALGS = ["RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "HS256", "HS384", "HS512", "none"];
- if (PS_SUPPORTED) {
- SUPPORTED_ALGS.splice(3, 0, "PS256", "PS384", "PS512");
- }
- var sign_options_schema = {
- expiresIn: { isValid: function(value) {
- return isInteger(value) || isString2(value) && value;
- }, message: '"expiresIn" should be a number of seconds or string representing a timespan' },
- notBefore: { isValid: function(value) {
- return isInteger(value) || isString2(value) && value;
- }, message: '"notBefore" should be a number of seconds or string representing a timespan' },
- audience: { isValid: function(value) {
- return isString2(value) || Array.isArray(value);
- }, message: '"audience" must be a string or array' },
- algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' },
- header: { isValid: isPlainObject5, message: '"header" must be an object' },
- encoding: { isValid: isString2, message: '"encoding" must be a string' },
- issuer: { isValid: isString2, message: '"issuer" must be a string' },
- subject: { isValid: isString2, message: '"subject" must be a string' },
- jwtid: { isValid: isString2, message: '"jwtid" must be a string' },
- noTimestamp: { isValid: isBoolean2, message: '"noTimestamp" must be a boolean' },
- keyid: { isValid: isString2, message: '"keyid" must be a string' },
- mutatePayload: { isValid: isBoolean2, message: '"mutatePayload" must be a boolean' },
- allowInsecureKeySizes: { isValid: isBoolean2, message: '"allowInsecureKeySizes" must be a boolean' },
- allowInvalidAsymmetricKeyTypes: { isValid: isBoolean2, message: '"allowInvalidAsymmetricKeyTypes" must be a boolean' }
- };
- var registered_claims_schema = {
- iat: { isValid: isNumber2, message: '"iat" should be a number of seconds' },
- exp: { isValid: isNumber2, message: '"exp" should be a number of seconds' },
- nbf: { isValid: isNumber2, message: '"nbf" should be a number of seconds' }
- };
- function validate3(schema5, allowUnknown, object2, parameterName) {
- if (!isPlainObject5(object2)) {
- throw new Error('Expected "' + parameterName + '" to be a plain object.');
- }
- Object.keys(object2).forEach(function(key) {
- const validator = schema5[key];
- if (!validator) {
- if (!allowUnknown) {
- throw new Error('"' + key + '" is not allowed in "' + parameterName + '"');
- }
- return;
- }
- if (!validator.isValid(object2[key])) {
- throw new Error(validator.message);
- }
- });
- }
- function validateOptions(options2) {
- return validate3(sign_options_schema, false, options2, "options");
- }
- function validatePayload(payload) {
- return validate3(registered_claims_schema, true, payload, "payload");
- }
- var options_to_payload = {
- audience: "aud",
- issuer: "iss",
- subject: "sub",
- jwtid: "jti"
- };
- var options_for_objects = [
- "expiresIn",
- "notBefore",
- "noTimestamp",
- "audience",
- "issuer",
- "subject",
- "jwtid"
- ];
- module.exports = function(payload, secretOrPrivateKey, options2, callback) {
- if (typeof options2 === "function") {
- callback = options2;
- options2 = {};
- } else {
- options2 = options2 || {};
- }
- const isObjectPayload = typeof payload === "object" && !Buffer.isBuffer(payload);
- const header = Object.assign({
- alg: options2.algorithm || "HS256",
- typ: isObjectPayload ? "JWT" : undefined,
- kid: options2.keyid
- }, options2.header);
- function failure(err) {
- if (callback) {
- return callback(err);
- }
- throw err;
- }
- if (!secretOrPrivateKey && options2.algorithm !== "none") {
- return failure(new Error("secretOrPrivateKey must have a value"));
- }
- if (secretOrPrivateKey != null && !(secretOrPrivateKey instanceof KeyObject)) {
- try {
- secretOrPrivateKey = createPrivateKey2(secretOrPrivateKey);
- } catch (_) {
- try {
- secretOrPrivateKey = createSecretKey(typeof secretOrPrivateKey === "string" ? Buffer.from(secretOrPrivateKey) : secretOrPrivateKey);
- } catch (_2) {
- return failure(new Error("secretOrPrivateKey is not valid key material"));
- }
- }
- }
- if (header.alg.startsWith("HS") && secretOrPrivateKey.type !== "secret") {
- return failure(new Error(`secretOrPrivateKey must be a symmetric key when using ${header.alg}`));
- } else if (/^(?:RS|PS|ES)/.test(header.alg)) {
- if (secretOrPrivateKey.type !== "private") {
- return failure(new Error(`secretOrPrivateKey must be an asymmetric key when using ${header.alg}`));
- }
- if (!options2.allowInsecureKeySizes && !header.alg.startsWith("ES") && secretOrPrivateKey.asymmetricKeyDetails !== undefined && secretOrPrivateKey.asymmetricKeyDetails.modulusLength < 2048) {
- return failure(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`));
- }
- }
- if (typeof payload === "undefined") {
- return failure(new Error("payload is required"));
- } else if (isObjectPayload) {
- try {
- validatePayload(payload);
- } catch (error44) {
- return failure(error44);
- }
- if (!options2.mutatePayload) {
- payload = Object.assign({}, payload);
- }
- } else {
- const invalid_options = options_for_objects.filter(function(opt) {
- return typeof options2[opt] !== "undefined";
- });
- if (invalid_options.length > 0) {
- return failure(new Error("invalid " + invalid_options.join(",") + " option for " + typeof payload + " payload"));
- }
- }
- if (typeof payload.exp !== "undefined" && typeof options2.expiresIn !== "undefined") {
- return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));
- }
- if (typeof payload.nbf !== "undefined" && typeof options2.notBefore !== "undefined") {
- return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));
- }
- try {
- validateOptions(options2);
- } catch (error44) {
- return failure(error44);
- }
- if (!options2.allowInvalidAsymmetricKeyTypes) {
- try {
- validateAsymmetricKey(header.alg, secretOrPrivateKey);
- } catch (error44) {
- return failure(error44);
- }
- }
- const timestamp = payload.iat || Math.floor(Date.now() / 1000);
- if (options2.noTimestamp) {
- delete payload.iat;
- } else if (isObjectPayload) {
- payload.iat = timestamp;
- }
- if (typeof options2.notBefore !== "undefined") {
- try {
- payload.nbf = timespan(options2.notBefore, timestamp);
- } catch (err) {
- return failure(err);
- }
- if (typeof payload.nbf === "undefined") {
- return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
- }
- }
- if (typeof options2.expiresIn !== "undefined" && typeof payload === "object") {
- try {
- payload.exp = timespan(options2.expiresIn, timestamp);
- } catch (err) {
- return failure(err);
- }
- if (typeof payload.exp === "undefined") {
- return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
- }
- }
- Object.keys(options_to_payload).forEach(function(key) {
- const claim = options_to_payload[key];
- if (typeof options2[key] !== "undefined") {
- if (typeof payload[claim] !== "undefined") {
- return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.'));
- }
- payload[claim] = options2[key];
- }
- });
- const encoding = options2.encoding || "utf8";
- if (typeof callback === "function") {
- callback = callback && once9(callback);
- jws.createSign({
- header,
- privateKey: secretOrPrivateKey,
- payload,
- encoding
- }).once("error", callback).once("done", function(signature7) {
- if (!options2.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature7.length < 256) {
- return callback(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`));
- }
- callback(null, signature7);
- });
- } else {
- let signature7 = jws.sign({ header, payload, secret: secretOrPrivateKey, encoding });
- if (!options2.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature7.length < 256) {
- throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`);
- }
- return signature7;
- }
- };
-});
-
-// node_modules/jsonwebtoken/index.js
-var require_jsonwebtoken = __commonJS((exports, module) => {
- module.exports = {
- decode: require_decode(),
- verify: require_verify(),
- sign: require_sign2(),
- JsonWebTokenError: require_JsonWebTokenError(),
- NotBeforeError: require_NotBeforeError(),
- TokenExpiredError: require_TokenExpiredError()
- };
-});
-
-// node_modules/@azure/msal-node/dist/error/ClientAuthErrorCodes.mjs
-var missingTenantIdError = "missing_tenant_id_error", userTimeoutReached = "user_timeout_reached", invalidAssertion = "invalid_assertion", invalidClientCredential = "invalid_client_credential", deviceCodePollingCancelled = "device_code_polling_cancelled", deviceCodeExpired = "device_code_expired", deviceCodeUnknownError = "device_code_unknown_error";
-var init_ClientAuthErrorCodes2 = __esm(() => {
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/client/ClientAssertion.mjs
-class ClientAssertion {
- static fromAssertion(assertion) {
- const clientAssertion = new ClientAssertion;
- clientAssertion.jwt = assertion;
- return clientAssertion;
- }
- static fromCertificate(thumbprint, privateKey, publicCertificate) {
- const clientAssertion = new ClientAssertion;
- clientAssertion.privateKey = privateKey;
- clientAssertion.thumbprint = thumbprint;
- clientAssertion.useSha256 = false;
- if (publicCertificate) {
- clientAssertion.publicCertificate = this.parseCertificate(publicCertificate);
- }
- return clientAssertion;
- }
- static fromCertificateWithSha256Thumbprint(thumbprint, privateKey, publicCertificate) {
- const clientAssertion = new ClientAssertion;
- clientAssertion.privateKey = privateKey;
- clientAssertion.thumbprint = thumbprint;
- clientAssertion.useSha256 = true;
- if (publicCertificate) {
- clientAssertion.publicCertificate = this.parseCertificate(publicCertificate);
- }
- return clientAssertion;
- }
- getJwt(cryptoProvider, issuer, jwtAudience) {
- if (this.privateKey && this.thumbprint) {
- if (this.jwt && !this.isExpired() && issuer === this.issuer && jwtAudience === this.jwtAudience) {
- return this.jwt;
- }
- return this.createJwt(cryptoProvider, issuer, jwtAudience);
- }
- if (this.jwt) {
- return this.jwt;
- }
- throw createClientAuthError(invalidAssertion);
- }
- createJwt(cryptoProvider, issuer, jwtAudience) {
- this.issuer = issuer;
- this.jwtAudience = jwtAudience;
- const issuedAt = exports_TimeUtils.nowSeconds();
- this.expirationTime = issuedAt + 600;
- const algorithm = this.useSha256 ? JwtConstants.PSS_256 : JwtConstants.RSA_256;
- const header = {
- alg: algorithm
- };
- const thumbprintHeader = this.useSha256 ? JwtConstants.X5T_256 : JwtConstants.X5T;
- Object.assign(header, {
- [thumbprintHeader]: EncodingUtils.base64EncodeUrl(this.thumbprint, exports_Constants.EncodingTypes.HEX)
- });
- if (this.publicCertificate) {
- Object.assign(header, {
- [JwtConstants.X5C]: this.publicCertificate
- });
- }
- const payload = {
- [JwtConstants.AUDIENCE]: this.jwtAudience,
- [JwtConstants.EXPIRATION_TIME]: this.expirationTime,
- [JwtConstants.ISSUER]: this.issuer,
- [JwtConstants.SUBJECT]: this.issuer,
- [JwtConstants.NOT_BEFORE]: issuedAt,
- [JwtConstants.JWT_ID]: cryptoProvider.createNewGuid()
- };
- this.jwt = import_jsonwebtoken.default.sign(payload, this.privateKey, { header });
- return this.jwt;
- }
- isExpired() {
- return this.expirationTime < exports_TimeUtils.nowSeconds();
- }
- static parseCertificate(publicCertificate) {
- const regexToFindCerts = /-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs;
- const certs = [];
- let matches;
- while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) {
- certs.push(matches[1].replace(/\r*\n/g, ""));
- }
- return certs;
- }
-}
-var import_jsonwebtoken;
-var init_ClientAssertion = __esm(() => {
- init_index_node();
- init_EncodingUtils();
- init_Constants2();
- init_ClientAuthErrorCodes2();
- import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1);
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/packageMetadata.mjs
-var name2 = "@azure/msal-node", version5 = "5.1.1";
-var init_packageMetadata2 = __esm(() => {
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/client/BaseClient.mjs
-class BaseClient {
- constructor(configuration) {
- this.config = buildClientConfiguration(configuration);
- this.logger = new Logger(this.config.loggerOptions, name2, version5);
- this.cryptoUtils = this.config.cryptoInterface;
- this.cacheManager = this.config.storageInterface;
- this.networkClient = this.config.networkInterface;
- this.serverTelemetryManager = this.config.serverTelemetryManager;
- this.authority = this.config.authOptions.authority;
- this.performanceClient = new StubPerformanceClient;
- }
- createTokenRequestHeaders(ccsCred) {
- return exports_Token.createTokenRequestHeaders(this.logger, false, ccsCred);
- }
- async executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId) {
- return exports_Token.executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, this.serverTelemetryManager);
- }
- async sendPostRequest(thumbprint, tokenEndpoint, options2, correlationId) {
- return exports_Token.sendPostRequest(thumbprint, tokenEndpoint, options2, correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient);
- }
- createTokenQueryParameters(request2) {
- return exports_Token.createTokenQueryParameters(request2, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);
- }
-}
-var init_BaseClient = __esm(() => {
- init_index_node();
- init_packageMetadata2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/client/UsernamePasswordClient.mjs
-var UsernamePasswordClient;
-var init_UsernamePasswordClient = __esm(() => {
- init_index_node();
- init_Constants2();
- init_BaseClient();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- UsernamePasswordClient = class UsernamePasswordClient extends BaseClient {
- constructor(configuration) {
- super(configuration);
- }
- async acquireToken(request2) {
- this.logger.info("in acquireToken call in username-password client", request2.correlationId);
- const reqTimestamp = exports_TimeUtils.nowSeconds();
- const response7 = await this.executeTokenRequest(this.authority, request2);
- const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
- responseHandler.validateTokenResponse(response7.body, request2.correlationId);
- const tokenResponse = responseHandler.handleServerTokenResponse(response7.body, this.authority, reqTimestamp, request2, ApiId.acquireTokenByUsernamePassword);
- return tokenResponse;
- }
- async executeTokenRequest(authority, request2) {
- const queryParametersString = this.createTokenQueryParameters(request2);
- const endpoint7 = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
- const requestBody = await this.createTokenRequestBody(request2);
- const headers = this.createTokenRequestHeaders({
- credential: request2.username,
- type: CcsCredentialType.UPN
- });
- const thumbprint = {
- clientId: this.config.authOptions.clientId,
- authority: authority.canonicalAuthority,
- scopes: request2.scopes,
- claims: request2.claims,
- authenticationScheme: request2.authenticationScheme,
- resourceRequestMethod: request2.resourceRequestMethod,
- resourceRequestUri: request2.resourceRequestUri,
- shrClaims: request2.shrClaims,
- sshKid: request2.sshKid
- };
- return this.executePostToTokenEndpoint(endpoint7, requestBody, headers, thumbprint, request2.correlationId);
- }
- async createTokenRequestBody(request2) {
- const parameters = new Map;
- exports_RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId);
- exports_RequestParameterBuilder.addUsername(parameters, request2.username);
- exports_RequestParameterBuilder.addPassword(parameters, request2.password);
- exports_RequestParameterBuilder.addScopes(parameters, request2.scopes);
- exports_RequestParameterBuilder.addResponseType(parameters, exports_Constants.OAuthResponseType.IDTOKEN_TOKEN);
- exports_RequestParameterBuilder.addGrantType(parameters, exports_Constants.GrantType.RESOURCE_OWNER_PASSWORD_GRANT);
- exports_RequestParameterBuilder.addClientInfo(parameters);
- exports_RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo);
- exports_RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application);
- exports_RequestParameterBuilder.addThrottling(parameters);
- if (this.serverTelemetryManager) {
- exports_RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager);
- }
- const correlationId = request2.correlationId || this.config.cryptoInterface.createNewGuid();
- exports_RequestParameterBuilder.addCorrelationId(parameters, correlationId);
- if (this.config.clientCredentials.clientSecret) {
- exports_RequestParameterBuilder.addClientSecret(parameters, this.config.clientCredentials.clientSecret);
- }
- const clientAssertion = this.config.clientCredentials.clientAssertion;
- if (clientAssertion) {
- exports_RequestParameterBuilder.addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request2.resourceRequestUri));
- exports_RequestParameterBuilder.addClientAssertionType(parameters, clientAssertion.assertionType);
- }
- if (!StringUtils.isEmptyObj(request2.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
- exports_RequestParameterBuilder.addClaims(parameters, request2.claims, this.config.authOptions.clientCapabilities);
- }
- if (this.config.systemOptions.preventCorsPreflight && request2.username) {
- exports_RequestParameterBuilder.addCcsUpn(parameters, request2.username);
- }
- return exports_UrlUtils.mapToQueryString(parameters);
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/protocol/Authorize.mjs
-function getAuthCodeRequestUrl(config8, authority, request2, logger10) {
- const parameters = exports_Authorize.getStandardAuthorizeRequestParameters({
- ...config8.auth,
- authority,
- redirectUri: request2.redirectUri || ""
- }, request2, logger10);
- exports_RequestParameterBuilder.addLibraryInfo(parameters, {
- sku: Constants.MSAL_SKU,
- version: version5,
- cpu: process.arch || "",
- os: process.platform || ""
- });
- if (config8.system.protocolMode !== ProtocolMode.OIDC) {
- exports_RequestParameterBuilder.addApplicationTelemetry(parameters, config8.telemetry.application);
- }
- exports_RequestParameterBuilder.addResponseType(parameters, exports_Constants.OAuthResponseType.CODE);
- if (request2.codeChallenge && request2.codeChallengeMethod) {
- exports_RequestParameterBuilder.addCodeChallengeParams(parameters, request2.codeChallenge, request2.codeChallengeMethod);
- }
- exports_RequestParameterBuilder.addExtraParameters(parameters, request2.extraQueryParameters || {});
- return exports_Authorize.getAuthorizeUrl(authority, parameters);
-}
-var init_Authorize2 = __esm(() => {
- init_index_node();
- init_Constants2();
- init_packageMetadata2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/client/ClientApplication.mjs
-class ClientApplication {
- constructor(configuration) {
- this.config = buildAppConfiguration(configuration);
- this.cryptoProvider = new CryptoProvider;
- this.logger = new Logger(this.config.system.loggerOptions, name2, version5);
- this.storage = new NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider, buildStaticAuthorityOptions(this.config.auth));
- this.tokenCache = new TokenCache(this.storage, this.logger, this.config.cache.cachePlugin);
- }
- async getAuthCodeUrl(request2) {
- this.logger.info("getAuthCodeUrl called", request2.correlationId || "");
- const validRequest = {
- ...request2,
- ...await this.initializeBaseRequest(request2),
- responseMode: request2.responseMode || exports_Constants.ResponseMode.QUERY,
- authenticationScheme: exports_Constants.AuthenticationScheme.BEARER,
- state: request2.state || "",
- nonce: request2.nonce || ""
- };
- const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request2.azureCloudOptions);
- return getAuthCodeRequestUrl(this.config, discoveredAuthority, validRequest, this.logger);
- }
- async acquireTokenByCode(request2, authCodePayLoad) {
- this.logger.info("acquireTokenByCode called", request2.correlationId || "");
- if (request2.state && authCodePayLoad) {
- this.logger.info("acquireTokenByCode - validating state", request2.correlationId || "");
- this.validateState(request2.state, authCodePayLoad.state || "");
- authCodePayLoad = { ...authCodePayLoad, state: "" };
- }
- const validRequest = {
- ...request2,
- ...await this.initializeBaseRequest(request2),
- authenticationScheme: exports_Constants.AuthenticationScheme.BEARER
- };
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByCode, validRequest.correlationId);
- try {
- const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request2.azureCloudOptions);
- const authClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri, serverTelemetryManager);
- const authorizationCodeClient = new AuthorizationCodeClient(authClientConfig, new StubPerformanceClient);
- this.logger.verbose("Auth code client created", validRequest.correlationId);
- return await authorizationCodeClient.acquireToken(validRequest, ApiId.acquireTokenByCode, authCodePayLoad);
- } catch (e4) {
- if (e4 instanceof AuthError) {
- e4.setCorrelationId(validRequest.correlationId);
- }
- serverTelemetryManager.cacheFailedRequest(e4);
- throw e4;
- }
- }
- async acquireTokenByRefreshToken(request2) {
- this.logger.info("acquireTokenByRefreshToken called", request2.correlationId || "");
- const validRequest = {
- ...request2,
- ...await this.initializeBaseRequest(request2),
- authenticationScheme: exports_Constants.AuthenticationScheme.BEARER
- };
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByRefreshToken, validRequest.correlationId);
- try {
- const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request2.azureCloudOptions);
- const refreshTokenClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager);
- const refreshTokenClient = new RefreshTokenClient(refreshTokenClientConfig, new StubPerformanceClient);
- this.logger.verbose("Refresh token client created", validRequest.correlationId);
- return await refreshTokenClient.acquireToken(validRequest, ApiId.acquireTokenByRefreshToken);
- } catch (e4) {
- if (e4 instanceof AuthError) {
- e4.setCorrelationId(validRequest.correlationId);
- }
- serverTelemetryManager.cacheFailedRequest(e4);
- throw e4;
- }
- }
- async acquireTokenSilent(request2) {
- const validRequest = {
- ...request2,
- ...await this.initializeBaseRequest(request2),
- forceRefresh: request2.forceRefresh || false
- };
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh);
- try {
- const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request2.azureCloudOptions);
- const clientConfiguration = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager);
- const silentFlowClient = new SilentFlowClient(clientConfiguration, new StubPerformanceClient);
- this.logger.verbose("Silent flow client created", validRequest.correlationId);
- try {
- await this.tokenCache.overwriteCache();
- return await this.acquireCachedTokenSilent(validRequest, silentFlowClient, clientConfiguration);
- } catch (error44) {
- if (error44 instanceof ClientAuthError && error44.errorCode === exports_ClientAuthErrorCodes.tokenRefreshRequired) {
- const refreshTokenClient = new RefreshTokenClient(clientConfiguration, new StubPerformanceClient);
- return refreshTokenClient.acquireTokenByRefreshToken(validRequest, ApiId.acquireTokenSilent);
- }
- throw error44;
- }
- } catch (error44) {
- if (error44 instanceof AuthError) {
- error44.setCorrelationId(validRequest.correlationId);
- }
- serverTelemetryManager.cacheFailedRequest(error44);
- throw error44;
- }
- }
- async acquireCachedTokenSilent(validRequest, silentFlowClient, clientConfiguration) {
- const [authResponse, cacheOutcome] = await silentFlowClient.acquireCachedToken({
- ...validRequest,
- scopes: validRequest.scopes?.length ? validRequest.scopes : [...exports_Constants.OIDC_DEFAULT_SCOPES]
- });
- if (cacheOutcome === exports_Constants.CacheOutcome.PROACTIVELY_REFRESHED) {
- this.logger.info("ClientApplication:acquireCachedTokenSilent - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.", validRequest.correlationId);
- const refreshTokenClient = new RefreshTokenClient(clientConfiguration, new StubPerformanceClient);
- try {
- await refreshTokenClient.acquireTokenByRefreshToken(validRequest, ApiId.acquireTokenSilent);
- } catch {}
- }
- return authResponse;
- }
- async acquireTokenByUsernamePassword(request2) {
- this.logger.info("acquireTokenByUsernamePassword called", request2.correlationId || "");
- const validRequest = {
- ...request2,
- ...await this.initializeBaseRequest(request2)
- };
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByUsernamePassword, validRequest.correlationId);
- try {
- const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request2.azureCloudOptions);
- const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager);
- const usernamePasswordClient = new UsernamePasswordClient(usernamePasswordClientConfig);
- this.logger.verbose("Username password client created", validRequest.correlationId);
- return await usernamePasswordClient.acquireToken(validRequest);
- } catch (e4) {
- if (e4 instanceof AuthError) {
- e4.setCorrelationId(validRequest.correlationId);
- }
- serverTelemetryManager.cacheFailedRequest(e4);
- throw e4;
- }
- }
- getTokenCache() {
- this.logger.info("getTokenCache called", "");
- return this.tokenCache;
- }
- validateState(state2, cachedState) {
- if (!state2) {
- throw NodeAuthError.createStateNotFoundError();
- }
- if (state2 !== cachedState) {
- throw createClientAuthError(exports_ClientAuthErrorCodes.stateMismatch);
- }
- }
- getLogger() {
- return this.logger;
- }
- setLogger(logger10) {
- this.logger = logger10;
- }
- async buildOauthClientConfiguration(discoveredAuthority, requestCorrelationId, redirectUri, serverTelemetryManager) {
- this.logger.verbose("buildOauthClientConfiguration called", requestCorrelationId);
- this.logger.info(`Building oauth client configuration with the following authority: ${discoveredAuthority.tokenEndpoint}.`, requestCorrelationId);
- serverTelemetryManager?.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);
- const clientConfiguration = {
- authOptions: {
- clientId: this.config.auth.clientId,
- authority: discoveredAuthority,
- clientCapabilities: this.config.auth.clientCapabilities,
- redirectUri,
- isMcp: this.config.auth.isMcp
- },
- loggerOptions: {
- logLevel: this.config.system.loggerOptions.logLevel,
- loggerCallback: this.config.system.loggerOptions.loggerCallback,
- piiLoggingEnabled: this.config.system.loggerOptions.piiLoggingEnabled,
- correlationId: requestCorrelationId
- },
- cryptoInterface: this.cryptoProvider,
- networkInterface: this.config.system.networkClient,
- storageInterface: this.storage,
- serverTelemetryManager,
- clientCredentials: {
- clientSecret: this.clientSecret,
- clientAssertion: await this.getClientAssertion(discoveredAuthority)
- },
- libraryInfo: {
- sku: Constants.MSAL_SKU,
- version: version5,
- cpu: process.arch || "",
- os: process.platform || ""
- },
- telemetry: this.config.telemetry,
- persistencePlugin: this.config.cache.cachePlugin,
- serializableCache: this.tokenCache
- };
- return clientConfiguration;
- }
- async getClientAssertion(authority) {
- if (this.developerProvidedClientAssertion) {
- this.clientAssertion = ClientAssertion.fromAssertion(await getClientAssertion(this.developerProvidedClientAssertion, this.config.auth.clientId, authority.tokenEndpoint));
- }
- return this.clientAssertion && {
- assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint),
- assertionType: Constants.JWT_BEARER_ASSERTION_TYPE
- };
- }
- async initializeBaseRequest(authRequest) {
- const correlationId = authRequest.correlationId || this.cryptoProvider.createNewGuid();
- this.logger.verbose("initializeRequestScopes called", correlationId);
- if (authRequest.authenticationScheme && authRequest.authenticationScheme === exports_Constants.AuthenticationScheme.POP) {
- this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request", correlationId);
- }
- authRequest.authenticationScheme = exports_Constants.AuthenticationScheme.BEARER;
- return {
- ...authRequest,
- scopes: [
- ...authRequest && authRequest.scopes || [],
- ...exports_Constants.OIDC_DEFAULT_SCOPES
- ],
- correlationId,
- authority: authRequest.authority || this.config.auth.authority
- };
- }
- initializeServerTelemetryManager(apiId, correlationId, forceRefresh) {
- const telemetryPayload = {
- clientId: this.config.auth.clientId,
- correlationId,
- apiId,
- forceRefresh: forceRefresh || false
- };
- return new ServerTelemetryManager(telemetryPayload, this.storage);
- }
- async createAuthority(authorityString, requestCorrelationId, azureRegionConfiguration, azureCloudOptions) {
- this.logger.verbose("createAuthority called", requestCorrelationId);
- const authorityUrl = Authority.generateAuthority(authorityString, azureCloudOptions || this.config.auth.azureCloudOptions);
- const authorityOptions = {
- protocolMode: this.config.system.protocolMode,
- knownAuthorities: this.config.auth.knownAuthorities,
- cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,
- authorityMetadata: this.config.auth.authorityMetadata,
- azureRegionConfiguration
- };
- return exports_AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger, requestCorrelationId, new StubPerformanceClient);
- }
- clearCache() {
- this.storage.clear();
- }
-}
-var init_ClientApplication = __esm(() => {
- init_index_node();
- init_Configuration();
- init_CryptoProvider();
- init_NodeStorage();
- init_Constants2();
- init_TokenCache();
- init_ClientAssertion();
- init_packageMetadata2();
- init_NodeAuthError();
- init_UsernamePasswordClient();
- init_Authorize2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/network/LoopbackClient.mjs
-import http10 from "http";
-
-class LoopbackClient {
- async listenForAuthCode(successTemplate, errorTemplate) {
- if (this.server) {
- throw NodeAuthError.createLoopbackServerAlreadyExistsError();
- }
- return new Promise((resolve9, reject) => {
- this.server = http10.createServer((req, res) => {
- const url3 = req.url;
- if (!url3) {
- res.end(errorTemplate || "Error occurred loading redirectUrl");
- reject(NodeAuthError.createUnableToLoadRedirectUrlError());
- return;
- } else if (url3 === exports_Constants.FORWARD_SLASH) {
- res.end(successTemplate || "Auth code was successfully acquired. You can close this window now.");
- return;
- }
- const redirectUri = this.getRedirectUri();
- const parsedUrl = new URL(url3, redirectUri);
- const authCodeResponse = exports_UrlUtils.getDeserializedResponse(parsedUrl.search) || {};
- if (authCodeResponse.code) {
- res.writeHead(exports_Constants.HTTP_REDIRECT, {
- location: redirectUri
- });
- res.end();
- }
- if (authCodeResponse.error) {
- res.end(errorTemplate || `Error occurred: ${authCodeResponse.error}`);
- }
- resolve9(authCodeResponse);
- });
- this.server.listen(0, "127.0.0.1");
- });
- }
- getRedirectUri() {
- if (!this.server || !this.server.listening) {
- throw NodeAuthError.createNoLoopbackServerExistsError();
- }
- const address = this.server.address();
- if (!address || typeof address === "string" || !address.port) {
- this.closeServer();
- throw NodeAuthError.createInvalidLoopbackAddressTypeError();
- }
- const port = address && address.port;
- return `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}:${port}`;
- }
- closeServer() {
- if (this.server) {
- this.server.close();
- if (typeof this.server.closeAllConnections === "function") {
- this.server.closeAllConnections();
- }
- this.server.unref();
- this.server = undefined;
- }
- }
-}
-var init_LoopbackClient = __esm(() => {
- init_index_node();
- init_NodeAuthError();
- init_Constants2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/client/DeviceCodeClient.mjs
-var DeviceCodeClient;
-var init_DeviceCodeClient = __esm(() => {
- init_index_node();
- init_Constants2();
- init_ClientAuthErrorCodes2();
- init_BaseClient();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- DeviceCodeClient = class DeviceCodeClient extends BaseClient {
- constructor(configuration) {
- super(configuration);
- }
- async acquireToken(request2) {
- const deviceCodeResponse = await this.getDeviceCode(request2);
- request2.deviceCodeCallback(deviceCodeResponse);
- const reqTimestamp = exports_TimeUtils.nowSeconds();
- const response7 = await this.acquireTokenWithDeviceCode(request2, deviceCodeResponse);
- const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
- responseHandler.validateTokenResponse(response7, request2.correlationId);
- return responseHandler.handleServerTokenResponse(response7, this.authority, reqTimestamp, request2, ApiId.acquireTokenByDeviceCode);
- }
- async getDeviceCode(request2) {
- const queryParametersString = this.createExtraQueryParameters(request2);
- const endpoint7 = UrlString.appendQueryString(this.authority.deviceCodeEndpoint, queryParametersString);
- const queryString = this.createQueryString(request2);
- const headers = this.createTokenRequestHeaders();
- const thumbprint = {
- clientId: this.config.authOptions.clientId,
- authority: request2.authority,
- scopes: request2.scopes,
- claims: request2.claims,
- authenticationScheme: request2.authenticationScheme,
- resourceRequestMethod: request2.resourceRequestMethod,
- resourceRequestUri: request2.resourceRequestUri,
- shrClaims: request2.shrClaims,
- sshKid: request2.sshKid
- };
- return this.executePostRequestToDeviceCodeEndpoint(endpoint7, queryString, headers, thumbprint, request2.correlationId);
- }
- createExtraQueryParameters(request2) {
- const parameters = new Map;
- if (request2.extraQueryParameters) {
- exports_RequestParameterBuilder.addExtraParameters(parameters, request2.extraQueryParameters);
- }
- return exports_UrlUtils.mapToQueryString(parameters);
- }
- async executePostRequestToDeviceCodeEndpoint(deviceCodeEndpoint, queryString, headers, thumbprint, correlationId) {
- const { body: { user_code: userCode, device_code: deviceCode, verification_uri: verificationUri, expires_in: expiresIn, interval, message } } = await this.sendPostRequest(thumbprint, deviceCodeEndpoint, {
- body: queryString,
- headers
- }, correlationId);
- return {
- userCode,
- deviceCode,
- verificationUri,
- expiresIn,
- interval,
- message
- };
- }
- createQueryString(request2) {
- const parameters = new Map;
- exports_RequestParameterBuilder.addScopes(parameters, request2.scopes);
- exports_RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId);
- if (request2.extraQueryParameters) {
- exports_RequestParameterBuilder.addExtraParameters(parameters, request2.extraQueryParameters);
- }
- if (request2.claims || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
- exports_RequestParameterBuilder.addClaims(parameters, request2.claims, this.config.authOptions.clientCapabilities);
- }
- return exports_UrlUtils.mapToQueryString(parameters);
- }
- continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, userSpecifiedCancelFlag) {
- if (userSpecifiedCancelFlag) {
- this.logger.error("Token request cancelled by setting DeviceCodeRequest.cancel = true", "");
- throw createClientAuthError(deviceCodePollingCancelled);
- } else if (userSpecifiedTimeout && userSpecifiedTimeout < deviceCodeExpirationTime && exports_TimeUtils.nowSeconds() > userSpecifiedTimeout) {
- this.logger.error(`User defined timeout for device code polling reached. The timeout was set for ${userSpecifiedTimeout}`, "");
- throw createClientAuthError(userTimeoutReached);
- } else if (exports_TimeUtils.nowSeconds() > deviceCodeExpirationTime) {
- if (userSpecifiedTimeout) {
- this.logger.verbose(`User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${userSpecifiedTimeout}`, "");
- }
- this.logger.error(`Device code expired. Expiration time of device code was ${deviceCodeExpirationTime}`, "");
- throw createClientAuthError(deviceCodeExpired);
- }
- return true;
- }
- async acquireTokenWithDeviceCode(request2, deviceCodeResponse) {
- const queryParametersString = this.createTokenQueryParameters(request2);
- const endpoint7 = UrlString.appendQueryString(this.authority.tokenEndpoint, queryParametersString);
- const requestBody = this.createTokenRequestBody(request2, deviceCodeResponse);
- const headers = this.createTokenRequestHeaders();
- const userSpecifiedTimeout = request2.timeout ? exports_TimeUtils.nowSeconds() + request2.timeout : undefined;
- const deviceCodeExpirationTime = exports_TimeUtils.nowSeconds() + deviceCodeResponse.expiresIn;
- const pollingIntervalMilli = deviceCodeResponse.interval * 1000;
- while (this.continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, request2.cancel)) {
- const thumbprint = {
- clientId: this.config.authOptions.clientId,
- authority: request2.authority,
- scopes: request2.scopes,
- claims: request2.claims,
- authenticationScheme: request2.authenticationScheme,
- resourceRequestMethod: request2.resourceRequestMethod,
- resourceRequestUri: request2.resourceRequestUri,
- shrClaims: request2.shrClaims,
- sshKid: request2.sshKid
- };
- const response7 = await this.executePostToTokenEndpoint(endpoint7, requestBody, headers, thumbprint, request2.correlationId);
- if (response7.body && response7.body.error) {
- if (response7.body.error === exports_Constants.AUTHORIZATION_PENDING) {
- this.logger.info("Authorization pending. Continue polling.", request2.correlationId);
- await exports_TimeUtils.delay(pollingIntervalMilli);
- } else {
- this.logger.info("Unexpected error in polling from the server", request2.correlationId);
- throw createAuthError(exports_AuthErrorCodes.postRequestFailed, response7.body.error);
- }
- } else {
- this.logger.verbose("Authorization completed successfully. Polling stopped.", request2.correlationId);
- return response7.body;
- }
- }
- this.logger.error("Polling stopped for unknown reasons.", request2.correlationId);
- throw createClientAuthError(deviceCodeUnknownError);
- }
- createTokenRequestBody(request2, deviceCodeResponse) {
- const parameters = new Map;
- exports_RequestParameterBuilder.addScopes(parameters, request2.scopes);
- exports_RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId);
- exports_RequestParameterBuilder.addGrantType(parameters, exports_Constants.GrantType.DEVICE_CODE_GRANT);
- exports_RequestParameterBuilder.addDeviceCode(parameters, deviceCodeResponse.deviceCode);
- const correlationId = request2.correlationId || this.config.cryptoInterface.createNewGuid();
- exports_RequestParameterBuilder.addCorrelationId(parameters, correlationId);
- exports_RequestParameterBuilder.addClientInfo(parameters);
- exports_RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo);
- exports_RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application);
- exports_RequestParameterBuilder.addThrottling(parameters);
- if (this.serverTelemetryManager) {
- exports_RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager);
- }
- if (!StringUtils.isEmptyObj(request2.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
- exports_RequestParameterBuilder.addClaims(parameters, request2.claims, this.config.authOptions.clientCapabilities);
- }
- return exports_UrlUtils.mapToQueryString(parameters);
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/client/PublicClientApplication.mjs
-var PublicClientApplication;
-var init_PublicClientApplication = __esm(() => {
- init_Constants2();
- init_index_node();
- init_ClientApplication();
- init_NodeAuthError();
- init_LoopbackClient();
- init_DeviceCodeClient();
- init_packageMetadata2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- PublicClientApplication = class PublicClientApplication extends ClientApplication {
- constructor(configuration) {
- super(configuration);
- if (this.config.broker.nativeBrokerPlugin) {
- if (this.config.broker.nativeBrokerPlugin.isBrokerAvailable) {
- this.nativeBrokerPlugin = this.config.broker.nativeBrokerPlugin;
- this.nativeBrokerPlugin.setLogger(this.config.system.loggerOptions);
- } else {
- this.logger.warning("NativeBroker implementation was provided but the broker is unavailable.", "");
- }
- }
- this.skus = ServerTelemetryManager.makeExtraSkuString({
- libraryName: Constants.MSAL_SKU,
- libraryVersion: version5
- });
- }
- async acquireTokenByDeviceCode(request2) {
- this.logger.info("acquireTokenByDeviceCode called", request2.correlationId || "");
- enforceResourceParameter(this.config.auth.isMcp, request2);
- const validRequest = Object.assign(request2, await this.initializeBaseRequest(request2));
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByDeviceCode, validRequest.correlationId);
- try {
- const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request2.azureCloudOptions);
- const deviceCodeConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager);
- const deviceCodeClient = new DeviceCodeClient(deviceCodeConfig);
- this.logger.verbose("Device code client created", validRequest.correlationId);
- return await deviceCodeClient.acquireToken(validRequest);
- } catch (e4) {
- if (e4 instanceof AuthError) {
- e4.setCorrelationId(validRequest.correlationId);
- }
- serverTelemetryManager.cacheFailedRequest(e4);
- throw e4;
- }
- }
- async acquireTokenInteractive(request2) {
- const correlationId = request2.correlationId || this.cryptoProvider.createNewGuid();
- this.logger.trace("acquireTokenInteractive called", correlationId);
- enforceResourceParameter(this.config.auth.isMcp, request2);
- const { openBrowser, successTemplate, errorTemplate, windowHandle, loopbackClient: customLoopbackClient, ...remainingProperties } = request2;
- if (this.nativeBrokerPlugin) {
- const brokerRequest = {
- ...remainingProperties,
- clientId: this.config.auth.clientId,
- scopes: request2.scopes || exports_Constants.OIDC_DEFAULT_SCOPES,
- redirectUri: request2.redirectUri || "",
- authority: request2.authority || this.config.auth.authority,
- correlationId,
- extraParameters: {
- ...remainingProperties.extraQueryParameters,
- ...remainingProperties.extraParameters,
- [exports_AADServerParamKeys.X_CLIENT_EXTRA_SKU]: this.skus
- },
- accountId: remainingProperties.account?.nativeAccountId
- };
- return this.nativeBrokerPlugin.acquireTokenInteractive(brokerRequest, windowHandle);
- }
- if (request2.redirectUri) {
- if (!this.config.broker.nativeBrokerPlugin) {
- throw NodeAuthError.createRedirectUriNotSupportedError();
- }
- request2.redirectUri = "";
- }
- const { verifier, challenge } = await this.cryptoProvider.generatePkceCodes();
- const loopbackClient = customLoopbackClient || new LoopbackClient;
- let authCodeResponse = {};
- let authCodeListenerError = null;
- try {
- const authCodeListener = loopbackClient.listenForAuthCode(successTemplate, errorTemplate).then((response7) => {
- authCodeResponse = response7;
- }).catch((e4) => {
- authCodeListenerError = e4;
- });
- const redirectUri = await this.waitForRedirectUri(loopbackClient);
- const validRequest = {
- ...remainingProperties,
- correlationId,
- scopes: request2.scopes || exports_Constants.OIDC_DEFAULT_SCOPES,
- redirectUri,
- responseMode: exports_Constants.ResponseMode.QUERY,
- codeChallenge: challenge,
- codeChallengeMethod: exports_Constants.CodeChallengeMethodValues.S256
- };
- const authCodeUrl = await this.getAuthCodeUrl(validRequest);
- await openBrowser(authCodeUrl);
- await authCodeListener;
- if (authCodeListenerError) {
- throw authCodeListenerError;
- }
- if (authCodeResponse.error) {
- throw new ServerError(authCodeResponse.error, authCodeResponse.error_description, authCodeResponse.suberror);
- } else if (!authCodeResponse.code) {
- throw NodeAuthError.createNoAuthCodeInResponseError();
- }
- const clientInfo = authCodeResponse.client_info;
- const tokenRequest = {
- code: authCodeResponse.code,
- codeVerifier: verifier,
- clientInfo: clientInfo || "",
- ...validRequest
- };
- return await this.acquireTokenByCode(tokenRequest);
- } finally {
- loopbackClient.closeServer();
- }
- }
- async acquireTokenSilent(request2) {
- const correlationId = request2.correlationId || this.cryptoProvider.createNewGuid();
- this.logger.trace("acquireTokenSilent called", correlationId);
- enforceResourceParameter(this.config.auth.isMcp, request2);
- if (this.nativeBrokerPlugin) {
- const brokerRequest = {
- ...request2,
- clientId: this.config.auth.clientId,
- scopes: request2.scopes || exports_Constants.OIDC_DEFAULT_SCOPES,
- redirectUri: request2.redirectUri || "",
- authority: request2.authority || this.config.auth.authority,
- correlationId,
- extraParameters: {
- ...request2.extraQueryParameters,
- ...request2.extraParameters,
- [exports_AADServerParamKeys.X_CLIENT_EXTRA_SKU]: this.skus
- },
- accountId: request2.account.nativeAccountId,
- forceRefresh: request2.forceRefresh || false
- };
- return this.nativeBrokerPlugin.acquireTokenSilent(brokerRequest);
- }
- if (request2.redirectUri) {
- if (!this.config.broker.nativeBrokerPlugin) {
- throw NodeAuthError.createRedirectUriNotSupportedError();
- }
- request2.redirectUri = "";
- }
- return super.acquireTokenSilent(request2);
- }
- async acquireTokenByCode(request2, authCodePayLoad) {
- enforceResourceParameter(this.config.auth.isMcp, request2);
- return super.acquireTokenByCode(request2, authCodePayLoad);
- }
- async acquireTokenByRefreshToken(request2) {
- enforceResourceParameter(this.config.auth.isMcp, request2);
- return super.acquireTokenByRefreshToken(request2);
- }
- async signOut(request2) {
- if (this.nativeBrokerPlugin && request2.account.nativeAccountId) {
- const signoutRequest = {
- clientId: this.config.auth.clientId,
- accountId: request2.account.nativeAccountId,
- correlationId: request2.correlationId || this.cryptoProvider.createNewGuid()
- };
- await this.nativeBrokerPlugin.signOut(signoutRequest);
- }
- await this.getTokenCache().removeAccount(request2.account, request2.correlationId);
- }
- async getAllAccounts() {
- if (this.nativeBrokerPlugin) {
- const correlationId = this.cryptoProvider.createNewGuid();
- return this.nativeBrokerPlugin.getAllAccounts(this.config.auth.clientId, correlationId);
- }
- return this.getTokenCache().getAllAccounts();
- }
- async waitForRedirectUri(loopbackClient) {
- return new Promise((resolve9, reject) => {
- let ticks = 0;
- const id = setInterval(() => {
- if (LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS / LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS < ticks) {
- clearInterval(id);
- reject(NodeAuthError.createLoopbackServerTimeoutError());
- return;
- }
- try {
- const r4 = loopbackClient.getRedirectUri();
- clearInterval(id);
- resolve9(r4);
- return;
- } catch (e4) {
- if (e4 instanceof AuthError && e4.errorCode === NodeAuthErrorMessage.noLoopbackServerExists.code) {
- ticks++;
- return;
- }
- clearInterval(id);
- reject(e4);
- return;
- }
- }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);
- });
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/client/ClientCredentialClient.mjs
-var ClientCredentialClient;
-var init_ClientCredentialClient = __esm(() => {
- init_index_node();
- init_Constants2();
- init_BaseClient();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- ClientCredentialClient = class ClientCredentialClient extends BaseClient {
- constructor(configuration, appTokenProvider) {
- super(configuration);
- this.appTokenProvider = appTokenProvider;
- }
- async acquireToken(request2) {
- if (request2.skipCache || request2.claims) {
- return this.executeTokenRequest(request2, this.authority);
- }
- const [cachedAuthenticationResult, lastCacheOutcome] = await this.getCachedAuthenticationResult(request2, this.config, this.cryptoUtils, this.authority, this.cacheManager, this.serverTelemetryManager);
- if (cachedAuthenticationResult) {
- if (lastCacheOutcome === exports_Constants.CacheOutcome.PROACTIVELY_REFRESHED) {
- this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.", request2.correlationId);
- const refreshAccessToken = true;
- await this.executeTokenRequest(request2, this.authority, refreshAccessToken);
- }
- return cachedAuthenticationResult;
- } else {
- return this.executeTokenRequest(request2, this.authority);
- }
- }
- async getCachedAuthenticationResult(request2, config8, cryptoUtils, authority, cacheManager, serverTelemetryManager) {
- const clientConfiguration = config8;
- const managedIdentityConfiguration = config8;
- let lastCacheOutcome = exports_Constants.CacheOutcome.NOT_APPLICABLE;
- let cacheContext;
- if (clientConfiguration.serializableCache && clientConfiguration.persistencePlugin) {
- cacheContext = new TokenCacheContext(clientConfiguration.serializableCache, false);
- await clientConfiguration.persistencePlugin.beforeCacheAccess(cacheContext);
- }
- const cachedAccessToken = this.readAccessTokenFromCache(authority, managedIdentityConfiguration.managedIdentityId?.id || clientConfiguration.authOptions.clientId, new ScopeSet(request2.scopes || []), cacheManager, request2.correlationId);
- if (clientConfiguration.serializableCache && clientConfiguration.persistencePlugin && cacheContext) {
- await clientConfiguration.persistencePlugin.afterCacheAccess(cacheContext);
- }
- if (!cachedAccessToken) {
- serverTelemetryManager?.setCacheOutcome(exports_Constants.CacheOutcome.NO_CACHED_ACCESS_TOKEN);
- return [null, exports_Constants.CacheOutcome.NO_CACHED_ACCESS_TOKEN];
- }
- if (exports_TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, clientConfiguration.systemOptions?.tokenRenewalOffsetSeconds || exports_Constants.DEFAULT_TOKEN_RENEWAL_OFFSET_SEC)) {
- serverTelemetryManager?.setCacheOutcome(exports_Constants.CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);
- return [null, exports_Constants.CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED];
- }
- if (cachedAccessToken.refreshOn && exports_TimeUtils.isTokenExpired(cachedAccessToken.refreshOn.toString(), 0)) {
- lastCacheOutcome = exports_Constants.CacheOutcome.PROACTIVELY_REFRESHED;
- serverTelemetryManager?.setCacheOutcome(exports_Constants.CacheOutcome.PROACTIVELY_REFRESHED);
- }
- return [
- await ResponseHandler.generateAuthenticationResult(cryptoUtils, authority, {
- account: null,
- idToken: null,
- accessToken: cachedAccessToken,
- refreshToken: null,
- appMetadata: null
- }, true, request2, this.performanceClient),
- lastCacheOutcome
- ];
- }
- readAccessTokenFromCache(authority, id, scopeSet, cacheManager, correlationId) {
- const accessTokenFilter = {
- homeAccountId: "",
- environment: authority.canonicalAuthorityUrlComponents.HostNameAndPort,
- credentialType: exports_Constants.CredentialType.ACCESS_TOKEN,
- clientId: id,
- realm: authority.tenant,
- target: ScopeSet.createSearchScopes(scopeSet.asArray())
- };
- const accessTokens = cacheManager.getAccessTokensByFilter(accessTokenFilter, correlationId);
- if (accessTokens.length < 1) {
- return null;
- } else if (accessTokens.length > 1) {
- throw createClientAuthError(exports_ClientAuthErrorCodes.multipleMatchingTokens);
- }
- return accessTokens[0];
- }
- async executeTokenRequest(request2, authority, refreshAccessToken) {
- let serverTokenResponse;
- let reqTimestamp;
- if (this.appTokenProvider) {
- this.logger.info("Using appTokenProvider extensibility.", request2.correlationId);
- const appTokenPropviderParameters = {
- correlationId: request2.correlationId,
- tenantId: this.config.authOptions.authority.tenant,
- scopes: request2.scopes,
- claims: request2.claims
- };
- reqTimestamp = exports_TimeUtils.nowSeconds();
- const appTokenProviderResult = await this.appTokenProvider(appTokenPropviderParameters);
- serverTokenResponse = {
- access_token: appTokenProviderResult.accessToken,
- expires_in: appTokenProviderResult.expiresInSeconds,
- refresh_in: appTokenProviderResult.refreshInSeconds,
- token_type: exports_Constants.AuthenticationScheme.BEARER
- };
- } else {
- const queryParametersString = this.createTokenQueryParameters(request2);
- const endpoint7 = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
- const requestBody = await this.createTokenRequestBody(request2);
- const headers = this.createTokenRequestHeaders();
- const thumbprint = {
- clientId: this.config.authOptions.clientId,
- authority: request2.authority,
- scopes: request2.scopes,
- claims: request2.claims,
- authenticationScheme: request2.authenticationScheme,
- resourceRequestMethod: request2.resourceRequestMethod,
- resourceRequestUri: request2.resourceRequestUri,
- shrClaims: request2.shrClaims,
- sshKid: request2.sshKid
- };
- this.logger.info("Sending token request to endpoint: " + authority.tokenEndpoint, request2.correlationId);
- reqTimestamp = exports_TimeUtils.nowSeconds();
- const response7 = await this.executePostToTokenEndpoint(endpoint7, requestBody, headers, thumbprint, request2.correlationId);
- serverTokenResponse = response7.body;
- serverTokenResponse.status = response7.status;
- }
- const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
- responseHandler.validateTokenResponse(serverTokenResponse, request2.correlationId, refreshAccessToken);
- const tokenResponse = await responseHandler.handleServerTokenResponse(serverTokenResponse, this.authority, reqTimestamp, request2, ApiId.acquireTokenByClientCredential);
- return tokenResponse;
- }
- async createTokenRequestBody(request2) {
- const parameters = new Map;
- exports_RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId);
- exports_RequestParameterBuilder.addScopes(parameters, request2.scopes, false);
- exports_RequestParameterBuilder.addGrantType(parameters, exports_Constants.GrantType.CLIENT_CREDENTIALS_GRANT);
- exports_RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo);
- exports_RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application);
- exports_RequestParameterBuilder.addThrottling(parameters);
- if (this.serverTelemetryManager) {
- exports_RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager);
- }
- const correlationId = request2.correlationId || this.config.cryptoInterface.createNewGuid();
- exports_RequestParameterBuilder.addCorrelationId(parameters, correlationId);
- if (this.config.clientCredentials.clientSecret) {
- exports_RequestParameterBuilder.addClientSecret(parameters, this.config.clientCredentials.clientSecret);
- }
- const clientAssertion = request2.clientAssertion || this.config.clientCredentials.clientAssertion;
- if (clientAssertion) {
- exports_RequestParameterBuilder.addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request2.resourceRequestUri));
- exports_RequestParameterBuilder.addClientAssertionType(parameters, clientAssertion.assertionType);
- }
- if (!StringUtils.isEmptyObj(request2.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
- exports_RequestParameterBuilder.addClaims(parameters, request2.claims, this.config.authOptions.clientCapabilities);
- }
- return exports_UrlUtils.mapToQueryString(parameters);
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/client/OnBehalfOfClient.mjs
-var OnBehalfOfClient;
-var init_OnBehalfOfClient = __esm(() => {
- init_index_node();
- init_Constants2();
- init_EncodingUtils();
- init_BaseClient();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- OnBehalfOfClient = class OnBehalfOfClient extends BaseClient {
- constructor(configuration) {
- super(configuration);
- }
- async acquireToken(request2) {
- this.scopeSet = new ScopeSet(request2.scopes || []);
- this.userAssertionHash = await this.cryptoUtils.hashString(request2.oboAssertion);
- if (request2.skipCache || request2.claims) {
- return this.executeTokenRequest(request2, this.authority, this.userAssertionHash);
- }
- try {
- return await this.getCachedAuthenticationResult(request2);
- } catch (e4) {
- return await this.executeTokenRequest(request2, this.authority, this.userAssertionHash);
- }
- }
- async getCachedAuthenticationResult(request2) {
- const cachedAccessToken = this.readAccessTokenFromCacheForOBO(this.config.authOptions.clientId, request2);
- if (!cachedAccessToken) {
- this.serverTelemetryManager?.setCacheOutcome(exports_Constants.CacheOutcome.NO_CACHED_ACCESS_TOKEN);
- this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.", request2.correlationId);
- throw createClientAuthError(exports_ClientAuthErrorCodes.tokenRefreshRequired);
- } else if (exports_TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
- this.serverTelemetryManager?.setCacheOutcome(exports_Constants.CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);
- this.logger.info(`OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`, request2.correlationId);
- throw createClientAuthError(exports_ClientAuthErrorCodes.tokenRefreshRequired);
- }
- const cachedIdToken = this.readIdTokenFromCacheForOBO(cachedAccessToken.homeAccountId, request2.correlationId);
- let idTokenClaims;
- let cachedAccount = null;
- if (cachedIdToken) {
- idTokenClaims = exports_AuthToken.extractTokenClaims(cachedIdToken.secret, EncodingUtils.base64Decode);
- const localAccountId = idTokenClaims.oid || idTokenClaims.sub;
- const accountInfo = {
- homeAccountId: cachedIdToken.homeAccountId,
- environment: cachedIdToken.environment,
- tenantId: cachedIdToken.realm,
- username: "",
- localAccountId: localAccountId || ""
- };
- cachedAccount = this.cacheManager.getAccount(this.cacheManager.generateAccountKey(accountInfo), request2.correlationId);
- }
- if (this.config.serverTelemetryManager) {
- this.config.serverTelemetryManager.incrementCacheHits();
- }
- return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, {
- account: cachedAccount,
- accessToken: cachedAccessToken,
- idToken: cachedIdToken,
- refreshToken: null,
- appMetadata: null
- }, true, request2, this.performanceClient, idTokenClaims);
- }
- readIdTokenFromCacheForOBO(atHomeAccountId, correlationId) {
- const idTokenFilter = {
- homeAccountId: atHomeAccountId,
- environment: this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,
- credentialType: exports_Constants.CredentialType.ID_TOKEN,
- clientId: this.config.authOptions.clientId,
- realm: this.authority.tenant
- };
- const idTokenMap = this.cacheManager.getIdTokensByFilter(idTokenFilter, correlationId);
- if (Object.values(idTokenMap).length < 1) {
- return null;
- }
- return Object.values(idTokenMap)[0];
- }
- readAccessTokenFromCacheForOBO(clientId, request2) {
- const authScheme = request2.authenticationScheme || exports_Constants.AuthenticationScheme.BEARER;
- const credentialType = authScheme && authScheme.toLowerCase() !== exports_Constants.AuthenticationScheme.BEARER.toLowerCase() ? exports_Constants.CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME : exports_Constants.CredentialType.ACCESS_TOKEN;
- const accessTokenFilter = {
- credentialType,
- clientId,
- target: ScopeSet.createSearchScopes(this.scopeSet.asArray()),
- tokenType: authScheme,
- keyId: request2.sshKid,
- userAssertionHash: this.userAssertionHash
- };
- const accessTokens = this.cacheManager.getAccessTokensByFilter(accessTokenFilter, request2.correlationId);
- const numAccessTokens = accessTokens.length;
- if (numAccessTokens < 1) {
- return null;
- } else if (numAccessTokens > 1) {
- throw createClientAuthError(exports_ClientAuthErrorCodes.multipleMatchingTokens);
- }
- return accessTokens[0];
- }
- async executeTokenRequest(request2, authority, userAssertionHash) {
- const queryParametersString = this.createTokenQueryParameters(request2);
- const endpoint7 = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
- const requestBody = await this.createTokenRequestBody(request2);
- const headers = this.createTokenRequestHeaders();
- const thumbprint = {
- clientId: this.config.authOptions.clientId,
- authority: request2.authority,
- scopes: request2.scopes,
- claims: request2.claims,
- authenticationScheme: request2.authenticationScheme,
- resourceRequestMethod: request2.resourceRequestMethod,
- resourceRequestUri: request2.resourceRequestUri,
- shrClaims: request2.shrClaims,
- sshKid: request2.sshKid
- };
- const reqTimestamp = exports_TimeUtils.nowSeconds();
- const response7 = await this.executePostToTokenEndpoint(endpoint7, requestBody, headers, thumbprint, request2.correlationId);
- const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
- responseHandler.validateTokenResponse(response7.body, request2.correlationId);
- const tokenResponse = await responseHandler.handleServerTokenResponse(response7.body, this.authority, reqTimestamp, request2, ApiId.acquireTokenByOBO, undefined, userAssertionHash);
- return tokenResponse;
- }
- async createTokenRequestBody(request2) {
- const parameters = new Map;
- exports_RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId);
- exports_RequestParameterBuilder.addScopes(parameters, request2.scopes);
- exports_RequestParameterBuilder.addGrantType(parameters, exports_Constants.GrantType.JWT_BEARER);
- exports_RequestParameterBuilder.addClientInfo(parameters);
- exports_RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo);
- exports_RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application);
- exports_RequestParameterBuilder.addThrottling(parameters);
- if (this.serverTelemetryManager) {
- exports_RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager);
- }
- const correlationId = request2.correlationId || this.config.cryptoInterface.createNewGuid();
- exports_RequestParameterBuilder.addCorrelationId(parameters, correlationId);
- exports_RequestParameterBuilder.addRequestTokenUse(parameters, exports_AADServerParamKeys.ON_BEHALF_OF);
- exports_RequestParameterBuilder.addOboAssertion(parameters, request2.oboAssertion);
- if (this.config.clientCredentials.clientSecret) {
- exports_RequestParameterBuilder.addClientSecret(parameters, this.config.clientCredentials.clientSecret);
- }
- const clientAssertion = this.config.clientCredentials.clientAssertion;
- if (clientAssertion) {
- exports_RequestParameterBuilder.addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request2.resourceRequestUri));
- exports_RequestParameterBuilder.addClientAssertionType(parameters, clientAssertion.assertionType);
- }
- if (request2.claims || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
- exports_RequestParameterBuilder.addClaims(parameters, request2.claims, this.config.authOptions.clientCapabilities);
- }
- return exports_UrlUtils.mapToQueryString(parameters);
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/client/ConfidentialClientApplication.mjs
-var ConfidentialClientApplication;
-var init_ConfidentialClientApplication = __esm(() => {
- init_ClientApplication();
- init_ClientAssertion();
- init_Constants2();
- init_index_node();
- init_ClientCredentialClient();
- init_OnBehalfOfClient();
- init_ClientAuthErrorCodes2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- ConfidentialClientApplication = class ConfidentialClientApplication extends ClientApplication {
- constructor(configuration) {
- super(configuration);
- const clientSecretNotEmpty = !!this.config.auth.clientSecret;
- const clientAssertionNotEmpty = !!this.config.auth.clientAssertion;
- const certificateNotEmpty = (!!this.config.auth.clientCertificate?.thumbprint || !!this.config.auth.clientCertificate?.thumbprintSha256) && !!this.config.auth.clientCertificate?.privateKey;
- if (this.appTokenProvider) {
- return;
- }
- if (clientSecretNotEmpty && clientAssertionNotEmpty || clientAssertionNotEmpty && certificateNotEmpty || clientSecretNotEmpty && certificateNotEmpty) {
- throw createClientAuthError(invalidClientCredential);
- }
- if (this.config.auth.clientSecret) {
- this.clientSecret = this.config.auth.clientSecret;
- return;
- }
- if (this.config.auth.clientAssertion) {
- this.developerProvidedClientAssertion = this.config.auth.clientAssertion;
- return;
- }
- if (!certificateNotEmpty) {
- throw createClientAuthError(invalidClientCredential);
- } else {
- this.clientAssertion = this.config.auth.clientCertificate.thumbprintSha256 ? ClientAssertion.fromCertificateWithSha256Thumbprint(this.config.auth.clientCertificate.thumbprintSha256, this.config.auth.clientCertificate.privateKey, this.config.auth.clientCertificate.x5c) : ClientAssertion.fromCertificate(this.config.auth.clientCertificate.thumbprint, this.config.auth.clientCertificate.privateKey, this.config.auth.clientCertificate.x5c);
- }
- this.appTokenProvider = undefined;
- }
- SetAppTokenProvider(provider5) {
- this.appTokenProvider = provider5;
- }
- async acquireTokenByClientCredential(request2) {
- this.logger.info("acquireTokenByClientCredential called", request2.correlationId || "");
- let clientAssertion;
- if (request2.clientAssertion) {
- clientAssertion = {
- assertion: await getClientAssertion(request2.clientAssertion, this.config.auth.clientId),
- assertionType: Constants.JWT_BEARER_ASSERTION_TYPE
- };
- }
- const baseRequest = await this.initializeBaseRequest(request2);
- const validBaseRequest = {
- ...baseRequest,
- scopes: baseRequest.scopes.filter((scope) => !exports_Constants.OIDC_DEFAULT_SCOPES.includes(scope))
- };
- const validRequest = {
- ...request2,
- ...validBaseRequest,
- clientAssertion
- };
- const authority = new UrlString(validRequest.authority);
- const tenantId = authority.getUrlComponents().PathSegments[0];
- if (Object.values(exports_Constants.AADAuthority).includes(tenantId)) {
- throw createClientAuthError(missingTenantIdError);
- }
- const ENV_MSAL_FORCE_REGION = process.env[MSAL_FORCE_REGION];
- let region;
- if (validRequest.azureRegion !== "DisableMsalForceRegion") {
- if (!validRequest.azureRegion && ENV_MSAL_FORCE_REGION) {
- region = ENV_MSAL_FORCE_REGION;
- } else {
- region = validRequest.azureRegion;
- }
- }
- const azureRegionConfiguration = {
- azureRegion: region,
- environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE]
- };
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByClientCredential, validRequest.correlationId, validRequest.skipCache);
- try {
- const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, azureRegionConfiguration, request2.azureCloudOptions);
- const clientCredentialConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager);
- const clientCredentialClient = new ClientCredentialClient(clientCredentialConfig, this.appTokenProvider);
- this.logger.verbose("Client credential client created", validRequest.correlationId);
- return await clientCredentialClient.acquireToken(validRequest);
- } catch (e4) {
- if (e4 instanceof AuthError) {
- e4.setCorrelationId(validRequest.correlationId);
- }
- serverTelemetryManager.cacheFailedRequest(e4);
- throw e4;
- }
- }
- async acquireTokenOnBehalfOf(request2) {
- this.logger.info("acquireTokenOnBehalfOf called", request2.correlationId || "");
- const validRequest = {
- ...request2,
- ...await this.initializeBaseRequest(request2)
- };
- try {
- const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request2.azureCloudOptions);
- const onBehalfOfConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", undefined);
- const oboClient = new OnBehalfOfClient(onBehalfOfConfig);
- this.logger.verbose("On behalf of client created", validRequest.correlationId);
- return await oboClient.acquireToken(validRequest);
- } catch (e4) {
- if (e4 instanceof AuthError) {
- e4.setCorrelationId(validRequest.correlationId);
- }
- throw e4;
- }
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/utils/TimeUtils.mjs
-function isIso8601(dateString) {
- if (typeof dateString !== "string") {
- return false;
- }
- const date5 = new Date(dateString);
- return !isNaN(date5.getTime()) && date5.toISOString() === dateString;
-}
-var init_TimeUtils2 = __esm(() => {
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/network/HttpClientWithRetries.mjs
-class HttpClientWithRetries {
- constructor(httpClientNoRetries, retryPolicy, logger10) {
- this.httpClientNoRetries = httpClientNoRetries;
- this.retryPolicy = retryPolicy;
- this.logger = logger10;
- }
- async sendNetworkRequestAsyncHelper(httpMethod, url3, options2) {
- if (httpMethod === HttpMethod2.GET) {
- return this.httpClientNoRetries.sendGetRequestAsync(url3, options2);
- } else {
- return this.httpClientNoRetries.sendPostRequestAsync(url3, options2);
- }
- }
- async sendNetworkRequestAsync(httpMethod, url3, options2) {
- let response7 = await this.sendNetworkRequestAsyncHelper(httpMethod, url3, options2);
- if ("isNewRequest" in this.retryPolicy) {
- this.retryPolicy.isNewRequest = true;
- }
- let currentRetry = 0;
- while (await this.retryPolicy.pauseForRetry(response7.status, currentRetry, this.logger, response7.headers[exports_Constants.HeaderNames.RETRY_AFTER])) {
- response7 = await this.sendNetworkRequestAsyncHelper(httpMethod, url3, options2);
- currentRetry++;
- }
- return response7;
- }
- async sendGetRequestAsync(url3, options2) {
- return this.sendNetworkRequestAsync(HttpMethod2.GET, url3, options2);
- }
- async sendPostRequestAsync(url3, options2) {
- return this.sendNetworkRequestAsync(HttpMethod2.POST, url3, options2);
- }
-}
-var init_HttpClientWithRetries = __esm(() => {
- init_index_node();
- init_Constants2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs
-class BaseManagedIdentitySource {
- constructor(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
- this.logger = logger10;
- this.nodeStorage = nodeStorage;
- this.networkClient = networkClient;
- this.cryptoProvider = cryptoProvider;
- this.disableInternalRetries = disableInternalRetries;
- }
- async getServerTokenResponseAsync(response7, _networkClient, _networkRequest, _networkRequestOptions) {
- return this.getServerTokenResponse(response7);
- }
- getServerTokenResponse(response7) {
- let refreshIn, expiresIn;
- if (response7.body.expires_on) {
- if (isIso8601(response7.body.expires_on)) {
- response7.body.expires_on = new Date(response7.body.expires_on).getTime() / 1000;
- }
- expiresIn = response7.body.expires_on - exports_TimeUtils.nowSeconds();
- if (expiresIn > 2 * 3600) {
- refreshIn = expiresIn / 2;
- }
- }
- const serverTokenResponse = {
- status: response7.status,
- access_token: response7.body.access_token,
- expires_in: expiresIn,
- scope: response7.body.resource,
- token_type: response7.body.token_type,
- refresh_in: refreshIn,
- correlation_id: response7.body.correlation_id || response7.body.correlationId,
- error: typeof response7.body.error === "string" ? response7.body.error : response7.body.error?.code,
- error_description: response7.body.message || (typeof response7.body.error === "string" ? response7.body.error_description : response7.body.error?.message),
- error_codes: response7.body.error_codes,
- timestamp: response7.body.timestamp,
- trace_id: response7.body.trace_id
- };
- return serverTokenResponse;
- }
- async acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) {
- const networkRequest = this.createRequest(managedIdentityRequest.resource, managedIdentityId);
- if (managedIdentityRequest.revokedTokenSha256Hash) {
- this.logger.info(`[Managed Identity] The following claims are present in the request: ${managedIdentityRequest.claims}`, "");
- networkRequest.queryParameters[ManagedIdentityQueryParameters.SHA256_TOKEN_TO_REFRESH] = managedIdentityRequest.revokedTokenSha256Hash;
- }
- if (managedIdentityRequest.clientCapabilities?.length) {
- const clientCapabilities = managedIdentityRequest.clientCapabilities.toString();
- this.logger.info(`[Managed Identity] The following client capabilities are present in the request: ${clientCapabilities}`, "");
- networkRequest.queryParameters[ManagedIdentityQueryParameters.XMS_CC] = clientCapabilities;
- }
- const headers = networkRequest.headers;
- headers[exports_Constants.HeaderNames.CONTENT_TYPE] = exports_Constants.URL_FORM_CONTENT_TYPE;
- const networkRequestOptions = { headers };
- if (Object.keys(networkRequest.bodyParameters).length) {
- networkRequestOptions.body = networkRequest.computeParametersBodyString();
- }
- const networkClientHelper = this.disableInternalRetries ? this.networkClient : new HttpClientWithRetries(this.networkClient, networkRequest.retryPolicy, this.logger);
- const reqTimestamp = exports_TimeUtils.nowSeconds();
- let response7;
- try {
- if (networkRequest.httpMethod === HttpMethod2.POST) {
- response7 = await networkClientHelper.sendPostRequestAsync(networkRequest.computeUri(), networkRequestOptions);
- } else {
- response7 = await networkClientHelper.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions);
- }
- } catch (error44) {
- if (error44 instanceof AuthError) {
- throw error44;
- } else {
- throw createClientAuthError(exports_ClientAuthErrorCodes.networkError);
- }
- }
- const responseHandler = new ResponseHandler(managedIdentityId.id, this.nodeStorage, this.cryptoProvider, this.logger, new StubPerformanceClient, null, null);
- const serverTokenResponse = await this.getServerTokenResponseAsync(response7, networkClientHelper, networkRequest, networkRequestOptions);
- responseHandler.validateTokenResponse(serverTokenResponse, serverTokenResponse.correlation_id || "", refreshAccessToken);
- return responseHandler.handleServerTokenResponse(serverTokenResponse, fakeAuthority, reqTimestamp, managedIdentityRequest, ApiId.acquireTokenWithManagedIdentity);
- }
- getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityIdType, isImds, usesApi2017) {
- switch (managedIdentityIdType) {
- case ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID:
- this.logger.info(`[Managed Identity] [API version ${usesApi2017 ? "2017+" : "2019+"}] Adding user assigned client id to the request.`, "");
- return usesApi2017 ? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017 : ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID;
- case ManagedIdentityIdType.USER_ASSIGNED_RESOURCE_ID:
- this.logger.info("[Managed Identity] Adding user assigned resource id to the request.", "");
- return isImds ? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_IMDS : ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS;
- case ManagedIdentityIdType.USER_ASSIGNED_OBJECT_ID:
- this.logger.info("[Managed Identity] Adding user assigned object id to the request.", "");
- return ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_OBJECT_ID;
- default:
- throw createManagedIdentityError(invalidManagedIdentityIdType);
- }
- }
-}
-var ManagedIdentityUserAssignedIdQueryParameterNames;
-var init_BaseManagedIdentitySource = __esm(() => {
- init_index_node();
- init_Constants2();
- init_ManagedIdentityError();
- init_TimeUtils2();
- init_HttpClientWithRetries();
- init_ManagedIdentityErrorCodes();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- ManagedIdentityUserAssignedIdQueryParameterNames = {
- MANAGED_IDENTITY_CLIENT_ID_2017: "clientid",
- MANAGED_IDENTITY_CLIENT_ID: "client_id",
- MANAGED_IDENTITY_OBJECT_ID: "object_id",
- MANAGED_IDENTITY_RESOURCE_ID_IMDS: "msi_res_id",
- MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS: "mi_res_id"
- };
- BaseManagedIdentitySource.getValidatedEnvVariableUrlString = (envVariableStringName, envVariable, sourceName, logger10) => {
- try {
- return new UrlString(envVariable).urlString;
- } catch (error44) {
- logger10.info(`[Managed Identity] ${sourceName} managed identity is unavailable because the '${envVariableStringName}' environment variable is malformed.`, "");
- throw createManagedIdentityError(MsiEnvironmentVariableUrlMalformedErrorCodes[envVariableStringName]);
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/retry/LinearRetryStrategy.mjs
-class LinearRetryStrategy {
- calculateDelay(retryHeader, minimumDelay) {
- if (!retryHeader) {
- return minimumDelay;
- }
- let millisToSleep = Math.round(parseFloat(retryHeader) * 1000);
- if (isNaN(millisToSleep)) {
- millisToSleep = new Date(retryHeader).valueOf() - new Date().valueOf();
- }
- return Math.max(minimumDelay, millisToSleep);
- }
-}
-var init_LinearRetryStrategy = __esm(() => {
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/retry/DefaultManagedIdentityRetryPolicy.mjs
-class DefaultManagedIdentityRetryPolicy {
- constructor() {
- this.linearRetryStrategy = new LinearRetryStrategy;
- }
- static get DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS() {
- return DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS;
- }
- async pauseForRetry(httpStatusCode, currentRetry, logger10, retryAfterHeader) {
- if (DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON.includes(httpStatusCode) && currentRetry < DEFAULT_MANAGED_IDENTITY_MAX_RETRIES) {
- const retryAfterDelay = this.linearRetryStrategy.calculateDelay(retryAfterHeader, DefaultManagedIdentityRetryPolicy.DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS);
- logger10.verbose(`Retrying request in ${retryAfterDelay}ms (retry attempt: ${currentRetry + 1})`, "");
- await new Promise((resolve9) => {
- return setTimeout(resolve9, retryAfterDelay);
- });
- return true;
- }
- return false;
- }
-}
-var DEFAULT_MANAGED_IDENTITY_MAX_RETRIES = 3, DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS = 1000, DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON;
-var init_DefaultManagedIdentityRetryPolicy = __esm(() => {
- init_index_node();
- init_LinearRetryStrategy();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON = [
- exports_Constants.HTTP_NOT_FOUND,
- exports_Constants.HTTP_REQUEST_TIMEOUT,
- exports_Constants.HTTP_TOO_MANY_REQUESTS,
- exports_Constants.HTTP_SERVER_ERROR,
- exports_Constants.HTTP_SERVICE_UNAVAILABLE,
- exports_Constants.HTTP_GATEWAY_TIMEOUT
- ];
-});
-
-// node_modules/@azure/msal-node/dist/config/ManagedIdentityRequestParameters.mjs
-class ManagedIdentityRequestParameters {
- constructor(httpMethod, endpoint7, retryPolicy) {
- this.httpMethod = httpMethod;
- this._baseEndpoint = endpoint7;
- this.headers = {};
- this.bodyParameters = {};
- this.queryParameters = {};
- this.retryPolicy = retryPolicy || new DefaultManagedIdentityRetryPolicy;
- }
- computeUri() {
- const parameters = new Map;
- if (this.queryParameters) {
- exports_RequestParameterBuilder.addExtraParameters(parameters, this.queryParameters);
- }
- const queryParametersString = exports_UrlUtils.mapToQueryString(parameters);
- return UrlString.appendQueryString(this._baseEndpoint, queryParametersString);
- }
- computeParametersBodyString() {
- const parameters = new Map;
- if (this.bodyParameters) {
- exports_RequestParameterBuilder.addExtraParameters(parameters, this.bodyParameters);
- }
- return exports_UrlUtils.mapToQueryString(parameters);
- }
-}
-var init_ManagedIdentityRequestParameters = __esm(() => {
- init_index_node();
- init_DefaultManagedIdentityRetryPolicy();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AppService.mjs
-var APP_SERVICE_MSI_API_VERSION = "2019-08-01", AppService;
-var init_AppService = __esm(() => {
- init_BaseManagedIdentitySource();
- init_Constants2();
- init_ManagedIdentityRequestParameters();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- AppService = class AppService extends BaseManagedIdentitySource {
- constructor(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader) {
- super(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
- this.identityEndpoint = identityEndpoint;
- this.identityHeader = identityHeader;
- }
- static getEnvironmentVariables() {
- const identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT];
- const identityHeader = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER];
- return [identityEndpoint, identityHeader];
- }
- static tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
- const [identityEndpoint, identityHeader] = AppService.getEnvironmentVariables();
- if (!identityEndpoint || !identityHeader) {
- logger10.info(`[Managed Identity] ${ManagedIdentitySourceNames.APP_SERVICE} managed identity is unavailable because one or both of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}' and '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' environment variables are not defined.`, "");
- return null;
- }
- const validatedIdentityEndpoint = AppService.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.APP_SERVICE, logger10);
- logger10.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.APP_SERVICE} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.APP_SERVICE} managed identity.`, "");
- return new AppService(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader);
- }
- createRequest(resource, managedIdentityId) {
- const request2 = new ManagedIdentityRequestParameters(HttpMethod2.GET, this.identityEndpoint);
- request2.headers[ManagedIdentityHeaders.APP_SERVICE_SECRET_HEADER_NAME] = this.identityHeader;
- request2.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = APP_SERVICE_MSI_API_VERSION;
- request2.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
- if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
- request2.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id;
- }
- return request2;
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AzureArc.mjs
-import { accessSync, constants as constants9, statSync as statSync4, readFileSync as readFileSync7 } from "fs";
-import path11 from "path";
-var ARC_API_VERSION = "2019-11-01", DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT = "http://127.0.0.1:40342/metadata/identity/oauth2/token", HIMDS_EXECUTABLE_HELPER_STRING = "N/A: himds executable exists", SUPPORTED_AZURE_ARC_PLATFORMS, AZURE_ARC_FILE_DETECTION, AzureArc;
-var init_AzureArc = __esm(() => {
- init_index_node();
- init_ManagedIdentityRequestParameters();
- init_BaseManagedIdentitySource();
- init_ManagedIdentityError();
- init_Constants2();
- init_ManagedIdentityErrorCodes();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- SUPPORTED_AZURE_ARC_PLATFORMS = {
- win32: `${process.env["ProgramData"]}\\AzureConnectedMachineAgent\\Tokens\\`,
- linux: "/var/opt/azcmagent/tokens/"
- };
- AZURE_ARC_FILE_DETECTION = {
- win32: `${process.env["ProgramFiles"]}\\AzureConnectedMachineAgent\\himds.exe`,
- linux: "/opt/azcmagent/bin/himds"
- };
- AzureArc = class AzureArc extends BaseManagedIdentitySource {
- constructor(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint) {
- super(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
- this.identityEndpoint = identityEndpoint;
- }
- static getEnvironmentVariables() {
- let identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT];
- let imdsEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT];
- if (!identityEndpoint || !imdsEndpoint) {
- const fileDetectionPath = AZURE_ARC_FILE_DETECTION[process.platform];
- try {
- accessSync(fileDetectionPath, constants9.F_OK | constants9.R_OK);
- identityEndpoint = DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT;
- imdsEndpoint = HIMDS_EXECUTABLE_HELPER_STRING;
- } catch (err) {}
- }
- return [identityEndpoint, imdsEndpoint];
- }
- static tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) {
- const [identityEndpoint, imdsEndpoint] = AzureArc.getEnvironmentVariables();
- if (!identityEndpoint || !imdsEndpoint) {
- logger10.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is unavailable through environment variables because one or both of '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' and '${ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT}' are not defined. ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is also unavailable through file detection.`, "");
- return null;
- }
- if (imdsEndpoint === HIMDS_EXECUTABLE_HELPER_STRING) {
- logger10.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is available through file detection. Defaulting to known ${ManagedIdentitySourceNames.AZURE_ARC} endpoint: ${DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`, "");
- } else {
- const validatedIdentityEndpoint = AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger10);
- validatedIdentityEndpoint.endsWith("/") && validatedIdentityEndpoint.slice(0, -1);
- AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT, imdsEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger10);
- logger10.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.AZURE_ARC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`, "");
- }
- if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
- throw createManagedIdentityError(unableToCreateAzureArc);
- }
- return new AzureArc(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint);
- }
- createRequest(resource) {
- const request2 = new ManagedIdentityRequestParameters(HttpMethod2.GET, this.identityEndpoint.replace("localhost", "127.0.0.1"));
- request2.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
- request2.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = ARC_API_VERSION;
- request2.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
- return request2;
- }
- async getServerTokenResponseAsync(originalResponse, networkClient, networkRequest, networkRequestOptions) {
- let retryResponse;
- if (originalResponse.status === exports_Constants.HTTP_UNAUTHORIZED) {
- const wwwAuthHeader = originalResponse.headers["www-authenticate"];
- if (!wwwAuthHeader) {
- throw createManagedIdentityError(wwwAuthenticateHeaderMissing);
- }
- if (!wwwAuthHeader.includes("Basic realm=")) {
- throw createManagedIdentityError(wwwAuthenticateHeaderUnsupportedFormat);
- }
- const secretFilePath = wwwAuthHeader.split("Basic realm=")[1];
- if (!SUPPORTED_AZURE_ARC_PLATFORMS.hasOwnProperty(process.platform)) {
- throw createManagedIdentityError(platformNotSupported);
- }
- const expectedSecretFilePath = SUPPORTED_AZURE_ARC_PLATFORMS[process.platform];
- const fileName = path11.basename(secretFilePath);
- if (!fileName.endsWith(".key")) {
- throw createManagedIdentityError(invalidFileExtension);
- }
- if (expectedSecretFilePath + fileName !== secretFilePath) {
- throw createManagedIdentityError(invalidFilePath);
- }
- let secretFileSize;
- try {
- secretFileSize = await statSync4(secretFilePath).size;
- } catch (e4) {
- throw createManagedIdentityError(unableToReadSecretFile);
- }
- if (secretFileSize > AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES) {
- throw createManagedIdentityError(invalidSecret);
- }
- let secret;
- try {
- secret = readFileSync7(secretFilePath, exports_Constants.EncodingTypes.UTF8);
- } catch (e4) {
- throw createManagedIdentityError(unableToReadSecretFile);
- }
- const authHeaderValue = `Basic ${secret}`;
- this.logger.info(`[Managed Identity] Adding authorization header to the request.`, "");
- networkRequest.headers[ManagedIdentityHeaders.AUTHORIZATION_HEADER_NAME] = authHeaderValue;
- try {
- retryResponse = await networkClient.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions);
- } catch (error44) {
- if (error44 instanceof AuthError) {
- throw error44;
- } else {
- throw createClientAuthError(exports_ClientAuthErrorCodes.networkError);
- }
- }
- }
- return this.getServerTokenResponse(retryResponse || originalResponse);
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/CloudShell.mjs
-var CloudShell;
-var init_CloudShell = __esm(() => {
- init_ManagedIdentityRequestParameters();
- init_BaseManagedIdentitySource();
- init_Constants2();
- init_ManagedIdentityError();
- init_ManagedIdentityErrorCodes();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- CloudShell = class CloudShell extends BaseManagedIdentitySource {
- constructor(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint) {
- super(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
- this.msiEndpoint = msiEndpoint;
- }
- static getEnvironmentVariables() {
- const msiEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT];
- return [msiEndpoint];
- }
- static tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) {
- const [msiEndpoint] = CloudShell.getEnvironmentVariables();
- if (!msiEndpoint) {
- logger10.info(`[Managed Identity] ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity is unavailable because the '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT} environment variable is not defined.`, "");
- return null;
- }
- const validatedMsiEndpoint = CloudShell.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT, msiEndpoint, ManagedIdentitySourceNames.CLOUD_SHELL, logger10);
- logger10.info(`[Managed Identity] Environment variable validation passed for ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity. Endpoint URI: ${validatedMsiEndpoint}. Creating ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity.`, "");
- if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
- throw createManagedIdentityError(unableToCreateCloudShell);
- }
- return new CloudShell(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint);
- }
- createRequest(resource) {
- const request2 = new ManagedIdentityRequestParameters(HttpMethod2.POST, this.msiEndpoint);
- request2.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
- request2.bodyParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
- return request2;
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/retry/ExponentialRetryStrategy.mjs
-class ExponentialRetryStrategy {
- constructor(minExponentialBackoff, maxExponentialBackoff, exponentialDeltaBackoff) {
- this.minExponentialBackoff = minExponentialBackoff;
- this.maxExponentialBackoff = maxExponentialBackoff;
- this.exponentialDeltaBackoff = exponentialDeltaBackoff;
- }
- calculateDelay(currentRetry) {
- if (currentRetry === 0) {
- return this.minExponentialBackoff;
- }
- const exponentialDelay = Math.min(Math.pow(2, currentRetry - 1) * this.exponentialDeltaBackoff, this.maxExponentialBackoff);
- return exponentialDelay;
- }
-}
-var init_ExponentialRetryStrategy = __esm(() => {
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/retry/ImdsRetryPolicy.mjs
-class ImdsRetryPolicy {
- constructor() {
- this.exponentialRetryStrategy = new ExponentialRetryStrategy(ImdsRetryPolicy.MIN_EXPONENTIAL_BACKOFF_MS, ImdsRetryPolicy.MAX_EXPONENTIAL_BACKOFF_MS, ImdsRetryPolicy.EXPONENTIAL_DELTA_BACKOFF_MS);
- }
- static get MIN_EXPONENTIAL_BACKOFF_MS() {
- return MIN_EXPONENTIAL_BACKOFF_MS;
- }
- static get MAX_EXPONENTIAL_BACKOFF_MS() {
- return MAX_EXPONENTIAL_BACKOFF_MS;
- }
- static get EXPONENTIAL_DELTA_BACKOFF_MS() {
- return EXPONENTIAL_DELTA_BACKOFF_MS;
- }
- static get HTTP_STATUS_GONE_RETRY_AFTER_MS() {
- return HTTP_STATUS_GONE_RETRY_AFTER_MS;
- }
- set isNewRequest(value) {
- this._isNewRequest = value;
- }
- async pauseForRetry(httpStatusCode, currentRetry, logger10) {
- if (this._isNewRequest) {
- this._isNewRequest = false;
- this.maxRetries = httpStatusCode === exports_Constants.HTTP_GONE ? LINEAR_STRATEGY_NUM_RETRIES : EXPONENTIAL_STRATEGY_NUM_RETRIES;
- }
- if ((HTTP_STATUS_400_CODES_FOR_EXPONENTIAL_STRATEGY.includes(httpStatusCode) || httpStatusCode >= exports_Constants.HTTP_SERVER_ERROR_RANGE_START && httpStatusCode <= exports_Constants.HTTP_SERVER_ERROR_RANGE_END && currentRetry < this.maxRetries) && currentRetry < this.maxRetries) {
- const retryAfterDelay = httpStatusCode === exports_Constants.HTTP_GONE ? ImdsRetryPolicy.HTTP_STATUS_GONE_RETRY_AFTER_MS : this.exponentialRetryStrategy.calculateDelay(currentRetry);
- logger10.verbose(`Retrying request in ${retryAfterDelay}ms (retry attempt: ${currentRetry + 1})`, "");
- await new Promise((resolve9) => {
- return setTimeout(resolve9, retryAfterDelay);
- });
- return true;
- }
- return false;
- }
-}
-var HTTP_STATUS_400_CODES_FOR_EXPONENTIAL_STRATEGY, EXPONENTIAL_STRATEGY_NUM_RETRIES = 3, LINEAR_STRATEGY_NUM_RETRIES = 7, MIN_EXPONENTIAL_BACKOFF_MS = 1000, MAX_EXPONENTIAL_BACKOFF_MS = 4000, EXPONENTIAL_DELTA_BACKOFF_MS = 2000, HTTP_STATUS_GONE_RETRY_AFTER_MS;
-var init_ImdsRetryPolicy = __esm(() => {
- init_index_node();
- init_ExponentialRetryStrategy();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- HTTP_STATUS_400_CODES_FOR_EXPONENTIAL_STRATEGY = [
- exports_Constants.HTTP_NOT_FOUND,
- exports_Constants.HTTP_REQUEST_TIMEOUT,
- exports_Constants.HTTP_GONE,
- exports_Constants.HTTP_TOO_MANY_REQUESTS
- ];
- HTTP_STATUS_GONE_RETRY_AFTER_MS = 10 * 1000;
-});
-
-// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/Imds.mjs
-var IMDS_TOKEN_PATH2 = "/metadata/identity/oauth2/token", DEFAULT_IMDS_ENDPOINT, IMDS_API_VERSION = "2018-02-01", Imds;
-var init_Imds = __esm(() => {
- init_ManagedIdentityRequestParameters();
- init_BaseManagedIdentitySource();
- init_Constants2();
- init_ImdsRetryPolicy();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- DEFAULT_IMDS_ENDPOINT = `http://169.254.169.254${IMDS_TOKEN_PATH2}`;
- Imds = class Imds extends BaseManagedIdentitySource {
- constructor(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint) {
- super(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
- this.identityEndpoint = identityEndpoint;
- }
- static tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
- let validatedIdentityEndpoint;
- if (process.env[ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST]) {
- logger10.info(`[Managed Identity] Environment variable ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} for ${ManagedIdentitySourceNames.IMDS} returned endpoint: ${process.env[ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST]}`, "");
- validatedIdentityEndpoint = Imds.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST, `${process.env[ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST]}${IMDS_TOKEN_PATH2}`, ManagedIdentitySourceNames.IMDS, logger10);
- } else {
- logger10.info(`[Managed Identity] Unable to find ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} environment variable for ${ManagedIdentitySourceNames.IMDS}, using the default endpoint.`, "");
- validatedIdentityEndpoint = DEFAULT_IMDS_ENDPOINT;
- }
- return new Imds(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, validatedIdentityEndpoint);
- }
- createRequest(resource, managedIdentityId) {
- const request2 = new ManagedIdentityRequestParameters(HttpMethod2.GET, this.identityEndpoint);
- request2.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
- request2.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = IMDS_API_VERSION;
- request2.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
- if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
- request2.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType, true)] = managedIdentityId.id;
- }
- request2.retryPolicy = new ImdsRetryPolicy;
- return request2;
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/ServiceFabric.mjs
-var SERVICE_FABRIC_MSI_API_VERSION = "2019-07-01-preview", ServiceFabric;
-var init_ServiceFabric = __esm(() => {
- init_ManagedIdentityRequestParameters();
- init_BaseManagedIdentitySource();
- init_Constants2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- ServiceFabric = class ServiceFabric extends BaseManagedIdentitySource {
- constructor(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader) {
- super(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
- this.identityEndpoint = identityEndpoint;
- this.identityHeader = identityHeader;
- }
- static getEnvironmentVariables() {
- const identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT];
- const identityHeader = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER];
- const identityServerThumbprint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_SERVER_THUMBPRINT];
- return [identityEndpoint, identityHeader, identityServerThumbprint];
- }
- static tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) {
- const [identityEndpoint, identityHeader, identityServerThumbprint] = ServiceFabric.getEnvironmentVariables();
- if (!identityEndpoint || !identityHeader || !identityServerThumbprint) {
- logger10.info(`[Managed Identity] ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity is unavailable because one or all of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}', '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' or '${ManagedIdentityEnvironmentVariableNames.IDENTITY_SERVER_THUMBPRINT}' environment variables are not defined.`, "");
- return null;
- }
- const validatedIdentityEndpoint = ServiceFabric.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.SERVICE_FABRIC, logger10);
- logger10.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity.`, "");
- if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
- logger10.warning(`[Managed Identity] ${ManagedIdentitySourceNames.SERVICE_FABRIC} user assigned managed identity is configured in the cluster, not during runtime. See also: https://learn.microsoft.com/en-us/azure/service-fabric/configure-existing-cluster-enable-managed-identity-token-service.`, "");
- }
- return new ServiceFabric(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader);
- }
- createRequest(resource, managedIdentityId) {
- const request2 = new ManagedIdentityRequestParameters(HttpMethod2.GET, this.identityEndpoint);
- request2.headers[ManagedIdentityHeaders.ML_AND_SF_SECRET_HEADER_NAME] = this.identityHeader;
- request2.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = SERVICE_FABRIC_MSI_API_VERSION;
- request2.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
- if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
- request2.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id;
- }
- return request2;
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/MachineLearning.mjs
-var MACHINE_LEARNING_MSI_API_VERSION = "2017-09-01", MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR, MachineLearning;
-var init_MachineLearning = __esm(() => {
- init_BaseManagedIdentitySource();
- init_Constants2();
- init_ManagedIdentityRequestParameters();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR = `Only client id is supported for user-assigned managed identity in ${ManagedIdentitySourceNames.MACHINE_LEARNING}.`;
- MachineLearning = class MachineLearning extends BaseManagedIdentitySource {
- constructor(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint, secret) {
- super(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
- this.msiEndpoint = msiEndpoint;
- this.secret = secret;
- }
- static getEnvironmentVariables() {
- const msiEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT];
- const secret = process.env[ManagedIdentityEnvironmentVariableNames.MSI_SECRET];
- return [msiEndpoint, secret];
- }
- static tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
- const [msiEndpoint, secret] = MachineLearning.getEnvironmentVariables();
- if (!msiEndpoint || !secret) {
- logger10.info(`[Managed Identity] ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity is unavailable because one or both of the '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT}' and '${ManagedIdentityEnvironmentVariableNames.MSI_SECRET}' environment variables are not defined.`, "");
- return null;
- }
- const validatedMsiEndpoint = MachineLearning.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT, msiEndpoint, ManagedIdentitySourceNames.MACHINE_LEARNING, logger10);
- logger10.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity. Endpoint URI: ${validatedMsiEndpoint}. Creating ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity.`, "");
- return new MachineLearning(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint, secret);
- }
- createRequest(resource, managedIdentityId) {
- const request2 = new ManagedIdentityRequestParameters(HttpMethod2.GET, this.msiEndpoint);
- request2.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
- request2.headers[ManagedIdentityHeaders.ML_AND_SF_SECRET_HEADER_NAME] = this.secret;
- request2.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = MACHINE_LEARNING_MSI_API_VERSION;
- request2.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
- if (managedIdentityId.idType === ManagedIdentityIdType.SYSTEM_ASSIGNED) {
- request2.queryParameters[ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017] = process.env[ManagedIdentityEnvironmentVariableNames.DEFAULT_IDENTITY_CLIENT_ID];
- } else if (managedIdentityId.idType === ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID) {
- request2.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType, false, true)] = managedIdentityId.id;
- } else {
- throw new Error(MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR);
- }
- return request2;
- }
- };
-});
-
-// node_modules/@azure/msal-node/dist/client/ManagedIdentityClient.mjs
-class ManagedIdentityClient {
- constructor(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
- this.logger = logger10;
- this.nodeStorage = nodeStorage;
- this.networkClient = networkClient;
- this.cryptoProvider = cryptoProvider;
- this.disableInternalRetries = disableInternalRetries;
- }
- async sendManagedIdentityTokenRequest(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) {
- if (!ManagedIdentityClient.identitySource) {
- ManagedIdentityClient.identitySource = this.selectManagedIdentitySource(this.logger, this.nodeStorage, this.networkClient, this.cryptoProvider, this.disableInternalRetries, managedIdentityId);
- }
- return ManagedIdentityClient.identitySource.acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken);
- }
- allEnvironmentVariablesAreDefined(environmentVariables) {
- return Object.values(environmentVariables).every((environmentVariable) => {
- return environmentVariable !== undefined;
- });
- }
- getManagedIdentitySource() {
- ManagedIdentityClient.sourceName = this.allEnvironmentVariablesAreDefined(ServiceFabric.getEnvironmentVariables()) ? ManagedIdentitySourceNames.SERVICE_FABRIC : this.allEnvironmentVariablesAreDefined(AppService.getEnvironmentVariables()) ? ManagedIdentitySourceNames.APP_SERVICE : this.allEnvironmentVariablesAreDefined(MachineLearning.getEnvironmentVariables()) ? ManagedIdentitySourceNames.MACHINE_LEARNING : this.allEnvironmentVariablesAreDefined(CloudShell.getEnvironmentVariables()) ? ManagedIdentitySourceNames.CLOUD_SHELL : this.allEnvironmentVariablesAreDefined(AzureArc.getEnvironmentVariables()) ? ManagedIdentitySourceNames.AZURE_ARC : ManagedIdentitySourceNames.DEFAULT_TO_IMDS;
- return ManagedIdentityClient.sourceName;
- }
- selectManagedIdentitySource(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) {
- const source = ServiceFabric.tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || AppService.tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) || MachineLearning.tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) || CloudShell.tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || AzureArc.tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || Imds.tryCreate(logger10, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
- if (!source) {
- throw createManagedIdentityError(unableToCreateSource);
- }
- return source;
- }
-}
-var init_ManagedIdentityClient = __esm(() => {
- init_AppService();
- init_AzureArc();
- init_CloudShell();
- init_Imds();
- init_ServiceFabric();
- init_ManagedIdentityError();
- init_Constants2();
- init_MachineLearning();
- init_ManagedIdentityErrorCodes();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/client/ManagedIdentityApplication.mjs
-class ManagedIdentityApplication {
- constructor(configuration) {
- this.config = buildManagedIdentityConfiguration(configuration || {});
- this.logger = new Logger(this.config.system.loggerOptions, name2, version5);
- const fakeStatusAuthorityOptions = {
- canonicalAuthority: exports_Constants.DEFAULT_AUTHORITY
- };
- if (!ManagedIdentityApplication.nodeStorage) {
- ManagedIdentityApplication.nodeStorage = new NodeStorage(this.logger, this.config.managedIdentityId.id, DEFAULT_CRYPTO_IMPLEMENTATION, fakeStatusAuthorityOptions);
- }
- this.networkClient = this.config.system.networkClient;
- this.cryptoProvider = new CryptoProvider;
- const fakeAuthorityOptions = {
- protocolMode: ProtocolMode.AAD,
- knownAuthorities: [DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY],
- cloudDiscoveryMetadata: "",
- authorityMetadata: ""
- };
- this.fakeAuthority = new Authority(DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY, this.networkClient, ManagedIdentityApplication.nodeStorage, fakeAuthorityOptions, this.logger, this.cryptoProvider.createNewGuid(), new StubPerformanceClient, true);
- this.fakeClientCredentialClient = new ClientCredentialClient({
- authOptions: {
- clientId: this.config.managedIdentityId.id,
- authority: this.fakeAuthority
- }
- });
- this.managedIdentityClient = new ManagedIdentityClient(this.logger, ManagedIdentityApplication.nodeStorage, this.networkClient, this.cryptoProvider, this.config.disableInternalRetries);
- this.hashUtils = new HashUtils;
- }
- async acquireToken(managedIdentityRequestParams) {
- if (!managedIdentityRequestParams.resource) {
- throw createClientConfigurationError(exports_ClientConfigurationErrorCodes.urlEmptyError);
- }
- const managedIdentityRequest = {
- forceRefresh: managedIdentityRequestParams.forceRefresh,
- resource: managedIdentityRequestParams.resource.replace("/.default", ""),
- scopes: [
- managedIdentityRequestParams.resource.replace("/.default", "")
- ],
- authority: this.fakeAuthority.canonicalAuthority,
- correlationId: this.cryptoProvider.createNewGuid(),
- claims: managedIdentityRequestParams.claims,
- clientCapabilities: this.config.clientCapabilities
- };
- if (managedIdentityRequest.forceRefresh) {
- return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority);
- }
- const [cachedAuthenticationResult, lastCacheOutcome] = await this.fakeClientCredentialClient.getCachedAuthenticationResult(managedIdentityRequest, this.config, this.cryptoProvider, this.fakeAuthority, ManagedIdentityApplication.nodeStorage);
- if (managedIdentityRequest.claims) {
- const sourceName = this.managedIdentityClient.getManagedIdentitySource();
- if (cachedAuthenticationResult && SOURCES_THAT_SUPPORT_TOKEN_REVOCATION.includes(sourceName)) {
- const revokedTokenSha256Hash = this.hashUtils.sha256(cachedAuthenticationResult.accessToken).toString(exports_Constants.EncodingTypes.HEX);
- managedIdentityRequest.revokedTokenSha256Hash = revokedTokenSha256Hash;
- }
- return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority);
- }
- if (cachedAuthenticationResult) {
- if (lastCacheOutcome === exports_Constants.CacheOutcome.PROACTIVELY_REFRESHED) {
- this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.", managedIdentityRequest.correlationId);
- const refreshAccessToken = true;
- await this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority, refreshAccessToken);
- }
- return cachedAuthenticationResult;
- } else {
- return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority);
- }
- }
- async acquireTokenFromManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) {
- return this.managedIdentityClient.sendManagedIdentityTokenRequest(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken);
- }
- getManagedIdentitySource() {
- return ManagedIdentityClient.sourceName || this.managedIdentityClient.getManagedIdentitySource();
- }
-}
-var SOURCES_THAT_SUPPORT_TOKEN_REVOCATION;
-var init_ManagedIdentityApplication = __esm(() => {
- init_index_node();
- init_Configuration();
- init_packageMetadata2();
- init_CryptoProvider();
- init_ClientCredentialClient();
- init_ManagedIdentityClient();
- init_NodeStorage();
- init_Constants2();
- init_HashUtils();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- SOURCES_THAT_SUPPORT_TOKEN_REVOCATION = [ManagedIdentitySourceNames.SERVICE_FABRIC];
-});
-
-// node_modules/@azure/msal-node/dist/cache/distributed/DistributedCachePlugin.mjs
-class DistributedCachePlugin {
- constructor(client14, partitionManager) {
- this.client = client14;
- this.partitionManager = partitionManager;
- }
- async beforeCacheAccess(cacheContext) {
- const partitionKey = await this.partitionManager.getKey();
- const cacheData = await this.client.get(partitionKey);
- cacheContext.tokenCache.deserialize(cacheData);
- }
- async afterCacheAccess(cacheContext) {
- if (cacheContext.cacheHasChanged) {
- const kvStore = cacheContext.tokenCache.getKVStore();
- const accountEntities = Object.values(kvStore).filter((value) => exports_AccountEntityUtils.isAccountEntity(value));
- let partitionKey;
- if (accountEntities.length > 0) {
- const accountEntity = accountEntities[0];
- partitionKey = await this.partitionManager.extractKey(accountEntity);
- } else {
- partitionKey = await this.partitionManager.getKey();
- }
- await this.client.set(partitionKey, cacheContext.tokenCache.serialize());
- }
- }
-}
-var init_DistributedCachePlugin = __esm(() => {
- init_index_node();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
-});
-
-// node_modules/@azure/msal-node/dist/index.mjs
-var exports_dist = {};
-__export(exports_dist, {
- version: () => version5,
- internals: () => exports_internals,
- TokenCacheContext: () => TokenCacheContext,
- TokenCache: () => TokenCache,
- ServerError: () => ServerError,
- ResponseMode: () => ResponseMode2,
- PublicClientApplication: () => PublicClientApplication,
- ProtocolMode: () => ProtocolMode,
- PromptValue: () => PromptValue2,
- ManagedIdentitySourceNames: () => ManagedIdentitySourceNames,
- ManagedIdentityApplication: () => ManagedIdentityApplication,
- Logger: () => Logger,
- LogLevel: () => LogLevel,
- InteractionRequiredAuthErrorCodes: () => exports_InteractionRequiredAuthErrorCodes,
- InteractionRequiredAuthError: () => InteractionRequiredAuthError,
- DistributedCachePlugin: () => DistributedCachePlugin,
- CryptoProvider: () => CryptoProvider,
- ConfidentialClientApplication: () => ConfidentialClientApplication,
- ClientConfigurationErrorCodes: () => exports_ClientConfigurationErrorCodes,
- ClientConfigurationError: () => ClientConfigurationError,
- ClientAuthErrorCodes: () => exports_ClientAuthErrorCodes,
- ClientAuthError: () => ClientAuthError,
- ClientAssertion: () => ClientAssertion,
- AzureCloudInstance: () => AzureCloudInstance,
- AuthErrorCodes: () => exports_AuthErrorCodes,
- AuthError: () => AuthError
-});
-var PromptValue2, ResponseMode2;
-var init_dist = __esm(() => {
- init_internals();
- init_index_node();
- init_index_node();
- init_PublicClientApplication();
- init_ConfidentialClientApplication();
- init_ManagedIdentityApplication();
- init_ClientAssertion();
- init_TokenCache();
- init_DistributedCachePlugin();
- init_Constants2();
- init_CryptoProvider();
- init_packageMetadata2();
- /*! @azure/msal-node v5.1.1 2026-03-18 */
- PromptValue2 = exports_Constants.PromptValue;
- ResponseMode2 = exports_Constants.ResponseMode;
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/random.js
-function getRandomIntegerInclusive(min, max) {
- min = Math.ceil(min);
- max = Math.floor(max);
- const offset = Math.floor(Math.random() * (max - min + 1));
- return offset + min;
-}
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/delay.js
-function calculateRetryDelay(retryAttempt, config8) {
- const exponentialDelay = config8.retryDelayInMs * Math.pow(2, retryAttempt);
- const clampedDelay = Math.min(config8.maxRetryDelayInMs, exponentialDelay);
- const retryAfterInMs = clampedDelay / 2 + getRandomIntegerInclusive(0, clampedDelay / 2);
- return { retryAfterInMs };
-}
-var init_delay = () => {};
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/object.js
-function isObject5(input) {
- return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date);
-}
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/error.js
-function isError(e4) {
- if (isObject5(e4)) {
- const hasName = typeof e4.name === "string";
- const hasMessage = typeof e4.message === "string";
- return hasName && hasMessage;
- }
- return false;
-}
-var init_error9 = () => {};
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/uuidUtils.js
-function randomUUID2() {
- return crypto.randomUUID();
-}
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/checkEnvironment.js
-var isBrowser2, isWebWorker, isDeno, isBun, isNodeLike, isReactNative2;
-var init_checkEnvironment = __esm(() => {
- isBrowser2 = typeof window !== "undefined" && typeof window.document !== "undefined";
- isWebWorker = typeof self === "object" && typeof self?.importScripts === "function" && (self.constructor?.name === "DedicatedWorkerGlobalScope" || self.constructor?.name === "ServiceWorkerGlobalScope" || self.constructor?.name === "SharedWorkerGlobalScope");
- isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined";
- isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
- isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean(globalThis.process.versions?.node);
- isReactNative2 = typeof navigator !== "undefined" && navigator?.product === "ReactNative";
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/bytesEncoding.js
-function stringToUint8Array2(value, format3) {
- return Buffer.from(value, format3);
-}
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/sanitizer.js
-class Sanitizer {
- allowedHeaderNames;
- allowedQueryParameters;
- constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) {
- allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
- allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
- this.allowedHeaderNames = new Set(allowedHeaderNames.map((n5) => n5.toLowerCase()));
- this.allowedQueryParameters = new Set(allowedQueryParameters.map((p4) => p4.toLowerCase()));
- }
- sanitize(obj) {
- const seen = new Set;
- return JSON.stringify(obj, (key, value) => {
- if (value instanceof Error) {
- return {
- ...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") {
- return;
- } else if (key === "response") {
- return;
- } else if (key === "operationSpec") {
- return;
- } else if (Array.isArray(value) || isObject5(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 url3 = new URL(value);
- if (!url3.search) {
- return value;
- }
- for (const [key] of url3.searchParams) {
- if (!this.allowedQueryParameters.has(key.toLowerCase())) {
- url3.searchParams.set(key, RedactedString);
- }
- }
- return url3.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 k4 of Object.keys(value)) {
- if (this.allowedQueryParameters.has(k4.toLowerCase())) {
- sanitized[k4] = value[k4];
- } else {
- sanitized[k4] = RedactedString;
- }
- }
- return sanitized;
- }
-}
-var RedactedString = "REDACTED", defaultAllowedHeaderNames, defaultAllowedQueryParameters;
-var init_sanitizer = __esm(() => {
- 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"
- ];
- defaultAllowedQueryParameters = ["api-version"];
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/internal.js
-var init_internal2 = __esm(() => {
- init_delay();
- init_error9();
- init_checkEnvironment();
- init_sanitizer();
-});
-
-// node_modules/@azure/abort-controller/dist/esm/AbortError.js
-var AbortError2;
-var init_AbortError = __esm(() => {
- AbortError2 = class AbortError2 extends Error {
- constructor(message) {
- super(message);
- this.name = "AbortError";
- }
- };
-});
-
-// node_modules/@azure/abort-controller/dist/esm/index.js
-var init_esm4 = __esm(() => {
- init_AbortError();
-});
-
-// node_modules/@azure/core-util/dist/esm/createAbortablePromise.js
-function createAbortablePromise(buildPromise, options2) {
- const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options2 ?? {};
- return new Promise((resolve9, reject) => {
- function rejectOnAbort() {
- reject(new AbortError2(abortErrorMsg ?? "The operation was aborted."));
- }
- function removeListeners() {
- abortSignal?.removeEventListener("abort", onAbort);
- }
- function onAbort() {
- cleanupBeforeAbort?.();
- removeListeners();
- rejectOnAbort();
- }
- if (abortSignal?.aborted) {
- return rejectOnAbort();
- }
- try {
- buildPromise((x3) => {
- removeListeners();
- resolve9(x3);
- }, (x3) => {
- removeListeners();
- reject(x3);
- });
- } catch (err) {
- reject(err);
- }
- abortSignal?.addEventListener("abort", onAbort);
- });
-}
-var init_createAbortablePromise = __esm(() => {
- init_esm4();
-});
-
-// node_modules/@azure/core-util/dist/esm/delay.js
-function delay2(timeInMs, options2) {
- let token;
- const { abortSignal, abortErrorMsg } = options2 ?? {};
- return createAbortablePromise((resolve9) => {
- token = setTimeout(resolve9, timeInMs);
- }, {
- cleanupBeforeAbort: () => clearTimeout(token),
- abortSignal,
- abortErrorMsg: abortErrorMsg ?? StandardAbortMessage
- });
-}
-var StandardAbortMessage = "The delay was aborted.";
-var init_delay2 = __esm(() => {
- init_createAbortablePromise();
-});
-
-// node_modules/@azure/core-util/dist/esm/error.js
-function getErrorMessage2(e4) {
- if (isError(e4)) {
- return e4.message;
- } else {
- let stringified;
- try {
- if (typeof e4 === "object" && e4) {
- stringified = JSON.stringify(e4);
- } else {
- stringified = String(e4);
- }
- } catch (err) {
- stringified = "[unable to stringify input]";
- }
- return `Unknown error ${stringified}`;
- }
-}
-var init_error10 = __esm(() => {
- init_internal2();
-});
-
-// node_modules/@azure/core-util/dist/esm/index.js
-function calculateRetryDelay2(retryAttempt, config8) {
- return calculateRetryDelay(retryAttempt, config8);
-}
-function isError2(e4) {
- return isError(e4);
-}
-var isNode, isNodeLike2;
-var init_esm5 = __esm(() => {
- init_internal2();
- init_delay2();
- init_error10();
- isNode = isNodeLike;
- isNodeLike2 = isNodeLike;
-});
-
-// node_modules/@azure/identity/dist/esm/msal/msal.js
-var init_msal = __esm(() => {
- init_dist();
-});
-
-// node_modules/@azure/identity/dist/esm/msal/utils.js
-function ensureValidMsalToken(scopes, msalToken, getTokenOptions) {
- const error44 = (message) => {
- logger10.getToken.info(message);
- return new AuthenticationRequiredError({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- getTokenOptions,
- message
- });
- };
- if (!msalToken) {
- throw error44("No response");
- }
- if (!msalToken.expiresOn) {
- throw error44(`Response had no "expiresOn" property.`);
- }
- if (!msalToken.accessToken) {
- throw error44(`Response had no "accessToken" property.`);
- }
-}
-function getAuthorityHost(options2) {
- let authorityHost = options2?.authorityHost;
- if (!authorityHost && isNodeLike2) {
- authorityHost = process.env.AZURE_AUTHORITY_HOST;
- }
- return authorityHost ?? DefaultAuthorityHost;
-}
-function getAuthority(tenantId, host) {
- if (!host) {
- host = DefaultAuthorityHost;
- }
- if (new RegExp(`${tenantId}/?$`).test(host)) {
- return host;
- }
- if (host.endsWith("/")) {
- return host + tenantId;
- } else {
- return `${host}/${tenantId}`;
- }
-}
-function getKnownAuthorities(tenantId, authorityHost, disableInstanceDiscovery) {
- if (tenantId === "adfs" && authorityHost || disableInstanceDiscovery) {
- return [authorityHost];
- }
- return [];
-}
-function getMSALLogLevel(logLevel) {
- switch (logLevel) {
- case "error":
- return exports_dist.LogLevel.Error;
- case "info":
- return exports_dist.LogLevel.Info;
- case "verbose":
- return exports_dist.LogLevel.Verbose;
- case "warning":
- return exports_dist.LogLevel.Warning;
- default:
- return exports_dist.LogLevel.Info;
- }
-}
-function handleMsalError(scopes, error44, getTokenOptions) {
- if (error44.name === "AuthError" || error44.name === "ClientAuthError" || error44.name === "BrowserAuthError") {
- const msalError = error44;
- switch (msalError.errorCode) {
- case "endpoints_resolution_error":
- logger10.info(formatError2(scopes, error44.message));
- return new CredentialUnavailableError(error44.message);
- case "device_code_polling_cancelled":
- return new AbortError2("The authentication has been aborted by the caller.");
- case "consent_required":
- case "interaction_required":
- case "login_required":
- logger10.info(formatError2(scopes, `Authentication returned errorCode ${msalError.errorCode}`));
- break;
- default:
- logger10.info(formatError2(scopes, `Failed to acquire token: ${error44.message}`));
- break;
- }
- }
- if (error44.name === "ClientConfigurationError" || error44.name === "BrowserConfigurationAuthError" || error44.name === "AbortError" || error44.name === "AuthenticationError") {
- return error44;
- }
- if (error44.name === "NativeAuthError") {
- logger10.info(formatError2(scopes, `Error from the native broker: ${error44.message} with status code: ${error44.statusCode}`));
- return error44;
- }
- return new AuthenticationRequiredError({ scopes, getTokenOptions, message: error44.message });
-}
-function publicToMsal(account) {
- return {
- localAccountId: account.homeAccountId,
- environment: account.authority,
- username: account.username,
- homeAccountId: account.homeAccountId,
- tenantId: account.tenantId
- };
-}
-function msalToPublic(clientId, account) {
- const record2 = {
- authority: account.environment ?? DefaultAuthority,
- homeAccountId: account.homeAccountId,
- tenantId: account.tenantId || DefaultTenantId,
- username: account.username,
- clientId,
- version: LatestAuthenticationRecordVersion
- };
- return record2;
-}
-function serializeAuthenticationRecord(record2) {
- return JSON.stringify(record2);
-}
-function deserializeAuthenticationRecord(serializedRecord) {
- const parsed = JSON.parse(serializedRecord);
- if (parsed.version && parsed.version !== LatestAuthenticationRecordVersion) {
- throw Error("Unsupported AuthenticationRecord version");
- }
- return parsed;
-}
-var logger10, LatestAuthenticationRecordVersion = "1.0", defaultLoggerCallback = (credLogger, platform2 = isNode ? "Node" : "Browser") => (level, message, containsPii) => {
- if (containsPii) {
- return;
- }
- switch (level) {
- case exports_dist.LogLevel.Error:
- credLogger.info(`MSAL ${platform2} V2 error: ${message}`);
- return;
- case exports_dist.LogLevel.Info:
- credLogger.info(`MSAL ${platform2} V2 info message: ${message}`);
- return;
- case exports_dist.LogLevel.Verbose:
- credLogger.info(`MSAL ${platform2} V2 verbose message: ${message}`);
- return;
- case exports_dist.LogLevel.Warning:
- credLogger.info(`MSAL ${platform2} V2 warning: ${message}`);
- return;
- }
-};
-var init_utils4 = __esm(() => {
- init_errors7();
- init_logging();
- init_constants9();
- init_esm5();
- init_esm4();
- init_msal();
- logger10 = credentialLogger("IdentityUtils");
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/httpHeaders.js
-function normalizeName(name3) {
- return name3.toLowerCase();
-}
-function* headerIterator(map7) {
- for (const entry of map7.values()) {
- yield [entry.name, entry.value];
- }
-}
-function createHttpHeaders(rawHeaders) {
- return new HttpHeadersImpl(rawHeaders);
-}
-var HttpHeadersImpl;
-var init_httpHeaders = __esm(() => {
- HttpHeadersImpl = class HttpHeadersImpl {
- _headersMap;
- constructor(rawHeaders) {
- this._headersMap = new Map;
- if (rawHeaders) {
- for (const headerName of Object.keys(rawHeaders)) {
- this.set(headerName, rawHeaders[headerName]);
- }
- }
- }
- set(name3, value) {
- this._headersMap.set(normalizeName(name3), { name: name3, value: String(value).trim() });
- }
- get(name3) {
- return this._headersMap.get(normalizeName(name3))?.value;
- }
- has(name3) {
- return this._headersMap.has(normalizeName(name3));
- }
- delete(name3) {
- this._headersMap.delete(normalizeName(name3));
- }
- toJSON(options2 = {}) {
- const result = {};
- if (options2.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;
- }
- toString() {
- return JSON.stringify(this.toJSON({ preserveCase: true }));
- }
- [Symbol.iterator]() {
- return headerIterator(this._headersMap);
- }
- };
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/pipelineRequest.js
-class PipelineRequestImpl {
- url;
- method;
- headers;
- timeout;
- withCredentials;
- body;
- multipartBody;
- formData;
- streamResponseStatusCodes;
- enableBrowserStreams;
- proxySettings;
- disableKeepAlive;
- abortSignal;
- requestId;
- allowInsecureConnection;
- onUploadProgress;
- onDownloadProgress;
- requestOverrides;
- authSchemes;
- constructor(options2) {
- this.url = options2.url;
- this.body = options2.body;
- this.headers = options2.headers ?? createHttpHeaders();
- this.method = options2.method ?? "GET";
- this.timeout = options2.timeout ?? 0;
- this.multipartBody = options2.multipartBody;
- this.formData = options2.formData;
- this.disableKeepAlive = options2.disableKeepAlive ?? false;
- this.proxySettings = options2.proxySettings;
- this.streamResponseStatusCodes = options2.streamResponseStatusCodes;
- this.withCredentials = options2.withCredentials ?? false;
- this.abortSignal = options2.abortSignal;
- this.onUploadProgress = options2.onUploadProgress;
- this.onDownloadProgress = options2.onDownloadProgress;
- this.requestId = options2.requestId || randomUUID2();
- this.allowInsecureConnection = options2.allowInsecureConnection ?? false;
- this.enableBrowserStreams = options2.enableBrowserStreams ?? false;
- this.requestOverrides = options2.requestOverrides;
- this.authSchemes = options2.authSchemes;
- }
-}
-function createPipelineRequest(options2) {
- return new PipelineRequestImpl(options2);
-}
-var init_pipelineRequest = __esm(() => {
- init_httpHeaders();
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/pipeline.js
-class HttpPipeline {
- _policies = [];
- _orderedPolicies;
- constructor(policies) {
- this._policies = policies?.slice(0) ?? [];
- this._orderedPolicies = undefined;
- }
- addPolicy(policy, options2 = {}) {
- if (options2.phase && options2.afterPhase) {
- throw new Error("Policies inside a phase cannot specify afterPhase.");
- }
- if (options2.phase && !ValidPhaseNames.has(options2.phase)) {
- throw new Error(`Invalid phase name: ${options2.phase}`);
- }
- if (options2.afterPhase && !ValidPhaseNames.has(options2.afterPhase)) {
- throw new Error(`Invalid afterPhase name: ${options2.afterPhase}`);
- }
- this._policies.push({
- policy,
- options: options2
- });
- this._orderedPolicies = undefined;
- }
- removePolicy(options2) {
- const removedPolicies = [];
- this._policies = this._policies.filter((policyDescriptor) => {
- if (options2.name && policyDescriptor.policy.name === options2.name || options2.phase && policyDescriptor.options.phase === options2.phase) {
- removedPolicies.push(policyDescriptor.policy);
- return false;
- } else {
- return true;
- }
- });
- this._orderedPolicies = undefined;
- return removedPolicies;
- }
- sendRequest(httpClient, request2) {
- const policies = this.getOrderedPolicies();
- const pipeline2 = policies.reduceRight((next, policy) => {
- return (req) => {
- return policy.sendRequest(req, next);
- };
- }, (req) => httpClient.sendRequest(req));
- return pipeline2(request2);
- }
- getOrderedPolicies() {
- if (!this._orderedPolicies) {
- this._orderedPolicies = this.orderPolicies();
- }
- return this._orderedPolicies;
- }
- clone() {
- return new HttpPipeline(this._policies);
- }
- static create() {
- return new HttpPipeline;
- }
- orderPolicies() {
- const result = [];
- const policyMap = new Map;
- function createPhase(name3) {
- return {
- name: name3,
- policies: new Set,
- hasRun: false,
- hasAfterPolicies: false
- };
- }
- const serializePhase = createPhase("Serialize");
- const noPhase = createPhase("None");
- const deserializePhase = createPhase("Deserialize");
- const retryPhase = createPhase("Retry");
- const signPhase = createPhase("Sign");
- const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];
- 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;
- }
- }
- for (const descriptor of this._policies) {
- const policy = descriptor.policy;
- const options2 = 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 (options2.afterPhase) {
- node.afterPhase = getPhase(options2.afterPhase);
- node.afterPhase.hasAfterPolicies = true;
- }
- policyMap.set(policyName, node);
- const phase = getPhase(options2.phase);
- phase.policies.add(node);
- }
- for (const descriptor of this._policies) {
- const { policy, options: options2 } = descriptor;
- const policyName = policy.name;
- const node = policyMap.get(policyName);
- if (!node) {
- throw new Error(`Missing node for policy ${policyName}`);
- }
- if (options2.afterPolicies) {
- for (const afterPolicyName of options2.afterPolicies) {
- const afterNode = policyMap.get(afterPolicyName);
- if (afterNode) {
- node.dependsOn.add(afterNode);
- afterNode.dependants.add(node);
- }
- }
- }
- if (options2.beforePolicies) {
- for (const beforePolicyName of options2.beforePolicies) {
- const beforeNode = policyMap.get(beforePolicyName);
- if (beforeNode) {
- beforeNode.dependsOn.add(node);
- node.dependants.add(beforeNode);
- }
- }
- }
- }
- function walkPhase(phase) {
- phase.hasRun = true;
- for (const node of phase.policies) {
- if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {
- continue;
- }
- if (node.dependsOn.size === 0) {
- result.push(node.policy);
- 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 (phase.policies.size > 0 && phase !== noPhase) {
- if (!noPhase.hasRun) {
- walkPhase(noPhase);
- }
- return;
- }
- if (phase.hasAfterPolicies) {
- walkPhase(noPhase);
- }
- }
- }
- let iteration = 0;
- while (policyMap.size > 0) {
- iteration++;
- const initialResultLength = result.length;
- walkPhases();
- if (result.length <= initialResultLength && iteration > 1) {
- throw new Error("Cannot satisfy policy dependencies due to requirements cycle.");
- }
- }
- return result;
- }
-}
-function createEmptyPipeline() {
- return HttpPipeline.create();
-}
-var ValidPhaseNames;
-var init_pipeline2 = __esm(() => {
- ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]);
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/inspect.js
-import { inspect as inspect3 } from "util";
-var custom2;
-var init_inspect = __esm(() => {
- custom2 = inspect3.custom;
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/restError.js
-function isRestError(e4) {
- if (e4 instanceof RestError) {
- return true;
- }
- return isError(e4) && e4.name === "RestError";
-}
-var errorSanitizer, RestError;
-var init_restError = __esm(() => {
- init_error9();
- init_inspect();
- init_sanitizer();
- errorSanitizer = new Sanitizer;
- RestError = class RestError extends Error {
- static REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
- static PARSE_ERROR = "PARSE_ERROR";
- code;
- statusCode;
- request;
- response;
- details;
- constructor(message, options2 = {}) {
- super(message);
- this.name = "RestError";
- this.code = options2.code;
- this.statusCode = options2.statusCode;
- Object.defineProperty(this, "request", { value: options2.request, enumerable: false });
- Object.defineProperty(this, "response", { value: options2.response, enumerable: false });
- const agent = this.request?.agent ? {
- maxFreeSockets: this.request.agent.maxFreeSockets,
- maxSockets: this.request.agent.maxSockets
- } : undefined;
- Object.defineProperty(this, custom2, {
- value: () => {
- return `RestError: ${this.message}
- ${errorSanitizer.sanitize({
- ...this,
- request: { ...this.request, agent },
- response: this.response
- })}`;
- },
- enumerable: false
- });
- Object.setPrototypeOf(this, RestError.prototype);
- }
- };
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/abort-controller/AbortError.js
-var AbortError3;
-var init_AbortError2 = __esm(() => {
- AbortError3 = class AbortError3 extends Error {
- constructor(message) {
- super(message);
- this.name = "AbortError";
- }
- };
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/log.js
-var logger11;
-var init_log8 = __esm(() => {
- init_logger7();
- logger11 = createClientLogger("ts-http-runtime");
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js
-import http11 from "http";
-import https2 from "https";
-import zlib2 from "zlib";
-import { Transform as Transform3 } from "stream";
-function isReadableStream4(body) {
- return body && typeof body.pipe === "function";
-}
-function isStreamComplete(stream10) {
- if (stream10.readable === false) {
- return Promise.resolve();
- }
- return new Promise((resolve9) => {
- const handler = () => {
- resolve9();
- stream10.removeListener("close", handler);
- stream10.removeListener("end", handler);
- stream10.removeListener("error", handler);
- };
- stream10.on("close", handler);
- stream10.on("end", handler);
- stream10.on("error", handler);
- });
-}
-function isArrayBuffer8(body) {
- return body && typeof body.byteLength === "number";
-}
-
-class NodeHttpClient {
- cachedHttpAgent;
- cachedHttpsAgents = new WeakMap;
- async sendRequest(request2) {
- const abortController = new AbortController;
- let abortListener;
- if (request2.abortSignal) {
- if (request2.abortSignal.aborted) {
- throw new AbortError3("The operation was aborted. Request has already been canceled.");
- }
- abortListener = (event) => {
- if (event.type === "abort") {
- abortController.abort();
- }
- };
- request2.abortSignal.addEventListener("abort", abortListener);
- }
- let timeoutId;
- if (request2.timeout > 0) {
- timeoutId = setTimeout(() => {
- const sanitizer = new Sanitizer;
- logger11.info(`request to '${sanitizer.sanitizeUrl(request2.url)}' timed out. canceling...`);
- abortController.abort();
- }, request2.timeout);
- }
- const acceptEncoding = request2.headers.get("Accept-Encoding");
- const shouldDecompress = acceptEncoding?.includes("gzip") || acceptEncoding?.includes("deflate");
- let body = typeof request2.body === "function" ? request2.body() : request2.body;
- if (body && !request2.headers.has("Content-Length")) {
- const bodyLength = getBodyLength(body);
- if (bodyLength !== null) {
- request2.headers.set("Content-Length", bodyLength);
- }
- }
- let responseStream;
- try {
- if (body && request2.onUploadProgress) {
- const onUploadProgress = request2.onUploadProgress;
- const uploadReportStream = new ReportTransform(onUploadProgress);
- uploadReportStream.on("error", (e4) => {
- logger11.error("Error in upload progress", e4);
- });
- if (isReadableStream4(body)) {
- body.pipe(uploadReportStream);
- } else {
- uploadReportStream.end(body);
- }
- body = uploadReportStream;
- }
- const res = await this.makeRequest(request2, abortController, body);
- if (timeoutId !== undefined) {
- clearTimeout(timeoutId);
- }
- const headers = getResponseHeaders(res);
- const status = res.statusCode ?? 0;
- const response7 = {
- status,
- headers,
- request: request2
- };
- if (request2.method === "HEAD") {
- res.resume();
- return response7;
- }
- responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
- const onDownloadProgress = request2.onDownloadProgress;
- if (onDownloadProgress) {
- const downloadReportStream = new ReportTransform(onDownloadProgress);
- downloadReportStream.on("error", (e4) => {
- logger11.error("Error in download progress", e4);
- });
- responseStream.pipe(downloadReportStream);
- responseStream = downloadReportStream;
- }
- if (request2.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) || request2.streamResponseStatusCodes?.has(response7.status)) {
- response7.readableStreamBody = responseStream;
- } else {
- response7.bodyAsText = await streamToText(responseStream);
- }
- return response7;
- } finally {
- if (request2.abortSignal && abortListener) {
- let uploadStreamDone = Promise.resolve();
- if (isReadableStream4(body)) {
- uploadStreamDone = isStreamComplete(body);
- }
- let downloadStreamDone = Promise.resolve();
- if (isReadableStream4(responseStream)) {
- downloadStreamDone = isStreamComplete(responseStream);
- }
- Promise.all([uploadStreamDone, downloadStreamDone]).then(() => {
- if (abortListener) {
- request2.abortSignal?.removeEventListener("abort", abortListener);
- }
- }).catch((e4) => {
- logger11.warning("Error when cleaning up abortListener on httpRequest", e4);
- });
- }
- }
- }
- makeRequest(request2, abortController, body) {
- const url3 = new URL(request2.url);
- const isInsecure = url3.protocol !== "https:";
- if (isInsecure && !request2.allowInsecureConnection) {
- throw new Error(`Cannot connect to ${request2.url} while allowInsecureConnection is false.`);
- }
- const agent = request2.agent ?? this.getOrCreateAgent(request2, isInsecure);
- const options2 = {
- agent,
- hostname: url3.hostname,
- path: `${url3.pathname}${url3.search}`,
- port: url3.port,
- method: request2.method,
- headers: request2.headers.toJSON({ preserveCase: true }),
- ...request2.requestOverrides
- };
- return new Promise((resolve9, reject) => {
- const req = isInsecure ? http11.request(options2, resolve9) : https2.request(options2, resolve9);
- req.once("error", (err) => {
- reject(new RestError(err.message, { code: err.code ?? RestError.REQUEST_SEND_ERROR, request: request2 }));
- });
- abortController.signal.addEventListener("abort", () => {
- const abortError = new AbortError3("The operation was aborted. Rejecting from abort signal callback while making request.");
- req.destroy(abortError);
- reject(abortError);
- });
- if (body && isReadableStream4(body)) {
- body.pipe(req);
- } else if (body) {
- if (typeof body === "string" || Buffer.isBuffer(body)) {
- req.end(body);
- } else if (isArrayBuffer8(body)) {
- req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));
- } else {
- logger11.error("Unrecognized body type", body);
- reject(new RestError("Unrecognized body type"));
- }
- } else {
- req.end();
- }
- });
- }
- getOrCreateAgent(request2, isInsecure) {
- const disableKeepAlive2 = request2.disableKeepAlive;
- if (isInsecure) {
- if (disableKeepAlive2) {
- return http11.globalAgent;
- }
- if (!this.cachedHttpAgent) {
- this.cachedHttpAgent = new http11.Agent({ keepAlive: true });
- }
- return this.cachedHttpAgent;
- } else {
- if (disableKeepAlive2 && !request2.tlsSettings) {
- return https2.globalAgent;
- }
- const tlsSettings = request2.tlsSettings ?? DEFAULT_TLS_SETTINGS;
- let agent = this.cachedHttpsAgents.get(tlsSettings);
- if (agent && agent.options.keepAlive === !disableKeepAlive2) {
- return agent;
- }
- logger11.info("No cached TLS Agent exist, creating a new Agent");
- agent = new https2.Agent({
- keepAlive: !disableKeepAlive2,
- ...tlsSettings
- });
- this.cachedHttpsAgents.set(tlsSettings, agent);
- return agent;
- }
- }
-}
-function getResponseHeaders(res) {
- const headers = 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);
- }
- }
- return headers;
-}
-function getDecodedResponseStream(stream10, headers) {
- const contentEncoding = headers.get("Content-Encoding");
- if (contentEncoding === "gzip") {
- const unzip = zlib2.createGunzip();
- stream10.pipe(unzip);
- return unzip;
- } else if (contentEncoding === "deflate") {
- const inflate = zlib2.createInflate();
- stream10.pipe(inflate);
- return inflate;
- }
- return stream10;
-}
-function streamToText(stream10) {
- return new Promise((resolve9, reject) => {
- const buffer = [];
- stream10.on("data", (chunk) => {
- if (Buffer.isBuffer(chunk)) {
- buffer.push(chunk);
- } else {
- buffer.push(Buffer.from(chunk));
- }
- });
- stream10.on("end", () => {
- resolve9(Buffer.concat(buffer).toString("utf8"));
- });
- stream10.on("error", (e4) => {
- if (e4 && e4?.name === "AbortError") {
- reject(e4);
- } else {
- reject(new RestError(`Error reading response as text: ${e4.message}`, {
- code: RestError.PARSE_ERROR
- }));
- }
- });
- });
-}
-function getBodyLength(body) {
- if (!body) {
- return 0;
- } else if (Buffer.isBuffer(body)) {
- return body.length;
- } else if (isReadableStream4(body)) {
- return null;
- } else if (isArrayBuffer8(body)) {
- return body.byteLength;
- } else if (typeof body === "string") {
- return Buffer.from(body).length;
- } else {
- return null;
- }
-}
-function createNodeHttpClient() {
- return new NodeHttpClient;
-}
-var DEFAULT_TLS_SETTINGS, ReportTransform;
-var init_nodeHttpClient = __esm(() => {
- init_AbortError2();
- init_httpHeaders();
- init_restError();
- init_log8();
- init_sanitizer();
- DEFAULT_TLS_SETTINGS = {};
- ReportTransform = class ReportTransform extends Transform3 {
- loadedBytes = 0;
- progressCallback;
- _transform(chunk, _encoding, callback) {
- this.push(chunk);
- this.loadedBytes += chunk.length;
- try {
- this.progressCallback({ loadedBytes: this.loadedBytes });
- callback();
- } catch (e4) {
- callback(e4);
- }
- }
- constructor(progressCallback) {
- super();
- this.progressCallback = progressCallback;
- }
- };
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/defaultHttpClient.js
-function createDefaultHttpClient() {
- return createNodeHttpClient();
-}
-var init_defaultHttpClient = __esm(() => {
- init_nodeHttpClient();
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/index.js
-var init_esm6 = __esm(() => {
- init_httpHeaders();
- init_pipelineRequest();
- init_pipeline2();
- init_restError();
- init_defaultHttpClient();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/pipeline.js
-function createEmptyPipeline2() {
- return createEmptyPipeline();
-}
-var init_pipeline3 = __esm(() => {
- init_esm6();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/log.js
-var logger12;
-var init_log9 = __esm(() => {
- init_esm2();
- logger12 = createClientLogger2("core-rest-pipeline");
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/policies/agentPolicy.js
-function agentPolicy(agent) {
- return {
- name: agentPolicyName,
- sendRequest: async (req, next) => {
- if (!req.agent) {
- req.agent = agent;
- }
- return next(req);
- }
- };
-}
-var agentPolicyName = "agentPolicy";
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/policies/decompressResponsePolicy.js
-function decompressResponsePolicy() {
- return {
- name: decompressResponsePolicyName,
- async sendRequest(request2, next) {
- if (request2.method !== "HEAD") {
- request2.headers.set("Accept-Encoding", "gzip,deflate");
- }
- return next(request2);
- }
- };
-}
-var decompressResponsePolicyName = "decompressResponsePolicy";
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/helpers.js
-function delay3(delayInMs, value, options2) {
- return new Promise((resolve9, reject) => {
- let timer = undefined;
- let onAborted = undefined;
- const rejectOnAbort = () => {
- return reject(new AbortError3(options2?.abortErrorMsg ? options2?.abortErrorMsg : StandardAbortMessage2));
- };
- const removeListeners = () => {
- if (options2?.abortSignal && onAborted) {
- options2.abortSignal.removeEventListener("abort", onAborted);
- }
- };
- onAborted = () => {
- if (timer) {
- clearTimeout(timer);
- }
- removeListeners();
- return rejectOnAbort();
- };
- if (options2?.abortSignal && options2.abortSignal.aborted) {
- return rejectOnAbort();
- }
- timer = setTimeout(() => {
- removeListeners();
- resolve9(value);
- }, delayInMs);
- if (options2?.abortSignal) {
- options2.abortSignal.addEventListener("abort", onAborted);
- }
- });
-}
-function parseHeaderValueAsNumber(response7, headerName) {
- const value = response7.headers.get(headerName);
- if (!value)
- return;
- const valueAsNum = Number(value);
- if (Number.isNaN(valueAsNum))
- return;
- return valueAsNum;
-}
-var StandardAbortMessage2 = "The operation was aborted.";
-var init_helpers = __esm(() => {
- init_AbortError2();
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/throttlingRetryStrategy.js
-function getRetryAfterInMs(response7) {
- if (!(response7 && [429, 503].includes(response7.status)))
- return;
- try {
- for (const header of AllRetryAfterHeaders) {
- const retryAfterValue = parseHeaderValueAsNumber(response7, header);
- if (retryAfterValue === 0 || retryAfterValue) {
- const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1;
- return retryAfterValue * multiplyingFactor;
- }
- }
- const retryAfterHeader = response7.headers.get(RetryAfterHeader);
- if (!retryAfterHeader)
- return;
- const date5 = Date.parse(retryAfterHeader);
- const diff = date5 - Date.now();
- return Number.isFinite(diff) ? Math.max(0, diff) : undefined;
- } catch {
- return;
- }
-}
-function isThrottlingRetryResponse(response7) {
- return Number.isFinite(getRetryAfterInMs(response7));
-}
-function throttlingRetryStrategy() {
- return {
- name: "throttlingRetryStrategy",
- retry({ response: response7 }) {
- const retryAfterInMs = getRetryAfterInMs(response7);
- if (!Number.isFinite(retryAfterInMs)) {
- return { skipStrategy: true };
- }
- return {
- retryAfterInMs
- };
- }
- };
-}
-var RetryAfterHeader = "Retry-After", AllRetryAfterHeaders;
-var init_throttlingRetryStrategy = __esm(() => {
- init_helpers();
- AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader];
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/exponentialRetryStrategy.js
-function exponentialRetryStrategy(options2 = {}) {
- const retryInterval = options2.retryDelayInMs ?? DEFAULT_CLIENT_RETRY_INTERVAL;
- const maxRetryInterval = options2.maxRetryDelayInMs ?? DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
- return {
- name: "exponentialRetryStrategy",
- retry({ retryCount, response: response7, responseError }) {
- const matchedSystemError = isSystemError(responseError);
- const ignoreSystemErrors = matchedSystemError && options2.ignoreSystemErrors;
- const isExponential = isExponentialRetryResponse(response7);
- const ignoreExponentialResponse = isExponential && options2.ignoreHttpStatusCodes;
- const unknownResponse = response7 && (isThrottlingRetryResponse(response7) || !isExponential);
- if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {
- return { skipStrategy: true };
- }
- if (responseError && !matchedSystemError && !isExponential) {
- return { errorToThrow: responseError };
- }
- return calculateRetryDelay(retryCount, {
- retryDelayInMs: retryInterval,
- maxRetryDelayInMs: maxRetryInterval
- });
- }
- };
-}
-function isExponentialRetryResponse(response7) {
- return Boolean(response7 && response7.status !== undefined && (response7.status >= 500 || response7.status === 408) && response7.status !== 501 && response7.status !== 505);
-}
-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";
-}
-var DEFAULT_CLIENT_RETRY_INTERVAL = 1000, DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
-var init_exponentialRetryStrategy = __esm(() => {
- init_delay();
- init_throttlingRetryStrategy();
- DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/constants.js
-var DEFAULT_RETRY_POLICY_COUNT = 3;
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/policies/retryPolicy.js
-function retryPolicy(strategies, options2 = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }) {
- const logger13 = options2.logger || retryPolicyLogger;
- return {
- name: retryPolicyName,
- async sendRequest(request2, next) {
- let response7;
- let responseError;
- let retryCount = -1;
- retryRequest:
- while (true) {
- retryCount += 1;
- response7 = undefined;
- responseError = undefined;
- try {
- logger13.info(`Retry ${retryCount}: Attempting to send request`, request2.requestId);
- response7 = await next(request2);
- logger13.info(`Retry ${retryCount}: Received a response from request`, request2.requestId);
- } catch (e4) {
- logger13.error(`Retry ${retryCount}: Received an error from request`, request2.requestId);
- responseError = e4;
- if (!e4 || responseError.name !== "RestError") {
- throw e4;
- }
- response7 = responseError.response;
- }
- if (request2.abortSignal?.aborted) {
- logger13.error(`Retry ${retryCount}: Request aborted.`);
- const abortError = new AbortError3;
- throw abortError;
- }
- if (retryCount >= (options2.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT)) {
- logger13.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);
- if (responseError) {
- throw responseError;
- } else if (response7) {
- return response7;
- } else {
- throw new Error("Maximum retries reached with no response or error to throw");
- }
- }
- logger13.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);
- strategiesLoop:
- for (const strategy of strategies) {
- const strategyLogger = strategy.logger || logger13;
- strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);
- const modifiers = strategy.retry({
- retryCount,
- response: response7,
- 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 delay3(retryAfterInMs, undefined, { abortSignal: request2.abortSignal });
- continue retryRequest;
- }
- if (redirectTo) {
- strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`);
- request2.url = redirectTo;
- continue retryRequest;
- }
- }
- if (responseError) {
- logger13.info(`None of the retry strategies could work with the received error. Throwing it.`);
- throw responseError;
- }
- if (response7) {
- logger13.info(`None of the retry strategies could work with the received response. Returning it.`);
- return response7;
- }
- }
- }
- };
-}
-var retryPolicyLogger, retryPolicyName = "retryPolicy";
-var init_retryPolicy = __esm(() => {
- init_helpers();
- init_AbortError2();
- init_logger7();
- retryPolicyLogger = createClientLogger("ts-http-runtime retryPolicy");
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/policies/defaultRetryPolicy.js
-function defaultRetryPolicy(options2 = {}) {
- return {
- name: defaultRetryPolicyName,
- sendRequest: retryPolicy([throttlingRetryStrategy(), exponentialRetryStrategy(options2)], {
- maxRetries: options2.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT
- }).sendRequest
- };
-}
-var defaultRetryPolicyName = "defaultRetryPolicy";
-var init_defaultRetryPolicy = __esm(() => {
- init_exponentialRetryStrategy();
- init_throttlingRetryStrategy();
- init_retryPolicy();
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/policies/formDataPolicy.js
-function formDataToFormDataMap(formData) {
- const formDataMap = {};
- for (const [key, value] of formData.entries()) {
- formDataMap[key] ??= [];
- formDataMap[key].push(value);
- }
- return formDataMap;
-}
-function formDataPolicy() {
- return {
- name: formDataPolicyName,
- async sendRequest(request2, next) {
- if (isNodeLike && typeof FormData !== "undefined" && request2.body instanceof FormData) {
- request2.formData = formDataToFormDataMap(request2.body);
- request2.body = undefined;
- }
- if (request2.formData) {
- const contentType = request2.headers.get("Content-Type");
- if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
- request2.body = wwwFormUrlEncode(request2.formData);
- } else {
- await prepareFormData(request2.formData, request2);
- }
- request2.formData = undefined;
- }
- return next(request2);
- }
- };
-}
-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());
- }
- }
- return urlSearchParams.toString();
-}
-async function prepareFormData(formData, request2) {
- const contentType = request2.headers.get("Content-Type");
- if (contentType && !contentType.startsWith("multipart/form-data")) {
- return;
- }
- request2.headers.set("Content-Type", contentType ?? "multipart/form-data");
- const parts = [];
- for (const [fieldName, values2] of Object.entries(formData)) {
- for (const value of Array.isArray(values2) ? values2 : [values2]) {
- if (typeof value === "string") {
- parts.push({
- headers: createHttpHeaders({
- "Content-Disposition": `form-data; name="${fieldName}"`
- }),
- body: stringToUint8Array2(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 {
- const fileName = value.name || "blob";
- const headers = createHttpHeaders();
- headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
- headers.set("Content-Type", value.type || "application/octet-stream");
- parts.push({
- headers,
- body: value
- });
- }
- }
- }
- request2.multipartBody = { parts };
-}
-var formDataPolicyName = "formDataPolicy";
-var init_formDataPolicy = __esm(() => {
- init_checkEnvironment();
- init_httpHeaders();
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/policies/logPolicy.js
-function logPolicy(options2 = {}) {
- const logger13 = options2.logger ?? logger11.info;
- const sanitizer = new Sanitizer({
- additionalAllowedHeaderNames: options2.additionalAllowedHeaderNames,
- additionalAllowedQueryParameters: options2.additionalAllowedQueryParameters
- });
- return {
- name: logPolicyName,
- async sendRequest(request2, next) {
- if (!logger13.enabled) {
- return next(request2);
- }
- logger13(`Request: ${sanitizer.sanitize(request2)}`);
- const response7 = await next(request2);
- logger13(`Response status code: ${response7.status}`);
- logger13(`Headers: ${sanitizer.sanitize(response7.headers)}`);
- return response7;
- }
- };
-}
-var logPolicyName = "logPolicy";
-var init_logPolicy = __esm(() => {
- init_log8();
- init_sanitizer();
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/typeGuards.js
-function isBlob2(x3) {
- return typeof x3.stream === "function";
-}
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/util/concat.js
-import { Readable as Readable8 } from "stream";
-async function* streamAsyncIterator() {
- const reader = this.getReader();
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) {
- return;
- }
- yield 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(stream10) {
- if (stream10 instanceof ReadableStream) {
- makeAsyncIterable(stream10);
- return Readable8.fromWeb(stream10);
- } else {
- return stream10;
- }
-}
-function toStream(source) {
- if (source instanceof Uint8Array) {
- return Readable8.from(Buffer.from(source));
- } else if (isBlob2(source)) {
- return ensureNodeStream(source.stream());
- } else {
- return ensureNodeStream(source);
- }
-}
-async function concat(sources) {
- return function() {
- const streams2 = sources.map((x3) => typeof x3 === "function" ? x3() : x3).map(toStream);
- return Readable8.from(async function* () {
- for (const stream10 of streams2) {
- for await (const chunk of stream10) {
- yield chunk;
- }
- }
- }());
- };
-}
-var init_concat = () => {};
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/policies/multipartPolicy.js
-function generateBoundary() {
- return `----AzSDKFormBoundary${randomUUID2()}`;
-}
-function encodeHeaders(headers) {
- let result = "";
- for (const [key, value] of headers) {
- result += `${key}: ${value}\r
-`;
- }
- return result;
-}
-function getLength(source) {
- if (source instanceof Uint8Array) {
- return source.byteLength;
- } else if (isBlob2(source)) {
- return source.size === -1 ? undefined : source.size;
- } else {
- return;
- }
-}
-function getTotalLength(sources) {
- let total = 0;
- for (const source of sources) {
- const partLength = getLength(source);
- if (partLength === undefined) {
- return;
- } else {
- total += partLength;
- }
- }
- return total;
-}
-async function buildRequestBody(request2, parts, boundary) {
- const sources = [
- stringToUint8Array2(`--${boundary}`, "utf-8"),
- ...parts.flatMap((part) => [
- stringToUint8Array2(`\r
-`, "utf-8"),
- stringToUint8Array2(encodeHeaders(part.headers), "utf-8"),
- stringToUint8Array2(`\r
-`, "utf-8"),
- part.body,
- stringToUint8Array2(`\r
---${boundary}`, "utf-8")
- ]),
- stringToUint8Array2(`--\r
-\r
-`, "utf-8")
- ];
- const contentLength = getTotalLength(sources);
- if (contentLength) {
- request2.headers.set("Content-Length", contentLength);
- }
- request2.body = await concat(sources);
-}
-function assertValidBoundary(boundary) {
- if (boundary.length > maxBoundaryLength) {
- throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
- }
- if (Array.from(boundary).some((x3) => !validBoundaryCharacters.has(x3))) {
- throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
- }
-}
-function multipartPolicy() {
- return {
- name: multipartPolicyName,
- async sendRequest(request2, next) {
- if (!request2.multipartBody) {
- return next(request2);
- }
- if (request2.body) {
- throw new Error("multipartBody and regular body cannot be set at the same time");
- }
- let boundary = request2.multipartBody.boundary;
- const contentTypeHeader = request2.headers.get("Content-Type") ?? "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 ??= parsedBoundary;
- if (boundary) {
- assertValidBoundary(boundary);
- } else {
- boundary = generateBoundary();
- }
- request2.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
- await buildRequestBody(request2, request2.multipartBody.parts, boundary);
- request2.multipartBody = undefined;
- return next(request2);
- }
- };
-}
-var multipartPolicyName = "multipartPolicy", maxBoundaryLength = 70, validBoundaryCharacters;
-var init_multipartPolicy = __esm(() => {
- init_concat();
- validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
-});
-
-// node_modules/http-proxy-agent/dist/index.js
-var require_dist4 = __commonJS((exports) => {
- var __createBinding2 = exports && exports.__createBinding || (Object.create ? function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- var desc = Object.getOwnPropertyDescriptor(m4, k4);
- if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() {
- return m4[k4];
- } };
- }
- Object.defineProperty(o5, k22, desc);
- } : function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- });
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
- Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
- } : function(o5, v6) {
- o5["default"] = v6;
- });
- var __importStar2 = exports && exports.__importStar || function(mod2) {
- if (mod2 && mod2.__esModule)
- return mod2;
- var result = {};
- if (mod2 != null) {
- for (var k4 in mod2)
- if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4))
- __createBinding2(result, mod2, k4);
- }
- __setModuleDefault(result, mod2);
- return result;
- };
- var __importDefault2 = exports && exports.__importDefault || function(mod2) {
- return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.HttpProxyAgent = undefined;
- var net = __importStar2(__require("net"));
- var tls = __importStar2(__require("tls"));
- var debug_1 = __importDefault2(require_src());
- var events_1 = __require("events");
- var agent_base_1 = require_dist();
- var url_1 = __require("url");
- var debug2 = (0, debug_1.default)("http-proxy-agent");
-
- 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 ?? {};
- debug2("Creating new HttpProxyAgent instance: %o", this.proxy.href);
- 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 ? omit2(opts, "headers") : null,
- host,
- port
- };
- }
- addRequest(req, opts) {
- req._header = null;
- this.setRequestProps(req, opts);
- super.addRequest(req, opts);
- }
- setRequestProps(req, opts) {
- const { proxy } = this;
- const protocol = opts.secureEndpoint ? "https:" : "http:";
- const hostname2 = req.getHeader("host") || "localhost";
- const base2 = `${protocol}//${hostname2}`;
- const url3 = new url_1.URL(req.path, base2);
- if (opts.port !== 80) {
- url3.port = String(opts.port);
- }
- req.path = String(url3);
- const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
- if (proxy.username || proxy.password) {
- const auth13 = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
- headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth13).toString("base64")}`;
- }
- if (!headers["Proxy-Connection"]) {
- headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
- }
- for (const name3 of Object.keys(headers)) {
- const value = headers[name3];
- if (value) {
- req.setHeader(name3, value);
- }
- }
- }
- async connect(req, opts) {
- req._header = null;
- if (!req.path.includes("://")) {
- this.setRequestProps(req, opts);
- }
- let first;
- let endOfHeaders;
- debug2("Regenerating stored HTTP header string for request");
- req._implicitHeader();
- if (req.outputData && req.outputData.length > 0) {
- debug2("Patching connection write() output buffer with updated header");
- first = req.outputData[0].data;
- endOfHeaders = first.indexOf(`\r
-\r
-`) + 4;
- req.outputData[0].data = req._header + first.substring(endOfHeaders);
- debug2("Output buffer: %o", req.outputData[0].data);
- }
- let socket;
- if (this.proxy.protocol === "https:") {
- debug2("Creating `tls.Socket`: %o", this.connectOpts);
- socket = tls.connect(this.connectOpts);
- } else {
- debug2("Creating `net.Socket`: %o", this.connectOpts);
- socket = net.connect(this.connectOpts);
- }
- await (0, events_1.once)(socket, "connect");
- return socket;
- }
- }
- HttpProxyAgent.protocols = ["http", "https"];
- exports.HttpProxyAgent = HttpProxyAgent;
- function omit2(obj, ...keys2) {
- const ret = {};
- let key;
- for (key in obj) {
- if (!keys2.includes(key)) {
- ret[key] = obj[key];
- }
- }
- return ret;
- }
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/policies/proxyPolicy.js
-function getEnvironmentValue(name3) {
- if (process.env[name3]) {
- return process.env[name3];
- } else if (process.env[name3.toLowerCase()]) {
- return process.env[name3.toLowerCase()];
- }
- return;
-}
-function loadEnvironmentProxyValue() {
- if (!process) {
- return;
- }
- const httpsProxy = getEnvironmentValue(HTTPS_PROXY);
- const allProxy = getEnvironmentValue(ALL_PROXY);
- const httpProxy = getEnvironmentValue(HTTP_PROXY);
- return httpsProxy || allProxy || httpProxy;
-}
-function isBypassed(uri7, noProxyList, bypassedMap) {
- if (noProxyList.length === 0) {
- return false;
- }
- const host = new URL(uri7).hostname;
- if (bypassedMap?.has(host)) {
- return bypassedMap.get(host);
- }
- let isBypassedFlag = false;
- for (const pattern of noProxyList) {
- if (pattern[0] === ".") {
- 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?.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 [];
-}
-function getDefaultProxySettingsInternal() {
- const envProxy = loadEnvironmentProxyValue();
- return envProxy ? new URL(envProxy) : undefined;
-}
-function getUrlFromProxySettings(settings) {
- let parsedProxyUrl;
- try {
- parsedProxyUrl = new URL(settings.host);
- } catch {
- 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(request2, cachedAgents, proxyUrl) {
- if (request2.agent) {
- return;
- }
- const url3 = new URL(request2.url);
- const isInsecure = url3.protocol !== "https:";
- if (request2.tlsSettings) {
- logger11.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");
- }
- const headers = request2.headers.toJSON();
- if (isInsecure) {
- if (!cachedAgents.httpProxyAgent) {
- cachedAgents.httpProxyAgent = new import_http_proxy_agent.HttpProxyAgent(proxyUrl, { headers });
- }
- request2.agent = cachedAgents.httpProxyAgent;
- } else {
- if (!cachedAgents.httpsProxyAgent) {
- cachedAgents.httpsProxyAgent = new import_https_proxy_agent2.HttpsProxyAgent(proxyUrl, { headers });
- }
- request2.agent = cachedAgents.httpsProxyAgent;
- }
-}
-function proxyPolicy(proxySettings, options2) {
- if (!noProxyListLoaded) {
- globalNoProxyList.push(...loadNoProxy());
- }
- const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal();
- const cachedAgents = {};
- return {
- name: proxyPolicyName,
- async sendRequest(request2, next) {
- if (!request2.proxySettings && defaultProxy && !isBypassed(request2.url, options2?.customNoProxyList ?? globalNoProxyList, options2?.customNoProxyList ? undefined : globalBypassedMap)) {
- setProxyAgentOnRequest(request2, cachedAgents, defaultProxy);
- } else if (request2.proxySettings) {
- setProxyAgentOnRequest(request2, cachedAgents, getUrlFromProxySettings(request2.proxySettings));
- }
- return next(request2);
- }
- };
-}
-var import_https_proxy_agent2, import_http_proxy_agent, HTTPS_PROXY = "HTTPS_PROXY", HTTP_PROXY = "HTTP_PROXY", ALL_PROXY = "ALL_PROXY", NO_PROXY = "NO_PROXY", proxyPolicyName = "proxyPolicy", globalNoProxyList, noProxyListLoaded = false, globalBypassedMap;
-var init_proxyPolicy = __esm(() => {
- init_log8();
- import_https_proxy_agent2 = __toESM(require_dist2(), 1);
- import_http_proxy_agent = __toESM(require_dist4(), 1);
- globalNoProxyList = [];
- globalBypassedMap = new Map;
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/policies/redirectPolicy.js
-function redirectPolicy(options2 = {}) {
- const { maxRetries = 20, allowCrossOriginRedirects = false } = options2;
- return {
- name: redirectPolicyName,
- async sendRequest(request2, next) {
- const response7 = await next(request2);
- return handleRedirect(next, response7, maxRetries, allowCrossOriginRedirects);
- }
- };
-}
-async function handleRedirect(next, response7, maxRetries, allowCrossOriginRedirects, currentRetries = 0) {
- const { request: request2, status, headers } = response7;
- const locationHeader = headers.get("location");
- if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request2.method) || status === 302 && allowedRedirect.includes(request2.method) || status === 303 && request2.method === "POST" || status === 307) && currentRetries < maxRetries) {
- const url3 = new URL(locationHeader, request2.url);
- if (!allowCrossOriginRedirects) {
- const originalUrl = new URL(request2.url);
- if (url3.origin !== originalUrl.origin) {
- logger11.verbose(`Skipping cross-origin redirect from ${originalUrl.origin} to ${url3.origin}.`);
- return response7;
- }
- }
- request2.url = url3.toString();
- if (status === 303) {
- request2.method = "GET";
- request2.headers.delete("Content-Length");
- delete request2.body;
- }
- request2.headers.delete("Authorization");
- const res = await next(request2);
- return handleRedirect(next, res, maxRetries, allowCrossOriginRedirects, currentRetries + 1);
- }
- return response7;
-}
-var redirectPolicyName = "redirectPolicy", allowedRedirect;
-var init_redirectPolicy = __esm(() => {
- init_log8();
- allowedRedirect = ["GET", "HEAD"];
-});
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/policies/tlsPolicy.js
-function tlsPolicy(tlsSettings) {
- return {
- name: tlsPolicyName,
- sendRequest: async (req, next) => {
- if (!req.tlsSettings) {
- req.tlsSettings = tlsSettings;
- }
- return next(req);
- }
- };
-}
-var tlsPolicyName = "tlsPolicy";
-
-// node_modules/@typespec/ts-http-runtime/dist/esm/policies/internal.js
-var init_internal3 = __esm(() => {
- init_defaultRetryPolicy();
- init_retryPolicy();
- init_formDataPolicy();
- init_logPolicy();
- init_multipartPolicy();
- init_proxyPolicy();
- init_redirectPolicy();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/logPolicy.js
-function logPolicy2(options2 = {}) {
- return logPolicy({
- logger: logger12.info,
- ...options2
- });
-}
-var init_logPolicy2 = __esm(() => {
- init_log9();
- init_internal3();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/redirectPolicy.js
-function redirectPolicy2(options2 = {}) {
- return redirectPolicy(options2);
-}
-var init_redirectPolicy2 = __esm(() => {
- init_internal3();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgentPlatform.js
-import os3 from "os";
-import process13 from "process";
-function getHeaderName() {
- return "User-Agent";
-}
-async function setPlatformSpecificData(map7) {
- if (process13 && process13.versions) {
- const osInfo = `${os3.type()} ${os3.release()}; ${os3.arch()}`;
- const versions2 = process13.versions;
- if (versions2.bun) {
- map7.set("Bun", `${versions2.bun} (${osInfo})`);
- } else if (versions2.deno) {
- map7.set("Deno", `${versions2.deno} (${osInfo})`);
- } else if (versions2.node) {
- map7.set("Node", `${versions2.node} (${osInfo})`);
- }
- }
-}
-var init_userAgentPlatform = () => {};
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/constants.js
-var SDK_VERSION3 = "1.22.3", DEFAULT_RETRY_POLICY_COUNT2 = 3;
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgent.js
-function getUserAgentString(telemetryInfo) {
- const parts = [];
- for (const [key, value] of telemetryInfo) {
- const token = value ? `${key}/${value}` : key;
- parts.push(token);
- }
- return parts.join(" ");
-}
-function getUserAgentHeaderName() {
- return getHeaderName();
-}
-async function getUserAgentValue(prefix) {
- const runtimeInfo = new Map;
- runtimeInfo.set("core-rest-pipeline", SDK_VERSION3);
- await setPlatformSpecificData(runtimeInfo);
- const defaultAgent = getUserAgentString(runtimeInfo);
- const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
- return userAgentValue;
-}
-var init_userAgent = __esm(() => {
- init_userAgentPlatform();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/userAgentPolicy.js
-function userAgentPolicy2(options2 = {}) {
- const userAgentValue = getUserAgentValue(options2.userAgentPrefix);
- return {
- name: userAgentPolicyName2,
- async sendRequest(request2, next) {
- if (!request2.headers.has(UserAgentHeaderName)) {
- request2.headers.set(UserAgentHeaderName, await userAgentValue);
- }
- return next(request2);
- }
- };
-}
-var UserAgentHeaderName, userAgentPolicyName2 = "userAgentPolicy";
-var init_userAgentPolicy = __esm(() => {
- init_userAgent();
- UserAgentHeaderName = getUserAgentHeaderName();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/util/file.js
-function hasRawContent(x3) {
- return typeof x3[rawContent] === "function";
-}
-function getRawContent(blob) {
- if (hasRawContent(blob)) {
- return blob[rawContent]();
- } else {
- return blob;
- }
-}
-var rawContent;
-var init_file2 = __esm(() => {
- rawContent = Symbol("rawContent");
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/multipartPolicy.js
-function multipartPolicy2() {
- const tspPolicy = multipartPolicy();
- return {
- name: multipartPolicyName2,
- sendRequest: async (request2, next) => {
- if (request2.multipartBody) {
- for (const part of request2.multipartBody.parts) {
- if (hasRawContent(part.body)) {
- part.body = getRawContent(part.body);
- }
- }
- }
- return tspPolicy.sendRequest(request2, next);
- }
- };
-}
-var multipartPolicyName2;
-var init_multipartPolicy2 = __esm(() => {
- init_internal3();
- init_file2();
- multipartPolicyName2 = multipartPolicyName;
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/decompressResponsePolicy.js
-function decompressResponsePolicy2() {
- return decompressResponsePolicy();
-}
-var init_decompressResponsePolicy = __esm(() => {
- init_internal3();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/defaultRetryPolicy.js
-function defaultRetryPolicy2(options2 = {}) {
- return defaultRetryPolicy(options2);
-}
-var init_defaultRetryPolicy2 = __esm(() => {
- init_internal3();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/formDataPolicy.js
-function formDataPolicy2() {
- return formDataPolicy();
-}
-var init_formDataPolicy2 = __esm(() => {
- init_internal3();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/proxyPolicy.js
-function proxyPolicy2(proxySettings, options2) {
- return proxyPolicy(proxySettings, options2);
-}
-var init_proxyPolicy2 = __esm(() => {
- init_internal3();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/setClientRequestIdPolicy.js
-function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
- return {
- name: setClientRequestIdPolicyName,
- async sendRequest(request2, next) {
- if (!request2.headers.has(requestIdHeaderName)) {
- request2.headers.set(requestIdHeaderName, request2.requestId);
- }
- return next(request2);
- }
- };
-}
-var setClientRequestIdPolicyName = "setClientRequestIdPolicy";
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/agentPolicy.js
-function agentPolicy2(agent) {
- return agentPolicy(agent);
-}
-var init_agentPolicy = __esm(() => {
- init_internal3();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/tlsPolicy.js
-function tlsPolicy2(tlsSettings) {
- return tlsPolicy(tlsSettings);
-}
-var init_tlsPolicy = __esm(() => {
- init_internal3();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/restError.js
-function isRestError2(e4) {
- return isRestError(e4);
-}
-var RestError2;
-var init_restError2 = __esm(() => {
- init_esm6();
- RestError2 = RestError;
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/tracingPolicy.js
-function tracingPolicy(options2 = {}) {
- const userAgentPromise = getUserAgentValue(options2.userAgentPrefix);
- const sanitizer = new Sanitizer({
- additionalAllowedQueryParameters: options2.additionalAllowedQueryParameters
- });
- const tracingClient2 = tryCreateTracingClient();
- return {
- name: tracingPolicyName,
- async sendRequest(request2, next) {
- if (!tracingClient2) {
- return next(request2);
- }
- const userAgent = await userAgentPromise;
- const spanAttributes = {
- "http.url": sanitizer.sanitizeUrl(request2.url),
- "http.method": request2.method,
- "http.user_agent": userAgent,
- requestId: request2.requestId
- };
- if (userAgent) {
- spanAttributes["http.user_agent"] = userAgent;
- }
- const { span, tracingContext } = tryCreateSpan(tracingClient2, request2, spanAttributes) ?? {};
- if (!span || !tracingContext) {
- return next(request2);
- }
- try {
- const response7 = await tracingClient2.withContext(tracingContext, next, request2);
- tryProcessResponse(span, response7);
- return response7;
- } catch (err) {
- tryProcessError(span, err);
- throw err;
- }
- }
- };
-}
-function tryCreateTracingClient() {
- try {
- return createTracingClient({
- namespace: "",
- packageName: "@azure/core-rest-pipeline",
- packageVersion: SDK_VERSION3
- });
- } catch (e4) {
- logger12.warning(`Error when creating the TracingClient: ${getErrorMessage2(e4)}`);
- return;
- }
-}
-function tryCreateSpan(tracingClient2, request2, spanAttributes) {
- try {
- const { span, updatedOptions } = tracingClient2.startSpan(`HTTP ${request2.method}`, { tracingOptions: request2.tracingOptions }, {
- spanKind: "client",
- spanAttributes
- });
- if (!span.isRecording()) {
- span.end();
- return;
- }
- const headers = tracingClient2.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
- for (const [key, value] of Object.entries(headers)) {
- request2.headers.set(key, value);
- }
- return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
- } catch (e4) {
- logger12.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage2(e4)}`);
- return;
- }
-}
-function tryProcessError(span, error44) {
- try {
- span.setStatus({
- status: "error",
- error: isError2(error44) ? error44 : undefined
- });
- if (isRestError2(error44) && error44.statusCode) {
- span.setAttribute("http.status_code", error44.statusCode);
- }
- span.end();
- } catch (e4) {
- logger12.warning(`Skipping tracing span processing due to an error: ${getErrorMessage2(e4)}`);
- }
-}
-function tryProcessResponse(span, response7) {
- try {
- span.setAttribute("http.status_code", response7.status);
- const serviceRequestId = response7.headers.get("x-ms-request-id");
- if (serviceRequestId) {
- span.setAttribute("serviceRequestId", serviceRequestId);
- }
- if (response7.status >= 400) {
- span.setStatus({
- status: "error"
- });
- }
- span.end();
- } catch (e4) {
- logger12.warning(`Skipping tracing span processing due to an error: ${getErrorMessage2(e4)}`);
- }
-}
-var tracingPolicyName = "tracingPolicy";
-var init_tracingPolicy = __esm(() => {
- init_esm3();
- init_userAgent();
- init_log9();
- init_esm5();
- init_restError2();
- init_internal2();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/util/wrapAbortSignal.js
-function wrapAbortSignalLike(abortSignalLike) {
- if (abortSignalLike instanceof AbortSignal) {
- return { abortSignal: abortSignalLike };
- }
- if (abortSignalLike.aborted) {
- return { abortSignal: AbortSignal.abort(abortSignalLike.reason) };
- }
- const controller = new AbortController;
- let needsCleanup = true;
- function cleanup() {
- if (needsCleanup) {
- abortSignalLike.removeEventListener("abort", listener);
- needsCleanup = false;
- }
- }
- function listener() {
- controller.abort(abortSignalLike.reason);
- cleanup();
- }
- abortSignalLike.addEventListener("abort", listener);
- return { abortSignal: controller.signal, cleanup };
-}
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/wrapAbortSignalLikePolicy.js
-function wrapAbortSignalLikePolicy() {
- return {
- name: wrapAbortSignalLikePolicyName,
- sendRequest: async (request2, next) => {
- if (!request2.abortSignal) {
- return next(request2);
- }
- const { abortSignal, cleanup } = wrapAbortSignalLike(request2.abortSignal);
- request2.abortSignal = abortSignal;
- try {
- return await next(request2);
- } finally {
- cleanup?.();
- }
- }
- };
-}
-var wrapAbortSignalLikePolicyName = "wrapAbortSignalLikePolicy";
-var init_wrapAbortSignalLikePolicy = () => {};
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/createPipelineFromOptions.js
-function createPipelineFromOptions(options2) {
- const pipeline2 = createEmptyPipeline2();
- if (isNodeLike2) {
- if (options2.agent) {
- pipeline2.addPolicy(agentPolicy2(options2.agent));
- }
- if (options2.tlsOptions) {
- pipeline2.addPolicy(tlsPolicy2(options2.tlsOptions));
- }
- pipeline2.addPolicy(proxyPolicy2(options2.proxyOptions));
- pipeline2.addPolicy(decompressResponsePolicy2());
- }
- pipeline2.addPolicy(wrapAbortSignalLikePolicy());
- pipeline2.addPolicy(formDataPolicy2(), { beforePolicies: [multipartPolicyName2] });
- pipeline2.addPolicy(userAgentPolicy2(options2.userAgentOptions));
- pipeline2.addPolicy(setClientRequestIdPolicy(options2.telemetryOptions?.clientRequestIdHeaderName));
- pipeline2.addPolicy(multipartPolicy2(), { afterPhase: "Deserialize" });
- pipeline2.addPolicy(defaultRetryPolicy2(options2.retryOptions), { phase: "Retry" });
- pipeline2.addPolicy(tracingPolicy({ ...options2.userAgentOptions, ...options2.loggingOptions }), {
- afterPhase: "Retry"
- });
- if (isNodeLike2) {
- pipeline2.addPolicy(redirectPolicy2(options2.redirectOptions), { afterPhase: "Retry" });
- }
- pipeline2.addPolicy(logPolicy2(options2.loggingOptions), { afterPhase: "Sign" });
- return pipeline2;
-}
-var init_createPipelineFromOptions = __esm(() => {
- init_logPolicy2();
- init_pipeline3();
- init_redirectPolicy2();
- init_userAgentPolicy();
- init_multipartPolicy2();
- init_decompressResponsePolicy();
- init_defaultRetryPolicy2();
- init_formDataPolicy2();
- init_esm5();
- init_proxyPolicy2();
- init_agentPolicy();
- init_tlsPolicy();
- init_tracingPolicy();
- init_wrapAbortSignalLikePolicy();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/defaultHttpClient.js
-function createDefaultHttpClient2() {
- const client14 = createDefaultHttpClient();
- return {
- async sendRequest(request2) {
- const { abortSignal, cleanup } = request2.abortSignal ? wrapAbortSignalLike(request2.abortSignal) : {};
- try {
- request2.abortSignal = abortSignal;
- return await client14.sendRequest(request2);
- } finally {
- cleanup?.();
- }
- }
- };
-}
-var init_defaultHttpClient2 = __esm(() => {
- init_esm6();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/httpHeaders.js
-function createHttpHeaders2(rawHeaders) {
- return createHttpHeaders(rawHeaders);
-}
-var init_httpHeaders2 = __esm(() => {
- init_esm6();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/pipelineRequest.js
-function createPipelineRequest2(options2) {
- return createPipelineRequest(options2);
-}
-var init_pipelineRequest2 = __esm(() => {
- init_esm6();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/retryPolicy.js
-function retryPolicy2(strategies, options2 = { maxRetries: DEFAULT_RETRY_POLICY_COUNT2 }) {
- return retryPolicy(strategies, {
- logger: retryPolicyLogger2,
- ...options2
- });
-}
-var retryPolicyLogger2;
-var init_retryPolicy2 = __esm(() => {
- init_esm2();
- init_internal3();
- retryPolicyLogger2 = createClientLogger2("core-rest-pipeline retryPolicy");
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/util/tokenCycler.js
-async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
- async function tryGetAccessToken() {
- if (Date.now() < refreshTimeout) {
- try {
- return await getAccessToken();
- } catch {
- return null;
- }
- } else {
- const finalToken = await getAccessToken();
- if (finalToken === null) {
- throw new Error("Failed to refresh access token.");
- }
- return finalToken;
- }
- }
- let token = await tryGetAccessToken();
- while (token === null) {
- await delay2(retryIntervalInMs);
- token = await tryGetAccessToken();
- }
- return token;
-}
-function createTokenCycler(credential, tokenCyclerOptions) {
- let refreshWorker = null;
- let token = null;
- let tenantId;
- const options2 = {
- ...DEFAULT_CYCLER_OPTIONS,
- ...tokenCyclerOptions
- };
- const cycler = {
- get isRefreshing() {
- return refreshWorker !== null;
- },
- get shouldRefresh() {
- if (cycler.isRefreshing) {
- return false;
- }
- if (token?.refreshAfterTimestamp && token.refreshAfterTimestamp < Date.now()) {
- return true;
- }
- return (token?.expiresOnTimestamp ?? 0) - options2.refreshWindowInMs < Date.now();
- },
- get mustRefresh() {
- return token === null || token.expiresOnTimestamp - options2.forcedRefreshWindowInMs < Date.now();
- }
- };
- function refresh(scopes, getTokenOptions) {
- if (!cycler.isRefreshing) {
- const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions);
- refreshWorker = beginRefresh(tryGetAccessToken, options2.retryIntervalInMs, token?.expiresOnTimestamp ?? Date.now()).then((_token) => {
- refreshWorker = null;
- token = _token;
- tenantId = getTokenOptions.tenantId;
- return token;
- }).catch((reason) => {
- refreshWorker = null;
- token = null;
- tenantId = undefined;
- throw reason;
- });
- }
- return refreshWorker;
- }
- return async (scopes, tokenOptions) => {
- const hasClaimChallenge = Boolean(tokenOptions.claims);
- const tenantIdChanged = tenantId !== tokenOptions.tenantId;
- if (hasClaimChallenge) {
- token = null;
- }
- const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;
- if (mustRefresh) {
- return refresh(scopes, tokenOptions);
- }
- if (cycler.shouldRefresh) {
- refresh(scopes, tokenOptions);
- }
- return token;
- };
-}
-var DEFAULT_CYCLER_OPTIONS;
-var init_tokenCycler = __esm(() => {
- init_esm5();
- DEFAULT_CYCLER_OPTIONS = {
- forcedRefreshWindowInMs: 1000,
- retryIntervalInMs: 3000,
- refreshWindowInMs: 1000 * 60 * 2
- };
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/policies/bearerTokenAuthenticationPolicy.js
-async function trySendRequest(request2, next) {
- try {
- return [await next(request2), undefined];
- } catch (e4) {
- if (isRestError2(e4) && e4.response) {
- return [e4.response, e4];
- } else {
- throw e4;
- }
- }
-}
-async function defaultAuthorizeRequest(options2) {
- const { scopes, getAccessToken, request: request2 } = options2;
- const getTokenOptions = {
- abortSignal: request2.abortSignal,
- tracingOptions: request2.tracingOptions,
- enableCae: true
- };
- const accessToken = await getAccessToken(scopes, getTokenOptions);
- if (accessToken) {
- options2.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
- }
-}
-function isChallengeResponse(response7) {
- return response7.status === 401 && response7.headers.has("WWW-Authenticate");
-}
-async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) {
- const { scopes } = onChallengeOptions;
- const accessToken = await onChallengeOptions.getAccessToken(scopes, {
- enableCae: true,
- claims: caeClaims
- });
- if (!accessToken) {
- return false;
- }
- onChallengeOptions.request.headers.set("Authorization", `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`);
- return true;
-}
-function bearerTokenAuthenticationPolicy(options2) {
- const { credential, scopes, challengeCallbacks } = options2;
- const logger13 = options2.logger || logger12;
- const callbacks = {
- authorizeRequest: challengeCallbacks?.authorizeRequest?.bind(challengeCallbacks) ?? defaultAuthorizeRequest,
- authorizeRequestOnChallenge: challengeCallbacks?.authorizeRequestOnChallenge?.bind(challengeCallbacks)
- };
- const getAccessToken = credential ? createTokenCycler(credential) : () => Promise.resolve(null);
- return {
- name: bearerTokenAuthenticationPolicyName,
- async sendRequest(request2, next) {
- if (!request2.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: request2,
- getAccessToken,
- logger: logger13
- });
- let response7;
- let error44;
- let shouldSendRequest;
- [response7, error44] = await trySendRequest(request2, next);
- if (isChallengeResponse(response7)) {
- let claims = getCaeChallengeClaims(response7.headers.get("WWW-Authenticate"));
- if (claims) {
- let parsedClaim;
- try {
- parsedClaim = atob(claims);
- } catch (e4) {
- logger13.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
- return response7;
- }
- shouldSendRequest = await authorizeRequestOnCaeChallenge({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- response: response7,
- request: request2,
- getAccessToken,
- logger: logger13
- }, parsedClaim);
- if (shouldSendRequest) {
- [response7, error44] = await trySendRequest(request2, next);
- }
- } else if (callbacks.authorizeRequestOnChallenge) {
- shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- request: request2,
- response: response7,
- getAccessToken,
- logger: logger13
- });
- if (shouldSendRequest) {
- [response7, error44] = await trySendRequest(request2, next);
- }
- if (isChallengeResponse(response7)) {
- claims = getCaeChallengeClaims(response7.headers.get("WWW-Authenticate"));
- if (claims) {
- let parsedClaim;
- try {
- parsedClaim = atob(claims);
- } catch (e4) {
- logger13.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
- return response7;
- }
- shouldSendRequest = await authorizeRequestOnCaeChallenge({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- response: response7,
- request: request2,
- getAccessToken,
- logger: logger13
- }, parsedClaim);
- if (shouldSendRequest) {
- [response7, error44] = await trySendRequest(request2, next);
- }
- }
- }
- }
- }
- if (error44) {
- throw error44;
- } else {
- return response7;
- }
- }
- };
-}
-function parseChallenges(challenges) {
- const challengeRegex = /(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g;
- const paramRegex = /(\w+)="([^"]*)"/g;
- const parsedChallenges = [];
- let match;
- while ((match = challengeRegex.exec(challenges)) !== null) {
- const scheme = match[1];
- const paramsString = match[2];
- const params = {};
- let paramMatch;
- while ((paramMatch = paramRegex.exec(paramsString)) !== null) {
- params[paramMatch[1]] = paramMatch[2];
- }
- parsedChallenges.push({ scheme, params });
- }
- return parsedChallenges;
-}
-function getCaeChallengeClaims(challenges) {
- if (!challenges) {
- return;
- }
- const parsedChallenges = parseChallenges(challenges);
- return parsedChallenges.find((x3) => x3.scheme === "Bearer" && x3.params.claims && x3.params.error === "insufficient_claims")?.params.claims;
-}
-var bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
-var init_bearerTokenAuthenticationPolicy = __esm(() => {
- init_tokenCycler();
- init_log9();
- init_restError2();
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/esm/index.js
-var init_esm7 = __esm(() => {
- init_pipeline3();
- init_createPipelineFromOptions();
- init_defaultHttpClient2();
- init_httpHeaders2();
- init_pipelineRequest2();
- init_restError2();
- init_retryPolicy2();
- init_bearerTokenAuthenticationPolicy();
-});
-
-// node_modules/@azure/core-client/dist/esm/interfaces.js
-var XML_ATTRKEY = "$", XML_CHARKEY = "_";
-
-// node_modules/@azure/core-client/dist/esm/utils.js
-function isPrimitiveBody(value, mapperTypeName) {
- return mapperTypeName !== "Composite" && mapperTypeName !== "Dictionary" && (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || mapperTypeName?.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i) !== null || value === undefined || value === null);
-}
-function handleNullableResponseAndWrappableBody(responseObject) {
- const combinedHeadersAndBody = {
- ...responseObject.headers,
- ...responseObject.body
- };
- if (responseObject.hasNullableType && Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) {
- return responseObject.shouldWrapBody ? { body: null } : null;
- } else {
- return responseObject.shouldWrapBody ? {
- ...responseObject.headers,
- body: responseObject.body
- } : combinedHeadersAndBody;
- }
-}
-function flattenResponse(fullResponse, responseSpec) {
- const parsedHeaders = fullResponse.parsedHeaders;
- if (fullResponse.request.method === "HEAD") {
- return {
- ...parsedHeaders,
- body: fullResponse.parsedBody
- };
- }
- const bodyMapper = responseSpec && responseSpec.bodyMapper;
- const isNullable = Boolean(bodyMapper?.nullable);
- const expectedBodyTypeName = bodyMapper?.type.name;
- if (expectedBodyTypeName === "Stream") {
- return {
- ...parsedHeaders,
- blobBody: fullResponse.blobBody,
- readableStreamBody: fullResponse.readableStreamBody
- };
- }
- const modelProperties = expectedBodyTypeName === "Composite" && bodyMapper.type.modelProperties || {};
- const isPageableResponse = Object.keys(modelProperties).some((k4) => modelProperties[k4].serializedName === "");
- if (expectedBodyTypeName === "Sequence" || isPageableResponse) {
- const arrayResponse = fullResponse.parsedBody ?? [];
- for (const key of Object.keys(modelProperties)) {
- if (modelProperties[key].serializedName) {
- arrayResponse[key] = fullResponse.parsedBody?.[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)
- });
-}
-var init_utils5 = () => {};
-
-// node_modules/@azure/core-client/dist/esm/serializer.js
-var MapperTypeNames;
-var init_serializer = __esm(() => {
- 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"
- };
-});
-
-// node_modules/@azure/core-client/dist/commonjs/state.js
-var require_state3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.state = undefined;
- exports.state = {
- operationRequestMap: new WeakMap
- };
-});
-
-// node_modules/@azure/core-client/dist/esm/state.js
-var import_state17, state2;
-var init_state3 = __esm(() => {
- import_state17 = __toESM(require_state3(), 1);
- state2 = import_state17.state;
-});
-
-// node_modules/@azure/core-client/dist/esm/operationHelpers.js
-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;
-}
-function getPropertyFromParameterPath(parent, parameterPath) {
- const result = { propertyFound: false };
- let i5 = 0;
- for (;i5 < parameterPath.length; ++i5) {
- const parameterPathPart = parameterPath[i5];
- if (parent && parameterPathPart in parent) {
- parent = parent[parameterPathPart];
- } else {
- break;
- }
- }
- if (i5 === parameterPath.length) {
- result.propertyValue = parent;
- result.propertyFound = true;
- }
- return result;
-}
-function hasOriginalRequest(request2) {
- return originalRequestSymbol in request2;
-}
-function getOperationRequestInfo(request2) {
- if (hasOriginalRequest(request2)) {
- return getOperationRequestInfo(request2[originalRequestSymbol]);
- }
- let info = state2.operationRequestMap.get(request2);
- if (!info) {
- info = {};
- state2.operationRequestMap.set(request2, info);
- }
- return info;
-}
-var originalRequestSymbol;
-var init_operationHelpers = __esm(() => {
- init_state3();
- originalRequestSymbol = Symbol.for("@azure/core-client original request");
-});
-
-// node_modules/@azure/core-client/dist/esm/deserializationPolicy.js
-function deserializationPolicy(options2 = {}) {
- const jsonContentTypes = options2.expectedContentTypes?.json ?? defaultJsonContentTypes;
- const xmlContentTypes = options2.expectedContentTypes?.xml ?? defaultXmlContentTypes;
- const parseXML = options2.parseXML;
- const serializerOptions = options2.serializerOptions;
- const updatedOptions = {
- xml: {
- rootName: serializerOptions?.xml.rootName ?? "",
- includeRoot: serializerOptions?.xml.includeRoot ?? false,
- xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY
- }
- };
- return {
- name: deserializationPolicyName,
- async sendRequest(request2, next) {
- const response7 = await next(request2);
- return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response7, updatedOptions, parseXML);
- }
- };
-}
-function getOperationResponseMap(parsedResponse) {
- let result;
- const request2 = parsedResponse.request;
- const operationInfo = getOperationRequestInfo(request2);
- const operationSpec = operationInfo?.operationSpec;
- if (operationSpec) {
- if (!operationInfo?.operationResponseGetter) {
- result = operationSpec.responses[parsedResponse.status];
- } else {
- result = operationInfo?.operationResponseGetter(operationSpec, parsedResponse);
- }
- }
- return result;
-}
-function shouldDeserializeResponse(parsedResponse) {
- const request2 = parsedResponse.request;
- const operationInfo = getOperationRequestInfo(request2);
- const shouldDeserialize = 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, response7, options2, parseXML) {
- const parsedResponse = await parse9(jsonContentTypes, xmlContentTypes, response7, options2, parseXML);
- if (!shouldDeserializeResponse(parsedResponse)) {
- return parsedResponse;
- }
- const operationInfo = getOperationRequestInfo(parsedResponse.request);
- const operationSpec = operationInfo?.operationSpec;
- if (!operationSpec || !operationSpec.responses) {
- return parsedResponse;
- }
- const responseSpec = getOperationResponseMap(parsedResponse);
- const { error: error44, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options2);
- if (error44) {
- throw error44;
- } else if (shouldReturnResponse) {
- return parsedResponse;
- }
- if (responseSpec) {
- if (responseSpec.bodyMapper) {
- let valueToDeserialize = parsedResponse.parsedBody;
- if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperTypeNames.Sequence) {
- valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : [];
- }
- try {
- parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options2);
- } catch (deserializeError) {
- const restError = new RestError2(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, {
- statusCode: parsedResponse.status,
- request: parsedResponse.request,
- response: parsedResponse
- });
- throw restError;
- }
- } else if (operationSpec.httpMethod === "HEAD") {
- parsedResponse.parsedBody = response7.status >= 200 && response7.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, options2) {
- 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 ?? operationSpec.responses.default;
- const initialErrorMessage = parsedResponse.request.streamResponseStatusCodes?.has(parsedResponse.status) ? `Unexpected status code: ${parsedResponse.status}` : parsedResponse.bodyAsText;
- const error44 = new RestError2(initialErrorMessage, {
- statusCode: parsedResponse.status,
- request: parsedResponse.request,
- response: parsedResponse
- });
- if (!errorResponseSpec && !(parsedResponse.parsedBody?.error?.code && parsedResponse.parsedBody?.error?.message)) {
- throw error44;
- }
- const defaultBodyMapper = errorResponseSpec?.bodyMapper;
- const defaultHeadersMapper = errorResponseSpec?.headersMapper;
- try {
- if (parsedResponse.parsedBody) {
- const parsedBody = parsedResponse.parsedBody;
- let deserializedError;
- if (defaultBodyMapper) {
- let valueToDeserialize = parsedBody;
- if (operationSpec.isXML && defaultBodyMapper.type.name === MapperTypeNames.Sequence) {
- valueToDeserialize = [];
- const elementName = defaultBodyMapper.xmlElementName;
- if (typeof parsedBody === "object" && elementName) {
- valueToDeserialize = parsedBody[elementName];
- }
- }
- deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options2);
- }
- const internalError = parsedBody.error || deserializedError || parsedBody;
- error44.code = internalError.code;
- if (internalError.message) {
- error44.message = internalError.message;
- }
- if (defaultBodyMapper) {
- error44.response.parsedBody = deserializedError;
- }
- }
- if (parsedResponse.headers && defaultHeadersMapper) {
- error44.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders");
- }
- } catch (defaultError) {
- error44.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`;
- }
- return { error: error44, shouldReturnResponse: false };
-}
-async function parse9(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) {
- if (!operationResponse.request.streamResponseStatusCodes?.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;
- }
- } catch (err) {
- const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;
- const errCode = err.code || RestError2.PARSE_ERROR;
- const e4 = new RestError2(msg, {
- code: errCode,
- statusCode: operationResponse.status,
- request: operationResponse.request,
- response: operationResponse
- });
- throw e4;
- }
- }
- return operationResponse;
-}
-var defaultJsonContentTypes, defaultXmlContentTypes, deserializationPolicyName = "deserializationPolicy";
-var init_deserializationPolicy = __esm(() => {
- init_esm7();
- init_serializer();
- init_operationHelpers();
- defaultJsonContentTypes = ["application/json", "text/json"];
- defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
-});
-
-// node_modules/@azure/core-client/dist/esm/interfaceHelpers.js
-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 === MapperTypeNames.Stream) {
- result.add(Number(statusCode));
- }
- }
- return result;
-}
-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;
-}
-var init_interfaceHelpers = __esm(() => {
- init_serializer();
-});
-
-// node_modules/@azure/core-client/dist/esm/serializationPolicy.js
-function serializationPolicy(options2 = {}) {
- const stringifyXML = options2.stringifyXML;
- return {
- name: serializationPolicyName,
- async sendRequest(request2, next) {
- const operationInfo = getOperationRequestInfo(request2);
- const operationSpec = operationInfo?.operationSpec;
- const operationArguments = operationInfo?.operationArguments;
- if (operationSpec && operationArguments) {
- serializeHeaders(request2, operationArguments, operationSpec);
- serializeRequestBody(request2, operationArguments, operationSpec, stringifyXML);
- }
- return next(request2);
- }
- };
-}
-function serializeHeaders(request2, operationArguments, operationSpec) {
- if (operationSpec.headerParameters) {
- for (const headerParameter of operationSpec.headerParameters) {
- let headerValue = getOperationArgumentValueFromParameter(operationArguments, headerParameter);
- if (headerValue !== null && headerValue !== undefined || headerParameter.mapper.required) {
- headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
- const headerCollectionPrefix = headerParameter.mapper.headerCollectionPrefix;
- if (headerCollectionPrefix) {
- for (const key of Object.keys(headerValue)) {
- request2.headers.set(headerCollectionPrefix + key, headerValue[key]);
- }
- } else {
- request2.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue);
- }
- }
- }
- }
- const customHeaders = operationArguments.options?.requestOptions?.customHeaders;
- if (customHeaders) {
- for (const customHeaderName of Object.keys(customHeaders)) {
- request2.headers.set(customHeaderName, customHeaders[customHeaderName]);
- }
- }
-}
-function serializeRequestBody(request2, operationArguments, operationSpec, stringifyXML = function() {
- throw new Error("XML serialization unsupported!");
-}) {
- const serializerOptions = operationArguments.options?.serializerOptions;
- const updatedOptions = {
- xml: {
- rootName: serializerOptions?.xml.rootName ?? "",
- includeRoot: serializerOptions?.xml.includeRoot ?? false,
- xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY
- }
- };
- const xmlCharKey = updatedOptions.xml.xmlCharKey;
- if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
- request2.body = getOperationArgumentValueFromParameter(operationArguments, operationSpec.requestBody);
- const bodyMapper = operationSpec.requestBody.mapper;
- const { required: required2, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable: nullable2 } = bodyMapper;
- const typeName = bodyMapper.type.name;
- try {
- if (request2.body !== undefined && request2.body !== null || nullable2 && request2.body === null || required2) {
- const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
- request2.body = operationSpec.serializer.serialize(bodyMapper, request2.body, requestBodyParameterPathString, updatedOptions);
- const isStream3 = typeName === MapperTypeNames.Stream;
- if (operationSpec.isXML) {
- const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
- const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request2.body, updatedOptions);
- if (typeName === MapperTypeNames.Sequence) {
- request2.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey });
- } else if (!isStream3) {
- request2.body = stringifyXML(value, {
- rootName: xmlName || serializedName,
- xmlCharKey
- });
- }
- } else if (typeName === MapperTypeNames.String && (operationSpec.contentType?.match("text/plain") || operationSpec.mediaType === "text")) {
- return;
- } else if (!isStream3) {
- request2.body = JSON.stringify(request2.body);
- }
- }
- } catch (error44) {
- throw new Error(`Error "${error44.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`);
- }
- } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
- request2.formData = {};
- for (const formDataParameter of operationSpec.formDataParameters) {
- const formDataParameterValue = getOperationArgumentValueFromParameter(operationArguments, formDataParameter);
- if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
- const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
- request2.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions);
- }
- }
- }
-}
-function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options2) {
- if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) {
- const result = {};
- result[options2.xml.xmlCharKey] = serializedValue;
- result[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[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };
- return result;
-}
-var serializationPolicyName = "serializationPolicy";
-var init_serializationPolicy = __esm(() => {
- init_operationHelpers();
- init_serializer();
- init_interfaceHelpers();
-});
-
-// node_modules/@azure/core-client/dist/esm/pipeline.js
-function createClientPipeline(options2 = {}) {
- const pipeline2 = createPipelineFromOptions(options2 ?? {});
- if (options2.credentialOptions) {
- pipeline2.addPolicy(bearerTokenAuthenticationPolicy({
- credential: options2.credentialOptions.credential,
- scopes: options2.credentialOptions.credentialScopes
- }));
- }
- pipeline2.addPolicy(serializationPolicy(options2.serializationOptions), { phase: "Serialize" });
- pipeline2.addPolicy(deserializationPolicy(options2.deserializationOptions), {
- phase: "Deserialize"
- });
- return pipeline2;
-}
-var init_pipeline4 = __esm(() => {
- init_deserializationPolicy();
- init_esm7();
- init_serializationPolicy();
-});
-
-// node_modules/@azure/core-client/dist/esm/httpClientCache.js
-function getCachedDefaultHttpClient() {
- if (!cachedHttpClient) {
- cachedHttpClient = createDefaultHttpClient2();
- }
- return cachedHttpClient;
-}
-var cachedHttpClient;
-var init_httpClientCache = __esm(() => {
- init_esm7();
-});
-
-// node_modules/@azure/core-client/dist/esm/urlHelpers.js
-function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) {
- const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject);
- let isAbsolutePath = false;
- let requestUrl = replaceAll(baseUri, urlReplacements);
- if (operationSpec.path) {
- let path12 = replaceAll(operationSpec.path, urlReplacements);
- if (operationSpec.path === "/{nextLink}" && path12.startsWith("/")) {
- path12 = path12.substring(1);
- }
- if (isAbsoluteUrl(path12)) {
- requestUrl = path12;
- isAbsolutePath = true;
- } else {
- requestUrl = appendPath(requestUrl, path12);
- }
- }
- const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject);
- requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);
- return requestUrl;
-}
-function replaceAll(input, replacements2) {
- let result = input;
- for (const [searchValue, replaceValue] of replacements2) {
- result = result.split(searchValue).join(replaceValue);
- }
- return result;
-}
-function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) {
- const result = new Map;
- if (operationSpec.urlParameters?.length) {
- for (const urlParameter of operationSpec.urlParameters) {
- let urlParameterValue = getOperationArgumentValueFromParameter(operationArguments, urlParameter, fallbackObject);
- const parameterPathString = getPathStringFromParameter(urlParameter);
- urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString);
- if (!urlParameter.skipEncoding) {
- urlParameterValue = encodeURIComponent(urlParameterValue);
- }
- result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue);
- }
- }
- return result;
-}
-function isAbsoluteUrl(url3) {
- return url3.includes("://");
-}
-function appendPath(url3, pathToAppend) {
- if (!pathToAppend) {
- return url3;
- }
- const parsedUrl = new URL(url3);
- let newPath = parsedUrl.pathname;
- if (!newPath.endsWith("/")) {
- newPath = `${newPath}/`;
- }
- if (pathToAppend.startsWith("/")) {
- pathToAppend = pathToAppend.substring(1);
- }
- const searchStart = pathToAppend.indexOf("?");
- if (searchStart !== -1) {
- const path12 = pathToAppend.substring(0, searchStart);
- const search = pathToAppend.substring(searchStart + 1);
- newPath = newPath + path12;
- if (search) {
- parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;
- }
- } else {
- newPath = newPath + pathToAppend;
- }
- parsedUrl.pathname = newPath;
- return parsedUrl.toString();
-}
-function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) {
- const result = new Map;
- const sequenceParams = new Set;
- if (operationSpec.queryParameters?.length) {
- for (const queryParameter of operationSpec.queryParameters) {
- if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) {
- sequenceParams.add(queryParameter.mapper.serializedName);
- }
- let queryParameterValue = getOperationArgumentValueFromParameter(operationArguments, queryParameter, fallbackObject);
- if (queryParameterValue !== undefined && queryParameterValue !== null || queryParameter.mapper.required) {
- queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
- const delimiter = queryParameter.collectionFormat ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat] : "";
- if (Array.isArray(queryParameterValue)) {
- 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);
- }
- }
- if (Array.isArray(queryParameterValue) && (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) {
- queryParameterValue = queryParameterValue.join(delimiter);
- }
- result.set(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
- }
- }
- }
- return {
- queryParams: result,
- sequenceParams
- };
-}
-function simpleParseQueryParams(queryString) {
- const result = new Map;
- if (!queryString || queryString[0] !== "?") {
- return result;
- }
- queryString = queryString.slice(1);
- const pairs = queryString.split("&");
- for (const pair of pairs) {
- const [name3, value] = pair.split("=", 2);
- const existingValue = result.get(name3);
- if (existingValue) {
- if (Array.isArray(existingValue)) {
- existingValue.push(value);
- } else {
- result.set(name3, [existingValue, value]);
- }
- } else {
- result.set(name3, value);
- }
- }
- return result;
-}
-function appendQueryParams(url3, queryParams, sequenceParams, noOverwrite = false) {
- if (queryParams.size === 0) {
- return url3;
- }
- const parsedUrl = new URL(url3);
- const combinedParams = simpleParseQueryParams(parsedUrl.search);
- for (const [name3, value] of queryParams) {
- const existingValue = combinedParams.get(name3);
- if (Array.isArray(existingValue)) {
- if (Array.isArray(value)) {
- existingValue.push(...value);
- const valueSet = new Set(existingValue);
- combinedParams.set(name3, Array.from(valueSet));
- } else {
- existingValue.push(value);
- }
- } else if (existingValue) {
- if (Array.isArray(value)) {
- value.unshift(existingValue);
- } else if (sequenceParams.has(name3)) {
- combinedParams.set(name3, [existingValue, value]);
- }
- if (!noOverwrite) {
- combinedParams.set(name3, value);
- }
- } else {
- combinedParams.set(name3, value);
- }
- }
- const searchPieces = [];
- for (const [name3, value] of combinedParams) {
- if (typeof value === "string") {
- searchPieces.push(`${name3}=${value}`);
- } else if (Array.isArray(value)) {
- for (const subValue of value) {
- searchPieces.push(`${name3}=${subValue}`);
- }
- } else {
- searchPieces.push(`${name3}=${value}`);
- }
- }
- parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
- return parsedUrl.toString();
-}
-var CollectionFormatToDelimiterMap;
-var init_urlHelpers = __esm(() => {
- init_operationHelpers();
- init_interfaceHelpers();
- CollectionFormatToDelimiterMap = {
- CSV: ",",
- SSV: " ",
- Multi: "Multi",
- TSV: "\t",
- Pipes: "|"
- };
-});
-
-// node_modules/@azure/core-client/dist/esm/log.js
-var logger13;
-var init_log10 = __esm(() => {
- init_esm2();
- logger13 = createClientLogger2("core-client");
-});
-
-// node_modules/@azure/core-client/dist/esm/serviceClient.js
-class ServiceClient {
- _endpoint;
- _requestContentType;
- _allowInsecureConnection;
- _httpClient;
- pipeline;
- constructor(options2 = {}) {
- this._requestContentType = options2.requestContentType;
- this._endpoint = options2.endpoint ?? options2.baseUri;
- if (options2.baseUri) {
- logger13.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.");
- }
- this._allowInsecureConnection = options2.allowInsecureConnection;
- this._httpClient = options2.httpClient || getCachedDefaultHttpClient();
- this.pipeline = options2.pipeline || createDefaultPipeline(options2);
- if (options2.additionalPolicies?.length) {
- for (const { policy, position: position2 } of options2.additionalPolicies) {
- const afterPhase = position2 === "perRetry" ? "Sign" : undefined;
- this.pipeline.addPolicy(policy, {
- afterPhase
- });
- }
- }
- }
- async sendRequest(request2) {
- return this.pipeline.sendRequest(this._httpClient, request2);
- }
- async sendOperationRequest(operationArguments, operationSpec) {
- const endpoint7 = operationSpec.baseUrl || this._endpoint;
- if (!endpoint7) {
- 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.");
- }
- const url3 = getRequestUrl(endpoint7, operationSpec, operationArguments, this);
- const request2 = createPipelineRequest2({
- url: url3
- });
- request2.method = operationSpec.httpMethod;
- const operationInfo = getOperationRequestInfo(request2);
- operationInfo.operationSpec = operationSpec;
- operationInfo.operationArguments = operationArguments;
- const contentType = operationSpec.contentType || this._requestContentType;
- if (contentType && operationSpec.requestBody) {
- request2.headers.set("Content-Type", contentType);
- }
- const options2 = operationArguments.options;
- if (options2) {
- const requestOptions = options2.requestOptions;
- if (requestOptions) {
- if (requestOptions.timeout) {
- request2.timeout = requestOptions.timeout;
- }
- if (requestOptions.onUploadProgress) {
- request2.onUploadProgress = requestOptions.onUploadProgress;
- }
- if (requestOptions.onDownloadProgress) {
- request2.onDownloadProgress = requestOptions.onDownloadProgress;
- }
- if (requestOptions.shouldDeserialize !== undefined) {
- operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;
- }
- if (requestOptions.allowInsecureConnection) {
- request2.allowInsecureConnection = true;
- }
- }
- if (options2.abortSignal) {
- request2.abortSignal = options2.abortSignal;
- }
- if (options2.tracingOptions) {
- request2.tracingOptions = options2.tracingOptions;
- }
- }
- if (this._allowInsecureConnection) {
- request2.allowInsecureConnection = true;
- }
- if (request2.streamResponseStatusCodes === undefined) {
- request2.streamResponseStatusCodes = getStreamingResponseStatusCodes(operationSpec);
- }
- try {
- const rawResponse = await this.sendRequest(request2);
- const flatResponse = flattenResponse(rawResponse, operationSpec.responses[rawResponse.status]);
- if (options2?.onResponse) {
- options2.onResponse(rawResponse, flatResponse);
- }
- return flatResponse;
- } catch (error44) {
- if (typeof error44 === "object" && error44?.response) {
- const rawResponse = error44.response;
- const flatResponse = flattenResponse(rawResponse, operationSpec.responses[error44.statusCode] || operationSpec.responses["default"]);
- error44.details = flatResponse;
- if (options2?.onResponse) {
- options2.onResponse(rawResponse, flatResponse, error44);
- }
- }
- throw error44;
- }
- }
-}
-function createDefaultPipeline(options2) {
- const credentialScopes = getCredentialScopes(options2);
- const credentialOptions = options2.credential && credentialScopes ? { credentialScopes, credential: options2.credential } : undefined;
- return createClientPipeline({
- ...options2,
- credentialOptions
- });
-}
-function getCredentialScopes(options2) {
- if (options2.credentialScopes) {
- return options2.credentialScopes;
- }
- if (options2.endpoint) {
- return `${options2.endpoint}/.default`;
- }
- if (options2.baseUri) {
- return `${options2.baseUri}/.default`;
- }
- if (options2.credential && !options2.credentialScopes) {
- throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`);
- }
- return;
-}
-var init_serviceClient = __esm(() => {
- init_esm7();
- init_pipeline4();
- init_utils5();
- init_httpClientCache();
- init_operationHelpers();
- init_urlHelpers();
- init_interfaceHelpers();
- init_log10();
-});
-
-// node_modules/@azure/core-client/dist/esm/index.js
-var init_esm8 = __esm(() => {
- init_serviceClient();
-});
-
-// node_modules/@azure/identity/dist/esm/util/identityTokenEndpoint.js
-function getIdentityTokenEndpointSuffix(tenantId) {
- if (tenantId === "adfs") {
- return "oauth2/token";
- } else {
- return "oauth2/v2.0/token";
- }
-}
-
-// node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/utils.js
-function mapScopesToResource(scopes) {
- let scope = "";
- if (Array.isArray(scopes)) {
- if (scopes.length !== 1) {
- return;
- }
- scope = scopes[0];
- } else if (typeof scopes === "string") {
- scope = scopes;
- }
- if (!scope.endsWith(DefaultScopeSuffix)) {
- return scope;
- }
- return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix));
-}
-function parseExpirationTimestamp(body) {
- if (typeof body.expires_on === "number") {
- return body.expires_on * 1000;
- }
- if (typeof body.expires_on === "string") {
- const asNumber = +body.expires_on;
- if (!isNaN(asNumber)) {
- return asNumber * 1000;
- }
- const asDate = Date.parse(body.expires_on);
- if (!isNaN(asDate)) {
- return asDate;
- }
- }
- if (typeof body.expires_in === "number") {
- return Date.now() + body.expires_in * 1000;
- }
- throw new Error(`Failed to parse token expiration from body. expires_in="${body.expires_in}", expires_on="${body.expires_on}"`);
-}
-function parseRefreshTimestamp(body) {
- if (body.refresh_on) {
- if (typeof body.refresh_on === "number") {
- return body.refresh_on * 1000;
- }
- if (typeof body.refresh_on === "string") {
- const asNumber = +body.refresh_on;
- if (!isNaN(asNumber)) {
- return asNumber * 1000;
- }
- const asDate = Date.parse(body.refresh_on);
- if (!isNaN(asDate)) {
- return asDate;
- }
- }
- throw new Error(`Failed to parse refresh_on from body. refresh_on="${body.refresh_on}"`);
- } else {
- return;
- }
-}
-var DefaultScopeSuffix = "/.default", serviceFabricErrorMessage = "Specifying a `clientId` or `resourceId` is not supported by the Service Fabric managed identity environment. The managed identity configuration is determined by the Service Fabric cluster resource configuration. See https://aka.ms/servicefabricmi for more information";
-
-// node_modules/@azure/identity/dist/esm/client/identityClient.js
-function getIdentityClientAuthorityHost(options2) {
- let authorityHost = options2?.authorityHost;
- if (isNode) {
- authorityHost = authorityHost ?? process.env.AZURE_AUTHORITY_HOST;
- }
- return authorityHost ?? DefaultAuthorityHost;
-}
-var noCorrelationId = "noCorrelationId", IdentityClient;
-var init_identityClient = __esm(() => {
- init_esm8();
- init_esm5();
- init_esm7();
- init_errors7();
- init_constants9();
- init_tracing();
- init_logging();
- IdentityClient = class IdentityClient extends ServiceClient {
- authorityHost;
- allowLoggingAccountIdentifiers;
- abortControllers;
- allowInsecureConnection = false;
- tokenCredentialOptions;
- constructor(options2) {
- const packageDetails = `azsdk-js-identity/${SDK_VERSION2}`;
- const userAgentPrefix = options2?.userAgentOptions?.userAgentPrefix ? `${options2.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`;
- const baseUri = getIdentityClientAuthorityHost(options2);
- if (!baseUri.startsWith("https:")) {
- throw new Error("The authorityHost address must use the 'https' protocol.");
- }
- super({
- requestContentType: "application/json; charset=utf-8",
- retryOptions: {
- maxRetries: 3
- },
- ...options2,
- userAgentOptions: {
- userAgentPrefix
- },
- baseUri
- });
- this.authorityHost = baseUri;
- this.abortControllers = new Map;
- this.allowLoggingAccountIdentifiers = options2?.loggingOptions?.allowLoggingAccountIdentifiers;
- this.tokenCredentialOptions = { ...options2 };
- if (options2?.allowInsecureConnection) {
- this.allowInsecureConnection = options2.allowInsecureConnection;
- }
- }
- async sendTokenRequest(request2) {
- logger8.info(`IdentityClient: sending token request to [${request2.url}]`);
- const response7 = await this.sendRequest(request2);
- if (response7.bodyAsText && (response7.status === 200 || response7.status === 201)) {
- const parsedBody = JSON.parse(response7.bodyAsText);
- if (!parsedBody.access_token) {
- return null;
- }
- this.logIdentifiers(response7);
- const token = {
- accessToken: {
- token: parsedBody.access_token,
- expiresOnTimestamp: parseExpirationTimestamp(parsedBody),
- refreshAfterTimestamp: parseRefreshTimestamp(parsedBody),
- tokenType: "Bearer"
- },
- refreshToken: parsedBody.refresh_token
- };
- logger8.info(`IdentityClient: [${request2.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`);
- return token;
- } else {
- const error44 = new AuthenticationError4(response7.status, response7.bodyAsText);
- logger8.warning(`IdentityClient: authentication error. HTTP status: ${response7.status}, ${error44.errorResponse.errorDescription}`);
- throw error44;
- }
- }
- async refreshAccessToken(tenantId, clientId, scopes, refreshToken, clientSecret, options2 = {}) {
- if (refreshToken === undefined) {
- return null;
- }
- logger8.info(`IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`);
- const refreshParams = {
- grant_type: "refresh_token",
- client_id: clientId,
- refresh_token: refreshToken,
- scope: scopes
- };
- if (clientSecret !== undefined) {
- refreshParams.client_secret = clientSecret;
- }
- const query = new URLSearchParams(refreshParams);
- return tracingClient.withSpan("IdentityClient.refreshAccessToken", options2, async (updatedOptions) => {
- try {
- const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);
- const request2 = createPipelineRequest2({
- url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,
- method: "POST",
- body: query.toString(),
- abortSignal: options2.abortSignal,
- headers: createHttpHeaders2({
- Accept: "application/json",
- "Content-Type": "application/x-www-form-urlencoded"
- }),
- tracingOptions: updatedOptions.tracingOptions
- });
- const response7 = await this.sendTokenRequest(request2);
- logger8.info(`IdentityClient: refreshed token for client ID: ${clientId}`);
- return response7;
- } catch (err) {
- if (err.name === AuthenticationErrorName && err.errorResponse.error === "interaction_required") {
- logger8.info(`IdentityClient: interaction required for client ID: ${clientId}`);
- return null;
- } else {
- logger8.warning(`IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`);
- throw err;
- }
- }
- });
- }
- generateAbortSignal(correlationId) {
- const controller = new AbortController;
- const controllers = this.abortControllers.get(correlationId) || [];
- controllers.push(controller);
- this.abortControllers.set(correlationId, controllers);
- const existingOnAbort = controller.signal.onabort;
- controller.signal.onabort = (...params) => {
- this.abortControllers.set(correlationId, undefined);
- if (existingOnAbort) {
- existingOnAbort.apply(controller.signal, params);
- }
- };
- return controller.signal;
- }
- abortRequests(correlationId) {
- const key = correlationId || noCorrelationId;
- const controllers = [
- ...this.abortControllers.get(key) || [],
- ...this.abortControllers.get(noCorrelationId) || []
- ];
- if (!controllers.length) {
- return;
- }
- for (const controller of controllers) {
- controller.abort();
- }
- this.abortControllers.set(key, undefined);
- }
- getCorrelationId(options2) {
- const parameter = options2?.body?.split("&").map((part) => part.split("=")).find(([key]) => key === "client-request-id");
- return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId;
- }
- async sendGetRequestAsync(url3, options2) {
- const request2 = createPipelineRequest2({
- url: url3,
- method: "GET",
- body: options2?.body,
- allowInsecureConnection: this.allowInsecureConnection,
- headers: createHttpHeaders2(options2?.headers),
- abortSignal: this.generateAbortSignal(noCorrelationId)
- });
- const response7 = await this.sendRequest(request2);
- this.logIdentifiers(response7);
- return {
- body: response7.bodyAsText ? JSON.parse(response7.bodyAsText) : undefined,
- headers: response7.headers.toJSON(),
- status: response7.status
- };
- }
- async sendPostRequestAsync(url3, options2) {
- const request2 = createPipelineRequest2({
- url: url3,
- method: "POST",
- body: options2?.body,
- headers: createHttpHeaders2(options2?.headers),
- allowInsecureConnection: this.allowInsecureConnection,
- abortSignal: this.generateAbortSignal(this.getCorrelationId(options2))
- });
- const response7 = await this.sendRequest(request2);
- this.logIdentifiers(response7);
- return {
- body: response7.bodyAsText ? JSON.parse(response7.bodyAsText) : undefined,
- headers: response7.headers.toJSON(),
- status: response7.status
- };
- }
- getTokenCredentialOptions() {
- return this.tokenCredentialOptions;
- }
- logIdentifiers(response7) {
- if (!this.allowLoggingAccountIdentifiers || !response7.bodyAsText) {
- return;
- }
- const unavailableUpn = "No User Principal Name available";
- try {
- const parsed = response7.parsedBody || JSON.parse(response7.bodyAsText);
- const accessToken = parsed.access_token;
- if (!accessToken) {
- return;
- }
- const base64Metadata = accessToken.split(".")[1];
- const { appid, upn, tid, oid } = JSON.parse(Buffer.from(base64Metadata, "base64").toString("utf8"));
- logger8.info(`[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${upn || unavailableUpn}. Object ID (user): ${oid}`);
- } catch (e4) {
- logger8.warning("allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:", e4.message);
- }
- }
- };
-});
-
-// node_modules/@azure/identity/dist/esm/regionalAuthority.js
-function calculateRegionalAuthority(regionalAuthority) {
- let azureRegion = regionalAuthority;
- if (azureRegion === undefined && globalThis.process?.env?.AZURE_REGIONAL_AUTHORITY_NAME !== undefined) {
- azureRegion = process.env.AZURE_REGIONAL_AUTHORITY_NAME;
- }
- if (azureRegion === RegionalAuthority.AutoDiscoverRegion) {
- return "AUTO_DISCOVER";
- }
- return azureRegion;
-}
-var RegionalAuthority;
-var init_regionalAuthority = __esm(() => {
- (function(RegionalAuthority2) {
- RegionalAuthority2["AutoDiscoverRegion"] = "AutoDiscoverRegion";
- RegionalAuthority2["USWest"] = "westus";
- RegionalAuthority2["USWest2"] = "westus2";
- RegionalAuthority2["USCentral"] = "centralus";
- RegionalAuthority2["USEast"] = "eastus";
- RegionalAuthority2["USEast2"] = "eastus2";
- RegionalAuthority2["USNorthCentral"] = "northcentralus";
- RegionalAuthority2["USSouthCentral"] = "southcentralus";
- RegionalAuthority2["USWestCentral"] = "westcentralus";
- RegionalAuthority2["CanadaCentral"] = "canadacentral";
- RegionalAuthority2["CanadaEast"] = "canadaeast";
- RegionalAuthority2["BrazilSouth"] = "brazilsouth";
- RegionalAuthority2["EuropeNorth"] = "northeurope";
- RegionalAuthority2["EuropeWest"] = "westeurope";
- RegionalAuthority2["UKSouth"] = "uksouth";
- RegionalAuthority2["UKWest"] = "ukwest";
- RegionalAuthority2["FranceCentral"] = "francecentral";
- RegionalAuthority2["FranceSouth"] = "francesouth";
- RegionalAuthority2["SwitzerlandNorth"] = "switzerlandnorth";
- RegionalAuthority2["SwitzerlandWest"] = "switzerlandwest";
- RegionalAuthority2["GermanyNorth"] = "germanynorth";
- RegionalAuthority2["GermanyWestCentral"] = "germanywestcentral";
- RegionalAuthority2["NorwayWest"] = "norwaywest";
- RegionalAuthority2["NorwayEast"] = "norwayeast";
- RegionalAuthority2["AsiaEast"] = "eastasia";
- RegionalAuthority2["AsiaSouthEast"] = "southeastasia";
- RegionalAuthority2["JapanEast"] = "japaneast";
- RegionalAuthority2["JapanWest"] = "japanwest";
- RegionalAuthority2["AustraliaEast"] = "australiaeast";
- RegionalAuthority2["AustraliaSouthEast"] = "australiasoutheast";
- RegionalAuthority2["AustraliaCentral"] = "australiacentral";
- RegionalAuthority2["AustraliaCentral2"] = "australiacentral2";
- RegionalAuthority2["IndiaCentral"] = "centralindia";
- RegionalAuthority2["IndiaSouth"] = "southindia";
- RegionalAuthority2["IndiaWest"] = "westindia";
- RegionalAuthority2["KoreaSouth"] = "koreasouth";
- RegionalAuthority2["KoreaCentral"] = "koreacentral";
- RegionalAuthority2["UAECentral"] = "uaecentral";
- RegionalAuthority2["UAENorth"] = "uaenorth";
- RegionalAuthority2["SouthAfricaNorth"] = "southafricanorth";
- RegionalAuthority2["SouthAfricaWest"] = "southafricawest";
- RegionalAuthority2["ChinaNorth"] = "chinanorth";
- RegionalAuthority2["ChinaEast"] = "chinaeast";
- RegionalAuthority2["ChinaNorth2"] = "chinanorth2";
- RegionalAuthority2["ChinaEast2"] = "chinaeast2";
- RegionalAuthority2["GermanyCentral"] = "germanycentral";
- RegionalAuthority2["GermanyNorthEast"] = "germanynortheast";
- RegionalAuthority2["GovernmentUSVirginia"] = "usgovvirginia";
- RegionalAuthority2["GovernmentUSIowa"] = "usgoviowa";
- RegionalAuthority2["GovernmentUSArizona"] = "usgovarizona";
- RegionalAuthority2["GovernmentUSTexas"] = "usgovtexas";
- RegionalAuthority2["GovernmentUSDodEast"] = "usdodeast";
- RegionalAuthority2["GovernmentUSDodCentral"] = "usdodcentral";
- })(RegionalAuthority || (RegionalAuthority = {}));
-});
-
-// node_modules/@azure/identity/dist/esm/util/processMultiTenantRequest.js
-function createConfigurationErrorMessage(tenantId) {
- return `The current credential is not configured to acquire tokens for tenant ${tenantId}. To enable acquiring tokens for this tenant add it to the AdditionallyAllowedTenants on the credential options, or add "*" to AdditionallyAllowedTenants to allow acquiring tokens for any tenant.`;
-}
-function processMultiTenantRequest(tenantId, getTokenOptions, additionallyAllowedTenantIds = [], logger14) {
- let resolvedTenantId;
- if (process.env.AZURE_IDENTITY_DISABLE_MULTITENANTAUTH) {
- resolvedTenantId = tenantId;
- } else if (tenantId === "adfs") {
- resolvedTenantId = tenantId;
- } else {
- resolvedTenantId = getTokenOptions?.tenantId ?? tenantId;
- }
- if (tenantId && resolvedTenantId !== tenantId && !additionallyAllowedTenantIds.includes("*") && !additionallyAllowedTenantIds.some((t4) => t4.localeCompare(resolvedTenantId) === 0)) {
- const message = createConfigurationErrorMessage(resolvedTenantId);
- logger14?.info(message);
- throw new CredentialUnavailableError(message);
- }
- return resolvedTenantId;
-}
-var init_processMultiTenantRequest = __esm(() => {
- init_errors7();
-});
-
-// node_modules/@azure/identity/dist/esm/util/tenantIdUtils.js
-function checkTenantId(logger14, tenantId) {
- if (!tenantId.match(/^[0-9a-zA-Z-.]+$/)) {
- const error44 = new Error("Invalid tenant id provided. You can locate your tenant id by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names.");
- logger14.info(formatError2("", error44));
- throw error44;
- }
-}
-function resolveTenantId(logger14, tenantId, clientId) {
- if (tenantId) {
- checkTenantId(logger14, tenantId);
- return tenantId;
- }
- if (!clientId) {
- clientId = DeveloperSignOnClientId;
- }
- if (clientId !== DeveloperSignOnClientId) {
- return "common";
- }
- return "organizations";
-}
-function resolveAdditionallyAllowedTenantIds(additionallyAllowedTenants) {
- if (!additionallyAllowedTenants || additionallyAllowedTenants.length === 0) {
- return [];
- }
- if (additionallyAllowedTenants.includes("*")) {
- return ALL_TENANTS;
- }
- return additionallyAllowedTenants;
-}
-var init_tenantIdUtils = __esm(() => {
- init_constants9();
- init_logging();
- init_processMultiTenantRequest();
-});
-
-// node_modules/is-docker/index.js
-import fs4 from "fs";
-function hasDockerEnv() {
- try {
- fs4.statSync("/.dockerenv");
- return true;
- } catch {
- return false;
- }
-}
-function hasDockerCGroup() {
- try {
- return fs4.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
- } catch {
- return false;
- }
-}
-function isDocker() {
- if (isDockerCached === undefined) {
- isDockerCached = hasDockerEnv() || hasDockerCGroup();
- }
- return isDockerCached;
-}
-var isDockerCached;
-var init_is_docker = () => {};
-
-// node_modules/is-inside-container/index.js
-import fs5 from "fs";
-function isInsideContainer() {
- if (cachedResult === undefined) {
- cachedResult = hasContainerEnv() || isDocker();
- }
- return cachedResult;
-}
-var cachedResult, hasContainerEnv = () => {
- try {
- fs5.statSync("/run/.containerenv");
- return true;
- } catch {
- return false;
- }
-};
-var init_is_inside_container = __esm(() => {
- init_is_docker();
-});
-
-// node_modules/is-wsl/index.js
-import process14 from "process";
-import os4 from "os";
-import fs6 from "fs";
-var isWsl = () => {
- if (process14.platform !== "linux") {
- return false;
- }
- if (os4.release().toLowerCase().includes("microsoft")) {
- if (isInsideContainer()) {
- return false;
- }
- return true;
- }
- try {
- if (fs6.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft")) {
- return !isInsideContainer();
- }
- } catch {}
- if (fs6.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop") || fs6.existsSync("/run/WSL")) {
- return !isInsideContainer();
- }
- return false;
-}, is_wsl_default;
-var init_is_wsl = __esm(() => {
- init_is_inside_container();
- is_wsl_default = process14.env.__IS_WSL_TEST__ ? isWsl : isWsl();
-});
-
-// node_modules/wsl-utils/index.js
-import process15 from "process";
-import fs7, { constants as fsConstants } from "fs/promises";
-var wslDrivesMountPoint, powerShellPathFromWsl = async () => {
- const mountPoint = await wslDrivesMountPoint();
- return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
-}, powerShellPath = async () => {
- if (is_wsl_default) {
- return powerShellPathFromWsl();
- }
- return `${process15.env.SYSTEMROOT || process15.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
-};
-var init_wsl_utils = __esm(() => {
- init_is_wsl();
- init_is_wsl();
- wslDrivesMountPoint = (() => {
- const defaultMountPoint = "/mnt/";
- let mountPoint;
- return async function() {
- if (mountPoint) {
- return mountPoint;
- }
- const configFilePath = "/etc/wsl.conf";
- let isConfigFileExists = false;
- try {
- await fs7.access(configFilePath, fsConstants.F_OK);
- isConfigFileExists = true;
- } catch {}
- if (!isConfigFileExists) {
- return defaultMountPoint;
- }
- const configContent = await fs7.readFile(configFilePath, { encoding: "utf8" });
- const configMountPoint = /(?.*)/g.exec(configContent);
- if (!configMountPoint) {
- return defaultMountPoint;
- }
- mountPoint = configMountPoint.groups.mountPoint.trim();
- mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
- return mountPoint;
- };
- })();
-});
-
-// node_modules/define-lazy-prop/index.js
-function defineLazyProperty(object2, propertyName, valueGetter) {
- const define2 = (value) => Object.defineProperty(object2, propertyName, { value, enumerable: true, writable: true });
- Object.defineProperty(object2, propertyName, {
- configurable: true,
- enumerable: true,
- get() {
- const result = valueGetter();
- define2(result);
- return result;
- },
- set(value) {
- define2(value);
- }
- });
- return object2;
-}
-
-// node_modules/default-browser-id/index.js
-import { promisify as promisify5 } from "util";
-import process16 from "process";
-import { execFile as execFile3 } from "child_process";
-async function defaultBrowserId() {
- if (process16.platform !== "darwin") {
- throw new Error("macOS only");
- }
- const { stdout } = await execFileAsync2("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
- const match = /LSHandlerRoleAll = "(?!-)(?[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
- const browserId = match?.groups.id ?? "com.apple.Safari";
- if (browserId === "com.apple.safari") {
- return "com.apple.Safari";
- }
- return browserId;
-}
-var execFileAsync2;
-var init_default_browser_id = __esm(() => {
- execFileAsync2 = promisify5(execFile3);
-});
-
-// node_modules/run-applescript/index.js
-import process17 from "process";
-import { promisify as promisify6 } from "util";
-import { execFile as execFile4, execFileSync } from "child_process";
-async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
- if (process17.platform !== "darwin") {
- throw new Error("macOS only");
- }
- const outputArguments = humanReadableOutput ? [] : ["-ss"];
- const execOptions = {};
- if (signal) {
- execOptions.signal = signal;
- }
- const { stdout } = await execFileAsync3("osascript", ["-e", script, outputArguments], execOptions);
- return stdout.trim();
-}
-var execFileAsync3;
-var init_run_applescript = __esm(() => {
- execFileAsync3 = promisify6(execFile4);
-});
-
-// node_modules/bundle-name/index.js
-async function bundleName(bundleId) {
- return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
-tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
-}
-var init_bundle_name = __esm(() => {
- init_run_applescript();
-});
-
-// node_modules/default-browser/windows.js
-import { promisify as promisify7 } from "util";
-import { execFile as execFile5 } from "child_process";
-async function defaultBrowser(_execFileAsync = execFileAsync4) {
- const { stdout } = await _execFileAsync("reg", [
- "QUERY",
- " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
- "/v",
- "ProgId"
- ]);
- const match = /ProgId\s*REG_SZ\s*(?\S+)/.exec(stdout);
- if (!match) {
- throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
- }
- const { id } = match.groups;
- const dotIndex = id.lastIndexOf(".");
- const hyphenIndex = id.lastIndexOf("-");
- const baseIdByDot = dotIndex === -1 ? undefined : id.slice(0, dotIndex);
- const baseIdByHyphen = hyphenIndex === -1 ? undefined : id.slice(0, hyphenIndex);
- return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? { name: id, id };
-}
-var execFileAsync4, windowsBrowserProgIds, _windowsBrowserProgIdMap, UnknownBrowserError;
-var init_windows = __esm(() => {
- execFileAsync4 = promisify7(execFile5);
- windowsBrowserProgIds = {
- MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
- MSEdgeBHTML: { name: "Edge Beta", id: "com.microsoft.edge.beta" },
- MSEdgeDHTML: { name: "Edge Dev", id: "com.microsoft.edge.dev" },
- AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
- ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
- ChromeBHTML: { name: "Chrome Beta", id: "com.google.chrome.beta" },
- ChromeDHTML: { name: "Chrome Dev", id: "com.google.chrome.dev" },
- ChromiumHTM: { name: "Chromium", id: "org.chromium.Chromium" },
- BraveHTML: { name: "Brave", id: "com.brave.Browser" },
- BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
- BraveDHTML: { name: "Brave Dev", id: "com.brave.Browser.dev" },
- BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" },
- FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
- OperaStable: { name: "Opera", id: "com.operasoftware.Opera" },
- VivaldiHTM: { name: "Vivaldi", id: "com.vivaldi.Vivaldi" },
- "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" }
- };
- _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
- UnknownBrowserError = class UnknownBrowserError extends Error {
- };
-});
-
-// node_modules/default-browser/index.js
-import { promisify as promisify8 } from "util";
-import process18 from "process";
-import { execFile as execFile6 } from "child_process";
-async function defaultBrowser2() {
- if (process18.platform === "darwin") {
- const id = await defaultBrowserId();
- const name3 = await bundleName(id);
- return { name: name3, id };
- }
- if (process18.platform === "linux") {
- const { stdout } = await execFileAsync5("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
- const id = stdout.trim();
- const name3 = titleize(id.replace(/.desktop$/, "").replace("-", " "));
- return { name: name3, id };
- }
- if (process18.platform === "win32") {
- return defaultBrowser();
- }
- throw new Error("Only macOS, Linux, and Windows are supported");
-}
-var execFileAsync5, titleize = (string4) => string4.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x3) => x3.toUpperCase());
-var init_default_browser = __esm(() => {
- init_default_browser_id();
- init_bundle_name();
- init_windows();
- execFileAsync5 = promisify8(execFile6);
-});
-
-// node_modules/open/index.js
-var exports_open = {};
-__export(exports_open, {
- openApp: () => openApp,
- default: () => open_default,
- apps: () => apps
-});
-import process19 from "process";
-import { Buffer as Buffer13 } from "buffer";
-import path12 from "path";
-import { fileURLToPath as fileURLToPath3 } from "url";
-import { promisify as promisify9 } from "util";
-import childProcess from "child_process";
-import fs8, { constants as fsConstants2 } from "fs/promises";
-async function getWindowsDefaultBrowserFromWsl() {
- const powershellPath = await powerShellPath();
- const rawCommand = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
- const encodedCommand = Buffer13.from(rawCommand, "utf16le").toString("base64");
- const { stdout } = await execFile7(powershellPath, [
- "-NoProfile",
- "-NonInteractive",
- "-ExecutionPolicy",
- "Bypass",
- "-EncodedCommand",
- encodedCommand
- ], { encoding: "utf8" });
- const progId = stdout.trim();
- const browserMap = {
- ChromeHTML: "com.google.chrome",
- BraveHTML: "com.brave.Browser",
- MSEdgeHTM: "com.microsoft.edge",
- FirefoxURL: "org.mozilla.firefox"
- };
- return browserMap[progId] ? { id: browserMap[progId] } : {};
-}
-function detectArchBinary(binary) {
- if (typeof binary === "string" || Array.isArray(binary)) {
- return binary;
- }
- const { [arch]: archBinary } = binary;
- if (!archBinary) {
- throw new Error(`${arch} is not supported`);
- }
- return archBinary;
-}
-function detectPlatformBinary({ [platform2]: platformBinary }, { wsl }) {
- if (wsl && is_wsl_default) {
- return detectArchBinary(wsl);
- }
- if (!platformBinary) {
- throw new Error(`${platform2} is not supported`);
- }
- return detectArchBinary(platformBinary);
-}
-var execFile7, __dirname2, localXdgOpenPath, platform2, arch, pTryEach = async (array2, mapper) => {
- let latestError;
- for (const item of array2) {
- try {
- return await mapper(item);
- } catch (error44) {
- latestError = error44;
- }
- }
- throw latestError;
-}, baseOpen = async (options2) => {
- options2 = {
- wait: false,
- background: false,
- newInstance: false,
- allowNonzeroExitCode: false,
- ...options2
- };
- if (Array.isArray(options2.app)) {
- return pTryEach(options2.app, (singleApp) => baseOpen({
- ...options2,
- app: singleApp
- }));
- }
- let { name: app, arguments: appArguments = [] } = options2.app ?? {};
- appArguments = [...appArguments];
- if (Array.isArray(app)) {
- return pTryEach(app, (appName) => baseOpen({
- ...options2,
- app: {
- name: appName,
- arguments: appArguments
- }
- }));
- }
- if (app === "browser" || app === "browserPrivate") {
- const ids = {
- "com.google.chrome": "chrome",
- "google-chrome.desktop": "chrome",
- "com.brave.Browser": "brave",
- "org.mozilla.firefox": "firefox",
- "firefox.desktop": "firefox",
- "com.microsoft.msedge": "edge",
- "com.microsoft.edge": "edge",
- "com.microsoft.edgemac": "edge",
- "microsoft-edge.desktop": "edge"
- };
- const flags = {
- chrome: "--incognito",
- brave: "--incognito",
- firefox: "--private-window",
- edge: "--inPrivate"
- };
- const browser = is_wsl_default ? await getWindowsDefaultBrowserFromWsl() : await defaultBrowser2();
- if (browser.id in ids) {
- const browserName = ids[browser.id];
- if (app === "browserPrivate") {
- appArguments.push(flags[browserName]);
- }
- return baseOpen({
- ...options2,
- app: {
- name: apps[browserName],
- arguments: appArguments
- }
- });
- }
- throw new Error(`${browser.name} is not supported as a default browser`);
- }
- let command12;
- const cliArguments = [];
- const childProcessOptions = {};
- if (platform2 === "darwin") {
- command12 = "open";
- if (options2.wait) {
- cliArguments.push("--wait-apps");
- }
- if (options2.background) {
- cliArguments.push("--background");
- }
- if (options2.newInstance) {
- cliArguments.push("--new");
- }
- if (app) {
- cliArguments.push("-a", app);
- }
- } else if (platform2 === "win32" || is_wsl_default && !isInsideContainer() && !app) {
- command12 = await powerShellPath();
- cliArguments.push("-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand");
- if (!is_wsl_default) {
- childProcessOptions.windowsVerbatimArguments = true;
- }
- const encodedArguments = ["Start"];
- if (options2.wait) {
- encodedArguments.push("-Wait");
- }
- if (app) {
- encodedArguments.push(`"\`"${app}\`""`);
- if (options2.target) {
- appArguments.push(options2.target);
- }
- } else if (options2.target) {
- encodedArguments.push(`"${options2.target}"`);
- }
- if (appArguments.length > 0) {
- appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
- encodedArguments.push("-ArgumentList", appArguments.join(","));
- }
- options2.target = Buffer13.from(encodedArguments.join(" "), "utf16le").toString("base64");
- } else {
- if (app) {
- command12 = app;
- } else {
- const isBundled = !__dirname2 || __dirname2 === "/";
- let exeLocalXdgOpen = false;
- try {
- await fs8.access(localXdgOpenPath, fsConstants2.X_OK);
- exeLocalXdgOpen = true;
- } catch {}
- const useSystemXdgOpen = process19.versions.electron ?? (platform2 === "android" || isBundled || !exeLocalXdgOpen);
- command12 = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
- }
- if (appArguments.length > 0) {
- cliArguments.push(...appArguments);
- }
- if (!options2.wait) {
- childProcessOptions.stdio = "ignore";
- childProcessOptions.detached = true;
- }
- }
- if (platform2 === "darwin" && appArguments.length > 0) {
- cliArguments.push("--args", ...appArguments);
- }
- if (options2.target) {
- cliArguments.push(options2.target);
- }
- const subprocess = childProcess.spawn(command12, cliArguments, childProcessOptions);
- if (options2.wait) {
- return new Promise((resolve9, reject) => {
- subprocess.once("error", reject);
- subprocess.once("close", (exitCode) => {
- if (!options2.allowNonzeroExitCode && exitCode > 0) {
- reject(new Error(`Exited with code ${exitCode}`));
- return;
- }
- resolve9(subprocess);
- });
- });
- }
- subprocess.unref();
- return subprocess;
-}, open4 = (target, options2) => {
- if (typeof target !== "string") {
- throw new TypeError("Expected a `target`");
- }
- return baseOpen({
- ...options2,
- target
- });
-}, openApp = (name3, options2) => {
- if (typeof name3 !== "string" && !Array.isArray(name3)) {
- throw new TypeError("Expected a valid `name`");
- }
- const { arguments: appArguments = [] } = options2 ?? {};
- if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) {
- throw new TypeError("Expected `appArguments` as Array type");
- }
- return baseOpen({
- ...options2,
- app: {
- name: name3,
- arguments: appArguments
- }
- });
-}, apps, open_default;
-var init_open = __esm(() => {
- init_wsl_utils();
- init_default_browser();
- init_is_inside_container();
- execFile7 = promisify9(childProcess.execFile);
- __dirname2 = path12.dirname(fileURLToPath3(import.meta.url));
- localXdgOpenPath = path12.join(__dirname2, "xdg-open");
- ({ platform: platform2, arch } = process19);
- apps = {};
- defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
- darwin: "google chrome",
- win32: "chrome",
- linux: ["google-chrome", "google-chrome-stable", "chromium"]
- }, {
- wsl: {
- ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
- x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
- }
- }));
- defineLazyProperty(apps, "brave", () => detectPlatformBinary({
- darwin: "brave browser",
- win32: "brave",
- linux: ["brave-browser", "brave"]
- }, {
- wsl: {
- ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
- x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
- }
- }));
- defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
- darwin: "firefox",
- win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
- linux: "firefox"
- }, {
- wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
- }));
- defineLazyProperty(apps, "edge", () => detectPlatformBinary({
- darwin: "microsoft edge",
- win32: "msedge",
- linux: ["microsoft-edge", "microsoft-edge-dev"]
- }, {
- wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
- }));
- defineLazyProperty(apps, "browser", () => "browser");
- defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
- open_default = open4;
-});
-
-// node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalClient.js
-function generateMsalConfiguration(clientId, tenantId, msalClientOptions = {}) {
- const resolvedTenant = resolveTenantId(msalClientOptions.logger ?? msalLogger, tenantId, clientId);
- const authority = getAuthority(resolvedTenant, getAuthorityHost(msalClientOptions));
- const httpClient = new IdentityClient({
- ...msalClientOptions.tokenCredentialOptions,
- authorityHost: authority,
- loggingOptions: msalClientOptions.loggingOptions
- });
- const msalConfig = {
- auth: {
- clientId,
- authority,
- knownAuthorities: getKnownAuthorities(resolvedTenant, authority, msalClientOptions.disableInstanceDiscovery)
- },
- system: {
- networkClient: httpClient,
- loggerOptions: {
- loggerCallback: defaultLoggerCallback(msalClientOptions.logger ?? msalLogger),
- logLevel: getMSALLogLevel(getLogLevel()),
- piiLoggingEnabled: msalClientOptions.loggingOptions?.enableUnsafeSupportLogging
- }
- }
- };
- return msalConfig;
-}
-function createMsalClient(clientId, tenantId, createMsalClientOptions = {}) {
- const state3 = {
- msalConfig: generateMsalConfiguration(clientId, tenantId, createMsalClientOptions),
- cachedAccount: createMsalClientOptions.authenticationRecord ? publicToMsal(createMsalClientOptions.authenticationRecord) : null,
- pluginConfiguration: msalPlugins.generatePluginConfiguration(createMsalClientOptions),
- logger: createMsalClientOptions.logger ?? msalLogger
- };
- const publicApps = new Map;
- async function getPublicApp(options2 = {}) {
- const appKey = options2.enableCae ? "CAE" : "default";
- let publicClientApp = publicApps.get(appKey);
- if (publicClientApp) {
- state3.logger.getToken.info("Existing PublicClientApplication found in cache, returning it.");
- return publicClientApp;
- }
- state3.logger.getToken.info(`Creating new PublicClientApplication with CAE ${options2.enableCae ? "enabled" : "disabled"}.`);
- const cachePlugin = options2.enableCae ? state3.pluginConfiguration.cache.cachePluginCae : state3.pluginConfiguration.cache.cachePlugin;
- state3.msalConfig.auth.clientCapabilities = options2.enableCae ? ["cp1"] : undefined;
- publicClientApp = new PublicClientApplication({
- ...state3.msalConfig,
- broker: { nativeBrokerPlugin: state3.pluginConfiguration.broker.nativeBrokerPlugin },
- cache: { cachePlugin: await cachePlugin }
- });
- publicApps.set(appKey, publicClientApp);
- return publicClientApp;
- }
- const confidentialApps = new Map;
- async function getConfidentialApp(options2 = {}) {
- const appKey = options2.enableCae ? "CAE" : "default";
- let confidentialClientApp = confidentialApps.get(appKey);
- if (confidentialClientApp) {
- state3.logger.getToken.info("Existing ConfidentialClientApplication found in cache, returning it.");
- return confidentialClientApp;
- }
- state3.logger.getToken.info(`Creating new ConfidentialClientApplication with CAE ${options2.enableCae ? "enabled" : "disabled"}.`);
- const cachePlugin = options2.enableCae ? state3.pluginConfiguration.cache.cachePluginCae : state3.pluginConfiguration.cache.cachePlugin;
- state3.msalConfig.auth.clientCapabilities = options2.enableCae ? ["cp1"] : undefined;
- confidentialClientApp = new ConfidentialClientApplication({
- ...state3.msalConfig,
- broker: { nativeBrokerPlugin: state3.pluginConfiguration.broker.nativeBrokerPlugin },
- cache: { cachePlugin: await cachePlugin }
- });
- confidentialApps.set(appKey, confidentialClientApp);
- return confidentialClientApp;
- }
- async function getTokenSilent(app, scopes, options2 = {}) {
- if (state3.cachedAccount === null) {
- state3.logger.getToken.info("No cached account found in local state.");
- throw new AuthenticationRequiredError({ scopes });
- }
- if (options2.claims) {
- state3.cachedClaims = options2.claims;
- }
- const silentRequest = {
- account: state3.cachedAccount,
- scopes,
- claims: state3.cachedClaims
- };
- if (state3.pluginConfiguration.broker.isEnabled) {
- silentRequest.extraQueryParameters ||= {};
- if (state3.pluginConfiguration.broker.enableMsaPassthrough) {
- silentRequest.extraQueryParameters["msal_request_type"] = "consumer_passthrough";
- }
- }
- if (options2.proofOfPossessionOptions) {
- silentRequest.shrNonce = options2.proofOfPossessionOptions.nonce;
- silentRequest.authenticationScheme = "pop";
- silentRequest.resourceRequestMethod = options2.proofOfPossessionOptions.resourceRequestMethod;
- silentRequest.resourceRequestUri = options2.proofOfPossessionOptions.resourceRequestUrl;
- }
- state3.logger.getToken.info("Attempting to acquire token silently");
- try {
- return await app.acquireTokenSilent(silentRequest);
- } catch (err) {
- throw handleMsalError(scopes, err, options2);
- }
- }
- function calculateRequestAuthority(options2) {
- if (options2?.tenantId) {
- return getAuthority(options2.tenantId, getAuthorityHost(createMsalClientOptions));
- }
- return state3.msalConfig.auth.authority;
- }
- async function withSilentAuthentication(msalApp, scopes, options2, onAuthenticationRequired) {
- let response7 = null;
- try {
- response7 = await getTokenSilent(msalApp, scopes, options2);
- } catch (e4) {
- if (e4.name !== "AuthenticationRequiredError") {
- throw e4;
- }
- if (options2.disableAutomaticAuthentication) {
- throw new AuthenticationRequiredError({
- scopes,
- getTokenOptions: options2,
- message: "Automatic authentication has been disabled. You may call the authentication() method."
- });
- }
- }
- if (response7 === null) {
- try {
- response7 = await onAuthenticationRequired();
- } catch (err) {
- throw handleMsalError(scopes, err, options2);
- }
- }
- ensureValidMsalToken(scopes, response7, options2);
- state3.cachedAccount = response7?.account ?? null;
- state3.logger.getToken.info(formatSuccess(scopes));
- return {
- token: response7.accessToken,
- expiresOnTimestamp: response7.expiresOn.getTime(),
- refreshAfterTimestamp: response7.refreshOn?.getTime(),
- tokenType: response7.tokenType
- };
- }
- async function getTokenByClientSecret(scopes, clientSecret, options2 = {}) {
- state3.logger.getToken.info(`Attempting to acquire token using client secret`);
- state3.msalConfig.auth.clientSecret = clientSecret;
- const msalApp = await getConfidentialApp(options2);
- try {
- const response7 = await msalApp.acquireTokenByClientCredential({
- scopes,
- authority: calculateRequestAuthority(options2),
- azureRegion: calculateRegionalAuthority(),
- claims: options2?.claims
- });
- ensureValidMsalToken(scopes, response7, options2);
- state3.logger.getToken.info(formatSuccess(scopes));
- return {
- token: response7.accessToken,
- expiresOnTimestamp: response7.expiresOn.getTime(),
- refreshAfterTimestamp: response7.refreshOn?.getTime(),
- tokenType: response7.tokenType
- };
- } catch (err) {
- throw handleMsalError(scopes, err, options2);
- }
- }
- async function getTokenByClientAssertion(scopes, clientAssertion, options2 = {}) {
- state3.logger.getToken.info(`Attempting to acquire token using client assertion`);
- state3.msalConfig.auth.clientAssertion = clientAssertion;
- const msalApp = await getConfidentialApp(options2);
- try {
- const response7 = await msalApp.acquireTokenByClientCredential({
- scopes,
- authority: calculateRequestAuthority(options2),
- azureRegion: calculateRegionalAuthority(),
- claims: options2?.claims,
- clientAssertion
- });
- ensureValidMsalToken(scopes, response7, options2);
- state3.logger.getToken.info(formatSuccess(scopes));
- return {
- token: response7.accessToken,
- expiresOnTimestamp: response7.expiresOn.getTime(),
- refreshAfterTimestamp: response7.refreshOn?.getTime(),
- tokenType: response7.tokenType
- };
- } catch (err) {
- throw handleMsalError(scopes, err, options2);
- }
- }
- async function getTokenByClientCertificate(scopes, certificate, options2 = {}) {
- state3.logger.getToken.info(`Attempting to acquire token using client certificate`);
- state3.msalConfig.auth.clientCertificate = certificate;
- const msalApp = await getConfidentialApp(options2);
- try {
- const response7 = await msalApp.acquireTokenByClientCredential({
- scopes,
- authority: calculateRequestAuthority(options2),
- azureRegion: calculateRegionalAuthority(),
- claims: options2?.claims
- });
- ensureValidMsalToken(scopes, response7, options2);
- state3.logger.getToken.info(formatSuccess(scopes));
- return {
- token: response7.accessToken,
- expiresOnTimestamp: response7.expiresOn.getTime(),
- refreshAfterTimestamp: response7.refreshOn?.getTime(),
- tokenType: response7.tokenType
- };
- } catch (err) {
- throw handleMsalError(scopes, err, options2);
- }
- }
- async function getTokenByDeviceCode(scopes, deviceCodeCallback, options2 = {}) {
- state3.logger.getToken.info(`Attempting to acquire token using device code`);
- const msalApp = await getPublicApp(options2);
- return withSilentAuthentication(msalApp, scopes, options2, () => {
- const requestOptions = {
- scopes,
- cancel: options2?.abortSignal?.aborted ?? false,
- deviceCodeCallback,
- authority: calculateRequestAuthority(options2),
- claims: options2?.claims
- };
- const deviceCodeRequest = msalApp.acquireTokenByDeviceCode(requestOptions);
- if (options2.abortSignal) {
- options2.abortSignal.addEventListener("abort", () => {
- requestOptions.cancel = true;
- });
- }
- return deviceCodeRequest;
- });
- }
- async function getTokenByUsernamePassword(scopes, username, password, options2 = {}) {
- state3.logger.getToken.info(`Attempting to acquire token using username and password`);
- const msalApp = await getPublicApp(options2);
- return withSilentAuthentication(msalApp, scopes, options2, () => {
- const requestOptions = {
- scopes,
- username,
- password,
- authority: calculateRequestAuthority(options2),
- claims: options2?.claims
- };
- return msalApp.acquireTokenByUsernamePassword(requestOptions);
- });
- }
- function getActiveAccount() {
- if (!state3.cachedAccount) {
- return;
- }
- return msalToPublic(clientId, state3.cachedAccount);
- }
- async function getTokenByAuthorizationCode(scopes, redirectUri, authorizationCode, clientSecret, options2 = {}) {
- state3.logger.getToken.info(`Attempting to acquire token using authorization code`);
- let msalApp;
- if (clientSecret) {
- state3.msalConfig.auth.clientSecret = clientSecret;
- msalApp = await getConfidentialApp(options2);
- } else {
- msalApp = await getPublicApp(options2);
- }
- return withSilentAuthentication(msalApp, scopes, options2, () => {
- return msalApp.acquireTokenByCode({
- scopes,
- redirectUri,
- code: authorizationCode,
- authority: calculateRequestAuthority(options2),
- claims: options2?.claims
- });
- });
- }
- async function getTokenOnBehalfOf(scopes, userAssertionToken, clientCredentials, options2 = {}) {
- msalLogger.getToken.info(`Attempting to acquire token on behalf of another user`);
- if (typeof clientCredentials === "string") {
- msalLogger.getToken.info(`Using client secret for on behalf of flow`);
- state3.msalConfig.auth.clientSecret = clientCredentials;
- } else if (typeof clientCredentials === "function") {
- msalLogger.getToken.info(`Using client assertion callback for on behalf of flow`);
- state3.msalConfig.auth.clientAssertion = clientCredentials;
- } else {
- msalLogger.getToken.info(`Using client certificate for on behalf of flow`);
- state3.msalConfig.auth.clientCertificate = clientCredentials;
- }
- const msalApp = await getConfidentialApp(options2);
- try {
- const response7 = await msalApp.acquireTokenOnBehalfOf({
- scopes,
- authority: calculateRequestAuthority(options2),
- claims: options2.claims,
- oboAssertion: userAssertionToken
- });
- ensureValidMsalToken(scopes, response7, options2);
- msalLogger.getToken.info(formatSuccess(scopes));
- return {
- token: response7.accessToken,
- expiresOnTimestamp: response7.expiresOn.getTime(),
- refreshAfterTimestamp: response7.refreshOn?.getTime(),
- tokenType: response7.tokenType
- };
- } catch (err) {
- throw handleMsalError(scopes, err, options2);
- }
- }
- function createBaseInteractiveRequest(scopes, options2) {
- return {
- openBrowser: async (url3) => {
- const open5 = await Promise.resolve().then(() => (init_open(), exports_open));
- await open5.default(url3, { newInstance: true });
- },
- scopes,
- authority: calculateRequestAuthority(options2),
- claims: options2?.claims,
- loginHint: options2?.loginHint,
- errorTemplate: options2?.browserCustomizationOptions?.errorMessage,
- successTemplate: options2?.browserCustomizationOptions?.successMessage,
- prompt: options2?.loginHint ? "login" : "select_account"
- };
- }
- async function getBrokeredTokenInternal(scopes, useDefaultBrokerAccount, options2 = {}) {
- msalLogger.verbose("Authentication will resume through the broker");
- const app = await getPublicApp(options2);
- const interactiveRequest = createBaseInteractiveRequest(scopes, options2);
- if (state3.pluginConfiguration.broker.parentWindowHandle) {
- interactiveRequest.windowHandle = Buffer.from(state3.pluginConfiguration.broker.parentWindowHandle);
- } else {
- msalLogger.warning("Parent window handle is not specified for the broker. This may cause unexpected behavior. Please provide the parentWindowHandle.");
- }
- if (state3.pluginConfiguration.broker.enableMsaPassthrough) {
- (interactiveRequest.extraQueryParameters ??= {})["msal_request_type"] = "consumer_passthrough";
- }
- if (useDefaultBrokerAccount) {
- interactiveRequest.prompt = "none";
- msalLogger.verbose("Attempting broker authentication using the default broker account");
- } else {
- msalLogger.verbose("Attempting broker authentication without the default broker account");
- }
- if (options2.proofOfPossessionOptions) {
- interactiveRequest.shrNonce = options2.proofOfPossessionOptions.nonce;
- interactiveRequest.authenticationScheme = "pop";
- interactiveRequest.resourceRequestMethod = options2.proofOfPossessionOptions.resourceRequestMethod;
- interactiveRequest.resourceRequestUri = options2.proofOfPossessionOptions.resourceRequestUrl;
- }
- try {
- return await app.acquireTokenInteractive(interactiveRequest);
- } catch (e4) {
- msalLogger.verbose(`Failed to authenticate through the broker: ${e4.message}`);
- if (options2.disableAutomaticAuthentication) {
- throw new AuthenticationRequiredError({
- scopes,
- getTokenOptions: options2,
- message: "Cannot silently authenticate with default broker account."
- });
- }
- if (useDefaultBrokerAccount) {
- return getBrokeredTokenInternal(scopes, false, options2);
- } else {
- throw e4;
- }
- }
- }
- async function getBrokeredToken(scopes, useDefaultBrokerAccount, options2 = {}) {
- msalLogger.getToken.info(`Attempting to acquire token using brokered authentication with useDefaultBrokerAccount: ${useDefaultBrokerAccount}`);
- const response7 = await getBrokeredTokenInternal(scopes, useDefaultBrokerAccount, options2);
- ensureValidMsalToken(scopes, response7, options2);
- state3.cachedAccount = response7?.account ?? null;
- state3.logger.getToken.info(formatSuccess(scopes));
- return {
- token: response7.accessToken,
- expiresOnTimestamp: response7.expiresOn.getTime(),
- refreshAfterTimestamp: response7.refreshOn?.getTime(),
- tokenType: response7.tokenType
- };
- }
- async function getTokenByInteractiveRequest(scopes, options2 = {}) {
- msalLogger.getToken.info(`Attempting to acquire token interactively`);
- const app = await getPublicApp(options2);
- return withSilentAuthentication(app, scopes, options2, async () => {
- const interactiveRequest = createBaseInteractiveRequest(scopes, options2);
- if (state3.pluginConfiguration.broker.isEnabled) {
- return getBrokeredTokenInternal(scopes, state3.pluginConfiguration.broker.useDefaultBrokerAccount ?? false, options2);
- }
- if (options2.proofOfPossessionOptions) {
- interactiveRequest.shrNonce = options2.proofOfPossessionOptions.nonce;
- interactiveRequest.authenticationScheme = "pop";
- interactiveRequest.resourceRequestMethod = options2.proofOfPossessionOptions.resourceRequestMethod;
- interactiveRequest.resourceRequestUri = options2.proofOfPossessionOptions.resourceRequestUrl;
- }
- return app.acquireTokenInteractive(interactiveRequest);
- });
- }
- return {
- getActiveAccount,
- getBrokeredToken,
- getTokenByClientSecret,
- getTokenByClientAssertion,
- getTokenByClientCertificate,
- getTokenByDeviceCode,
- getTokenByUsernamePassword,
- getTokenByAuthorizationCode,
- getTokenOnBehalfOf,
- getTokenByInteractiveRequest
- };
-}
-var msalLogger;
-var init_msalClient = __esm(() => {
- init_dist();
- init_logging();
- init_msalPlugins();
- init_utils4();
- init_errors7();
- init_identityClient();
- init_regionalAuthority();
- init_esm2();
- init_tenantIdUtils();
- msalLogger = credentialLogger("MsalClient");
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/clientCertificateCredential.js
-import { createHash as createHash4, createPrivateKey as createPrivateKey2 } from "crypto";
-import { readFile as readFile8 } from "fs/promises";
-
-class ClientCertificateCredential {
- tenantId;
- additionallyAllowedTenantIds;
- certificateConfiguration;
- sendCertificateChain;
- msalClient;
- constructor(tenantId, clientId, certificatePathOrConfiguration, options2 = {}) {
- if (!tenantId || !clientId) {
- throw new Error(`${credentialName}: tenantId and clientId are required parameters.`);
- }
- this.tenantId = tenantId;
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- this.sendCertificateChain = options2.sendCertificateChain;
- this.certificateConfiguration = {
- ...typeof certificatePathOrConfiguration === "string" ? {
- certificatePath: certificatePathOrConfiguration
- } : certificatePathOrConfiguration
- };
- const certificate = this.certificateConfiguration.certificate;
- const certificatePath = this.certificateConfiguration.certificatePath;
- if (!this.certificateConfiguration || !(certificate || certificatePath)) {
- throw new Error(`${credentialName}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
- }
- if (certificate && certificatePath) {
- throw new Error(`${credentialName}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
- }
- this.msalClient = createMsalClient(clientId, tenantId, {
- ...options2,
- logger: logger14,
- tokenCredentialOptions: options2
- });
- }
- async getToken(scopes, options2 = {}) {
- return tracingClient.withSpan(`${credentialName}.getToken`, options2, async (newOptions) => {
- newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger14);
- const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
- const certificate = await this.buildClientCertificate();
- return this.msalClient.getTokenByClientCertificate(arrayScopes, certificate, newOptions);
- });
- }
- async buildClientCertificate() {
- const parts = await parseCertificate(this.certificateConfiguration, this.sendCertificateChain ?? false);
- let privateKey;
- if (this.certificateConfiguration.certificatePassword !== undefined) {
- privateKey = createPrivateKey2({
- key: parts.certificateContents,
- passphrase: this.certificateConfiguration.certificatePassword,
- format: "pem"
- }).export({
- format: "pem",
- type: "pkcs8"
- }).toString();
- } else {
- privateKey = parts.certificateContents;
- }
- return {
- thumbprint: parts.thumbprint,
- thumbprintSha256: parts.thumbprintSha256,
- privateKey,
- x5c: parts.x5c
- };
- }
-}
-async function parseCertificate(certificateConfiguration, sendCertificateChain) {
- const certificate = certificateConfiguration.certificate;
- const certificatePath = certificateConfiguration.certificatePath;
- const certificateContents = certificate || await readFile8(certificatePath, "utf8");
- const x5c = sendCertificateChain ? certificateContents : undefined;
- const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/g;
- const publicKeys = [];
- let match;
- do {
- match = certificatePattern.exec(certificateContents);
- if (match) {
- publicKeys.push(match[3]);
- }
- } while (match);
- if (publicKeys.length === 0) {
- throw new Error("The file at the specified path does not contain a PEM-encoded certificate.");
- }
- const thumbprint = createHash4("sha1").update(Buffer.from(publicKeys[0], "base64")).digest("hex").toUpperCase();
- const thumbprintSha256 = createHash4("sha256").update(Buffer.from(publicKeys[0], "base64")).digest("hex").toUpperCase();
- return {
- certificateContents,
- thumbprintSha256,
- thumbprint,
- x5c
- };
-}
-var credentialName = "ClientCertificateCredential", logger14;
-var init_clientCertificateCredential = __esm(() => {
- init_msalClient();
- init_tenantIdUtils();
- init_logging();
- init_tracing();
- logger14 = credentialLogger(credentialName);
-});
-
-// node_modules/@azure/identity/dist/esm/util/scopeUtils.js
-function ensureScopes(scopes) {
- return Array.isArray(scopes) ? scopes : [scopes];
-}
-function ensureValidScopeForDevTimeCreds(scope, logger15) {
- if (!scope.match(/^[0-9a-zA-Z-_.:/]+$/)) {
- const error44 = new Error("Invalid scope was specified by the user or calling client");
- logger15.getToken.info(formatError2(scope, error44));
- throw error44;
- }
-}
-function getScopeResource(scope) {
- return scope.replace(/\/.default$/, "");
-}
-var init_scopeUtils = __esm(() => {
- init_logging();
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/clientSecretCredential.js
-class ClientSecretCredential {
- tenantId;
- additionallyAllowedTenantIds;
- msalClient;
- clientSecret;
- constructor(tenantId, clientId, clientSecret, options2 = {}) {
- if (!tenantId) {
- throw new CredentialUnavailableError("ClientSecretCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.");
- }
- if (!clientId) {
- throw new CredentialUnavailableError("ClientSecretCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.");
- }
- if (!clientSecret) {
- throw new CredentialUnavailableError("ClientSecretCredential: clientSecret is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.");
- }
- this.clientSecret = clientSecret;
- this.tenantId = tenantId;
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- this.msalClient = createMsalClient(clientId, tenantId, {
- ...options2,
- logger: logger15,
- tokenCredentialOptions: options2
- });
- }
- async getToken(scopes, options2 = {}) {
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options2, async (newOptions) => {
- newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger15);
- const arrayScopes = ensureScopes(scopes);
- return this.msalClient.getTokenByClientSecret(arrayScopes, this.clientSecret, newOptions);
- });
- }
-}
-var logger15;
-var init_clientSecretCredential = __esm(() => {
- init_msalClient();
- init_tenantIdUtils();
- init_errors7();
- init_logging();
- init_scopeUtils();
- init_tracing();
- logger15 = credentialLogger("ClientSecretCredential");
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/usernamePasswordCredential.js
-class UsernamePasswordCredential {
- tenantId;
- additionallyAllowedTenantIds;
- msalClient;
- username;
- password;
- constructor(tenantId, clientId, username, password, options2 = {}) {
- if (!tenantId) {
- throw new CredentialUnavailableError("UsernamePasswordCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");
- }
- if (!clientId) {
- throw new CredentialUnavailableError("UsernamePasswordCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");
- }
- if (!username) {
- throw new CredentialUnavailableError("UsernamePasswordCredential: username is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");
- }
- if (!password) {
- throw new CredentialUnavailableError("UsernamePasswordCredential: password is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");
- }
- this.tenantId = tenantId;
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- this.username = username;
- this.password = password;
- this.msalClient = createMsalClient(clientId, this.tenantId, {
- ...options2,
- tokenCredentialOptions: options2 ?? {}
- });
- }
- async getToken(scopes, options2 = {}) {
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options2, async (newOptions) => {
- newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger16);
- const arrayScopes = ensureScopes(scopes);
- return this.msalClient.getTokenByUsernamePassword(arrayScopes, this.username, this.password, newOptions);
- });
- }
-}
-var logger16;
-var init_usernamePasswordCredential = __esm(() => {
- init_msalClient();
- init_tenantIdUtils();
- init_errors7();
- init_logging();
- init_scopeUtils();
- init_tracing();
- logger16 = credentialLogger("UsernamePasswordCredential");
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/environmentCredential.js
-function getAdditionallyAllowedTenants() {
- const additionallyAllowedValues = process.env.AZURE_ADDITIONALLY_ALLOWED_TENANTS ?? "";
- return additionallyAllowedValues.split(";");
-}
-function getSendCertificateChain() {
- const sendCertificateChain = (process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN ?? "").toLowerCase();
- const result = sendCertificateChain === "true" || sendCertificateChain === "1";
- logger17.verbose(`AZURE_CLIENT_SEND_CERTIFICATE_CHAIN: ${process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN}; sendCertificateChain: ${result}`);
- return result;
-}
-
-class EnvironmentCredential {
- _credential = undefined;
- constructor(options2) {
- const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(", ");
- logger17.info(`Found the following environment variables: ${assigned}`);
- const tenantId = process.env.AZURE_TENANT_ID, clientId = process.env.AZURE_CLIENT_ID, clientSecret = process.env.AZURE_CLIENT_SECRET;
- const additionallyAllowedTenantIds = getAdditionallyAllowedTenants();
- const sendCertificateChain = getSendCertificateChain();
- const newOptions = { ...options2, additionallyAllowedTenantIds, sendCertificateChain };
- if (tenantId) {
- checkTenantId(logger17, tenantId);
- }
- if (tenantId && clientId && clientSecret) {
- logger17.info(`Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`);
- this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, newOptions);
- return;
- }
- const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH;
- const certificatePassword = process.env.AZURE_CLIENT_CERTIFICATE_PASSWORD;
- if (tenantId && clientId && certificatePath) {
- logger17.info(`Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`);
- this._credential = new ClientCertificateCredential(tenantId, clientId, { certificatePath, certificatePassword }, newOptions);
- return;
- }
- const username = process.env.AZURE_USERNAME;
- const password = process.env.AZURE_PASSWORD;
- if (tenantId && clientId && username && password) {
- logger17.info(`Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`);
- logger17.warning("Environment is configured to use username and password authentication. This authentication method is deprecated, as it doesn't support multifactor authentication (MFA). Use a more secure credential. For more details, see https://aka.ms/azsdk/identity/mfa.");
- this._credential = new UsernamePasswordCredential(tenantId, clientId, username, password, newOptions);
- }
- }
- async getToken(scopes, options2 = {}) {
- return tracingClient.withSpan(`${credentialName2}.getToken`, options2, async (newOptions) => {
- if (this._credential) {
- try {
- const result = await this._credential.getToken(scopes, newOptions);
- logger17.getToken.info(formatSuccess(scopes));
- return result;
- } catch (err) {
- const authenticationError = new AuthenticationError4(400, {
- error: `${credentialName2} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,
- error_description: err.message.toString().split("More details:").join("")
- });
- logger17.getToken.info(formatError2(scopes, authenticationError));
- throw authenticationError;
- }
- }
- throw new CredentialUnavailableError(`${credentialName2} is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`);
- });
- }
-}
-var AllSupportedEnvironmentVariables, credentialName2 = "EnvironmentCredential", logger17;
-var init_environmentCredential = __esm(() => {
- init_errors7();
- init_logging();
- init_clientCertificateCredential();
- init_clientSecretCredential();
- init_usernamePasswordCredential();
- init_tenantIdUtils();
- init_tracing();
- AllSupportedEnvironmentVariables = [
- "AZURE_TENANT_ID",
- "AZURE_CLIENT_ID",
- "AZURE_CLIENT_SECRET",
- "AZURE_CLIENT_CERTIFICATE_PATH",
- "AZURE_CLIENT_CERTIFICATE_PASSWORD",
- "AZURE_USERNAME",
- "AZURE_PASSWORD",
- "AZURE_ADDITIONALLY_ALLOWED_TENANTS",
- "AZURE_CLIENT_SEND_CERTIFICATE_CHAIN"
- ];
- logger17 = credentialLogger(credentialName2);
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsRetryPolicy.js
-function imdsRetryPolicy(msiRetryConfig) {
- return retryPolicy2([
- {
- name: "imdsRetryPolicy",
- retry: ({ retryCount, response: response7 }) => {
- if (response7?.status !== 404 && response7?.status !== 410) {
- return { skipStrategy: true };
- }
- const initialDelayMs = response7?.status === 410 ? Math.max(MIN_DELAY_FOR_410_MS, msiRetryConfig.startDelayInMs) : msiRetryConfig.startDelayInMs;
- return calculateRetryDelay2(retryCount, {
- retryDelayInMs: initialDelayMs,
- maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL2
- });
- }
- }
- ], {
- maxRetries: msiRetryConfig.maxRetries
- });
-}
-var DEFAULT_CLIENT_MAX_RETRY_INTERVAL2, MIN_DELAY_FOR_410_MS = 3000;
-var init_imdsRetryPolicy = __esm(() => {
- init_esm7();
- init_esm5();
- DEFAULT_CLIENT_MAX_RETRY_INTERVAL2 = 1000 * 64;
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsMsi.js
-function prepareInvalidRequestOptions(scopes) {
- const resource = mapScopesToResource(scopes);
- if (!resource) {
- throw new Error(`${msiName}: Multiple scopes are not supported.`);
- }
- const url3 = new URL(imdsEndpointPath, process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST ?? imdsHost);
- const rawHeaders = {
- Accept: "application/json"
- };
- return {
- url: `${url3}`,
- method: "GET",
- headers: createHttpHeaders2(rawHeaders)
- };
-}
-var msiName = "ManagedIdentityCredential - IMDS", logger18, imdsHost = "http://169.254.169.254", imdsEndpointPath = "/metadata/identity/oauth2/token", imdsMsi;
-var init_imdsMsi = __esm(() => {
- init_esm7();
- init_esm5();
- init_logging();
- init_tracing();
- logger18 = credentialLogger(msiName);
- imdsMsi = {
- name: "imdsMsi",
- async isAvailable(options2) {
- const { scopes, identityClient, getTokenOptions } = options2;
- const resource = mapScopesToResource(scopes);
- if (!resource) {
- logger18.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
- return false;
- }
- if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {
- return true;
- }
- if (!identityClient) {
- throw new Error("Missing IdentityClient");
- }
- const requestOptions = prepareInvalidRequestOptions(resource);
- return tracingClient.withSpan("ManagedIdentityCredential-pingImdsEndpoint", getTokenOptions ?? {}, async (updatedOptions) => {
- requestOptions.tracingOptions = updatedOptions.tracingOptions;
- const request2 = createPipelineRequest2(requestOptions);
- request2.timeout = updatedOptions.requestOptions?.timeout || 1000;
- request2.allowInsecureConnection = true;
- let response7;
- try {
- logger18.info(`${msiName}: Pinging the Azure IMDS endpoint`);
- response7 = await identityClient.sendRequest(request2);
- } catch (err) {
- if (isError2(err)) {
- logger18.verbose(`${msiName}: Caught error ${err.name}: ${err.message}`);
- }
- logger18.info(`${msiName}: The Azure IMDS endpoint is unavailable`);
- return false;
- }
- if (response7.status === 403) {
- if (response7.bodyAsText?.includes("unreachable")) {
- logger18.info(`${msiName}: The Azure IMDS endpoint is unavailable`);
- logger18.info(`${msiName}: ${response7.bodyAsText}`);
- return false;
- }
- }
- logger18.info(`${msiName}: The Azure IMDS endpoint is available`);
- return true;
- });
- }
- };
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/clientAssertionCredential.js
-class ClientAssertionCredential {
- msalClient;
- tenantId;
- additionallyAllowedTenantIds;
- getAssertion;
- options;
- constructor(tenantId, clientId, getAssertion, options2 = {}) {
- if (!tenantId) {
- throw new CredentialUnavailableError("ClientAssertionCredential: tenantId is a required parameter.");
- }
- if (!clientId) {
- throw new CredentialUnavailableError("ClientAssertionCredential: clientId is a required parameter.");
- }
- if (!getAssertion) {
- throw new CredentialUnavailableError("ClientAssertionCredential: clientAssertion is a required parameter.");
- }
- this.tenantId = tenantId;
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- this.options = options2;
- this.getAssertion = getAssertion;
- this.msalClient = createMsalClient(clientId, tenantId, {
- ...options2,
- logger: logger19,
- tokenCredentialOptions: this.options
- });
- }
- async getToken(scopes, options2 = {}) {
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options2, async (newOptions) => {
- newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger19);
- const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
- return this.msalClient.getTokenByClientAssertion(arrayScopes, this.getAssertion, newOptions);
- });
- }
-}
-var logger19;
-var init_clientAssertionCredential = __esm(() => {
- init_msalClient();
- init_tenantIdUtils();
- init_errors7();
- init_logging();
- init_tracing();
- logger19 = credentialLogger("ClientAssertionCredential");
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/workloadIdentityCredential.js
-import { readFile as readFile9 } from "fs/promises";
-
-class WorkloadIdentityCredential {
- client;
- azureFederatedTokenFileContent = undefined;
- cacheDate = undefined;
- federatedTokenFilePath;
- constructor(options2) {
- const assignedEnv = processEnvVars(SupportedWorkloadEnvironmentVariables).assigned.join(", ");
- logger20.info(`Found the following environment variables: ${assignedEnv}`);
- const workloadIdentityCredentialOptions = options2 ?? {};
- const tenantId = workloadIdentityCredentialOptions.tenantId || process.env.AZURE_TENANT_ID;
- const clientId = workloadIdentityCredentialOptions.clientId || process.env.AZURE_CLIENT_ID;
- this.federatedTokenFilePath = workloadIdentityCredentialOptions.tokenFilePath || process.env.AZURE_FEDERATED_TOKEN_FILE;
- if (tenantId) {
- checkTenantId(logger20, tenantId);
- }
- if (!clientId) {
- throw new CredentialUnavailableError(`${credentialName3}: is unavailable. clientId is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - "AZURE_CLIENT_ID".
- See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`);
- }
- if (!tenantId) {
- throw new CredentialUnavailableError(`${credentialName3}: is unavailable. tenantId is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - "AZURE_TENANT_ID".
- See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`);
- }
- if (!this.federatedTokenFilePath) {
- throw new CredentialUnavailableError(`${credentialName3}: is unavailable. federatedTokenFilePath is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - "AZURE_FEDERATED_TOKEN_FILE".
- See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`);
- }
- logger20.info(`Invoking ClientAssertionCredential with tenant ID: ${tenantId}, clientId: ${workloadIdentityCredentialOptions.clientId} and federated token path: [REDACTED]`);
- this.client = new ClientAssertionCredential(tenantId, clientId, this.readFileContents.bind(this), options2);
- }
- async getToken(scopes, options2) {
- if (!this.client) {
- const errorMessage2 = `${credentialName3}: is unavailable. tenantId, clientId, and federatedTokenFilePath are required parameters.
- In DefaultAzureCredential and ManagedIdentityCredential, these can be provided as environment variables -
- "AZURE_TENANT_ID",
- "AZURE_CLIENT_ID",
- "AZURE_FEDERATED_TOKEN_FILE". See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`;
- logger20.info(errorMessage2);
- throw new CredentialUnavailableError(errorMessage2);
- }
- logger20.info("Invoking getToken() of Client Assertion Credential");
- return this.client.getToken(scopes, options2);
- }
- async readFileContents() {
- if (this.cacheDate !== undefined && Date.now() - this.cacheDate >= 1000 * 60 * 5) {
- this.azureFederatedTokenFileContent = undefined;
- }
- if (!this.federatedTokenFilePath) {
- throw new CredentialUnavailableError(`${credentialName3}: is unavailable. Invalid file path provided ${this.federatedTokenFilePath}.`);
- }
- if (!this.azureFederatedTokenFileContent) {
- const file2 = await readFile9(this.federatedTokenFilePath, "utf8");
- const value = file2.trim();
- if (!value) {
- throw new CredentialUnavailableError(`${credentialName3}: is unavailable. No content on the file ${this.federatedTokenFilePath}.`);
- } else {
- this.azureFederatedTokenFileContent = value;
- this.cacheDate = Date.now();
- }
- }
- return this.azureFederatedTokenFileContent;
- }
-}
-var credentialName3 = "WorkloadIdentityCredential", SupportedWorkloadEnvironmentVariables, logger20;
-var init_workloadIdentityCredential = __esm(() => {
- init_logging();
- init_clientAssertionCredential();
- init_errors7();
- init_tenantIdUtils();
- SupportedWorkloadEnvironmentVariables = [
- "AZURE_TENANT_ID",
- "AZURE_CLIENT_ID",
- "AZURE_FEDERATED_TOKEN_FILE"
- ];
- logger20 = credentialLogger(credentialName3);
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/tokenExchangeMsi.js
-var msiName2 = "ManagedIdentityCredential - Token Exchange", logger21, tokenExchangeMsi;
-var init_tokenExchangeMsi = __esm(() => {
- init_workloadIdentityCredential();
- init_logging();
- logger21 = credentialLogger(msiName2);
- tokenExchangeMsi = {
- name: "tokenExchangeMsi",
- async isAvailable(clientId) {
- const env5 = process.env;
- const result = Boolean((clientId || env5.AZURE_CLIENT_ID) && env5.AZURE_TENANT_ID && process.env.AZURE_FEDERATED_TOKEN_FILE);
- if (!result) {
- logger21.info(`${msiName2}: Unavailable. The environment variables needed are: AZURE_CLIENT_ID (or the client ID sent through the parameters), AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE`);
- }
- return result;
- },
- async getToken(configuration, getTokenOptions = {}) {
- const { scopes, clientId } = configuration;
- const identityClientTokenCredentialOptions = {};
- const workloadIdentityCredential = new WorkloadIdentityCredential({
- clientId,
- tenantId: process.env.AZURE_TENANT_ID,
- tokenFilePath: process.env.AZURE_FEDERATED_TOKEN_FILE,
- ...identityClientTokenCredentialOptions,
- disableInstanceDiscovery: true
- });
- return workloadIdentityCredential.getToken(scopes, getTokenOptions);
- }
- };
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/index.js
-class ManagedIdentityCredential {
- managedIdentityApp;
- identityClient;
- clientId;
- resourceId;
- objectId;
- msiRetryConfig = {
- maxRetries: 5,
- startDelayInMs: 800,
- intervalIncrement: 2
- };
- isAvailableIdentityClient;
- sendProbeRequest;
- constructor(clientIdOrOptions, options2) {
- let _options;
- if (typeof clientIdOrOptions === "string") {
- this.clientId = clientIdOrOptions;
- _options = options2 ?? {};
- } else {
- this.clientId = clientIdOrOptions?.clientId;
- _options = clientIdOrOptions ?? {};
- }
- this.resourceId = _options?.resourceId;
- this.objectId = _options?.objectId;
- this.sendProbeRequest = _options?.sendProbeRequest ?? false;
- const providedIds = [
- { key: "clientId", value: this.clientId },
- { key: "resourceId", value: this.resourceId },
- { key: "objectId", value: this.objectId }
- ].filter((id) => id.value);
- if (providedIds.length > 1) {
- throw new Error(`ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify({ clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId })}`);
- }
- _options.allowInsecureConnection = true;
- if (_options.retryOptions?.maxRetries !== undefined) {
- this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;
- }
- this.identityClient = new IdentityClient({
- ..._options,
- additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: "perCall" }]
- });
- this.managedIdentityApp = new ManagedIdentityApplication({
- managedIdentityIdParams: {
- userAssignedClientId: this.clientId,
- userAssignedResourceId: this.resourceId,
- userAssignedObjectId: this.objectId
- },
- system: {
- disableInternalRetries: true,
- networkClient: this.identityClient,
- loggerOptions: {
- logLevel: getMSALLogLevel(getLogLevel()),
- piiLoggingEnabled: _options.loggingOptions?.enableUnsafeSupportLogging,
- loggerCallback: defaultLoggerCallback(logger22)
- }
- }
- });
- this.isAvailableIdentityClient = new IdentityClient({
- ..._options,
- retryOptions: {
- maxRetries: 0
- }
- });
- const managedIdentitySource = this.managedIdentityApp.getManagedIdentitySource();
- if (managedIdentitySource === "CloudShell") {
- if (this.clientId || this.resourceId || this.objectId) {
- logger22.warning(`CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify({
- clientId: this.clientId,
- resourceId: this.resourceId,
- objectId: this.objectId
- })}.`);
- throw new CredentialUnavailableError("ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters.");
- }
- }
- if (managedIdentitySource === "ServiceFabric") {
- if (this.clientId || this.resourceId || this.objectId) {
- logger22.warning(`Service Fabric detected with user-provided IDs - throwing. Received values: ${JSON.stringify({
- clientId: this.clientId,
- resourceId: this.resourceId,
- objectId: this.objectId
- })}.`);
- throw new CredentialUnavailableError(`ManagedIdentityCredential: ${serviceFabricErrorMessage}`);
- }
- }
- logger22.info(`Using ${managedIdentitySource} managed identity.`);
- if (providedIds.length === 1) {
- const { key, value } = providedIds[0];
- logger22.info(`${managedIdentitySource} with ${key}: ${value}`);
- }
- }
- async getToken(scopes, options2 = {}) {
- logger22.getToken.info("Using the MSAL provider for Managed Identity.");
- const resource = mapScopesToResource(scopes);
- if (!resource) {
- throw new CredentialUnavailableError(`ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(scopes)}`);
- }
- return tracingClient.withSpan("ManagedIdentityCredential.getToken", options2, async () => {
- try {
- const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable(this.clientId);
- const identitySource = this.managedIdentityApp.getManagedIdentitySource();
- const isImdsMsi = identitySource === "DefaultToImds" || identitySource === "Imds";
- logger22.getToken.info(`MSAL Identity source: ${identitySource}`);
- if (isTokenExchangeMsi) {
- logger22.getToken.info("Using the token exchange managed identity.");
- const result = await tokenExchangeMsi.getToken({
- scopes,
- clientId: this.clientId,
- identityClient: this.identityClient,
- retryConfig: this.msiRetryConfig,
- resourceId: this.resourceId
- });
- if (result === null) {
- throw new CredentialUnavailableError("Attempted to use the token exchange managed identity, but received a null response.");
- }
- return result;
- } else if (isImdsMsi && this.sendProbeRequest) {
- logger22.getToken.info("Using the IMDS endpoint to probe for availability.");
- const isAvailable = await imdsMsi.isAvailable({
- scopes,
- clientId: this.clientId,
- getTokenOptions: options2,
- identityClient: this.isAvailableIdentityClient,
- resourceId: this.resourceId
- });
- if (!isAvailable) {
- throw new CredentialUnavailableError(`Attempted to use the IMDS endpoint, but it is not available.`);
- }
- }
- logger22.getToken.info("Calling into MSAL for managed identity token.");
- const token = await this.managedIdentityApp.acquireToken({
- resource
- });
- this.ensureValidMsalToken(scopes, token, options2);
- logger22.getToken.info(formatSuccess(scopes));
- return {
- expiresOnTimestamp: token.expiresOn.getTime(),
- token: token.accessToken,
- refreshAfterTimestamp: token.refreshOn?.getTime(),
- tokenType: "Bearer"
- };
- } catch (err) {
- logger22.getToken.error(formatError2(scopes, err));
- if (err.name === "AuthenticationRequiredError") {
- throw err;
- }
- if (isNetworkError(err)) {
- throw new CredentialUnavailableError(`ManagedIdentityCredential: Network unreachable. Message: ${err.message}`, { cause: err });
- }
- throw new CredentialUnavailableError(`ManagedIdentityCredential: Authentication failed. Message ${err.message}`, { cause: err });
- }
- });
- }
- ensureValidMsalToken(scopes, msalToken, getTokenOptions) {
- const createError = (message) => {
- logger22.getToken.info(message);
- return new AuthenticationRequiredError({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- getTokenOptions,
- message
- });
- };
- if (!msalToken) {
- throw createError("No response.");
- }
- if (!msalToken.expiresOn) {
- throw createError(`Response had no "expiresOn" property.`);
- }
- if (!msalToken.accessToken) {
- throw createError(`Response had no "accessToken" property.`);
- }
- }
-}
-function isNetworkError(err) {
- if (err.errorCode === "network_error") {
- return true;
- }
- if (err.code === "ENETUNREACH" || err.code === "EHOSTUNREACH") {
- return true;
- }
- if (err.statusCode === 403 || err.code === 403) {
- if (err.message.includes("unreachable")) {
- return true;
- }
- }
- return false;
-}
-var logger22;
-var init_managedIdentityCredential = __esm(() => {
- init_esm2();
- init_dist();
- init_identityClient();
- init_errors7();
- init_utils4();
- init_imdsRetryPolicy();
- init_logging();
- init_tracing();
- init_imdsMsi();
- init_tokenExchangeMsi();
- logger22 = credentialLogger("ManagedIdentityCredential");
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/azureDeveloperCliCredential.js
-import child_process from "child_process";
-
-class AzureDeveloperCliCredential {
- tenantId;
- additionallyAllowedTenantIds;
- timeout;
- constructor(options2) {
- if (options2?.tenantId) {
- checkTenantId(logger23, options2?.tenantId);
- this.tenantId = options2?.tenantId;
- }
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- this.timeout = options2?.processTimeoutInMs;
- }
- async getToken(scopes, options2 = {}) {
- const tenantId = processMultiTenantRequest(this.tenantId, options2, this.additionallyAllowedTenantIds);
- if (tenantId) {
- checkTenantId(logger23, tenantId);
- }
- let scopeList;
- if (typeof scopes === "string") {
- scopeList = [scopes];
- } else {
- scopeList = scopes;
- }
- logger23.getToken.info(`Using the scopes ${scopes}`);
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options2, async () => {
- try {
- scopeList.forEach((scope) => {
- ensureValidScopeForDevTimeCreds(scope, logger23);
- });
- const obj = await developerCliCredentialInternals.getAzdAccessToken(scopeList, tenantId, this.timeout, options2.claims);
- const isMFARequiredError = obj.stderr?.match("must use multi-factor authentication") || obj.stderr?.match("reauthentication required");
- const isNotLoggedInError = obj.stderr?.match("not logged in, run `azd login` to login") || obj.stderr?.match("not logged in, run `azd auth login` to login");
- const isNotInstallError = obj.stderr?.match("azd:(.*)not found") || obj.stderr?.startsWith("'azd' is not recognized");
- if (isNotInstallError || obj.error && obj.error.code === "ENOENT") {
- const error44 = new CredentialUnavailableError(azureDeveloperCliPublicErrorMessages.notInstalled);
- logger23.getToken.info(formatError2(scopes, error44));
- throw error44;
- }
- if (isNotLoggedInError) {
- const error44 = new CredentialUnavailableError(azureDeveloperCliPublicErrorMessages.login);
- logger23.getToken.info(formatError2(scopes, error44));
- throw error44;
- }
- if (isMFARequiredError) {
- const scope = scopeList.reduce((previous, current) => previous.concat("--scope", current), []).join(" ");
- const loginCmd = `azd auth login ${scope}`;
- const error44 = new CredentialUnavailableError(`${azureDeveloperCliPublicErrorMessages.claim} ${loginCmd}`);
- logger23.getToken.info(formatError2(scopes, error44));
- throw error44;
- }
- try {
- const resp = JSON.parse(obj.stdout);
- logger23.getToken.info(formatSuccess(scopes));
- return {
- token: resp.token,
- expiresOnTimestamp: new Date(resp.expiresOn).getTime(),
- tokenType: "Bearer"
- };
- } catch (e4) {
- if (obj.stderr) {
- throw new CredentialUnavailableError(obj.stderr);
- }
- throw e4;
- }
- } catch (err) {
- const error44 = err.name === "CredentialUnavailableError" ? err : new CredentialUnavailableError(err.message || azureDeveloperCliPublicErrorMessages.unknown);
- logger23.getToken.info(formatError2(scopes, error44));
- throw error44;
- }
- });
- }
-}
-var logger23, azureDeveloperCliPublicErrorMessages, developerCliCredentialInternals;
-var init_azureDeveloperCliCredential = __esm(() => {
- init_logging();
- init_errors7();
- init_tenantIdUtils();
- init_tracing();
- init_scopeUtils();
- logger23 = credentialLogger("AzureDeveloperCliCredential");
- azureDeveloperCliPublicErrorMessages = {
- notInstalled: "Azure Developer CLI couldn't be found. To mitigate this issue, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.",
- login: "Please run 'azd auth login' from a command prompt to authenticate before using this credential. For more information, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.",
- unknown: "Unknown error while trying to retrieve the access token",
- claim: "This credential doesn't support claims challenges. To authenticate with the required claims, please run the following command:"
- };
- developerCliCredentialInternals = {
- getSafeWorkingDir() {
- if (process.platform === "win32") {
- let systemRoot = process.env.SystemRoot || process.env["SYSTEMROOT"];
- if (!systemRoot) {
- logger23.getToken.warning("The SystemRoot environment variable is not set. This may cause issues when using the Azure Developer CLI credential.");
- systemRoot = "C:\\Windows";
- }
- return systemRoot;
- } else {
- return "/bin";
- }
- },
- async getAzdAccessToken(scopes, tenantId, timeout, claims) {
- let tenantSection = [];
- if (tenantId) {
- tenantSection = ["--tenant-id", tenantId];
- }
- let claimsSections = [];
- if (claims) {
- const encodedClaims = btoa(claims);
- claimsSections = ["--claims", encodedClaims];
- }
- return new Promise((resolve9, reject) => {
- try {
- const args = [
- "auth",
- "token",
- "--output",
- "json",
- "--no-prompt",
- ...scopes.reduce((previous, current) => previous.concat("--scope", current), []),
- ...tenantSection,
- ...claimsSections
- ];
- const command12 = ["azd", ...args].join(" ");
- child_process.exec(command12, {
- cwd: developerCliCredentialInternals.getSafeWorkingDir(),
- timeout
- }, (error44, stdout, stderr) => {
- resolve9({ stdout, stderr, error: error44 });
- });
- } catch (err) {
- reject(err);
- }
- });
- }
- };
-});
-
-// node_modules/@azure/identity/dist/esm/util/subscriptionUtils.js
-function checkSubscription(logger24, subscription) {
- if (!subscription.match(/^[0-9a-zA-Z-._ ]+$/)) {
- const error44 = new Error(`Subscription '${subscription}' contains invalid characters. If this is the name of a subscription, use ` + `its ID instead. You can locate your subscription by following the instructions listed here: ` + `https://learn.microsoft.com/azure/azure-portal/get-subscription-tenant-id`);
- logger24.info(formatError2("", error44));
- throw error44;
- }
-}
-var init_subscriptionUtils = __esm(() => {
- init_logging();
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/azureCliCredential.js
-import child_process2 from "child_process";
-
-class AzureCliCredential {
- tenantId;
- additionallyAllowedTenantIds;
- timeout;
- subscription;
- constructor(options2) {
- if (options2?.tenantId) {
- checkTenantId(logger24, options2?.tenantId);
- this.tenantId = options2?.tenantId;
- }
- if (options2?.subscription) {
- checkSubscription(logger24, options2?.subscription);
- this.subscription = options2?.subscription;
- }
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- this.timeout = options2?.processTimeoutInMs;
- }
- async getToken(scopes, options2 = {}) {
- const scope = typeof scopes === "string" ? scopes : scopes[0];
- const claimsValue = options2.claims;
- if (claimsValue && claimsValue.trim()) {
- const encodedClaims = btoa(claimsValue);
- let loginCmd = `az login --claims-challenge ${encodedClaims} --scope ${scope}`;
- const tenantIdFromOptions = options2.tenantId;
- if (tenantIdFromOptions) {
- loginCmd += ` --tenant ${tenantIdFromOptions}`;
- }
- const error44 = new CredentialUnavailableError(`${azureCliPublicErrorMessages.claim} ${loginCmd}`);
- logger24.getToken.info(formatError2(scope, error44));
- throw error44;
- }
- const tenantId = processMultiTenantRequest(this.tenantId, options2, this.additionallyAllowedTenantIds);
- if (tenantId) {
- checkTenantId(logger24, tenantId);
- }
- if (this.subscription) {
- checkSubscription(logger24, this.subscription);
- }
- logger24.getToken.info(`Using the scope ${scope}`);
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options2, async () => {
- try {
- ensureValidScopeForDevTimeCreds(scope, logger24);
- const resource = getScopeResource(scope);
- const obj = await cliCredentialInternals.getAzureCliAccessToken(resource, tenantId, this.subscription, this.timeout);
- const specificScope = obj.stderr?.match("(.*)az login --scope(.*)");
- const isLoginError = obj.stderr?.match("(.*)az login(.*)") && !specificScope;
- const isNotInstallError = obj.stderr?.match("az:(.*)not found") || obj.stderr?.startsWith("'az' is not recognized");
- if (isNotInstallError) {
- const error44 = new CredentialUnavailableError(azureCliPublicErrorMessages.notInstalled);
- logger24.getToken.info(formatError2(scopes, error44));
- throw error44;
- }
- if (isLoginError) {
- const error44 = new CredentialUnavailableError(azureCliPublicErrorMessages.login);
- logger24.getToken.info(formatError2(scopes, error44));
- throw error44;
- }
- try {
- const responseData = obj.stdout;
- const response7 = this.parseRawResponse(responseData);
- logger24.getToken.info(formatSuccess(scopes));
- return response7;
- } catch (e4) {
- if (obj.stderr) {
- throw new CredentialUnavailableError(obj.stderr);
- }
- throw e4;
- }
- } catch (err) {
- const error44 = err.name === "CredentialUnavailableError" ? err : new CredentialUnavailableError(err.message || azureCliPublicErrorMessages.unknown);
- logger24.getToken.info(formatError2(scopes, error44));
- throw error44;
- }
- });
- }
- parseRawResponse(rawResponse) {
- const response7 = JSON.parse(rawResponse);
- const token = response7.accessToken;
- let expiresOnTimestamp = Number.parseInt(response7.expires_on, 10) * 1000;
- if (!isNaN(expiresOnTimestamp)) {
- logger24.getToken.info("expires_on is available and is valid, using it");
- return {
- token,
- expiresOnTimestamp,
- tokenType: "Bearer"
- };
- }
- expiresOnTimestamp = new Date(response7.expiresOn).getTime();
- if (isNaN(expiresOnTimestamp)) {
- throw new CredentialUnavailableError(`${azureCliPublicErrorMessages.unexpectedResponse} "${response7.expiresOn}"`);
- }
- return {
- token,
- expiresOnTimestamp,
- tokenType: "Bearer"
- };
- }
-}
-var logger24, azureCliPublicErrorMessages, cliCredentialInternals;
-var init_azureCliCredential = __esm(() => {
- init_tenantIdUtils();
- init_logging();
- init_scopeUtils();
- init_errors7();
- init_tracing();
- init_subscriptionUtils();
- logger24 = credentialLogger("AzureCliCredential");
- azureCliPublicErrorMessages = {
- claim: "This credential doesn't support claims challenges. To authenticate with the required claims, please run the following command:",
- notInstalled: "Azure CLI could not be found. Please visit https://aka.ms/azure-cli for installation instructions and then, once installed, authenticate to your Azure account using 'az login'.",
- login: "Please run 'az login' from a command prompt to authenticate before using this credential.",
- unknown: "Unknown error while trying to retrieve the access token",
- unexpectedResponse: 'Unexpected response from Azure CLI when getting token. Expected "expiresOn" to be a RFC3339 date string. Got:'
- };
- cliCredentialInternals = {
- getSafeWorkingDir() {
- if (process.platform === "win32") {
- let systemRoot = process.env.SystemRoot || process.env["SYSTEMROOT"];
- if (!systemRoot) {
- logger24.getToken.warning("The SystemRoot environment variable is not set. This may cause issues when using the Azure CLI credential.");
- systemRoot = "C:\\Windows";
- }
- return systemRoot;
- } else {
- return "/bin";
- }
- },
- async getAzureCliAccessToken(resource, tenantId, subscription, timeout) {
- let tenantSection = [];
- let subscriptionSection = [];
- if (tenantId) {
- tenantSection = ["--tenant", tenantId];
- }
- if (subscription) {
- subscriptionSection = ["--subscription", `"${subscription}"`];
- }
- return new Promise((resolve9, reject) => {
- try {
- const args = [
- "account",
- "get-access-token",
- "--output",
- "json",
- "--resource",
- resource,
- ...tenantSection,
- ...subscriptionSection
- ];
- const command12 = ["az", ...args].join(" ");
- child_process2.exec(command12, { cwd: cliCredentialInternals.getSafeWorkingDir(), timeout }, (error44, stdout, stderr) => {
- resolve9({ stdout, stderr, error: error44 });
- });
- } catch (err) {
- reject(err);
- }
- });
- }
- };
-});
-
-// node_modules/@azure/identity/dist/esm/util/processUtils.js
-import childProcess2 from "child_process";
-var processUtils;
-var init_processUtils = __esm(() => {
- processUtils = {
- execFile(file2, params, options2) {
- return new Promise((resolve9, reject) => {
- childProcess2.execFile(file2, params, options2, (error44, stdout, stderr) => {
- if (Buffer.isBuffer(stdout)) {
- stdout = stdout.toString("utf8");
- }
- if (Buffer.isBuffer(stderr)) {
- stderr = stderr.toString("utf8");
- }
- if (stderr || error44) {
- reject(stderr ? new Error(stderr) : error44);
- } else {
- resolve9(stdout);
- }
- });
- });
- }
- };
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/azurePowerShellCredential.js
-function formatCommand(commandName) {
- if (isWindows) {
- return `${commandName}.exe`;
- } else {
- return commandName;
- }
-}
-async function runCommands(commands7, timeout) {
- const results = [];
- for (const command12 of commands7) {
- const [file2, ...parameters] = command12;
- const result = await processUtils.execFile(file2, parameters, {
- encoding: "utf8",
- timeout
- });
- results.push(result);
- }
- return results;
-}
-
-class AzurePowerShellCredential {
- tenantId;
- additionallyAllowedTenantIds;
- timeout;
- constructor(options2) {
- if (options2?.tenantId) {
- checkTenantId(logger25, options2?.tenantId);
- this.tenantId = options2?.tenantId;
- }
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- this.timeout = options2?.processTimeoutInMs;
- }
- async getAzurePowerShellAccessToken(resource, tenantId, timeout) {
- for (const powerShellCommand of [...commandStack]) {
- try {
- await runCommands([[powerShellCommand, "/?"]], timeout);
- } catch (e4) {
- commandStack.shift();
- continue;
- }
- const results = await runCommands([
- [
- powerShellCommand,
- "-NoProfile",
- "-NonInteractive",
- "-Command",
- `
- $tenantId = "${tenantId ?? ""}"
- $m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru
- $useSecureString = $m.Version -ge [version]'2.17.0' -and $m.Version -lt [version]'5.0.0'
-
- $params = @{
- ResourceUrl = "${resource}"
- }
-
- if ($tenantId.Length -gt 0) {
- $params["TenantId"] = $tenantId
- }
-
- if ($useSecureString) {
- $params["AsSecureString"] = $true
- }
-
- $token = Get-AzAccessToken @params
-
- $result = New-Object -TypeName PSObject
- $result | Add-Member -MemberType NoteProperty -Name ExpiresOn -Value $token.ExpiresOn
-
- if ($token.Token -is [System.Security.SecureString]) {
- if ($PSVersionTable.PSVersion.Major -lt 7) {
- $ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($token.Token)
- try {
- $result | Add-Member -MemberType NoteProperty -Name Token -Value ([System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr))
- }
- finally {
- [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)
- }
- }
- else {
- $result | Add-Member -MemberType NoteProperty -Name Token -Value ($token.Token | ConvertFrom-SecureString -AsPlainText)
- }
- }
- else {
- $result | Add-Member -MemberType NoteProperty -Name Token -Value $token.Token
- }
-
- Write-Output (ConvertTo-Json $result)
- `
- ]
- ]);
- const result = results[0];
- return parseJsonToken(result);
- }
- throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`);
- }
- async getToken(scopes, options2 = {}) {
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options2, async () => {
- const scope = typeof scopes === "string" ? scopes : scopes[0];
- const claimsValue = options2.claims;
- if (claimsValue && claimsValue.trim()) {
- const encodedClaims = btoa(claimsValue);
- let loginCmd = `Connect-AzAccount -ClaimsChallenge ${encodedClaims}`;
- const tenantIdFromOptions = options2.tenantId;
- if (tenantIdFromOptions) {
- loginCmd += ` -Tenant ${tenantIdFromOptions}`;
- }
- const error44 = new CredentialUnavailableError(`${powerShellPublicErrorMessages.claim} ${loginCmd}`);
- logger25.getToken.info(formatError2(scope, error44));
- throw error44;
- }
- const tenantId = processMultiTenantRequest(this.tenantId, options2, this.additionallyAllowedTenantIds);
- if (tenantId) {
- checkTenantId(logger25, tenantId);
- }
- try {
- ensureValidScopeForDevTimeCreds(scope, logger25);
- logger25.getToken.info(`Using the scope ${scope}`);
- const resource = getScopeResource(scope);
- const response7 = await this.getAzurePowerShellAccessToken(resource, tenantId, this.timeout);
- logger25.getToken.info(formatSuccess(scopes));
- return {
- token: response7.Token,
- expiresOnTimestamp: new Date(response7.ExpiresOn).getTime(),
- tokenType: "Bearer"
- };
- } catch (err) {
- if (isNotInstalledError(err)) {
- const error45 = new CredentialUnavailableError(powerShellPublicErrorMessages.installed);
- logger25.getToken.info(formatError2(scope, error45));
- throw error45;
- } else if (isLoginError(err)) {
- const error45 = new CredentialUnavailableError(powerShellPublicErrorMessages.login);
- logger25.getToken.info(formatError2(scope, error45));
- throw error45;
- }
- const error44 = new CredentialUnavailableError(`${err}. ${powerShellPublicErrorMessages.troubleshoot}`);
- logger25.getToken.info(formatError2(scope, error44));
- throw error44;
- }
- });
- }
-}
-async function parseJsonToken(result) {
- const jsonRegex = /{[^{}]*}/g;
- const matches = result.match(jsonRegex);
- let resultWithoutToken = result;
- if (matches) {
- try {
- for (const item of matches) {
- try {
- const jsonContent = JSON.parse(item);
- if (jsonContent?.Token) {
- resultWithoutToken = resultWithoutToken.replace(item, "");
- if (resultWithoutToken) {
- logger25.getToken.warning(resultWithoutToken);
- }
- return jsonContent;
- }
- } catch (e4) {
- continue;
- }
- }
- } catch (e4) {
- throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`);
- }
- }
- throw new Error(`No access token found in the output. Received output: ${result}`);
-}
-var logger25, isWindows, powerShellErrors, powerShellPublicErrorMessages, isLoginError = (err) => err.message.match(`(.*)${powerShellErrors.login}(.*)`), isNotInstalledError = (err) => err.message.match(powerShellErrors.installed), commandStack;
-var init_azurePowerShellCredential = __esm(() => {
- init_tenantIdUtils();
- init_logging();
- init_scopeUtils();
- init_errors7();
- init_processUtils();
- init_tracing();
- logger25 = credentialLogger("AzurePowerShellCredential");
- isWindows = process.platform === "win32";
- powerShellErrors = {
- login: "Run Connect-AzAccount to login",
- installed: "The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory"
- };
- powerShellPublicErrorMessages = {
- login: "Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.",
- installed: `The 'Az.Account' module >= 2.2.0 is not installed. Install the Azure Az PowerShell module with: "Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force".`,
- claim: "This credential doesn't support claims challenges. To authenticate with the required claims, please run the following command:",
- troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`
- };
- commandStack = [formatCommand("pwsh")];
- if (isWindows) {
- commandStack.push(formatCommand("powershell"));
- }
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/visualStudioCodeCredential.js
-import { readFile as readFile10 } from "fs/promises";
-function checkUnsupportedTenant(tenantId) {
- const unsupportedTenantError = unsupportedTenantIds[tenantId];
- if (unsupportedTenantError) {
- throw new CredentialUnavailableError(unsupportedTenantError);
- }
-}
-
-class VisualStudioCodeCredential {
- tenantId;
- additionallyAllowedTenantIds;
- msalClient;
- options;
- constructor(options2) {
- this.options = options2 || {};
- if (options2 && options2.tenantId) {
- checkTenantId(logger26, options2.tenantId);
- this.tenantId = options2.tenantId;
- } else {
- this.tenantId = CommonTenantId;
- }
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- checkUnsupportedTenant(this.tenantId);
- }
- async prepare(scopes) {
- const tenantId = processMultiTenantRequest(this.tenantId, this.options, this.additionallyAllowedTenantIds, logger26) || this.tenantId;
- if (!hasVSCodePlugin() || !vsCodeAuthRecordPath) {
- throw new CredentialUnavailableError("Visual Studio Code Authentication is not available." + " Ensure you have have Azure Resources Extension installed in VS Code," + " signed into Azure via VS Code, installed the @azure/identity-vscode package," + " and properly configured the extension.");
- }
- const authenticationRecord = await this.loadAuthRecord(vsCodeAuthRecordPath, scopes);
- this.msalClient = createMsalClient(VSCodeClientId, tenantId, {
- ...this.options,
- isVSCodeCredential: true,
- brokerOptions: {
- enabled: true,
- parentWindowHandle: new Uint8Array(0),
- useDefaultBrokerAccount: true
- },
- authenticationRecord
- });
- }
- preparePromise;
- prepareOnce(scopes) {
- if (!this.preparePromise) {
- this.preparePromise = this.prepare(scopes);
- }
- return this.preparePromise;
- }
- async getToken(scopes, options2) {
- const scopeArray = ensureScopes(scopes);
- await this.prepareOnce(scopeArray);
- if (!this.msalClient) {
- throw new CredentialUnavailableError("Visual Studio Code Authentication failed to initialize." + " Ensure you have have Azure Resources Extension installed in VS Code," + " signed into Azure via VS Code, installed the @azure/identity-vscode package," + " and properly configured the extension.");
- }
- return this.msalClient.getTokenByInteractiveRequest(scopeArray, {
- ...options2,
- disableAutomaticAuthentication: true
- });
- }
- async loadAuthRecord(authRecordPath, scopes) {
- try {
- const authRecordContent = await readFile10(authRecordPath, { encoding: "utf8" });
- return deserializeAuthenticationRecord(authRecordContent);
- } catch (error44) {
- logger26.getToken.info(formatError2(scopes, error44));
- throw new CredentialUnavailableError("Cannot load authentication record in Visual Studio Code." + " Ensure you have have Azure Resources Extension installed in VS Code," + " signed into Azure via VS Code, installed the @azure/identity-vscode package," + " and properly configured the extension.");
- }
- }
-}
-var CommonTenantId = "common", VSCodeClientId = "aebc6443-996d-45c2-90f0-388ff96faa56", logger26, unsupportedTenantIds;
-var init_visualStudioCodeCredential = __esm(() => {
- init_logging();
- init_tenantIdUtils();
- init_errors7();
- init_tenantIdUtils();
- init_msalClient();
- init_scopeUtils();
- init_msalPlugins();
- init_utils4();
- logger26 = credentialLogger("VisualStudioCodeCredential");
- unsupportedTenantIds = {
- adfs: "The VisualStudioCodeCredential does not support authentication with ADFS tenants."
- };
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/brokerCredential.js
-class BrokerCredential {
- brokerMsalClient;
- brokerTenantId;
- brokerAdditionallyAllowedTenantIds;
- constructor(options2) {
- this.brokerTenantId = resolveTenantId(logger27, options2.tenantId);
- this.brokerAdditionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- const msalClientOptions = {
- ...options2,
- tokenCredentialOptions: options2,
- logger: logger27,
- brokerOptions: {
- enabled: true,
- parentWindowHandle: new Uint8Array(0),
- useDefaultBrokerAccount: true
- }
- };
- this.brokerMsalClient = createMsalClient(DeveloperSignOnClientId, this.brokerTenantId, msalClientOptions);
- }
- async getToken(scopes, options2 = {}) {
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options2, async (newOptions) => {
- newOptions.tenantId = processMultiTenantRequest(this.brokerTenantId, newOptions, this.brokerAdditionallyAllowedTenantIds, logger27);
- const arrayScopes = ensureScopes(scopes);
- try {
- return this.brokerMsalClient.getBrokeredToken(arrayScopes, true, {
- ...newOptions,
- disableAutomaticAuthentication: true
- });
- } catch (e4) {
- logger27.getToken.info(formatError2(arrayScopes, e4));
- throw new CredentialUnavailableError("Failed to acquire token using broker authentication", { cause: e4 });
- }
- });
- }
-}
-var logger27;
-var init_brokerCredential = __esm(() => {
- init_tenantIdUtils();
- init_logging();
- init_scopeUtils();
- init_tracing();
- init_msalClient();
- init_constants9();
- init_errors7();
- logger27 = credentialLogger("BrokerCredential");
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/defaultAzureCredentialFunctions.js
-function createDefaultBrokerCredential(options2 = {}) {
- return new BrokerCredential(options2);
-}
-function createDefaultVisualStudioCodeCredential(options2 = {}) {
- return new VisualStudioCodeCredential(options2);
-}
-function createDefaultManagedIdentityCredential(options2 = {}) {
- options2.retryOptions ??= {
- maxRetries: 5,
- retryDelayInMs: 800
- };
- options2.sendProbeRequest ??= true;
- const managedIdentityClientId = options2?.managedIdentityClientId ?? process.env.AZURE_CLIENT_ID;
- const workloadIdentityClientId = options2?.workloadIdentityClientId ?? managedIdentityClientId;
- const managedResourceId = options2?.managedIdentityResourceId;
- const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;
- const tenantId = options2?.tenantId ?? process.env.AZURE_TENANT_ID;
- if (managedResourceId) {
- const managedIdentityResourceIdOptions = {
- ...options2,
- resourceId: managedResourceId
- };
- return new ManagedIdentityCredential(managedIdentityResourceIdOptions);
- }
- if (workloadFile && workloadIdentityClientId) {
- const workloadIdentityCredentialOptions = {
- ...options2,
- tenantId
- };
- return new ManagedIdentityCredential(workloadIdentityClientId, workloadIdentityCredentialOptions);
- }
- if (managedIdentityClientId) {
- const managedIdentityClientOptions = {
- ...options2,
- clientId: managedIdentityClientId
- };
- return new ManagedIdentityCredential(managedIdentityClientOptions);
- }
- return new ManagedIdentityCredential(options2);
-}
-function createDefaultWorkloadIdentityCredential(options2) {
- const managedIdentityClientId = options2?.managedIdentityClientId ?? process.env.AZURE_CLIENT_ID;
- const workloadIdentityClientId = options2?.workloadIdentityClientId ?? managedIdentityClientId;
- const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;
- const tenantId = options2?.tenantId ?? process.env.AZURE_TENANT_ID;
- if (workloadFile && workloadIdentityClientId) {
- const workloadIdentityCredentialOptions = {
- ...options2,
- tenantId,
- clientId: workloadIdentityClientId,
- tokenFilePath: workloadFile
- };
- return new WorkloadIdentityCredential(workloadIdentityCredentialOptions);
- }
- if (tenantId) {
- const workloadIdentityClientTenantOptions = {
- ...options2,
- tenantId
- };
- return new WorkloadIdentityCredential(workloadIdentityClientTenantOptions);
- }
- return new WorkloadIdentityCredential(options2);
-}
-function createDefaultAzureDeveloperCliCredential(options2 = {}) {
- return new AzureDeveloperCliCredential(options2);
-}
-function createDefaultAzureCliCredential(options2 = {}) {
- return new AzureCliCredential(options2);
-}
-function createDefaultAzurePowershellCredential(options2 = {}) {
- return new AzurePowerShellCredential(options2);
-}
-function createDefaultEnvironmentCredential(options2 = {}) {
- return new EnvironmentCredential(options2);
-}
-var init_defaultAzureCredentialFunctions = __esm(() => {
- init_environmentCredential();
- init_managedIdentityCredential();
- init_workloadIdentityCredential();
- init_azureDeveloperCliCredential();
- init_azureCliCredential();
- init_azurePowerShellCredential();
- init_visualStudioCodeCredential();
- init_brokerCredential();
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/defaultAzureCredential.js
-class UnavailableDefaultCredential {
- credentialUnavailableErrorMessage;
- credentialName;
- constructor(credentialName4, message) {
- this.credentialName = credentialName4;
- this.credentialUnavailableErrorMessage = message;
- }
- getToken() {
- logger28.getToken.info(`Skipping ${this.credentialName}, reason: ${this.credentialUnavailableErrorMessage}`);
- return Promise.resolve(null);
- }
-}
-function validateRequiredEnvVars(options2) {
- if (options2?.requiredEnvVars) {
- const requiredVars = Array.isArray(options2.requiredEnvVars) ? options2.requiredEnvVars : [options2.requiredEnvVars];
- const missing = requiredVars.filter((envVar) => !process.env[envVar]);
- if (missing.length > 0) {
- const errorMessage2 = `Required environment ${missing.length === 1 ? "variable" : "variables"} '${missing.join(", ")}' for DefaultAzureCredential ${missing.length === 1 ? "is" : "are"} not set or empty.`;
- logger28.warning(errorMessage2);
- throw new Error(errorMessage2);
- }
- }
-}
-var logger28, DefaultAzureCredential;
-var init_defaultAzureCredential = __esm(() => {
- init_chainedTokenCredential();
- init_logging();
- init_defaultAzureCredentialFunctions();
- logger28 = credentialLogger("DefaultAzureCredential");
- DefaultAzureCredential = class DefaultAzureCredential extends ChainedTokenCredential {
- constructor(options2) {
- validateRequiredEnvVars(options2);
- const azureTokenCredentials = process.env.AZURE_TOKEN_CREDENTIALS ? process.env.AZURE_TOKEN_CREDENTIALS.trim().toLowerCase() : undefined;
- const devCredentialFunctions = [
- createDefaultVisualStudioCodeCredential,
- createDefaultAzureCliCredential,
- createDefaultAzurePowershellCredential,
- createDefaultAzureDeveloperCliCredential,
- createDefaultBrokerCredential
- ];
- const prodCredentialFunctions = [
- createDefaultEnvironmentCredential,
- createDefaultWorkloadIdentityCredential,
- createDefaultManagedIdentityCredential
- ];
- let credentialFunctions = [];
- const validCredentialNames = "EnvironmentCredential, WorkloadIdentityCredential, ManagedIdentityCredential, VisualStudioCodeCredential, AzureCliCredential, AzurePowerShellCredential, AzureDeveloperCliCredential";
- if (azureTokenCredentials) {
- switch (azureTokenCredentials) {
- case "dev":
- credentialFunctions = devCredentialFunctions;
- break;
- case "prod":
- credentialFunctions = prodCredentialFunctions;
- break;
- case "environmentcredential":
- credentialFunctions = [createDefaultEnvironmentCredential];
- break;
- case "workloadidentitycredential":
- credentialFunctions = [createDefaultWorkloadIdentityCredential];
- break;
- case "managedidentitycredential":
- credentialFunctions = [
- () => createDefaultManagedIdentityCredential({ sendProbeRequest: false })
- ];
- break;
- case "visualstudiocodecredential":
- credentialFunctions = [createDefaultVisualStudioCodeCredential];
- break;
- case "azureclicredential":
- credentialFunctions = [createDefaultAzureCliCredential];
- break;
- case "azurepowershellcredential":
- credentialFunctions = [createDefaultAzurePowershellCredential];
- break;
- case "azuredeveloperclicredential":
- credentialFunctions = [createDefaultAzureDeveloperCliCredential];
- break;
- default: {
- const errorMessage2 = `Invalid value for AZURE_TOKEN_CREDENTIALS = ${process.env.AZURE_TOKEN_CREDENTIALS}. Valid values are 'prod' or 'dev' or any of these credentials - ${validCredentialNames}.`;
- logger28.warning(errorMessage2);
- throw new Error(errorMessage2);
- }
- }
- } else {
- credentialFunctions = [...prodCredentialFunctions, ...devCredentialFunctions];
- }
- const credentials = credentialFunctions.map((createCredentialFn) => {
- try {
- return createCredentialFn(options2 ?? {});
- } catch (err) {
- logger28.warning(`Skipped ${createCredentialFn.name} because of an error creating the credential: ${err}`);
- return new UnavailableDefaultCredential(createCredentialFn.name, err.message);
- }
- });
- super(...credentials);
- }
- };
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/interactiveBrowserCredential.js
-class InteractiveBrowserCredential {
- tenantId;
- additionallyAllowedTenantIds;
- msalClient;
- disableAutomaticAuthentication;
- browserCustomizationOptions;
- loginHint;
- constructor(options2) {
- this.tenantId = resolveTenantId(logger29, options2.tenantId, options2.clientId);
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- const msalClientOptions = {
- ...options2,
- tokenCredentialOptions: options2,
- logger: logger29
- };
- const ibcNodeOptions = options2;
- this.browserCustomizationOptions = ibcNodeOptions.browserCustomizationOptions;
- this.loginHint = ibcNodeOptions.loginHint;
- if (ibcNodeOptions?.brokerOptions?.enabled) {
- if (!ibcNodeOptions?.brokerOptions?.parentWindowHandle) {
- throw new Error("In order to do WAM authentication, `parentWindowHandle` under `brokerOptions` is a required parameter");
- } else {
- msalClientOptions.brokerOptions = {
- enabled: true,
- parentWindowHandle: ibcNodeOptions.brokerOptions.parentWindowHandle,
- legacyEnableMsaPassthrough: ibcNodeOptions.brokerOptions?.legacyEnableMsaPassthrough,
- useDefaultBrokerAccount: ibcNodeOptions.brokerOptions?.useDefaultBrokerAccount
- };
- }
- }
- this.msalClient = createMsalClient(options2.clientId ?? DeveloperSignOnClientId, this.tenantId, msalClientOptions);
- this.disableAutomaticAuthentication = options2?.disableAutomaticAuthentication;
- }
- async getToken(scopes, options2 = {}) {
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options2, async (newOptions) => {
- newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger29);
- const arrayScopes = ensureScopes(scopes);
- return this.msalClient.getTokenByInteractiveRequest(arrayScopes, {
- ...newOptions,
- disableAutomaticAuthentication: this.disableAutomaticAuthentication,
- browserCustomizationOptions: this.browserCustomizationOptions,
- loginHint: this.loginHint
- });
- });
- }
- async authenticate(scopes, options2 = {}) {
- return tracingClient.withSpan(`${this.constructor.name}.authenticate`, options2, async (newOptions) => {
- const arrayScopes = ensureScopes(scopes);
- await this.msalClient.getTokenByInteractiveRequest(arrayScopes, {
- ...newOptions,
- disableAutomaticAuthentication: false,
- browserCustomizationOptions: this.browserCustomizationOptions,
- loginHint: this.loginHint
- });
- return this.msalClient.getActiveAccount();
- });
- }
-}
-var logger29;
-var init_interactiveBrowserCredential = __esm(() => {
- init_tenantIdUtils();
- init_logging();
- init_scopeUtils();
- init_tracing();
- init_msalClient();
- init_constants9();
- logger29 = credentialLogger("InteractiveBrowserCredential");
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/deviceCodeCredential.js
-function defaultDeviceCodePromptCallback(deviceCodeInfo) {
- console.log(deviceCodeInfo.message);
-}
-
-class DeviceCodeCredential {
- tenantId;
- additionallyAllowedTenantIds;
- disableAutomaticAuthentication;
- msalClient;
- userPromptCallback;
- constructor(options2) {
- this.tenantId = options2?.tenantId;
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- const clientId = options2?.clientId ?? DeveloperSignOnClientId;
- const tenantId = resolveTenantId(logger30, options2?.tenantId, clientId);
- this.userPromptCallback = options2?.userPromptCallback ?? defaultDeviceCodePromptCallback;
- this.msalClient = createMsalClient(clientId, tenantId, {
- ...options2,
- logger: logger30,
- tokenCredentialOptions: options2 || {}
- });
- this.disableAutomaticAuthentication = options2?.disableAutomaticAuthentication;
- }
- async getToken(scopes, options2 = {}) {
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options2, async (newOptions) => {
- newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger30);
- const arrayScopes = ensureScopes(scopes);
- return this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, {
- ...newOptions,
- disableAutomaticAuthentication: this.disableAutomaticAuthentication
- });
- });
- }
- async authenticate(scopes, options2 = {}) {
- return tracingClient.withSpan(`${this.constructor.name}.authenticate`, options2, async (newOptions) => {
- const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
- await this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, {
- ...newOptions,
- disableAutomaticAuthentication: false
- });
- return this.msalClient.getActiveAccount();
- });
- }
-}
-var logger30;
-var init_deviceCodeCredential = __esm(() => {
- init_tenantIdUtils();
- init_logging();
- init_scopeUtils();
- init_tracing();
- init_msalClient();
- init_constants9();
- logger30 = credentialLogger("DeviceCodeCredential");
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/azurePipelinesCredential.js
-class AzurePipelinesCredential {
- clientAssertionCredential;
- identityClient;
- constructor(tenantId, clientId, serviceConnectionId, systemAccessToken, options2 = {}) {
- if (!clientId) {
- throw new CredentialUnavailableError(`${credentialName4}: is unavailable. clientId is a required parameter.`);
- }
- if (!tenantId) {
- throw new CredentialUnavailableError(`${credentialName4}: is unavailable. tenantId is a required parameter.`);
- }
- if (!serviceConnectionId) {
- throw new CredentialUnavailableError(`${credentialName4}: is unavailable. serviceConnectionId is a required parameter.`);
- }
- if (!systemAccessToken) {
- throw new CredentialUnavailableError(`${credentialName4}: is unavailable. systemAccessToken is a required parameter.`);
- }
- options2.loggingOptions = {
- ...options2?.loggingOptions,
- additionalAllowedHeaderNames: [
- ...options2.loggingOptions?.additionalAllowedHeaderNames ?? [],
- "x-vss-e2eid",
- "x-msedge-ref"
- ]
- };
- this.identityClient = new IdentityClient(options2);
- checkTenantId(logger31, tenantId);
- logger31.info(`Invoking AzurePipelinesCredential with tenant ID: ${tenantId}, client ID: ${clientId}, and service connection ID: ${serviceConnectionId}`);
- if (!process.env.SYSTEM_OIDCREQUESTURI) {
- throw new CredentialUnavailableError(`${credentialName4}: is unavailable. Ensure that you're running this task in an Azure Pipeline, so that following missing system variable(s) can be defined- "SYSTEM_OIDCREQUESTURI"`);
- }
- const oidcRequestUrl = `${process.env.SYSTEM_OIDCREQUESTURI}?api-version=${OIDC_API_VERSION}&serviceConnectionId=${serviceConnectionId}`;
- logger31.info(`Invoking ClientAssertionCredential with tenant ID: ${tenantId}, client ID: ${clientId} and service connection ID: ${serviceConnectionId}`);
- this.clientAssertionCredential = new ClientAssertionCredential(tenantId, clientId, this.requestOidcToken.bind(this, oidcRequestUrl, systemAccessToken), options2);
- }
- async getToken(scopes, options2) {
- if (!this.clientAssertionCredential) {
- const errorMessage2 = `${credentialName4}: is unavailable. To use Federation Identity in Azure Pipelines, the following parameters are required -
- tenantId,
- clientId,
- serviceConnectionId,
- systemAccessToken,
- "SYSTEM_OIDCREQUESTURI".
- See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;
- logger31.error(errorMessage2);
- throw new CredentialUnavailableError(errorMessage2);
- }
- logger31.info("Invoking getToken() of Client Assertion Credential");
- return this.clientAssertionCredential.getToken(scopes, options2);
- }
- async requestOidcToken(oidcRequestUrl, systemAccessToken) {
- logger31.info("Requesting OIDC token from Azure Pipelines...");
- logger31.info(oidcRequestUrl);
- const request2 = createPipelineRequest2({
- url: oidcRequestUrl,
- method: "POST",
- headers: createHttpHeaders2({
- "Content-Type": "application/json",
- Authorization: `Bearer ${systemAccessToken}`,
- "X-TFS-FedAuthRedirect": "Suppress"
- })
- });
- const response7 = await this.identityClient.sendRequest(request2);
- return handleOidcResponse(response7);
- }
-}
-function handleOidcResponse(response7) {
- const text = response7.bodyAsText;
- if (!text) {
- logger31.error(`${credentialName4}: Authentication Failed. Received null token from OIDC request. Response status- ${response7.status}. Complete response - ${JSON.stringify(response7)}`);
- throw new AuthenticationError4(response7.status, {
- error: `${credentialName4}: Authentication Failed. Received null token from OIDC request.`,
- error_description: `${JSON.stringify(response7)}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`
- });
- }
- try {
- const result = JSON.parse(text);
- if (result?.oidcToken) {
- return result.oidcToken;
- } else {
- const errorMessage2 = `${credentialName4}: Authentication Failed. oidcToken field not detected in the response.`;
- let errorDescription = ``;
- if (response7.status !== 200) {
- errorDescription = `Response body = ${text}. Response Headers ["x-vss-e2eid"] = ${response7.headers.get("x-vss-e2eid")} and ["x-msedge-ref"] = ${response7.headers.get("x-msedge-ref")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;
- }
- logger31.error(errorMessage2);
- logger31.error(errorDescription);
- throw new AuthenticationError4(response7.status, {
- error: errorMessage2,
- error_description: errorDescription
- });
- }
- } catch (e4) {
- const errorDetails = `${credentialName4}: Authentication Failed. oidcToken field not detected in the response.`;
- logger31.error(`Response from service = ${text}, Response Headers ["x-vss-e2eid"] = ${response7.headers.get("x-vss-e2eid")}
- and ["x-msedge-ref"] = ${response7.headers.get("x-msedge-ref")}, error message = ${e4.message}`);
- logger31.error(errorDetails);
- throw new AuthenticationError4(response7.status, {
- error: errorDetails,
- error_description: `Response = ${text}. Response headers ["x-vss-e2eid"] = ${response7.headers.get("x-vss-e2eid")} and ["x-msedge-ref"] = ${response7.headers.get("x-msedge-ref")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`
- });
- }
-}
-var credentialName4 = "AzurePipelinesCredential", logger31, OIDC_API_VERSION = "7.1";
-var init_azurePipelinesCredential = __esm(() => {
- init_errors7();
- init_esm7();
- init_clientAssertionCredential();
- init_identityClient();
- init_tenantIdUtils();
- init_logging();
- logger31 = credentialLogger(credentialName4);
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/authorizationCodeCredential.js
-class AuthorizationCodeCredential {
- msalClient;
- disableAutomaticAuthentication;
- authorizationCode;
- redirectUri;
- tenantId;
- additionallyAllowedTenantIds;
- clientSecret;
- constructor(tenantId, clientId, clientSecretOrAuthorizationCode, authorizationCodeOrRedirectUri, redirectUriOrOptions, options2) {
- checkTenantId(logger32, tenantId);
- this.clientSecret = clientSecretOrAuthorizationCode;
- if (typeof redirectUriOrOptions === "string") {
- this.authorizationCode = authorizationCodeOrRedirectUri;
- this.redirectUri = redirectUriOrOptions;
- } else {
- this.authorizationCode = clientSecretOrAuthorizationCode;
- this.redirectUri = authorizationCodeOrRedirectUri;
- this.clientSecret = undefined;
- options2 = redirectUriOrOptions;
- }
- this.tenantId = tenantId;
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options2?.additionallyAllowedTenants);
- this.msalClient = createMsalClient(clientId, tenantId, {
- ...options2,
- logger: logger32,
- tokenCredentialOptions: options2 ?? {}
- });
- }
- async getToken(scopes, options2 = {}) {
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options2, async (newOptions) => {
- const tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds);
- newOptions.tenantId = tenantId;
- const arrayScopes = ensureScopes(scopes);
- return this.msalClient.getTokenByAuthorizationCode(arrayScopes, this.redirectUri, this.authorizationCode, this.clientSecret, {
- ...newOptions,
- disableAutomaticAuthentication: this.disableAutomaticAuthentication
- });
- });
- }
-}
-var logger32;
-var init_authorizationCodeCredential = __esm(() => {
- init_tenantIdUtils();
- init_tenantIdUtils();
- init_logging();
- init_scopeUtils();
- init_tracing();
- init_msalClient();
- logger32 = credentialLogger("AuthorizationCodeCredential");
-});
-
-// node_modules/@azure/identity/dist/esm/credentials/onBehalfOfCredential.js
-import { createHash as createHash5 } from "crypto";
-import { readFile as readFile11 } from "fs/promises";
-
-class OnBehalfOfCredential {
- tenantId;
- additionallyAllowedTenantIds;
- msalClient;
- sendCertificateChain;
- certificatePath;
- clientSecret;
- userAssertionToken;
- clientAssertion;
- constructor(options2) {
- const { clientSecret } = options2;
- const { certificatePath, sendCertificateChain } = options2;
- const { getAssertion } = options2;
- const { tenantId, clientId, userAssertionToken, additionallyAllowedTenants: additionallyAllowedTenantIds } = options2;
- if (!tenantId) {
- throw new CredentialUnavailableError(`${credentialName5}: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
- }
- if (!clientId) {
- throw new CredentialUnavailableError(`${credentialName5}: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
- }
- if (!clientSecret && !certificatePath && !getAssertion) {
- throw new CredentialUnavailableError(`${credentialName5}: You must provide one of clientSecret, certificatePath, or a getAssertion callback but none were provided. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
- }
- if (!userAssertionToken) {
- throw new CredentialUnavailableError(`${credentialName5}: userAssertionToken is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
- }
- this.certificatePath = certificatePath;
- this.clientSecret = clientSecret;
- this.userAssertionToken = userAssertionToken;
- this.sendCertificateChain = sendCertificateChain;
- this.clientAssertion = getAssertion;
- this.tenantId = tenantId;
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(additionallyAllowedTenantIds);
- this.msalClient = createMsalClient(clientId, this.tenantId, {
- ...options2,
- logger: logger33,
- tokenCredentialOptions: options2
- });
- }
- async getToken(scopes, options2 = {}) {
- return tracingClient.withSpan(`${credentialName5}.getToken`, options2, async (newOptions) => {
- newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger33);
- const arrayScopes = ensureScopes(scopes);
- if (this.certificatePath) {
- const clientCertificate = await this.buildClientCertificate(this.certificatePath);
- return this.msalClient.getTokenOnBehalfOf(arrayScopes, this.userAssertionToken, clientCertificate, newOptions);
- } else if (this.clientSecret) {
- return this.msalClient.getTokenOnBehalfOf(arrayScopes, this.userAssertionToken, this.clientSecret, options2);
- } else if (this.clientAssertion) {
- return this.msalClient.getTokenOnBehalfOf(arrayScopes, this.userAssertionToken, this.clientAssertion, options2);
- } else {
- throw new Error("Expected either clientSecret or certificatePath or clientAssertion to be defined.");
- }
- });
- }
- async buildClientCertificate(certificatePath) {
- try {
- const parts = await this.parseCertificate({ certificatePath }, this.sendCertificateChain);
- return {
- thumbprint: parts.thumbprint,
- thumbprintSha256: parts.thumbprintSha256,
- privateKey: parts.certificateContents,
- x5c: parts.x5c
- };
- } catch (error44) {
- logger33.info(formatError2("", error44));
- throw error44;
- }
- }
- async parseCertificate(configuration, sendCertificateChain) {
- const certificatePath = configuration.certificatePath;
- const certificateContents = await readFile11(certificatePath, "utf8");
- const x5c = sendCertificateChain ? certificateContents : undefined;
- const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/g;
- const publicKeys = [];
- let match;
- do {
- match = certificatePattern.exec(certificateContents);
- if (match) {
- publicKeys.push(match[3]);
- }
- } while (match);
- if (publicKeys.length === 0) {
- throw new Error("The file at the specified path does not contain a PEM-encoded certificate.");
- }
- const thumbprint = createHash5("sha1").update(Buffer.from(publicKeys[0], "base64")).digest("hex").toUpperCase();
- const thumbprintSha256 = createHash5("sha256").update(Buffer.from(publicKeys[0], "base64")).digest("hex").toUpperCase();
- return {
- certificateContents,
- thumbprintSha256,
- thumbprint,
- x5c
- };
- }
-}
-var credentialName5 = "OnBehalfOfCredential", logger33;
-var init_onBehalfOfCredential = __esm(() => {
- init_msalClient();
- init_logging();
- init_tenantIdUtils();
- init_errors7();
- init_scopeUtils();
- init_tracing();
- logger33 = credentialLogger(credentialName5);
-});
-
-// node_modules/@azure/identity/dist/esm/tokenProvider.js
-function getBearerTokenProvider(credential, scopes, options2) {
- const { abortSignal, tracingOptions } = options2 || {};
- const pipeline2 = createEmptyPipeline2();
- pipeline2.addPolicy(bearerTokenAuthenticationPolicy({ credential, scopes }));
- async function getRefreshedToken() {
- const res = await pipeline2.sendRequest({
- sendRequest: (request2) => Promise.resolve({
- request: request2,
- status: 200,
- headers: request2.headers
- })
- }, createPipelineRequest2({
- url: "https://example.com",
- abortSignal,
- tracingOptions
- }));
- const accessToken = res.headers.get("authorization")?.split(" ")[1];
- if (!accessToken) {
- throw new Error("Failed to get access token");
- }
- return accessToken;
- }
- return getRefreshedToken;
-}
-var init_tokenProvider = __esm(() => {
- init_esm7();
-});
-
-// node_modules/@azure/identity/dist/esm/index.js
-var exports_esm = {};
-__export(exports_esm, {
- useIdentityPlugin: () => useIdentityPlugin,
- serializeAuthenticationRecord: () => serializeAuthenticationRecord,
- logger: () => logger8,
- getDefaultAzureCredential: () => getDefaultAzureCredential,
- getBearerTokenProvider: () => getBearerTokenProvider,
- deserializeAuthenticationRecord: () => deserializeAuthenticationRecord,
- WorkloadIdentityCredential: () => WorkloadIdentityCredential,
- VisualStudioCodeCredential: () => VisualStudioCodeCredential,
- UsernamePasswordCredential: () => UsernamePasswordCredential,
- OnBehalfOfCredential: () => OnBehalfOfCredential,
- ManagedIdentityCredential: () => ManagedIdentityCredential,
- InteractiveBrowserCredential: () => InteractiveBrowserCredential,
- EnvironmentCredential: () => EnvironmentCredential,
- DeviceCodeCredential: () => DeviceCodeCredential,
- DefaultAzureCredential: () => DefaultAzureCredential,
- CredentialUnavailableErrorName: () => CredentialUnavailableErrorName,
- CredentialUnavailableError: () => CredentialUnavailableError,
- ClientSecretCredential: () => ClientSecretCredential,
- ClientCertificateCredential: () => ClientCertificateCredential,
- ClientAssertionCredential: () => ClientAssertionCredential,
- ChainedTokenCredential: () => ChainedTokenCredential,
- AzurePowerShellCredential: () => AzurePowerShellCredential,
- AzurePipelinesCredential: () => AzurePipelinesCredential,
- AzureDeveloperCliCredential: () => AzureDeveloperCliCredential,
- AzureCliCredential: () => AzureCliCredential,
- AzureAuthorityHosts: () => AzureAuthorityHosts,
- AuthorizationCodeCredential: () => AuthorizationCodeCredential,
- AuthenticationRequiredError: () => AuthenticationRequiredError,
- AuthenticationErrorName: () => AuthenticationErrorName,
- AuthenticationError: () => AuthenticationError4,
- AggregateAuthenticationErrorName: () => AggregateAuthenticationErrorName,
- AggregateAuthenticationError: () => AggregateAuthenticationError
-});
-function getDefaultAzureCredential() {
- return new DefaultAzureCredential;
-}
-var init_esm9 = __esm(() => {
- init_defaultAzureCredential();
- init_errors7();
- init_utils4();
- init_chainedTokenCredential();
- init_clientSecretCredential();
- init_defaultAzureCredential();
- init_environmentCredential();
- init_clientCertificateCredential();
- init_clientAssertionCredential();
- init_azureCliCredential();
- init_azureDeveloperCliCredential();
- init_interactiveBrowserCredential();
- init_managedIdentityCredential();
- init_deviceCodeCredential();
- init_azurePipelinesCredential();
- init_authorizationCodeCredential();
- init_azurePowerShellCredential();
- init_usernamePasswordCredential();
- init_visualStudioCodeCredential();
- init_onBehalfOfCredential();
- init_workloadIdentityCredential();
- init_logging();
- init_constants9();
- init_tokenProvider();
- init_consumer();
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/tslib.mjs
-function __classPrivateFieldSet8(receiver, state3, value, kind2, f4) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a setter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return kind2 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state3.set(receiver, value), value;
-}
-function __classPrivateFieldGet8(receiver, state3, kind2, f4) {
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a getter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind2 === "m" ? f4 : kind2 === "a" ? f4.call(receiver) : f4 ? f4.value : state3.get(receiver);
-}
-var init_tslib3 = () => {};
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs
-var uuid45 = function() {
- const { crypto: crypto11 } = globalThis;
- if (crypto11?.randomUUID) {
- uuid45 = crypto11.randomUUID.bind(crypto11);
- return crypto11.randomUUID();
- }
- const u8 = new Uint8Array(1);
- const randomByte = crypto11 ? () => crypto11.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
- return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c8) => (+c8 ^ randomByte() & 15 >> +c8 / 4).toString(16));
-};
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/errors.mjs
-function isAbortError6(err) {
- return typeof err === "object" && err !== null && (("name" in err) && err.name === "AbortError" || ("message" in err) && String(err.message).includes("FetchRequestCanceledException"));
-}
-var castToError4 = (err) => {
- if (err instanceof Error)
- return err;
- if (typeof err === "object" && err !== null) {
- try {
- if (Object.prototype.toString.call(err) === "[object Error]") {
- const error44 = new Error(err.message, err.cause ? { cause: err.cause } : {});
- if (err.stack)
- error44.stack = err.stack;
- if (err.cause && !error44.cause)
- error44.cause = err.cause;
- if (err.name)
- error44.name = err.name;
- return error44;
- }
- } catch {}
- try {
- return new Error(JSON.stringify(err));
- } catch {}
- }
- return new Error(err);
-};
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/core/error.mjs
-var AnthropicError4, APIError4, APIUserAbortError4, APIConnectionError4, APIConnectionTimeoutError4, BadRequestError4, AuthenticationError5, PermissionDeniedError4, NotFoundError4, ConflictError4, UnprocessableEntityError4, RateLimitError4, InternalServerError4;
-var init_error11 = __esm(() => {
- AnthropicError4 = class AnthropicError4 extends Error {
- };
- APIError4 = class APIError4 extends AnthropicError4 {
- constructor(status, error44, message, headers) {
- super(`${APIError4.makeMessage(status, error44, message)}`);
- this.status = status;
- this.headers = headers;
- this.requestID = headers?.get("request-id");
- this.error = error44;
- }
- static makeMessage(status, error44, message) {
- const msg = error44?.message ? typeof error44.message === "string" ? error44.message : JSON.stringify(error44.message) : error44 ? JSON.stringify(error44) : message;
- if (status && msg) {
- return `${status} ${msg}`;
- }
- if (status) {
- return `${status} status code (no body)`;
- }
- if (msg) {
- return msg;
- }
- return "(no status code or body)";
- }
- static generate(status, errorResponse, message, headers) {
- if (!status || !headers) {
- return new APIConnectionError4({ message, cause: castToError4(errorResponse) });
- }
- const error44 = errorResponse;
- if (status === 400) {
- return new BadRequestError4(status, error44, message, headers);
- }
- if (status === 401) {
- return new AuthenticationError5(status, error44, message, headers);
- }
- if (status === 403) {
- return new PermissionDeniedError4(status, error44, message, headers);
- }
- if (status === 404) {
- return new NotFoundError4(status, error44, message, headers);
- }
- if (status === 409) {
- return new ConflictError4(status, error44, message, headers);
- }
- if (status === 422) {
- return new UnprocessableEntityError4(status, error44, message, headers);
- }
- if (status === 429) {
- return new RateLimitError4(status, error44, message, headers);
- }
- if (status >= 500) {
- return new InternalServerError4(status, error44, message, headers);
- }
- return new APIError4(status, error44, message, headers);
- }
- };
- APIUserAbortError4 = class APIUserAbortError4 extends APIError4 {
- constructor({ message } = {}) {
- super(undefined, undefined, message || "Request was aborted.", undefined);
- }
- };
- APIConnectionError4 = class APIConnectionError4 extends APIError4 {
- constructor({ message, cause }) {
- super(undefined, undefined, message || "Connection error.", undefined);
- if (cause)
- this.cause = cause;
- }
- };
- APIConnectionTimeoutError4 = class APIConnectionTimeoutError4 extends APIConnectionError4 {
- constructor({ message } = {}) {
- super({ message: message ?? "Request timed out." });
- }
- };
- BadRequestError4 = class BadRequestError4 extends APIError4 {
- };
- AuthenticationError5 = class AuthenticationError5 extends APIError4 {
- };
- PermissionDeniedError4 = class PermissionDeniedError4 extends APIError4 {
- };
- NotFoundError4 = class NotFoundError4 extends APIError4 {
- };
- ConflictError4 = class ConflictError4 extends APIError4 {
- };
- UnprocessableEntityError4 = class UnprocessableEntityError4 extends APIError4 {
- };
- RateLimitError4 = class RateLimitError4 extends APIError4 {
- };
- InternalServerError4 = class InternalServerError4 extends APIError4 {
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs
-function maybeObj3(x3) {
- if (typeof x3 !== "object") {
- return {};
- }
- return x3 ?? {};
-}
-function isEmptyObj4(obj) {
- if (!obj)
- return true;
- for (const _k3 in obj)
- return false;
- return true;
-}
-function hasOwn6(obj, key) {
- return Object.prototype.hasOwnProperty.call(obj, key);
-}
-var startsWithSchemeRegexp4, isAbsoluteURL5 = (url3) => {
- return startsWithSchemeRegexp4.test(url3);
-}, isArray7 = (val) => (isArray7 = Array.isArray, isArray7(val)), isReadonlyArray5, validatePositiveInteger4 = (name3, n5) => {
- if (typeof n5 !== "number" || !Number.isInteger(n5)) {
- throw new AnthropicError4(`${name3} must be an integer`);
- }
- if (n5 < 0) {
- throw new AnthropicError4(`${name3} must be a positive integer`);
- }
- return n5;
-}, safeJSON5 = (text) => {
- try {
- return JSON.parse(text);
- } catch (err) {
- return;
- }
-};
-var init_values6 = __esm(() => {
- init_error11();
- startsWithSchemeRegexp4 = /^[a-z][a-z0-9+.-]*:/i;
- isReadonlyArray5 = isArray7;
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs
-var sleep5 = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/version.mjs
-var VERSION6 = "0.80.0";
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs
-function getDetectedPlatform3() {
- if (typeof Deno !== "undefined" && Deno.build != null) {
- return "deno";
- }
- if (typeof EdgeRuntime !== "undefined") {
- return "edge";
- }
- if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
- return "node";
- }
- return "unknown";
-}
-function getBrowserInfo4() {
- if (typeof navigator === "undefined" || !navigator) {
- return null;
- }
- const browserPatterns = [
- { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
- { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
- ];
- for (const { key, pattern } of browserPatterns) {
- const match = pattern.exec(navigator.userAgent);
- if (match) {
- const major = match[1] || 0;
- const minor = match[2] || 0;
- const patch = match[3] || 0;
- return { browser: key, version: `${major}.${minor}.${patch}` };
- }
- }
- return null;
-}
-var isRunningInBrowser4 = () => {
- return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined";
-}, getPlatformProperties4 = () => {
- const detectedPlatform = getDetectedPlatform3();
- if (detectedPlatform === "deno") {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION6,
- "X-Stainless-OS": normalizePlatform4(Deno.build.os),
- "X-Stainless-Arch": normalizeArch4(Deno.build.arch),
- "X-Stainless-Runtime": "deno",
- "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
- };
- }
- if (typeof EdgeRuntime !== "undefined") {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION6,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": `other:${EdgeRuntime}`,
- "X-Stainless-Runtime": "edge",
- "X-Stainless-Runtime-Version": globalThis.process.version
- };
- }
- if (detectedPlatform === "node") {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION6,
- "X-Stainless-OS": normalizePlatform4(globalThis.process.platform ?? "unknown"),
- "X-Stainless-Arch": normalizeArch4(globalThis.process.arch ?? "unknown"),
- "X-Stainless-Runtime": "node",
- "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
- };
- }
- const browserInfo = getBrowserInfo4();
- if (browserInfo) {
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION6,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": "unknown",
- "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
- "X-Stainless-Runtime-Version": browserInfo.version
- };
- }
- return {
- "X-Stainless-Lang": "js",
- "X-Stainless-Package-Version": VERSION6,
- "X-Stainless-OS": "Unknown",
- "X-Stainless-Arch": "unknown",
- "X-Stainless-Runtime": "unknown",
- "X-Stainless-Runtime-Version": "unknown"
- };
-}, normalizeArch4 = (arch2) => {
- if (arch2 === "x32")
- return "x32";
- if (arch2 === "x86_64" || arch2 === "x64")
- return "x64";
- if (arch2 === "arm")
- return "arm";
- if (arch2 === "aarch64" || arch2 === "arm64")
- return "arm64";
- if (arch2)
- return `other:${arch2}`;
- return "unknown";
-}, normalizePlatform4 = (platform3) => {
- platform3 = platform3.toLowerCase();
- if (platform3.includes("ios"))
- return "iOS";
- if (platform3 === "android")
- return "Android";
- if (platform3 === "darwin")
- return "MacOS";
- if (platform3 === "win32")
- return "Windows";
- if (platform3 === "freebsd")
- return "FreeBSD";
- if (platform3 === "openbsd")
- return "OpenBSD";
- if (platform3 === "linux")
- return "Linux";
- if (platform3)
- return `Other:${platform3}`;
- return "Unknown";
-}, _platformHeaders4, getPlatformHeaders4 = () => {
- return _platformHeaders4 ?? (_platformHeaders4 = getPlatformProperties4());
-};
-var init_detect_platform3 = () => {};
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/shims.mjs
-function getDefaultFetch3() {
- if (typeof fetch !== "undefined") {
- return fetch;
- }
- throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
-}
-function makeReadableStream3(...args) {
- const ReadableStream4 = globalThis.ReadableStream;
- if (typeof ReadableStream4 === "undefined") {
- throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
- }
- return new ReadableStream4(...args);
-}
-function ReadableStreamFrom3(iterable) {
- let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
- return makeReadableStream3({
- start() {},
- async pull(controller) {
- const { done, value } = await iter.next();
- if (done) {
- controller.close();
- } else {
- controller.enqueue(value);
- }
- },
- async cancel() {
- await iter.return?.();
- }
- });
-}
-function ReadableStreamToAsyncIterable5(stream10) {
- if (stream10[Symbol.asyncIterator])
- return stream10;
- const reader = stream10.getReader();
- return {
- async next() {
- try {
- const result = await reader.read();
- if (result?.done)
- reader.releaseLock();
- return result;
- } catch (e4) {
- reader.releaseLock();
- throw e4;
- }
- },
- async return() {
- const cancelPromise = reader.cancel();
- reader.releaseLock();
- await cancelPromise;
- return { done: true, value: undefined };
- },
- [Symbol.asyncIterator]() {
- return this;
- }
- };
-}
-async function CancelReadableStream3(stream10) {
- if (stream10 === null || typeof stream10 !== "object")
- return;
- if (stream10[Symbol.asyncIterator]) {
- await stream10[Symbol.asyncIterator]().return?.();
- return;
- }
- const reader = stream10.getReader();
- const cancelPromise = reader.cancel();
- reader.releaseLock();
- await cancelPromise;
-}
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/request-options.mjs
-var FallbackEncoder3 = ({ headers, body }) => {
- return {
- bodyHeaders: {
- "content-type": "application/json"
- },
- body: JSON.stringify(body)
- };
-};
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs
-function stringifyQuery3(query) {
- return Object.entries(query).filter(([_, value]) => typeof value !== "undefined").map(([key, value]) => {
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
- }
- if (value === null) {
- return `${encodeURIComponent(key)}=`;
- }
- throw new AnthropicError4(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
- }).join("&");
-}
-var init_query3 = __esm(() => {
- init_error11();
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs
-function concatBytes3(buffers) {
- let length = 0;
- for (const buffer of buffers) {
- length += buffer.length;
- }
- const output = new Uint8Array(length);
- let index2 = 0;
- for (const buffer of buffers) {
- output.set(buffer, index2);
- index2 += buffer.length;
- }
- return output;
-}
-function encodeUTF84(str) {
- let encoder;
- return (encodeUTF8_3 ?? (encoder = new globalThis.TextEncoder, encodeUTF8_3 = encoder.encode.bind(encoder)))(str);
-}
-function decodeUTF83(bytes) {
- let decoder;
- return (decodeUTF8_3 ?? (decoder = new globalThis.TextDecoder, decodeUTF8_3 = decoder.decode.bind(decoder)))(bytes);
-}
-var encodeUTF8_3, decodeUTF8_3;
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs
-class LineDecoder4 {
- constructor() {
- _LineDecoder_buffer3.set(this, undefined);
- _LineDecoder_carriageReturnIndex4.set(this, undefined);
- __classPrivateFieldSet8(this, _LineDecoder_buffer3, new Uint8Array, "f");
- __classPrivateFieldSet8(this, _LineDecoder_carriageReturnIndex4, null, "f");
- }
- decode(chunk) {
- if (chunk == null) {
- return [];
- }
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF84(chunk) : chunk;
- __classPrivateFieldSet8(this, _LineDecoder_buffer3, concatBytes3([__classPrivateFieldGet8(this, _LineDecoder_buffer3, "f"), binaryChunk]), "f");
- const lines = [];
- let patternIndex;
- while ((patternIndex = findNewlineIndex4(__classPrivateFieldGet8(this, _LineDecoder_buffer3, "f"), __classPrivateFieldGet8(this, _LineDecoder_carriageReturnIndex4, "f"))) != null) {
- if (patternIndex.carriage && __classPrivateFieldGet8(this, _LineDecoder_carriageReturnIndex4, "f") == null) {
- __classPrivateFieldSet8(this, _LineDecoder_carriageReturnIndex4, patternIndex.index, "f");
- continue;
- }
- if (__classPrivateFieldGet8(this, _LineDecoder_carriageReturnIndex4, "f") != null && (patternIndex.index !== __classPrivateFieldGet8(this, _LineDecoder_carriageReturnIndex4, "f") + 1 || patternIndex.carriage)) {
- lines.push(decodeUTF83(__classPrivateFieldGet8(this, _LineDecoder_buffer3, "f").subarray(0, __classPrivateFieldGet8(this, _LineDecoder_carriageReturnIndex4, "f") - 1)));
- __classPrivateFieldSet8(this, _LineDecoder_buffer3, __classPrivateFieldGet8(this, _LineDecoder_buffer3, "f").subarray(__classPrivateFieldGet8(this, _LineDecoder_carriageReturnIndex4, "f")), "f");
- __classPrivateFieldSet8(this, _LineDecoder_carriageReturnIndex4, null, "f");
- continue;
- }
- const endIndex = __classPrivateFieldGet8(this, _LineDecoder_carriageReturnIndex4, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
- const line = decodeUTF83(__classPrivateFieldGet8(this, _LineDecoder_buffer3, "f").subarray(0, endIndex));
- lines.push(line);
- __classPrivateFieldSet8(this, _LineDecoder_buffer3, __classPrivateFieldGet8(this, _LineDecoder_buffer3, "f").subarray(patternIndex.index), "f");
- __classPrivateFieldSet8(this, _LineDecoder_carriageReturnIndex4, null, "f");
- }
- return lines;
- }
- flush() {
- if (!__classPrivateFieldGet8(this, _LineDecoder_buffer3, "f").length) {
- return [];
- }
- return this.decode(`
-`);
- }
-}
-function findNewlineIndex4(buffer, startIndex) {
- const newline2 = 10;
- const carriage = 13;
- for (let i5 = startIndex ?? 0;i5 < buffer.length; i5++) {
- if (buffer[i5] === newline2) {
- return { preceding: i5, index: i5 + 1, carriage: false };
- }
- if (buffer[i5] === carriage) {
- return { preceding: i5, index: i5 + 1, carriage: true };
- }
- }
- return null;
-}
-function findDoubleNewlineIndex4(buffer) {
- const newline2 = 10;
- const carriage = 13;
- for (let i5 = 0;i5 < buffer.length - 1; i5++) {
- if (buffer[i5] === newline2 && buffer[i5 + 1] === newline2) {
- return i5 + 2;
- }
- if (buffer[i5] === carriage && buffer[i5 + 1] === carriage) {
- return i5 + 2;
- }
- if (buffer[i5] === carriage && buffer[i5 + 1] === newline2 && i5 + 3 < buffer.length && buffer[i5 + 2] === carriage && buffer[i5 + 3] === newline2) {
- return i5 + 4;
- }
- }
- return -1;
-}
-var _LineDecoder_buffer3, _LineDecoder_carriageReturnIndex4;
-var init_line4 = __esm(() => {
- init_tslib3();
- _LineDecoder_buffer3 = new WeakMap, _LineDecoder_carriageReturnIndex4 = new WeakMap;
- LineDecoder4.NEWLINE_CHARS = new Set([`
-`, "\r"]);
- LineDecoder4.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs
-function noop9() {}
-function makeLogFn4(fnLevel, logger34, logLevel) {
- if (!logger34 || levelNumbers4[fnLevel] > levelNumbers4[logLevel]) {
- return noop9;
- } else {
- return logger34[fnLevel].bind(logger34);
- }
-}
-function loggerFor4(client14) {
- const logger34 = client14.logger;
- const logLevel = client14.logLevel ?? "off";
- if (!logger34) {
- return noopLogger4;
- }
- const cachedLogger = cachedLoggers4.get(logger34);
- if (cachedLogger && cachedLogger[0] === logLevel) {
- return cachedLogger[1];
- }
- const levelLogger = {
- error: makeLogFn4("error", logger34, logLevel),
- warn: makeLogFn4("warn", logger34, logLevel),
- info: makeLogFn4("info", logger34, logLevel),
- debug: makeLogFn4("debug", logger34, logLevel)
- };
- cachedLoggers4.set(logger34, [logLevel, levelLogger]);
- return levelLogger;
-}
-var levelNumbers4, parseLogLevel3 = (maybeLevel, sourceName, client14) => {
- if (!maybeLevel) {
- return;
- }
- if (hasOwn6(levelNumbers4, maybeLevel)) {
- return maybeLevel;
- }
- loggerFor4(client14).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers4))}`);
- return;
-}, noopLogger4, cachedLoggers4, formatRequestDetails3 = (details) => {
- if (details.options) {
- details.options = { ...details.options };
- delete details.options["headers"];
- }
- if (details.headers) {
- details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name3, value]) => [
- name3,
- name3.toLowerCase() === "x-api-key" || name3.toLowerCase() === "authorization" || name3.toLowerCase() === "cookie" || name3.toLowerCase() === "set-cookie" ? "***" : value
- ]));
- }
- if ("retryOfRequestLogID" in details) {
- if (details.retryOfRequestLogID) {
- details.retryOf = details.retryOfRequestLogID;
- }
- delete details.retryOfRequestLogID;
- }
- return details;
-};
-var init_log11 = __esm(() => {
- init_values6();
- levelNumbers4 = {
- off: 0,
- error: 200,
- warn: 300,
- info: 400,
- debug: 500
- };
- noopLogger4 = {
- error: noop9,
- warn: noop9,
- info: noop9,
- debug: noop9
- };
- cachedLoggers4 = /* @__PURE__ */ new WeakMap;
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/core/streaming.mjs
-async function* _iterSSEMessages4(response7, controller) {
- if (!response7.body) {
- controller.abort();
- if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
- throw new AnthropicError4(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
- }
- throw new AnthropicError4(`Attempted to iterate over a response with no body`);
- }
- const sseDecoder = new SSEDecoder4;
- const lineDecoder = new LineDecoder4;
- const iter = ReadableStreamToAsyncIterable5(response7.body);
- for await (const sseChunk of iterSSEChunks4(iter)) {
- for (const line of lineDecoder.decode(sseChunk)) {
- const sse = sseDecoder.decode(line);
- if (sse)
- yield sse;
- }
- }
- for (const line of lineDecoder.flush()) {
- const sse = sseDecoder.decode(line);
- if (sse)
- yield sse;
- }
-}
-async function* iterSSEChunks4(iterator2) {
- let data = new Uint8Array;
- for await (const chunk of iterator2) {
- if (chunk == null) {
- continue;
- }
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF84(chunk) : chunk;
- let newData = new Uint8Array(data.length + binaryChunk.length);
- newData.set(data);
- newData.set(binaryChunk, data.length);
- data = newData;
- let patternIndex;
- while ((patternIndex = findDoubleNewlineIndex4(data)) !== -1) {
- yield data.slice(0, patternIndex);
- data = data.slice(patternIndex);
- }
- }
- if (data.length > 0) {
- yield data;
- }
-}
-
-class SSEDecoder4 {
- constructor() {
- this.event = null;
- this.data = [];
- this.chunks = [];
- }
- decode(line) {
- if (line.endsWith("\r")) {
- line = line.substring(0, line.length - 1);
- }
- if (!line) {
- if (!this.event && !this.data.length)
- return null;
- const sse = {
- event: this.event,
- data: this.data.join(`
-`),
- raw: this.chunks
- };
- this.event = null;
- this.data = [];
- this.chunks = [];
- return sse;
- }
- this.chunks.push(line);
- if (line.startsWith(":")) {
- return null;
- }
- let [fieldname, _, value] = partition4(line, ":");
- if (value.startsWith(" ")) {
- value = value.substring(1);
- }
- if (fieldname === "event") {
- this.event = value;
- } else if (fieldname === "data") {
- this.data.push(value);
- }
- return null;
- }
-}
-function partition4(str, delimiter) {
- const index2 = str.indexOf(delimiter);
- if (index2 !== -1) {
- return [str.substring(0, index2), delimiter, str.substring(index2 + delimiter.length)];
- }
- return [str, "", ""];
-}
-var _Stream_client3, Stream5;
-var init_streaming8 = __esm(() => {
- init_tslib3();
- init_error11();
- init_line4();
- init_values6();
- init_log11();
- init_error11();
- Stream5 = class Stream5 {
- constructor(iterator2, controller, client14) {
- this.iterator = iterator2;
- _Stream_client3.set(this, undefined);
- this.controller = controller;
- __classPrivateFieldSet8(this, _Stream_client3, client14, "f");
- }
- static fromSSEResponse(response7, controller, client14) {
- let consumed = false;
- const logger34 = client14 ? loggerFor4(client14) : console;
- async function* iterator2() {
- if (consumed) {
- throw new AnthropicError4("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
- }
- consumed = true;
- let done = false;
- try {
- for await (const sse of _iterSSEMessages4(response7, controller)) {
- if (sse.event === "completion") {
- try {
- yield JSON.parse(sse.data);
- } catch (e4) {
- logger34.error(`Could not parse message into JSON:`, sse.data);
- logger34.error(`From chunk:`, sse.raw);
- throw e4;
- }
- }
- if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
- try {
- yield JSON.parse(sse.data);
- } catch (e4) {
- logger34.error(`Could not parse message into JSON:`, sse.data);
- logger34.error(`From chunk:`, sse.raw);
- throw e4;
- }
- }
- if (sse.event === "ping") {
- continue;
- }
- if (sse.event === "error") {
- throw new APIError4(undefined, safeJSON5(sse.data) ?? sse.data, undefined, response7.headers);
- }
- }
- done = true;
- } catch (e4) {
- if (isAbortError6(e4))
- return;
- throw e4;
- } finally {
- if (!done)
- controller.abort();
- }
- }
- return new Stream5(iterator2, controller, client14);
- }
- static fromReadableStream(readableStream, controller, client14) {
- let consumed = false;
- async function* iterLines() {
- const lineDecoder = new LineDecoder4;
- const iter = ReadableStreamToAsyncIterable5(readableStream);
- for await (const chunk of iter) {
- for (const line of lineDecoder.decode(chunk)) {
- yield line;
- }
- }
- for (const line of lineDecoder.flush()) {
- yield line;
- }
- }
- async function* iterator2() {
- if (consumed) {
- throw new AnthropicError4("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
- }
- consumed = true;
- let done = false;
- try {
- for await (const line of iterLines()) {
- if (done)
- continue;
- if (line)
- yield JSON.parse(line);
- }
- done = true;
- } catch (e4) {
- if (isAbortError6(e4))
- return;
- throw e4;
- } finally {
- if (!done)
- controller.abort();
- }
- }
- return new Stream5(iterator2, controller, client14);
- }
- [(_Stream_client3 = new WeakMap, Symbol.asyncIterator)]() {
- return this.iterator();
- }
- tee() {
- const left = [];
- const right = [];
- const iterator2 = this.iterator();
- const teeIterator = (queue) => {
- return {
- next: () => {
- if (queue.length === 0) {
- const result = iterator2.next();
- left.push(result);
- right.push(result);
- }
- return queue.shift();
- }
- };
- };
- return [
- new Stream5(() => teeIterator(left), this.controller, __classPrivateFieldGet8(this, _Stream_client3, "f")),
- new Stream5(() => teeIterator(right), this.controller, __classPrivateFieldGet8(this, _Stream_client3, "f"))
- ];
- }
- toReadableStream() {
- const self2 = this;
- let iter;
- return makeReadableStream3({
- async start() {
- iter = self2[Symbol.asyncIterator]();
- },
- async pull(ctrl) {
- try {
- const { value, done } = await iter.next();
- if (done)
- return ctrl.close();
- const bytes = encodeUTF84(JSON.stringify(value) + `
-`);
- ctrl.enqueue(bytes);
- } catch (err) {
- ctrl.error(err);
- }
- },
- async cancel() {
- await iter.return?.();
- }
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/parse.mjs
-async function defaultParseResponse4(client14, props) {
- const { response: response7, requestLogID, retryOfRequestLogID, startTime } = props;
- const body = await (async () => {
- if (props.options.stream) {
- loggerFor4(client14).debug("response", response7.status, response7.url, response7.headers, response7.body);
- if (props.options.__streamClass) {
- return props.options.__streamClass.fromSSEResponse(response7, props.controller);
- }
- return Stream5.fromSSEResponse(response7, props.controller);
- }
- if (response7.status === 204) {
- return null;
- }
- if (props.options.__binaryResponse) {
- return response7;
- }
- const contentType = response7.headers.get("content-type");
- const mediaType = contentType?.split(";")[0]?.trim();
- const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
- if (isJSON) {
- const contentLength = response7.headers.get("content-length");
- if (contentLength === "0") {
- return;
- }
- const json2 = await response7.json();
- return addRequestID3(json2, response7);
- }
- const text = await response7.text();
- return text;
- })();
- loggerFor4(client14).debug(`[${requestLogID}] response parsed`, formatRequestDetails3({
- retryOfRequestLogID,
- url: response7.url,
- status: response7.status,
- body,
- durationMs: Date.now() - startTime
- }));
- return body;
-}
-function addRequestID3(value, response7) {
- if (!value || typeof value !== "object" || Array.isArray(value)) {
- return value;
- }
- return Object.defineProperty(value, "_request_id", {
- value: response7.headers.get("request-id"),
- enumerable: false
- });
-}
-var init_parse5 = __esm(() => {
- init_streaming8();
- init_log11();
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/core/api-promise.mjs
-var _APIPromise_client3, APIPromise4;
-var init_api_promise3 = __esm(() => {
- init_tslib3();
- init_parse5();
- APIPromise4 = class APIPromise4 extends Promise {
- constructor(client14, responsePromise, parseResponse = defaultParseResponse4) {
- super((resolve9) => {
- resolve9(null);
- });
- this.responsePromise = responsePromise;
- this.parseResponse = parseResponse;
- _APIPromise_client3.set(this, undefined);
- __classPrivateFieldSet8(this, _APIPromise_client3, client14, "f");
- }
- _thenUnwrap(transform2) {
- return new APIPromise4(__classPrivateFieldGet8(this, _APIPromise_client3, "f"), this.responsePromise, async (client14, props) => addRequestID3(transform2(await this.parseResponse(client14, props), props), props.response));
- }
- asResponse() {
- return this.responsePromise.then((p4) => p4.response);
- }
- async withResponse() {
- const [data, response7] = await Promise.all([this.parse(), this.asResponse()]);
- return { data, response: response7, request_id: response7.headers.get("request-id") };
- }
- parse() {
- if (!this.parsedPromise) {
- this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet8(this, _APIPromise_client3, "f"), data));
- }
- return this.parsedPromise;
- }
- then(onfulfilled, onrejected) {
- return this.parse().then(onfulfilled, onrejected);
- }
- catch(onrejected) {
- return this.parse().catch(onrejected);
- }
- finally(onfinally) {
- return this.parse().finally(onfinally);
- }
- };
- _APIPromise_client3 = new WeakMap;
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/core/pagination.mjs
-var _AbstractPage_client4, AbstractPage4, PagePromise4, Page4, PageCursor3;
-var init_pagination12 = __esm(() => {
- init_tslib3();
- init_error11();
- init_parse5();
- init_api_promise3();
- init_values6();
- AbstractPage4 = class AbstractPage4 {
- constructor(client14, response7, body, options2) {
- _AbstractPage_client4.set(this, undefined);
- __classPrivateFieldSet8(this, _AbstractPage_client4, client14, "f");
- this.options = options2;
- this.response = response7;
- this.body = body;
- }
- hasNextPage() {
- const items = this.getPaginatedItems();
- if (!items.length)
- return false;
- return this.nextPageRequestOptions() != null;
- }
- async getNextPage() {
- const nextOptions = this.nextPageRequestOptions();
- if (!nextOptions) {
- throw new AnthropicError4("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
- }
- return await __classPrivateFieldGet8(this, _AbstractPage_client4, "f").requestAPIList(this.constructor, nextOptions);
- }
- async* iterPages() {
- let page = this;
- yield page;
- while (page.hasNextPage()) {
- page = await page.getNextPage();
- yield page;
- }
- }
- async* [(_AbstractPage_client4 = new WeakMap, Symbol.asyncIterator)]() {
- for await (const page of this.iterPages()) {
- for (const item of page.getPaginatedItems()) {
- yield item;
- }
- }
- }
- };
- PagePromise4 = class PagePromise4 extends APIPromise4 {
- constructor(client14, request2, Page4) {
- super(client14, request2, async (client15, props) => new Page4(client15, props.response, await defaultParseResponse4(client15, props), props.options));
- }
- async* [Symbol.asyncIterator]() {
- const page = await this;
- for await (const item of page) {
- yield item;
- }
- }
- };
- Page4 = class Page4 extends AbstractPage4 {
- constructor(client14, response7, body, options2) {
- super(client14, response7, body, options2);
- this.data = body.data || [];
- this.has_more = body.has_more || false;
- this.first_id = body.first_id || null;
- this.last_id = body.last_id || null;
- }
- getPaginatedItems() {
- return this.data ?? [];
- }
- hasNextPage() {
- if (this.has_more === false) {
- return false;
- }
- return super.hasNextPage();
- }
- nextPageRequestOptions() {
- if (this.options.query?.["before_id"]) {
- const first_id = this.first_id;
- if (!first_id) {
- return null;
- }
- return {
- ...this.options,
- query: {
- ...maybeObj3(this.options.query),
- before_id: first_id
- }
- };
- }
- const cursor = this.last_id;
- if (!cursor) {
- return null;
- }
- return {
- ...this.options,
- query: {
- ...maybeObj3(this.options.query),
- after_id: cursor
- }
- };
- }
- };
- PageCursor3 = class PageCursor3 extends AbstractPage4 {
- constructor(client14, response7, body, options2) {
- super(client14, response7, body, options2);
- this.data = body.data || [];
- this.has_more = body.has_more || false;
- this.next_page = body.next_page || null;
- }
- getPaginatedItems() {
- return this.data ?? [];
- }
- hasNextPage() {
- if (this.has_more === false) {
- return false;
- }
- return super.hasNextPage();
- }
- nextPageRequestOptions() {
- const cursor = this.next_page;
- if (!cursor) {
- return null;
- }
- return {
- ...this.options,
- query: {
- ...maybeObj3(this.options.query),
- page: cursor
- }
- };
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/uploads.mjs
-function makeFile3(fileBits, fileName, options2) {
- checkFileSupport3();
- return new File(fileBits, fileName ?? "unknown_file", options2);
-}
-function getName4(value, stripPath) {
- const val = typeof value === "object" && value !== null && (("name" in value) && value.name && String(value.name) || ("url" in value) && value.url && String(value.url) || ("filename" in value) && value.filename && String(value.filename) || ("path" in value) && value.path && String(value.path)) || "";
- return stripPath ? val.split(/[\\/]/).pop() || undefined : val;
-}
-function supportsFormData3(fetchObject) {
- const fetch3 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
- const cached2 = supportsFormDataMap3.get(fetch3);
- if (cached2)
- return cached2;
- const promise2 = (async () => {
- try {
- const FetchResponse = "Response" in fetch3 ? fetch3.Response : (await fetch3("data:,")).constructor;
- const data = new FormData;
- if (data.toString() === await new FetchResponse(data).text()) {
- return false;
- }
- return true;
- } catch {
- return true;
- }
- })();
- supportsFormDataMap3.set(fetch3, promise2);
- return promise2;
-}
-var checkFileSupport3 = () => {
- if (typeof File === "undefined") {
- const { process: process20 } = globalThis;
- const isOldNode = typeof process20?.versions?.node === "string" && parseInt(process20.versions.node.split(".")) < 20;
- throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
- }
-}, isAsyncIterable3 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", multipartFormRequestOptions3 = async (opts, fetch3, stripFilenames = true) => {
- return { ...opts, body: await createForm3(opts.body, fetch3, stripFilenames) };
-}, supportsFormDataMap3, createForm3 = async (body, fetch3, stripFilenames = true) => {
- if (!await supportsFormData3(fetch3)) {
- throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
- }
- const form = new FormData;
- await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue3(form, key, value, stripFilenames)));
- return form;
-}, isNamedBlob3 = (value) => value instanceof Blob && ("name" in value), addFormValue3 = async (form, key, value, stripFilenames) => {
- if (value === undefined)
- return;
- if (value == null) {
- throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
- }
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
- form.append(key, String(value));
- } else if (value instanceof Response) {
- let options2 = {};
- const contentType = value.headers.get("Content-Type");
- if (contentType) {
- options2 = { type: contentType };
- }
- form.append(key, makeFile3([await value.blob()], getName4(value, stripFilenames), options2));
- } else if (isAsyncIterable3(value)) {
- form.append(key, makeFile3([await new Response(ReadableStreamFrom3(value)).blob()], getName4(value, stripFilenames)));
- } else if (isNamedBlob3(value)) {
- form.append(key, makeFile3([value], getName4(value, stripFilenames), { type: value.type }));
- } else if (Array.isArray(value)) {
- await Promise.all(value.map((entry) => addFormValue3(form, key + "[]", entry, stripFilenames)));
- } else if (typeof value === "object") {
- await Promise.all(Object.entries(value).map(([name3, prop]) => addFormValue3(form, `${key}[${name3}]`, prop, stripFilenames)));
- } else {
- throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
- }
-};
-var init_uploads6 = __esm(() => {
- supportsFormDataMap3 = /* @__PURE__ */ new WeakMap;
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/to-file.mjs
-async function toFile4(value, name3, options2) {
- checkFileSupport3();
- value = await value;
- name3 || (name3 = getName4(value, true));
- if (isFileLike4(value)) {
- if (value instanceof File && name3 == null && options2 == null) {
- return value;
- }
- return makeFile3([await value.arrayBuffer()], name3 ?? value.name, {
- type: value.type,
- lastModified: value.lastModified,
- ...options2
- });
- }
- if (isResponseLike4(value)) {
- const blob = await value.blob();
- name3 || (name3 = new URL(value.url).pathname.split(/[\\/]/).pop());
- return makeFile3(await getBytes4(blob), name3, options2);
- }
- const parts = await getBytes4(value);
- if (!options2?.type) {
- const type = parts.find((part) => typeof part === "object" && ("type" in part) && part.type);
- if (typeof type === "string") {
- options2 = { ...options2, type };
- }
- }
- return makeFile3(parts, name3, options2);
-}
-async function getBytes4(value) {
- let parts = [];
- if (typeof value === "string" || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
- parts.push(value);
- } else if (isBlobLike4(value)) {
- parts.push(value instanceof Blob ? value : await value.arrayBuffer());
- } else if (isAsyncIterable3(value)) {
- for await (const chunk of value) {
- parts.push(...await getBytes4(chunk));
- }
- } else {
- const constructor = value?.constructor?.name;
- throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError4(value)}`);
- }
- return parts;
-}
-function propsForError4(value) {
- if (typeof value !== "object" || value === null)
- return "";
- const props = Object.getOwnPropertyNames(value);
- return `; props: [${props.map((p4) => `"${p4}"`).join(", ")}]`;
-}
-var isBlobLike4 = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", isFileLike4 = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike4(value), isResponseLike4 = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
-var init_to_file3 = __esm(() => {
- init_uploads6();
- init_uploads6();
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/core/uploads.mjs
-var init_uploads7 = __esm(() => {
- init_to_file3();
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/shared.mjs
-var init_shared11 = () => {};
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/core/resource.mjs
-class APIResource4 {
- constructor(client14) {
- this._client = client14;
- }
-}
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/headers.mjs
-function* iterateHeaders5(headers) {
- if (!headers)
- return;
- if (brand_privateNullableHeaders5 in headers) {
- const { values: values2, nulls } = headers;
- yield* values2.entries();
- for (const name3 of nulls) {
- yield [name3, null];
- }
- return;
- }
- let shouldClear = false;
- let iter;
- if (headers instanceof Headers) {
- iter = headers.entries();
- } else if (isReadonlyArray5(headers)) {
- iter = headers;
- } else {
- shouldClear = true;
- iter = Object.entries(headers ?? {});
- }
- for (let row of iter) {
- const name3 = row[0];
- if (typeof name3 !== "string")
- throw new TypeError("expected header name to be a string");
- const values2 = isReadonlyArray5(row[1]) ? row[1] : [row[1]];
- let didClear = false;
- for (const value of values2) {
- if (value === undefined)
- continue;
- if (shouldClear && !didClear) {
- didClear = true;
- yield [name3, null];
- }
- yield [name3, value];
- }
- }
-}
-var brand_privateNullableHeaders5, buildHeaders5 = (newHeaders) => {
- const targetHeaders = new Headers;
- const nullHeaders = new Set;
- for (const headers of newHeaders) {
- const seenHeaders = new Set;
- for (const [name3, value] of iterateHeaders5(headers)) {
- const lowerName = name3.toLowerCase();
- if (!seenHeaders.has(lowerName)) {
- targetHeaders.delete(name3);
- seenHeaders.add(lowerName);
- }
- if (value === null) {
- targetHeaders.delete(name3);
- nullHeaders.add(lowerName);
- } else {
- targetHeaders.append(name3, value);
- nullHeaders.delete(lowerName);
- }
- }
- }
- return { [brand_privateNullableHeaders5]: true, values: targetHeaders, nulls: nullHeaders };
-};
-var init_headers5 = __esm(() => {
- init_values6();
- brand_privateNullableHeaders5 = Symbol.for("brand.privateNullableHeaders");
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs
-function wasCreatedByStainlessHelper3(value) {
- return typeof value === "object" && value !== null && SDK_HELPER_SYMBOL3 in value;
-}
-function collectStainlessHelpers3(tools, messages) {
- const helpers3 = new Set;
- if (tools) {
- for (const tool of tools) {
- if (wasCreatedByStainlessHelper3(tool)) {
- helpers3.add(tool[SDK_HELPER_SYMBOL3]);
- }
- }
- }
- if (messages) {
- for (const message of messages) {
- if (wasCreatedByStainlessHelper3(message)) {
- helpers3.add(message[SDK_HELPER_SYMBOL3]);
- }
- if (Array.isArray(message.content)) {
- for (const block2 of message.content) {
- if (wasCreatedByStainlessHelper3(block2)) {
- helpers3.add(block2[SDK_HELPER_SYMBOL3]);
- }
- }
- }
- }
- }
- return Array.from(helpers3);
-}
-function stainlessHelperHeader3(tools, messages) {
- const helpers3 = collectStainlessHelpers3(tools, messages);
- if (helpers3.length === 0)
- return {};
- return { "x-stainless-helper": helpers3.join(", ") };
-}
-function stainlessHelperHeaderFromFile3(file2) {
- if (wasCreatedByStainlessHelper3(file2)) {
- return { "x-stainless-helper": file2[SDK_HELPER_SYMBOL3] };
- }
- return {};
-}
-var SDK_HELPER_SYMBOL3;
-var init_stainless_helper_header3 = __esm(() => {
- SDK_HELPER_SYMBOL3 = Symbol("anthropic.sdk.stainlessHelper");
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs
-function encodeURIPath4(str) {
- return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
-}
-var EMPTY4, createPathTagFunction4 = (pathEncoder = encodeURIPath4) => function path13(statics, ...params) {
- if (statics.length === 1)
- return statics[0];
- let postPath = false;
- const invalidSegments = [];
- const path14 = statics.reduce((previousValue, currentValue, index2) => {
- if (/[?#]/.test(currentValue)) {
- postPath = true;
- }
- const value = params[index2];
- let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
- if (index2 !== params.length && (value == null || typeof value === "object" && value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY4) ?? EMPTY4)?.toString)) {
- encoded = value + "";
- invalidSegments.push({
- start: previousValue.length + currentValue.length,
- length: encoded.length,
- error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
- });
- }
- return previousValue + currentValue + (index2 === params.length ? "" : encoded);
- }, "");
- const pathOnly = path14.split(/[?#]/, 1)[0];
- const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
- let match;
- while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
- invalidSegments.push({
- start: match.index,
- length: match[0].length,
- error: `Value "${match[0]}" can't be safely passed as a path parameter`
- });
- }
- invalidSegments.sort((a5, b4) => a5.start - b4.start);
- if (invalidSegments.length > 0) {
- let lastEnd = 0;
- const underline2 = invalidSegments.reduce((acc, segment) => {
- const spaces = " ".repeat(segment.start - lastEnd);
- const arrows = "^".repeat(segment.length);
- lastEnd = segment.start + segment.length;
- return acc + spaces + arrows;
- }, "");
- throw new AnthropicError4(`Path parameters result in path with invalid segments:
-${invalidSegments.map((e4) => e4.error).join(`
-`)}
-${path14}
-${underline2}`);
- }
- return path14;
-}, path13;
-var init_path5 = __esm(() => {
- init_error11();
- EMPTY4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
- path13 = /* @__PURE__ */ createPathTagFunction4(encodeURIPath4);
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs
-var Files3;
-var init_files4 = __esm(() => {
- init_pagination12();
- init_headers5();
- init_stainless_helper_header3();
- init_uploads6();
- init_path5();
- Files3 = class Files3 extends APIResource4 {
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/files", Page4, {
- query,
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- options2?.headers
- ])
- });
- }
- delete(fileID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.delete(path13`/v1/files/${fileID}`, {
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- options2?.headers
- ])
- });
- }
- download(fileID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path13`/v1/files/${fileID}/content`, {
- ...options2,
- headers: buildHeaders5([
- {
- "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString(),
- Accept: "application/binary"
- },
- options2?.headers
- ]),
- __binaryResponse: true
- });
- }
- retrieveMetadata(fileID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path13`/v1/files/${fileID}`, {
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- options2?.headers
- ])
- });
- }
- upload(params, options2) {
- const { betas, ...body } = params;
- return this._client.post("/v1/files", multipartFormRequestOptions3({
- body,
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
- stainlessHelperHeaderFromFile3(body.file),
- options2?.headers
- ])
- }, this._client));
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs
-var Models7;
-var init_models7 = __esm(() => {
- init_pagination12();
- init_headers5();
- init_path5();
- Models7 = class Models7 extends APIResource4 {
- retrieve(modelID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path13`/v1/models/${modelID}?beta=true`, {
- ...options2,
- headers: buildHeaders5([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/models?beta=true", Page4, {
- query,
- ...options2,
- headers: buildHeaders5([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/error.mjs
-var init_error12 = __esm(() => {
- init_error11();
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/constants.mjs
-var MODEL_NONSTREAMING_TOKENS3;
-var init_constants10 = __esm(() => {
- MODEL_NONSTREAMING_TOKENS3 = {
- "claude-opus-4-20250514": 8192,
- "claude-opus-4-0": 8192,
- "claude-4-opus-20250514": 8192,
- "anthropic.claude-opus-4-20250514-v1:0": 8192,
- "claude-opus-4@20250514": 8192,
- "claude-opus-4-1-20250805": 8192,
- "anthropic.claude-opus-4-1-20250805-v1:0": 8192,
- "claude-opus-4-1@20250805": 8192
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs
-function getOutputFormat5(params) {
- return params?.output_format ?? params?.output_config?.format;
-}
-function maybeParseBetaMessage3(message, params, opts) {
- const outputFormat = getOutputFormat5(params);
- if (!params || !("parse" in (outputFormat ?? {}))) {
- return {
- ...message,
- content: message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: null,
- enumerable: false
- });
- return Object.defineProperty(parsedBlock, "parsed", {
- get() {
- opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");
- return null;
- },
- enumerable: false
- });
- }
- return block2;
- }),
- parsed_output: null
- };
- }
- return parseBetaMessage3(message, params, opts);
-}
-function parseBetaMessage3(message, params, opts) {
- let firstParsedOutput = null;
- const content = message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedOutput = parseBetaOutputFormat3(params, block2.text);
- if (firstParsedOutput === null) {
- firstParsedOutput = parsedOutput;
- }
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: parsedOutput,
- enumerable: false
- });
- return Object.defineProperty(parsedBlock, "parsed", {
- get() {
- opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");
- return parsedOutput;
- },
- enumerable: false
- });
- }
- return block2;
- });
- return {
- ...message,
- content,
- parsed_output: firstParsedOutput
- };
-}
-function parseBetaOutputFormat3(params, content) {
- const outputFormat = getOutputFormat5(params);
- if (outputFormat?.type !== "json_schema") {
- return null;
- }
- try {
- if ("parse" in outputFormat) {
- return outputFormat.parse(content);
- }
- return JSON.parse(content);
- } catch (error45) {
- throw new AnthropicError4(`Failed to parse structured output: ${error45}`);
- }
-}
-var init_beta_parser3 = __esm(() => {
- init_error11();
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs
-var tokenize4 = (input) => {
- let current = 0;
- let tokens = [];
- while (current < input.length) {
- let char = input[current];
- if (char === "\\") {
- current++;
- continue;
- }
- if (char === "{") {
- tokens.push({
- type: "brace",
- value: "{"
- });
- current++;
- continue;
- }
- if (char === "}") {
- tokens.push({
- type: "brace",
- value: "}"
- });
- current++;
- continue;
- }
- if (char === "[") {
- tokens.push({
- type: "paren",
- value: "["
- });
- current++;
- continue;
- }
- if (char === "]") {
- tokens.push({
- type: "paren",
- value: "]"
- });
- current++;
- continue;
- }
- if (char === ":") {
- tokens.push({
- type: "separator",
- value: ":"
- });
- current++;
- continue;
- }
- if (char === ",") {
- tokens.push({
- type: "delimiter",
- value: ","
- });
- current++;
- continue;
- }
- if (char === '"') {
- let value = "";
- let danglingQuote = false;
- char = input[++current];
- while (char !== '"') {
- if (current === input.length) {
- danglingQuote = true;
- break;
- }
- if (char === "\\") {
- current++;
- if (current === input.length) {
- danglingQuote = true;
- break;
- }
- value += char + input[current];
- char = input[++current];
- } else {
- value += char;
- char = input[++current];
- }
- }
- char = input[++current];
- if (!danglingQuote) {
- tokens.push({
- type: "string",
- value
- });
- }
- continue;
- }
- let WHITESPACE = /\s/;
- if (char && WHITESPACE.test(char)) {
- current++;
- continue;
- }
- let NUMBERS = /[0-9]/;
- if (char && NUMBERS.test(char) || char === "-" || char === ".") {
- let value = "";
- if (char === "-") {
- value += char;
- char = input[++current];
- }
- while (char && NUMBERS.test(char) || char === ".") {
- value += char;
- char = input[++current];
- }
- tokens.push({
- type: "number",
- value
- });
- continue;
- }
- let LETTERS = /[a-z]/i;
- if (char && LETTERS.test(char)) {
- let value = "";
- while (char && LETTERS.test(char)) {
- if (current === input.length) {
- break;
- }
- value += char;
- char = input[++current];
- }
- if (value == "true" || value == "false" || value === "null") {
- tokens.push({
- type: "name",
- value
- });
- } else {
- current++;
- continue;
- }
- continue;
- }
- current++;
- }
- return tokens;
-}, strip4 = (tokens) => {
- if (tokens.length === 0) {
- return tokens;
- }
- let lastToken = tokens[tokens.length - 1];
- switch (lastToken.type) {
- case "separator":
- tokens = tokens.slice(0, tokens.length - 1);
- return strip4(tokens);
- break;
- case "number":
- let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
- if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip4(tokens);
- }
- case "string":
- let tokenBeforeTheLastToken = tokens[tokens.length - 2];
- if (tokenBeforeTheLastToken?.type === "delimiter") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip4(tokens);
- } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") {
- tokens = tokens.slice(0, tokens.length - 1);
- return strip4(tokens);
- }
- break;
- case "delimiter":
- tokens = tokens.slice(0, tokens.length - 1);
- return strip4(tokens);
- break;
- }
- return tokens;
-}, unstrip4 = (tokens) => {
- let tail = [];
- tokens.map((token) => {
- if (token.type === "brace") {
- if (token.value === "{") {
- tail.push("}");
- } else {
- tail.splice(tail.lastIndexOf("}"), 1);
- }
- }
- if (token.type === "paren") {
- if (token.value === "[") {
- tail.push("]");
- } else {
- tail.splice(tail.lastIndexOf("]"), 1);
- }
- }
- });
- if (tail.length > 0) {
- tail.reverse().map((item) => {
- if (item === "}") {
- tokens.push({
- type: "brace",
- value: "}"
- });
- } else if (item === "]") {
- tokens.push({
- type: "paren",
- value: "]"
- });
- }
- });
- }
- return tokens;
-}, generate4 = (tokens) => {
- let output = "";
- tokens.map((token) => {
- switch (token.type) {
- case "string":
- output += '"' + token.value + '"';
- break;
- default:
- output += token.value;
- break;
- }
- });
- return output;
-}, partialParse4 = (input) => JSON.parse(generate4(unstrip4(strip4(tokenize4(input)))));
-var init_parser7 = () => {};
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/streaming.mjs
-var init_streaming9 = __esm(() => {
- init_streaming8();
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs
-function tracksToolInput5(content) {
- return content.type === "tool_use" || content.type === "server_tool_use" || content.type === "mcp_tool_use";
-}
-function checkNever7(x3) {}
-var _BetaMessageStream_instances4, _BetaMessageStream_currentMessageSnapshot4, _BetaMessageStream_params3, _BetaMessageStream_connectedPromise4, _BetaMessageStream_resolveConnectedPromise4, _BetaMessageStream_rejectConnectedPromise4, _BetaMessageStream_endPromise4, _BetaMessageStream_resolveEndPromise4, _BetaMessageStream_rejectEndPromise4, _BetaMessageStream_listeners4, _BetaMessageStream_ended4, _BetaMessageStream_errored4, _BetaMessageStream_aborted4, _BetaMessageStream_catchingPromiseCreated4, _BetaMessageStream_response4, _BetaMessageStream_request_id4, _BetaMessageStream_logger3, _BetaMessageStream_getFinalMessage4, _BetaMessageStream_getFinalText4, _BetaMessageStream_handleError4, _BetaMessageStream_beginRequest4, _BetaMessageStream_addStreamEvent4, _BetaMessageStream_endRequest4, _BetaMessageStream_accumulateMessage4, JSON_BUF_PROPERTY7 = "__json_buf", BetaMessageStream4;
-var init_BetaMessageStream4 = __esm(() => {
- init_tslib3();
- init_parser7();
- init_error12();
- init_streaming9();
- init_beta_parser3();
- BetaMessageStream4 = class BetaMessageStream4 {
- constructor(params, opts) {
- _BetaMessageStream_instances4.add(this);
- this.messages = [];
- this.receivedMessages = [];
- _BetaMessageStream_currentMessageSnapshot4.set(this, undefined);
- _BetaMessageStream_params3.set(this, null);
- this.controller = new AbortController;
- _BetaMessageStream_connectedPromise4.set(this, undefined);
- _BetaMessageStream_resolveConnectedPromise4.set(this, () => {});
- _BetaMessageStream_rejectConnectedPromise4.set(this, () => {});
- _BetaMessageStream_endPromise4.set(this, undefined);
- _BetaMessageStream_resolveEndPromise4.set(this, () => {});
- _BetaMessageStream_rejectEndPromise4.set(this, () => {});
- _BetaMessageStream_listeners4.set(this, {});
- _BetaMessageStream_ended4.set(this, false);
- _BetaMessageStream_errored4.set(this, false);
- _BetaMessageStream_aborted4.set(this, false);
- _BetaMessageStream_catchingPromiseCreated4.set(this, false);
- _BetaMessageStream_response4.set(this, undefined);
- _BetaMessageStream_request_id4.set(this, undefined);
- _BetaMessageStream_logger3.set(this, undefined);
- _BetaMessageStream_handleError4.set(this, (error45) => {
- __classPrivateFieldSet8(this, _BetaMessageStream_errored4, true, "f");
- if (isAbortError6(error45)) {
- error45 = new APIUserAbortError4;
- }
- if (error45 instanceof APIUserAbortError4) {
- __classPrivateFieldSet8(this, _BetaMessageStream_aborted4, true, "f");
- return this._emit("abort", error45);
- }
- if (error45 instanceof AnthropicError4) {
- return this._emit("error", error45);
- }
- if (error45 instanceof Error) {
- const anthropicError = new AnthropicError4(error45.message);
- anthropicError.cause = error45;
- return this._emit("error", anthropicError);
- }
- return this._emit("error", new AnthropicError4(String(error45)));
- });
- __classPrivateFieldSet8(this, _BetaMessageStream_connectedPromise4, new Promise((resolve9, reject) => {
- __classPrivateFieldSet8(this, _BetaMessageStream_resolveConnectedPromise4, resolve9, "f");
- __classPrivateFieldSet8(this, _BetaMessageStream_rejectConnectedPromise4, reject, "f");
- }), "f");
- __classPrivateFieldSet8(this, _BetaMessageStream_endPromise4, new Promise((resolve9, reject) => {
- __classPrivateFieldSet8(this, _BetaMessageStream_resolveEndPromise4, resolve9, "f");
- __classPrivateFieldSet8(this, _BetaMessageStream_rejectEndPromise4, reject, "f");
- }), "f");
- __classPrivateFieldGet8(this, _BetaMessageStream_connectedPromise4, "f").catch(() => {});
- __classPrivateFieldGet8(this, _BetaMessageStream_endPromise4, "f").catch(() => {});
- __classPrivateFieldSet8(this, _BetaMessageStream_params3, params, "f");
- __classPrivateFieldSet8(this, _BetaMessageStream_logger3, opts?.logger ?? console, "f");
- }
- get response() {
- return __classPrivateFieldGet8(this, _BetaMessageStream_response4, "f");
- }
- get request_id() {
- return __classPrivateFieldGet8(this, _BetaMessageStream_request_id4, "f");
- }
- async withResponse() {
- __classPrivateFieldSet8(this, _BetaMessageStream_catchingPromiseCreated4, true, "f");
- const response7 = await __classPrivateFieldGet8(this, _BetaMessageStream_connectedPromise4, "f");
- if (!response7) {
- throw new Error("Could not resolve a `Response` object");
- }
- return {
- data: this,
- response: response7,
- request_id: response7.headers.get("request-id")
- };
- }
- static fromReadableStream(stream10) {
- const runner = new BetaMessageStream4(null);
- runner._run(() => runner._fromReadableStream(stream10));
- return runner;
- }
- static createMessage(messages, params, options2, { logger: logger34 } = {}) {
- const runner = new BetaMessageStream4(params, { logger: logger34 });
- for (const message of params.messages) {
- runner._addMessageParam(message);
- }
- __classPrivateFieldSet8(runner, _BetaMessageStream_params3, { ...params, stream: true }, "f");
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options2, headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" } }));
- return runner;
- }
- _run(executor) {
- executor().then(() => {
- this._emitFinal();
- this._emit("end");
- }, __classPrivateFieldGet8(this, _BetaMessageStream_handleError4, "f"));
- }
- _addMessageParam(message) {
- this.messages.push(message);
- }
- _addMessage(message, emit = true) {
- this.receivedMessages.push(message);
- if (emit) {
- this._emit("message", message);
- }
- }
- async _createMessage(messages, params, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet8(this, _BetaMessageStream_instances4, "m", _BetaMessageStream_beginRequest4).call(this);
- const { response: response7, data: stream10 } = await messages.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal }).withResponse();
- this._connected(response7);
- for await (const event of stream10) {
- __classPrivateFieldGet8(this, _BetaMessageStream_instances4, "m", _BetaMessageStream_addStreamEvent4).call(this, event);
- }
- if (stream10.controller.signal?.aborted) {
- throw new APIUserAbortError4;
- }
- __classPrivateFieldGet8(this, _BetaMessageStream_instances4, "m", _BetaMessageStream_endRequest4).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- _connected(response7) {
- if (this.ended)
- return;
- __classPrivateFieldSet8(this, _BetaMessageStream_response4, response7, "f");
- __classPrivateFieldSet8(this, _BetaMessageStream_request_id4, response7?.headers.get("request-id"), "f");
- __classPrivateFieldGet8(this, _BetaMessageStream_resolveConnectedPromise4, "f").call(this, response7);
- this._emit("connect");
- }
- get ended() {
- return __classPrivateFieldGet8(this, _BetaMessageStream_ended4, "f");
- }
- get errored() {
- return __classPrivateFieldGet8(this, _BetaMessageStream_errored4, "f");
- }
- get aborted() {
- return __classPrivateFieldGet8(this, _BetaMessageStream_aborted4, "f");
- }
- abort() {
- this.controller.abort();
- }
- on(event, listener) {
- const listeners = __classPrivateFieldGet8(this, _BetaMessageStream_listeners4, "f")[event] || (__classPrivateFieldGet8(this, _BetaMessageStream_listeners4, "f")[event] = []);
- listeners.push({ listener });
- return this;
- }
- off(event, listener) {
- const listeners = __classPrivateFieldGet8(this, _BetaMessageStream_listeners4, "f")[event];
- if (!listeners)
- return this;
- const index2 = listeners.findIndex((l4) => l4.listener === listener);
- if (index2 >= 0)
- listeners.splice(index2, 1);
- return this;
- }
- once(event, listener) {
- const listeners = __classPrivateFieldGet8(this, _BetaMessageStream_listeners4, "f")[event] || (__classPrivateFieldGet8(this, _BetaMessageStream_listeners4, "f")[event] = []);
- listeners.push({ listener, once: true });
- return this;
- }
- emitted(event) {
- return new Promise((resolve9, reject) => {
- __classPrivateFieldSet8(this, _BetaMessageStream_catchingPromiseCreated4, true, "f");
- if (event !== "error")
- this.once("error", reject);
- this.once(event, resolve9);
- });
- }
- async done() {
- __classPrivateFieldSet8(this, _BetaMessageStream_catchingPromiseCreated4, true, "f");
- await __classPrivateFieldGet8(this, _BetaMessageStream_endPromise4, "f");
- }
- get currentMessage() {
- return __classPrivateFieldGet8(this, _BetaMessageStream_currentMessageSnapshot4, "f");
- }
- async finalMessage() {
- await this.done();
- return __classPrivateFieldGet8(this, _BetaMessageStream_instances4, "m", _BetaMessageStream_getFinalMessage4).call(this);
- }
- async finalText() {
- await this.done();
- return __classPrivateFieldGet8(this, _BetaMessageStream_instances4, "m", _BetaMessageStream_getFinalText4).call(this);
- }
- _emit(event, ...args) {
- if (__classPrivateFieldGet8(this, _BetaMessageStream_ended4, "f"))
- return;
- if (event === "end") {
- __classPrivateFieldSet8(this, _BetaMessageStream_ended4, true, "f");
- __classPrivateFieldGet8(this, _BetaMessageStream_resolveEndPromise4, "f").call(this);
- }
- const listeners = __classPrivateFieldGet8(this, _BetaMessageStream_listeners4, "f")[event];
- if (listeners) {
- __classPrivateFieldGet8(this, _BetaMessageStream_listeners4, "f")[event] = listeners.filter((l4) => !l4.once);
- listeners.forEach(({ listener }) => listener(...args));
- }
- if (event === "abort") {
- const error45 = args[0];
- if (!__classPrivateFieldGet8(this, _BetaMessageStream_catchingPromiseCreated4, "f") && !listeners?.length) {
- Promise.reject(error45);
- }
- __classPrivateFieldGet8(this, _BetaMessageStream_rejectConnectedPromise4, "f").call(this, error45);
- __classPrivateFieldGet8(this, _BetaMessageStream_rejectEndPromise4, "f").call(this, error45);
- this._emit("end");
- return;
- }
- if (event === "error") {
- const error45 = args[0];
- if (!__classPrivateFieldGet8(this, _BetaMessageStream_catchingPromiseCreated4, "f") && !listeners?.length) {
- Promise.reject(error45);
- }
- __classPrivateFieldGet8(this, _BetaMessageStream_rejectConnectedPromise4, "f").call(this, error45);
- __classPrivateFieldGet8(this, _BetaMessageStream_rejectEndPromise4, "f").call(this, error45);
- this._emit("end");
- }
- }
- _emitFinal() {
- const finalMessage = this.receivedMessages.at(-1);
- if (finalMessage) {
- this._emit("finalMessage", __classPrivateFieldGet8(this, _BetaMessageStream_instances4, "m", _BetaMessageStream_getFinalMessage4).call(this));
- }
- }
- async _fromReadableStream(readableStream, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet8(this, _BetaMessageStream_instances4, "m", _BetaMessageStream_beginRequest4).call(this);
- this._connected(null);
- const stream10 = Stream5.fromReadableStream(readableStream, this.controller);
- for await (const event of stream10) {
- __classPrivateFieldGet8(this, _BetaMessageStream_instances4, "m", _BetaMessageStream_addStreamEvent4).call(this, event);
- }
- if (stream10.controller.signal?.aborted) {
- throw new APIUserAbortError4;
- }
- __classPrivateFieldGet8(this, _BetaMessageStream_instances4, "m", _BetaMessageStream_endRequest4).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- [(_BetaMessageStream_currentMessageSnapshot4 = new WeakMap, _BetaMessageStream_params3 = new WeakMap, _BetaMessageStream_connectedPromise4 = new WeakMap, _BetaMessageStream_resolveConnectedPromise4 = new WeakMap, _BetaMessageStream_rejectConnectedPromise4 = new WeakMap, _BetaMessageStream_endPromise4 = new WeakMap, _BetaMessageStream_resolveEndPromise4 = new WeakMap, _BetaMessageStream_rejectEndPromise4 = new WeakMap, _BetaMessageStream_listeners4 = new WeakMap, _BetaMessageStream_ended4 = new WeakMap, _BetaMessageStream_errored4 = new WeakMap, _BetaMessageStream_aborted4 = new WeakMap, _BetaMessageStream_catchingPromiseCreated4 = new WeakMap, _BetaMessageStream_response4 = new WeakMap, _BetaMessageStream_request_id4 = new WeakMap, _BetaMessageStream_logger3 = new WeakMap, _BetaMessageStream_handleError4 = new WeakMap, _BetaMessageStream_instances4 = new WeakSet, _BetaMessageStream_getFinalMessage4 = function _BetaMessageStream_getFinalMessage5() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError4("stream ended without producing a Message with role=assistant");
- }
- return this.receivedMessages.at(-1);
- }, _BetaMessageStream_getFinalText4 = function _BetaMessageStream_getFinalText5() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError4("stream ended without producing a Message with role=assistant");
- }
- const textBlocks = this.receivedMessages.at(-1).content.filter((block2) => block2.type === "text").map((block2) => block2.text);
- if (textBlocks.length === 0) {
- throw new AnthropicError4("stream ended without producing a content block with type=text");
- }
- return textBlocks.join(" ");
- }, _BetaMessageStream_beginRequest4 = function _BetaMessageStream_beginRequest5() {
- if (this.ended)
- return;
- __classPrivateFieldSet8(this, _BetaMessageStream_currentMessageSnapshot4, undefined, "f");
- }, _BetaMessageStream_addStreamEvent4 = function _BetaMessageStream_addStreamEvent5(event) {
- if (this.ended)
- return;
- const messageSnapshot = __classPrivateFieldGet8(this, _BetaMessageStream_instances4, "m", _BetaMessageStream_accumulateMessage4).call(this, event);
- this._emit("streamEvent", event, messageSnapshot);
- switch (event.type) {
- case "content_block_delta": {
- const content = messageSnapshot.content.at(-1);
- switch (event.delta.type) {
- case "text_delta": {
- if (content.type === "text") {
- this._emit("text", event.delta.text, content.text || "");
- }
- break;
- }
- case "citations_delta": {
- if (content.type === "text") {
- this._emit("citation", event.delta.citation, content.citations ?? []);
- }
- break;
- }
- case "input_json_delta": {
- if (tracksToolInput5(content) && content.input) {
- this._emit("inputJson", event.delta.partial_json, content.input);
- }
- break;
- }
- case "thinking_delta": {
- if (content.type === "thinking") {
- this._emit("thinking", event.delta.thinking, content.thinking);
- }
- break;
- }
- case "signature_delta": {
- if (content.type === "thinking") {
- this._emit("signature", content.signature);
- }
- break;
- }
- case "compaction_delta": {
- if (content.type === "compaction" && content.content) {
- this._emit("compaction", content.content);
- }
- break;
- }
- default:
- checkNever7(event.delta);
- }
- break;
- }
- case "message_stop": {
- this._addMessageParam(messageSnapshot);
- this._addMessage(maybeParseBetaMessage3(messageSnapshot, __classPrivateFieldGet8(this, _BetaMessageStream_params3, "f"), { logger: __classPrivateFieldGet8(this, _BetaMessageStream_logger3, "f") }), true);
- break;
- }
- case "content_block_stop": {
- this._emit("contentBlock", messageSnapshot.content.at(-1));
- break;
- }
- case "message_start": {
- __classPrivateFieldSet8(this, _BetaMessageStream_currentMessageSnapshot4, messageSnapshot, "f");
- break;
- }
- case "content_block_start":
- case "message_delta":
- break;
- }
- }, _BetaMessageStream_endRequest4 = function _BetaMessageStream_endRequest5() {
- if (this.ended) {
- throw new AnthropicError4(`stream has ended, this shouldn't happen`);
- }
- const snapshot = __classPrivateFieldGet8(this, _BetaMessageStream_currentMessageSnapshot4, "f");
- if (!snapshot) {
- throw new AnthropicError4(`request ended without sending any chunks`);
- }
- __classPrivateFieldSet8(this, _BetaMessageStream_currentMessageSnapshot4, undefined, "f");
- return maybeParseBetaMessage3(snapshot, __classPrivateFieldGet8(this, _BetaMessageStream_params3, "f"), { logger: __classPrivateFieldGet8(this, _BetaMessageStream_logger3, "f") });
- }, _BetaMessageStream_accumulateMessage4 = function _BetaMessageStream_accumulateMessage5(event) {
- let snapshot = __classPrivateFieldGet8(this, _BetaMessageStream_currentMessageSnapshot4, "f");
- if (event.type === "message_start") {
- if (snapshot) {
- throw new AnthropicError4(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
- }
- return event.message;
- }
- if (!snapshot) {
- throw new AnthropicError4(`Unexpected event order, got ${event.type} before "message_start"`);
- }
- switch (event.type) {
- case "message_stop":
- return snapshot;
- case "message_delta":
- snapshot.container = event.delta.container;
- snapshot.stop_reason = event.delta.stop_reason;
- snapshot.stop_sequence = event.delta.stop_sequence;
- snapshot.usage.output_tokens = event.usage.output_tokens;
- snapshot.context_management = event.context_management;
- if (event.usage.input_tokens != null) {
- snapshot.usage.input_tokens = event.usage.input_tokens;
- }
- if (event.usage.cache_creation_input_tokens != null) {
- snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
- }
- if (event.usage.cache_read_input_tokens != null) {
- snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
- }
- if (event.usage.server_tool_use != null) {
- snapshot.usage.server_tool_use = event.usage.server_tool_use;
- }
- if (event.usage.iterations != null) {
- snapshot.usage.iterations = event.usage.iterations;
- }
- return snapshot;
- case "content_block_start":
- snapshot.content.push(event.content_block);
- return snapshot;
- case "content_block_delta": {
- const snapshotContent = snapshot.content.at(event.index);
- switch (event.delta.type) {
- case "text_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- text: (snapshotContent.text || "") + event.delta.text
- };
- }
- break;
- }
- case "citations_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- citations: [...snapshotContent.citations ?? [], event.delta.citation]
- };
- }
- break;
- }
- case "input_json_delta": {
- if (snapshotContent && tracksToolInput5(snapshotContent)) {
- let jsonBuf = snapshotContent[JSON_BUF_PROPERTY7] || "";
- jsonBuf += event.delta.partial_json;
- const newContent = { ...snapshotContent };
- Object.defineProperty(newContent, JSON_BUF_PROPERTY7, {
- value: jsonBuf,
- enumerable: false,
- writable: true
- });
- if (jsonBuf) {
- try {
- newContent.input = partialParse4(jsonBuf);
- } catch (err) {
- const error45 = new AnthropicError4(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`);
- __classPrivateFieldGet8(this, _BetaMessageStream_handleError4, "f").call(this, error45);
- }
- }
- snapshot.content[event.index] = newContent;
- }
- break;
- }
- case "thinking_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- thinking: snapshotContent.thinking + event.delta.thinking
- };
- }
- break;
- }
- case "signature_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- signature: event.delta.signature
- };
- }
- break;
- }
- case "compaction_delta": {
- if (snapshotContent?.type === "compaction") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- content: (snapshotContent.content || "") + event.delta.content
- };
- }
- break;
- }
- default:
- checkNever7(event.delta);
- }
- return snapshot;
- }
- case "content_block_stop":
- return snapshot;
- }
- }, Symbol.asyncIterator)]() {
- const pushQueue = [];
- const readQueue = [];
- let done = false;
- this.on("streamEvent", (event) => {
- const reader = readQueue.shift();
- if (reader) {
- reader.resolve(event);
- } else {
- pushQueue.push(event);
- }
- });
- this.on("end", () => {
- done = true;
- for (const reader of readQueue) {
- reader.resolve(undefined);
- }
- readQueue.length = 0;
- });
- this.on("abort", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- this.on("error", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- return {
- next: async () => {
- if (!pushQueue.length) {
- if (done) {
- return { value: undefined, done: true };
- }
- return new Promise((resolve9, reject) => readQueue.push({ resolve: resolve9, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
- }
- const chunk = pushQueue.shift();
- return { value: chunk, done: false };
- },
- return: async () => {
- this.abort();
- return { value: undefined, done: true };
- }
- };
- }
- toReadableStream() {
- const stream10 = new Stream5(this[Symbol.asyncIterator].bind(this), this.controller);
- return stream10.toReadableStream();
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs
-var ToolError3;
-var init_ToolError3 = __esm(() => {
- ToolError3 = class ToolError3 extends Error {
- constructor(content) {
- const message = typeof content === "string" ? content : content.map((block2) => {
- if (block2.type === "text")
- return block2.text;
- return `[${block2.type}]`;
- }).join(" ");
- super(message);
- this.name = "ToolError";
- this.content = content;
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs
-var DEFAULT_TOKEN_THRESHOLD3 = 1e5, DEFAULT_SUMMARY_PROMPT3 = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
-1. Task Overview
-The user's core request and success criteria
-Any clarifications or constraints they specified
-2. Current State
-What has been completed so far
-Files created, modified, or analyzed (with paths if relevant)
-Key outputs or artifacts produced
-3. Important Discoveries
-Technical constraints or requirements uncovered
-Decisions made and their rationale
-Errors encountered and how they were resolved
-What approaches were tried that didn't work (and why)
-4. Next Steps
-Specific actions needed to complete the task
-Any blockers or open questions to resolve
-Priority order if multiple steps remain
-5. Context to Preserve
-User preferences or style requirements
-Domain-specific details that aren't obvious
-Any promises made to the user
-Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
-Wrap your summary in tags.`;
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs
-function promiseWithResolvers3() {
- let resolve9;
- let reject;
- const promise2 = new Promise((res, rej) => {
- resolve9 = res;
- reject = rej;
- });
- return { promise: promise2, resolve: resolve9, reject };
-}
-async function generateToolResponse3(params, lastMessage = params.messages.at(-1)) {
- if (!lastMessage || lastMessage.role !== "assistant" || !lastMessage.content || typeof lastMessage.content === "string") {
- return null;
- }
- const toolUseBlocks = lastMessage.content.filter((content) => content.type === "tool_use");
- if (toolUseBlocks.length === 0) {
- return null;
- }
- const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => {
- const tool = params.tools.find((t4) => ("name" in t4 ? t4.name : t4.mcp_server_name) === toolUse.name);
- if (!tool || !("run" in tool)) {
- return {
- type: "tool_result",
- tool_use_id: toolUse.id,
- content: `Error: Tool '${toolUse.name}' not found`,
- is_error: true
- };
- }
- try {
- let input = toolUse.input;
- if ("parse" in tool && tool.parse) {
- input = tool.parse(input);
- }
- const result = await tool.run(input);
- return {
- type: "tool_result",
- tool_use_id: toolUse.id,
- content: result
- };
- } catch (error45) {
- return {
- type: "tool_result",
- tool_use_id: toolUse.id,
- content: error45 instanceof ToolError3 ? error45.content : `Error: ${error45 instanceof Error ? error45.message : String(error45)}`,
- is_error: true
- };
- }
- }));
- return {
- role: "user",
- content: toolResults
- };
-}
-var _BetaToolRunner_instances3, _BetaToolRunner_consumed3, _BetaToolRunner_mutated3, _BetaToolRunner_state3, _BetaToolRunner_options3, _BetaToolRunner_message3, _BetaToolRunner_toolResponse3, _BetaToolRunner_completion3, _BetaToolRunner_iterationCount3, _BetaToolRunner_checkAndCompact3, _BetaToolRunner_generateToolResponse5, BetaToolRunner3;
-var init_BetaToolRunner3 = __esm(() => {
- init_tslib3();
- init_ToolError3();
- init_error11();
- init_headers5();
- init_stainless_helper_header3();
- BetaToolRunner3 = class BetaToolRunner3 {
- constructor(client14, params, options2) {
- _BetaToolRunner_instances3.add(this);
- this.client = client14;
- _BetaToolRunner_consumed3.set(this, false);
- _BetaToolRunner_mutated3.set(this, false);
- _BetaToolRunner_state3.set(this, undefined);
- _BetaToolRunner_options3.set(this, undefined);
- _BetaToolRunner_message3.set(this, undefined);
- _BetaToolRunner_toolResponse3.set(this, undefined);
- _BetaToolRunner_completion3.set(this, undefined);
- _BetaToolRunner_iterationCount3.set(this, 0);
- __classPrivateFieldSet8(this, _BetaToolRunner_state3, {
- params: {
- ...params,
- messages: structuredClone(params.messages)
- }
- }, "f");
- const helpers3 = collectStainlessHelpers3(params.tools, params.messages);
- const helperValue = ["BetaToolRunner", ...helpers3].join(", ");
- __classPrivateFieldSet8(this, _BetaToolRunner_options3, {
- ...options2,
- headers: buildHeaders5([{ "x-stainless-helper": helperValue }, options2?.headers])
- }, "f");
- __classPrivateFieldSet8(this, _BetaToolRunner_completion3, promiseWithResolvers3(), "f");
- }
- async* [(_BetaToolRunner_consumed3 = new WeakMap, _BetaToolRunner_mutated3 = new WeakMap, _BetaToolRunner_state3 = new WeakMap, _BetaToolRunner_options3 = new WeakMap, _BetaToolRunner_message3 = new WeakMap, _BetaToolRunner_toolResponse3 = new WeakMap, _BetaToolRunner_completion3 = new WeakMap, _BetaToolRunner_iterationCount3 = new WeakMap, _BetaToolRunner_instances3 = new WeakSet, _BetaToolRunner_checkAndCompact3 = async function _BetaToolRunner_checkAndCompact4() {
- const compactionControl = __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params.compactionControl;
- if (!compactionControl || !compactionControl.enabled) {
- return false;
- }
- let tokensUsed = 0;
- if (__classPrivateFieldGet8(this, _BetaToolRunner_message3, "f") !== undefined) {
- try {
- const message = await __classPrivateFieldGet8(this, _BetaToolRunner_message3, "f");
- const totalInputTokens = message.usage.input_tokens + (message.usage.cache_creation_input_tokens ?? 0) + (message.usage.cache_read_input_tokens ?? 0);
- tokensUsed = totalInputTokens + message.usage.output_tokens;
- } catch {
- return false;
- }
- }
- const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD3;
- if (tokensUsed < threshold) {
- return false;
- }
- const model = compactionControl.model ?? __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params.model;
- const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT3;
- const messages = __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params.messages;
- if (messages[messages.length - 1].role === "assistant") {
- const lastMessage = messages[messages.length - 1];
- if (Array.isArray(lastMessage.content)) {
- const nonToolBlocks = lastMessage.content.filter((block2) => block2.type !== "tool_use");
- if (nonToolBlocks.length === 0) {
- messages.pop();
- } else {
- lastMessage.content = nonToolBlocks;
- }
- }
- }
- const response7 = await this.client.beta.messages.create({
- model,
- messages: [
- ...messages,
- {
- role: "user",
- content: [
- {
- type: "text",
- text: summaryPrompt
- }
- ]
- }
- ],
- max_tokens: __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params.max_tokens
- }, {
- headers: { "x-stainless-helper": "compaction" }
- });
- if (response7.content[0]?.type !== "text") {
- throw new AnthropicError4("Expected text response for compaction");
- }
- __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params.messages = [
- {
- role: "user",
- content: response7.content
- }
- ];
- return true;
- }, Symbol.asyncIterator)]() {
- var _a7;
- if (__classPrivateFieldGet8(this, _BetaToolRunner_consumed3, "f")) {
- throw new AnthropicError4("Cannot iterate over a consumed stream");
- }
- __classPrivateFieldSet8(this, _BetaToolRunner_consumed3, true, "f");
- __classPrivateFieldSet8(this, _BetaToolRunner_mutated3, true, "f");
- __classPrivateFieldSet8(this, _BetaToolRunner_toolResponse3, undefined, "f");
- try {
- while (true) {
- let stream10;
- try {
- if (__classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params.max_iterations && __classPrivateFieldGet8(this, _BetaToolRunner_iterationCount3, "f") >= __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params.max_iterations) {
- break;
- }
- __classPrivateFieldSet8(this, _BetaToolRunner_mutated3, false, "f");
- __classPrivateFieldSet8(this, _BetaToolRunner_toolResponse3, undefined, "f");
- __classPrivateFieldSet8(this, _BetaToolRunner_iterationCount3, (_a7 = __classPrivateFieldGet8(this, _BetaToolRunner_iterationCount3, "f"), _a7++, _a7), "f");
- __classPrivateFieldSet8(this, _BetaToolRunner_message3, undefined, "f");
- const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params;
- if (params.stream) {
- stream10 = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet8(this, _BetaToolRunner_options3, "f"));
- __classPrivateFieldSet8(this, _BetaToolRunner_message3, stream10.finalMessage(), "f");
- __classPrivateFieldGet8(this, _BetaToolRunner_message3, "f").catch(() => {});
- yield stream10;
- } else {
- __classPrivateFieldSet8(this, _BetaToolRunner_message3, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet8(this, _BetaToolRunner_options3, "f")), "f");
- yield __classPrivateFieldGet8(this, _BetaToolRunner_message3, "f");
- }
- const isCompacted = await __classPrivateFieldGet8(this, _BetaToolRunner_instances3, "m", _BetaToolRunner_checkAndCompact3).call(this);
- if (!isCompacted) {
- if (!__classPrivateFieldGet8(this, _BetaToolRunner_mutated3, "f")) {
- const { role, content } = await __classPrivateFieldGet8(this, _BetaToolRunner_message3, "f");
- __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params.messages.push({ role, content });
- }
- const toolMessage = await __classPrivateFieldGet8(this, _BetaToolRunner_instances3, "m", _BetaToolRunner_generateToolResponse5).call(this, __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params.messages.at(-1));
- if (toolMessage) {
- __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params.messages.push(toolMessage);
- } else if (!__classPrivateFieldGet8(this, _BetaToolRunner_mutated3, "f")) {
- break;
- }
- }
- } finally {
- if (stream10) {
- stream10.abort();
- }
- }
- }
- if (!__classPrivateFieldGet8(this, _BetaToolRunner_message3, "f")) {
- throw new AnthropicError4("ToolRunner concluded without a message from the server");
- }
- __classPrivateFieldGet8(this, _BetaToolRunner_completion3, "f").resolve(await __classPrivateFieldGet8(this, _BetaToolRunner_message3, "f"));
- } catch (error45) {
- __classPrivateFieldSet8(this, _BetaToolRunner_consumed3, false, "f");
- __classPrivateFieldGet8(this, _BetaToolRunner_completion3, "f").promise.catch(() => {});
- __classPrivateFieldGet8(this, _BetaToolRunner_completion3, "f").reject(error45);
- __classPrivateFieldSet8(this, _BetaToolRunner_completion3, promiseWithResolvers3(), "f");
- throw error45;
- }
- }
- setMessagesParams(paramsOrMutator) {
- if (typeof paramsOrMutator === "function") {
- __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params = paramsOrMutator(__classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params);
- } else {
- __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params = paramsOrMutator;
- }
- __classPrivateFieldSet8(this, _BetaToolRunner_mutated3, true, "f");
- __classPrivateFieldSet8(this, _BetaToolRunner_toolResponse3, undefined, "f");
- }
- async generateToolResponse() {
- const message = await __classPrivateFieldGet8(this, _BetaToolRunner_message3, "f") ?? this.params.messages.at(-1);
- if (!message) {
- return null;
- }
- return __classPrivateFieldGet8(this, _BetaToolRunner_instances3, "m", _BetaToolRunner_generateToolResponse5).call(this, message);
- }
- done() {
- return __classPrivateFieldGet8(this, _BetaToolRunner_completion3, "f").promise;
- }
- async runUntilDone() {
- if (!__classPrivateFieldGet8(this, _BetaToolRunner_consumed3, "f")) {
- for await (const _ of this) {}
- }
- return this.done();
- }
- get params() {
- return __classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params;
- }
- pushMessages(...messages) {
- this.setMessagesParams((params) => ({
- ...params,
- messages: [...params.messages, ...messages]
- }));
- }
- then(onfulfilled, onrejected) {
- return this.runUntilDone().then(onfulfilled, onrejected);
- }
- };
- _BetaToolRunner_generateToolResponse5 = async function _BetaToolRunner_generateToolResponse6(lastMessage) {
- if (__classPrivateFieldGet8(this, _BetaToolRunner_toolResponse3, "f") !== undefined) {
- return __classPrivateFieldGet8(this, _BetaToolRunner_toolResponse3, "f");
- }
- __classPrivateFieldSet8(this, _BetaToolRunner_toolResponse3, generateToolResponse3(__classPrivateFieldGet8(this, _BetaToolRunner_state3, "f").params, lastMessage), "f");
- return __classPrivateFieldGet8(this, _BetaToolRunner_toolResponse3, "f");
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs
-var JSONLDecoder4;
-var init_jsonl4 = __esm(() => {
- init_error11();
- init_line4();
- JSONLDecoder4 = class JSONLDecoder4 {
- constructor(iterator2, controller) {
- this.iterator = iterator2;
- this.controller = controller;
- }
- async* decoder() {
- const lineDecoder = new LineDecoder4;
- for await (const chunk of this.iterator) {
- for (const line of lineDecoder.decode(chunk)) {
- yield JSON.parse(line);
- }
- }
- for (const line of lineDecoder.flush()) {
- yield JSON.parse(line);
- }
- }
- [Symbol.asyncIterator]() {
- return this.decoder();
- }
- static fromResponse(response7, controller) {
- if (!response7.body) {
- controller.abort();
- if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
- throw new AnthropicError4(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
- }
- throw new AnthropicError4(`Attempted to iterate over a response with no body`);
- }
- return new JSONLDecoder4(ReadableStreamToAsyncIterable5(response7.body), controller);
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs
-var Batches7;
-var init_batches7 = __esm(() => {
- init_pagination12();
- init_headers5();
- init_jsonl4();
- init_error12();
- init_path5();
- Batches7 = class Batches7 extends APIResource4 {
- create(params, options2) {
- const { betas, ...body } = params;
- return this._client.post("/v1/messages/batches?beta=true", {
- body,
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- retrieve(messageBatchID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path13`/v1/messages/batches/${messageBatchID}?beta=true`, {
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/messages/batches?beta=true", Page4, {
- query,
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- delete(messageBatchID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.delete(path13`/v1/messages/batches/${messageBatchID}?beta=true`, {
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- cancel(messageBatchID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.post(path13`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
- options2?.headers
- ])
- });
- }
- async results(messageBatchID, params = {}, options2) {
- const batch = await this.retrieve(messageBatchID);
- if (!batch.results_url) {
- throw new AnthropicError4(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
- }
- const { betas } = params ?? {};
- return this._client.get(batch.results_url, {
- ...options2,
- headers: buildHeaders5([
- {
- "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
- Accept: "application/binary"
- },
- options2?.headers
- ]),
- stream: true,
- __binaryResponse: true
- })._thenUnwrap((_, props) => JSONLDecoder4.fromResponse(props.response, props.controller));
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs
-function transformOutputFormat3(params) {
- if (!params.output_format) {
- return params;
- }
- if (params.output_config?.format) {
- throw new AnthropicError4("Both output_format and output_config.format were provided. " + "Please use only output_config.format (output_format is deprecated).");
- }
- const { output_format, ...rest } = params;
- return {
- ...rest,
- output_config: {
- ...params.output_config,
- format: output_format
- }
- };
-}
-var DEPRECATED_MODELS7, MODELS_TO_WARN_WITH_THINKING_ENABLED5, Messages8;
-var init_messages7 = __esm(() => {
- init_error12();
- init_constants10();
- init_headers5();
- init_stainless_helper_header3();
- init_beta_parser3();
- init_BetaMessageStream4();
- init_BetaToolRunner3();
- init_ToolError3();
- init_batches7();
- init_batches7();
- init_BetaToolRunner3();
- init_ToolError3();
- DEPRECATED_MODELS7 = {
- "claude-1.3": "November 6th, 2024",
- "claude-1.3-100k": "November 6th, 2024",
- "claude-instant-1.1": "November 6th, 2024",
- "claude-instant-1.1-100k": "November 6th, 2024",
- "claude-instant-1.2": "November 6th, 2024",
- "claude-3-sonnet-20240229": "July 21st, 2025",
- "claude-3-opus-20240229": "January 5th, 2026",
- "claude-2.1": "July 21st, 2025",
- "claude-2.0": "July 21st, 2025",
- "claude-3-7-sonnet-latest": "February 19th, 2026",
- "claude-3-7-sonnet-20250219": "February 19th, 2026"
- };
- MODELS_TO_WARN_WITH_THINKING_ENABLED5 = ["claude-opus-4-6"];
- Messages8 = class Messages8 extends APIResource4 {
- constructor() {
- super(...arguments);
- this.batches = new Batches7(this._client);
- }
- create(params, options2) {
- const modifiedParams = transformOutputFormat3(params);
- const { betas, ...body } = modifiedParams;
- if (body.model in DEPRECATED_MODELS7) {
- console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS7[body.model]}
-Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
- }
- if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED5 && body.thinking && body.thinking.type === "enabled") {
- console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
- }
- let timeout = this._client._options.timeout;
- if (!body.stream && timeout == null) {
- const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS3[body.model] ?? undefined;
- timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
- }
- const helperHeader = stainlessHelperHeader3(body.tools, body.messages);
- return this._client.post("/v1/messages?beta=true", {
- body,
- timeout: timeout ?? 600000,
- ...options2,
- headers: buildHeaders5([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- helperHeader,
- options2?.headers
- ]),
- stream: modifiedParams.stream ?? false
- });
- }
- parse(params, options2) {
- options2 = {
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...params.betas ?? [], "structured-outputs-2025-12-15"].toString() },
- options2?.headers
- ])
- };
- return this.create(params, options2).then((message) => parseBetaMessage3(message, params, { logger: this._client.logger ?? console }));
- }
- stream(body, options2) {
- return BetaMessageStream4.createMessage(this, body, options2);
- }
- countTokens(params, options2) {
- const modifiedParams = transformOutputFormat3(params);
- const { betas, ...body } = modifiedParams;
- return this._client.post("/v1/messages/count_tokens?beta=true", {
- body,
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString() },
- options2?.headers
- ])
- });
- }
- toolRunner(body, options2) {
- return new BetaToolRunner3(this._client, body, options2);
- }
- };
- Messages8.Batches = Batches7;
- Messages8.BetaToolRunner = BetaToolRunner3;
- Messages8.ToolError = ToolError3;
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs
-var Versions3;
-var init_versions4 = __esm(() => {
- init_pagination12();
- init_headers5();
- init_uploads6();
- init_path5();
- Versions3 = class Versions3 extends APIResource4 {
- create(skillID, params = {}, options2) {
- const { betas, ...body } = params ?? {};
- return this._client.post(path13`/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions3({
- body,
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- }, this._client));
- }
- retrieve(version6, params, options2) {
- const { skill_id, betas } = params;
- return this._client.get(path13`/v1/skills/${skill_id}/versions/${version6}?beta=true`, {
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- list(skillID, params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList(path13`/v1/skills/${skillID}/versions?beta=true`, PageCursor3, {
- query,
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- delete(version6, params, options2) {
- const { skill_id, betas } = params;
- return this._client.delete(path13`/v1/skills/${skill_id}/versions/${version6}?beta=true`, {
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs
-var Skills3;
-var init_skills3 = __esm(() => {
- init_versions4();
- init_versions4();
- init_pagination12();
- init_headers5();
- init_uploads6();
- init_path5();
- Skills3 = class Skills3 extends APIResource4 {
- constructor() {
- super(...arguments);
- this.versions = new Versions3(this._client);
- }
- create(params = {}, options2) {
- const { betas, ...body } = params ?? {};
- return this._client.post("/v1/skills?beta=true", multipartFormRequestOptions3({
- body,
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- }, this._client, false));
- }
- retrieve(skillID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path13`/v1/skills/${skillID}?beta=true`, {
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/skills?beta=true", PageCursor3, {
- query,
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- delete(skillID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.delete(path13`/v1/skills/${skillID}?beta=true`, {
- ...options2,
- headers: buildHeaders5([
- { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() },
- options2?.headers
- ])
- });
- }
- };
- Skills3.Versions = Versions3;
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs
-var Beta4;
-var init_beta4 = __esm(() => {
- init_files4();
- init_files4();
- init_models7();
- init_models7();
- init_messages7();
- init_messages7();
- init_skills3();
- init_skills3();
- Beta4 = class Beta4 extends APIResource4 {
- constructor() {
- super(...arguments);
- this.models = new Models7(this._client);
- this.messages = new Messages8(this._client);
- this.files = new Files3(this._client);
- this.skills = new Skills3(this._client);
- }
- };
- Beta4.Models = Models7;
- Beta4.Messages = Messages8;
- Beta4.Files = Files3;
- Beta4.Skills = Skills3;
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/completions.mjs
-var Completions4;
-var init_completions4 = __esm(() => {
- init_headers5();
- Completions4 = class Completions4 extends APIResource4 {
- create(params, options2) {
- const { betas, ...body } = params;
- return this._client.post("/v1/complete", {
- body,
- timeout: this._client._options.timeout ?? 600000,
- ...options2,
- headers: buildHeaders5([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ]),
- stream: params.stream ?? false
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/lib/parser.mjs
-function getOutputFormat6(params) {
- return params?.output_config?.format;
-}
-function maybeParseMessage3(message, params, opts) {
- const outputFormat = getOutputFormat6(params);
- if (!params || !("parse" in (outputFormat ?? {}))) {
- return {
- ...message,
- content: message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: null,
- enumerable: false
- });
- return parsedBlock;
- }
- return block2;
- }),
- parsed_output: null
- };
- }
- return parseMessage3(message, params, opts);
-}
-function parseMessage3(message, params, opts) {
- let firstParsedOutput = null;
- const content = message.content.map((block2) => {
- if (block2.type === "text") {
- const parsedOutput = parseOutputFormat3(params, block2.text);
- if (firstParsedOutput === null) {
- firstParsedOutput = parsedOutput;
- }
- const parsedBlock = Object.defineProperty({ ...block2 }, "parsed_output", {
- value: parsedOutput,
- enumerable: false
- });
- return parsedBlock;
- }
- return block2;
- });
- return {
- ...message,
- content,
- parsed_output: firstParsedOutput
- };
-}
-function parseOutputFormat3(params, content) {
- const outputFormat = getOutputFormat6(params);
- if (outputFormat?.type !== "json_schema") {
- return null;
- }
- try {
- if ("parse" in outputFormat) {
- return outputFormat.parse(content);
- }
- return JSON.parse(content);
- } catch (error45) {
- throw new AnthropicError4(`Failed to parse structured output: ${error45}`);
- }
-}
-var init_parser8 = __esm(() => {
- init_error11();
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs
-function tracksToolInput6(content) {
- return content.type === "tool_use" || content.type === "server_tool_use";
-}
-function checkNever8(x3) {}
-var _MessageStream_instances4, _MessageStream_currentMessageSnapshot4, _MessageStream_params3, _MessageStream_connectedPromise4, _MessageStream_resolveConnectedPromise4, _MessageStream_rejectConnectedPromise4, _MessageStream_endPromise4, _MessageStream_resolveEndPromise4, _MessageStream_rejectEndPromise4, _MessageStream_listeners4, _MessageStream_ended4, _MessageStream_errored4, _MessageStream_aborted4, _MessageStream_catchingPromiseCreated4, _MessageStream_response4, _MessageStream_request_id4, _MessageStream_logger3, _MessageStream_getFinalMessage4, _MessageStream_getFinalText4, _MessageStream_handleError4, _MessageStream_beginRequest4, _MessageStream_addStreamEvent4, _MessageStream_endRequest4, _MessageStream_accumulateMessage4, JSON_BUF_PROPERTY8 = "__json_buf", MessageStream4;
-var init_MessageStream4 = __esm(() => {
- init_tslib3();
- init_error12();
- init_streaming9();
- init_parser7();
- init_parser8();
- MessageStream4 = class MessageStream4 {
- constructor(params, opts) {
- _MessageStream_instances4.add(this);
- this.messages = [];
- this.receivedMessages = [];
- _MessageStream_currentMessageSnapshot4.set(this, undefined);
- _MessageStream_params3.set(this, null);
- this.controller = new AbortController;
- _MessageStream_connectedPromise4.set(this, undefined);
- _MessageStream_resolveConnectedPromise4.set(this, () => {});
- _MessageStream_rejectConnectedPromise4.set(this, () => {});
- _MessageStream_endPromise4.set(this, undefined);
- _MessageStream_resolveEndPromise4.set(this, () => {});
- _MessageStream_rejectEndPromise4.set(this, () => {});
- _MessageStream_listeners4.set(this, {});
- _MessageStream_ended4.set(this, false);
- _MessageStream_errored4.set(this, false);
- _MessageStream_aborted4.set(this, false);
- _MessageStream_catchingPromiseCreated4.set(this, false);
- _MessageStream_response4.set(this, undefined);
- _MessageStream_request_id4.set(this, undefined);
- _MessageStream_logger3.set(this, undefined);
- _MessageStream_handleError4.set(this, (error45) => {
- __classPrivateFieldSet8(this, _MessageStream_errored4, true, "f");
- if (isAbortError6(error45)) {
- error45 = new APIUserAbortError4;
- }
- if (error45 instanceof APIUserAbortError4) {
- __classPrivateFieldSet8(this, _MessageStream_aborted4, true, "f");
- return this._emit("abort", error45);
- }
- if (error45 instanceof AnthropicError4) {
- return this._emit("error", error45);
- }
- if (error45 instanceof Error) {
- const anthropicError = new AnthropicError4(error45.message);
- anthropicError.cause = error45;
- return this._emit("error", anthropicError);
- }
- return this._emit("error", new AnthropicError4(String(error45)));
- });
- __classPrivateFieldSet8(this, _MessageStream_connectedPromise4, new Promise((resolve9, reject) => {
- __classPrivateFieldSet8(this, _MessageStream_resolveConnectedPromise4, resolve9, "f");
- __classPrivateFieldSet8(this, _MessageStream_rejectConnectedPromise4, reject, "f");
- }), "f");
- __classPrivateFieldSet8(this, _MessageStream_endPromise4, new Promise((resolve9, reject) => {
- __classPrivateFieldSet8(this, _MessageStream_resolveEndPromise4, resolve9, "f");
- __classPrivateFieldSet8(this, _MessageStream_rejectEndPromise4, reject, "f");
- }), "f");
- __classPrivateFieldGet8(this, _MessageStream_connectedPromise4, "f").catch(() => {});
- __classPrivateFieldGet8(this, _MessageStream_endPromise4, "f").catch(() => {});
- __classPrivateFieldSet8(this, _MessageStream_params3, params, "f");
- __classPrivateFieldSet8(this, _MessageStream_logger3, opts?.logger ?? console, "f");
- }
- get response() {
- return __classPrivateFieldGet8(this, _MessageStream_response4, "f");
- }
- get request_id() {
- return __classPrivateFieldGet8(this, _MessageStream_request_id4, "f");
- }
- async withResponse() {
- __classPrivateFieldSet8(this, _MessageStream_catchingPromiseCreated4, true, "f");
- const response7 = await __classPrivateFieldGet8(this, _MessageStream_connectedPromise4, "f");
- if (!response7) {
- throw new Error("Could not resolve a `Response` object");
- }
- return {
- data: this,
- response: response7,
- request_id: response7.headers.get("request-id")
- };
- }
- static fromReadableStream(stream10) {
- const runner = new MessageStream4(null);
- runner._run(() => runner._fromReadableStream(stream10));
- return runner;
- }
- static createMessage(messages, params, options2, { logger: logger34 } = {}) {
- const runner = new MessageStream4(params, { logger: logger34 });
- for (const message of params.messages) {
- runner._addMessageParam(message);
- }
- __classPrivateFieldSet8(runner, _MessageStream_params3, { ...params, stream: true }, "f");
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options2, headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" } }));
- return runner;
- }
- _run(executor) {
- executor().then(() => {
- this._emitFinal();
- this._emit("end");
- }, __classPrivateFieldGet8(this, _MessageStream_handleError4, "f"));
- }
- _addMessageParam(message) {
- this.messages.push(message);
- }
- _addMessage(message, emit = true) {
- this.receivedMessages.push(message);
- if (emit) {
- this._emit("message", message);
- }
- }
- async _createMessage(messages, params, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet8(this, _MessageStream_instances4, "m", _MessageStream_beginRequest4).call(this);
- const { response: response7, data: stream10 } = await messages.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal }).withResponse();
- this._connected(response7);
- for await (const event of stream10) {
- __classPrivateFieldGet8(this, _MessageStream_instances4, "m", _MessageStream_addStreamEvent4).call(this, event);
- }
- if (stream10.controller.signal?.aborted) {
- throw new APIUserAbortError4;
- }
- __classPrivateFieldGet8(this, _MessageStream_instances4, "m", _MessageStream_endRequest4).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- _connected(response7) {
- if (this.ended)
- return;
- __classPrivateFieldSet8(this, _MessageStream_response4, response7, "f");
- __classPrivateFieldSet8(this, _MessageStream_request_id4, response7?.headers.get("request-id"), "f");
- __classPrivateFieldGet8(this, _MessageStream_resolveConnectedPromise4, "f").call(this, response7);
- this._emit("connect");
- }
- get ended() {
- return __classPrivateFieldGet8(this, _MessageStream_ended4, "f");
- }
- get errored() {
- return __classPrivateFieldGet8(this, _MessageStream_errored4, "f");
- }
- get aborted() {
- return __classPrivateFieldGet8(this, _MessageStream_aborted4, "f");
- }
- abort() {
- this.controller.abort();
- }
- on(event, listener) {
- const listeners = __classPrivateFieldGet8(this, _MessageStream_listeners4, "f")[event] || (__classPrivateFieldGet8(this, _MessageStream_listeners4, "f")[event] = []);
- listeners.push({ listener });
- return this;
- }
- off(event, listener) {
- const listeners = __classPrivateFieldGet8(this, _MessageStream_listeners4, "f")[event];
- if (!listeners)
- return this;
- const index2 = listeners.findIndex((l4) => l4.listener === listener);
- if (index2 >= 0)
- listeners.splice(index2, 1);
- return this;
- }
- once(event, listener) {
- const listeners = __classPrivateFieldGet8(this, _MessageStream_listeners4, "f")[event] || (__classPrivateFieldGet8(this, _MessageStream_listeners4, "f")[event] = []);
- listeners.push({ listener, once: true });
- return this;
- }
- emitted(event) {
- return new Promise((resolve9, reject) => {
- __classPrivateFieldSet8(this, _MessageStream_catchingPromiseCreated4, true, "f");
- if (event !== "error")
- this.once("error", reject);
- this.once(event, resolve9);
- });
- }
- async done() {
- __classPrivateFieldSet8(this, _MessageStream_catchingPromiseCreated4, true, "f");
- await __classPrivateFieldGet8(this, _MessageStream_endPromise4, "f");
- }
- get currentMessage() {
- return __classPrivateFieldGet8(this, _MessageStream_currentMessageSnapshot4, "f");
- }
- async finalMessage() {
- await this.done();
- return __classPrivateFieldGet8(this, _MessageStream_instances4, "m", _MessageStream_getFinalMessage4).call(this);
- }
- async finalText() {
- await this.done();
- return __classPrivateFieldGet8(this, _MessageStream_instances4, "m", _MessageStream_getFinalText4).call(this);
- }
- _emit(event, ...args) {
- if (__classPrivateFieldGet8(this, _MessageStream_ended4, "f"))
- return;
- if (event === "end") {
- __classPrivateFieldSet8(this, _MessageStream_ended4, true, "f");
- __classPrivateFieldGet8(this, _MessageStream_resolveEndPromise4, "f").call(this);
- }
- const listeners = __classPrivateFieldGet8(this, _MessageStream_listeners4, "f")[event];
- if (listeners) {
- __classPrivateFieldGet8(this, _MessageStream_listeners4, "f")[event] = listeners.filter((l4) => !l4.once);
- listeners.forEach(({ listener }) => listener(...args));
- }
- if (event === "abort") {
- const error45 = args[0];
- if (!__classPrivateFieldGet8(this, _MessageStream_catchingPromiseCreated4, "f") && !listeners?.length) {
- Promise.reject(error45);
- }
- __classPrivateFieldGet8(this, _MessageStream_rejectConnectedPromise4, "f").call(this, error45);
- __classPrivateFieldGet8(this, _MessageStream_rejectEndPromise4, "f").call(this, error45);
- this._emit("end");
- return;
- }
- if (event === "error") {
- const error45 = args[0];
- if (!__classPrivateFieldGet8(this, _MessageStream_catchingPromiseCreated4, "f") && !listeners?.length) {
- Promise.reject(error45);
- }
- __classPrivateFieldGet8(this, _MessageStream_rejectConnectedPromise4, "f").call(this, error45);
- __classPrivateFieldGet8(this, _MessageStream_rejectEndPromise4, "f").call(this, error45);
- this._emit("end");
- }
- }
- _emitFinal() {
- const finalMessage = this.receivedMessages.at(-1);
- if (finalMessage) {
- this._emit("finalMessage", __classPrivateFieldGet8(this, _MessageStream_instances4, "m", _MessageStream_getFinalMessage4).call(this));
- }
- }
- async _fromReadableStream(readableStream, options2) {
- const signal = options2?.signal;
- let abortHandler;
- if (signal) {
- if (signal.aborted)
- this.controller.abort();
- abortHandler = this.controller.abort.bind(this.controller);
- signal.addEventListener("abort", abortHandler);
- }
- try {
- __classPrivateFieldGet8(this, _MessageStream_instances4, "m", _MessageStream_beginRequest4).call(this);
- this._connected(null);
- const stream10 = Stream5.fromReadableStream(readableStream, this.controller);
- for await (const event of stream10) {
- __classPrivateFieldGet8(this, _MessageStream_instances4, "m", _MessageStream_addStreamEvent4).call(this, event);
- }
- if (stream10.controller.signal?.aborted) {
- throw new APIUserAbortError4;
- }
- __classPrivateFieldGet8(this, _MessageStream_instances4, "m", _MessageStream_endRequest4).call(this);
- } finally {
- if (signal && abortHandler) {
- signal.removeEventListener("abort", abortHandler);
- }
- }
- }
- [(_MessageStream_currentMessageSnapshot4 = new WeakMap, _MessageStream_params3 = new WeakMap, _MessageStream_connectedPromise4 = new WeakMap, _MessageStream_resolveConnectedPromise4 = new WeakMap, _MessageStream_rejectConnectedPromise4 = new WeakMap, _MessageStream_endPromise4 = new WeakMap, _MessageStream_resolveEndPromise4 = new WeakMap, _MessageStream_rejectEndPromise4 = new WeakMap, _MessageStream_listeners4 = new WeakMap, _MessageStream_ended4 = new WeakMap, _MessageStream_errored4 = new WeakMap, _MessageStream_aborted4 = new WeakMap, _MessageStream_catchingPromiseCreated4 = new WeakMap, _MessageStream_response4 = new WeakMap, _MessageStream_request_id4 = new WeakMap, _MessageStream_logger3 = new WeakMap, _MessageStream_handleError4 = new WeakMap, _MessageStream_instances4 = new WeakSet, _MessageStream_getFinalMessage4 = function _MessageStream_getFinalMessage5() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError4("stream ended without producing a Message with role=assistant");
- }
- return this.receivedMessages.at(-1);
- }, _MessageStream_getFinalText4 = function _MessageStream_getFinalText5() {
- if (this.receivedMessages.length === 0) {
- throw new AnthropicError4("stream ended without producing a Message with role=assistant");
- }
- const textBlocks = this.receivedMessages.at(-1).content.filter((block2) => block2.type === "text").map((block2) => block2.text);
- if (textBlocks.length === 0) {
- throw new AnthropicError4("stream ended without producing a content block with type=text");
- }
- return textBlocks.join(" ");
- }, _MessageStream_beginRequest4 = function _MessageStream_beginRequest5() {
- if (this.ended)
- return;
- __classPrivateFieldSet8(this, _MessageStream_currentMessageSnapshot4, undefined, "f");
- }, _MessageStream_addStreamEvent4 = function _MessageStream_addStreamEvent5(event) {
- if (this.ended)
- return;
- const messageSnapshot = __classPrivateFieldGet8(this, _MessageStream_instances4, "m", _MessageStream_accumulateMessage4).call(this, event);
- this._emit("streamEvent", event, messageSnapshot);
- switch (event.type) {
- case "content_block_delta": {
- const content = messageSnapshot.content.at(-1);
- switch (event.delta.type) {
- case "text_delta": {
- if (content.type === "text") {
- this._emit("text", event.delta.text, content.text || "");
- }
- break;
- }
- case "citations_delta": {
- if (content.type === "text") {
- this._emit("citation", event.delta.citation, content.citations ?? []);
- }
- break;
- }
- case "input_json_delta": {
- if (tracksToolInput6(content) && content.input) {
- this._emit("inputJson", event.delta.partial_json, content.input);
- }
- break;
- }
- case "thinking_delta": {
- if (content.type === "thinking") {
- this._emit("thinking", event.delta.thinking, content.thinking);
- }
- break;
- }
- case "signature_delta": {
- if (content.type === "thinking") {
- this._emit("signature", content.signature);
- }
- break;
- }
- default:
- checkNever8(event.delta);
- }
- break;
- }
- case "message_stop": {
- this._addMessageParam(messageSnapshot);
- this._addMessage(maybeParseMessage3(messageSnapshot, __classPrivateFieldGet8(this, _MessageStream_params3, "f"), { logger: __classPrivateFieldGet8(this, _MessageStream_logger3, "f") }), true);
- break;
- }
- case "content_block_stop": {
- this._emit("contentBlock", messageSnapshot.content.at(-1));
- break;
- }
- case "message_start": {
- __classPrivateFieldSet8(this, _MessageStream_currentMessageSnapshot4, messageSnapshot, "f");
- break;
- }
- case "content_block_start":
- case "message_delta":
- break;
- }
- }, _MessageStream_endRequest4 = function _MessageStream_endRequest5() {
- if (this.ended) {
- throw new AnthropicError4(`stream has ended, this shouldn't happen`);
- }
- const snapshot = __classPrivateFieldGet8(this, _MessageStream_currentMessageSnapshot4, "f");
- if (!snapshot) {
- throw new AnthropicError4(`request ended without sending any chunks`);
- }
- __classPrivateFieldSet8(this, _MessageStream_currentMessageSnapshot4, undefined, "f");
- return maybeParseMessage3(snapshot, __classPrivateFieldGet8(this, _MessageStream_params3, "f"), { logger: __classPrivateFieldGet8(this, _MessageStream_logger3, "f") });
- }, _MessageStream_accumulateMessage4 = function _MessageStream_accumulateMessage5(event) {
- let snapshot = __classPrivateFieldGet8(this, _MessageStream_currentMessageSnapshot4, "f");
- if (event.type === "message_start") {
- if (snapshot) {
- throw new AnthropicError4(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
- }
- return event.message;
- }
- if (!snapshot) {
- throw new AnthropicError4(`Unexpected event order, got ${event.type} before "message_start"`);
- }
- switch (event.type) {
- case "message_stop":
- return snapshot;
- case "message_delta":
- snapshot.stop_reason = event.delta.stop_reason;
- snapshot.stop_sequence = event.delta.stop_sequence;
- snapshot.usage.output_tokens = event.usage.output_tokens;
- if (event.usage.input_tokens != null) {
- snapshot.usage.input_tokens = event.usage.input_tokens;
- }
- if (event.usage.cache_creation_input_tokens != null) {
- snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
- }
- if (event.usage.cache_read_input_tokens != null) {
- snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
- }
- if (event.usage.server_tool_use != null) {
- snapshot.usage.server_tool_use = event.usage.server_tool_use;
- }
- return snapshot;
- case "content_block_start":
- snapshot.content.push({ ...event.content_block });
- return snapshot;
- case "content_block_delta": {
- const snapshotContent = snapshot.content.at(event.index);
- switch (event.delta.type) {
- case "text_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- text: (snapshotContent.text || "") + event.delta.text
- };
- }
- break;
- }
- case "citations_delta": {
- if (snapshotContent?.type === "text") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- citations: [...snapshotContent.citations ?? [], event.delta.citation]
- };
- }
- break;
- }
- case "input_json_delta": {
- if (snapshotContent && tracksToolInput6(snapshotContent)) {
- let jsonBuf = snapshotContent[JSON_BUF_PROPERTY8] || "";
- jsonBuf += event.delta.partial_json;
- const newContent = { ...snapshotContent };
- Object.defineProperty(newContent, JSON_BUF_PROPERTY8, {
- value: jsonBuf,
- enumerable: false,
- writable: true
- });
- if (jsonBuf) {
- newContent.input = partialParse4(jsonBuf);
- }
- snapshot.content[event.index] = newContent;
- }
- break;
- }
- case "thinking_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- thinking: snapshotContent.thinking + event.delta.thinking
- };
- }
- break;
- }
- case "signature_delta": {
- if (snapshotContent?.type === "thinking") {
- snapshot.content[event.index] = {
- ...snapshotContent,
- signature: event.delta.signature
- };
- }
- break;
- }
- default:
- checkNever8(event.delta);
- }
- return snapshot;
- }
- case "content_block_stop":
- return snapshot;
- }
- }, Symbol.asyncIterator)]() {
- const pushQueue = [];
- const readQueue = [];
- let done = false;
- this.on("streamEvent", (event) => {
- const reader = readQueue.shift();
- if (reader) {
- reader.resolve(event);
- } else {
- pushQueue.push(event);
- }
- });
- this.on("end", () => {
- done = true;
- for (const reader of readQueue) {
- reader.resolve(undefined);
- }
- readQueue.length = 0;
- });
- this.on("abort", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- this.on("error", (err) => {
- done = true;
- for (const reader of readQueue) {
- reader.reject(err);
- }
- readQueue.length = 0;
- });
- return {
- next: async () => {
- if (!pushQueue.length) {
- if (done) {
- return { value: undefined, done: true };
- }
- return new Promise((resolve9, reject) => readQueue.push({ resolve: resolve9, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
- }
- const chunk = pushQueue.shift();
- return { value: chunk, done: false };
- },
- return: async () => {
- this.abort();
- return { value: undefined, done: true };
- }
- };
- }
- toReadableStream() {
- const stream10 = new Stream5(this[Symbol.asyncIterator].bind(this), this.controller);
- return stream10.toReadableStream();
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs
-var Batches8;
-var init_batches8 = __esm(() => {
- init_pagination12();
- init_headers5();
- init_jsonl4();
- init_error12();
- init_path5();
- Batches8 = class Batches8 extends APIResource4 {
- create(body, options2) {
- return this._client.post("/v1/messages/batches", { body, ...options2 });
- }
- retrieve(messageBatchID, options2) {
- return this._client.get(path13`/v1/messages/batches/${messageBatchID}`, options2);
- }
- list(query = {}, options2) {
- return this._client.getAPIList("/v1/messages/batches", Page4, { query, ...options2 });
- }
- delete(messageBatchID, options2) {
- return this._client.delete(path13`/v1/messages/batches/${messageBatchID}`, options2);
- }
- cancel(messageBatchID, options2) {
- return this._client.post(path13`/v1/messages/batches/${messageBatchID}/cancel`, options2);
- }
- async results(messageBatchID, options2) {
- const batch = await this.retrieve(messageBatchID);
- if (!batch.results_url) {
- throw new AnthropicError4(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
- }
- return this._client.get(batch.results_url, {
- ...options2,
- headers: buildHeaders5([{ Accept: "application/binary" }, options2?.headers]),
- stream: true,
- __binaryResponse: true
- })._thenUnwrap((_, props) => JSONLDecoder4.fromResponse(props.response, props.controller));
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs
-var Messages9, DEPRECATED_MODELS8, MODELS_TO_WARN_WITH_THINKING_ENABLED6;
-var init_messages8 = __esm(() => {
- init_headers5();
- init_stainless_helper_header3();
- init_MessageStream4();
- init_parser8();
- init_batches8();
- init_batches8();
- init_constants10();
- Messages9 = class Messages9 extends APIResource4 {
- constructor() {
- super(...arguments);
- this.batches = new Batches8(this._client);
- }
- create(body, options2) {
- if (body.model in DEPRECATED_MODELS8) {
- console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS8[body.model]}
-Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
- }
- if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED6 && body.thinking && body.thinking.type === "enabled") {
- console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
- }
- let timeout = this._client._options.timeout;
- if (!body.stream && timeout == null) {
- const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS3[body.model] ?? undefined;
- timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
- }
- const helperHeader = stainlessHelperHeader3(body.tools, body.messages);
- return this._client.post("/v1/messages", {
- body,
- timeout: timeout ?? 600000,
- ...options2,
- headers: buildHeaders5([helperHeader, options2?.headers]),
- stream: body.stream ?? false
- });
- }
- parse(params, options2) {
- return this.create(params, options2).then((message) => parseMessage3(message, params, { logger: this._client.logger ?? console }));
- }
- stream(body, options2) {
- return MessageStream4.createMessage(this, body, options2, { logger: this._client.logger ?? console });
- }
- countTokens(body, options2) {
- return this._client.post("/v1/messages/count_tokens", { body, ...options2 });
- }
- };
- DEPRECATED_MODELS8 = {
- "claude-1.3": "November 6th, 2024",
- "claude-1.3-100k": "November 6th, 2024",
- "claude-instant-1.1": "November 6th, 2024",
- "claude-instant-1.1-100k": "November 6th, 2024",
- "claude-instant-1.2": "November 6th, 2024",
- "claude-3-sonnet-20240229": "July 21st, 2025",
- "claude-3-opus-20240229": "January 5th, 2026",
- "claude-2.1": "July 21st, 2025",
- "claude-2.0": "July 21st, 2025",
- "claude-3-7-sonnet-latest": "February 19th, 2026",
- "claude-3-7-sonnet-20250219": "February 19th, 2026",
- "claude-3-5-haiku-latest": "February 19th, 2026",
- "claude-3-5-haiku-20241022": "February 19th, 2026"
- };
- MODELS_TO_WARN_WITH_THINKING_ENABLED6 = ["claude-opus-4-6"];
- Messages9.Batches = Batches8;
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/models.mjs
-var Models8;
-var init_models8 = __esm(() => {
- init_pagination12();
- init_headers5();
- init_path5();
- Models8 = class Models8 extends APIResource4 {
- retrieve(modelID, params = {}, options2) {
- const { betas } = params ?? {};
- return this._client.get(path13`/v1/models/${modelID}`, {
- ...options2,
- headers: buildHeaders5([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- list(params = {}, options2) {
- const { betas, ...query } = params ?? {};
- return this._client.getAPIList("/v1/models", Page4, {
- query,
- ...options2,
- headers: buildHeaders5([
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
- options2?.headers
- ])
- });
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/resources/index.mjs
-var init_resources4 = __esm(() => {
- init_beta4();
- init_completions4();
- init_messages8();
- init_models8();
- init_shared11();
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs
-var readEnv6 = (env5) => {
- if (typeof globalThis.process !== "undefined") {
- return globalThis.process.env?.[env5]?.trim() ?? undefined;
- }
- if (typeof globalThis.Deno !== "undefined") {
- return globalThis.Deno.env?.get?.(env5)?.trim();
- }
- return;
-};
-
-// node_modules/@anthropic-ai/vertex-sdk/node_modules/@anthropic-ai/sdk/client.mjs
-class BaseAnthropic3 {
- constructor({ baseURL = readEnv6("ANTHROPIC_BASE_URL"), apiKey = readEnv6("ANTHROPIC_API_KEY") ?? null, authToken = readEnv6("ANTHROPIC_AUTH_TOKEN") ?? null, ...opts } = {}) {
- _BaseAnthropic_instances3.add(this);
- _BaseAnthropic_encoder3.set(this, undefined);
- const options2 = {
- apiKey,
- authToken,
- ...opts,
- baseURL: baseURL || `https://api.anthropic.com`
- };
- if (!options2.dangerouslyAllowBrowser && isRunningInBrowser4()) {
- throw new AnthropicError4(`It looks like you're running in a browser-like environment.
-
-This is disabled by default, as it risks exposing your secret API credentials to attackers.
-If you understand the risks and have appropriate mitigations in place,
-you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
-
-new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
-`);
- }
- this.baseURL = options2.baseURL;
- this.timeout = options2.timeout ?? _a7.DEFAULT_TIMEOUT;
- this.logger = options2.logger ?? console;
- const defaultLogLevel = "warn";
- this.logLevel = defaultLogLevel;
- this.logLevel = parseLogLevel3(options2.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel3(readEnv6("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", this) ?? defaultLogLevel;
- this.fetchOptions = options2.fetchOptions;
- this.maxRetries = options2.maxRetries ?? 2;
- this.fetch = options2.fetch ?? getDefaultFetch3();
- __classPrivateFieldSet8(this, _BaseAnthropic_encoder3, FallbackEncoder3, "f");
- this._options = options2;
- this.apiKey = typeof apiKey === "string" ? apiKey : null;
- this.authToken = authToken;
- }
- withOptions(options2) {
- const client14 = new this.constructor({
- ...this._options,
- baseURL: this.baseURL,
- maxRetries: this.maxRetries,
- timeout: this.timeout,
- logger: this.logger,
- logLevel: this.logLevel,
- fetch: this.fetch,
- fetchOptions: this.fetchOptions,
- apiKey: this.apiKey,
- authToken: this.authToken,
- ...options2
- });
- return client14;
- }
- defaultQuery() {
- return this._options.defaultQuery;
- }
- validateHeaders({ values: values2, nulls }) {
- if (values2.get("x-api-key") || values2.get("authorization")) {
- return;
- }
- if (this.apiKey && values2.get("x-api-key")) {
- return;
- }
- if (nulls.has("x-api-key")) {
- return;
- }
- if (this.authToken && values2.get("authorization")) {
- return;
- }
- if (nulls.has("authorization")) {
- return;
- }
- throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
- }
- async authHeaders(opts) {
- return buildHeaders5([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
- }
- async apiKeyAuth(opts) {
- if (this.apiKey == null) {
- return;
- }
- return buildHeaders5([{ "X-Api-Key": this.apiKey }]);
- }
- async bearerAuth(opts) {
- if (this.authToken == null) {
- return;
- }
- return buildHeaders5([{ Authorization: `Bearer ${this.authToken}` }]);
- }
- stringifyQuery(query) {
- return stringifyQuery3(query);
- }
- getUserAgent() {
- return `${this.constructor.name}/JS ${VERSION6}`;
- }
- defaultIdempotencyKey() {
- return `stainless-node-retry-${uuid45()}`;
- }
- makeStatusError(status, error45, message, headers) {
- return APIError4.generate(status, error45, message, headers);
- }
- buildURL(path14, query, defaultBaseURL) {
- const baseURL = !__classPrivateFieldGet8(this, _BaseAnthropic_instances3, "m", _BaseAnthropic_baseURLOverridden5).call(this) && defaultBaseURL || this.baseURL;
- const url3 = isAbsoluteURL5(path14) ? new URL(path14) : new URL(baseURL + (baseURL.endsWith("/") && path14.startsWith("/") ? path14.slice(1) : path14));
- const defaultQuery = this.defaultQuery();
- const pathQuery = Object.fromEntries(url3.searchParams);
- if (!isEmptyObj4(defaultQuery) || !isEmptyObj4(pathQuery)) {
- query = { ...pathQuery, ...defaultQuery, ...query };
- }
- if (typeof query === "object" && query && !Array.isArray(query)) {
- url3.search = this.stringifyQuery(query);
- }
- return url3.toString();
- }
- _calculateNonstreamingTimeout(maxTokens) {
- const defaultTimeout = 10 * 60;
- const expectedTimeout = 60 * 60 * maxTokens / 128000;
- if (expectedTimeout > defaultTimeout) {
- throw new AnthropicError4("Streaming is required for operations that may take longer than 10 minutes. " + "See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");
- }
- return defaultTimeout * 1000;
- }
- async prepareOptions(options2) {}
- async prepareRequest(request2, { url: url3, options: options2 }) {}
- get(path14, opts) {
- return this.methodRequest("get", path14, opts);
- }
- post(path14, opts) {
- return this.methodRequest("post", path14, opts);
- }
- patch(path14, opts) {
- return this.methodRequest("patch", path14, opts);
- }
- put(path14, opts) {
- return this.methodRequest("put", path14, opts);
- }
- delete(path14, opts) {
- return this.methodRequest("delete", path14, opts);
- }
- methodRequest(method, path14, opts) {
- return this.request(Promise.resolve(opts).then((opts2) => {
- return { method, path: path14, ...opts2 };
- }));
- }
- request(options2, remainingRetries = null) {
- return new APIPromise4(this, this.makeRequest(options2, remainingRetries, undefined));
- }
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
- const options2 = await optionsInput;
- const maxRetries = options2.maxRetries ?? this.maxRetries;
- if (retriesRemaining == null) {
- retriesRemaining = maxRetries;
- }
- await this.prepareOptions(options2);
- const { req, url: url3, timeout } = await this.buildRequest(options2, {
- retryCount: maxRetries - retriesRemaining
- });
- await this.prepareRequest(req, { url: url3, options: options2 });
- const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
- const retryLogStr = retryOfRequestLogID === undefined ? "" : `, retryOf: ${retryOfRequestLogID}`;
- const startTime = Date.now();
- loggerFor4(this).debug(`[${requestLogID}] sending request`, formatRequestDetails3({
- retryOfRequestLogID,
- method: options2.method,
- url: url3,
- options: options2,
- headers: req.headers
- }));
- if (options2.signal?.aborted) {
- throw new APIUserAbortError4;
- }
- const controller = new AbortController;
- const response7 = await this.fetchWithTimeout(url3, req, timeout, controller).catch(castToError4);
- const headersTime = Date.now();
- if (response7 instanceof globalThis.Error) {
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
- if (options2.signal?.aborted) {
- throw new APIUserAbortError4;
- }
- const isTimeout = isAbortError6(response7) || /timed? ?out/i.test(String(response7) + ("cause" in response7 ? String(response7.cause) : ""));
- if (retriesRemaining) {
- loggerFor4(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
- loggerFor4(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails3({
- retryOfRequestLogID,
- url: url3,
- durationMs: headersTime - startTime,
- message: response7.message
- }));
- return this.retryRequest(options2, retriesRemaining, retryOfRequestLogID ?? requestLogID);
- }
- loggerFor4(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
- loggerFor4(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails3({
- retryOfRequestLogID,
- url: url3,
- durationMs: headersTime - startTime,
- message: response7.message
- }));
- if (isTimeout) {
- throw new APIConnectionTimeoutError4;
- }
- throw new APIConnectionError4({ cause: response7 });
- }
- const specialHeaders = [...response7.headers.entries()].filter(([name3]) => name3 === "request-id").map(([name3, value]) => ", " + name3 + ": " + JSON.stringify(value)).join("");
- const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url3} ${response7.ok ? "succeeded" : "failed"} with status ${response7.status} in ${headersTime - startTime}ms`;
- if (!response7.ok) {
- const shouldRetry = await this.shouldRetry(response7);
- if (retriesRemaining && shouldRetry) {
- const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
- await CancelReadableStream3(response7.body);
- loggerFor4(this).info(`${responseInfo} - ${retryMessage2}`);
- loggerFor4(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails3({
- retryOfRequestLogID,
- url: response7.url,
- status: response7.status,
- headers: response7.headers,
- durationMs: headersTime - startTime
- }));
- return this.retryRequest(options2, retriesRemaining, retryOfRequestLogID ?? requestLogID, response7.headers);
- }
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
- loggerFor4(this).info(`${responseInfo} - ${retryMessage}`);
- const errText = await response7.text().catch((err2) => castToError4(err2).message);
- const errJSON = safeJSON5(errText);
- const errMessage = errJSON ? undefined : errText;
- loggerFor4(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails3({
- retryOfRequestLogID,
- url: response7.url,
- status: response7.status,
- headers: response7.headers,
- message: errMessage,
- durationMs: Date.now() - startTime
- }));
- const err = this.makeStatusError(response7.status, errJSON, errMessage, response7.headers);
- throw err;
- }
- loggerFor4(this).info(responseInfo);
- loggerFor4(this).debug(`[${requestLogID}] response start`, formatRequestDetails3({
- retryOfRequestLogID,
- url: response7.url,
- status: response7.status,
- headers: response7.headers,
- durationMs: headersTime - startTime
- }));
- return { response: response7, options: options2, controller, requestLogID, retryOfRequestLogID, startTime };
- }
- getAPIList(path14, Page5, opts) {
- return this.requestAPIList(Page5, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path14, ...opts2 })) : { method: "get", path: path14, ...opts });
- }
- requestAPIList(Page5, options2) {
- const request2 = this.makeRequest(options2, null, undefined);
- return new PagePromise4(this, request2, Page5);
- }
- async fetchWithTimeout(url3, init, ms, controller) {
- const { signal, method, ...options2 } = init || {};
- const abort7 = this._makeAbort(controller);
- if (signal)
- signal.addEventListener("abort", abort7, { once: true });
- const timeout = setTimeout(abort7, ms);
- const isReadableBody = globalThis.ReadableStream && options2.body instanceof globalThis.ReadableStream || typeof options2.body === "object" && options2.body !== null && Symbol.asyncIterator in options2.body;
- const fetchOptions = {
- signal: controller.signal,
- ...isReadableBody ? { duplex: "half" } : {},
- method: "GET",
- ...options2
- };
- if (method) {
- fetchOptions.method = method.toUpperCase();
- }
- try {
- return await this.fetch.call(undefined, url3, fetchOptions);
- } finally {
- clearTimeout(timeout);
- }
- }
- async shouldRetry(response7) {
- const shouldRetryHeader = response7.headers.get("x-should-retry");
- if (shouldRetryHeader === "true")
- return true;
- if (shouldRetryHeader === "false")
- return false;
- if (response7.status === 408)
- return true;
- if (response7.status === 409)
- return true;
- if (response7.status === 429)
- return true;
- if (response7.status >= 500)
- return true;
- return false;
- }
- async retryRequest(options2, retriesRemaining, requestLogID, responseHeaders) {
- let timeoutMillis;
- const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
- if (retryAfterMillisHeader) {
- const timeoutMs = parseFloat(retryAfterMillisHeader);
- if (!Number.isNaN(timeoutMs)) {
- timeoutMillis = timeoutMs;
- }
- }
- const retryAfterHeader = responseHeaders?.get("retry-after");
- if (retryAfterHeader && !timeoutMillis) {
- const timeoutSeconds = parseFloat(retryAfterHeader);
- if (!Number.isNaN(timeoutSeconds)) {
- timeoutMillis = timeoutSeconds * 1000;
- } else {
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
- }
- }
- if (timeoutMillis === undefined) {
- const maxRetries = options2.maxRetries ?? this.maxRetries;
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
- }
- await sleep5(timeoutMillis);
- return this.makeRequest(options2, retriesRemaining - 1, requestLogID);
- }
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
- const initialRetryDelay = 0.5;
- const maxRetryDelay = 8;
- const numRetries = maxRetries - retriesRemaining;
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
- const jitter = 1 - Math.random() * 0.25;
- return sleepSeconds * jitter * 1000;
- }
- calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
- const maxTime = 60 * 60 * 1000;
- const defaultTime = 60 * 10 * 1000;
- const expectedTime = maxTime * maxTokens / 128000;
- if (expectedTime > defaultTime || maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens) {
- throw new AnthropicError4("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");
- }
- return defaultTime;
- }
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
- const options2 = { ...inputOptions };
- const { method, path: path14, query, defaultBaseURL } = options2;
- const url3 = this.buildURL(path14, query, defaultBaseURL);
- if ("timeout" in options2)
- validatePositiveInteger4("timeout", options2.timeout);
- options2.timeout = options2.timeout ?? this.timeout;
- const { bodyHeaders, body } = this.buildBody({ options: options2 });
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
- const req = {
- method,
- headers: reqHeaders,
- ...options2.signal && { signal: options2.signal },
- ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
- ...body && { body },
- ...this.fetchOptions ?? {},
- ...options2.fetchOptions ?? {}
- };
- return { req, url: url3, timeout: options2.timeout };
- }
- async buildHeaders({ options: options2, method, bodyHeaders, retryCount }) {
- let idempotencyHeaders = {};
- if (this.idempotencyHeader && method !== "get") {
- if (!options2.idempotencyKey)
- options2.idempotencyKey = this.defaultIdempotencyKey();
- idempotencyHeaders[this.idempotencyHeader] = options2.idempotencyKey;
- }
- const headers = buildHeaders5([
- idempotencyHeaders,
- {
- Accept: "application/json",
- "User-Agent": this.getUserAgent(),
- "X-Stainless-Retry-Count": String(retryCount),
- ...options2.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options2.timeout / 1000)) } : {},
- ...getPlatformHeaders4(),
- ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : undefined,
- "anthropic-version": "2023-06-01"
- },
- await this.authHeaders(options2),
- this._options.defaultHeaders,
- bodyHeaders,
- options2.headers
- ]);
- this.validateHeaders(headers);
- return headers.values;
- }
- _makeAbort(controller) {
- return () => controller.abort();
- }
- buildBody({ options: { body, headers: rawHeaders } }) {
- if (!body) {
- return { bodyHeaders: undefined, body: undefined };
- }
- const headers = buildHeaders5([rawHeaders]);
- if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && headers.values.has("content-type") || globalThis.Blob && body instanceof globalThis.Blob || body instanceof FormData || body instanceof URLSearchParams || globalThis.ReadableStream && body instanceof globalThis.ReadableStream) {
- return { bodyHeaders: undefined, body };
- } else if (typeof body === "object" && ((Symbol.asyncIterator in body) || (Symbol.iterator in body) && ("next" in body) && typeof body.next === "function")) {
- return { bodyHeaders: undefined, body: ReadableStreamFrom3(body) };
- } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
- return {
- bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
- body: this.stringifyQuery(body)
- };
- } else {
- return __classPrivateFieldGet8(this, _BaseAnthropic_encoder3, "f").call(this, { body, headers });
- }
- }
-}
-var _BaseAnthropic_instances3, _a7, _BaseAnthropic_encoder3, _BaseAnthropic_baseURLOverridden5, HUMAN_PROMPT3 = "\\n\\nHuman:", AI_PROMPT3 = "\\n\\nAssistant:", Anthropic4;
-var init_client17 = __esm(() => {
- init_tslib3();
- init_values6();
- init_detect_platform3();
- init_query3();
- init_error11();
- init_pagination12();
- init_uploads7();
- init_resources4();
- init_api_promise3();
- init_completions4();
- init_models8();
- init_beta4();
- init_messages8();
- init_detect_platform3();
- init_headers5();
- init_log11();
- init_values6();
- _a7 = BaseAnthropic3, _BaseAnthropic_encoder3 = new WeakMap, _BaseAnthropic_instances3 = new WeakSet, _BaseAnthropic_baseURLOverridden5 = function _BaseAnthropic_baseURLOverridden6() {
- return this.baseURL !== "https://api.anthropic.com";
- };
- BaseAnthropic3.Anthropic = _a7;
- BaseAnthropic3.HUMAN_PROMPT = HUMAN_PROMPT3;
- BaseAnthropic3.AI_PROMPT = AI_PROMPT3;
- BaseAnthropic3.DEFAULT_TIMEOUT = 600000;
- BaseAnthropic3.AnthropicError = AnthropicError4;
- BaseAnthropic3.APIError = APIError4;
- BaseAnthropic3.APIConnectionError = APIConnectionError4;
- BaseAnthropic3.APIConnectionTimeoutError = APIConnectionTimeoutError4;
- BaseAnthropic3.APIUserAbortError = APIUserAbortError4;
- BaseAnthropic3.NotFoundError = NotFoundError4;
- BaseAnthropic3.ConflictError = ConflictError4;
- BaseAnthropic3.RateLimitError = RateLimitError4;
- BaseAnthropic3.BadRequestError = BadRequestError4;
- BaseAnthropic3.AuthenticationError = AuthenticationError5;
- BaseAnthropic3.InternalServerError = InternalServerError4;
- BaseAnthropic3.PermissionDeniedError = PermissionDeniedError4;
- BaseAnthropic3.UnprocessableEntityError = UnprocessableEntityError4;
- BaseAnthropic3.toFile = toFile4;
- Anthropic4 = class Anthropic4 extends BaseAnthropic3 {
- constructor() {
- super(...arguments);
- this.completions = new Completions4(this);
- this.messages = new Messages9(this);
- this.models = new Models8(this);
- this.beta = new Beta4(this);
- }
- };
- Anthropic4.Completions = Completions4;
- Anthropic4.Messages = Messages9;
- Anthropic4.Models = Models8;
- Anthropic4.Beta = Beta4;
-});
-
-// node_modules/extend/index.js
-var require_extend = __commonJS((exports, module) => {
- var hasOwn7 = Object.prototype.hasOwnProperty;
- var toStr = Object.prototype.toString;
- var defineProperty2 = Object.defineProperty;
- var gOPD = Object.getOwnPropertyDescriptor;
- var isArray8 = function isArray9(arr) {
- if (typeof Array.isArray === "function") {
- return Array.isArray(arr);
- }
- return toStr.call(arr) === "[object Array]";
- };
- var isPlainObject5 = function isPlainObject6(obj) {
- if (!obj || toStr.call(obj) !== "[object Object]") {
- return false;
- }
- var hasOwnConstructor = hasOwn7.call(obj, "constructor");
- var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn7.call(obj.constructor.prototype, "isPrototypeOf");
- if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
- return false;
- }
- var key;
- for (key in obj) {}
- return typeof key === "undefined" || hasOwn7.call(obj, key);
- };
- var setProperty2 = function setProperty3(target, options2) {
- if (defineProperty2 && options2.name === "__proto__") {
- defineProperty2(target, options2.name, {
- enumerable: true,
- configurable: true,
- value: options2.newValue,
- writable: true
- });
- } else {
- target[options2.name] = options2.newValue;
- }
- };
- var getProperty = function getProperty2(obj, name3) {
- if (name3 === "__proto__") {
- if (!hasOwn7.call(obj, name3)) {
- return;
- } else if (gOPD) {
- return gOPD(obj, name3).value;
- }
- }
- return obj[name3];
- };
- module.exports = function extend4() {
- var options2, name3, src, copy, copyIsArray, clone3;
- var target = arguments[0];
- var i5 = 1;
- var length = arguments.length;
- var deep = false;
- if (typeof target === "boolean") {
- deep = target;
- target = arguments[1] || {};
- i5 = 2;
- }
- if (target == null || typeof target !== "object" && typeof target !== "function") {
- target = {};
- }
- for (;i5 < length; ++i5) {
- options2 = arguments[i5];
- if (options2 != null) {
- for (name3 in options2) {
- src = getProperty(target, name3);
- copy = getProperty(options2, name3);
- if (target !== copy) {
- if (deep && copy && (isPlainObject5(copy) || (copyIsArray = isArray8(copy)))) {
- if (copyIsArray) {
- copyIsArray = false;
- clone3 = src && isArray8(src) ? src : [];
- } else {
- clone3 = src && isPlainObject5(src) ? src : {};
- }
- setProperty2(target, { name: name3, newValue: extend4(deep, clone3, copy) });
- } else if (typeof copy !== "undefined") {
- setProperty2(target, { name: name3, newValue: copy });
- }
- }
- }
- }
- }
- return target;
- };
-});
-
-// node_modules/gaxios/node_modules/is-stream/index.js
-var require_is_stream = __commonJS((exports, module) => {
- var isStream3 = (stream10) => stream10 !== null && typeof stream10 === "object" && typeof stream10.pipe === "function";
- isStream3.writable = (stream10) => isStream3(stream10) && stream10.writable !== false && typeof stream10._write === "function" && typeof stream10._writableState === "object";
- isStream3.readable = (stream10) => isStream3(stream10) && stream10.readable !== false && typeof stream10._read === "function" && typeof stream10._readableState === "object";
- isStream3.duplex = (stream10) => isStream3.writable(stream10) && isStream3.readable(stream10);
- isStream3.transform = (stream10) => isStream3.duplex(stream10) && typeof stream10._transform === "function";
- module.exports = isStream3;
-});
-
-// node_modules/gaxios/package.json
-var require_package2 = __commonJS((exports, module) => {
- module.exports = {
- name: "gaxios",
- version: "6.7.1",
- description: "A simple common HTTP client specifically for Google APIs and services.",
- main: "build/src/index.js",
- types: "build/src/index.d.ts",
- files: [
- "build/src"
- ],
- scripts: {
- lint: "gts check",
- test: "c8 mocha build/test",
- "presystem-test": "npm run compile",
- "system-test": "mocha build/system-test --timeout 80000",
- compile: "tsc -p .",
- fix: "gts fix",
- prepare: "npm run compile",
- pretest: "npm run compile",
- webpack: "webpack",
- "prebrowser-test": "npm run compile",
- "browser-test": "node build/browser-test/browser-test-runner.js",
- docs: "compodoc src/",
- "docs-test": "linkinator docs",
- "predocs-test": "npm run docs",
- "samples-test": "cd samples/ && npm link ../ && npm test && cd ../",
- prelint: "cd samples; npm link ../; npm install",
- clean: "gts clean",
- precompile: "gts clean"
- },
- repository: "googleapis/gaxios",
- keywords: [
- "google"
- ],
- engines: {
- node: ">=14"
- },
- author: "Google, LLC",
- license: "Apache-2.0",
- devDependencies: {
- "@babel/plugin-proposal-private-methods": "^7.18.6",
- "@compodoc/compodoc": "1.1.19",
- "@types/cors": "^2.8.6",
- "@types/express": "^4.16.1",
- "@types/extend": "^3.0.1",
- "@types/mocha": "^9.0.0",
- "@types/multiparty": "0.0.36",
- "@types/mv": "^2.1.0",
- "@types/ncp": "^2.0.1",
- "@types/node": "^20.0.0",
- "@types/node-fetch": "^2.5.7",
- "@types/sinon": "^17.0.0",
- "@types/tmp": "0.2.6",
- "@types/uuid": "^10.0.0",
- "abort-controller": "^3.0.0",
- assert: "^2.0.0",
- browserify: "^17.0.0",
- c8: "^8.0.0",
- cheerio: "1.0.0-rc.10",
- cors: "^2.8.5",
- execa: "^5.0.0",
- express: "^4.16.4",
- "form-data": "^4.0.0",
- gts: "^5.0.0",
- "is-docker": "^2.0.0",
- karma: "^6.0.0",
- "karma-chrome-launcher": "^3.0.0",
- "karma-coverage": "^2.0.0",
- "karma-firefox-launcher": "^2.0.0",
- "karma-mocha": "^2.0.0",
- "karma-remap-coverage": "^0.1.5",
- "karma-sourcemap-loader": "^0.4.0",
- "karma-webpack": "5.0.0",
- linkinator: "^3.0.0",
- mocha: "^8.0.0",
- multiparty: "^4.2.1",
- mv: "^2.1.1",
- ncp: "^2.0.0",
- nock: "^13.0.0",
- "null-loader": "^4.0.0",
- puppeteer: "^19.0.0",
- sinon: "^18.0.0",
- "stream-browserify": "^3.0.0",
- tmp: "0.2.3",
- "ts-loader": "^8.0.0",
- typescript: "^5.1.6",
- webpack: "^5.35.0",
- "webpack-cli": "^4.0.0"
- },
- dependencies: {
- extend: "^3.0.2",
- "https-proxy-agent": "^7.0.1",
- "is-stream": "^2.0.0",
- "node-fetch": "^2.6.9",
- uuid: "^9.0.1"
- }
- };
-});
-
-// node_modules/gaxios/build/src/util.js
-var require_util = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.pkg = undefined;
- exports.pkg = require_package2();
-});
-
-// node_modules/gaxios/build/src/common.js
-var require_common2 = __commonJS((exports) => {
- var __importDefault2 = exports && exports.__importDefault || function(mod2) {
- return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
- };
- var _a8;
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.GaxiosError = exports.GAXIOS_ERROR_SYMBOL = undefined;
- exports.defaultErrorRedactor = defaultErrorRedactor;
- var url_1 = __require("url");
- var util_1 = require_util();
- var extend_1 = __importDefault2(require_extend());
- exports.GAXIOS_ERROR_SYMBOL = Symbol.for(`${util_1.pkg.name}-gaxios-error`);
-
- class GaxiosError extends Error {
- static [(_a8 = exports.GAXIOS_ERROR_SYMBOL, Symbol.hasInstance)](instance) {
- if (instance && typeof instance === "object" && exports.GAXIOS_ERROR_SYMBOL in instance && instance[exports.GAXIOS_ERROR_SYMBOL] === util_1.pkg.version) {
- return true;
- }
- return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance);
- }
- constructor(message, config8, response7, error45) {
- var _b2;
- super(message);
- this.config = config8;
- this.response = response7;
- this.error = error45;
- this[_a8] = util_1.pkg.version;
- this.config = (0, extend_1.default)(true, {}, config8);
- if (this.response) {
- this.response.config = (0, extend_1.default)(true, {}, this.response.config);
- }
- if (this.response) {
- try {
- this.response.data = translateData(this.config.responseType, (_b2 = this.response) === null || _b2 === undefined ? undefined : _b2.data);
- } catch (_c4) {}
- this.status = this.response.status;
- }
- if (error45 && "code" in error45 && error45.code) {
- this.code = error45.code;
- }
- if (config8.errorRedactor) {
- config8.errorRedactor({
- config: this.config,
- response: this.response
- });
- }
- }
- }
- exports.GaxiosError = GaxiosError;
- function translateData(responseType, data) {
- switch (responseType) {
- case "stream":
- return data;
- case "json":
- return JSON.parse(JSON.stringify(data));
- case "arraybuffer":
- return JSON.parse(Buffer.from(data).toString("utf8"));
- case "blob":
- return JSON.parse(data.text());
- default:
- return data;
- }
- }
- function defaultErrorRedactor(data) {
- const REDACT = "< - See `errorRedactor` option in `gaxios` for configuration>.";
- function redactHeaders(headers) {
- if (!headers)
- return;
- for (const key of Object.keys(headers)) {
- if (/^authentication$/i.test(key)) {
- headers[key] = REDACT;
- }
- if (/^authorization$/i.test(key)) {
- headers[key] = REDACT;
- }
- if (/secret/i.test(key)) {
- headers[key] = REDACT;
- }
- }
- }
- function redactString(obj, key) {
- if (typeof obj === "object" && obj !== null && typeof obj[key] === "string") {
- const text = obj[key];
- if (/grant_type=/i.test(text) || /assertion=/i.test(text) || /secret/i.test(text)) {
- obj[key] = REDACT;
- }
- }
- }
- function redactObject(obj) {
- if (typeof obj === "object" && obj !== null) {
- if ("grant_type" in obj) {
- obj["grant_type"] = REDACT;
- }
- if ("assertion" in obj) {
- obj["assertion"] = REDACT;
- }
- if ("client_secret" in obj) {
- obj["client_secret"] = REDACT;
- }
- }
- }
- if (data.config) {
- redactHeaders(data.config.headers);
- redactString(data.config, "data");
- redactObject(data.config.data);
- redactString(data.config, "body");
- redactObject(data.config.body);
- try {
- const url3 = new url_1.URL("", data.config.url);
- if (url3.searchParams.has("token")) {
- url3.searchParams.set("token", REDACT);
- }
- if (url3.searchParams.has("client_secret")) {
- url3.searchParams.set("client_secret", REDACT);
- }
- data.config.url = url3.toString();
- } catch (_b2) {}
- }
- if (data.response) {
- defaultErrorRedactor({ config: data.response.config });
- redactHeaders(data.response.headers);
- redactString(data.response, "data");
- redactObject(data.response.data);
- }
- return data;
- }
-});
-
-// node_modules/gaxios/build/src/retry.js
-var require_retry2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRetryConfig = getRetryConfig;
- async function getRetryConfig(err) {
- let config8 = getConfig2(err);
- if (!err || !err.config || !config8 && !err.config.retry) {
- return { shouldRetry: false };
- }
- config8 = config8 || {};
- config8.currentRetryAttempt = config8.currentRetryAttempt || 0;
- config8.retry = config8.retry === undefined || config8.retry === null ? 3 : config8.retry;
- config8.httpMethodsToRetry = config8.httpMethodsToRetry || [
- "GET",
- "HEAD",
- "PUT",
- "OPTIONS",
- "DELETE"
- ];
- config8.noResponseRetries = config8.noResponseRetries === undefined || config8.noResponseRetries === null ? 2 : config8.noResponseRetries;
- config8.retryDelayMultiplier = config8.retryDelayMultiplier ? config8.retryDelayMultiplier : 2;
- config8.timeOfFirstRequest = config8.timeOfFirstRequest ? config8.timeOfFirstRequest : Date.now();
- config8.totalTimeout = config8.totalTimeout ? config8.totalTimeout : Number.MAX_SAFE_INTEGER;
- config8.maxRetryDelay = config8.maxRetryDelay ? config8.maxRetryDelay : Number.MAX_SAFE_INTEGER;
- const retryRanges = [
- [100, 199],
- [408, 408],
- [429, 429],
- [500, 599]
- ];
- config8.statusCodesToRetry = config8.statusCodesToRetry || retryRanges;
- err.config.retryConfig = config8;
- const shouldRetryFn = config8.shouldRetry || shouldRetryRequest;
- if (!await shouldRetryFn(err)) {
- return { shouldRetry: false, config: err.config };
- }
- const delay4 = getNextRetryDelay(config8);
- err.config.retryConfig.currentRetryAttempt += 1;
- const backoff = config8.retryBackoff ? config8.retryBackoff(err, delay4) : new Promise((resolve9) => {
- setTimeout(resolve9, delay4);
- });
- if (config8.onRetryAttempt) {
- config8.onRetryAttempt(err);
- }
- await backoff;
- return { shouldRetry: true, config: err.config };
- }
- function shouldRetryRequest(err) {
- var _a8;
- const config8 = getConfig2(err);
- if (err.name === "AbortError" || ((_a8 = err.error) === null || _a8 === undefined ? undefined : _a8.name) === "AbortError") {
- return false;
- }
- if (!config8 || config8.retry === 0) {
- return false;
- }
- if (!err.response && (config8.currentRetryAttempt || 0) >= config8.noResponseRetries) {
- return false;
- }
- if (!err.config.method || config8.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) {
- return false;
- }
- if (err.response && err.response.status) {
- let isInRange2 = false;
- for (const [min, max] of config8.statusCodesToRetry) {
- const status = err.response.status;
- if (status >= min && status <= max) {
- isInRange2 = true;
- break;
- }
- }
- if (!isInRange2) {
- return false;
- }
- }
- config8.currentRetryAttempt = config8.currentRetryAttempt || 0;
- if (config8.currentRetryAttempt >= config8.retry) {
- return false;
- }
- return true;
- }
- function getConfig2(err) {
- if (err && err.config && err.config.retryConfig) {
- return err.config.retryConfig;
- }
- return;
- }
- function getNextRetryDelay(config8) {
- var _a8;
- const retryDelay = config8.currentRetryAttempt ? 0 : (_a8 = config8.retryDelay) !== null && _a8 !== undefined ? _a8 : 100;
- const calculatedDelay = retryDelay + (Math.pow(config8.retryDelayMultiplier, config8.currentRetryAttempt) - 1) / 2 * 1000;
- const maxAllowableDelay = config8.totalTimeout - (Date.now() - config8.timeOfFirstRequest);
- return Math.min(calculatedDelay, maxAllowableDelay, config8.maxRetryDelay);
- }
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/rng.js
-var require_rng2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = rng;
- var _crypto = _interopRequireDefault(__require("crypto"));
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var rnds8Pool = new Uint8Array(256);
- var poolPtr = rnds8Pool.length;
- function rng() {
- if (poolPtr > rnds8Pool.length - 16) {
- _crypto.default.randomFillSync(rnds8Pool);
- poolPtr = 0;
- }
- return rnds8Pool.slice(poolPtr, poolPtr += 16);
- }
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/regex.js
-var require_regex2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _default3 = /^(?:[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 = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/validate.js
-var require_validate2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _regex2 = _interopRequireDefault(require_regex2());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- function validate3(uuid8) {
- return typeof uuid8 === "string" && _regex2.default.test(uuid8);
- }
- var _default3 = validate3;
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/stringify.js
-var require_stringify2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- exports.unsafeStringify = unsafeStringify;
- var _validate = _interopRequireDefault(require_validate2());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var byteToHex = [];
- for (let i5 = 0;i5 < 256; ++i5) {
- byteToHex.push((i5 + 256).toString(16).slice(1));
- }
- function unsafeStringify(arr, offset = 0) {
- 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 stringify2(arr, offset = 0) {
- const uuid8 = unsafeStringify(arr, offset);
- if (!(0, _validate.default)(uuid8)) {
- throw TypeError("Stringified UUID is invalid");
- }
- return uuid8;
- }
- var _default3 = stringify2;
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/v1.js
-var require_v12 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _rng = _interopRequireDefault(require_rng2());
- var _stringify = require_stringify2();
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var _nodeId;
- var _clockseq;
- var _lastMSecs = 0;
- var _lastNSecs = 0;
- function v12(options2, buf, offset) {
- let i5 = buf && offset || 0;
- const b4 = buf || new Array(16);
- options2 = options2 || {};
- let node = options2.node || _nodeId;
- let clockseq = options2.clockseq !== undefined ? options2.clockseq : _clockseq;
- if (node == null || clockseq == null) {
- const seedBytes = options2.random || (options2.rng || _rng.default)();
- if (node == null) {
- node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
- }
- if (clockseq == null) {
- clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383;
- }
- }
- let msecs = options2.msecs !== undefined ? options2.msecs : Date.now();
- let nsecs = options2.nsecs !== undefined ? options2.nsecs : _lastNSecs + 1;
- const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4;
- if (dt < 0 && options2.clockseq === undefined) {
- clockseq = clockseq + 1 & 16383;
- }
- if ((dt < 0 || msecs > _lastMSecs) && options2.nsecs === undefined) {
- nsecs = 0;
- }
- if (nsecs >= 1e4) {
- throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
- }
- _lastMSecs = msecs;
- _lastNSecs = nsecs;
- _clockseq = clockseq;
- msecs += 12219292800000;
- const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;
- b4[i5++] = tl >>> 24 & 255;
- b4[i5++] = tl >>> 16 & 255;
- b4[i5++] = tl >>> 8 & 255;
- b4[i5++] = tl & 255;
- const tmh = msecs / 4294967296 * 1e4 & 268435455;
- b4[i5++] = tmh >>> 8 & 255;
- b4[i5++] = tmh & 255;
- b4[i5++] = tmh >>> 24 & 15 | 16;
- b4[i5++] = tmh >>> 16 & 255;
- b4[i5++] = clockseq >>> 8 | 128;
- b4[i5++] = clockseq & 255;
- for (let n5 = 0;n5 < 6; ++n5) {
- b4[i5 + n5] = node[n5];
- }
- return buf || (0, _stringify.unsafeStringify)(b4);
- }
- var _default3 = v12;
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/parse.js
-var require_parse5 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _validate = _interopRequireDefault(require_validate2());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- function parse10(uuid8) {
- if (!(0, _validate.default)(uuid8)) {
- throw TypeError("Invalid UUID");
- }
- let v6;
- const arr = new Uint8Array(16);
- arr[0] = (v6 = parseInt(uuid8.slice(0, 8), 16)) >>> 24;
- arr[1] = v6 >>> 16 & 255;
- arr[2] = v6 >>> 8 & 255;
- arr[3] = v6 & 255;
- arr[4] = (v6 = parseInt(uuid8.slice(9, 13), 16)) >>> 8;
- arr[5] = v6 & 255;
- arr[6] = (v6 = parseInt(uuid8.slice(14, 18), 16)) >>> 8;
- arr[7] = v6 & 255;
- arr[8] = (v6 = parseInt(uuid8.slice(19, 23), 16)) >>> 8;
- arr[9] = v6 & 255;
- arr[10] = (v6 = parseInt(uuid8.slice(24, 36), 16)) / 1099511627776 & 255;
- arr[11] = v6 / 4294967296 & 255;
- arr[12] = v6 >>> 24 & 255;
- arr[13] = v6 >>> 16 & 255;
- arr[14] = v6 >>> 8 & 255;
- arr[15] = v6 & 255;
- return arr;
- }
- var _default3 = parse10;
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/v35.js
-var require_v352 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.URL = exports.DNS = undefined;
- exports.default = v35;
- var _stringify = require_stringify2();
- var _parse2 = _interopRequireDefault(require_parse5());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- function stringToBytes(str) {
- str = unescape(encodeURIComponent(str));
- const bytes = [];
- for (let i5 = 0;i5 < str.length; ++i5) {
- bytes.push(str.charCodeAt(i5));
- }
- return bytes;
- }
- var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
- exports.DNS = DNS;
- var URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
- exports.URL = URL2;
- function v35(name3, version6, hashfunc) {
- function generateUUID(value, namespace, buf, offset) {
- var _namespace;
- if (typeof value === "string") {
- value = stringToBytes(value);
- }
- if (typeof namespace === "string") {
- namespace = (0, _parse2.default)(namespace);
- }
- if (((_namespace = namespace) === null || _namespace === undefined ? undefined : _namespace.length) !== 16) {
- throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
- }
- let bytes = new Uint8Array(16 + value.length);
- bytes.set(namespace);
- bytes.set(value, namespace.length);
- bytes = hashfunc(bytes);
- bytes[6] = bytes[6] & 15 | version6;
- bytes[8] = bytes[8] & 63 | 128;
- if (buf) {
- offset = offset || 0;
- for (let i5 = 0;i5 < 16; ++i5) {
- buf[offset + i5] = bytes[i5];
- }
- return buf;
- }
- return (0, _stringify.unsafeStringify)(bytes);
- }
- try {
- generateUUID.name = name3;
- } catch (err) {}
- generateUUID.DNS = DNS;
- generateUUID.URL = URL2;
- return generateUUID;
- }
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/md5.js
-var require_md52 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _crypto = _interopRequireDefault(__require("crypto"));
- 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 _default3 = md5;
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/v3.js
-var require_v32 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _v3 = _interopRequireDefault(require_v352());
- var _md = _interopRequireDefault(require_md52());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var v33 = (0, _v3.default)("v3", 48, _md.default);
- var _default3 = v33;
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/native.js
-var require_native = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _crypto = _interopRequireDefault(__require("crypto"));
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var _default3 = {
- randomUUID: _crypto.default.randomUUID
- };
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/v4.js
-var require_v42 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _native = _interopRequireDefault(require_native());
- var _rng = _interopRequireDefault(require_rng2());
- var _stringify = require_stringify2();
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- function v42(options2, buf, offset) {
- if (_native.default.randomUUID && !buf && !options2) {
- return _native.default.randomUUID();
- }
- options2 = options2 || {};
- const rnds = options2.random || (options2.rng || _rng.default)();
- rnds[6] = rnds[6] & 15 | 64;
- rnds[8] = rnds[8] & 63 | 128;
- if (buf) {
- offset = offset || 0;
- for (let i5 = 0;i5 < 16; ++i5) {
- buf[offset + i5] = rnds[i5];
- }
- return buf;
- }
- return (0, _stringify.unsafeStringify)(rnds);
- }
- var _default3 = v42;
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/sha1.js
-var require_sha12 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _crypto = _interopRequireDefault(__require("crypto"));
- 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();
- }
- var _default3 = sha1;
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/v5.js
-var require_v52 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _v3 = _interopRequireDefault(require_v352());
- var _sha = _interopRequireDefault(require_sha12());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var v52 = (0, _v3.default)("v5", 80, _sha.default);
- var _default3 = v52;
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/nil.js
-var require_nil2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _default3 = "00000000-0000-0000-0000-000000000000";
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/version.js
-var require_version2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = undefined;
- var _validate = _interopRequireDefault(require_validate2());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- function version6(uuid8) {
- if (!(0, _validate.default)(uuid8)) {
- throw TypeError("Invalid UUID");
- }
- return parseInt(uuid8.slice(14, 15), 16);
- }
- var _default3 = version6;
- exports.default = _default3;
-});
-
-// node_modules/gaxios/node_modules/uuid/dist/index.js
-var require_dist5 = __commonJS((exports) => {
- 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 _parse2.default;
- }
- });
- Object.defineProperty(exports, "stringify", {
- enumerable: true,
- get: function() {
- return _stringify.default;
- }
- });
- Object.defineProperty(exports, "v1", {
- enumerable: true,
- get: function() {
- return _v3.default;
- }
- });
- Object.defineProperty(exports, "v3", {
- enumerable: true,
- get: function() {
- return _v22.default;
- }
- });
- Object.defineProperty(exports, "v4", {
- enumerable: true,
- get: function() {
- return _v32.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 _v3 = _interopRequireDefault(require_v12());
- var _v22 = _interopRequireDefault(require_v32());
- var _v32 = _interopRequireDefault(require_v42());
- var _v4 = _interopRequireDefault(require_v52());
- var _nil = _interopRequireDefault(require_nil2());
- var _version = _interopRequireDefault(require_version2());
- var _validate = _interopRequireDefault(require_validate2());
- var _stringify = _interopRequireDefault(require_stringify2());
- var _parse2 = _interopRequireDefault(require_parse5());
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
-});
-
-// node_modules/gaxios/build/src/interceptor.js
-var require_interceptor = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.GaxiosInterceptorManager = undefined;
-
- class GaxiosInterceptorManager extends Set {
- }
- exports.GaxiosInterceptorManager = GaxiosInterceptorManager;
-});
-
-// node_modules/gaxios/build/src/gaxios.js
-var require_gaxios = __commonJS((exports) => {
- var __createBinding2 = exports && exports.__createBinding || (Object.create ? function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- var desc = Object.getOwnPropertyDescriptor(m4, k4);
- if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() {
- return m4[k4];
- } };
- }
- Object.defineProperty(o5, k22, desc);
- } : function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- });
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
- Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
- } : function(o5, v6) {
- o5["default"] = v6;
- });
- var __importStar2 = exports && exports.__importStar || function(mod2) {
- if (mod2 && mod2.__esModule)
- return mod2;
- var result = {};
- if (mod2 != null) {
- for (var k4 in mod2)
- if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4))
- __createBinding2(result, mod2, k4);
- }
- __setModuleDefault(result, mod2);
- return result;
- };
- var __classPrivateFieldGet9 = exports && exports.__classPrivateFieldGet || function(receiver, state3, kind2, f4) {
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a getter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind2 === "m" ? f4 : kind2 === "a" ? f4.call(receiver) : f4 ? f4.value : state3.get(receiver);
- };
- var __classPrivateFieldSet9 = exports && exports.__classPrivateFieldSet || function(receiver, state3, value, kind2, f4) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a setter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return kind2 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state3.set(receiver, value), value;
- };
- var __importDefault2 = exports && exports.__importDefault || function(mod2) {
- return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
- };
- var _Gaxios_instances;
- var _a8;
- var _Gaxios_urlMayUseProxy;
- var _Gaxios_applyRequestInterceptors;
- var _Gaxios_applyResponseInterceptors;
- var _Gaxios_prepareRequest;
- var _Gaxios_proxyAgent;
- var _Gaxios_getProxyAgent;
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Gaxios = undefined;
- var extend_1 = __importDefault2(require_extend());
- var https_1 = __require("https");
- var node_fetch_1 = __importDefault2(__require("node-fetch"));
- var querystring_1 = __importDefault2(__require("querystring"));
- var is_stream_1 = __importDefault2(require_is_stream());
- var url_1 = __require("url");
- var common_1 = require_common2();
- var retry_1 = require_retry2();
- var stream_1 = __require("stream");
- var uuid_1 = require_dist5();
- var interceptor_1 = require_interceptor();
- var fetch3 = hasFetch() ? window.fetch : node_fetch_1.default;
- function hasWindow() {
- return typeof window !== "undefined" && !!window;
- }
- function hasFetch() {
- return hasWindow() && !!window.fetch;
- }
- function hasBuffer() {
- return typeof Buffer !== "undefined";
- }
- function hasHeader2(options2, header) {
- return !!getHeader2(options2, header);
- }
- function getHeader2(options2, header) {
- header = header.toLowerCase();
- for (const key of Object.keys((options2 === null || options2 === undefined ? undefined : options2.headers) || {})) {
- if (header === key.toLowerCase()) {
- return options2.headers[key];
- }
- }
- return;
- }
-
- class Gaxios {
- constructor(defaults2) {
- _Gaxios_instances.add(this);
- this.agentCache = new Map;
- this.defaults = defaults2 || {};
- this.interceptors = {
- request: new interceptor_1.GaxiosInterceptorManager,
- response: new interceptor_1.GaxiosInterceptorManager
- };
- }
- async request(opts = {}) {
- opts = await __classPrivateFieldGet9(this, _Gaxios_instances, "m", _Gaxios_prepareRequest).call(this, opts);
- opts = await __classPrivateFieldGet9(this, _Gaxios_instances, "m", _Gaxios_applyRequestInterceptors).call(this, opts);
- return __classPrivateFieldGet9(this, _Gaxios_instances, "m", _Gaxios_applyResponseInterceptors).call(this, this._request(opts));
- }
- async _defaultAdapter(opts) {
- const fetchImpl = opts.fetchImplementation || fetch3;
- const res = await fetchImpl(opts.url, opts);
- const data = await this.getResponseData(opts, res);
- return this.translateResponse(opts, res, data);
- }
- async _request(opts = {}) {
- var _b2;
- try {
- let translatedResponse;
- if (opts.adapter) {
- translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this));
- } else {
- translatedResponse = await this._defaultAdapter(opts);
- }
- if (!opts.validateStatus(translatedResponse.status)) {
- if (opts.responseType === "stream") {
- let response7 = "";
- await new Promise((resolve9) => {
- (translatedResponse === null || translatedResponse === undefined ? undefined : translatedResponse.data).on("data", (chunk) => {
- response7 += chunk;
- });
- (translatedResponse === null || translatedResponse === undefined ? undefined : translatedResponse.data).on("end", resolve9);
- });
- translatedResponse.data = response7;
- }
- throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse);
- }
- return translatedResponse;
- } catch (e4) {
- const err = e4 instanceof common_1.GaxiosError ? e4 : new common_1.GaxiosError(e4.message, opts, undefined, e4);
- const { shouldRetry, config: config8 } = await (0, retry_1.getRetryConfig)(err);
- if (shouldRetry && config8) {
- err.config.retryConfig.currentRetryAttempt = config8.retryConfig.currentRetryAttempt;
- opts.retryConfig = (_b2 = err.config) === null || _b2 === undefined ? undefined : _b2.retryConfig;
- return this._request(opts);
- }
- throw err;
- }
- }
- async getResponseData(opts, res) {
- switch (opts.responseType) {
- case "stream":
- return res.body;
- case "json": {
- let data = await res.text();
- try {
- data = JSON.parse(data);
- } catch (_b2) {}
- return data;
- }
- case "arraybuffer":
- return res.arrayBuffer();
- case "blob":
- return res.blob();
- case "text":
- return res.text();
- default:
- return this.getResponseDataFromContentType(res);
- }
- }
- validateStatus(status) {
- return status >= 200 && status < 300;
- }
- paramsSerializer(params) {
- return querystring_1.default.stringify(params);
- }
- translateResponse(opts, res, data) {
- const headers = {};
- res.headers.forEach((value, key) => {
- headers[key] = value;
- });
- return {
- config: opts,
- data,
- headers,
- status: res.status,
- statusText: res.statusText,
- request: {
- responseURL: res.url
- }
- };
- }
- async getResponseDataFromContentType(response7) {
- let contentType = response7.headers.get("Content-Type");
- if (contentType === null) {
- return response7.text();
- }
- contentType = contentType.toLowerCase();
- if (contentType.includes("application/json")) {
- let data = await response7.text();
- try {
- data = JSON.parse(data);
- } catch (_b2) {}
- return data;
- } else if (contentType.match(/^text\//)) {
- return response7.text();
- } else {
- return response7.blob();
- }
- }
- async* getMultipartRequest(multipartOptions, boundary) {
- const finale = `--${boundary}--`;
- for (const currentPart of multipartOptions) {
- const partContentType = currentPart.headers["Content-Type"] || "application/octet-stream";
- const preamble = `--${boundary}\r
-Content-Type: ${partContentType}\r
-\r
-`;
- yield preamble;
- if (typeof currentPart.content === "string") {
- yield currentPart.content;
- } else {
- yield* currentPart.content;
- }
- yield `\r
-`;
- }
- yield finale;
- }
- }
- exports.Gaxios = Gaxios;
- _a8 = Gaxios, _Gaxios_instances = new WeakSet, _Gaxios_urlMayUseProxy = function _Gaxios_urlMayUseProxy2(url3, noProxy = []) {
- var _b2, _c4;
- const candidate = new url_1.URL(url3);
- const noProxyList = [...noProxy];
- const noProxyEnvList = ((_c4 = (_b2 = process.env.NO_PROXY) !== null && _b2 !== undefined ? _b2 : process.env.no_proxy) === null || _c4 === undefined ? undefined : _c4.split(",")) || [];
- for (const rule of noProxyEnvList) {
- noProxyList.push(rule.trim());
- }
- for (const rule of noProxyList) {
- if (rule instanceof RegExp) {
- if (rule.test(candidate.toString())) {
- return false;
- }
- } else if (rule instanceof url_1.URL) {
- if (rule.origin === candidate.origin) {
- return false;
- }
- } else if (rule.startsWith("*.") || rule.startsWith(".")) {
- const cleanedRule = rule.replace(/^\*\./, ".");
- if (candidate.hostname.endsWith(cleanedRule)) {
- return false;
- }
- } else if (rule === candidate.origin || rule === candidate.hostname || rule === candidate.href) {
- return false;
- }
- }
- return true;
- }, _Gaxios_applyRequestInterceptors = async function _Gaxios_applyRequestInterceptors2(options2) {
- let promiseChain = Promise.resolve(options2);
- for (const interceptor of this.interceptors.request.values()) {
- if (interceptor) {
- promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
- }
- }
- return promiseChain;
- }, _Gaxios_applyResponseInterceptors = async function _Gaxios_applyResponseInterceptors2(response7) {
- let promiseChain = Promise.resolve(response7);
- for (const interceptor of this.interceptors.response.values()) {
- if (interceptor) {
- promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
- }
- }
- return promiseChain;
- }, _Gaxios_prepareRequest = async function _Gaxios_prepareRequest2(options2) {
- var _b2, _c4, _d3, _e4;
- const opts = (0, extend_1.default)(true, {}, this.defaults, options2);
- if (!opts.url) {
- throw new Error("URL is required.");
- }
- const baseUrl = opts.baseUrl || opts.baseURL;
- if (baseUrl) {
- opts.url = baseUrl.toString() + opts.url;
- }
- opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer;
- if (opts.params && Object.keys(opts.params).length > 0) {
- let additionalQueryParams = opts.paramsSerializer(opts.params);
- if (additionalQueryParams.startsWith("?")) {
- additionalQueryParams = additionalQueryParams.slice(1);
- }
- const prefix = opts.url.toString().includes("?") ? "&" : "?";
- opts.url = opts.url + prefix + additionalQueryParams;
- }
- if (typeof options2.maxContentLength === "number") {
- opts.size = options2.maxContentLength;
- }
- if (typeof options2.maxRedirects === "number") {
- opts.follow = options2.maxRedirects;
- }
- opts.headers = opts.headers || {};
- if (opts.multipart === undefined && opts.data) {
- const isFormData2 = typeof FormData === "undefined" ? false : (opts === null || opts === undefined ? undefined : opts.data) instanceof FormData;
- if (is_stream_1.default.readable(opts.data)) {
- opts.body = opts.data;
- } else if (hasBuffer() && Buffer.isBuffer(opts.data)) {
- opts.body = opts.data;
- if (!hasHeader2(opts, "Content-Type")) {
- opts.headers["Content-Type"] = "application/json";
- }
- } else if (typeof opts.data === "object") {
- if (!isFormData2) {
- if (getHeader2(opts, "content-type") === "application/x-www-form-urlencoded") {
- opts.body = opts.paramsSerializer(opts.data);
- } else {
- if (!hasHeader2(opts, "Content-Type")) {
- opts.headers["Content-Type"] = "application/json";
- }
- opts.body = JSON.stringify(opts.data);
- }
- }
- } else {
- opts.body = opts.data;
- }
- } else if (opts.multipart && opts.multipart.length > 0) {
- const boundary = (0, uuid_1.v4)();
- opts.headers["Content-Type"] = `multipart/related; boundary=${boundary}`;
- const bodyStream = new stream_1.PassThrough;
- opts.body = bodyStream;
- (0, stream_1.pipeline)(this.getMultipartRequest(opts.multipart, boundary), bodyStream, () => {});
- }
- opts.validateStatus = opts.validateStatus || this.validateStatus;
- opts.responseType = opts.responseType || "unknown";
- if (!opts.headers["Accept"] && opts.responseType === "json") {
- opts.headers["Accept"] = "application/json";
- }
- opts.method = opts.method || "GET";
- const proxy = opts.proxy || ((_b2 = process === null || process === undefined ? undefined : process.env) === null || _b2 === undefined ? undefined : _b2.HTTPS_PROXY) || ((_c4 = process === null || process === undefined ? undefined : process.env) === null || _c4 === undefined ? undefined : _c4.https_proxy) || ((_d3 = process === null || process === undefined ? undefined : process.env) === null || _d3 === undefined ? undefined : _d3.HTTP_PROXY) || ((_e4 = process === null || process === undefined ? undefined : process.env) === null || _e4 === undefined ? undefined : _e4.http_proxy);
- const urlMayUseProxy = __classPrivateFieldGet9(this, _Gaxios_instances, "m", _Gaxios_urlMayUseProxy).call(this, opts.url, opts.noProxy);
- if (opts.agent) {} else if (proxy && urlMayUseProxy) {
- const HttpsProxyAgent3 = await __classPrivateFieldGet9(_a8, _a8, "m", _Gaxios_getProxyAgent).call(_a8);
- if (this.agentCache.has(proxy)) {
- opts.agent = this.agentCache.get(proxy);
- } else {
- opts.agent = new HttpsProxyAgent3(proxy, {
- cert: opts.cert,
- key: opts.key
- });
- this.agentCache.set(proxy, opts.agent);
- }
- } else if (opts.cert && opts.key) {
- if (this.agentCache.has(opts.key)) {
- opts.agent = this.agentCache.get(opts.key);
- } else {
- opts.agent = new https_1.Agent({
- cert: opts.cert,
- key: opts.key
- });
- this.agentCache.set(opts.key, opts.agent);
- }
- }
- if (typeof opts.errorRedactor !== "function" && opts.errorRedactor !== false) {
- opts.errorRedactor = common_1.defaultErrorRedactor;
- }
- return opts;
- }, _Gaxios_getProxyAgent = async function _Gaxios_getProxyAgent2() {
- __classPrivateFieldSet9(this, _a8, __classPrivateFieldGet9(this, _a8, "f", _Gaxios_proxyAgent) || (await Promise.resolve().then(() => __importStar2(require_dist2()))).HttpsProxyAgent, "f", _Gaxios_proxyAgent);
- return __classPrivateFieldGet9(this, _a8, "f", _Gaxios_proxyAgent);
- };
- _Gaxios_proxyAgent = { value: undefined };
-});
-
-// node_modules/gaxios/build/src/index.js
-var require_src2 = __commonJS((exports) => {
- var __createBinding2 = exports && exports.__createBinding || (Object.create ? function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- var desc = Object.getOwnPropertyDescriptor(m4, k4);
- if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() {
- return m4[k4];
- } };
- }
- Object.defineProperty(o5, k22, desc);
- } : function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- });
- var __exportStar2 = exports && exports.__exportStar || function(m4, exports2) {
- for (var p4 in m4)
- if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
- __createBinding2(exports2, m4, p4);
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.instance = exports.Gaxios = exports.GaxiosError = undefined;
- exports.request = request2;
- var gaxios_1 = require_gaxios();
- Object.defineProperty(exports, "Gaxios", { enumerable: true, get: function() {
- return gaxios_1.Gaxios;
- } });
- var common_1 = require_common2();
- Object.defineProperty(exports, "GaxiosError", { enumerable: true, get: function() {
- return common_1.GaxiosError;
- } });
- __exportStar2(require_interceptor(), exports);
- exports.instance = new gaxios_1.Gaxios;
- async function request2(opts) {
- return exports.instance.request(opts);
- }
-});
-
-// node_modules/bignumber.js/bignumber.js
-var require_bignumber = __commonJS((exports, module) => {
- (function(globalObject) {
- var BigNumber, isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil = Math.ceil, mathfloor = Math.floor, bignumberError = "[BigNumber Error] ", tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: ", BASE = 100000000000000, LOG_BASE = 14, MAX_SAFE_INTEGER3 = 9007199254740991, POWS_TEN = [1, 10, 100, 1000, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000], SQRT_BASE = 1e7, MAX = 1e9;
- function clone3(configObject) {
- var div, convertBase, parseNumeric, P = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = {
- prefix: "",
- groupSize: 3,
- secondaryGroupSize: 0,
- groupSeparator: ",",
- decimalSeparator: ".",
- fractionGroupSize: 0,
- fractionGroupSeparator: "\xA0",
- suffix: ""
- }, ALPHABET2 = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true;
- function BigNumber2(v6, b4) {
- var alphabet, c8, caseChanged, e4, i5, isNum, len, str, x3 = this;
- if (!(x3 instanceof BigNumber2))
- return new BigNumber2(v6, b4);
- if (b4 == null) {
- if (v6 && v6._isBigNumber === true) {
- x3.s = v6.s;
- if (!v6.c || v6.e > MAX_EXP) {
- x3.c = x3.e = null;
- } else if (v6.e < MIN_EXP) {
- x3.c = [x3.e = 0];
- } else {
- x3.e = v6.e;
- x3.c = v6.c.slice();
- }
- return;
- }
- if ((isNum = typeof v6 == "number") && v6 * 0 == 0) {
- x3.s = 1 / v6 < 0 ? (v6 = -v6, -1) : 1;
- if (v6 === ~~v6) {
- for (e4 = 0, i5 = v6;i5 >= 10; i5 /= 10, e4++)
- ;
- if (e4 > MAX_EXP) {
- x3.c = x3.e = null;
- } else {
- x3.e = e4;
- x3.c = [v6];
- }
- return;
- }
- str = String(v6);
- } else {
- if (!isNumeric.test(str = String(v6)))
- return parseNumeric(x3, str, isNum);
- x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;
- }
- if ((e4 = str.indexOf(".")) > -1)
- str = str.replace(".", "");
- if ((i5 = str.search(/e/i)) > 0) {
- if (e4 < 0)
- e4 = i5;
- e4 += +str.slice(i5 + 1);
- str = str.substring(0, i5);
- } else if (e4 < 0) {
- e4 = str.length;
- }
- } else {
- intCheck(b4, 2, ALPHABET2.length, "Base");
- if (b4 == 10 && alphabetHasNormalDecimalDigits) {
- x3 = new BigNumber2(v6);
- return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE);
- }
- str = String(v6);
- if (isNum = typeof v6 == "number") {
- if (v6 * 0 != 0)
- return parseNumeric(x3, str, isNum, b4);
- x3.s = 1 / v6 < 0 ? (str = str.slice(1), -1) : 1;
- if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) {
- throw Error(tooManyDigits + v6);
- }
- } else {
- x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;
- }
- alphabet = ALPHABET2.slice(0, b4);
- e4 = i5 = 0;
- for (len = str.length;i5 < len; i5++) {
- if (alphabet.indexOf(c8 = str.charAt(i5)) < 0) {
- if (c8 == ".") {
- if (i5 > e4) {
- e4 = len;
- continue;
- }
- } else if (!caseChanged) {
- if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) {
- caseChanged = true;
- i5 = -1;
- e4 = 0;
- continue;
- }
- }
- return parseNumeric(x3, String(v6), isNum, b4);
- }
- }
- isNum = false;
- str = convertBase(str, b4, 10, x3.s);
- if ((e4 = str.indexOf(".")) > -1)
- str = str.replace(".", "");
- else
- e4 = str.length;
- }
- for (i5 = 0;str.charCodeAt(i5) === 48; i5++)
- ;
- for (len = str.length;str.charCodeAt(--len) === 48; )
- ;
- if (str = str.slice(i5, ++len)) {
- len -= i5;
- if (isNum && BigNumber2.DEBUG && len > 15 && (v6 > MAX_SAFE_INTEGER3 || v6 !== mathfloor(v6))) {
- throw Error(tooManyDigits + x3.s * v6);
- }
- if ((e4 = e4 - i5 - 1) > MAX_EXP) {
- x3.c = x3.e = null;
- } else if (e4 < MIN_EXP) {
- x3.c = [x3.e = 0];
- } else {
- x3.e = e4;
- x3.c = [];
- i5 = (e4 + 1) % LOG_BASE;
- if (e4 < 0)
- i5 += LOG_BASE;
- if (i5 < len) {
- if (i5)
- x3.c.push(+str.slice(0, i5));
- for (len -= LOG_BASE;i5 < len; ) {
- x3.c.push(+str.slice(i5, i5 += LOG_BASE));
- }
- i5 = LOG_BASE - (str = str.slice(i5)).length;
- } else {
- i5 -= len;
- }
- for (;i5--; str += "0")
- ;
- x3.c.push(+str);
- }
- } else {
- x3.c = [x3.e = 0];
- }
- }
- BigNumber2.clone = clone3;
- BigNumber2.ROUND_UP = 0;
- BigNumber2.ROUND_DOWN = 1;
- BigNumber2.ROUND_CEIL = 2;
- BigNumber2.ROUND_FLOOR = 3;
- BigNumber2.ROUND_HALF_UP = 4;
- BigNumber2.ROUND_HALF_DOWN = 5;
- BigNumber2.ROUND_HALF_EVEN = 6;
- BigNumber2.ROUND_HALF_CEIL = 7;
- BigNumber2.ROUND_HALF_FLOOR = 8;
- BigNumber2.EUCLID = 9;
- BigNumber2.config = BigNumber2.set = function(obj) {
- var p4, v6;
- if (obj != null) {
- if (typeof obj == "object") {
- if (obj.hasOwnProperty(p4 = "DECIMAL_PLACES")) {
- v6 = obj[p4];
- intCheck(v6, 0, MAX, p4);
- DECIMAL_PLACES = v6;
- }
- if (obj.hasOwnProperty(p4 = "ROUNDING_MODE")) {
- v6 = obj[p4];
- intCheck(v6, 0, 8, p4);
- ROUNDING_MODE = v6;
- }
- if (obj.hasOwnProperty(p4 = "EXPONENTIAL_AT")) {
- v6 = obj[p4];
- if (v6 && v6.pop) {
- intCheck(v6[0], -MAX, 0, p4);
- intCheck(v6[1], 0, MAX, p4);
- TO_EXP_NEG = v6[0];
- TO_EXP_POS = v6[1];
- } else {
- intCheck(v6, -MAX, MAX, p4);
- TO_EXP_NEG = -(TO_EXP_POS = v6 < 0 ? -v6 : v6);
- }
- }
- if (obj.hasOwnProperty(p4 = "RANGE")) {
- v6 = obj[p4];
- if (v6 && v6.pop) {
- intCheck(v6[0], -MAX, -1, p4);
- intCheck(v6[1], 1, MAX, p4);
- MIN_EXP = v6[0];
- MAX_EXP = v6[1];
- } else {
- intCheck(v6, -MAX, MAX, p4);
- if (v6) {
- MIN_EXP = -(MAX_EXP = v6 < 0 ? -v6 : v6);
- } else {
- throw Error(bignumberError + p4 + " cannot be zero: " + v6);
- }
- }
- }
- if (obj.hasOwnProperty(p4 = "CRYPTO")) {
- v6 = obj[p4];
- if (v6 === !!v6) {
- if (v6) {
- if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
- CRYPTO = v6;
- } else {
- CRYPTO = !v6;
- throw Error(bignumberError + "crypto unavailable");
- }
- } else {
- CRYPTO = v6;
- }
- } else {
- throw Error(bignumberError + p4 + " not true or false: " + v6);
- }
- }
- if (obj.hasOwnProperty(p4 = "MODULO_MODE")) {
- v6 = obj[p4];
- intCheck(v6, 0, 9, p4);
- MODULO_MODE = v6;
- }
- if (obj.hasOwnProperty(p4 = "POW_PRECISION")) {
- v6 = obj[p4];
- intCheck(v6, 0, MAX, p4);
- POW_PRECISION = v6;
- }
- if (obj.hasOwnProperty(p4 = "FORMAT")) {
- v6 = obj[p4];
- if (typeof v6 == "object")
- FORMAT = v6;
- else
- throw Error(bignumberError + p4 + " not an object: " + v6);
- }
- if (obj.hasOwnProperty(p4 = "ALPHABET")) {
- v6 = obj[p4];
- if (typeof v6 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v6)) {
- alphabetHasNormalDecimalDigits = v6.slice(0, 10) == "0123456789";
- ALPHABET2 = v6;
- } else {
- throw Error(bignumberError + p4 + " invalid: " + v6);
- }
- }
- } else {
- throw Error(bignumberError + "Object expected: " + obj);
- }
- }
- return {
- DECIMAL_PLACES,
- ROUNDING_MODE,
- EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],
- RANGE: [MIN_EXP, MAX_EXP],
- CRYPTO,
- MODULO_MODE,
- POW_PRECISION,
- FORMAT,
- ALPHABET: ALPHABET2
- };
- };
- BigNumber2.isBigNumber = function(v6) {
- if (!v6 || v6._isBigNumber !== true)
- return false;
- if (!BigNumber2.DEBUG)
- return true;
- var i5, n5, c8 = v6.c, e4 = v6.e, s4 = v6.s;
- out:
- if ({}.toString.call(c8) == "[object Array]") {
- if ((s4 === 1 || s4 === -1) && e4 >= -MAX && e4 <= MAX && e4 === mathfloor(e4)) {
- if (c8[0] === 0) {
- if (e4 === 0 && c8.length === 1)
- return true;
- break out;
- }
- i5 = (e4 + 1) % LOG_BASE;
- if (i5 < 1)
- i5 += LOG_BASE;
- if (String(c8[0]).length == i5) {
- for (i5 = 0;i5 < c8.length; i5++) {
- n5 = c8[i5];
- if (n5 < 0 || n5 >= BASE || n5 !== mathfloor(n5))
- break out;
- }
- if (n5 !== 0)
- return true;
- }
- }
- } else if (c8 === null && e4 === null && (s4 === null || s4 === 1 || s4 === -1)) {
- return true;
- }
- throw Error(bignumberError + "Invalid BigNumber: " + v6);
- };
- BigNumber2.maximum = BigNumber2.max = function() {
- return maxOrMin(arguments, -1);
- };
- BigNumber2.minimum = BigNumber2.min = function() {
- return maxOrMin(arguments, 1);
- };
- BigNumber2.random = function() {
- var pow2_53 = 9007199254740992;
- var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() {
- return mathfloor(Math.random() * pow2_53);
- } : function() {
- return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0);
- };
- return function(dp) {
- var a5, b4, e4, k4, v6, i5 = 0, c8 = [], rand = new BigNumber2(ONE);
- if (dp == null)
- dp = DECIMAL_PLACES;
- else
- intCheck(dp, 0, MAX);
- k4 = mathceil(dp / LOG_BASE);
- if (CRYPTO) {
- if (crypto.getRandomValues) {
- a5 = crypto.getRandomValues(new Uint32Array(k4 *= 2));
- for (;i5 < k4; ) {
- v6 = a5[i5] * 131072 + (a5[i5 + 1] >>> 11);
- if (v6 >= 9000000000000000) {
- b4 = crypto.getRandomValues(new Uint32Array(2));
- a5[i5] = b4[0];
- a5[i5 + 1] = b4[1];
- } else {
- c8.push(v6 % 100000000000000);
- i5 += 2;
- }
- }
- i5 = k4 / 2;
- } else if (crypto.randomBytes) {
- a5 = crypto.randomBytes(k4 *= 7);
- for (;i5 < k4; ) {
- v6 = (a5[i5] & 31) * 281474976710656 + a5[i5 + 1] * 1099511627776 + a5[i5 + 2] * 4294967296 + a5[i5 + 3] * 16777216 + (a5[i5 + 4] << 16) + (a5[i5 + 5] << 8) + a5[i5 + 6];
- if (v6 >= 9000000000000000) {
- crypto.randomBytes(7).copy(a5, i5);
- } else {
- c8.push(v6 % 100000000000000);
- i5 += 7;
- }
- }
- i5 = k4 / 7;
- } else {
- CRYPTO = false;
- throw Error(bignumberError + "crypto unavailable");
- }
- }
- if (!CRYPTO) {
- for (;i5 < k4; ) {
- v6 = random53bitInt();
- if (v6 < 9000000000000000)
- c8[i5++] = v6 % 100000000000000;
- }
- }
- k4 = c8[--i5];
- dp %= LOG_BASE;
- if (k4 && dp) {
- v6 = POWS_TEN[LOG_BASE - dp];
- c8[i5] = mathfloor(k4 / v6) * v6;
- }
- for (;c8[i5] === 0; c8.pop(), i5--)
- ;
- if (i5 < 0) {
- c8 = [e4 = 0];
- } else {
- for (e4 = -1;c8[0] === 0; c8.splice(0, 1), e4 -= LOG_BASE)
- ;
- for (i5 = 1, v6 = c8[0];v6 >= 10; v6 /= 10, i5++)
- ;
- if (i5 < LOG_BASE)
- e4 -= LOG_BASE - i5;
- }
- rand.e = e4;
- rand.c = c8;
- return rand;
- };
- }();
- BigNumber2.sum = function() {
- var i5 = 1, args = arguments, sum = new BigNumber2(args[0]);
- for (;i5 < args.length; )
- sum = sum.plus(args[i5++]);
- return sum;
- };
- convertBase = function() {
- var decimal = "0123456789";
- function toBaseOut(str, baseIn, baseOut, alphabet) {
- var j4, arr = [0], arrL, i5 = 0, len = str.length;
- for (;i5 < len; ) {
- for (arrL = arr.length;arrL--; arr[arrL] *= baseIn)
- ;
- arr[0] += alphabet.indexOf(str.charAt(i5++));
- for (j4 = 0;j4 < arr.length; j4++) {
- if (arr[j4] > baseOut - 1) {
- if (arr[j4 + 1] == null)
- arr[j4 + 1] = 0;
- arr[j4 + 1] += arr[j4] / baseOut | 0;
- arr[j4] %= baseOut;
- }
- }
- }
- return arr.reverse();
- }
- return function(str, baseIn, baseOut, sign2, callerIsToString) {
- var alphabet, d4, e4, k4, r4, x3, xc, y3, i5 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE;
- if (i5 >= 0) {
- k4 = POW_PRECISION;
- POW_PRECISION = 0;
- str = str.replace(".", "");
- y3 = new BigNumber2(baseIn);
- x3 = y3.pow(str.length - i5);
- POW_PRECISION = k4;
- y3.c = toBaseOut(toFixedPoint(coeffToString(x3.c), x3.e, "0"), 10, baseOut, decimal);
- y3.e = y3.c.length;
- }
- xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET2, decimal) : (alphabet = decimal, ALPHABET2));
- e4 = k4 = xc.length;
- for (;xc[--k4] == 0; xc.pop())
- ;
- if (!xc[0])
- return alphabet.charAt(0);
- if (i5 < 0) {
- --e4;
- } else {
- x3.c = xc;
- x3.e = e4;
- x3.s = sign2;
- x3 = div(x3, y3, dp, rm, baseOut);
- xc = x3.c;
- r4 = x3.r;
- e4 = x3.e;
- }
- d4 = e4 + dp + 1;
- i5 = xc[d4];
- k4 = baseOut / 2;
- r4 = r4 || d4 < 0 || xc[d4 + 1] != null;
- r4 = rm < 4 ? (i5 != null || r4) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i5 > k4 || i5 == k4 && (rm == 4 || r4 || rm == 6 && xc[d4 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7));
- if (d4 < 1 || !xc[0]) {
- str = r4 ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);
- } else {
- xc.length = d4;
- if (r4) {
- for (--baseOut;++xc[--d4] > baseOut; ) {
- xc[d4] = 0;
- if (!d4) {
- ++e4;
- xc = [1].concat(xc);
- }
- }
- }
- for (k4 = xc.length;!xc[--k4]; )
- ;
- for (i5 = 0, str = "";i5 <= k4; str += alphabet.charAt(xc[i5++]))
- ;
- str = toFixedPoint(str, e4, alphabet.charAt(0));
- }
- return str;
- };
- }();
- div = function() {
- function multiply(x3, k4, base2) {
- var m4, temp, xlo, xhi, carry = 0, i5 = x3.length, klo = k4 % SQRT_BASE, khi = k4 / SQRT_BASE | 0;
- for (x3 = x3.slice();i5--; ) {
- xlo = x3[i5] % SQRT_BASE;
- xhi = x3[i5] / SQRT_BASE | 0;
- m4 = khi * xlo + xhi * klo;
- temp = klo * xlo + m4 % SQRT_BASE * SQRT_BASE + carry;
- carry = (temp / base2 | 0) + (m4 / SQRT_BASE | 0) + khi * xhi;
- x3[i5] = temp % base2;
- }
- if (carry)
- x3 = [carry].concat(x3);
- return x3;
- }
- function compare2(a5, b4, aL, bL) {
- var i5, cmp;
- if (aL != bL) {
- cmp = aL > bL ? 1 : -1;
- } else {
- for (i5 = cmp = 0;i5 < aL; i5++) {
- if (a5[i5] != b4[i5]) {
- cmp = a5[i5] > b4[i5] ? 1 : -1;
- break;
- }
- }
- }
- return cmp;
- }
- function subtract(a5, b4, aL, base2) {
- var i5 = 0;
- for (;aL--; ) {
- a5[aL] -= i5;
- i5 = a5[aL] < b4[aL] ? 1 : 0;
- a5[aL] = i5 * base2 + a5[aL] - b4[aL];
- }
- for (;!a5[0] && a5.length > 1; a5.splice(0, 1))
- ;
- }
- return function(x3, y3, dp, rm, base2) {
- var cmp, e4, i5, more, n5, prod, prodL, q4, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s4 = x3.s == y3.s ? 1 : -1, xc = x3.c, yc = y3.c;
- if (!xc || !xc[0] || !yc || !yc[0]) {
- return new BigNumber2(!x3.s || !y3.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : xc && xc[0] == 0 || !yc ? s4 * 0 : s4 / 0);
- }
- q4 = new BigNumber2(s4);
- qc = q4.c = [];
- e4 = x3.e - y3.e;
- s4 = dp + e4 + 1;
- if (!base2) {
- base2 = BASE;
- e4 = bitFloor(x3.e / LOG_BASE) - bitFloor(y3.e / LOG_BASE);
- s4 = s4 / LOG_BASE | 0;
- }
- for (i5 = 0;yc[i5] == (xc[i5] || 0); i5++)
- ;
- if (yc[i5] > (xc[i5] || 0))
- e4--;
- if (s4 < 0) {
- qc.push(1);
- more = true;
- } else {
- xL = xc.length;
- yL = yc.length;
- i5 = 0;
- s4 += 2;
- n5 = mathfloor(base2 / (yc[0] + 1));
- if (n5 > 1) {
- yc = multiply(yc, n5, base2);
- xc = multiply(xc, n5, base2);
- yL = yc.length;
- xL = xc.length;
- }
- xi = yL;
- rem = xc.slice(0, yL);
- remL = rem.length;
- for (;remL < yL; rem[remL++] = 0)
- ;
- yz = yc.slice();
- yz = [0].concat(yz);
- yc0 = yc[0];
- if (yc[1] >= base2 / 2)
- yc0++;
- do {
- n5 = 0;
- cmp = compare2(yc, rem, yL, remL);
- if (cmp < 0) {
- rem0 = rem[0];
- if (yL != remL)
- rem0 = rem0 * base2 + (rem[1] || 0);
- n5 = mathfloor(rem0 / yc0);
- if (n5 > 1) {
- if (n5 >= base2)
- n5 = base2 - 1;
- prod = multiply(yc, n5, base2);
- prodL = prod.length;
- remL = rem.length;
- while (compare2(prod, rem, prodL, remL) == 1) {
- n5--;
- subtract(prod, yL < prodL ? yz : yc, prodL, base2);
- prodL = prod.length;
- cmp = 1;
- }
- } else {
- if (n5 == 0) {
- cmp = n5 = 1;
- }
- prod = yc.slice();
- prodL = prod.length;
- }
- if (prodL < remL)
- prod = [0].concat(prod);
- subtract(rem, prod, remL, base2);
- remL = rem.length;
- if (cmp == -1) {
- while (compare2(yc, rem, yL, remL) < 1) {
- n5++;
- subtract(rem, yL < remL ? yz : yc, remL, base2);
- remL = rem.length;
- }
- }
- } else if (cmp === 0) {
- n5++;
- rem = [0];
- }
- qc[i5++] = n5;
- if (rem[0]) {
- rem[remL++] = xc[xi] || 0;
- } else {
- rem = [xc[xi]];
- remL = 1;
- }
- } while ((xi++ < xL || rem[0] != null) && s4--);
- more = rem[0] != null;
- if (!qc[0])
- qc.splice(0, 1);
- }
- if (base2 == BASE) {
- for (i5 = 1, s4 = qc[0];s4 >= 10; s4 /= 10, i5++)
- ;
- round(q4, dp + (q4.e = i5 + e4 * LOG_BASE - 1) + 1, rm, more);
- } else {
- q4.e = e4;
- q4.r = +more;
- }
- return q4;
- };
- }();
- function format3(n5, i5, rm, id) {
- var c0, e4, ne, len, str;
- if (rm == null)
- rm = ROUNDING_MODE;
- else
- intCheck(rm, 0, 8);
- if (!n5.c)
- return n5.toString();
- c0 = n5.c[0];
- ne = n5.e;
- if (i5 == null) {
- str = coeffToString(n5.c);
- str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, "0");
- } else {
- n5 = round(new BigNumber2(n5), i5, rm);
- e4 = n5.e;
- str = coeffToString(n5.c);
- len = str.length;
- if (id == 1 || id == 2 && (i5 <= e4 || e4 <= TO_EXP_NEG)) {
- for (;len < i5; str += "0", len++)
- ;
- str = toExponential(str, e4);
- } else {
- i5 -= ne + (id === 2 && e4 > ne);
- str = toFixedPoint(str, e4, "0");
- if (e4 + 1 > len) {
- if (--i5 > 0)
- for (str += ".";i5--; str += "0")
- ;
- } else {
- i5 += e4 - len;
- if (i5 > 0) {
- if (e4 + 1 == len)
- str += ".";
- for (;i5--; str += "0")
- ;
- }
- }
- }
- }
- return n5.s < 0 && c0 ? "-" + str : str;
- }
- function maxOrMin(args, n5) {
- var k4, y3, i5 = 1, x3 = new BigNumber2(args[0]);
- for (;i5 < args.length; i5++) {
- y3 = new BigNumber2(args[i5]);
- if (!y3.s || (k4 = compare(x3, y3)) === n5 || k4 === 0 && x3.s === n5) {
- x3 = y3;
- }
- }
- return x3;
- }
- function normalise(n5, c8, e4) {
- var i5 = 1, j4 = c8.length;
- for (;!c8[--j4]; c8.pop())
- ;
- for (j4 = c8[0];j4 >= 10; j4 /= 10, i5++)
- ;
- if ((e4 = i5 + e4 * LOG_BASE - 1) > MAX_EXP) {
- n5.c = n5.e = null;
- } else if (e4 < MIN_EXP) {
- n5.c = [n5.e = 0];
- } else {
- n5.e = e4;
- n5.c = c8;
- }
- return n5;
- }
- parseNumeric = function() {
- var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
- return function(x3, str, isNum, b4) {
- var base2, s4 = isNum ? str : str.replace(whitespaceOrPlus, "");
- if (isInfinityOrNaN.test(s4)) {
- x3.s = isNaN(s4) ? null : s4 < 0 ? -1 : 1;
- } else {
- if (!isNum) {
- s4 = s4.replace(basePrefix, function(m4, p1, p22) {
- base2 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8;
- return !b4 || b4 == base2 ? p1 : m4;
- });
- if (b4) {
- base2 = b4;
- s4 = s4.replace(dotAfter, "$1").replace(dotBefore, "0.$1");
- }
- if (str != s4)
- return new BigNumber2(s4, base2);
- }
- if (BigNumber2.DEBUG) {
- throw Error(bignumberError + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str);
- }
- x3.s = null;
- }
- x3.c = x3.e = null;
- };
- }();
- function round(x3, sd, rm, r4) {
- var d4, i5, j4, k4, n5, ni, rd, xc = x3.c, pows10 = POWS_TEN;
- if (xc) {
- out: {
- for (d4 = 1, k4 = xc[0];k4 >= 10; k4 /= 10, d4++)
- ;
- i5 = sd - d4;
- if (i5 < 0) {
- i5 += LOG_BASE;
- j4 = sd;
- n5 = xc[ni = 0];
- rd = mathfloor(n5 / pows10[d4 - j4 - 1] % 10);
- } else {
- ni = mathceil((i5 + 1) / LOG_BASE);
- if (ni >= xc.length) {
- if (r4) {
- for (;xc.length <= ni; xc.push(0))
- ;
- n5 = rd = 0;
- d4 = 1;
- i5 %= LOG_BASE;
- j4 = i5 - LOG_BASE + 1;
- } else {
- break out;
- }
- } else {
- n5 = k4 = xc[ni];
- for (d4 = 1;k4 >= 10; k4 /= 10, d4++)
- ;
- i5 %= LOG_BASE;
- j4 = i5 - LOG_BASE + d4;
- rd = j4 < 0 ? 0 : mathfloor(n5 / pows10[d4 - j4 - 1] % 10);
- }
- }
- r4 = r4 || sd < 0 || xc[ni + 1] != null || (j4 < 0 ? n5 : n5 % pows10[d4 - j4 - 1]);
- r4 = rm < 4 ? (rd || r4) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r4 || rm == 6 && (i5 > 0 ? j4 > 0 ? n5 / pows10[d4 - j4] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7));
- if (sd < 1 || !xc[0]) {
- xc.length = 0;
- if (r4) {
- sd -= x3.e + 1;
- xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];
- x3.e = -sd || 0;
- } else {
- xc[0] = x3.e = 0;
- }
- return x3;
- }
- if (i5 == 0) {
- xc.length = ni;
- k4 = 1;
- ni--;
- } else {
- xc.length = ni + 1;
- k4 = pows10[LOG_BASE - i5];
- xc[ni] = j4 > 0 ? mathfloor(n5 / pows10[d4 - j4] % pows10[j4]) * k4 : 0;
- }
- if (r4) {
- for (;; ) {
- if (ni == 0) {
- for (i5 = 1, j4 = xc[0];j4 >= 10; j4 /= 10, i5++)
- ;
- j4 = xc[0] += k4;
- for (k4 = 1;j4 >= 10; j4 /= 10, k4++)
- ;
- if (i5 != k4) {
- x3.e++;
- if (xc[0] == BASE)
- xc[0] = 1;
- }
- break;
- } else {
- xc[ni] += k4;
- if (xc[ni] != BASE)
- break;
- xc[ni--] = 0;
- k4 = 1;
- }
- }
- }
- for (i5 = xc.length;xc[--i5] === 0; xc.pop())
- ;
- }
- if (x3.e > MAX_EXP) {
- x3.c = x3.e = null;
- } else if (x3.e < MIN_EXP) {
- x3.c = [x3.e = 0];
- }
- }
- return x3;
- }
- function valueOf(n5) {
- var str, e4 = n5.e;
- if (e4 === null)
- return n5.toString();
- str = coeffToString(n5.c);
- str = e4 <= TO_EXP_NEG || e4 >= TO_EXP_POS ? toExponential(str, e4) : toFixedPoint(str, e4, "0");
- return n5.s < 0 ? "-" + str : str;
- }
- P.absoluteValue = P.abs = function() {
- var x3 = new BigNumber2(this);
- if (x3.s < 0)
- x3.s = 1;
- return x3;
- };
- P.comparedTo = function(y3, b4) {
- return compare(this, new BigNumber2(y3, b4));
- };
- P.decimalPlaces = P.dp = function(dp, rm) {
- var c8, n5, v6, x3 = this;
- if (dp != null) {
- intCheck(dp, 0, MAX);
- if (rm == null)
- rm = ROUNDING_MODE;
- else
- intCheck(rm, 0, 8);
- return round(new BigNumber2(x3), dp + x3.e + 1, rm);
- }
- if (!(c8 = x3.c))
- return null;
- n5 = ((v6 = c8.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;
- if (v6 = c8[v6])
- for (;v6 % 10 == 0; v6 /= 10, n5--)
- ;
- if (n5 < 0)
- n5 = 0;
- return n5;
- };
- P.dividedBy = P.div = function(y3, b4) {
- return div(this, new BigNumber2(y3, b4), DECIMAL_PLACES, ROUNDING_MODE);
- };
- P.dividedToIntegerBy = P.idiv = function(y3, b4) {
- return div(this, new BigNumber2(y3, b4), 0, 1);
- };
- P.exponentiatedBy = P.pow = function(n5, m4) {
- var half, isModExp, i5, k4, more, nIsBig, nIsNeg, nIsOdd, y3, x3 = this;
- n5 = new BigNumber2(n5);
- if (n5.c && !n5.isInteger()) {
- throw Error(bignumberError + "Exponent not an integer: " + valueOf(n5));
- }
- if (m4 != null)
- m4 = new BigNumber2(m4);
- nIsBig = n5.e > 14;
- if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n5.c || !n5.c[0]) {
- y3 = new BigNumber2(Math.pow(+valueOf(x3), nIsBig ? n5.s * (2 - isOdd(n5)) : +valueOf(n5)));
- return m4 ? y3.mod(m4) : y3;
- }
- nIsNeg = n5.s < 0;
- if (m4) {
- if (m4.c ? !m4.c[0] : !m4.s)
- return new BigNumber2(NaN);
- isModExp = !nIsNeg && x3.isInteger() && m4.isInteger();
- if (isModExp)
- x3 = x3.mod(m4);
- } else if (n5.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 240000000 : x3.c[0] < 80000000000000 || nIsBig && x3.c[0] <= 99999750000000))) {
- k4 = x3.s < 0 && isOdd(n5) ? -0 : 0;
- if (x3.e > -1)
- k4 = 1 / k4;
- return new BigNumber2(nIsNeg ? 1 / k4 : k4);
- } else if (POW_PRECISION) {
- k4 = mathceil(POW_PRECISION / LOG_BASE + 2);
- }
- if (nIsBig) {
- half = new BigNumber2(0.5);
- if (nIsNeg)
- n5.s = 1;
- nIsOdd = isOdd(n5);
- } else {
- i5 = Math.abs(+valueOf(n5));
- nIsOdd = i5 % 2;
- }
- y3 = new BigNumber2(ONE);
- for (;; ) {
- if (nIsOdd) {
- y3 = y3.times(x3);
- if (!y3.c)
- break;
- if (k4) {
- if (y3.c.length > k4)
- y3.c.length = k4;
- } else if (isModExp) {
- y3 = y3.mod(m4);
- }
- }
- if (i5) {
- i5 = mathfloor(i5 / 2);
- if (i5 === 0)
- break;
- nIsOdd = i5 % 2;
- } else {
- n5 = n5.times(half);
- round(n5, n5.e + 1, 1);
- if (n5.e > 14) {
- nIsOdd = isOdd(n5);
- } else {
- i5 = +valueOf(n5);
- if (i5 === 0)
- break;
- nIsOdd = i5 % 2;
- }
- }
- x3 = x3.times(x3);
- if (k4) {
- if (x3.c && x3.c.length > k4)
- x3.c.length = k4;
- } else if (isModExp) {
- x3 = x3.mod(m4);
- }
- }
- if (isModExp)
- return y3;
- if (nIsNeg)
- y3 = ONE.div(y3);
- return m4 ? y3.mod(m4) : k4 ? round(y3, POW_PRECISION, ROUNDING_MODE, more) : y3;
- };
- P.integerValue = function(rm) {
- var n5 = new BigNumber2(this);
- if (rm == null)
- rm = ROUNDING_MODE;
- else
- intCheck(rm, 0, 8);
- return round(n5, n5.e + 1, rm);
- };
- P.isEqualTo = P.eq = function(y3, b4) {
- return compare(this, new BigNumber2(y3, b4)) === 0;
- };
- P.isFinite = function() {
- return !!this.c;
- };
- P.isGreaterThan = P.gt = function(y3, b4) {
- return compare(this, new BigNumber2(y3, b4)) > 0;
- };
- P.isGreaterThanOrEqualTo = P.gte = function(y3, b4) {
- return (b4 = compare(this, new BigNumber2(y3, b4))) === 1 || b4 === 0;
- };
- P.isInteger = function() {
- return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;
- };
- P.isLessThan = P.lt = function(y3, b4) {
- return compare(this, new BigNumber2(y3, b4)) < 0;
- };
- P.isLessThanOrEqualTo = P.lte = function(y3, b4) {
- return (b4 = compare(this, new BigNumber2(y3, b4))) === -1 || b4 === 0;
- };
- P.isNaN = function() {
- return !this.s;
- };
- P.isNegative = function() {
- return this.s < 0;
- };
- P.isPositive = function() {
- return this.s > 0;
- };
- P.isZero = function() {
- return !!this.c && this.c[0] == 0;
- };
- P.minus = function(y3, b4) {
- var i5, j4, t4, xLTy, x3 = this, a5 = x3.s;
- y3 = new BigNumber2(y3, b4);
- b4 = y3.s;
- if (!a5 || !b4)
- return new BigNumber2(NaN);
- if (a5 != b4) {
- y3.s = -b4;
- return x3.plus(y3);
- }
- var xe = x3.e / LOG_BASE, ye = y3.e / LOG_BASE, xc = x3.c, yc = y3.c;
- if (!xe || !ye) {
- if (!xc || !yc)
- return xc ? (y3.s = -b4, y3) : new BigNumber2(yc ? x3 : NaN);
- if (!xc[0] || !yc[0]) {
- return yc[0] ? (y3.s = -b4, y3) : new BigNumber2(xc[0] ? x3 : ROUNDING_MODE == 3 ? -0 : 0);
- }
- }
- xe = bitFloor(xe);
- ye = bitFloor(ye);
- xc = xc.slice();
- if (a5 = xe - ye) {
- if (xLTy = a5 < 0) {
- a5 = -a5;
- t4 = xc;
- } else {
- ye = xe;
- t4 = yc;
- }
- t4.reverse();
- for (b4 = a5;b4--; t4.push(0))
- ;
- t4.reverse();
- } else {
- j4 = (xLTy = (a5 = xc.length) < (b4 = yc.length)) ? a5 : b4;
- for (a5 = b4 = 0;b4 < j4; b4++) {
- if (xc[b4] != yc[b4]) {
- xLTy = xc[b4] < yc[b4];
- break;
- }
- }
- }
- if (xLTy) {
- t4 = xc;
- xc = yc;
- yc = t4;
- y3.s = -y3.s;
- }
- b4 = (j4 = yc.length) - (i5 = xc.length);
- if (b4 > 0)
- for (;b4--; xc[i5++] = 0)
- ;
- b4 = BASE - 1;
- for (;j4 > a5; ) {
- if (xc[--j4] < yc[j4]) {
- for (i5 = j4;i5 && !xc[--i5]; xc[i5] = b4)
- ;
- --xc[i5];
- xc[j4] += BASE;
- }
- xc[j4] -= yc[j4];
- }
- for (;xc[0] == 0; xc.splice(0, 1), --ye)
- ;
- if (!xc[0]) {
- y3.s = ROUNDING_MODE == 3 ? -1 : 1;
- y3.c = [y3.e = 0];
- return y3;
- }
- return normalise(y3, xc, ye);
- };
- P.modulo = P.mod = function(y3, b4) {
- var q4, s4, x3 = this;
- y3 = new BigNumber2(y3, b4);
- if (!x3.c || !y3.s || y3.c && !y3.c[0]) {
- return new BigNumber2(NaN);
- } else if (!y3.c || x3.c && !x3.c[0]) {
- return new BigNumber2(x3);
- }
- if (MODULO_MODE == 9) {
- s4 = y3.s;
- y3.s = 1;
- q4 = div(x3, y3, 0, 3);
- y3.s = s4;
- q4.s *= s4;
- } else {
- q4 = div(x3, y3, 0, MODULO_MODE);
- }
- y3 = x3.minus(q4.times(y3));
- if (!y3.c[0] && MODULO_MODE == 1)
- y3.s = x3.s;
- return y3;
- };
- P.multipliedBy = P.times = function(y3, b4) {
- var c8, e4, i5, j4, k4, m4, xcL, xlo, xhi, ycL, ylo, yhi, zc, base2, sqrtBase, x3 = this, xc = x3.c, yc = (y3 = new BigNumber2(y3, b4)).c;
- if (!xc || !yc || !xc[0] || !yc[0]) {
- if (!x3.s || !y3.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {
- y3.c = y3.e = y3.s = null;
- } else {
- y3.s *= x3.s;
- if (!xc || !yc) {
- y3.c = y3.e = null;
- } else {
- y3.c = [0];
- y3.e = 0;
- }
- }
- return y3;
- }
- e4 = bitFloor(x3.e / LOG_BASE) + bitFloor(y3.e / LOG_BASE);
- y3.s *= x3.s;
- xcL = xc.length;
- ycL = yc.length;
- if (xcL < ycL) {
- zc = xc;
- xc = yc;
- yc = zc;
- i5 = xcL;
- xcL = ycL;
- ycL = i5;
- }
- for (i5 = xcL + ycL, zc = [];i5--; zc.push(0))
- ;
- base2 = BASE;
- sqrtBase = SQRT_BASE;
- for (i5 = ycL;--i5 >= 0; ) {
- c8 = 0;
- ylo = yc[i5] % sqrtBase;
- yhi = yc[i5] / sqrtBase | 0;
- for (k4 = xcL, j4 = i5 + k4;j4 > i5; ) {
- xlo = xc[--k4] % sqrtBase;
- xhi = xc[k4] / sqrtBase | 0;
- m4 = yhi * xlo + xhi * ylo;
- xlo = ylo * xlo + m4 % sqrtBase * sqrtBase + zc[j4] + c8;
- c8 = (xlo / base2 | 0) + (m4 / sqrtBase | 0) + yhi * xhi;
- zc[j4--] = xlo % base2;
- }
- zc[j4] = c8;
- }
- if (c8) {
- ++e4;
- } else {
- zc.splice(0, 1);
- }
- return normalise(y3, zc, e4);
- };
- P.negated = function() {
- var x3 = new BigNumber2(this);
- x3.s = -x3.s || null;
- return x3;
- };
- P.plus = function(y3, b4) {
- var t4, x3 = this, a5 = x3.s;
- y3 = new BigNumber2(y3, b4);
- b4 = y3.s;
- if (!a5 || !b4)
- return new BigNumber2(NaN);
- if (a5 != b4) {
- y3.s = -b4;
- return x3.minus(y3);
- }
- var xe = x3.e / LOG_BASE, ye = y3.e / LOG_BASE, xc = x3.c, yc = y3.c;
- if (!xe || !ye) {
- if (!xc || !yc)
- return new BigNumber2(a5 / 0);
- if (!xc[0] || !yc[0])
- return yc[0] ? y3 : new BigNumber2(xc[0] ? x3 : a5 * 0);
- }
- xe = bitFloor(xe);
- ye = bitFloor(ye);
- xc = xc.slice();
- if (a5 = xe - ye) {
- if (a5 > 0) {
- ye = xe;
- t4 = yc;
- } else {
- a5 = -a5;
- t4 = xc;
- }
- t4.reverse();
- for (;a5--; t4.push(0))
- ;
- t4.reverse();
- }
- a5 = xc.length;
- b4 = yc.length;
- if (a5 - b4 < 0) {
- t4 = yc;
- yc = xc;
- xc = t4;
- b4 = a5;
- }
- for (a5 = 0;b4; ) {
- a5 = (xc[--b4] = xc[b4] + yc[b4] + a5) / BASE | 0;
- xc[b4] = BASE === xc[b4] ? 0 : xc[b4] % BASE;
- }
- if (a5) {
- xc = [a5].concat(xc);
- ++ye;
- }
- return normalise(y3, xc, ye);
- };
- P.precision = P.sd = function(sd, rm) {
- var c8, n5, v6, x3 = this;
- if (sd != null && sd !== !!sd) {
- intCheck(sd, 1, MAX);
- if (rm == null)
- rm = ROUNDING_MODE;
- else
- intCheck(rm, 0, 8);
- return round(new BigNumber2(x3), sd, rm);
- }
- if (!(c8 = x3.c))
- return null;
- v6 = c8.length - 1;
- n5 = v6 * LOG_BASE + 1;
- if (v6 = c8[v6]) {
- for (;v6 % 10 == 0; v6 /= 10, n5--)
- ;
- for (v6 = c8[0];v6 >= 10; v6 /= 10, n5++)
- ;
- }
- if (sd && x3.e + 1 > n5)
- n5 = x3.e + 1;
- return n5;
- };
- P.shiftedBy = function(k4) {
- intCheck(k4, -MAX_SAFE_INTEGER3, MAX_SAFE_INTEGER3);
- return this.times("1e" + k4);
- };
- P.squareRoot = P.sqrt = function() {
- var m4, n5, r4, rep, t4, x3 = this, c8 = x3.c, s4 = x3.s, e4 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5");
- if (s4 !== 1 || !c8 || !c8[0]) {
- return new BigNumber2(!s4 || s4 < 0 && (!c8 || c8[0]) ? NaN : c8 ? x3 : 1 / 0);
- }
- s4 = Math.sqrt(+valueOf(x3));
- if (s4 == 0 || s4 == 1 / 0) {
- n5 = coeffToString(c8);
- if ((n5.length + e4) % 2 == 0)
- n5 += "0";
- s4 = Math.sqrt(+n5);
- e4 = bitFloor((e4 + 1) / 2) - (e4 < 0 || e4 % 2);
- if (s4 == 1 / 0) {
- n5 = "5e" + e4;
- } else {
- n5 = s4.toExponential();
- n5 = n5.slice(0, n5.indexOf("e") + 1) + e4;
- }
- r4 = new BigNumber2(n5);
- } else {
- r4 = new BigNumber2(s4 + "");
- }
- if (r4.c[0]) {
- e4 = r4.e;
- s4 = e4 + dp;
- if (s4 < 3)
- s4 = 0;
- for (;; ) {
- t4 = r4;
- r4 = half.times(t4.plus(div(x3, t4, dp, 1)));
- if (coeffToString(t4.c).slice(0, s4) === (n5 = coeffToString(r4.c)).slice(0, s4)) {
- if (r4.e < e4)
- --s4;
- n5 = n5.slice(s4 - 3, s4 + 1);
- if (n5 == "9999" || !rep && n5 == "4999") {
- if (!rep) {
- round(t4, t4.e + DECIMAL_PLACES + 2, 0);
- if (t4.times(t4).eq(x3)) {
- r4 = t4;
- break;
- }
- }
- dp += 4;
- s4 += 4;
- rep = 1;
- } else {
- if (!+n5 || !+n5.slice(1) && n5.charAt(0) == "5") {
- round(r4, r4.e + DECIMAL_PLACES + 2, 1);
- m4 = !r4.times(r4).eq(x3);
- }
- break;
- }
- }
- }
- }
- return round(r4, r4.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m4);
- };
- P.toExponential = function(dp, rm) {
- if (dp != null) {
- intCheck(dp, 0, MAX);
- dp++;
- }
- return format3(this, dp, rm, 1);
- };
- P.toFixed = function(dp, rm) {
- if (dp != null) {
- intCheck(dp, 0, MAX);
- dp = dp + this.e + 1;
- }
- return format3(this, dp, rm);
- };
- P.toFormat = function(dp, rm, format4) {
- var str, x3 = this;
- if (format4 == null) {
- if (dp != null && rm && typeof rm == "object") {
- format4 = rm;
- rm = null;
- } else if (dp && typeof dp == "object") {
- format4 = dp;
- dp = rm = null;
- } else {
- format4 = FORMAT;
- }
- } else if (typeof format4 != "object") {
- throw Error(bignumberError + "Argument not an object: " + format4);
- }
- str = x3.toFixed(dp, rm);
- if (x3.c) {
- var i5, arr = str.split("."), g1 = +format4.groupSize, g22 = +format4.secondaryGroupSize, groupSeparator = format4.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length;
- if (g22) {
- i5 = g1;
- g1 = g22;
- g22 = i5;
- len -= i5;
- }
- if (g1 > 0 && len > 0) {
- i5 = len % g1 || g1;
- intPart = intDigits.substr(0, i5);
- for (;i5 < len; i5 += g1)
- intPart += groupSeparator + intDigits.substr(i5, g1);
- if (g22 > 0)
- intPart += groupSeparator + intDigits.slice(i5);
- if (isNeg)
- intPart = "-" + intPart;
- }
- str = fractionPart ? intPart + (format4.decimalSeparator || "") + ((g22 = +format4.fractionGroupSize) ? fractionPart.replace(new RegExp("\\d{" + g22 + "}\\B", "g"), "$&" + (format4.fractionGroupSeparator || "")) : fractionPart) : intPart;
- }
- return (format4.prefix || "") + str + (format4.suffix || "");
- };
- P.toFraction = function(md) {
- var d4, d0, d1, d22, e4, exp, n5, n04, n1, q4, r4, s4, x3 = this, xc = x3.c;
- if (md != null) {
- n5 = new BigNumber2(md);
- if (!n5.isInteger() && (n5.c || n5.s !== 1) || n5.lt(ONE)) {
- throw Error(bignumberError + "Argument " + (n5.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n5));
- }
- }
- if (!xc)
- return new BigNumber2(x3);
- d4 = new BigNumber2(ONE);
- n1 = d0 = new BigNumber2(ONE);
- d1 = n04 = new BigNumber2(ONE);
- s4 = coeffToString(xc);
- e4 = d4.e = s4.length - x3.e - 1;
- d4.c[0] = POWS_TEN[(exp = e4 % LOG_BASE) < 0 ? LOG_BASE + exp : exp];
- md = !md || n5.comparedTo(d4) > 0 ? e4 > 0 ? d4 : n1 : n5;
- exp = MAX_EXP;
- MAX_EXP = 1 / 0;
- n5 = new BigNumber2(s4);
- n04.c[0] = 0;
- for (;; ) {
- q4 = div(n5, d4, 0, 1);
- d22 = d0.plus(q4.times(d1));
- if (d22.comparedTo(md) == 1)
- break;
- d0 = d1;
- d1 = d22;
- n1 = n04.plus(q4.times(d22 = n1));
- n04 = d22;
- d4 = n5.minus(q4.times(d22 = d4));
- n5 = d22;
- }
- d22 = div(md.minus(d0), d1, 0, 1);
- n04 = n04.plus(d22.times(n1));
- d0 = d0.plus(d22.times(d1));
- n04.s = n1.s = x3.s;
- e4 = e4 * 2;
- r4 = div(n1, d1, e4, ROUNDING_MODE).minus(x3).abs().comparedTo(div(n04, d0, e4, ROUNDING_MODE).minus(x3).abs()) < 1 ? [n1, d1] : [n04, d0];
- MAX_EXP = exp;
- return r4;
- };
- P.toNumber = function() {
- return +valueOf(this);
- };
- P.toPrecision = function(sd, rm) {
- if (sd != null)
- intCheck(sd, 1, MAX);
- return format3(this, sd, rm, 2);
- };
- P.toString = function(b4) {
- var str, n5 = this, s4 = n5.s, e4 = n5.e;
- if (e4 === null) {
- if (s4) {
- str = "Infinity";
- if (s4 < 0)
- str = "-" + str;
- } else {
- str = "NaN";
- }
- } else {
- if (b4 == null) {
- str = e4 <= TO_EXP_NEG || e4 >= TO_EXP_POS ? toExponential(coeffToString(n5.c), e4) : toFixedPoint(coeffToString(n5.c), e4, "0");
- } else if (b4 === 10 && alphabetHasNormalDecimalDigits) {
- n5 = round(new BigNumber2(n5), DECIMAL_PLACES + e4 + 1, ROUNDING_MODE);
- str = toFixedPoint(coeffToString(n5.c), n5.e, "0");
- } else {
- intCheck(b4, 2, ALPHABET2.length, "Base");
- str = convertBase(toFixedPoint(coeffToString(n5.c), e4, "0"), 10, b4, s4, true);
- }
- if (s4 < 0 && n5.c[0])
- str = "-" + str;
- }
- return str;
- };
- P.valueOf = P.toJSON = function() {
- return valueOf(this);
- };
- P._isBigNumber = true;
- if (configObject != null)
- BigNumber2.set(configObject);
- return BigNumber2;
- }
- function bitFloor(n5) {
- var i5 = n5 | 0;
- return n5 > 0 || n5 === i5 ? i5 : i5 - 1;
- }
- function coeffToString(a5) {
- var s4, z3, i5 = 1, j4 = a5.length, r4 = a5[0] + "";
- for (;i5 < j4; ) {
- s4 = a5[i5++] + "";
- z3 = LOG_BASE - s4.length;
- for (;z3--; s4 = "0" + s4)
- ;
- r4 += s4;
- }
- for (j4 = r4.length;r4.charCodeAt(--j4) === 48; )
- ;
- return r4.slice(0, j4 + 1 || 1);
- }
- function compare(x3, y3) {
- var a5, b4, xc = x3.c, yc = y3.c, i5 = x3.s, j4 = y3.s, k4 = x3.e, l4 = y3.e;
- if (!i5 || !j4)
- return null;
- a5 = xc && !xc[0];
- b4 = yc && !yc[0];
- if (a5 || b4)
- return a5 ? b4 ? 0 : -j4 : i5;
- if (i5 != j4)
- return i5;
- a5 = i5 < 0;
- b4 = k4 == l4;
- if (!xc || !yc)
- return b4 ? 0 : !xc ^ a5 ? 1 : -1;
- if (!b4)
- return k4 > l4 ^ a5 ? 1 : -1;
- j4 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4;
- for (i5 = 0;i5 < j4; i5++)
- if (xc[i5] != yc[i5])
- return xc[i5] > yc[i5] ^ a5 ? 1 : -1;
- return k4 == l4 ? 0 : k4 > l4 ^ a5 ? 1 : -1;
- }
- function intCheck(n5, min, max, name3) {
- if (n5 < min || n5 > max || n5 !== mathfloor(n5)) {
- throw Error(bignumberError + (name3 || "Argument") + (typeof n5 == "number" ? n5 < min || n5 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n5));
- }
- }
- function isOdd(n5) {
- var k4 = n5.c.length - 1;
- return bitFloor(n5.e / LOG_BASE) == k4 && n5.c[k4] % 2 != 0;
- }
- function toExponential(str, e4) {
- return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e4 < 0 ? "e" : "e+") + e4;
- }
- function toFixedPoint(str, e4, z3) {
- var len, zs;
- if (e4 < 0) {
- for (zs = z3 + ".";++e4; zs += z3)
- ;
- str = zs + str;
- } else {
- len = str.length;
- if (++e4 > len) {
- for (zs = z3, e4 -= len;--e4; zs += z3)
- ;
- str += zs;
- } else if (e4 < len) {
- str = str.slice(0, e4) + "." + str.slice(e4);
- }
- }
- return str;
- }
- BigNumber = clone3();
- BigNumber["default"] = BigNumber.BigNumber = BigNumber;
- if (typeof define == "function" && define.amd) {
- define(function() {
- return BigNumber;
- });
- } else if (typeof module != "undefined" && module.exports) {
- module.exports = BigNumber;
- } else {
- if (!globalObject) {
- globalObject = typeof self != "undefined" && self ? self : window;
- }
- globalObject.BigNumber = BigNumber;
- }
- })(exports);
-});
-
-// node_modules/json-bigint/lib/stringify.js
-var require_stringify3 = __commonJS((exports, module) => {
- var BigNumber = require_bignumber();
- var JSON2 = exports;
- (function() {
- function f4(n5) {
- return n5 < 10 ? "0" + n5 : n5;
- }
- 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 = {
- "\b": "\\b",
- "\t": "\\t",
- "\n": "\\n",
- "\f": "\\f",
- "\r": "\\r",
- '"': "\\\"",
- "\\": "\\\\"
- }, rep;
- function quote(string4) {
- escapable.lastIndex = 0;
- return escapable.test(string4) ? '"' + string4.replace(escapable, function(a5) {
- var c8 = meta[a5];
- return typeof c8 === "string" ? c8 : "\\u" + ("0000" + a5.charCodeAt(0).toString(16)).slice(-4);
- }) + '"' : '"' + string4 + '"';
- }
- function str(key, holder) {
- var i5, k4, v6, length, mind = gap, partial2, value = holder[key], isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value));
- if (value && typeof value === "object" && typeof value.toJSON === "function") {
- value = value.toJSON(key);
- }
- if (typeof rep === "function") {
- value = rep.call(holder, key, value);
- }
- switch (typeof value) {
- case "string":
- if (isBigNumber) {
- return value;
- } else {
- return quote(value);
- }
- case "number":
- return isFinite(value) ? String(value) : "null";
- case "boolean":
- case "null":
- case "bigint":
- return String(value);
- case "object":
- if (!value) {
- return "null";
- }
- gap += indent;
- partial2 = [];
- if (Object.prototype.toString.apply(value) === "[object Array]") {
- length = value.length;
- for (i5 = 0;i5 < length; i5 += 1) {
- partial2[i5] = str(i5, value) || "null";
- }
- v6 = partial2.length === 0 ? "[]" : gap ? `[
-` + gap + partial2.join(`,
-` + gap) + `
-` + mind + "]" : "[" + partial2.join(",") + "]";
- gap = mind;
- return v6;
- }
- if (rep && typeof rep === "object") {
- length = rep.length;
- for (i5 = 0;i5 < length; i5 += 1) {
- if (typeof rep[i5] === "string") {
- k4 = rep[i5];
- v6 = str(k4, value);
- if (v6) {
- partial2.push(quote(k4) + (gap ? ": " : ":") + v6);
- }
- }
- }
- } else {
- Object.keys(value).forEach(function(k5) {
- var v7 = str(k5, value);
- if (v7) {
- partial2.push(quote(k5) + (gap ? ": " : ":") + v7);
- }
- });
- }
- v6 = partial2.length === 0 ? "{}" : gap ? `{
-` + gap + partial2.join(`,
-` + gap) + `
-` + mind + "}" : "{" + partial2.join(",") + "}";
- gap = mind;
- return v6;
- }
- }
- if (typeof JSON2.stringify !== "function") {
- JSON2.stringify = function(value, replacer, space) {
- var i5;
- gap = "";
- indent = "";
- if (typeof space === "number") {
- for (i5 = 0;i5 < space; i5 += 1) {
- indent += " ";
- }
- } else if (typeof space === "string") {
- indent = space;
- }
- rep = replacer;
- if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) {
- throw new Error("JSON.stringify");
- }
- return str("", { "": value });
- };
- }
- })();
-});
-
-// node_modules/json-bigint/lib/parse.js
-var require_parse6 = __commonJS((exports, module) => {
- var BigNumber = null;
- var suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/;
- var 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)/;
- var json_parse = function(options2) {
- var _options = {
- strict: false,
- storeAsString: false,
- alwaysParseAsBig: false,
- useNativeBigInt: false,
- protoAction: "error",
- constructorAction: "error"
- };
- if (options2 !== undefined && options2 !== null) {
- if (options2.strict === true) {
- _options.strict = true;
- }
- if (options2.storeAsString === true) {
- _options.storeAsString = true;
- }
- _options.alwaysParseAsBig = options2.alwaysParseAsBig === true ? options2.alwaysParseAsBig : false;
- _options.useNativeBigInt = options2.useNativeBigInt === true ? options2.useNativeBigInt : false;
- if (typeof options2.constructorAction !== "undefined") {
- if (options2.constructorAction === "error" || options2.constructorAction === "ignore" || options2.constructorAction === "preserve") {
- _options.constructorAction = options2.constructorAction;
- } else {
- throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options2.constructorAction}`);
- }
- }
- if (typeof options2.protoAction !== "undefined") {
- if (options2.protoAction === "error" || options2.protoAction === "ignore" || options2.protoAction === "preserve") {
- _options.protoAction = options2.protoAction;
- } else {
- throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options2.protoAction}`);
- }
- }
- }
- var at, ch, escapee = {
- '"': '"',
- "\\": "\\",
- "/": "/",
- b: "\b",
- f: "\f",
- n: `
-`,
- r: "\r",
- t: "\t"
- }, text, error45 = function(m4) {
- throw {
- name: "SyntaxError",
- message: m4,
- at,
- text
- };
- }, next = function(c8) {
- if (c8 && c8 !== ch) {
- error45("Expected '" + c8 + "' instead of '" + ch + "'");
- }
- ch = text.charAt(at);
- at += 1;
- return ch;
- }, number4 = function() {
- var number5, string5 = "";
- if (ch === "-") {
- string5 = "-";
- next("-");
- }
- while (ch >= "0" && ch <= "9") {
- string5 += ch;
- next();
- }
- if (ch === ".") {
- string5 += ".";
- while (next() && ch >= "0" && ch <= "9") {
- string5 += ch;
- }
- }
- if (ch === "e" || ch === "E") {
- string5 += ch;
- next();
- if (ch === "-" || ch === "+") {
- string5 += ch;
- next();
- }
- while (ch >= "0" && ch <= "9") {
- string5 += ch;
- next();
- }
- }
- number5 = +string5;
- if (!isFinite(number5)) {
- error45("Bad number");
- } else {
- if (BigNumber == null)
- BigNumber = require_bignumber();
- if (string5.length > 15)
- return _options.storeAsString ? string5 : _options.useNativeBigInt ? BigInt(string5) : new BigNumber(string5);
- else
- return !_options.alwaysParseAsBig ? number5 : _options.useNativeBigInt ? BigInt(number5) : new BigNumber(number5);
- }
- }, string4 = function() {
- var hex, i5, string5 = "", uffff;
- if (ch === '"') {
- var startAt = at;
- while (next()) {
- if (ch === '"') {
- if (at - 1 > startAt)
- string5 += text.substring(startAt, at - 1);
- next();
- return string5;
- }
- if (ch === "\\") {
- if (at - 1 > startAt)
- string5 += text.substring(startAt, at - 1);
- next();
- if (ch === "u") {
- uffff = 0;
- for (i5 = 0;i5 < 4; i5 += 1) {
- hex = parseInt(next(), 16);
- if (!isFinite(hex)) {
- break;
- }
- uffff = uffff * 16 + hex;
- }
- string5 += String.fromCharCode(uffff);
- } else if (typeof escapee[ch] === "string") {
- string5 += escapee[ch];
- } else {
- break;
- }
- startAt = at;
- }
- }
- }
- error45("Bad string");
- }, white2 = function() {
- while (ch && ch <= " ") {
- next();
- }
- }, word = function() {
- 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;
- }
- error45("Unexpected '" + ch + "'");
- }, value, array2 = function() {
- var array3 = [];
- if (ch === "[") {
- next("[");
- white2();
- if (ch === "]") {
- next("]");
- return array3;
- }
- while (ch) {
- array3.push(value());
- white2();
- if (ch === "]") {
- next("]");
- return array3;
- }
- next(",");
- white2();
- }
- }
- error45("Bad array");
- }, object2 = function() {
- var key, object3 = Object.create(null);
- if (ch === "{") {
- next("{");
- white2();
- if (ch === "}") {
- next("}");
- return object3;
- }
- while (ch) {
- key = string4();
- white2();
- next(":");
- if (_options.strict === true && Object.hasOwnProperty.call(object3, key)) {
- error45('Duplicate key "' + key + '"');
- }
- if (suspectProtoRx.test(key) === true) {
- if (_options.protoAction === "error") {
- error45("Object contains forbidden prototype property");
- } else if (_options.protoAction === "ignore") {
- value();
- } else {
- object3[key] = value();
- }
- } else if (suspectConstructorRx.test(key) === true) {
- if (_options.constructorAction === "error") {
- error45("Object contains forbidden constructor property");
- } else if (_options.constructorAction === "ignore") {
- value();
- } else {
- object3[key] = value();
- }
- } else {
- object3[key] = value();
- }
- white2();
- if (ch === "}") {
- next("}");
- return object3;
- }
- next(",");
- white2();
- }
- }
- error45("Bad object");
- };
- value = function() {
- white2();
- switch (ch) {
- case "{":
- return object2();
- case "[":
- return array2();
- case '"':
- return string4();
- case "-":
- return number4();
- default:
- return ch >= "0" && ch <= "9" ? number4() : word();
- }
- };
- return function(source, reviver) {
- var result;
- text = source + "";
- at = 0;
- ch = " ";
- result = value();
- white2();
- if (ch) {
- error45("Syntax error");
- }
- return typeof reviver === "function" ? function walk(holder, key) {
- var k4, v6, value2 = holder[key];
- if (value2 && typeof value2 === "object") {
- Object.keys(value2).forEach(function(k5) {
- v6 = walk(value2, k5);
- if (v6 !== undefined) {
- value2[k5] = v6;
- } else {
- delete value2[k5];
- }
- });
- }
- return reviver.call(holder, key, value2);
- }({ "": result }, "") : result;
- };
- };
- module.exports = json_parse;
-});
-
-// node_modules/json-bigint/index.js
-var require_json_bigint = __commonJS((exports, module) => {
- var json_stringify = require_stringify3().stringify;
- var json_parse = require_parse6();
- module.exports = function(options2) {
- return {
- parse: json_parse(options2),
- stringify: json_stringify
- };
- };
- module.exports.parse = json_parse();
- module.exports.stringify = json_stringify;
-});
-
-// node_modules/gcp-metadata/build/src/gcp-residency.js
-var require_gcp_residency = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.GCE_LINUX_BIOS_PATHS = undefined;
- exports.isGoogleCloudServerless = isGoogleCloudServerless;
- exports.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux;
- exports.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress;
- exports.isGoogleComputeEngine = isGoogleComputeEngine;
- exports.detectGCPResidency = detectGCPResidency;
- var fs_1 = __require("fs");
- var os_1 = __require("os");
- exports.GCE_LINUX_BIOS_PATHS = {
- BIOS_DATE: "/sys/class/dmi/id/bios_date",
- BIOS_VENDOR: "/sys/class/dmi/id/bios_vendor"
- };
- var GCE_MAC_ADDRESS_REGEX = /^42:01/;
- function isGoogleCloudServerless() {
- const isGFEnvironment = process.env.CLOUD_RUN_JOB || process.env.FUNCTION_NAME || process.env.K_SERVICE;
- return !!isGFEnvironment;
- }
- function isGoogleComputeEngineLinux() {
- if ((0, os_1.platform)() !== "linux")
- return false;
- try {
- (0, fs_1.statSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_DATE);
- const biosVendor = (0, fs_1.readFileSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR, "utf8");
- return /Google/.test(biosVendor);
- } catch (_a8) {
- return false;
- }
- }
- function isGoogleComputeEngineMACAddress() {
- const interfaces = (0, os_1.networkInterfaces)();
- for (const item of Object.values(interfaces)) {
- if (!item)
- continue;
- for (const { mac } of item) {
- if (GCE_MAC_ADDRESS_REGEX.test(mac)) {
- return true;
- }
- }
- }
- return false;
- }
- function isGoogleComputeEngine() {
- return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress();
- }
- function detectGCPResidency() {
- return isGoogleCloudServerless() || isGoogleComputeEngine();
- }
-});
-
-// node_modules/google-logging-utils/build/src/colours.js
-var require_colours = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Colours = undefined;
-
- class Colours {
- static isEnabled(stream10) {
- return stream10.isTTY && (typeof stream10.getColorDepth === "function" ? stream10.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 = "";
- } else {
- Colours.reset = "\x1B[0m";
- Colours.bright = "\x1B[1m";
- Colours.dim = "\x1B[2m";
- Colours.red = "\x1B[31m";
- Colours.green = "\x1B[32m";
- Colours.yellow = "\x1B[33m";
- Colours.blue = "\x1B[34m";
- Colours.magenta = "\x1B[35m";
- Colours.cyan = "\x1B[36m";
- Colours.white = "\x1B[37m";
- Colours.grey = "\x1B[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();
-});
-
-// node_modules/google-logging-utils/build/src/logging-utils.js
-var require_logging_utils = __commonJS((exports) => {
- var __createBinding2 = exports && exports.__createBinding || (Object.create ? function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- var desc = Object.getOwnPropertyDescriptor(m4, k4);
- if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() {
- return m4[k4];
- } };
- }
- Object.defineProperty(o5, k22, desc);
- } : function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- });
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o5, v6) {
- Object.defineProperty(o5, "default", { enumerable: true, value: v6 });
- } : function(o5, v6) {
- o5["default"] = v6;
- });
- var __importStar2 = exports && exports.__importStar || function(mod2) {
- if (mod2 && mod2.__esModule)
- return mod2;
- var result = {};
- if (mod2 != null) {
- for (var k4 in mod2)
- if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4))
- __createBinding2(result, mod2, k4);
- }
- __setModuleDefault(result, mod2);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = undefined;
- exports.getNodeBackend = getNodeBackend;
- exports.getDebugBackend = getDebugBackend;
- exports.getStructuredBackend = getStructuredBackend;
- exports.setBackend = setBackend;
- exports.log = log3;
- var node_events_1 = __require("events");
- var process20 = __importStar2(__require("process"));
- var util10 = __importStar2(__require("util"));
- var colours_1 = require_colours();
- var LogSeverity;
- (function(LogSeverity2) {
- LogSeverity2["DEFAULT"] = "DEFAULT";
- LogSeverity2["DEBUG"] = "DEBUG";
- LogSeverity2["INFO"] = "INFO";
- LogSeverity2["WARNING"] = "WARNING";
- LogSeverity2["ERROR"] = "ERROR";
- })(LogSeverity || (exports.LogSeverity = LogSeverity = {}));
-
- class AdhocDebugLogger extends node_events_1.EventEmitter {
- constructor(namespace, upstream) {
- super();
- this.namespace = namespace;
- this.upstream = upstream;
- this.func = Object.assign(this.invoke.bind(this), {
- instance: this,
- on: (event, listener) => this.on(event, listener)
- });
- 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 = (namespace2) => log3(namespace2, this.func);
- }
- invoke(fields, ...args) {
- if (this.upstream) {
- this.upstream(fields, ...args);
- }
- this.emit("log", fields, args);
- }
- invokeSeverity(severity, ...args) {
- this.invoke({ severity }, ...args);
- }
- }
- exports.AdhocDebugLogger = AdhocDebugLogger;
- exports.placeholder = new AdhocDebugLogger("", () => {}).func;
-
- class DebugLogBackendBase {
- constructor() {
- var _a8;
- this.cached = new Map;
- this.filters = [];
- this.filtersSet = false;
- let nodeFlag = (_a8 = process20.env[exports.env.nodeEnables]) !== null && _a8 !== undefined ? _a8 : "*";
- if (nodeFlag === "all") {
- nodeFlag = "*";
- }
- this.filters = nodeFlag.split(",");
- }
- log(namespace, fields, ...args) {
- try {
- if (!this.filtersSet) {
- this.setFilters();
- this.filtersSet = true;
- }
- let logger34 = this.cached.get(namespace);
- if (!logger34) {
- logger34 = this.makeLogger(namespace);
- this.cached.set(namespace, logger34);
- }
- logger34(fields, ...args);
- } catch (e4) {
- console.error(e4);
- }
- }
- }
- exports.DebugLogBackendBase = DebugLogBackendBase;
-
- class NodeBackend extends DebugLogBackendBase {
- constructor() {
- super(...arguments);
- this.enabledRegexp = /.*/g;
- }
- isEnabled(namespace) {
- return this.enabledRegexp.test(namespace);
- }
- makeLogger(namespace) {
- if (!this.enabledRegexp.test(namespace)) {
- return () => {};
- }
- return (fields, ...args) => {
- var _a8;
- const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`;
- const pid = `${colours_1.Colours.yellow}${process20.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 = (_a8 = fields.severity) !== null && _a8 !== undefined ? _a8 : LogSeverity.DEFAULT;
- break;
- }
- const msg = util10.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}` : "");
- };
- }
- setFilters() {
- const totalFilters = this.filters.join(",");
- const regexp = totalFilters.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^");
- this.enabledRegexp = new RegExp(`^${regexp}$`, "i");
- }
- }
- 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) => {
- debugLogger(args[0], ...args.slice(1));
- };
- }
- setFilters() {
- var _a8;
- const existingFilters = (_a8 = process20.env["NODE_DEBUG"]) !== null && _a8 !== undefined ? _a8 : "";
- process20.env["NODE_DEBUG"] = `${existingFilters}${existingFilters ? "," : ""}${this.filters.join(",")}`;
- }
- }
- function getDebugBackend(debugPkg) {
- return new DebugBackend(debugPkg);
- }
-
- class StructuredBackend extends DebugLogBackendBase {
- constructor(upstream) {
- var _a8;
- super();
- this.upstream = (_a8 = upstream) !== null && _a8 !== undefined ? _a8 : new NodeBackend;
- }
- makeLogger(namespace) {
- const debugLogger = this.upstream.makeLogger(namespace);
- return (fields, ...args) => {
- var _a8;
- const severity = (_a8 = fields.severity) !== null && _a8 !== undefined ? _a8 : LogSeverity.INFO;
- const json2 = Object.assign({
- severity,
- message: util10.format(...args)
- }, fields);
- const jsonString = JSON.stringify(json2);
- debugLogger(fields, jsonString);
- };
- }
- setFilters() {
- this.upstream.setFilters();
- }
- }
- function getStructuredBackend(upstream) {
- return new StructuredBackend(upstream);
- }
- exports.env = {
- nodeEnables: "GOOGLE_SDK_NODE_LOGGING"
- };
- var loggerCache = new Map;
- var cachedBackend = undefined;
- function setBackend(backend) {
- cachedBackend = backend;
- loggerCache.clear();
- }
- function log3(namespace, parent) {
- const enablesFlag = process20.env[exports.env.nodeEnables];
- if (!enablesFlag) {
- return exports.placeholder;
- }
- if (!namespace) {
- return exports.placeholder;
- }
- if (parent) {
- namespace = `${parent.instance.namespace}:${namespace}`;
- }
- const existing = loggerCache.get(namespace);
- if (existing) {
- return existing.func;
- }
- if (cachedBackend === null) {
- return exports.placeholder;
- } else if (cachedBackend === undefined) {
- cachedBackend = getNodeBackend();
- }
- const logger34 = (() => {
- let previousBackend = undefined;
- const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => {
- if (previousBackend !== cachedBackend) {
- if (cachedBackend === null) {
- return;
- } else if (cachedBackend === undefined) {
- cachedBackend = getNodeBackend();
- }
- previousBackend = cachedBackend;
- }
- cachedBackend === null || cachedBackend === undefined || cachedBackend.log(namespace, fields, ...args);
- });
- return newLogger;
- })();
- loggerCache.set(namespace, logger34);
- return logger34.func;
- }
-});
-
-// node_modules/google-logging-utils/build/src/index.js
-var require_src3 = __commonJS((exports) => {
- var __createBinding2 = exports && exports.__createBinding || (Object.create ? function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- var desc = Object.getOwnPropertyDescriptor(m4, k4);
- if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() {
- return m4[k4];
- } };
- }
- Object.defineProperty(o5, k22, desc);
- } : function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- });
- var __exportStar2 = exports && exports.__exportStar || function(m4, exports2) {
- for (var p4 in m4)
- if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
- __createBinding2(exports2, m4, p4);
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- __exportStar2(require_logging_utils(), exports);
-});
-
-// node_modules/gcp-metadata/build/src/index.js
-var require_src4 = __commonJS((exports) => {
- var __createBinding2 = exports && exports.__createBinding || (Object.create ? function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- var desc = Object.getOwnPropertyDescriptor(m4, k4);
- if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() {
- return m4[k4];
- } };
- }
- Object.defineProperty(o5, k22, desc);
- } : function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- });
- var __exportStar2 = exports && exports.__exportStar || function(m4, exports2) {
- for (var p4 in m4)
- if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
- __createBinding2(exports2, m4, p4);
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.gcpResidencyCache = exports.METADATA_SERVER_DETECTION = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = undefined;
- exports.instance = instance;
- exports.project = project;
- exports.universe = universe;
- exports.bulk = bulk;
- exports.isAvailable = isAvailable;
- exports.resetIsAvailableCache = resetIsAvailableCache;
- exports.getGCPResidency = getGCPResidency;
- exports.setGCPResidency = setGCPResidency;
- exports.requestTimeout = requestTimeout;
- var gaxios_1 = require_src2();
- var jsonBigint = require_json_bigint();
- var gcp_residency_1 = require_gcp_residency();
- var logger34 = require_src3();
- exports.BASE_PATH = "/computeMetadata/v1";
- exports.HOST_ADDRESS = "http://169.254.169.254";
- exports.SECONDARY_HOST_ADDRESS = "http://metadata.google.internal.";
- exports.HEADER_NAME = "Metadata-Flavor";
- exports.HEADER_VALUE = "Google";
- exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE });
- var log3 = logger34.log("gcp metadata");
- exports.METADATA_SERVER_DETECTION = Object.freeze({
- "assume-present": "don't try to ping the metadata server, but assume it's present",
- none: "don't try to ping the metadata server, but don't try to use it either",
- "bios-only": "treat the result of a BIOS probe as canonical (don't fall back to pinging)",
- "ping-only": "skip the BIOS probe, and go straight to pinging"
- });
- function getBaseUrl(baseUrl) {
- if (!baseUrl) {
- baseUrl = process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST || exports.HOST_ADDRESS;
- }
- if (!/^https?:\/\//.test(baseUrl)) {
- baseUrl = `http://${baseUrl}`;
- }
- return new URL(exports.BASE_PATH, baseUrl).href;
- }
- function validate3(options2) {
- Object.keys(options2).forEach((key) => {
- switch (key) {
- case "params":
- case "property":
- case "headers":
- break;
- case "qs":
- throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");
- default:
- throw new Error(`'${key}' is not a valid configuration option.`);
- }
- });
- }
- async function metadataAccessor(type, options2 = {}, noResponseRetries = 3, fastFail = false) {
- let metadataKey = "";
- let params = {};
- let headers = {};
- if (typeof type === "object") {
- const metadataAccessor2 = type;
- metadataKey = metadataAccessor2.metadataKey;
- params = metadataAccessor2.params || params;
- headers = metadataAccessor2.headers || headers;
- noResponseRetries = metadataAccessor2.noResponseRetries || noResponseRetries;
- fastFail = metadataAccessor2.fastFail || fastFail;
- } else {
- metadataKey = type;
- }
- if (typeof options2 === "string") {
- metadataKey += `/${options2}`;
- } else {
- validate3(options2);
- if (options2.property) {
- metadataKey += `/${options2.property}`;
- }
- headers = options2.headers || headers;
- params = options2.params || params;
- }
- const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request;
- const req = {
- url: `${getBaseUrl()}/${metadataKey}`,
- headers: { ...exports.HEADERS, ...headers },
- retryConfig: { noResponseRetries },
- params,
- responseType: "text",
- timeout: requestTimeout()
- };
- log3.info("instance request %j", req);
- const res = await requestMethod(req);
- log3.info("instance metadata is %s", res.data);
- if (res.headers[exports.HEADER_NAME.toLowerCase()] !== exports.HEADER_VALUE) {
- throw new Error(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${res.headers[exports.HEADER_NAME.toLowerCase()] ? `'${res.headers[exports.HEADER_NAME.toLowerCase()]}'` : "no header"}`);
- }
- if (typeof res.data === "string") {
- try {
- return jsonBigint.parse(res.data);
- } catch (_a8) {}
- }
- return res.data;
- }
- async function fastFailMetadataRequest(options2) {
- var _a8;
- const secondaryOptions = {
- ...options2,
- url: (_a8 = options2.url) === null || _a8 === undefined ? undefined : _a8.toString().replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS))
- };
- let responded = false;
- const r1 = (0, gaxios_1.request)(options2).then((res) => {
- responded = true;
- return res;
- }).catch((err) => {
- if (responded) {
- return r22;
- } else {
- responded = true;
- throw err;
- }
- });
- const r22 = (0, gaxios_1.request)(secondaryOptions).then((res) => {
- responded = true;
- return res;
- }).catch((err) => {
- if (responded) {
- return r1;
- } else {
- responded = true;
- throw err;
- }
- });
- return Promise.race([r1, r22]);
- }
- function instance(options2) {
- return metadataAccessor("instance", options2);
- }
- function project(options2) {
- return metadataAccessor("project", options2);
- }
- function universe(options2) {
- return metadataAccessor("universe", options2);
- }
- async function bulk(properties) {
- const r4 = {};
- await Promise.all(properties.map((item) => {
- return (async () => {
- const res = await metadataAccessor(item);
- const key = item.metadataKey;
- r4[key] = res;
- })();
- }));
- return r4;
- }
- function detectGCPAvailableRetries() {
- return process.env.DETECT_GCP_RETRIES ? Number(process.env.DETECT_GCP_RETRIES) : 0;
- }
- var cachedIsAvailableResponse;
- async function isAvailable() {
- if (process.env.METADATA_SERVER_DETECTION) {
- const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();
- if (!(value in exports.METADATA_SERVER_DETECTION)) {
- throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);
- }
- switch (value) {
- case "assume-present":
- return true;
- case "none":
- return false;
- case "bios-only":
- return getGCPResidency();
- case "ping-only":
- }
- }
- try {
- if (cachedIsAvailableResponse === undefined) {
- cachedIsAvailableResponse = metadataAccessor("instance", undefined, detectGCPAvailableRetries(), !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST));
- }
- await cachedIsAvailableResponse;
- return true;
- } catch (e4) {
- const err = e4;
- if (process.env.DEBUG_AUTH) {
- console.info(err);
- }
- if (err.type === "request-timeout") {
- return false;
- }
- if (err.response && err.response.status === 404) {
- return false;
- } else {
- if (!(err.response && err.response.status === 404) && (!err.code || ![
- "EHOSTDOWN",
- "EHOSTUNREACH",
- "ENETUNREACH",
- "ENOENT",
- "ENOTFOUND",
- "ECONNREFUSED"
- ].includes(err.code))) {
- let code = "UNKNOWN";
- if (err.code)
- code = err.code;
- process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, "MetadataLookupWarning");
- }
- return false;
- }
- }
- }
- function resetIsAvailableCache() {
- cachedIsAvailableResponse = undefined;
- }
- exports.gcpResidencyCache = null;
- function getGCPResidency() {
- if (exports.gcpResidencyCache === null) {
- setGCPResidency();
- }
- return exports.gcpResidencyCache;
- }
- function setGCPResidency(value = null) {
- exports.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)();
- }
- function requestTimeout() {
- return getGCPResidency() ? 0 : 3000;
- }
- __exportStar2(require_gcp_residency(), exports);
-});
-
-// node_modules/base64-js/index.js
-var require_base64_js = __commonJS((exports) => {
- exports.byteLength = byteLength;
- exports.toByteArray = toByteArray;
- exports.fromByteArray = fromByteArray;
- var lookup = [];
- var revLookup = [];
- var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
- var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- for (i5 = 0, len = code.length;i5 < len; ++i5) {
- lookup[i5] = code[i5];
- revLookup[code.charCodeAt(i5)] = i5;
- }
- var i5;
- var len;
- revLookup[45] = 62;
- revLookup[95] = 63;
- function getLens(b64) {
- var len2 = b64.length;
- if (len2 % 4 > 0) {
- throw new Error("Invalid string. Length must be a multiple of 4");
- }
- var validLen = b64.indexOf("=");
- if (validLen === -1)
- validLen = len2;
- var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
- return [validLen, placeHoldersLen];
- }
- function byteLength(b64) {
- var lens = getLens(b64);
- var validLen = lens[0];
- var placeHoldersLen = lens[1];
- return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
- }
- function _byteLength(b64, validLen, placeHoldersLen) {
- return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
- }
- function toByteArray(b64) {
- var tmp;
- var lens = getLens(b64);
- var validLen = lens[0];
- var placeHoldersLen = lens[1];
- var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
- var curByte = 0;
- var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
- var i6;
- for (i6 = 0;i6 < len2; i6 += 4) {
- tmp = revLookup[b64.charCodeAt(i6)] << 18 | revLookup[b64.charCodeAt(i6 + 1)] << 12 | revLookup[b64.charCodeAt(i6 + 2)] << 6 | revLookup[b64.charCodeAt(i6 + 3)];
- arr[curByte++] = tmp >> 16 & 255;
- arr[curByte++] = tmp >> 8 & 255;
- arr[curByte++] = tmp & 255;
- }
- if (placeHoldersLen === 2) {
- tmp = revLookup[b64.charCodeAt(i6)] << 2 | revLookup[b64.charCodeAt(i6 + 1)] >> 4;
- arr[curByte++] = tmp & 255;
- }
- if (placeHoldersLen === 1) {
- tmp = revLookup[b64.charCodeAt(i6)] << 10 | revLookup[b64.charCodeAt(i6 + 1)] << 4 | revLookup[b64.charCodeAt(i6 + 2)] >> 2;
- arr[curByte++] = tmp >> 8 & 255;
- arr[curByte++] = tmp & 255;
- }
- return arr;
- }
- function tripletToBase64(num) {
- return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
- }
- function encodeChunk(uint8, start, end) {
- var tmp;
- var output = [];
- for (var i6 = start;i6 < end; i6 += 3) {
- tmp = (uint8[i6] << 16 & 16711680) + (uint8[i6 + 1] << 8 & 65280) + (uint8[i6 + 2] & 255);
- output.push(tripletToBase64(tmp));
- }
- return output.join("");
- }
- function fromByteArray(uint8) {
- var tmp;
- var len2 = uint8.length;
- var extraBytes = len2 % 3;
- var parts = [];
- var maxChunkLength = 16383;
- for (var i6 = 0, len22 = len2 - extraBytes;i6 < len22; i6 += maxChunkLength) {
- parts.push(encodeChunk(uint8, i6, i6 + maxChunkLength > len22 ? len22 : i6 + maxChunkLength));
- }
- if (extraBytes === 1) {
- tmp = uint8[len2 - 1];
- parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==");
- } else if (extraBytes === 2) {
- tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
- parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=");
- }
- return parts.join("");
- }
-});
-
-// node_modules/google-auth-library/build/src/crypto/browser/crypto.js
-var require_crypto = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.BrowserCrypto = undefined;
- var base64js = require_base64_js();
- var crypto_1 = require_crypto3();
-
- 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) {
- const inputBuffer = new TextEncoder().encode(str);
- const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer);
- return base64js.fromByteArray(new Uint8Array(outputBuffer));
- }
- randomBytesBase64(count3) {
- const array2 = new Uint8Array(count3);
- window.crypto.getRandomValues(array2);
- return base64js.fromByteArray(array2);
- }
- static padBase64(base644) {
- while (base644.length % 4 !== 0) {
- base644 += "=";
- }
- return base644;
- }
- async verify(pubkey, data, signature7) {
- const algo = {
- name: "RSASSA-PKCS1-v1_5",
- hash: { name: "SHA-256" }
- };
- const dataArray = new TextEncoder().encode(data);
- const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature7));
- const cryptoKey = await window.crypto.subtle.importKey("jwk", pubkey, algo, true, ["verify"]);
- 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"]);
- const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);
- return base64js.fromByteArray(new Uint8Array(result));
- }
- decodeBase64StringUtf8(base644) {
- const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base644));
- const result = new TextDecoder().decode(uint8array);
- return result;
- }
- encodeBase64StringUtf8(text) {
- const uint8array = new TextEncoder().encode(text);
- const result = base64js.fromByteArray(uint8array);
- return result;
- }
- async sha256DigestHex(str) {
- const inputBuffer = new TextEncoder().encode(str);
- const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer);
- return (0, crypto_1.fromArrayBufferToHex)(outputBuffer);
- }
- async signWithHmacSha256(key, msg) {
- 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;
-});
-
-// node_modules/google-auth-library/build/src/crypto/node/crypto.js
-var require_crypto2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.NodeCrypto = undefined;
- var crypto11 = __require("crypto");
-
- class NodeCrypto {
- async sha256DigestBase64(str) {
- return crypto11.createHash("sha256").update(str).digest("base64");
- }
- randomBytesBase64(count3) {
- return crypto11.randomBytes(count3).toString("base64");
- }
- async verify(pubkey, data, signature7) {
- const verifier = crypto11.createVerify("RSA-SHA256");
- verifier.update(data);
- verifier.end();
- return verifier.verify(pubkey, signature7, "base64");
- }
- async sign(privateKey, data) {
- const signer = crypto11.createSign("RSA-SHA256");
- signer.update(data);
- signer.end();
- return signer.sign(privateKey, "base64");
- }
- decodeBase64StringUtf8(base644) {
- return Buffer.from(base644, "base64").toString("utf-8");
- }
- encodeBase64StringUtf8(text) {
- return Buffer.from(text, "utf-8").toString("base64");
- }
- async sha256DigestHex(str) {
- return crypto11.createHash("sha256").update(str).digest("hex");
- }
- async signWithHmacSha256(key, msg) {
- const cryptoKey = typeof key === "string" ? key : toBuffer(key);
- return toArrayBuffer(crypto11.createHmac("sha256", cryptoKey).update(msg).digest());
- }
- }
- exports.NodeCrypto = NodeCrypto;
- function toArrayBuffer(buffer) {
- return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
- }
- function toBuffer(arrayBuffer) {
- return Buffer.from(arrayBuffer);
- }
-});
-
-// node_modules/google-auth-library/build/src/crypto/crypto.js
-var require_crypto3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.createCrypto = createCrypto;
- exports.hasBrowserCrypto = hasBrowserCrypto;
- exports.fromArrayBufferToHex = fromArrayBufferToHex;
- var crypto_1 = require_crypto();
- var crypto_2 = require_crypto2();
- 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";
- }
- function fromArrayBufferToHex(arrayBuffer) {
- const byteArray = Array.from(new Uint8Array(arrayBuffer));
- return byteArray.map((byte) => {
- return byte.toString(16).padStart(2, "0");
- }).join("");
- }
-});
-
-// node_modules/google-auth-library/build/src/options.js
-var require_options = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.validate = validate3;
- function validate3(options2) {
- const vpairs = [
- { invalid: "uri", expected: "url" },
- { invalid: "json", expected: "data" },
- { invalid: "qs", expected: "params" }
- ];
- for (const pair of vpairs) {
- if (options2[pair.invalid]) {
- const e4 = `'${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(e4);
- }
- }
- }
-});
-
-// node_modules/google-auth-library/package.json
-var require_package3 = __commonJS((exports, module) => {
- module.exports = {
- name: "google-auth-library",
- version: "9.15.1",
- author: "Google Inc.",
- description: "Google APIs Authentication Client Library for Node.js",
- engines: {
- node: ">=14"
- },
- main: "./build/src/index.js",
- types: "./build/src/index.d.ts",
- repository: "googleapis/google-auth-library-nodejs.git",
- keywords: [
- "google",
- "api",
- "google apis",
- "client",
- "client library"
- ],
- dependencies: {
- "base64-js": "^1.3.0",
- "ecdsa-sig-formatter": "^1.0.11",
- gaxios: "^6.1.1",
- "gcp-metadata": "^6.1.0",
- gtoken: "^7.0.0",
- jws: "^4.0.0"
- },
- devDependencies: {
- "@types/base64-js": "^1.2.5",
- "@types/chai": "^4.1.7",
- "@types/jws": "^3.1.0",
- "@types/mocha": "^9.0.0",
- "@types/mv": "^2.1.0",
- "@types/ncp": "^2.0.1",
- "@types/node": "^20.4.2",
- "@types/sinon": "^17.0.0",
- "assert-rejects": "^1.0.0",
- c8: "^8.0.0",
- chai: "^4.2.0",
- cheerio: "1.0.0-rc.12",
- codecov: "^3.0.2",
- "engine.io": "6.6.2",
- gts: "^5.0.0",
- "is-docker": "^2.0.0",
- jsdoc: "^4.0.0",
- "jsdoc-fresh": "^3.0.0",
- "jsdoc-region-tag": "^3.0.0",
- karma: "^6.0.0",
- "karma-chrome-launcher": "^3.0.0",
- "karma-coverage": "^2.0.0",
- "karma-firefox-launcher": "^2.0.0",
- "karma-mocha": "^2.0.0",
- "karma-sourcemap-loader": "^0.4.0",
- "karma-webpack": "5.0.0",
- keypair: "^1.0.4",
- linkinator: "^4.0.0",
- mocha: "^9.2.2",
- mv: "^2.1.1",
- ncp: "^2.0.0",
- nock: "^13.0.0",
- "null-loader": "^4.0.0",
- pdfmake: "0.2.12",
- puppeteer: "^21.0.0",
- sinon: "^18.0.0",
- "ts-loader": "^8.0.0",
- typescript: "^5.1.6",
- webpack: "^5.21.2",
- "webpack-cli": "^4.0.0"
- },
- files: [
- "build/src",
- "!build/src/**/*.map"
- ],
- scripts: {
- test: "c8 mocha build/test",
- clean: "gts clean",
- prepare: "npm run compile",
- lint: "gts check",
- compile: "tsc -p .",
- fix: "gts fix",
- pretest: "npm run compile -- --sourceMap",
- docs: "jsdoc -c .jsdoc.json",
- "samples-setup": "cd samples/ && npm link ../ && npm run setup && cd ../",
- "samples-test": "cd samples/ && npm link ../ && npm test && cd ../",
- "system-test": "mocha build/system-test --timeout 60000",
- "presystem-test": "npm run compile -- --sourceMap",
- webpack: "webpack",
- "browser-test": "karma start",
- "docs-test": "linkinator docs",
- "predocs-test": "npm run docs",
- prelint: "cd samples; npm link ../; npm install",
- precompile: "gts clean"
- },
- license: "Apache-2.0"
- };
-});
-
-// node_modules/google-auth-library/build/src/transporters.js
-var require_transporters = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.DefaultTransporter = undefined;
- var gaxios_1 = require_src2();
- var options_1 = require_options();
- var pkg = require_package3();
- var PRODUCT_NAME = "google-api-nodejs-client";
-
- class DefaultTransporter {
- constructor() {
- this.instance = new gaxios_1.Gaxios;
- }
- configure(opts = {}) {
- opts.headers = opts.headers || {};
- if (typeof window === "undefined") {
- const uaValue = opts.headers["User-Agent"];
- if (!uaValue) {
- opts.headers["User-Agent"] = DefaultTransporter.USER_AGENT;
- } else if (!uaValue.includes(`${PRODUCT_NAME}/`)) {
- opts.headers["User-Agent"] = `${uaValue} ${DefaultTransporter.USER_AGENT}`;
- }
- if (!opts.headers["x-goog-api-client"]) {
- const nodeVersion = process.version.replace(/^v/, "");
- opts.headers["x-goog-api-client"] = `gl-node/${nodeVersion}`;
- }
- }
- return opts;
- }
- request(opts) {
- opts = this.configure(opts);
- (0, options_1.validate)(opts);
- return this.instance.request(opts).catch((e4) => {
- throw this.processError(e4);
- });
- }
- get defaults() {
- return this.instance.defaults;
- }
- set defaults(opts) {
- this.instance.defaults = opts;
- }
- processError(e4) {
- const res = e4.response;
- const err = e4;
- 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(`
-`);
- 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) {
- err.message = body;
- err.status = res.status;
- }
- return err;
- }
- }
- exports.DefaultTransporter = DefaultTransporter;
- DefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`;
-});
-
-// node_modules/google-auth-library/build/src/util.js
-var require_util2 = __commonJS((exports) => {
- var __classPrivateFieldGet9 = exports && exports.__classPrivateFieldGet || function(receiver, state3, kind2, f4) {
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a getter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind2 === "m" ? f4 : kind2 === "a" ? f4.call(receiver) : f4 ? f4.value : state3.get(receiver);
- };
- var _LRUCache_instances;
- var _LRUCache_cache;
- var _LRUCache_moveToEnd;
- var _LRUCache_evict;
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.LRUCache = undefined;
- exports.snakeToCamel = snakeToCamel;
- exports.originalOrCamelOptions = originalOrCamelOptions;
- function snakeToCamel(str) {
- return str.replace(/([_][^_])/g, (match) => match.slice(1).toUpperCase());
- }
- function originalOrCamelOptions(obj) {
- function get2(key) {
- var _a8;
- const o5 = obj || {};
- return (_a8 = o5[key]) !== null && _a8 !== undefined ? _a8 : o5[snakeToCamel(key)];
- }
- return { get: get2 };
- }
-
- class LRUCache {
- constructor(options2) {
- _LRUCache_instances.add(this);
- _LRUCache_cache.set(this, new Map);
- this.capacity = options2.capacity;
- this.maxAge = options2.maxAge;
- }
- set(key, value) {
- __classPrivateFieldGet9(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, value);
- __classPrivateFieldGet9(this, _LRUCache_instances, "m", _LRUCache_evict).call(this);
- }
- get(key) {
- const item = __classPrivateFieldGet9(this, _LRUCache_cache, "f").get(key);
- if (!item)
- return;
- __classPrivateFieldGet9(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, item.value);
- __classPrivateFieldGet9(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_moveToEnd2(key, value) {
- __classPrivateFieldGet9(this, _LRUCache_cache, "f").delete(key);
- __classPrivateFieldGet9(this, _LRUCache_cache, "f").set(key, {
- value,
- lastAccessed: Date.now()
- });
- }, _LRUCache_evict = function _LRUCache_evict2() {
- const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0;
- let oldestItem = __classPrivateFieldGet9(this, _LRUCache_cache, "f").entries().next();
- while (!oldestItem.done && (__classPrivateFieldGet9(this, _LRUCache_cache, "f").size > this.capacity || oldestItem.value[1].lastAccessed < cutoffDate)) {
- __classPrivateFieldGet9(this, _LRUCache_cache, "f").delete(oldestItem.value[0]);
- oldestItem = __classPrivateFieldGet9(this, _LRUCache_cache, "f").entries().next();
- }
- };
-});
-
-// node_modules/google-auth-library/build/src/auth/authclient.js
-var require_authclient = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = undefined;
- var events_1 = __require("events");
- var gaxios_1 = require_src2();
- var transporters_1 = require_transporters();
- var util_1 = require_util2();
- exports.DEFAULT_UNIVERSE = "googleapis.com";
- exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000;
-
- class AuthClient extends events_1.EventEmitter {
- constructor(opts = {}) {
- var _a8, _b2, _c4, _d3, _e4;
- super();
- this.credentials = {};
- this.eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;
- this.forceRefreshOnFailure = false;
- this.universeDomain = exports.DEFAULT_UNIVERSE;
- const options2 = (0, util_1.originalOrCamelOptions)(opts);
- this.apiKey = opts.apiKey;
- this.projectId = (_a8 = options2.get("project_id")) !== null && _a8 !== undefined ? _a8 : null;
- this.quotaProjectId = options2.get("quota_project_id");
- this.credentials = (_b2 = options2.get("credentials")) !== null && _b2 !== undefined ? _b2 : {};
- this.universeDomain = (_c4 = options2.get("universe_domain")) !== null && _c4 !== undefined ? _c4 : exports.DEFAULT_UNIVERSE;
- this.transporter = (_d3 = opts.transporter) !== null && _d3 !== undefined ? _d3 : new transporters_1.DefaultTransporter;
- if (opts.transporterOptions) {
- this.transporter.defaults = opts.transporterOptions;
- }
- if (opts.eagerRefreshThresholdMillis) {
- this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis;
- }
- this.forceRefreshOnFailure = (_e4 = opts.forceRefreshOnFailure) !== null && _e4 !== undefined ? _e4 : false;
- }
- get gaxios() {
- if (this.transporter instanceof gaxios_1.Gaxios) {
- return this.transporter;
- } else if (this.transporter instanceof transporters_1.DefaultTransporter) {
- return this.transporter.instance;
- } else if ("instance" in this.transporter && this.transporter.instance instanceof gaxios_1.Gaxios) {
- return this.transporter.instance;
- }
- return null;
- }
- setCredentials(credentials) {
- this.credentials = credentials;
- }
- addSharedMetadataHeaders(headers) {
- if (!headers["x-goog-user-project"] && this.quotaProjectId) {
- headers["x-goog-user-project"] = this.quotaProjectId;
- }
- return headers;
- }
- static get RETRY_CONFIG() {
- return {
- retry: true,
- retryConfig: {
- httpMethodsToRetry: ["GET", "PUT", "POST", "HEAD", "OPTIONS", "DELETE"]
- }
- };
- }
- }
- exports.AuthClient = AuthClient;
-});
-
-// node_modules/google-auth-library/build/src/auth/loginticket.js
-var require_loginticket = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.LoginTicket = undefined;
-
- class LoginTicket {
- constructor(env5, pay) {
- this.envelope = env5;
- this.payload = pay;
- }
- getEnvelope() {
- return this.envelope;
- }
- getPayload() {
- return this.payload;
- }
- getUserId() {
- const payload = this.getPayload();
- if (payload && payload.sub) {
- return payload.sub;
- }
- return null;
- }
- getAttributes() {
- return { envelope: this.getEnvelope(), payload: this.getPayload() };
- }
- }
- exports.LoginTicket = LoginTicket;
-});
-
-// node_modules/google-auth-library/build/src/auth/oauth2client.js
-var require_oauth2client = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = undefined;
- var gaxios_1 = require_src2();
- var querystring = __require("querystring");
- var stream10 = __require("stream");
- var formatEcdsa = require_ecdsa_sig_formatter();
- var crypto_1 = require_crypto3();
- var authclient_1 = require_authclient();
- var loginticket_1 = require_loginticket();
- var CodeChallengeMethod;
- (function(CodeChallengeMethod2) {
- CodeChallengeMethod2["Plain"] = "plain";
- CodeChallengeMethod2["S256"] = "S256";
- })(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {}));
- var CertificateFormat;
- (function(CertificateFormat2) {
- CertificateFormat2["PEM"] = "PEM";
- CertificateFormat2["JWK"] = "JWK";
- })(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {}));
- var ClientAuthentication;
- (function(ClientAuthentication2) {
- ClientAuthentication2["ClientSecretPost"] = "ClientSecretPost";
- ClientAuthentication2["ClientSecretBasic"] = "ClientSecretBasic";
- ClientAuthentication2["None"] = "None";
- })(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {}));
-
- class OAuth2Client extends authclient_1.AuthClient {
- constructor(optionsOrClientId, clientSecret, redirectUri) {
- const opts = optionsOrClientId && typeof optionsOrClientId === "object" ? optionsOrClientId : { clientId: optionsOrClientId, clientSecret, redirectUri };
- super(opts);
- this.certificateCache = {};
- this.certificateExpiry = null;
- this.certificateCacheFormat = CertificateFormat.PEM;
- this.refreshTokenPromises = new Map;
- this._clientId = opts.clientId;
- this._clientSecret = opts.clientSecret;
- this.redirectUri = opts.redirectUri;
- this.endpoints = {
- tokenInfoUrl: "https://oauth2.googleapis.com/tokeninfo",
- oauth2AuthBaseUrl: "https://accounts.google.com/o/oauth2/v2/auth",
- oauth2TokenUrl: "https://oauth2.googleapis.com/token",
- oauth2RevokeUrl: "https://oauth2.googleapis.com/revoke",
- oauth2FederatedSignonPemCertsUrl: "https://www.googleapis.com/oauth2/v1/certs",
- oauth2FederatedSignonJwkCertsUrl: "https://www.googleapis.com/oauth2/v3/certs",
- oauth2IapPublicKeyUrl: "https://www.gstatic.com/iap/verify/public_key",
- ...opts.endpoints
- };
- this.clientAuthentication = opts.clientAuthentication || ClientAuthentication.ClientSecretPost;
- this.issuers = opts.issuers || [
- "accounts.google.com",
- "https://accounts.google.com",
- this.universeDomain
- ];
- }
- generateAuthUrl(opts = {}) {
- if (opts.code_challenge_method && !opts.code_challenge) {
- throw new Error("If a code_challenge_method is provided, code_challenge must be included.");
- }
- opts.response_type = opts.response_type || "code";
- opts.client_id = opts.client_id || this._clientId;
- opts.redirect_uri = opts.redirect_uri || this.redirectUri;
- if (Array.isArray(opts.scope)) {
- opts.scope = opts.scope.join(" ");
- }
- const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString();
- return rootUrl + "?" + querystring.stringify(opts);
- }
- generateCodeVerifier() {
- throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.");
- }
- async generateCodeVerifierAsync() {
- const crypto11 = (0, crypto_1.createCrypto)();
- const randomString2 = crypto11.randomBytesBase64(96);
- const codeVerifier = randomString2.replace(/\+/g, "~").replace(/=/g, "_").replace(/\//g, "-");
- const unencodedCodeChallenge = await crypto11.sha256DigestBase64(codeVerifier);
- const codeChallenge = unencodedCodeChallenge.split("=")[0].replace(/\+/g, "-").replace(/\//g, "_");
- return { codeVerifier, codeChallenge };
- }
- getToken(codeOrOptions, callback) {
- const options2 = typeof codeOrOptions === "string" ? { code: codeOrOptions } : codeOrOptions;
- if (callback) {
- this.getTokenAsync(options2).then((r4) => callback(null, r4.tokens, r4.res), (e4) => callback(e4, null, e4.response));
- } else {
- return this.getTokenAsync(options2);
- }
- }
- async getTokenAsync(options2) {
- const url3 = this.endpoints.oauth2TokenUrl.toString();
- const headers = {
- "Content-Type": "application/x-www-form-urlencoded"
- };
- const values2 = {
- client_id: options2.client_id || this._clientId,
- code_verifier: options2.codeVerifier,
- code: options2.code,
- grant_type: "authorization_code",
- redirect_uri: options2.redirect_uri || this.redirectUri
- };
- if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) {
- const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`);
- headers["Authorization"] = `Basic ${basic.toString("base64")}`;
- }
- if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) {
- values2.client_secret = this._clientSecret;
- }
- const res = await this.transporter.request({
- ...OAuth2Client.RETRY_CONFIG,
- method: "POST",
- url: url3,
- data: querystring.stringify(values2),
- headers
- });
- const tokens = res.data;
- if (res.data && res.data.expires_in) {
- tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;
- delete tokens.expires_in;
- }
- this.emit("tokens", tokens);
- return { tokens, res };
- }
- async refreshToken(refreshToken) {
- if (!refreshToken) {
- return this.refreshTokenNoCache(refreshToken);
- }
- if (this.refreshTokenPromises.has(refreshToken)) {
- return this.refreshTokenPromises.get(refreshToken);
- }
- const p4 = this.refreshTokenNoCache(refreshToken).then((r4) => {
- this.refreshTokenPromises.delete(refreshToken);
- return r4;
- }, (e4) => {
- this.refreshTokenPromises.delete(refreshToken);
- throw e4;
- });
- this.refreshTokenPromises.set(refreshToken, p4);
- return p4;
- }
- async refreshTokenNoCache(refreshToken) {
- var _a8;
- if (!refreshToken) {
- throw new Error("No refresh token is set.");
- }
- const url3 = this.endpoints.oauth2TokenUrl.toString();
- const data = {
- refresh_token: refreshToken,
- client_id: this._clientId,
- client_secret: this._clientSecret,
- grant_type: "refresh_token"
- };
- let res;
- try {
- res = await this.transporter.request({
- ...OAuth2Client.RETRY_CONFIG,
- method: "POST",
- url: url3,
- data: querystring.stringify(data),
- headers: { "Content-Type": "application/x-www-form-urlencoded" }
- });
- } catch (e4) {
- if (e4 instanceof gaxios_1.GaxiosError && e4.message === "invalid_grant" && ((_a8 = e4.response) === null || _a8 === undefined ? undefined : _a8.data) && /ReAuth/i.test(e4.response.data.error_description)) {
- e4.message = JSON.stringify(e4.response.data);
- }
- throw e4;
- }
- const tokens = res.data;
- if (res.data && res.data.expires_in) {
- tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;
- delete tokens.expires_in;
- }
- this.emit("tokens", tokens);
- return { tokens, res };
- }
- refreshAccessToken(callback) {
- if (callback) {
- this.refreshAccessTokenAsync().then((r4) => callback(null, r4.credentials, r4.res), callback);
- } else {
- return this.refreshAccessTokenAsync();
- }
- }
- async refreshAccessTokenAsync() {
- const r4 = await this.refreshToken(this.credentials.refresh_token);
- const tokens = r4.tokens;
- tokens.refresh_token = this.credentials.refresh_token;
- this.credentials = tokens;
- return { credentials: this.credentials, res: r4.res };
- }
- getAccessToken(callback) {
- if (callback) {
- this.getAccessTokenAsync().then((r4) => callback(null, r4.token, r4.res), callback);
- } else {
- return this.getAccessTokenAsync();
- }
- }
- async getAccessTokenAsync() {
- const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring();
- if (shouldRefresh) {
- if (!this.credentials.refresh_token) {
- if (this.refreshHandler) {
- const refreshedAccessToken = await this.processAndValidateRefreshHandler();
- if (refreshedAccessToken === null || refreshedAccessToken === undefined ? undefined : refreshedAccessToken.access_token) {
- this.setCredentials(refreshedAccessToken);
- return { token: this.credentials.access_token };
- }
- } else {
- throw new Error("No refresh token or refresh handler callback is set.");
- }
- }
- const r4 = await this.refreshAccessTokenAsync();
- if (!r4.credentials || r4.credentials && !r4.credentials.access_token) {
- throw new Error("Could not refresh access token.");
- }
- return { token: r4.credentials.access_token, res: r4.res };
- } else {
- return { token: this.credentials.access_token };
- }
- }
- async getRequestHeaders(url3) {
- const headers = (await this.getRequestMetadataAsync(url3)).headers;
- return headers;
- }
- async getRequestMetadataAsync(url3) {
- 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 headers2 = {
- Authorization: thisCreds.token_type + " " + thisCreds.access_token
- };
- return { headers: this.addSharedMetadataHeaders(headers2) };
- }
- if (this.refreshHandler) {
- const refreshedAccessToken = await this.processAndValidateRefreshHandler();
- if (refreshedAccessToken === null || refreshedAccessToken === undefined ? undefined : refreshedAccessToken.access_token) {
- this.setCredentials(refreshedAccessToken);
- const headers2 = {
- Authorization: "Bearer " + this.credentials.access_token
- };
- return { headers: this.addSharedMetadataHeaders(headers2) };
- }
- }
- if (this.apiKey) {
- return { headers: { "X-Goog-Api-Key": this.apiKey } };
- }
- let r4 = null;
- let tokens = null;
- try {
- r4 = await this.refreshToken(thisCreds.refresh_token);
- tokens = r4.tokens;
- } catch (err) {
- const e4 = err;
- if (e4.response && (e4.response.status === 403 || e4.response.status === 404)) {
- e4.message = `Could not refresh access token: ${e4.message}`;
- }
- throw e4;
- }
- 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: r4.res };
- }
- static getRevokeTokenUrl(token) {
- return new OAuth2Client().getRevokeTokenURL(token).toString();
- }
- getRevokeTokenURL(token) {
- const url3 = new URL(this.endpoints.oauth2RevokeUrl);
- url3.searchParams.append("token", token);
- return url3;
- }
- revokeToken(token, callback) {
- const opts = {
- ...OAuth2Client.RETRY_CONFIG,
- url: this.getRevokeTokenURL(token).toString(),
- method: "POST"
- };
- if (callback) {
- this.transporter.request(opts).then((r4) => callback(null, r4), callback);
- } else {
- return this.transporter.request(opts);
- }
- }
- revokeCredentials(callback) {
- if (callback) {
- this.revokeCredentialsAsync().then((res) => callback(null, res), callback);
- } else {
- return this.revokeCredentialsAsync();
- }
- }
- async revokeCredentialsAsync() {
- const token = this.credentials.access_token;
- this.credentials = {};
- if (token) {
- return this.revokeToken(token);
- } else {
- throw new Error("No access token to revoke.");
- }
- }
- request(opts, callback) {
- if (callback) {
- this.requestAsync(opts).then((r4) => callback(null, r4), (e4) => {
- return callback(e4, e4.response);
- });
- } else {
- return this.requestAsync(opts);
- }
- }
- async requestAsync(opts, reAuthRetried = false) {
- let r22;
- try {
- const r4 = await this.getRequestMetadataAsync(opts.url);
- opts.headers = opts.headers || {};
- if (r4.headers && r4.headers["x-goog-user-project"]) {
- opts.headers["x-goog-user-project"] = r4.headers["x-goog-user-project"];
- }
- if (r4.headers && r4.headers.Authorization) {
- opts.headers.Authorization = r4.headers.Authorization;
- }
- if (this.apiKey) {
- opts.headers["X-Goog-Api-Key"] = this.apiKey;
- }
- r22 = await this.transporter.request(opts);
- } catch (e4) {
- const res = e4.response;
- if (res) {
- const statusCode = res.status;
- 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 isReadableStream5 = res.config.data instanceof stream10.Readable;
- const isAuthErr = statusCode === 401 || statusCode === 403;
- if (!reAuthRetried && isAuthErr && !isReadableStream5 && mayRequireRefresh) {
- await this.refreshAccessTokenAsync();
- return this.requestAsync(opts, true);
- } else if (!reAuthRetried && isAuthErr && !isReadableStream5 && mayRequireRefreshWithNoRefreshToken) {
- const refreshedAccessToken = await this.processAndValidateRefreshHandler();
- if (refreshedAccessToken === null || refreshedAccessToken === undefined ? undefined : refreshedAccessToken.access_token) {
- this.setCredentials(refreshedAccessToken);
- }
- return this.requestAsync(opts, true);
- }
- }
- throw e4;
- }
- return r22;
- }
- verifyIdToken(options2, callback) {
- 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(options2).then((r4) => callback(null, r4), callback);
- } else {
- return this.verifyIdTokenAsync(options2);
- }
- }
- async verifyIdTokenAsync(options2) {
- if (!options2.idToken) {
- throw new Error("The verifyIdToken method requires an ID Token");
- }
- const response7 = await this.getFederatedSignonCertsAsync();
- const login = await this.verifySignedJwtWithCertsAsync(options2.idToken, response7.certs, options2.audience, this.issuers, options2.maxExpiry);
- return login;
- }
- 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((r4) => callback(null, r4.certs, r4.res), callback);
- } else {
- return this.getFederatedSignonCertsAsync();
- }
- }
- async getFederatedSignonCertsAsync() {
- const nowTime = new Date().getTime();
- const format3 = (0, crypto_1.hasBrowserCrypto)() ? CertificateFormat.JWK : CertificateFormat.PEM;
- if (this.certificateExpiry && nowTime < this.certificateExpiry.getTime() && this.certificateCacheFormat === format3) {
- return { certs: this.certificateCache, format: format3 };
- }
- let res;
- let url3;
- switch (format3) {
- case CertificateFormat.PEM:
- url3 = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();
- break;
- case CertificateFormat.JWK:
- url3 = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();
- break;
- default:
- throw new Error(`Unsupported certificate format ${format3}`);
- }
- try {
- res = await this.transporter.request({
- ...OAuth2Client.RETRY_CONFIG,
- url: url3
- });
- } catch (e4) {
- if (e4 instanceof Error) {
- e4.message = `Failed to retrieve verification certificates: ${e4.message}`;
- }
- throw e4;
- }
- 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) {
- cacheAge = Number(regexResult[1]) * 1000;
- }
- }
- let certificates = {};
- switch (format3) {
- 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 ${format3}`);
- }
- const now = new Date;
- this.certificateExpiry = cacheAge === -1 ? null : new Date(now.getTime() + cacheAge);
- this.certificateCache = certificates;
- this.certificateCacheFormat = format3;
- return { certs: certificates, format: format3, res };
- }
- getIapPublicKeys(callback) {
- if (callback) {
- this.getIapPublicKeysAsync().then((r4) => callback(null, r4.pubkeys, r4.res), callback);
- } else {
- return this.getIapPublicKeysAsync();
- }
- }
- async getIapPublicKeysAsync() {
- let res;
- const url3 = this.endpoints.oauth2IapPublicKeyUrl.toString();
- try {
- res = await this.transporter.request({
- ...OAuth2Client.RETRY_CONFIG,
- url: url3
- });
- } catch (e4) {
- if (e4 instanceof Error) {
- e4.message = `Failed to retrieve verification certificates: ${e4.message}`;
- }
- throw e4;
- }
- return { pubkeys: res.data, res };
- }
- verifySignedJwtWithCerts() {
- throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.");
- }
- async verifySignedJwtWithCertsAsync(jwt3, certs, requiredAudience, issuers, maxExpiry) {
- const crypto11 = (0, crypto_1.createCrypto)();
- if (!maxExpiry) {
- maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;
- }
- const segments = jwt3.split(".");
- if (segments.length !== 3) {
- throw new Error("Wrong number of segments in token: " + jwt3);
- }
- const signed = segments[0] + "." + segments[1];
- let signature7 = segments[2];
- let envelope;
- let payload;
- try {
- envelope = JSON.parse(crypto11.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(crypto11.decodeBase64StringUtf8(segments[1]));
- } catch (err) {
- if (err instanceof Error) {
- err.message = `Can't parse token payload '${segments[0]}`;
- }
- throw err;
- }
- if (!payload) {
- throw new Error("Can't parse token payload: " + segments[1]);
- }
- if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {
- throw new Error("No pem found for envelope: " + JSON.stringify(envelope));
- }
- const cert = certs[envelope.kid];
- if (envelope.alg === "ES256") {
- signature7 = formatEcdsa.joseToDer(signature7, "ES256").toString("base64");
- }
- const verified = await crypto11.verify(cert, signed, signature7);
- if (!verified) {
- throw new Error("Invalid token signature: " + jwt3);
- }
- 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);
- }
- if (typeof requiredAudience !== "undefined" && requiredAudience !== null) {
- const aud = payload.aud;
- let audVerified = false;
- if (requiredAudience.constructor === Array) {
- audVerified = requiredAudience.indexOf(aud) > -1;
- } else {
- audVerified = aud === requiredAudience;
- }
- if (!audVerified) {
- throw new Error("Wrong recipient, payload audience != requiredAudience");
- }
- }
- return new loginticket_1.LoginTicket(envelope, payload);
- }
- 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;
- }
- isTokenExpiring() {
- const expiryDate = this.credentials.expiry_date;
- return expiryDate ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis : false;
- }
- }
- exports.OAuth2Client = OAuth2Client;
- OAuth2Client.GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo";
- OAuth2Client.CLOCK_SKEW_SECS_ = 300;
- OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400;
-});
-
-// node_modules/google-auth-library/build/src/auth/computeclient.js
-var require_computeclient = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Compute = undefined;
- var gaxios_1 = require_src2();
- var gcpMetadata = require_src4();
- var oauth2client_1 = require_oauth2client();
-
- class Compute extends oauth2client_1.OAuth2Client {
- constructor(options2 = {}) {
- super(options2);
- this.credentials = { expiry_date: 1, refresh_token: "compute-placeholder" };
- this.serviceAccountEmail = options2.serviceAccountEmail || "default";
- this.scopes = Array.isArray(options2.scopes) ? options2.scopes : options2.scopes ? [options2.scopes] : [];
- }
- async refreshTokenNoCache(refreshToken) {
- const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;
- let data;
- try {
- const instanceOptions = {
- property: tokenPath
- };
- if (this.scopes.length > 0) {
- instanceOptions.params = {
- scopes: this.scopes.join(",")
- };
- }
- data = await gcpMetadata.instance(instanceOptions);
- } catch (e4) {
- if (e4 instanceof gaxios_1.GaxiosError) {
- e4.message = `Could not refresh access token: ${e4.message}`;
- this.wrapError(e4);
- }
- throw e4;
- }
- const tokens = data;
- if (data && data.expires_in) {
- tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;
- delete tokens.expires_in;
- }
- this.emit("tokens", tokens);
- return { tokens, res: null };
- }
- async fetchIdToken(targetAudience) {
- const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` + `?format=full&audience=${targetAudience}`;
- let idToken;
- try {
- const instanceOptions = {
- property: idTokenPath
- };
- idToken = await gcpMetadata.instance(instanceOptions);
- } catch (e4) {
- if (e4 instanceof Error) {
- e4.message = `Could not fetch ID token: ${e4.message}`;
- }
- throw e4;
- }
- return idToken;
- }
- wrapError(e4) {
- const res = e4.response;
- if (res && res.status) {
- e4.status = res.status;
- if (res.status === 403) {
- e4.message = "A Forbidden error was returned while attempting to retrieve an access " + "token for the Compute Engine built-in service account. This may be because the Compute " + "Engine instance does not have the correct permission scopes specified: " + e4.message;
- } else if (res.status === 404) {
- e4.message = "A Not Found error was returned while attempting to retrieve an access" + "token for the Compute Engine built-in service account. This may be because the Compute " + "Engine instance does not have any permission scopes specified: " + e4.message;
- }
- }
- }
- }
- exports.Compute = Compute;
-});
-
-// node_modules/google-auth-library/build/src/auth/idtokenclient.js
-var require_idtokenclient = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.IdTokenClient = undefined;
- var oauth2client_1 = require_oauth2client();
-
- class IdTokenClient extends oauth2client_1.OAuth2Client {
- constructor(options2) {
- super(options2);
- this.targetAudience = options2.targetAudience;
- this.idTokenProvider = options2.idTokenProvider;
- }
- async getRequestMetadataAsync(url3) {
- if (!this.credentials.id_token || !this.credentials.expiry_date || this.isTokenExpiring()) {
- const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);
- this.credentials = {
- id_token: idToken,
- expiry_date: this.getIdTokenExpiryDate(idToken)
- };
- }
- const headers = {
- Authorization: "Bearer " + this.credentials.id_token
- };
- return { headers };
- }
- getIdTokenExpiryDate(idToken) {
- const payloadB64 = idToken.split(".")[1];
- if (payloadB64) {
- const payload = JSON.parse(Buffer.from(payloadB64, "base64").toString("ascii"));
- return payload.exp * 1000;
- }
- }
- }
- exports.IdTokenClient = IdTokenClient;
-});
-
-// node_modules/google-auth-library/build/src/auth/envDetect.js
-var require_envDetect = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.GCPEnv = undefined;
- exports.clear = clear;
- exports.getEnv = getEnv3;
- var gcpMetadata = require_src4();
- var GCPEnv;
- (function(GCPEnv2) {
- GCPEnv2["APP_ENGINE"] = "APP_ENGINE";
- GCPEnv2["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE";
- GCPEnv2["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS";
- GCPEnv2["COMPUTE_ENGINE"] = "COMPUTE_ENGINE";
- GCPEnv2["CLOUD_RUN"] = "CLOUD_RUN";
- GCPEnv2["NONE"] = "NONE";
- })(GCPEnv || (exports.GCPEnv = GCPEnv = {}));
- var envPromise;
- function clear() {
- envPromise = undefined;
- }
- async function getEnv3() {
- if (envPromise) {
- return envPromise;
- }
- envPromise = getEnvMemoized();
- return envPromise;
- }
- async function getEnvMemoized() {
- let env5 = GCPEnv.NONE;
- if (isAppEngine()) {
- env5 = GCPEnv.APP_ENGINE;
- } else if (isCloudFunction()) {
- env5 = GCPEnv.CLOUD_FUNCTIONS;
- } else if (await isComputeEngine()) {
- if (await isKubernetesEngine()) {
- env5 = GCPEnv.KUBERNETES_ENGINE;
- } else if (isCloudRun()) {
- env5 = GCPEnv.CLOUD_RUN;
- } else {
- env5 = GCPEnv.COMPUTE_ENGINE;
- }
- } else {
- env5 = GCPEnv.NONE;
- }
- return env5;
- }
- function isAppEngine() {
- return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);
- }
- function isCloudFunction() {
- return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET);
- }
- function isCloudRun() {
- return !!process.env.K_CONFIGURATION;
- }
- async function isKubernetesEngine() {
- try {
- await gcpMetadata.instance("attributes/cluster-name");
- return true;
- } catch (e4) {
- return false;
- }
- }
- async function isComputeEngine() {
- return gcpMetadata.isAvailable();
- }
-});
-
-// node_modules/gtoken/build/src/index.js
-var require_src5 = __commonJS((exports) => {
- var __classPrivateFieldGet9 = exports && exports.__classPrivateFieldGet || function(receiver, state3, kind2, f4) {
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a getter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind2 === "m" ? f4 : kind2 === "a" ? f4.call(receiver) : f4 ? f4.value : state3.get(receiver);
- };
- var __classPrivateFieldSet9 = exports && exports.__classPrivateFieldSet || function(receiver, state3, value, kind2, f4) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a setter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return kind2 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state3.set(receiver, value), value;
- };
- var _GoogleToken_instances;
- var _GoogleToken_inFlightRequest;
- var _GoogleToken_getTokenAsync;
- var _GoogleToken_getTokenAsyncInner;
- var _GoogleToken_ensureEmail;
- var _GoogleToken_revokeTokenAsync;
- var _GoogleToken_configure;
- var _GoogleToken_requestToken;
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.GoogleToken = undefined;
- var fs9 = __require("fs");
- var gaxios_1 = require_src2();
- var jws = require_jws();
- var path14 = __require("path");
- var util_1 = __require("util");
- var readFile12 = fs9.readFile ? (0, util_1.promisify)(fs9.readFile) : async () => {
- throw new ErrorWithCode("use key rather than keyFile.", "MISSING_CREDENTIALS");
- };
- var GOOGLE_TOKEN_URL = "https://www.googleapis.com/oauth2/v4/token";
- var 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;
- }
- constructor(options2) {
- _GoogleToken_instances.add(this);
- this.transporter = {
- request: (opts) => (0, gaxios_1.request)(opts)
- };
- _GoogleToken_inFlightRequest.set(this, undefined);
- __classPrivateFieldGet9(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, options2);
- }
- hasExpired() {
- const now = new Date().getTime();
- if (this.rawToken && this.expiresAt) {
- return now >= this.expiresAt;
- } else {
- return true;
- }
- }
- isTokenExpiring() {
- var _a8;
- const now = new Date().getTime();
- const eagerRefreshThresholdMillis = (_a8 = this.eagerRefreshThresholdMillis) !== null && _a8 !== undefined ? _a8 : 0;
- if (this.rawToken && this.expiresAt) {
- return this.expiresAt <= now + eagerRefreshThresholdMillis;
- } else {
- return true;
- }
- }
- getToken(callback, opts = {}) {
- if (typeof callback === "object") {
- opts = callback;
- callback = undefined;
- }
- opts = Object.assign({
- forceRefresh: false
- }, opts);
- if (callback) {
- const cb = callback;
- __classPrivateFieldGet9(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts).then((t4) => cb(null, t4), callback);
- return;
- }
- return __classPrivateFieldGet9(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts);
- }
- async getCredentials(keyFile) {
- const ext = path14.extname(keyFile);
- switch (ext) {
- case ".json": {
- const key = await readFile12(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 readFile12(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");
- }
- }
- revokeToken(callback) {
- if (callback) {
- __classPrivateFieldGet9(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this).then(() => callback(), callback);
- return;
- }
- return __classPrivateFieldGet9(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this);
- }
- }
- exports.GoogleToken = GoogleToken;
- _GoogleToken_inFlightRequest = new WeakMap, _GoogleToken_instances = new WeakSet, _GoogleToken_getTokenAsync = async function _GoogleToken_getTokenAsync2(opts) {
- if (__classPrivateFieldGet9(this, _GoogleToken_inFlightRequest, "f") && !opts.forceRefresh) {
- return __classPrivateFieldGet9(this, _GoogleToken_inFlightRequest, "f");
- }
- try {
- return await __classPrivateFieldSet9(this, _GoogleToken_inFlightRequest, __classPrivateFieldGet9(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsyncInner).call(this, opts), "f");
- } finally {
- __classPrivateFieldSet9(this, _GoogleToken_inFlightRequest, undefined, "f");
- }
- }, _GoogleToken_getTokenAsyncInner = async function _GoogleToken_getTokenAsyncInner2(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) {
- __classPrivateFieldGet9(this, _GoogleToken_instances, "m", _GoogleToken_ensureEmail).call(this);
- }
- }
- return __classPrivateFieldGet9(this, _GoogleToken_instances, "m", _GoogleToken_requestToken).call(this);
- }, _GoogleToken_ensureEmail = function _GoogleToken_ensureEmail2() {
- if (!this.iss) {
- throw new ErrorWithCode("email is required.", "MISSING_CREDENTIALS");
- }
- }, _GoogleToken_revokeTokenAsync = async function _GoogleToken_revokeTokenAsync2() {
- if (!this.accessToken) {
- throw new Error("No token to revoke.");
- }
- const url3 = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;
- await this.transporter.request({
- url: url3,
- retry: true
- });
- __classPrivateFieldGet9(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_configure2(options2 = {}) {
- this.keyFile = options2.keyFile;
- this.key = options2.key;
- this.rawToken = undefined;
- this.iss = options2.email || options2.iss;
- this.sub = options2.sub;
- this.additionalClaims = options2.additionalClaims;
- if (typeof options2.scope === "object") {
- this.scope = options2.scope.join(" ");
- } else {
- this.scope = options2.scope;
- }
- this.eagerRefreshThresholdMillis = options2.eagerRefreshThresholdMillis;
- if (options2.transporter) {
- this.transporter = options2.transporter;
- }
- }, _GoogleToken_requestToken = async function _GoogleToken_requestToken2() {
- var _a8, _b2;
- 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 r4 = 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 = r4.data;
- this.expiresAt = r4.data.expires_in === null || r4.data.expires_in === undefined ? undefined : (iat + r4.data.expires_in) * 1000;
- return this.rawToken;
- } catch (e4) {
- this.rawToken = undefined;
- this.tokenExpires = undefined;
- const body = e4.response && ((_a8 = e4.response) === null || _a8 === undefined ? undefined : _a8.data) ? (_b2 = e4.response) === null || _b2 === undefined ? undefined : _b2.data : {};
- if (body.error) {
- const desc = body.error_description ? `: ${body.error_description}` : "";
- e4.message = `${body.error}${desc}`;
- }
- throw e4;
- }
- };
-});
-
-// node_modules/google-auth-library/build/src/auth/jwtaccess.js
-var require_jwtaccess = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.JWTAccess = undefined;
- var jws = require_jws();
- var util_1 = require_util2();
- var DEFAULT_HEADER = {
- alg: "RS256",
- typ: "JWT"
- };
-
- class JWTAccess {
- constructor(email3, key, keyId, eagerRefreshThresholdMillis) {
- this.cache = new util_1.LRUCache({
- capacity: 500,
- maxAge: 60 * 60 * 1000
- });
- this.email = email3;
- this.key = key;
- this.keyId = keyId;
- this.eagerRefreshThresholdMillis = eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== undefined ? eagerRefreshThresholdMillis : 5 * 60 * 1000;
- }
- getCachedKey(url3, scopes) {
- let cacheKey = url3;
- if (scopes && Array.isArray(scopes) && scopes.length) {
- cacheKey = url3 ? `${url3}_${scopes.join("_")}` : `${scopes.join("_")}`;
- } else if (typeof scopes === "string") {
- cacheKey = url3 ? `${url3}_${scopes}` : scopes;
- }
- if (!cacheKey) {
- throw Error("Scopes or url must be provided");
- }
- return cacheKey;
- }
- getRequestHeaders(url3, additionalClaims, scopes) {
- const key = this.getCachedKey(url3, scopes);
- const cachedToken = this.cache.get(key);
- const now = Date.now();
- if (cachedToken && cachedToken.expiration - now > this.eagerRefreshThresholdMillis) {
- return cachedToken.headers;
- }
- const iat = Math.floor(Date.now() / 1000);
- const exp = JWTAccess.getExpirationTime(iat);
- let defaultClaims;
- if (Array.isArray(scopes)) {
- scopes = scopes.join(" ");
- }
- if (scopes) {
- defaultClaims = {
- iss: this.email,
- sub: this.email,
- scope: scopes,
- exp,
- iat
- };
- } else {
- defaultClaims = {
- iss: this.email,
- sub: this.email,
- aud: url3,
- exp,
- iat
- };
- }
- if (additionalClaims) {
- for (const claim in defaultClaims) {
- if (additionalClaims[claim]) {
- throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`);
- }
- }
- }
- const header = this.keyId ? { ...DEFAULT_HEADER, kid: this.keyId } : DEFAULT_HEADER;
- const payload = Object.assign(defaultClaims, additionalClaims);
- const signedJWT = jws.sign({ header, payload, secret: this.key });
- const headers = { Authorization: `Bearer ${signedJWT}` };
- this.cache.set(key, {
- expiration: exp * 1000,
- headers
- });
- return headers;
- }
- static getExpirationTime(iat) {
- const exp = iat + 3600;
- return exp;
- }
- fromJSON(json2) {
- if (!json2) {
- throw new Error("Must pass in a JSON object containing the service account auth settings.");
- }
- if (!json2.client_email) {
- throw new Error("The incoming JSON object does not contain a client_email field");
- }
- if (!json2.private_key) {
- throw new Error("The incoming JSON object does not contain a private_key field");
- }
- this.email = json2.client_email;
- this.key = json2.private_key;
- this.keyId = json2.private_key_id;
- this.projectId = json2.project_id;
- }
- fromStream(inputStream, callback) {
- if (callback) {
- this.fromStreamAsync(inputStream).then(() => callback(), callback);
- } else {
- return this.fromStreamAsync(inputStream);
- }
- }
- fromStreamAsync(inputStream) {
- return new Promise((resolve9, reject) => {
- if (!inputStream) {
- reject(new Error("Must pass in a stream containing the service account auth settings."));
- }
- let s4 = "";
- inputStream.setEncoding("utf8").on("data", (chunk) => s4 += chunk).on("error", reject).on("end", () => {
- try {
- const data = JSON.parse(s4);
- this.fromJSON(data);
- resolve9();
- } catch (err) {
- reject(err);
- }
- });
- });
- }
- }
- exports.JWTAccess = JWTAccess;
-});
-
-// node_modules/google-auth-library/build/src/auth/jwtclient.js
-var require_jwtclient = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.JWT = undefined;
- var gtoken_1 = require_src5();
- var jwtaccess_1 = require_jwtaccess();
- var oauth2client_1 = require_oauth2client();
- var authclient_1 = require_authclient();
-
- class JWT extends oauth2client_1.OAuth2Client {
- constructor(optionsOrEmail, keyFile, key, scopes, subject, keyId) {
- const opts = optionsOrEmail && typeof optionsOrEmail === "object" ? optionsOrEmail : { email: optionsOrEmail, keyFile, key, keyId, scopes, subject };
- super(opts);
- this.email = opts.email;
- this.keyFile = opts.keyFile;
- this.key = opts.key;
- this.keyId = opts.keyId;
- this.scopes = opts.scopes;
- this.subject = opts.subject;
- this.additionalClaims = opts.additionalClaims;
- this.credentials = { refresh_token: "jwt-placeholder", expiry_date: 1 };
- }
- createScoped(scopes) {
- const jwt3 = new JWT(this);
- jwt3.scopes = scopes;
- return jwt3;
- }
- async getRequestMetadataAsync(url3) {
- url3 = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url3;
- const useSelfSignedJWT = !this.hasUserScopes() && url3 || this.useJWTAccessWithScope && this.hasAnyScopes() || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;
- if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) {
- throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`);
- }
- if (!this.apiKey && useSelfSignedJWT) {
- if (this.additionalClaims && this.additionalClaims.target_audience) {
- const { tokens } = await this.refreshToken();
- return {
- headers: this.addSharedMetadataHeaders({
- Authorization: `Bearer ${tokens.id_token}`
- })
- };
- } else {
- if (!this.access) {
- this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis);
- }
- let scopes;
- if (this.hasUserScopes()) {
- scopes = this.scopes;
- } else if (!url3) {
- scopes = this.defaultScopes;
- }
- const useScopes = this.useJWTAccessWithScope || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;
- const headers = await this.access.getRequestHeaders(url3 !== null && url3 !== undefined ? url3 : undefined, this.additionalClaims, useScopes ? scopes : undefined);
- return { headers: this.addSharedMetadataHeaders(headers) };
- }
- } else if (this.hasAnyScopes() || this.apiKey) {
- return super.getRequestMetadataAsync(url3);
- } else {
- return { headers: {} };
- }
- }
- async fetchIdToken(targetAudience) {
- const gtoken = new gtoken_1.GoogleToken({
- iss: this.email,
- sub: this.subject,
- scope: this.scopes || this.defaultScopes,
- keyFile: this.keyFile,
- key: this.key,
- additionalClaims: { target_audience: targetAudience },
- transporter: this.transporter
- });
- await gtoken.getToken({
- forceRefresh: true
- });
- if (!gtoken.idToken) {
- throw new Error("Unknown error: Failed to fetch ID token");
- }
- return gtoken.idToken;
- }
- hasUserScopes() {
- if (!this.scopes) {
- return false;
- }
- return this.scopes.length > 0;
- }
- hasAnyScopes() {
- if (this.scopes && this.scopes.length > 0)
- return true;
- if (this.defaultScopes && this.defaultScopes.length > 0)
- return true;
- return false;
- }
- authorize(callback) {
- if (callback) {
- this.authorizeAsync().then((r4) => callback(null, r4), callback);
- } else {
- return this.authorizeAsync();
- }
- }
- async authorizeAsync() {
- const result = await this.refreshToken();
- if (!result) {
- throw new Error("No result returned");
- }
- this.credentials = result.tokens;
- this.credentials.refresh_token = "jwt-placeholder";
- this.key = this.gtoken.key;
- this.email = this.gtoken.iss;
- return result.tokens;
- }
- async refreshTokenNoCache(refreshToken) {
- const gtoken = this.createGToken();
- const token = await gtoken.getToken({
- forceRefresh: this.isTokenExpiring()
- });
- const tokens = {
- access_token: token.access_token,
- token_type: "Bearer",
- expiry_date: gtoken.expiresAt,
- id_token: gtoken.idToken
- };
- this.emit("tokens", tokens);
- return { res: null, tokens };
- }
- createGToken() {
- if (!this.gtoken) {
- this.gtoken = new gtoken_1.GoogleToken({
- iss: this.email,
- sub: this.subject,
- scope: this.scopes || this.defaultScopes,
- keyFile: this.keyFile,
- key: this.key,
- additionalClaims: this.additionalClaims,
- transporter: this.transporter
- });
- }
- return this.gtoken;
- }
- fromJSON(json2) {
- if (!json2) {
- throw new Error("Must pass in a JSON object containing the service account auth settings.");
- }
- if (!json2.client_email) {
- throw new Error("The incoming JSON object does not contain a client_email field");
- }
- if (!json2.private_key) {
- throw new Error("The incoming JSON object does not contain a private_key field");
- }
- this.email = json2.client_email;
- this.key = json2.private_key;
- this.keyId = json2.private_key_id;
- this.projectId = json2.project_id;
- this.quotaProjectId = json2.quota_project_id;
- this.universeDomain = json2.universe_domain || this.universeDomain;
- }
- fromStream(inputStream, callback) {
- if (callback) {
- this.fromStreamAsync(inputStream).then(() => callback(), callback);
- } else {
- return this.fromStreamAsync(inputStream);
- }
- }
- fromStreamAsync(inputStream) {
- return new Promise((resolve9, reject) => {
- if (!inputStream) {
- throw new Error("Must pass in a stream containing the service account auth settings.");
- }
- let s4 = "";
- inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s4 += chunk).on("end", () => {
- try {
- const data = JSON.parse(s4);
- this.fromJSON(data);
- resolve9();
- } catch (e4) {
- reject(e4);
- }
- });
- });
- }
- fromAPIKey(apiKey) {
- if (typeof apiKey !== "string") {
- throw new Error("Must provide an API Key string.");
- }
- this.apiKey = apiKey;
- }
- async getCredentials() {
- if (this.key) {
- return { private_key: this.key, client_email: this.email };
- } else if (this.keyFile) {
- const gtoken = this.createGToken();
- const creds = await gtoken.getCredentials(this.keyFile);
- return { private_key: creds.privateKey, client_email: creds.clientEmail };
- }
- throw new Error("A key or a keyFile must be provided to getCredentials.");
- }
- }
- exports.JWT = JWT;
-});
-
-// node_modules/google-auth-library/build/src/auth/refreshclient.js
-var require_refreshclient = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = undefined;
- var oauth2client_1 = require_oauth2client();
- var querystring_1 = __require("querystring");
- 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;
- }
- async refreshTokenNoCache(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;
- }
- fromJSON(json2) {
- if (!json2) {
- throw new Error("Must pass in a JSON object containing the user refresh token");
- }
- if (json2.type !== "authorized_user") {
- throw new Error('The incoming JSON object does not have the "authorized_user" type');
- }
- if (!json2.client_id) {
- throw new Error("The incoming JSON object does not contain a client_id field");
- }
- if (!json2.client_secret) {
- throw new Error("The incoming JSON object does not contain a client_secret field");
- }
- if (!json2.refresh_token) {
- throw new Error("The incoming JSON object does not contain a refresh_token field");
- }
- this._clientId = json2.client_id;
- this._clientSecret = json2.client_secret;
- this._refreshToken = json2.refresh_token;
- this.credentials.refresh_token = json2.refresh_token;
- this.quotaProjectId = json2.quota_project_id;
- this.universeDomain = json2.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((resolve9, reject) => {
- if (!inputStream) {
- return reject(new Error("Must pass in a stream containing the user refresh token."));
- }
- let s4 = "";
- inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s4 += chunk).on("end", () => {
- try {
- const data = JSON.parse(s4);
- this.fromJSON(data);
- return resolve9();
- } catch (err) {
- return reject(err);
- }
- });
- });
- }
- static fromJSON(json2) {
- const client14 = new UserRefreshClient;
- client14.fromJSON(json2);
- return client14;
- }
- }
- exports.UserRefreshClient = UserRefreshClient;
-});
-
-// node_modules/google-auth-library/build/src/auth/impersonated.js
-var require_impersonated = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = undefined;
- var oauth2client_1 = require_oauth2client();
- var gaxios_1 = require_src2();
- var util_1 = require_util2();
- exports.IMPERSONATED_ACCOUNT_TYPE = "impersonated_service_account";
-
- class Impersonated extends oauth2client_1.OAuth2Client {
- constructor(options2 = {}) {
- var _a8, _b2, _c4, _d3, _e4, _f3;
- super(options2);
- this.credentials = {
- expiry_date: 1,
- refresh_token: "impersonated-placeholder"
- };
- this.sourceClient = (_a8 = options2.sourceClient) !== null && _a8 !== undefined ? _a8 : new oauth2client_1.OAuth2Client;
- this.targetPrincipal = (_b2 = options2.targetPrincipal) !== null && _b2 !== undefined ? _b2 : "";
- this.delegates = (_c4 = options2.delegates) !== null && _c4 !== undefined ? _c4 : [];
- this.targetScopes = (_d3 = options2.targetScopes) !== null && _d3 !== undefined ? _d3 : [];
- this.lifetime = (_e4 = options2.lifetime) !== null && _e4 !== undefined ? _e4 : 3600;
- const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options2).get("universe_domain");
- if (!usingExplicitUniverseDomain) {
- this.universeDomain = this.sourceClient.universeDomain;
- } else if (this.sourceClient.universeDomain !== this.universeDomain) {
- throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);
- }
- this.endpoint = (_f3 = options2.endpoint) !== null && _f3 !== undefined ? _f3 : `https://iamcredentials.${this.universeDomain}`;
- }
- async sign(blobToSign) {
- await this.sourceClient.getAccessToken();
- const name3 = `projects/-/serviceAccounts/${this.targetPrincipal}`;
- const u5 = `${this.endpoint}/v1/${name3}:signBlob`;
- const body = {
- delegates: this.delegates,
- payload: Buffer.from(blobToSign).toString("base64")
- };
- const res = await this.sourceClient.request({
- ...Impersonated.RETRY_CONFIG,
- url: u5,
- data: body,
- method: "POST"
- });
- return res.data;
- }
- getTargetPrincipal() {
- return this.targetPrincipal;
- }
- async refreshToken() {
- var _a8, _b2, _c4, _d3, _e4, _f3;
- try {
- await this.sourceClient.getAccessToken();
- const name3 = "projects/-/serviceAccounts/" + this.targetPrincipal;
- const u5 = `${this.endpoint}/v1/${name3}:generateAccessToken`;
- const body = {
- delegates: this.delegates,
- scope: this.targetScopes,
- lifetime: this.lifetime + "s"
- };
- const res = await this.sourceClient.request({
- ...Impersonated.RETRY_CONFIG,
- url: u5,
- data: body,
- method: "POST"
- });
- const tokenResponse = res.data;
- this.credentials.access_token = tokenResponse.accessToken;
- this.credentials.expiry_date = Date.parse(tokenResponse.expireTime);
- return {
- tokens: this.credentials,
- res
- };
- } catch (error45) {
- if (!(error45 instanceof Error))
- throw error45;
- let status = 0;
- let message = "";
- if (error45 instanceof gaxios_1.GaxiosError) {
- status = (_c4 = (_b2 = (_a8 = error45 === null || error45 === undefined ? undefined : error45.response) === null || _a8 === undefined ? undefined : _a8.data) === null || _b2 === undefined ? undefined : _b2.error) === null || _c4 === undefined ? undefined : _c4.status;
- message = (_f3 = (_e4 = (_d3 = error45 === null || error45 === undefined ? undefined : error45.response) === null || _d3 === undefined ? undefined : _d3.data) === null || _e4 === undefined ? undefined : _e4.error) === null || _f3 === undefined ? undefined : _f3.message;
- }
- if (status && message) {
- error45.message = `${status}: unable to impersonate: ${message}`;
- throw error45;
- } else {
- error45.message = `unable to impersonate: ${error45}`;
- throw error45;
- }
- }
- }
- async fetchIdToken(targetAudience, options2) {
- var _a8, _b2;
- await this.sourceClient.getAccessToken();
- const name3 = `projects/-/serviceAccounts/${this.targetPrincipal}`;
- const u5 = `${this.endpoint}/v1/${name3}:generateIdToken`;
- const body = {
- delegates: this.delegates,
- audience: targetAudience,
- includeEmail: (_a8 = options2 === null || options2 === undefined ? undefined : options2.includeEmail) !== null && _a8 !== undefined ? _a8 : true,
- useEmailAzp: (_b2 = options2 === null || options2 === undefined ? undefined : options2.includeEmail) !== null && _b2 !== undefined ? _b2 : true
- };
- const res = await this.sourceClient.request({
- ...Impersonated.RETRY_CONFIG,
- url: u5,
- data: body,
- method: "POST"
- });
- return res.data.token;
- }
- }
- exports.Impersonated = Impersonated;
-});
-
-// node_modules/google-auth-library/build/src/auth/oauth2common.js
-var require_oauth2common = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.OAuthClientAuthHandler = undefined;
- exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse;
- var querystring = __require("querystring");
- var crypto_1 = require_crypto3();
- var METHODS_SUPPORTING_REQUEST_BODY = ["PUT", "POST", "PATCH"];
-
- class OAuthClientAuthHandler {
- constructor(clientAuthentication) {
- this.clientAuthentication = clientAuthentication;
- this.crypto = (0, crypto_1.createCrypto)();
- }
- applyClientAuthenticationOptions(opts, bearerToken) {
- this.injectAuthenticatedHeaders(opts, bearerToken);
- if (!bearerToken) {
- this.injectAuthenticatedRequestBody(opts);
- }
- }
- injectAuthenticatedHeaders(opts, bearerToken) {
- var _a8;
- if (bearerToken) {
- opts.headers = opts.headers || {};
- Object.assign(opts.headers, {
- Authorization: `Bearer ${bearerToken}}`
- });
- } else if (((_a8 = this.clientAuthentication) === null || _a8 === undefined ? undefined : _a8.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}`
- });
- }
- }
- injectAuthenticatedRequestBody(opts) {
- var _a8;
- if (((_a8 = this.clientAuthentication) === null || _a8 === undefined ? undefined : _a8.confidentialClientType) === "request-body") {
- const method = (opts.method || "GET").toUpperCase();
- if (METHODS_SUPPORTING_REQUEST_BODY.indexOf(method) !== -1) {
- let contentType;
- const headers = opts.headers || {};
- for (const key in headers) {
- if (key.toLowerCase() === "content-type" && headers[key]) {
- contentType = headers[key].toLowerCase();
- break;
- }
- }
- 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(`${contentType} content-types are not supported with ` + `${this.clientAuthentication.confidentialClientType} ` + "client authentication");
- }
- } else {
- throw new Error(`${method} HTTP method does not support ` + `${this.clientAuthentication.confidentialClientType} ` + "client authentication");
- }
- }
- }
- static get RETRY_CONFIG() {
- return {
- retry: true,
- retryConfig: {
- httpMethodsToRetry: ["GET", "PUT", "POST", "HEAD", "OPTIONS", "DELETE"]
- }
- };
- }
- }
- exports.OAuthClientAuthHandler = OAuthClientAuthHandler;
- function getErrorFromOAuthErrorResponse(resp, err) {
- 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);
- if (err) {
- const keys2 = Object.keys(err);
- if (err.stack) {
- keys2.push("stack");
- }
- keys2.forEach((key) => {
- if (key !== "message") {
- Object.defineProperty(newError, key, {
- value: err[key],
- writable: false,
- enumerable: true
- });
- }
- });
- }
- return newError;
- }
-});
-
-// node_modules/google-auth-library/build/src/auth/stscredentials.js
-var require_stscredentials = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.StsCredentials = undefined;
- var gaxios_1 = require_src2();
- var querystring = __require("querystring");
- var transporters_1 = require_transporters();
- var oauth2common_1 = require_oauth2common();
-
- class StsCredentials extends oauth2common_1.OAuthClientAuthHandler {
- constructor(tokenExchangeEndpoint, clientAuthentication) {
- super(clientAuthentication);
- this.tokenExchangeEndpoint = tokenExchangeEndpoint;
- this.transporter = new transporters_1.DefaultTransporter;
- }
- async exchangeToken(stsCredentialsOptions, additionalHeaders, options2) {
- var _a8, _b2, _c4;
- const values2 = {
- grant_type: stsCredentialsOptions.grantType,
- resource: stsCredentialsOptions.resource,
- audience: stsCredentialsOptions.audience,
- scope: (_a8 = stsCredentialsOptions.scope) === null || _a8 === undefined ? undefined : _a8.join(" "),
- requested_token_type: stsCredentialsOptions.requestedTokenType,
- subject_token: stsCredentialsOptions.subjectToken,
- subject_token_type: stsCredentialsOptions.subjectTokenType,
- actor_token: (_b2 = stsCredentialsOptions.actingParty) === null || _b2 === undefined ? undefined : _b2.actorToken,
- actor_token_type: (_c4 = stsCredentialsOptions.actingParty) === null || _c4 === undefined ? undefined : _c4.actorTokenType,
- options: options2 && JSON.stringify(options2)
- };
- Object.keys(values2).forEach((key) => {
- if (typeof values2[key] === "undefined") {
- delete values2[key];
- }
- });
- const headers = {
- "Content-Type": "application/x-www-form-urlencoded"
- };
- Object.assign(headers, additionalHeaders || {});
- const opts = {
- ...StsCredentials.RETRY_CONFIG,
- url: this.tokenExchangeEndpoint.toString(),
- method: "POST",
- headers,
- data: querystring.stringify(values2),
- responseType: "json"
- };
- this.applyClientAuthenticationOptions(opts);
- try {
- const response7 = await this.transporter.request(opts);
- const stsSuccessfulResponse = response7.data;
- stsSuccessfulResponse.res = response7;
- return stsSuccessfulResponse;
- } catch (error45) {
- if (error45 instanceof gaxios_1.GaxiosError && error45.response) {
- throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error45.response.data, error45);
- }
- throw error45;
- }
- }
- }
- exports.StsCredentials = StsCredentials;
-});
-
-// node_modules/google-auth-library/build/src/auth/baseexternalclient.js
-var require_baseexternalclient = __commonJS((exports) => {
- var __classPrivateFieldGet9 = exports && exports.__classPrivateFieldGet || function(receiver, state3, kind2, f4) {
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a getter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind2 === "m" ? f4 : kind2 === "a" ? f4.call(receiver) : f4 ? f4.value : state3.get(receiver);
- };
- var __classPrivateFieldSet9 = exports && exports.__classPrivateFieldSet || function(receiver, state3, value, kind2, f4) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a setter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return kind2 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state3.set(receiver, value), value;
- };
- var _BaseExternalAccountClient_instances;
- var _BaseExternalAccountClient_pendingAccessToken;
- var _BaseExternalAccountClient_internalRefreshAccessTokenAsync;
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.BaseExternalAccountClient = exports.DEFAULT_UNIVERSE = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = undefined;
- var stream10 = __require("stream");
- var authclient_1 = require_authclient();
- var sts = require_stscredentials();
- var util_1 = require_util2();
- var STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
- var STS_REQUEST_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
- var DEFAULT_OAUTH_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
- var DEFAULT_TOKEN_LIFESPAN = 3600;
- exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;
- exports.EXTERNAL_ACCOUNT_TYPE = "external_account";
- exports.CLOUD_RESOURCE_MANAGER = "https://cloudresourcemanager.googleapis.com/v1/projects/";
- var WORKFORCE_AUDIENCE_PATTERN = "//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+";
- var DEFAULT_TOKEN_URL = "https://sts.{universeDomain}/v1/token";
- var pkg = require_package3();
- var authclient_2 = require_authclient();
- Object.defineProperty(exports, "DEFAULT_UNIVERSE", { enumerable: true, get: function() {
- return authclient_2.DEFAULT_UNIVERSE;
- } });
-
- class BaseExternalAccountClient extends authclient_1.AuthClient {
- constructor(options2, additionalOptions) {
- var _a8;
- super({ ...options2, ...additionalOptions });
- _BaseExternalAccountClient_instances.add(this);
- _BaseExternalAccountClient_pendingAccessToken.set(this, null);
- const opts = (0, util_1.originalOrCamelOptions)(options2);
- const type = opts.get("type");
- if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) {
- throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` + `received "${options2.type}"`);
- }
- const clientId = opts.get("client_id");
- const clientSecret = opts.get("client_secret");
- const tokenUrl = (_a8 = opts.get("token_url")) !== null && _a8 !== undefined ? _a8 : DEFAULT_TOKEN_URL.replace("{universeDomain}", this.universeDomain);
- const subjectTokenType = opts.get("subject_token_type");
- const workforcePoolUserProject = opts.get("workforce_pool_user_project");
- const serviceAccountImpersonationUrl = opts.get("service_account_impersonation_url");
- const serviceAccountImpersonation = opts.get("service_account_impersonation");
- const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get("token_lifetime_seconds");
- this.cloudResourceManagerURL = new URL(opts.get("cloud_resource_manager_url") || `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`);
- if (clientId) {
- this.clientAuth = {
- confidentialClientType: "basic",
- clientId,
- clientSecret
- };
- }
- this.stsCredential = new sts.StsCredentials(tokenUrl, this.clientAuth);
- this.scopes = opts.get("scopes") || [DEFAULT_OAUTH_SCOPE];
- this.cachedAccessToken = null;
- this.audience = opts.get("audience");
- this.subjectTokenType = subjectTokenType;
- this.workforcePoolUserProject = workforcePoolUserProject;
- const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN);
- if (this.workforcePoolUserProject && !this.audience.match(workforceAudiencePattern)) {
- throw new Error("workforcePoolUserProject should not be set for non-workforce pool " + "credentials.");
- }
- this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl;
- this.serviceAccountImpersonationLifetime = serviceAccountImpersonationLifetime;
- if (this.serviceAccountImpersonationLifetime) {
- this.configLifetimeRequested = true;
- } else {
- this.configLifetimeRequested = false;
- this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN;
- }
- this.projectNumber = this.getProjectNumber(this.audience);
- this.supplierContext = {
- audience: this.audience,
- subjectTokenType: this.subjectTokenType,
- transporter: this.transporter
- };
- }
- getServiceAccountEmail() {
- var _a8;
- if (this.serviceAccountImpersonationUrl) {
- if (this.serviceAccountImpersonationUrl.length > 256) {
- throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);
- }
- const re = /serviceAccounts\/(?[^:]+):generateAccessToken$/;
- const result = re.exec(this.serviceAccountImpersonationUrl);
- return ((_a8 = result === null || result === undefined ? undefined : result.groups) === null || _a8 === undefined ? undefined : _a8.email) || null;
- }
- return null;
- }
- setCredentials(credentials) {
- super.setCredentials(credentials);
- this.cachedAccessToken = credentials;
- }
- async getAccessToken() {
- if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {
- await this.refreshAccessTokenAsync();
- }
- return {
- token: this.cachedAccessToken.access_token,
- res: this.cachedAccessToken.res
- };
- }
- async getRequestHeaders() {
- const accessTokenResponse = await this.getAccessToken();
- const headers = {
- Authorization: `Bearer ${accessTokenResponse.token}`
- };
- return this.addSharedMetadataHeaders(headers);
- }
- request(opts, callback) {
- if (callback) {
- this.requestAsync(opts).then((r4) => callback(null, r4), (e4) => {
- return callback(e4, e4.response);
- });
- } else {
- return this.requestAsync(opts);
- }
- }
- async getProjectId() {
- const projectNumber = this.projectNumber || this.workforcePoolUserProject;
- if (this.projectId) {
- return this.projectId;
- } else if (projectNumber) {
- const headers = await this.getRequestHeaders();
- const response7 = await this.transporter.request({
- ...BaseExternalAccountClient.RETRY_CONFIG,
- headers,
- url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`,
- responseType: "json"
- });
- this.projectId = response7.data.projectId;
- return this.projectId;
- }
- return null;
- }
- async requestAsync(opts, reAuthRetried = false) {
- let response7;
- try {
- const requestHeaders = await this.getRequestHeaders();
- opts.headers = opts.headers || {};
- if (requestHeaders && requestHeaders["x-goog-user-project"]) {
- opts.headers["x-goog-user-project"] = requestHeaders["x-goog-user-project"];
- }
- if (requestHeaders && requestHeaders.Authorization) {
- opts.headers.Authorization = requestHeaders.Authorization;
- }
- response7 = await this.transporter.request(opts);
- } catch (e4) {
- const res = e4.response;
- if (res) {
- const statusCode = res.status;
- const isReadableStream5 = res.config.data instanceof stream10.Readable;
- const isAuthErr = statusCode === 401 || statusCode === 403;
- if (!reAuthRetried && isAuthErr && !isReadableStream5 && this.forceRefreshOnFailure) {
- await this.refreshAccessTokenAsync();
- return await this.requestAsync(opts, true);
- }
- }
- throw e4;
- }
- return response7;
- }
- async refreshAccessTokenAsync() {
- __classPrivateFieldSet9(this, _BaseExternalAccountClient_pendingAccessToken, __classPrivateFieldGet9(this, _BaseExternalAccountClient_pendingAccessToken, "f") || __classPrivateFieldGet9(this, _BaseExternalAccountClient_instances, "m", _BaseExternalAccountClient_internalRefreshAccessTokenAsync).call(this), "f");
- try {
- return await __classPrivateFieldGet9(this, _BaseExternalAccountClient_pendingAccessToken, "f");
- } finally {
- __classPrivateFieldSet9(this, _BaseExternalAccountClient_pendingAccessToken, null, "f");
- }
- }
- getProjectNumber(audience) {
- const match = audience.match(/\/projects\/([^/]+)/);
- if (!match) {
- return null;
- }
- return match[1];
- }
- async getImpersonatedAccessToken(token) {
- const opts = {
- ...BaseExternalAccountClient.RETRY_CONFIG,
- url: this.serviceAccountImpersonationUrl,
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${token}`
- },
- data: {
- scope: this.getScopesArray(),
- lifetime: this.serviceAccountImpersonationLifetime + "s"
- },
- responseType: "json"
- };
- const response7 = await this.transporter.request(opts);
- const successResponse = response7.data;
- return {
- access_token: successResponse.accessToken,
- expiry_date: new Date(successResponse.expireTime).getTime(),
- res: response7
- };
- }
- isExpired(accessToken) {
- const now = new Date().getTime();
- return accessToken.expiry_date ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis : false;
- }
- getScopesArray() {
- if (typeof this.scopes === "string") {
- return [this.scopes];
- }
- return this.scopes || [DEFAULT_OAUTH_SCOPE];
- }
- getMetricsHeaderValue() {
- const nodeVersion = process.version.replace(/^v/, "");
- const saImpersonation = this.serviceAccountImpersonationUrl !== undefined;
- const credentialSourceType = this.credentialSourceType ? this.credentialSourceType : "unknown";
- return `gl-node/${nodeVersion} auth/${pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`;
- }
- }
- exports.BaseExternalAccountClient = BaseExternalAccountClient;
- _BaseExternalAccountClient_pendingAccessToken = new WeakMap, _BaseExternalAccountClient_instances = new WeakSet, _BaseExternalAccountClient_internalRefreshAccessTokenAsync = async function _BaseExternalAccountClient_internalRefreshAccessTokenAsync2() {
- const subjectToken = await this.retrieveSubjectToken();
- const stsCredentialsOptions = {
- grantType: STS_GRANT_TYPE,
- audience: this.audience,
- requestedTokenType: STS_REQUEST_TOKEN_TYPE,
- subjectToken,
- subjectTokenType: this.subjectTokenType,
- scope: this.serviceAccountImpersonationUrl ? [DEFAULT_OAUTH_SCOPE] : this.getScopesArray()
- };
- const additionalOptions = !this.clientAuth && this.workforcePoolUserProject ? { userProject: this.workforcePoolUserProject } : undefined;
- const additionalHeaders = {
- "x-goog-api-client": this.getMetricsHeaderValue()
- };
- const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions);
- if (this.serviceAccountImpersonationUrl) {
- this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token);
- } else if (stsResponse.expires_in) {
- this.cachedAccessToken = {
- access_token: stsResponse.access_token,
- expiry_date: new Date().getTime() + stsResponse.expires_in * 1000,
- res: stsResponse.res
- };
- } else {
- this.cachedAccessToken = {
- access_token: stsResponse.access_token,
- res: stsResponse.res
- };
- }
- this.credentials = {};
- Object.assign(this.credentials, this.cachedAccessToken);
- delete this.credentials.res;
- this.emit("tokens", {
- refresh_token: null,
- expiry_date: this.cachedAccessToken.expiry_date,
- access_token: this.cachedAccessToken.access_token,
- token_type: "Bearer",
- id_token: null
- });
- return this.cachedAccessToken;
- };
-});
-
-// node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js
-var require_filesubjecttokensupplier = __commonJS((exports) => {
- var _a8;
- var _b2;
- var _c4;
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.FileSubjectTokenSupplier = undefined;
- var util_1 = __require("util");
- var fs9 = __require("fs");
- var readFile12 = (0, util_1.promisify)((_a8 = fs9.readFile) !== null && _a8 !== undefined ? _a8 : () => {});
- var realpath4 = (0, util_1.promisify)((_b2 = fs9.realpath) !== null && _b2 !== undefined ? _b2 : () => {});
- var lstat = (0, util_1.promisify)((_c4 = fs9.lstat) !== null && _c4 !== undefined ? _c4 : () => {});
-
- class FileSubjectTokenSupplier {
- constructor(opts) {
- this.filePath = opts.filePath;
- this.formatType = opts.formatType;
- this.subjectTokenFieldName = opts.subjectTokenFieldName;
- }
- async getSubjectToken(context3) {
- let parsedFilePath = this.filePath;
- try {
- parsedFilePath = await realpath4(parsedFilePath);
- if (!(await lstat(parsedFilePath)).isFile()) {
- throw new Error;
- }
- } catch (err) {
- if (err instanceof Error) {
- err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`;
- }
- throw err;
- }
- let subjectToken;
- const rawText = await readFile12(parsedFilePath, { encoding: "utf8" });
- if (this.formatType === "text") {
- subjectToken = rawText;
- } else if (this.formatType === "json" && this.subjectTokenFieldName) {
- const json2 = JSON.parse(rawText);
- subjectToken = json2[this.subjectTokenFieldName];
- }
- if (!subjectToken) {
- throw new Error("Unable to parse the subject_token from the credential_source file");
- }
- return subjectToken;
- }
- }
- exports.FileSubjectTokenSupplier = FileSubjectTokenSupplier;
-});
-
-// node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js
-var require_urlsubjecttokensupplier = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.UrlSubjectTokenSupplier = undefined;
-
- class UrlSubjectTokenSupplier {
- constructor(opts) {
- this.url = opts.url;
- this.formatType = opts.formatType;
- this.subjectTokenFieldName = opts.subjectTokenFieldName;
- this.headers = opts.headers;
- this.additionalGaxiosOptions = opts.additionalGaxiosOptions;
- }
- async getSubjectToken(context3) {
- const opts = {
- ...this.additionalGaxiosOptions,
- url: this.url,
- method: "GET",
- headers: this.headers,
- responseType: this.formatType
- };
- let subjectToken;
- if (this.formatType === "text") {
- const response7 = await context3.transporter.request(opts);
- subjectToken = response7.data;
- } else if (this.formatType === "json" && this.subjectTokenFieldName) {
- const response7 = await context3.transporter.request(opts);
- subjectToken = response7.data[this.subjectTokenFieldName];
- }
- if (!subjectToken) {
- throw new Error("Unable to parse the subject_token from the credential_source URL");
- }
- return subjectToken;
- }
- }
- exports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier;
-});
-
-// node_modules/google-auth-library/build/src/auth/identitypoolclient.js
-var require_identitypoolclient = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.IdentityPoolClient = undefined;
- var baseexternalclient_1 = require_baseexternalclient();
- var util_1 = require_util2();
- var filesubjecttokensupplier_1 = require_filesubjecttokensupplier();
- var urlsubjecttokensupplier_1 = require_urlsubjecttokensupplier();
-
- class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient {
- constructor(options2, additionalOptions) {
- super(options2, additionalOptions);
- const opts = (0, util_1.originalOrCamelOptions)(options2);
- const credentialSource = opts.get("credential_source");
- const subjectTokenSupplier = opts.get("subject_token_supplier");
- if (!credentialSource && !subjectTokenSupplier) {
- throw new Error("A credential source or subject token supplier must be specified.");
- }
- if (credentialSource && subjectTokenSupplier) {
- throw new Error("Only one of credential source or subject token supplier can be specified.");
- }
- if (subjectTokenSupplier) {
- this.subjectTokenSupplier = subjectTokenSupplier;
- this.credentialSourceType = "programmatic";
- } else {
- const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);
- const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get("format"));
- const formatType = formatOpts.get("type") || "text";
- const formatSubjectTokenFieldName = formatOpts.get("subject_token_field_name");
- if (formatType !== "json" && formatType !== "text") {
- throw new Error(`Invalid credential_source format "${formatType}"`);
- }
- if (formatType === "json" && !formatSubjectTokenFieldName) {
- throw new Error("Missing subject_token_field_name for JSON credential_source format");
- }
- const file2 = credentialSourceOpts.get("file");
- const url3 = credentialSourceOpts.get("url");
- const headers = credentialSourceOpts.get("headers");
- if (file2 && url3) {
- throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.');
- } else if (file2 && !url3) {
- this.credentialSourceType = "file";
- this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({
- filePath: file2,
- formatType,
- subjectTokenFieldName: formatSubjectTokenFieldName
- });
- } else if (!file2 && url3) {
- this.credentialSourceType = "url";
- this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({
- url: url3,
- formatType,
- subjectTokenFieldName: formatSubjectTokenFieldName,
- headers,
- additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG
- });
- } else {
- throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.');
- }
- }
- }
- async retrieveSubjectToken() {
- return this.subjectTokenSupplier.getSubjectToken(this.supplierContext);
- }
- }
- exports.IdentityPoolClient = IdentityPoolClient;
-});
-
-// node_modules/google-auth-library/build/src/auth/awsrequestsigner.js
-var require_awsrequestsigner = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AwsRequestSigner = undefined;
- var crypto_1 = require_crypto3();
- var AWS_ALGORITHM = "AWS4-HMAC-SHA256";
- var AWS_REQUEST_TYPE = "aws4_request";
-
- class AwsRequestSigner {
- constructor(getCredentials2, region) {
- this.getCredentials = getCredentials2;
- this.region = region;
- this.crypto = (0, crypto_1.createCrypto)();
- }
- async getRequestOptions(amzOptions) {
- if (!amzOptions.url) {
- throw new Error('"url" is required in "amzOptions"');
- }
- const requestPayloadData = typeof amzOptions.data === "object" ? JSON.stringify(amzOptions.data) : amzOptions.data;
- const url3 = amzOptions.url;
- const method = amzOptions.method || "GET";
- const requestPayload = amzOptions.body || requestPayloadData;
- const additionalAmzHeaders = amzOptions.headers;
- const awsSecurityCredentials = await this.getCredentials();
- const uri7 = new URL(url3);
- const headerMap = await generateAuthenticationHeaderMap({
- crypto: this.crypto,
- host: uri7.host,
- canonicalUri: uri7.pathname,
- canonicalQuerystring: uri7.search.substr(1),
- method,
- region: this.region,
- securityCredentials: awsSecurityCredentials,
- requestPayload,
- additionalAmzHeaders
- });
- const headers = Object.assign(headerMap.amzDate ? { "x-amz-date": headerMap.amzDate } : {}, {
- Authorization: headerMap.authorizationHeader,
- host: uri7.host
- }, additionalAmzHeaders || {});
- if (awsSecurityCredentials.token) {
- Object.assign(headers, {
- "x-amz-security-token": awsSecurityCredentials.token
- });
- }
- const awsSignedReq = {
- url: url3,
- method,
- headers
- };
- if (typeof requestPayload !== "undefined") {
- awsSignedReq.body = requestPayload;
- }
- return awsSignedReq;
- }
- }
- exports.AwsRequestSigner = AwsRequestSigner;
- async function sign2(crypto11, key, msg) {
- return await crypto11.signWithHmacSha256(key, msg);
- }
- async function getSigningKey2(crypto11, key, dateStamp, region, serviceName) {
- const kDate = await sign2(crypto11, `AWS4${key}`, dateStamp);
- const kRegion = await sign2(crypto11, kDate, region);
- const kService = await sign2(crypto11, kRegion, serviceName);
- const kSigning = await sign2(crypto11, kService, "aws4_request");
- return kSigning;
- }
- async function generateAuthenticationHeaderMap(options2) {
- const additionalAmzHeaders = options2.additionalAmzHeaders || {};
- const requestPayload = options2.requestPayload || "";
- const serviceName = options2.host.split(".")[0];
- const now = new Date;
- const amzDate = now.toISOString().replace(/[-:]/g, "").replace(/\.[0-9]+/, "");
- const dateStamp = now.toISOString().replace(/[-]/g, "").replace(/T.*/, "");
- const reformattedAdditionalAmzHeaders = {};
- Object.keys(additionalAmzHeaders).forEach((key) => {
- reformattedAdditionalAmzHeaders[key.toLowerCase()] = additionalAmzHeaders[key];
- });
- if (options2.securityCredentials.token) {
- reformattedAdditionalAmzHeaders["x-amz-security-token"] = options2.securityCredentials.token;
- }
- const amzHeaders = Object.assign({
- host: options2.host
- }, reformattedAdditionalAmzHeaders.date ? {} : { "x-amz-date": amzDate }, reformattedAdditionalAmzHeaders);
- let canonicalHeaders = "";
- const signedHeadersList = Object.keys(amzHeaders).sort();
- signedHeadersList.forEach((key) => {
- canonicalHeaders += `${key}:${amzHeaders[key]}
-`;
- });
- const signedHeaders = signedHeadersList.join(";");
- const payloadHash = await options2.crypto.sha256DigestHex(requestPayload);
- const canonicalRequest = `${options2.method}
-` + `${options2.canonicalUri}
-` + `${options2.canonicalQuerystring}
-` + `${canonicalHeaders}
-` + `${signedHeaders}
-` + `${payloadHash}`;
- const credentialScope = `${dateStamp}/${options2.region}/${serviceName}/${AWS_REQUEST_TYPE}`;
- const stringToSign = `${AWS_ALGORITHM}
-` + `${amzDate}
-` + `${credentialScope}
-` + await options2.crypto.sha256DigestHex(canonicalRequest);
- const signingKey = await getSigningKey2(options2.crypto, options2.securityCredentials.secretAccessKey, dateStamp, options2.region, serviceName);
- const signature7 = await sign2(options2.crypto, signingKey, stringToSign);
- const authorizationHeader = `${AWS_ALGORITHM} Credential=${options2.securityCredentials.accessKeyId}/` + `${credentialScope}, SignedHeaders=${signedHeaders}, ` + `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature7)}`;
- return {
- amzDate: reformattedAdditionalAmzHeaders.date ? undefined : amzDate,
- authorizationHeader,
- canonicalQuerystring: options2.canonicalQuerystring
- };
- }
-});
-
-// node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js
-var require_defaultawssecuritycredentialssupplier = __commonJS((exports) => {
- var __classPrivateFieldGet9 = exports && exports.__classPrivateFieldGet || function(receiver, state3, kind2, f4) {
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a getter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind2 === "m" ? f4 : kind2 === "a" ? f4.call(receiver) : f4 ? f4.value : state3.get(receiver);
- };
- var _DefaultAwsSecurityCredentialsSupplier_instances;
- var _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken;
- var _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName;
- var _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials;
- var _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get;
- var _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get;
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.DefaultAwsSecurityCredentialsSupplier = undefined;
-
- class DefaultAwsSecurityCredentialsSupplier {
- constructor(opts) {
- _DefaultAwsSecurityCredentialsSupplier_instances.add(this);
- this.regionUrl = opts.regionUrl;
- this.securityCredentialsUrl = opts.securityCredentialsUrl;
- this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl;
- this.additionalGaxiosOptions = opts.additionalGaxiosOptions;
- }
- async getAwsRegion(context3) {
- if (__classPrivateFieldGet9(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get)) {
- return __classPrivateFieldGet9(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get);
- }
- const metadataHeaders = {};
- if (!__classPrivateFieldGet9(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get) && this.imdsV2SessionTokenUrl) {
- metadataHeaders["x-aws-ec2-metadata-token"] = await __classPrivateFieldGet9(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context3.transporter);
- }
- if (!this.regionUrl) {
- throw new Error("Unable to determine AWS region due to missing " + '"options.credential_source.region_url"');
- }
- const opts = {
- ...this.additionalGaxiosOptions,
- url: this.regionUrl,
- method: "GET",
- responseType: "text",
- headers: metadataHeaders
- };
- const response7 = await context3.transporter.request(opts);
- return response7.data.substr(0, response7.data.length - 1);
- }
- async getAwsSecurityCredentials(context3) {
- if (__classPrivateFieldGet9(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get)) {
- return __classPrivateFieldGet9(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get);
- }
- const metadataHeaders = {};
- if (this.imdsV2SessionTokenUrl) {
- metadataHeaders["x-aws-ec2-metadata-token"] = await __classPrivateFieldGet9(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context3.transporter);
- }
- const roleName = await __classPrivateFieldGet9(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName).call(this, metadataHeaders, context3.transporter);
- const awsCreds = await __classPrivateFieldGet9(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials).call(this, roleName, metadataHeaders, context3.transporter);
- return {
- accessKeyId: awsCreds.AccessKeyId,
- secretAccessKey: awsCreds.SecretAccessKey,
- token: awsCreds.Token
- };
- }
- }
- exports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier;
- _DefaultAwsSecurityCredentialsSupplier_instances = new WeakSet, _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken = async function _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken2(transporter) {
- const opts = {
- ...this.additionalGaxiosOptions,
- url: this.imdsV2SessionTokenUrl,
- method: "PUT",
- responseType: "text",
- headers: { "x-aws-ec2-metadata-token-ttl-seconds": "300" }
- };
- const response7 = await transporter.request(opts);
- return response7.data;
- }, _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName = async function _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName2(headers, transporter) {
- if (!this.securityCredentialsUrl) {
- throw new Error("Unable to determine AWS role name due to missing " + '"options.credential_source.url"');
- }
- const opts = {
- ...this.additionalGaxiosOptions,
- url: this.securityCredentialsUrl,
- method: "GET",
- responseType: "text",
- headers
- };
- const response7 = await transporter.request(opts);
- return response7.data;
- }, _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials = async function _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials2(roleName, headers, transporter) {
- const response7 = await transporter.request({
- ...this.additionalGaxiosOptions,
- url: `${this.securityCredentialsUrl}/${roleName}`,
- responseType: "json",
- headers
- });
- return response7.data;
- }, _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get2() {
- return process.env["AWS_REGION"] || process.env["AWS_DEFAULT_REGION"] || null;
- }, _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get2() {
- if (process.env["AWS_ACCESS_KEY_ID"] && process.env["AWS_SECRET_ACCESS_KEY"]) {
- return {
- accessKeyId: process.env["AWS_ACCESS_KEY_ID"],
- secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"],
- token: process.env["AWS_SESSION_TOKEN"]
- };
- }
- return null;
- };
-});
-
-// node_modules/google-auth-library/build/src/auth/awsclient.js
-var require_awsclient = __commonJS((exports) => {
- var __classPrivateFieldGet9 = exports && exports.__classPrivateFieldGet || function(receiver, state3, kind2, f4) {
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a getter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind2 === "m" ? f4 : kind2 === "a" ? f4.call(receiver) : f4 ? f4.value : state3.get(receiver);
- };
- var _a8;
- var _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL;
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AwsClient = undefined;
- var awsrequestsigner_1 = require_awsrequestsigner();
- var baseexternalclient_1 = require_baseexternalclient();
- var defaultawssecuritycredentialssupplier_1 = require_defaultawssecuritycredentialssupplier();
- var util_1 = require_util2();
-
- class AwsClient extends baseexternalclient_1.BaseExternalAccountClient {
- constructor(options2, additionalOptions) {
- super(options2, additionalOptions);
- const opts = (0, util_1.originalOrCamelOptions)(options2);
- const credentialSource = opts.get("credential_source");
- const awsSecurityCredentialsSupplier = opts.get("aws_security_credentials_supplier");
- if (!credentialSource && !awsSecurityCredentialsSupplier) {
- throw new Error("A credential source or AWS security credentials supplier must be specified.");
- }
- if (credentialSource && awsSecurityCredentialsSupplier) {
- throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");
- }
- if (awsSecurityCredentialsSupplier) {
- this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier;
- this.regionalCredVerificationUrl = __classPrivateFieldGet9(_a8, _a8, "f", _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL);
- this.credentialSourceType = "programmatic";
- } else {
- const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);
- this.environmentId = credentialSourceOpts.get("environment_id");
- const regionUrl = credentialSourceOpts.get("region_url");
- const securityCredentialsUrl = credentialSourceOpts.get("url");
- const imdsV2SessionTokenUrl = credentialSourceOpts.get("imdsv2_session_token_url");
- this.awsSecurityCredentialsSupplier = new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({
- regionUrl,
- securityCredentialsUrl,
- imdsV2SessionTokenUrl
- });
- this.regionalCredVerificationUrl = credentialSourceOpts.get("regional_cred_verification_url");
- this.credentialSourceType = "aws";
- this.validateEnvironmentId();
- }
- this.awsRequestSigner = null;
- this.region = "";
- }
- validateEnvironmentId() {
- var _b2;
- const match = (_b2 = this.environmentId) === null || _b2 === undefined ? undefined : _b2.match(/^(aws)(\d+)$/);
- if (!match || !this.regionalCredVerificationUrl) {
- throw new Error('No valid AWS "credential_source" provided');
- } else if (parseInt(match[2], 10) !== 1) {
- throw new Error(`aws version "${match[2]}" is not supported in the current build.`);
- }
- }
- async retrieveSubjectToken() {
- if (!this.awsRequestSigner) {
- this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext);
- this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => {
- return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext);
- }, this.region);
- }
- const options2 = await this.awsRequestSigner.getRequestOptions({
- ..._a8.RETRY_CONFIG,
- url: this.regionalCredVerificationUrl.replace("{region}", this.region),
- method: "POST"
- });
- const reformattedHeader = [];
- const extendedHeaders = Object.assign({
- "x-goog-cloud-target-resource": this.audience
- }, options2.headers);
- for (const key in extendedHeaders) {
- reformattedHeader.push({
- key,
- value: extendedHeaders[key]
- });
- }
- return encodeURIComponent(JSON.stringify({
- url: options2.url,
- method: options2.method,
- headers: reformattedHeader
- }));
- }
- }
- exports.AwsClient = AwsClient;
- _a8 = AwsClient;
- _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = { value: "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15" };
- AwsClient.AWS_EC2_METADATA_IPV4_ADDRESS = "169.254.169.254";
- AwsClient.AWS_EC2_METADATA_IPV6_ADDRESS = "fd00:ec2::254";
-});
-
-// node_modules/google-auth-library/build/src/auth/executable-response.js
-var require_executable_response = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = undefined;
- var SAML_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:saml2";
- var OIDC_SUBJECT_TOKEN_TYPE1 = "urn:ietf:params:oauth:token-type:id_token";
- var OIDC_SUBJECT_TOKEN_TYPE2 = "urn:ietf:params:oauth:token-type:jwt";
-
- class ExecutableResponse {
- constructor(responseJson) {
- if (!responseJson.version) {
- throw new InvalidVersionFieldError("Executable response must contain a 'version' field.");
- }
- if (responseJson.success === undefined) {
- throw new InvalidSuccessFieldError("Executable response must contain a 'success' field.");
- }
- this.version = responseJson.version;
- this.success = responseJson.success;
- if (this.success) {
- this.expirationTime = responseJson.expiration_time;
- this.tokenType = responseJson.token_type;
- if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE && this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 && this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) {
- throw new InvalidTokenTypeFieldError("Executable response must contain a 'token_type' field when successful " + `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`);
- }
- if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) {
- if (!responseJson.saml_response) {
- throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`);
- }
- this.subjectToken = responseJson.saml_response;
- } else {
- if (!responseJson.id_token) {
- throw new InvalidSubjectTokenError("Executable response must contain a 'id_token' field when " + `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`);
- }
- this.subjectToken = responseJson.id_token;
- }
- } else {
- if (!responseJson.code) {
- throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful.");
- }
- if (!responseJson.message) {
- throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful.");
- }
- this.errorCode = responseJson.code;
- this.errorMessage = responseJson.message;
- }
- }
- isValid() {
- return !this.isExpired() && this.success;
- }
- isExpired() {
- return this.expirationTime !== undefined && this.expirationTime < Math.round(Date.now() / 1000);
- }
- }
- exports.ExecutableResponse = ExecutableResponse;
-
- class ExecutableResponseError extends Error {
- constructor(message) {
- super(message);
- Object.setPrototypeOf(this, new.target.prototype);
- }
- }
- exports.ExecutableResponseError = ExecutableResponseError;
-
- class InvalidVersionFieldError extends ExecutableResponseError {
- }
- exports.InvalidVersionFieldError = InvalidVersionFieldError;
-
- class InvalidSuccessFieldError extends ExecutableResponseError {
- }
- exports.InvalidSuccessFieldError = InvalidSuccessFieldError;
-
- class InvalidExpirationTimeFieldError extends ExecutableResponseError {
- }
- exports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError;
-
- class InvalidTokenTypeFieldError extends ExecutableResponseError {
- }
- exports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError;
-
- class InvalidCodeFieldError extends ExecutableResponseError {
- }
- exports.InvalidCodeFieldError = InvalidCodeFieldError;
-
- class InvalidMessageFieldError extends ExecutableResponseError {
- }
- exports.InvalidMessageFieldError = InvalidMessageFieldError;
-
- class InvalidSubjectTokenError extends ExecutableResponseError {
- }
- exports.InvalidSubjectTokenError = InvalidSubjectTokenError;
-});
-
-// node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js
-var require_pluggable_auth_handler = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.PluggableAuthHandler = undefined;
- var pluggable_auth_client_1 = require_pluggable_auth_client();
- var executable_response_1 = require_executable_response();
- var childProcess3 = __require("child_process");
- var fs9 = __require("fs");
-
- class PluggableAuthHandler {
- constructor(options2) {
- if (!options2.command) {
- throw new Error("No command provided.");
- }
- this.commandComponents = PluggableAuthHandler.parseCommand(options2.command);
- this.timeoutMillis = options2.timeoutMillis;
- if (!this.timeoutMillis) {
- throw new Error("No timeoutMillis provided.");
- }
- this.outputFile = options2.outputFile;
- }
- retrieveResponseFromExecutable(envMap) {
- return new Promise((resolve9, reject) => {
- const child = childProcess3.spawn(this.commandComponents[0], this.commandComponents.slice(1), {
- env: { ...process.env, ...Object.fromEntries(envMap) }
- });
- let output = "";
- child.stdout.on("data", (data) => {
- output += data;
- });
- child.stderr.on("data", (err) => {
- output += err;
- });
- const timeout = setTimeout(() => {
- child.removeAllListeners();
- child.kill();
- return reject(new Error("The executable failed to finish within the timeout specified."));
- }, this.timeoutMillis);
- child.on("close", (code) => {
- clearTimeout(timeout);
- if (code === 0) {
- try {
- const responseJson = JSON.parse(output);
- const response7 = new executable_response_1.ExecutableResponse(responseJson);
- return resolve9(response7);
- } catch (error45) {
- if (error45 instanceof executable_response_1.ExecutableResponseError) {
- return reject(error45);
- }
- 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()));
- }
- });
- });
- }
- async retrieveCachedResponse() {
- if (!this.outputFile || this.outputFile.length === 0) {
- return;
- }
- let filePath;
- try {
- filePath = await fs9.promises.realpath(this.outputFile);
- } catch (_a8) {
- return;
- }
- if (!(await fs9.promises.lstat(filePath)).isFile()) {
- return;
- }
- const responseString = await fs9.promises.readFile(filePath, {
- encoding: "utf8"
- });
- if (responseString === "") {
- return;
- }
- try {
- const responseJson = JSON.parse(responseString);
- const response7 = new executable_response_1.ExecutableResponse(responseJson);
- if (response7.isValid()) {
- return new executable_response_1.ExecutableResponse(responseJson);
- }
- return;
- } catch (error45) {
- if (error45 instanceof executable_response_1.ExecutableResponseError) {
- throw error45;
- }
- throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`);
- }
- }
- static parseCommand(command12) {
- const components = command12.match(/(?:[^\s"]+|"[^"]*")+/g);
- if (!components) {
- throw new Error(`Provided command: "${command12}" could not be parsed.`);
- }
- for (let i5 = 0;i5 < components.length; i5++) {
- if (components[i5][0] === '"' && components[i5].slice(-1) === '"') {
- components[i5] = components[i5].slice(1, -1);
- }
- }
- return components;
- }
- }
- exports.PluggableAuthHandler = PluggableAuthHandler;
-});
-
-// node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js
-var require_pluggable_auth_client = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.PluggableAuthClient = exports.ExecutableError = undefined;
- var baseexternalclient_1 = require_baseexternalclient();
- var executable_response_1 = require_executable_response();
- var pluggable_auth_handler_1 = require_pluggable_auth_handler();
-
- 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;
- var DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000;
- var MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000;
- var MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000;
- var GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = "GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES";
- var MAXIMUM_EXECUTABLE_VERSION = 1;
-
- class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient {
- constructor(options2, additionalOptions) {
- super(options2, additionalOptions);
- if (!options2.credential_source.executable) {
- throw new Error('No valid Pluggable Auth "credential_source" provided.');
- }
- this.command = options2.credential_source.executable.command;
- if (!this.command) {
- throw new Error('No valid Pluggable Auth "credential_source" provided.');
- }
- if (options2.credential_source.executable.timeout_millis === undefined) {
- this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS;
- } else {
- this.timeoutMillis = options2.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 = options2.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";
- }
- async retrieveSubjectToken() {
- 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;
- if (this.outputFile) {
- executableResponse = await this.handler.retrieveCachedResponse();
- }
- if (!executableResponse) {
- const envMap = new Map;
- envMap.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE", this.audience);
- envMap.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE", this.subjectTokenType);
- 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}.`);
- }
- if (!executableResponse.success) {
- throw new ExecutableError(executableResponse.errorMessage, executableResponse.errorCode);
- }
- 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.");
- }
- }
- if (executableResponse.isExpired()) {
- throw new Error("Executable response is expired.");
- }
- return executableResponse.subjectToken;
- }
- }
- exports.PluggableAuthClient = PluggableAuthClient;
-});
-
-// node_modules/google-auth-library/build/src/auth/externalclient.js
-var require_externalclient = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ExternalAccountClient = undefined;
- var baseexternalclient_1 = require_baseexternalclient();
- var identitypoolclient_1 = require_identitypoolclient();
- var awsclient_1 = require_awsclient();
- var pluggable_auth_client_1 = require_pluggable_auth_client();
-
- class ExternalAccountClient {
- constructor() {
- throw new Error("ExternalAccountClients should be initialized via: " + "ExternalAccountClient.fromJSON(), " + "directly via explicit constructors, eg. " + "new AwsClient(options), new IdentityPoolClient(options), new" + "PluggableAuthClientOptions, or via " + "new GoogleAuth(options).getClient()");
- }
- static fromJSON(options2, additionalOptions) {
- var _a8, _b2;
- if (options2 && options2.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
- if ((_a8 = options2.credential_source) === null || _a8 === undefined ? undefined : _a8.environment_id) {
- return new awsclient_1.AwsClient(options2, additionalOptions);
- } else if ((_b2 = options2.credential_source) === null || _b2 === undefined ? undefined : _b2.executable) {
- return new pluggable_auth_client_1.PluggableAuthClient(options2, additionalOptions);
- } else {
- return new identitypoolclient_1.IdentityPoolClient(options2, additionalOptions);
- }
- } else {
- return null;
- }
- }
- }
- exports.ExternalAccountClient = ExternalAccountClient;
-});
-
-// node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js
-var require_externalAccountAuthorizedUserClient = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = undefined;
- var authclient_1 = require_authclient();
- var oauth2common_1 = require_oauth2common();
- var gaxios_1 = require_src2();
- var stream10 = __require("stream");
- var baseexternalclient_1 = require_baseexternalclient();
- exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = "external_account_authorized_user";
- var DEFAULT_TOKEN_URL = "https://sts.{universeDomain}/v1/oauthtoken";
-
- class ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler {
- constructor(url3, transporter, clientAuthentication) {
- super(clientAuthentication);
- this.url = url3;
- this.transporter = transporter;
- }
- async refreshToken(refreshToken, additionalHeaders) {
- const values2 = new URLSearchParams({
- grant_type: "refresh_token",
- refresh_token: refreshToken
- });
- const headers = {
- "Content-Type": "application/x-www-form-urlencoded",
- ...additionalHeaders
- };
- const opts = {
- ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG,
- url: this.url,
- method: "POST",
- headers,
- data: values2.toString(),
- responseType: "json"
- };
- this.applyClientAuthenticationOptions(opts);
- try {
- const response7 = await this.transporter.request(opts);
- const tokenRefreshResponse = response7.data;
- tokenRefreshResponse.res = response7;
- return tokenRefreshResponse;
- } catch (error45) {
- if (error45 instanceof gaxios_1.GaxiosError && error45.response) {
- throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error45.response.data, error45);
- }
- throw error45;
- }
- }
- }
-
- class ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient {
- constructor(options2, additionalOptions) {
- var _a8;
- super({ ...options2, ...additionalOptions });
- if (options2.universe_domain) {
- this.universeDomain = options2.universe_domain;
- }
- this.refreshToken = options2.refresh_token;
- const clientAuth = {
- confidentialClientType: "basic",
- clientId: options2.client_id,
- clientSecret: options2.client_secret
- };
- this.externalAccountAuthorizedUserHandler = new ExternalAccountAuthorizedUserHandler((_a8 = options2.token_url) !== null && _a8 !== undefined ? _a8 : DEFAULT_TOKEN_URL.replace("{universeDomain}", this.universeDomain), this.transporter, clientAuth);
- this.cachedAccessToken = null;
- this.quotaProjectId = options2.quota_project_id;
- if (typeof (additionalOptions === null || additionalOptions === undefined ? undefined : additionalOptions.eagerRefreshThresholdMillis) !== "number") {
- this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET;
- } else {
- this.eagerRefreshThresholdMillis = additionalOptions.eagerRefreshThresholdMillis;
- }
- this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === undefined ? undefined : additionalOptions.forceRefreshOnFailure);
- }
- async getAccessToken() {
- if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {
- await this.refreshAccessTokenAsync();
- }
- return {
- token: this.cachedAccessToken.access_token,
- res: this.cachedAccessToken.res
- };
- }
- async getRequestHeaders() {
- const accessTokenResponse = await this.getAccessToken();
- const headers = {
- Authorization: `Bearer ${accessTokenResponse.token}`
- };
- return this.addSharedMetadataHeaders(headers);
- }
- request(opts, callback) {
- if (callback) {
- this.requestAsync(opts).then((r4) => callback(null, r4), (e4) => {
- return callback(e4, e4.response);
- });
- } else {
- return this.requestAsync(opts);
- }
- }
- async requestAsync(opts, reAuthRetried = false) {
- let response7;
- try {
- const requestHeaders = await this.getRequestHeaders();
- opts.headers = opts.headers || {};
- if (requestHeaders && requestHeaders["x-goog-user-project"]) {
- opts.headers["x-goog-user-project"] = requestHeaders["x-goog-user-project"];
- }
- if (requestHeaders && requestHeaders.Authorization) {
- opts.headers.Authorization = requestHeaders.Authorization;
- }
- response7 = await this.transporter.request(opts);
- } catch (e4) {
- const res = e4.response;
- if (res) {
- const statusCode = res.status;
- const isReadableStream5 = res.config.data instanceof stream10.Readable;
- const isAuthErr = statusCode === 401 || statusCode === 403;
- if (!reAuthRetried && isAuthErr && !isReadableStream5 && this.forceRefreshOnFailure) {
- await this.refreshAccessTokenAsync();
- return await this.requestAsync(opts, true);
- }
- }
- throw e4;
- }
- return response7;
- }
- async refreshAccessTokenAsync() {
- const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);
- this.cachedAccessToken = {
- access_token: refreshResponse.access_token,
- expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000,
- res: refreshResponse.res
- };
- if (refreshResponse.refresh_token !== undefined) {
- this.refreshToken = refreshResponse.refresh_token;
- }
- return this.cachedAccessToken;
- }
- isExpired(credentials) {
- const now = new Date().getTime();
- return credentials.expiry_date ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis : false;
- }
- }
- exports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient;
-});
-
-// node_modules/google-auth-library/build/src/auth/googleauth.js
-var require_googleauth = __commonJS((exports) => {
- var __classPrivateFieldGet9 = exports && exports.__classPrivateFieldGet || function(receiver, state3, kind2, f4) {
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a getter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind2 === "m" ? f4 : kind2 === "a" ? f4.call(receiver) : f4 ? f4.value : state3.get(receiver);
- };
- var __classPrivateFieldSet9 = exports && exports.__classPrivateFieldSet || function(receiver, state3, value, kind2, f4) {
- if (kind2 === "m")
- throw new TypeError("Private method is not writable");
- if (kind2 === "a" && !f4)
- throw new TypeError("Private accessor was defined without a setter");
- if (typeof state3 === "function" ? receiver !== state3 || !f4 : !state3.has(receiver))
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return kind2 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state3.set(receiver, value), value;
- };
- var _GoogleAuth_instances;
- var _GoogleAuth_pendingAuthClient;
- var _GoogleAuth_prepareAndCacheClient;
- var _GoogleAuth_determineClient;
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.GoogleAuth = exports.GoogleAuthExceptionMessages = exports.CLOUD_SDK_CLIENT_ID = undefined;
- var child_process_1 = __require("child_process");
- var fs9 = __require("fs");
- var gcpMetadata = require_src4();
- var os5 = __require("os");
- var path14 = __require("path");
- var crypto_1 = require_crypto3();
- var transporters_1 = require_transporters();
- var computeclient_1 = require_computeclient();
- var idtokenclient_1 = require_idtokenclient();
- var envDetect_1 = require_envDetect();
- var jwtclient_1 = require_jwtclient();
- var refreshclient_1 = require_refreshclient();
- var impersonated_1 = require_impersonated();
- var externalclient_1 = require_externalclient();
- var baseexternalclient_1 = require_baseexternalclient();
- var authclient_1 = require_authclient();
- var externalAccountAuthorizedUserClient_1 = require_externalAccountAuthorizedUserClient();
- var util_1 = require_util2();
- exports.CLOUD_SDK_CLIENT_ID = "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com";
- exports.GoogleAuthExceptionMessages = {
- API_KEY_WITH_CREDENTIALS: "API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",
- NO_PROJECT_ID_FOUND: `Unable to detect a Project Id in the current environment.
-` + `To learn more about authentication and Google APIs, visit:
-` + "https://cloud.google.com/docs/authentication/getting-started",
- NO_CREDENTIALS_FOUND: `Unable to find credentials in current environment.
-` + `To learn more about authentication and Google APIs, visit:
-` + "https://cloud.google.com/docs/authentication/getting-started",
- NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",
- NO_UNIVERSE_DOMAIN_FOUND: `Unable to detect a Universe Domain in the current environment.
-` + `To learn more about Universe Domain retrieval, visit:
-` + "https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys"
- };
-
- class GoogleAuth {
- get isGCE() {
- return this.checkIsGCE;
- }
- constructor(opts = {}) {
- _GoogleAuth_instances.add(this);
- this.checkIsGCE = undefined;
- this.jsonContent = null;
- this.cachedCredential = null;
- _GoogleAuth_pendingAuthClient.set(this, null);
- this.clientOptions = {};
- this._cachedProjectId = opts.projectId || null;
- this.cachedCredential = opts.authClient || null;
- this.keyFilename = opts.keyFilename || opts.keyFile;
- this.scopes = opts.scopes;
- this.clientOptions = opts.clientOptions || {};
- this.jsonContent = opts.credentials || null;
- this.apiKey = opts.apiKey || this.clientOptions.apiKey || null;
- if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) {
- throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);
- }
- if (opts.universeDomain) {
- this.clientOptions.universeDomain = opts.universeDomain;
- }
- }
- setGapicJWTValues(client14) {
- client14.defaultServicePath = this.defaultServicePath;
- client14.useJWTAccessWithScope = this.useJWTAccessWithScope;
- client14.defaultScopes = this.defaultScopes;
- }
- getProjectId(callback) {
- if (callback) {
- this.getProjectIdAsync().then((r4) => callback(null, r4), callback);
- } else {
- return this.getProjectIdAsync();
- }
- }
- async getProjectIdOptional() {
- try {
- return await this.getProjectId();
- } catch (e4) {
- if (e4 instanceof Error && e4.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) {
- return null;
- } else {
- throw e4;
- }
- }
- }
- async findAndCacheProjectId() {
- let projectId = null;
- projectId || (projectId = await this.getProductionProjectId());
- projectId || (projectId = await this.getFileProjectId());
- projectId || (projectId = await this.getDefaultServiceProjectId());
- projectId || (projectId = await this.getGCEProjectId());
- projectId || (projectId = await this.getExternalAccountClientProjectId());
- if (projectId) {
- this._cachedProjectId = projectId;
- return projectId;
- } else {
- throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND);
- }
- }
- async getProjectIdAsync() {
- if (this._cachedProjectId) {
- return this._cachedProjectId;
- }
- if (!this._findProjectIdPromise) {
- this._findProjectIdPromise = this.findAndCacheProjectId();
- }
- return this._findProjectIdPromise;
- }
- async getUniverseDomainFromMetadataServer() {
- var _a8;
- let universeDomain;
- try {
- universeDomain = await gcpMetadata.universe("universe-domain");
- universeDomain || (universeDomain = authclient_1.DEFAULT_UNIVERSE);
- } catch (e4) {
- if (e4 && ((_a8 = e4 === null || e4 === undefined ? undefined : e4.response) === null || _a8 === undefined ? undefined : _a8.status) === 404) {
- universeDomain = authclient_1.DEFAULT_UNIVERSE;
- } else {
- throw e4;
- }
- }
- return universeDomain;
- }
- async getUniverseDomain() {
- let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get("universe_domain");
- try {
- universeDomain !== null && universeDomain !== undefined || (universeDomain = (await this.getClient()).universeDomain);
- } catch (_a8) {
- universeDomain !== null && universeDomain !== undefined || (universeDomain = authclient_1.DEFAULT_UNIVERSE);
- }
- return universeDomain;
- }
- getAnyScopes() {
- return this.scopes || this.defaultScopes;
- }
- getApplicationDefault(optionsOrCallback = {}, callback) {
- let options2;
- if (typeof optionsOrCallback === "function") {
- callback = optionsOrCallback;
- } else {
- options2 = optionsOrCallback;
- }
- if (callback) {
- this.getApplicationDefaultAsync(options2).then((r4) => callback(null, r4.credential, r4.projectId), callback);
- } else {
- return this.getApplicationDefaultAsync(options2);
- }
- }
- async getApplicationDefaultAsync(options2 = {}) {
- if (this.cachedCredential) {
- return await __classPrivateFieldGet9(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, this.cachedCredential, null);
- }
- let credential;
- credential = await this._tryGetApplicationCredentialsFromEnvironmentVariable(options2);
- if (credential) {
- if (credential instanceof jwtclient_1.JWT) {
- credential.scopes = this.scopes;
- } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {
- credential.scopes = this.getAnyScopes();
- }
- return await __classPrivateFieldGet9(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential);
- }
- credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options2);
- if (credential) {
- if (credential instanceof jwtclient_1.JWT) {
- credential.scopes = this.scopes;
- } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {
- credential.scopes = this.getAnyScopes();
- }
- return await __classPrivateFieldGet9(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential);
- }
- if (await this._checkIsGCE()) {
- options2.scopes = this.getAnyScopes();
- return await __classPrivateFieldGet9(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, new computeclient_1.Compute(options2));
- }
- throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND);
- }
- async _checkIsGCE() {
- if (this.checkIsGCE === undefined) {
- this.checkIsGCE = gcpMetadata.getGCPResidency() || await gcpMetadata.isAvailable();
- }
- return this.checkIsGCE;
- }
- async _tryGetApplicationCredentialsFromEnvironmentVariable(options2) {
- const credentialsPath = process.env["GOOGLE_APPLICATION_CREDENTIALS"] || process.env["google_application_credentials"];
- if (!credentialsPath || credentialsPath.length === 0) {
- return null;
- }
- try {
- return this._getApplicationCredentialsFromFilePath(credentialsPath, options2);
- } catch (e4) {
- if (e4 instanceof Error) {
- e4.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e4.message}`;
- }
- throw e4;
- }
- }
- async _tryGetApplicationCredentialsFromWellKnownFile(options2) {
- let location = null;
- if (this._isWindows()) {
- location = process.env["APPDATA"];
- } else {
- const home = process.env["HOME"];
- if (home) {
- location = path14.join(home, ".config");
- }
- }
- if (location) {
- location = path14.join(location, "gcloud", "application_default_credentials.json");
- if (!fs9.existsSync(location)) {
- location = null;
- }
- }
- if (!location) {
- return null;
- }
- const client14 = await this._getApplicationCredentialsFromFilePath(location, options2);
- return client14;
- }
- async _getApplicationCredentialsFromFilePath(filePath, options2 = {}) {
- if (!filePath || filePath.length === 0) {
- throw new Error("The file path is invalid.");
- }
- try {
- filePath = fs9.realpathSync(filePath);
- if (!fs9.lstatSync(filePath).isFile()) {
- throw new Error;
- }
- } catch (err) {
- if (err instanceof Error) {
- err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;
- }
- throw err;
- }
- const readStream2 = fs9.createReadStream(filePath);
- return this.fromStream(readStream2, options2);
- }
- fromImpersonatedJSON(json2) {
- var _a8, _b2, _c4, _d3;
- if (!json2) {
- throw new Error("Must pass in a JSON object containing an impersonated refresh token");
- }
- if (json2.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
- throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`);
- }
- if (!json2.source_credentials) {
- throw new Error("The incoming JSON object does not contain a source_credentials field");
- }
- if (!json2.service_account_impersonation_url) {
- throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");
- }
- const sourceClient = this.fromJSON(json2.source_credentials);
- if (((_a8 = json2.service_account_impersonation_url) === null || _a8 === undefined ? undefined : _a8.length) > 256) {
- throw new RangeError(`Target principal is too long: ${json2.service_account_impersonation_url}`);
- }
- const targetPrincipal = (_c4 = (_b2 = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json2.service_account_impersonation_url)) === null || _b2 === undefined ? undefined : _b2.groups) === null || _c4 === undefined ? undefined : _c4.target;
- if (!targetPrincipal) {
- throw new RangeError(`Cannot extract target principal from ${json2.service_account_impersonation_url}`);
- }
- const targetScopes = (_d3 = this.getAnyScopes()) !== null && _d3 !== undefined ? _d3 : [];
- return new impersonated_1.Impersonated({
- ...json2,
- sourceClient,
- targetPrincipal,
- targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes]
- });
- }
- fromJSON(json2, options2 = {}) {
- let client14;
- const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options2).get("universe_domain");
- if (json2.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) {
- client14 = new refreshclient_1.UserRefreshClient(options2);
- client14.fromJSON(json2);
- } else if (json2.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
- client14 = this.fromImpersonatedJSON(json2);
- } else if (json2.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
- client14 = externalclient_1.ExternalAccountClient.fromJSON(json2, options2);
- client14.scopes = this.getAnyScopes();
- } else if (json2.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) {
- client14 = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient(json2, options2);
- } else {
- options2.scopes = this.scopes;
- client14 = new jwtclient_1.JWT(options2);
- this.setGapicJWTValues(client14);
- client14.fromJSON(json2);
- }
- if (preferredUniverseDomain) {
- client14.universeDomain = preferredUniverseDomain;
- }
- return client14;
- }
- _cacheClientFromJSON(json2, options2) {
- const client14 = this.fromJSON(json2, options2);
- this.jsonContent = json2;
- this.cachedCredential = client14;
- return client14;
- }
- fromStream(inputStream, optionsOrCallback = {}, callback) {
- let options2 = {};
- if (typeof optionsOrCallback === "function") {
- callback = optionsOrCallback;
- } else {
- options2 = optionsOrCallback;
- }
- if (callback) {
- this.fromStreamAsync(inputStream, options2).then((r4) => callback(null, r4), callback);
- } else {
- return this.fromStreamAsync(inputStream, options2);
- }
- }
- fromStreamAsync(inputStream, options2) {
- return new Promise((resolve9, reject) => {
- if (!inputStream) {
- throw new Error("Must pass in a stream containing the Google auth settings.");
- }
- const chunks = [];
- inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => chunks.push(chunk)).on("end", () => {
- try {
- try {
- const data = JSON.parse(chunks.join(""));
- const r4 = this._cacheClientFromJSON(data, options2);
- return resolve9(r4);
- } catch (err) {
- if (!this.keyFilename)
- throw err;
- const client14 = new jwtclient_1.JWT({
- ...this.clientOptions,
- keyFile: this.keyFilename
- });
- this.cachedCredential = client14;
- this.setGapicJWTValues(client14);
- return resolve9(client14);
- }
- } catch (err) {
- return reject(err);
- }
- });
- });
- }
- fromAPIKey(apiKey, options2 = {}) {
- return new jwtclient_1.JWT({ ...options2, apiKey });
- }
- _isWindows() {
- const sys = os5.platform();
- if (sys && sys.length >= 3) {
- if (sys.substring(0, 3).toLowerCase() === "win") {
- return true;
- }
- }
- return false;
- }
- async getDefaultServiceProjectId() {
- return new Promise((resolve9) => {
- (0, child_process_1.exec)("gcloud config config-helper --format json", (err, stdout) => {
- if (!err && stdout) {
- try {
- const projectId = JSON.parse(stdout).configuration.properties.core.project;
- resolve9(projectId);
- return;
- } catch (e4) {}
- }
- resolve9(null);
- });
- });
- }
- getProductionProjectId() {
- return process.env["GCLOUD_PROJECT"] || process.env["GOOGLE_CLOUD_PROJECT"] || process.env["gcloud_project"] || process.env["google_cloud_project"];
- }
- async getFileProjectId() {
- if (this.cachedCredential) {
- return this.cachedCredential.projectId;
- }
- if (this.keyFilename) {
- const creds = await this.getClient();
- if (creds && creds.projectId) {
- return creds.projectId;
- }
- }
- const r4 = await this._tryGetApplicationCredentialsFromEnvironmentVariable();
- if (r4) {
- return r4.projectId;
- } else {
- return null;
- }
- }
- async getExternalAccountClientProjectId() {
- if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
- return null;
- }
- const creds = await this.getClient();
- return await creds.getProjectId();
- }
- async getGCEProjectId() {
- try {
- const r4 = await gcpMetadata.project("project-id");
- return r4;
- } catch (e4) {
- return null;
- }
- }
- getCredentials(callback) {
- if (callback) {
- this.getCredentialsAsync().then((r4) => callback(null, r4), callback);
- } else {
- return this.getCredentialsAsync();
- }
- }
- async getCredentialsAsync() {
- const client14 = await this.getClient();
- if (client14 instanceof impersonated_1.Impersonated) {
- return { client_email: client14.getTargetPrincipal() };
- }
- if (client14 instanceof baseexternalclient_1.BaseExternalAccountClient) {
- const serviceAccountEmail = client14.getServiceAccountEmail();
- if (serviceAccountEmail) {
- return {
- client_email: serviceAccountEmail,
- universe_domain: client14.universeDomain
- };
- }
- }
- if (this.jsonContent) {
- return {
- client_email: this.jsonContent.client_email,
- private_key: this.jsonContent.private_key,
- universe_domain: this.jsonContent.universe_domain
- };
- }
- if (await this._checkIsGCE()) {
- const [client_email, universe_domain] = await Promise.all([
- gcpMetadata.instance("service-accounts/default/email"),
- this.getUniverseDomain()
- ]);
- return { client_email, universe_domain };
- }
- throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND);
- }
- async getClient() {
- if (this.cachedCredential) {
- return this.cachedCredential;
- }
- __classPrivateFieldSet9(this, _GoogleAuth_pendingAuthClient, __classPrivateFieldGet9(this, _GoogleAuth_pendingAuthClient, "f") || __classPrivateFieldGet9(this, _GoogleAuth_instances, "m", _GoogleAuth_determineClient).call(this), "f");
- try {
- return await __classPrivateFieldGet9(this, _GoogleAuth_pendingAuthClient, "f");
- } finally {
- __classPrivateFieldSet9(this, _GoogleAuth_pendingAuthClient, null, "f");
- }
- }
- async getIdTokenClient(targetAudience) {
- const client14 = await this.getClient();
- if (!("fetchIdToken" in client14)) {
- throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");
- }
- return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client14 });
- }
- async getAccessToken() {
- const client14 = await this.getClient();
- return (await client14.getAccessToken()).token;
- }
- async getRequestHeaders(url3) {
- const client14 = await this.getClient();
- return client14.getRequestHeaders(url3);
- }
- async authorizeRequest(opts) {
- opts = opts || {};
- const url3 = opts.url || opts.uri;
- const client14 = await this.getClient();
- const headers = await client14.getRequestHeaders(url3);
- opts.headers = Object.assign(opts.headers || {}, headers);
- return opts;
- }
- async request(opts) {
- const client14 = await this.getClient();
- return client14.request(opts);
- }
- getEnv() {
- return (0, envDetect_1.getEnv)();
- }
- async sign(data, endpoint7) {
- const client14 = await this.getClient();
- const universe = await this.getUniverseDomain();
- endpoint7 = endpoint7 || `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`;
- if (client14 instanceof impersonated_1.Impersonated) {
- const signed = await client14.sign(data);
- return signed.signedBlob;
- }
- const crypto11 = (0, crypto_1.createCrypto)();
- if (client14 instanceof jwtclient_1.JWT && client14.key) {
- const sign2 = await crypto11.sign(client14.key, data);
- return sign2;
- }
- const creds = await this.getCredentials();
- if (!creds.client_email) {
- throw new Error("Cannot sign data without `client_email`.");
- }
- return this.signBlob(crypto11, creds.client_email, data, endpoint7);
- }
- async signBlob(crypto11, emailOrUniqueId, data, endpoint7) {
- const url3 = new URL(endpoint7 + `${emailOrUniqueId}:signBlob`);
- const res = await this.request({
- method: "POST",
- url: url3.href,
- data: {
- payload: crypto11.encodeBase64StringUtf8(data)
- },
- retry: true,
- retryConfig: {
- httpMethodsToRetry: ["POST"]
- }
- });
- return res.data.signedBlob;
- }
- }
- exports.GoogleAuth = GoogleAuth;
- _GoogleAuth_pendingAuthClient = new WeakMap, _GoogleAuth_instances = new WeakSet, _GoogleAuth_prepareAndCacheClient = async function _GoogleAuth_prepareAndCacheClient2(credential, quotaProjectIdOverride = process.env["GOOGLE_CLOUD_QUOTA_PROJECT"] || null) {
- const projectId = await this.getProjectIdOptional();
- if (quotaProjectIdOverride) {
- credential.quotaProjectId = quotaProjectIdOverride;
- }
- this.cachedCredential = credential;
- return { credential, projectId };
- }, _GoogleAuth_determineClient = async function _GoogleAuth_determineClient2() {
- if (this.jsonContent) {
- return this._cacheClientFromJSON(this.jsonContent, this.clientOptions);
- } else if (this.keyFilename) {
- const filePath = path14.resolve(this.keyFilename);
- const stream10 = fs9.createReadStream(filePath);
- return await this.fromStreamAsync(stream10, this.clientOptions);
- } else if (this.apiKey) {
- const client14 = await this.fromAPIKey(this.apiKey, this.clientOptions);
- client14.scopes = this.scopes;
- const { credential } = await __classPrivateFieldGet9(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, client14);
- return credential;
- } else {
- const { credential } = await this.getApplicationDefaultAsync(this.clientOptions);
- return credential;
- }
- };
- GoogleAuth.DefaultTransporter = transporters_1.DefaultTransporter;
-});
-
-// node_modules/google-auth-library/build/src/auth/iam.js
-var require_iam = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.IAMAuth = undefined;
-
- class IAMAuth {
- constructor(selector, token) {
- this.selector = selector;
- this.token = token;
- this.selector = selector;
- this.token = token;
- }
- getRequestHeaders() {
- return {
- "x-goog-iam-authority-selector": this.selector,
- "x-goog-iam-authorization-token": this.token
- };
- }
- }
- exports.IAMAuth = IAMAuth;
-});
-
-// node_modules/google-auth-library/build/src/auth/downscopedclient.js
-var require_downscopedclient = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = undefined;
- var stream10 = __require("stream");
- var authclient_1 = require_authclient();
- var sts = require_stscredentials();
- var STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
- var STS_REQUEST_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
- var STS_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
- exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10;
- exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;
-
- class DownscopedClient extends authclient_1.AuthClient {
- constructor(authClient, credentialAccessBoundary, additionalOptions, quotaProjectId) {
- super({ ...additionalOptions, quotaProjectId });
- this.authClient = authClient;
- this.credentialAccessBoundary = credentialAccessBoundary;
- if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) {
- throw new Error("At least one access boundary rule needs to be defined.");
- } else if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length > exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) {
- throw new Error("The provided access boundary has more than " + `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);
- }
- for (const rule of credentialAccessBoundary.accessBoundary.accessBoundaryRules) {
- if (rule.availablePermissions.length === 0) {
- throw new Error("At least one permission should be defined in access boundary rules.");
- }
- }
- this.stsCredential = new sts.StsCredentials(`https://sts.${this.universeDomain}/v1/token`);
- this.cachedDownscopedAccessToken = null;
- }
- setCredentials(credentials) {
- if (!credentials.expiry_date) {
- throw new Error("The access token expiry_date field is missing in the provided " + "credentials.");
- }
- super.setCredentials(credentials);
- this.cachedDownscopedAccessToken = credentials;
- }
- async getAccessToken() {
- if (!this.cachedDownscopedAccessToken || this.isExpired(this.cachedDownscopedAccessToken)) {
- await this.refreshAccessTokenAsync();
- }
- return {
- token: this.cachedDownscopedAccessToken.access_token,
- expirationTime: this.cachedDownscopedAccessToken.expiry_date,
- res: this.cachedDownscopedAccessToken.res
- };
- }
- async getRequestHeaders() {
- const accessTokenResponse = await this.getAccessToken();
- const headers = {
- Authorization: `Bearer ${accessTokenResponse.token}`
- };
- return this.addSharedMetadataHeaders(headers);
- }
- request(opts, callback) {
- if (callback) {
- this.requestAsync(opts).then((r4) => callback(null, r4), (e4) => {
- return callback(e4, e4.response);
- });
- } else {
- return this.requestAsync(opts);
- }
- }
- async requestAsync(opts, reAuthRetried = false) {
- let response7;
- try {
- const requestHeaders = await this.getRequestHeaders();
- opts.headers = opts.headers || {};
- if (requestHeaders && requestHeaders["x-goog-user-project"]) {
- opts.headers["x-goog-user-project"] = requestHeaders["x-goog-user-project"];
- }
- if (requestHeaders && requestHeaders.Authorization) {
- opts.headers.Authorization = requestHeaders.Authorization;
- }
- response7 = await this.transporter.request(opts);
- } catch (e4) {
- const res = e4.response;
- if (res) {
- const statusCode = res.status;
- const isReadableStream5 = res.config.data instanceof stream10.Readable;
- const isAuthErr = statusCode === 401 || statusCode === 403;
- if (!reAuthRetried && isAuthErr && !isReadableStream5 && this.forceRefreshOnFailure) {
- await this.refreshAccessTokenAsync();
- return await this.requestAsync(opts, true);
- }
- }
- throw e4;
- }
- return response7;
- }
- async refreshAccessTokenAsync() {
- var _a8;
- const subjectToken = (await this.authClient.getAccessToken()).token;
- const stsCredentialsOptions = {
- grantType: STS_GRANT_TYPE,
- requestedTokenType: STS_REQUEST_TOKEN_TYPE,
- subjectToken,
- subjectTokenType: STS_SUBJECT_TOKEN_TYPE
- };
- const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary);
- const sourceCredExpireDate = ((_a8 = this.authClient.credentials) === null || _a8 === undefined ? undefined : _a8.expiry_date) || null;
- const expiryDate = stsResponse.expires_in ? new Date().getTime() + stsResponse.expires_in * 1000 : sourceCredExpireDate;
- this.cachedDownscopedAccessToken = {
- access_token: stsResponse.access_token,
- expiry_date: expiryDate,
- res: stsResponse.res
- };
- this.credentials = {};
- Object.assign(this.credentials, this.cachedDownscopedAccessToken);
- delete this.credentials.res;
- this.emit("tokens", {
- refresh_token: null,
- expiry_date: this.cachedDownscopedAccessToken.expiry_date,
- access_token: this.cachedDownscopedAccessToken.access_token,
- token_type: "Bearer",
- id_token: null
- });
- return this.cachedDownscopedAccessToken;
- }
- isExpired(downscopedAccessToken) {
- const now = new Date().getTime();
- return downscopedAccessToken.expiry_date ? now >= downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis : false;
- }
- }
- exports.DownscopedClient = DownscopedClient;
-});
-
-// node_modules/google-auth-library/build/src/auth/passthrough.js
-var require_passthrough = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.PassThroughClient = undefined;
- var authclient_1 = require_authclient();
-
- class PassThroughClient extends authclient_1.AuthClient {
- async request(opts) {
- return this.transporter.request(opts);
- }
- async getAccessToken() {
- return {};
- }
- async getRequestHeaders() {
- return {};
- }
- }
- exports.PassThroughClient = PassThroughClient;
- var a5 = new PassThroughClient;
- a5.getAccessToken();
-});
-
-// node_modules/google-auth-library/build/src/index.js
-var require_src6 = __commonJS((exports) => {
- 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 = undefined;
- var googleauth_1 = require_googleauth();
- Object.defineProperty(exports, "GoogleAuth", { enumerable: true, get: function() {
- return googleauth_1.GoogleAuth;
- } });
- exports.gcpMetadata = require_src4();
- exports.gaxios = require_src2();
- var authclient_1 = require_authclient();
- 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 = require_computeclient();
- Object.defineProperty(exports, "Compute", { enumerable: true, get: function() {
- return computeclient_1.Compute;
- } });
- var envDetect_1 = require_envDetect();
- Object.defineProperty(exports, "GCPEnv", { enumerable: true, get: function() {
- return envDetect_1.GCPEnv;
- } });
- var iam_1 = require_iam();
- Object.defineProperty(exports, "IAMAuth", { enumerable: true, get: function() {
- return iam_1.IAMAuth;
- } });
- var idtokenclient_1 = require_idtokenclient();
- Object.defineProperty(exports, "IdTokenClient", { enumerable: true, get: function() {
- return idtokenclient_1.IdTokenClient;
- } });
- var jwtaccess_1 = require_jwtaccess();
- Object.defineProperty(exports, "JWTAccess", { enumerable: true, get: function() {
- return jwtaccess_1.JWTAccess;
- } });
- var jwtclient_1 = require_jwtclient();
- Object.defineProperty(exports, "JWT", { enumerable: true, get: function() {
- return jwtclient_1.JWT;
- } });
- var impersonated_1 = require_impersonated();
- Object.defineProperty(exports, "Impersonated", { enumerable: true, get: function() {
- return impersonated_1.Impersonated;
- } });
- var oauth2client_1 = require_oauth2client();
- 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 = require_loginticket();
- Object.defineProperty(exports, "LoginTicket", { enumerable: true, get: function() {
- return loginticket_1.LoginTicket;
- } });
- var refreshclient_1 = require_refreshclient();
- Object.defineProperty(exports, "UserRefreshClient", { enumerable: true, get: function() {
- return refreshclient_1.UserRefreshClient;
- } });
- var awsclient_1 = require_awsclient();
- Object.defineProperty(exports, "AwsClient", { enumerable: true, get: function() {
- return awsclient_1.AwsClient;
- } });
- var awsrequestsigner_1 = require_awsrequestsigner();
- Object.defineProperty(exports, "AwsRequestSigner", { enumerable: true, get: function() {
- return awsrequestsigner_1.AwsRequestSigner;
- } });
- var identitypoolclient_1 = require_identitypoolclient();
- Object.defineProperty(exports, "IdentityPoolClient", { enumerable: true, get: function() {
- return identitypoolclient_1.IdentityPoolClient;
- } });
- var externalclient_1 = require_externalclient();
- Object.defineProperty(exports, "ExternalAccountClient", { enumerable: true, get: function() {
- return externalclient_1.ExternalAccountClient;
- } });
- var baseexternalclient_1 = require_baseexternalclient();
- Object.defineProperty(exports, "BaseExternalAccountClient", { enumerable: true, get: function() {
- return baseexternalclient_1.BaseExternalAccountClient;
- } });
- var downscopedclient_1 = require_downscopedclient();
- Object.defineProperty(exports, "DownscopedClient", { enumerable: true, get: function() {
- return downscopedclient_1.DownscopedClient;
- } });
- var pluggable_auth_client_1 = require_pluggable_auth_client();
- 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 = require_passthrough();
- Object.defineProperty(exports, "PassThroughClient", { enumerable: true, get: function() {
- return passthrough_1.PassThroughClient;
- } });
- var transporters_1 = require_transporters();
- Object.defineProperty(exports, "DefaultTransporter", { enumerable: true, get: function() {
- return transporters_1.DefaultTransporter;
- } });
- var auth13 = new googleauth_1.GoogleAuth;
- exports.auth = auth13;
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs
-var readEnv7 = (env5) => {
- if (typeof globalThis.process !== "undefined") {
- return globalThis.process.env?.[env5]?.trim() ?? undefined;
- }
- if (typeof globalThis.Deno !== "undefined") {
- return globalThis.Deno.env?.get?.(env5)?.trim();
- }
- return;
-};
-
-// node_modules/@anthropic-ai/vertex-sdk/core/error.mjs
-var init_error13 = __esm(() => {
- init_error11();
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs
-function isObj3(obj) {
- return obj != null && typeof obj === "object" && !Array.isArray(obj);
-}
-var isArray8 = (val) => (isArray8 = Array.isArray, isArray8(val)), isReadonlyArray6;
-var init_values7 = __esm(() => {
- init_error13();
- isReadonlyArray6 = isArray8;
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs
-function* iterateHeaders6(headers) {
- if (!headers)
- return;
- if (brand_privateNullableHeaders6 in headers) {
- const { values: values2, nulls } = headers;
- yield* values2.entries();
- for (const name3 of nulls) {
- yield [name3, null];
- }
- return;
- }
- let shouldClear = false;
- let iter;
- if (headers instanceof Headers) {
- iter = headers.entries();
- } else if (isReadonlyArray6(headers)) {
- iter = headers;
- } else {
- shouldClear = true;
- iter = Object.entries(headers ?? {});
- }
- for (let row of iter) {
- const name3 = row[0];
- if (typeof name3 !== "string")
- throw new TypeError("expected header name to be a string");
- const values2 = isReadonlyArray6(row[1]) ? row[1] : [row[1]];
- let didClear = false;
- for (const value of values2) {
- if (value === undefined)
- continue;
- if (shouldClear && !didClear) {
- didClear = true;
- yield [name3, null];
- }
- yield [name3, value];
- }
- }
-}
-var brand_privateNullableHeaders6, buildHeaders6 = (newHeaders) => {
- const targetHeaders = new Headers;
- const nullHeaders = new Set;
- for (const headers of newHeaders) {
- const seenHeaders = new Set;
- for (const [name3, value] of iterateHeaders6(headers)) {
- const lowerName = name3.toLowerCase();
- if (!seenHeaders.has(lowerName)) {
- targetHeaders.delete(name3);
- seenHeaders.add(lowerName);
- }
- if (value === null) {
- targetHeaders.delete(name3);
- nullHeaders.add(lowerName);
- } else {
- targetHeaders.append(name3, value);
- nullHeaders.delete(lowerName);
- }
- }
- }
- return { [brand_privateNullableHeaders6]: true, values: targetHeaders, nulls: nullHeaders };
-};
-var init_headers6 = __esm(() => {
- init_values7();
- brand_privateNullableHeaders6 = Symbol.for("brand.privateNullableHeaders");
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/client.mjs
-function makeMessagesResource3(client14) {
- const resource = new Messages9(client14);
- delete resource.batches;
- return resource;
-}
-function makeBetaResource3(client14) {
- const resource = new Beta4(client14);
- delete resource.messages.batches;
- return resource;
-}
-var import_google_auth_library, DEFAULT_VERSION2 = "vertex-2023-10-16", MODEL_ENDPOINTS2, AnthropicVertex;
-var init_client18 = __esm(() => {
- init_client17();
- init_resources4();
- init_values7();
- init_headers6();
- init_client17();
- import_google_auth_library = __toESM(require_src6(), 1);
- MODEL_ENDPOINTS2 = new Set(["/v1/messages", "/v1/messages?beta=true"]);
- AnthropicVertex = class AnthropicVertex extends BaseAnthropic3 {
- constructor({ baseURL = readEnv7("ANTHROPIC_VERTEX_BASE_URL"), region = readEnv7("CLOUD_ML_REGION") ?? null, projectId = readEnv7("ANTHROPIC_VERTEX_PROJECT_ID") ?? null, ...opts } = {}) {
- if (!region) {
- throw new Error("No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.");
- }
- super({
- baseURL: baseURL || (region === "global" ? "https://aiplatform.googleapis.com/v1" : `https://${region}-aiplatform.googleapis.com/v1`),
- ...opts
- });
- this.messages = makeMessagesResource3(this);
- this.beta = makeBetaResource3(this);
- this.region = region;
- this.projectId = projectId;
- this.accessToken = opts.accessToken ?? null;
- if (opts.authClient && opts.googleAuth) {
- throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");
- } else if (opts.authClient) {
- this._authClientPromise = Promise.resolve(opts.authClient);
- } else {
- this._auth = opts.googleAuth ?? new import_google_auth_library.GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
- this._authClientPromise = this._auth.getClient();
- }
- }
- validateHeaders() {}
- async prepareOptions(options2) {
- const authClient = await this._authClientPromise;
- const authHeaders = await authClient.getRequestHeaders();
- const projectId = authClient.projectId ?? authHeaders["x-goog-user-project"];
- if (!this.projectId && projectId) {
- this.projectId = projectId;
- }
- options2.headers = buildHeaders6([authHeaders, options2.headers]);
- }
- async buildRequest(options2) {
- if (isObj3(options2.body)) {
- options2.body = { ...options2.body };
- }
- if (isObj3(options2.body)) {
- if (!options2.body["anthropic_version"]) {
- options2.body["anthropic_version"] = DEFAULT_VERSION2;
- }
- }
- if (MODEL_ENDPOINTS2.has(options2.path) && options2.method === "post") {
- if (!this.projectId) {
- throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");
- }
- if (!isObj3(options2.body)) {
- throw new Error("Expected request body to be an object for post /v1/messages");
- }
- const model = options2.body["model"];
- options2.body["model"] = undefined;
- const stream10 = options2.body["stream"] ?? false;
- const specifier = stream10 ? "streamRawPredict" : "rawPredict";
- options2.path = `/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${model}:${specifier}`;
- }
- if (options2.path === "/v1/messages/count_tokens" || options2.path == "/v1/messages/count_tokens?beta=true" && options2.method === "post") {
- if (!this.projectId) {
- throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");
- }
- options2.path = `/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`;
- }
- return super.buildRequest(options2);
- }
- };
-});
-
-// node_modules/@anthropic-ai/vertex-sdk/index.mjs
-var exports_vertex_sdk = {};
-__export(exports_vertex_sdk, {
- default: () => AnthropicVertex,
- BaseAnthropic: () => BaseAnthropic3,
- AnthropicVertex: () => AnthropicVertex
-});
-var init_vertex_sdk = __esm(() => {
- init_client18();
- init_client18();
-});
-
-// src/services/api/client.ts
-import { randomUUID as randomUUID4 } from "crypto";
-function createStderrLogger() {
- return {
- error: (msg, ...args) => console.error("[Anthropic SDK ERROR]", msg, ...args),
- warn: (msg, ...args) => console.error("[Anthropic SDK WARN]", msg, ...args),
- info: (msg, ...args) => console.error("[Anthropic SDK INFO]", msg, ...args),
- debug: (msg, ...args) => console.error("[Anthropic SDK DEBUG]", msg, ...args)
- };
-}
-async function getAnthropicClient({
- apiKey,
- maxRetries,
- model,
- fetchOverride,
- source
-}) {
- const containerId = process.env.CLAUDE_CODE_CONTAINER_ID;
- const remoteSessionId = process.env.CLAUDE_CODE_REMOTE_SESSION_ID;
- const clientApp = process.env.CLAUDE_AGENT_SDK_CLIENT_APP;
- const customHeaders = getCustomHeaders();
- const defaultHeaders = {
- "x-app": "cli",
- "User-Agent": getUserAgent(),
- "X-Claude-Code-Session-Id": getSessionId(),
- ...customHeaders,
- ...containerId ? { "x-claude-remote-container-id": containerId } : {},
- ...remoteSessionId ? { "x-claude-remote-session-id": remoteSessionId } : {},
- ...clientApp ? { "x-client-app": clientApp } : {}
- };
- logForDebugging(`[API:request] Creating client, ANTHROPIC_CUSTOM_HEADERS present: ${!!process.env.ANTHROPIC_CUSTOM_HEADERS}, has Authorization header: ${!!customHeaders["Authorization"]}`);
- const additionalProtectionEnabled = isEnvTruthy(process.env.CLAUDE_CODE_ADDITIONAL_PROTECTION);
- if (additionalProtectionEnabled) {
- defaultHeaders["x-anthropic-additional-protection"] = "true";
- }
- logForDebugging("[API:auth] OAuth token check starting");
- await checkAndRefreshOAuthTokenIfNeeded();
- logForDebugging("[API:auth] OAuth token check complete");
- if (!isClaudeAISubscriber()) {
- await configureApiKeyHeaders(defaultHeaders, getIsNonInteractiveSession());
- }
- const resolvedFetch = buildFetch(fetchOverride, source);
- const ARGS = {
- defaultHeaders,
- maxRetries,
- timeout: parseInt(process.env.API_TIMEOUT_MS || String(600 * 1000), 10),
- dangerouslyAllowBrowser: true,
- fetchOptions: getProxyFetchOptions({
- forAnthropicAPI: true
- }),
- ...resolvedFetch && {
- fetch: resolvedFetch
- }
- };
- if (isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK)) {
- const { AnthropicBedrock: AnthropicBedrock2 } = await Promise.resolve().then(() => (init_bedrock_sdk(), exports_bedrock_sdk));
- const awsRegion = model === getSmallFastModel() && process.env.ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION ? process.env.ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION : getAWSRegion();
- const bedrockArgs = {
- ...ARGS,
- awsRegion,
- ...isEnvTruthy(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH) && {
- skipAuth: true
- },
- ...isDebugToStdErr() && { logger: createStderrLogger() }
- };
- if (process.env.AWS_BEARER_TOKEN_BEDROCK) {
- bedrockArgs.skipAuth = true;
- bedrockArgs.defaultHeaders = {
- ...bedrockArgs.defaultHeaders,
- Authorization: `Bearer ${process.env.AWS_BEARER_TOKEN_BEDROCK}`
- };
- } else if (!isEnvTruthy(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH)) {
- const cachedCredentials = await refreshAndGetAwsCredentials();
- if (cachedCredentials) {
- bedrockArgs.awsAccessKey = cachedCredentials.accessKeyId;
- bedrockArgs.awsSecretKey = cachedCredentials.secretAccessKey;
- bedrockArgs.awsSessionToken = cachedCredentials.sessionToken;
- }
- }
- return new AnthropicBedrock2(bedrockArgs);
- }
- if (isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY)) {
- const { AnthropicFoundry: AnthropicFoundry2 } = await Promise.resolve().then(() => (init_foundry_sdk(), exports_foundry_sdk));
- let azureADTokenProvider;
- if (!process.env.ANTHROPIC_FOUNDRY_API_KEY) {
- if (isEnvTruthy(process.env.CLAUDE_CODE_SKIP_FOUNDRY_AUTH)) {
- azureADTokenProvider = () => Promise.resolve("");
- } else {
- const {
- DefaultAzureCredential: AzureCredential,
- getBearerTokenProvider: getBearerTokenProvider2
- } = await Promise.resolve().then(() => (init_esm9(), exports_esm));
- azureADTokenProvider = getBearerTokenProvider2(new AzureCredential, "https://cognitiveservices.azure.com/.default");
- }
- }
- const foundryArgs = {
- ...ARGS,
- ...azureADTokenProvider && { azureADTokenProvider },
- ...isDebugToStdErr() && { logger: createStderrLogger() }
- };
- return new AnthropicFoundry2(foundryArgs);
- }
- if (isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX)) {
- if (!isEnvTruthy(process.env.CLAUDE_CODE_SKIP_VERTEX_AUTH)) {
- await refreshGcpCredentialsIfNeeded();
- }
- const [{ AnthropicVertex: AnthropicVertex2 }, { GoogleAuth: GoogleAuth2 }] = await Promise.all([
- Promise.resolve().then(() => (init_vertex_sdk(), exports_vertex_sdk)),
- Promise.resolve().then(() => __toESM(require_src6(), 1))
- ]);
- const hasProjectEnvVar = process.env["GCLOUD_PROJECT"] || process.env["GOOGLE_CLOUD_PROJECT"] || process.env["gcloud_project"] || process.env["google_cloud_project"];
- const hasKeyFile = process.env["GOOGLE_APPLICATION_CREDENTIALS"] || process.env["google_application_credentials"];
- const googleAuth = isEnvTruthy(process.env.CLAUDE_CODE_SKIP_VERTEX_AUTH) ? {
- getClient: () => ({
- getRequestHeaders: () => ({})
- })
- } : new GoogleAuth2({
- scopes: ["https://www.googleapis.com/auth/cloud-platform"],
- ...hasProjectEnvVar || hasKeyFile ? {} : {
- projectId: process.env.ANTHROPIC_VERTEX_PROJECT_ID
- }
- });
- const vertexArgs = {
- ...ARGS,
- region: getVertexRegionForModel(model),
- googleAuth,
- ...isDebugToStdErr() && { logger: createStderrLogger() }
- };
- return new AnthropicVertex2(vertexArgs);
- }
- const clientConfig = {
- apiKey: isClaudeAISubscriber() ? null : apiKey || getAnthropicApiKey(),
- authToken: isClaudeAISubscriber() ? getClaudeAIOAuthTokens()?.accessToken : undefined,
- ...process.env.USER_TYPE === "ant" && isEnvTruthy(process.env.USE_STAGING_OAUTH) ? { baseURL: getOauthConfig().BASE_API_URL } : {},
- ...ARGS,
- ...isDebugToStdErr() && { logger: createStderrLogger() }
- };
- return new sdk_default(clientConfig);
-}
-async function configureApiKeyHeaders(headers, isNonInteractiveSession) {
- const token = process.env.ANTHROPIC_AUTH_TOKEN || await getApiKeyFromApiKeyHelper(isNonInteractiveSession);
- if (token) {
- headers["Authorization"] = `Bearer ${token}`;
- }
-}
-function getCustomHeaders() {
- const customHeaders = {};
- const customHeadersEnv = process.env.ANTHROPIC_CUSTOM_HEADERS;
- if (!customHeadersEnv)
- return customHeaders;
- const headerStrings = customHeadersEnv.split(/\n|\r\n/);
- for (const headerString of headerStrings) {
- if (!headerString.trim())
- continue;
- const colonIdx = headerString.indexOf(":");
- if (colonIdx === -1)
- continue;
- const name3 = headerString.slice(0, colonIdx).trim();
- const value = headerString.slice(colonIdx + 1).trim();
- if (name3) {
- customHeaders[name3] = value;
- }
- }
- return customHeaders;
-}
-function buildFetch(fetchOverride, source) {
- const inner = fetchOverride ?? globalThis.fetch;
- const injectClientRequestId = getAPIProvider() === "firstParty" && isFirstPartyAnthropicBaseUrl();
- return (input, init) => {
- const headers = new Headers(init?.headers);
- if (injectClientRequestId && !headers.has(CLIENT_REQUEST_ID_HEADER)) {
- headers.set(CLIENT_REQUEST_ID_HEADER, randomUUID4());
- }
- try {
- const url3 = input instanceof Request ? input.url : String(input);
- const id = headers.get(CLIENT_REQUEST_ID_HEADER);
- logForDebugging(`[API REQUEST] ${new URL(url3).pathname}${id ? ` ${CLIENT_REQUEST_ID_HEADER}=${id}` : ""} source=${source ?? "unknown"}`);
- } catch {}
- return inner(input, { ...init, headers });
- };
-}
-var CLIENT_REQUEST_ID_HEADER = "x-client-request-id";
-var init_client19 = __esm(() => {
- init_sdk();
- init_auth14();
- init_http8();
- init_model();
- init_providers();
- init_proxy();
- init_state();
- init_oauth();
- init_debug();
- init_envUtils();
-});
-
-// src/utils/model/modelCapabilities.ts
-import { readFileSync as readFileSync8 } from "fs";
-import { mkdir as mkdir3, writeFile as writeFile3 } from "fs/promises";
-import { join as join22 } from "path";
-function getCacheDir() {
- return join22(getClaudeConfigHomeDir(), "cache");
-}
-function getCachePath() {
- return join22(getCacheDir(), "model-capabilities.json");
-}
-function isModelCapabilitiesEligible() {
- if (process.env.USER_TYPE !== "ant")
- return false;
- if (getAPIProvider() !== "firstParty")
- return false;
- if (!isFirstPartyAnthropicBaseUrl())
- return false;
- return true;
-}
-function sortForMatching(models) {
- return [...models].sort((a5, b4) => b4.id.length - a5.id.length || a5.id.localeCompare(b4.id));
-}
-function getModelCapability(model) {
- if (!isModelCapabilitiesEligible())
- return;
- const cached2 = loadCache(getCachePath());
- if (!cached2 || cached2.length === 0)
- return;
- const m4 = model.toLowerCase();
- const exact = cached2.find((c8) => c8.id.toLowerCase() === m4);
- if (exact)
- return exact;
- return cached2.find((c8) => m4.includes(c8.id.toLowerCase()));
-}
-async function refreshModelCapabilities() {
- if (!isModelCapabilitiesEligible())
- return;
- if (isEssentialTrafficOnly())
- return;
- try {
- const anthropic = await getAnthropicClient({ maxRetries: 1 });
- const betas = isClaudeAISubscriber() ? [OAUTH_BETA_HEADER] : undefined;
- const parsed = [];
- for await (const entry of anthropic.models.list({ betas })) {
- const result = ModelCapabilitySchema().safeParse(entry);
- if (result.success)
- parsed.push(result.data);
- }
- if (parsed.length === 0)
- return;
- const path14 = getCachePath();
- const models = sortForMatching(parsed);
- if (isEqual_default(loadCache(path14), models)) {
- logForDebugging("[modelCapabilities] cache unchanged, skipping write");
- return;
- }
- await mkdir3(getCacheDir(), { recursive: true });
- await writeFile3(path14, jsonStringify({ models, timestamp: Date.now() }), {
- encoding: "utf-8",
- mode: 384
- });
- loadCache.cache.delete(path14);
- logForDebugging(`[modelCapabilities] cached ${models.length} models`);
- } catch (error46) {
- logForDebugging(`[modelCapabilities] fetch failed: ${error46 instanceof Error ? error46.message : "unknown"}`);
- }
-}
-var ModelCapabilitySchema, CacheFileSchema, loadCache;
-var init_modelCapabilities = __esm(() => {
- init_isEqual();
- init_memoize();
- init_v4();
- init_oauth();
- init_client19();
- init_auth14();
- init_debug();
- init_envUtils();
- init_json();
- init_slowOperations();
- init_providers();
- ModelCapabilitySchema = lazySchema(() => exports_external.object({
- id: exports_external.string(),
- max_input_tokens: exports_external.number().optional(),
- max_tokens: exports_external.number().optional()
- }).strip());
- CacheFileSchema = lazySchema(() => exports_external.object({
- models: exports_external.array(ModelCapabilitySchema()),
- timestamp: exports_external.number()
- }));
- loadCache = memoize_default((path14) => {
- try {
- const raw = readFileSync8(path14, "utf-8");
- const parsed = CacheFileSchema().safeParse(safeParseJSON(raw, false));
- return parsed.success ? parsed.data.models : null;
- } catch {
- return null;
- }
- }, (path14) => path14);
-});
-
-// src/utils/context.ts
-function is1mContextDisabled() {
- return isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_1M_CONTEXT);
-}
-function has1mContext(model) {
- if (is1mContextDisabled()) {
- return false;
- }
- return /\[1m\]/i.test(model);
-}
-function modelSupports1M(model) {
- if (is1mContextDisabled()) {
- return false;
- }
- const canonical = getCanonicalName(model);
- return canonical.includes("claude-sonnet-4") || canonical.includes("opus-4-6");
-}
-function getContextWindowForModel(model, betas) {
- if (process.env.USER_TYPE === "ant" && process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS) {
- const override = parseInt(process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS, 10);
- if (!isNaN(override) && override > 0) {
- return override;
- }
- }
- if (has1mContext(model)) {
- return 1e6;
- }
- const cap = getModelCapability(model);
- if (cap?.max_input_tokens && cap.max_input_tokens >= 1e5) {
- if (cap.max_input_tokens > MODEL_CONTEXT_WINDOW_DEFAULT && is1mContextDisabled()) {
- return MODEL_CONTEXT_WINDOW_DEFAULT;
- }
- return cap.max_input_tokens;
- }
- if (betas?.includes(CONTEXT_1M_BETA_HEADER) && modelSupports1M(model)) {
- return 1e6;
- }
- if (getSonnet1mExpTreatmentEnabled(model)) {
- return 1e6;
- }
- if (process.env.USER_TYPE === "ant") {
- const antModel = resolveAntModel(model);
- if (antModel?.contextWindow) {
- return antModel.contextWindow;
- }
- }
- return MODEL_CONTEXT_WINDOW_DEFAULT;
-}
-function getSonnet1mExpTreatmentEnabled(model) {
- if (is1mContextDisabled()) {
- return false;
- }
- if (has1mContext(model)) {
- return false;
- }
- if (!getCanonicalName(model).includes("sonnet-4-6")) {
- return false;
- }
- return getGlobalConfig().clientDataCache?.["coral_reef_sonnet"] === "true";
-}
-function calculateContextPercentages(currentUsage, contextWindowSize) {
- if (!currentUsage) {
- return { used: null, remaining: null };
- }
- const totalInputTokens = currentUsage.input_tokens + currentUsage.cache_creation_input_tokens + currentUsage.cache_read_input_tokens;
- const usedPercentage = Math.round(totalInputTokens / contextWindowSize * 100);
- const clampedUsed = Math.min(100, Math.max(0, usedPercentage));
- return {
- used: clampedUsed,
- remaining: 100 - clampedUsed
- };
-}
-function getModelMaxOutputTokens(model) {
- let defaultTokens;
- let upperLimit;
- if (process.env.USER_TYPE === "ant") {
- const antModel = resolveAntModel(model.toLowerCase());
- if (antModel) {
- defaultTokens = antModel.defaultMaxTokens ?? MAX_OUTPUT_TOKENS_DEFAULT;
- upperLimit = antModel.upperMaxTokensLimit ?? MAX_OUTPUT_TOKENS_UPPER_LIMIT;
- return { default: defaultTokens, upperLimit };
- }
- }
- const m4 = getCanonicalName(model);
- if (m4.includes("opus-4-6")) {
- defaultTokens = 64000;
- upperLimit = 128000;
- } else if (m4.includes("sonnet-4-6")) {
- defaultTokens = 32000;
- upperLimit = 128000;
- } else if (m4.includes("opus-4-5") || m4.includes("sonnet-4") || m4.includes("haiku-4")) {
- defaultTokens = 32000;
- upperLimit = 64000;
- } else if (m4.includes("opus-4-1") || m4.includes("opus-4")) {
- defaultTokens = 32000;
- upperLimit = 32000;
- } else if (m4.includes("claude-3-opus")) {
- defaultTokens = 4096;
- upperLimit = 4096;
- } else if (m4.includes("claude-3-sonnet")) {
- defaultTokens = 8192;
- upperLimit = 8192;
- } else if (m4.includes("claude-3-haiku")) {
- defaultTokens = 4096;
- upperLimit = 4096;
- } else if (m4.includes("3-5-sonnet") || m4.includes("3-5-haiku")) {
- defaultTokens = 8192;
- upperLimit = 8192;
- } else if (m4.includes("3-7-sonnet")) {
- defaultTokens = 32000;
- upperLimit = 64000;
- } else {
- defaultTokens = MAX_OUTPUT_TOKENS_DEFAULT;
- upperLimit = MAX_OUTPUT_TOKENS_UPPER_LIMIT;
- }
- const cap = getModelCapability(model);
- if (cap?.max_tokens && cap.max_tokens >= 4096) {
- upperLimit = cap.max_tokens;
- defaultTokens = Math.min(defaultTokens, upperLimit);
- }
- return { default: defaultTokens, upperLimit };
-}
-function getMaxThinkingTokensForModel(model) {
- return getModelMaxOutputTokens(model).upperLimit - 1;
-}
-var MODEL_CONTEXT_WINDOW_DEFAULT = 200000, COMPACT_MAX_OUTPUT_TOKENS = 20000, MAX_OUTPUT_TOKENS_DEFAULT = 32000, MAX_OUTPUT_TOKENS_UPPER_LIMIT = 64000, CAPPED_DEFAULT_MAX_TOKENS = 8000, ESCALATED_MAX_TOKENS = 64000;
-var init_context = __esm(() => {
- init_betas();
- init_config();
- init_envUtils();
- init_model();
- init_modelCapabilities();
-});
-
-// src/utils/model/modelSupportOverrides.ts
-var TIERS, get3PModelCapabilityOverride;
-var init_modelSupportOverrides = __esm(() => {
- init_memoize();
- init_providers();
- TIERS = [
- {
- modelEnvVar: "ANTHROPIC_DEFAULT_OPUS_MODEL",
- capabilitiesEnvVar: "ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES"
- },
- {
- modelEnvVar: "ANTHROPIC_DEFAULT_SONNET_MODEL",
- capabilitiesEnvVar: "ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES"
- },
- {
- modelEnvVar: "ANTHROPIC_DEFAULT_HAIKU_MODEL",
- capabilitiesEnvVar: "ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES"
- }
- ];
- get3PModelCapabilityOverride = memoize_default((model, capability) => {
- if (getAPIProvider() === "firstParty") {
- return;
- }
- const m4 = model.toLowerCase();
- for (const tier of TIERS) {
- const pinned = process.env[tier.modelEnvVar];
- const capabilities = process.env[tier.capabilitiesEnvVar];
- if (!pinned || capabilities === undefined)
- continue;
- if (m4 !== pinned.toLowerCase())
- continue;
- return capabilities.toLowerCase().split(",").map((s4) => s4.trim()).includes(capability);
- }
- return;
- }, (model, capability) => `${model.toLowerCase()}:${capability}`);
-});
-
-// src/utils/betas.ts
-function partitionBetasByAllowlist(betas) {
- const allowed = [];
- const disallowed = [];
- for (const beta of betas) {
- if (ALLOWED_SDK_BETAS.includes(beta)) {
- allowed.push(beta);
- } else {
- disallowed.push(beta);
- }
- }
- return { allowed, disallowed };
-}
-function filterAllowedSdkBetas(sdkBetas) {
- if (!sdkBetas || sdkBetas.length === 0) {
- return;
- }
- if (isClaudeAISubscriber()) {
- console.warn("Warning: Custom betas are only available for API key users. Ignoring provided betas.");
- return;
- }
- const { allowed, disallowed } = partitionBetasByAllowlist(sdkBetas);
- for (const beta of disallowed) {
- console.warn(`Warning: Beta header '${beta}' is not allowed. Only the following betas are supported: ${ALLOWED_SDK_BETAS.join(", ")}`);
- }
- return allowed.length > 0 ? allowed : undefined;
-}
-function modelSupportsISP(model) {
- const supported3P = get3PModelCapabilityOverride(model, "interleaved_thinking");
- if (supported3P !== undefined) {
- return supported3P;
- }
- const canonical = getCanonicalName(model);
- const provider5 = getAPIProvider();
- if (provider5 === "foundry") {
- return true;
- }
- if (provider5 === "firstParty") {
- return !canonical.includes("claude-3-");
- }
- return canonical.includes("claude-opus-4") || canonical.includes("claude-sonnet-4");
-}
-function vertexModelSupportsWebSearch(model) {
- const canonical = getCanonicalName(model);
- return canonical.includes("claude-opus-4") || canonical.includes("claude-sonnet-4") || canonical.includes("claude-haiku-4");
-}
-function modelSupportsContextManagement(model) {
- const canonical = getCanonicalName(model);
- const provider5 = getAPIProvider();
- if (provider5 === "foundry") {
- return true;
- }
- if (provider5 === "firstParty") {
- return !canonical.includes("claude-3-");
- }
- return canonical.includes("claude-opus-4") || canonical.includes("claude-sonnet-4") || canonical.includes("claude-haiku-4");
-}
-function modelSupportsStructuredOutputs(model) {
- const canonical = getCanonicalName(model);
- const provider5 = getAPIProvider();
- if (provider5 !== "firstParty" && provider5 !== "foundry") {
- return false;
- }
- return canonical.includes("claude-sonnet-4-6") || canonical.includes("claude-sonnet-4-5") || canonical.includes("claude-opus-4-1") || canonical.includes("claude-opus-4-5") || canonical.includes("claude-opus-4-6") || canonical.includes("claude-haiku-4-5");
-}
-function modelSupportsAutoMode(model) {
- if (false) {}
- return false;
-}
-function getToolSearchBetaHeader() {
- const provider5 = getAPIProvider();
- if (provider5 === "vertex" || provider5 === "bedrock") {
- return TOOL_SEARCH_BETA_HEADER_3P;
- }
- return TOOL_SEARCH_BETA_HEADER_1P;
-}
-function shouldIncludeFirstPartyOnlyBetas() {
- return (getAPIProvider() === "firstParty" || getAPIProvider() === "foundry") && !isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS);
-}
-function shouldUseGlobalCacheScope() {
- return getAPIProvider() === "firstParty" && !isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS);
-}
-function getMergedBetas(model, options2) {
- const baseBetas = [...getModelBetas(model)];
- if (options2?.isAgenticQuery) {
- if (!baseBetas.includes(CLAUDE_CODE_20250219_BETA_HEADER)) {
- baseBetas.push(CLAUDE_CODE_20250219_BETA_HEADER);
- }
- if (process.env.USER_TYPE === "ant" && process.env.CLAUDE_CODE_ENTRYPOINT === "cli" && CLI_INTERNAL_BETA_HEADER && !baseBetas.includes(CLI_INTERNAL_BETA_HEADER)) {
- baseBetas.push(CLI_INTERNAL_BETA_HEADER);
- }
- }
- const sdkBetas = getSdkBetas();
- if (!sdkBetas || sdkBetas.length === 0) {
- return baseBetas;
- }
- return [...baseBetas, ...sdkBetas.filter((b4) => !baseBetas.includes(b4))];
-}
-function clearBetasCaches() {
- getAllModelBetas.cache?.clear?.();
- getModelBetas.cache?.clear?.();
- getBedrockExtraBodyParamsBetas.cache?.clear?.();
-}
-var ALLOWED_SDK_BETAS, getAllModelBetas, getModelBetas, getBedrockExtraBodyParamsBetas;
-var init_betas2 = __esm(() => {
- init_memoize();
- init_growthbook();
- init_state();
- init_betas();
- init_oauth();
- init_auth14();
- init_context();
- init_envUtils();
- init_model();
- init_modelSupportOverrides();
- init_providers();
- init_settings2();
- ALLOWED_SDK_BETAS = [CONTEXT_1M_BETA_HEADER];
- getAllModelBetas = memoize_default((model) => {
- const betaHeaders = [];
- const isHaiku = getCanonicalName(model).includes("haiku");
- const provider5 = getAPIProvider();
- const includeFirstPartyOnlyBetas = shouldIncludeFirstPartyOnlyBetas();
- if (!isHaiku) {
- betaHeaders.push(CLAUDE_CODE_20250219_BETA_HEADER);
- if (process.env.USER_TYPE === "ant" && process.env.CLAUDE_CODE_ENTRYPOINT === "cli") {
- if (CLI_INTERNAL_BETA_HEADER) {
- betaHeaders.push(CLI_INTERNAL_BETA_HEADER);
- }
- }
- }
- if (isClaudeAISubscriber()) {
- betaHeaders.push(OAUTH_BETA_HEADER);
- }
- if (has1mContext(model)) {
- betaHeaders.push(CONTEXT_1M_BETA_HEADER);
- }
- if (!isEnvTruthy(process.env.DISABLE_INTERLEAVED_THINKING) && modelSupportsISP(model)) {
- betaHeaders.push(INTERLEAVED_THINKING_BETA_HEADER);
- }
- if (includeFirstPartyOnlyBetas && modelSupportsISP(model) && !getIsNonInteractiveSession() && getInitialSettings().showThinkingSummaries !== true) {
- betaHeaders.push(REDACT_THINKING_BETA_HEADER);
- }
- if (SUMMARIZE_CONNECTOR_TEXT_BETA_HEADER && process.env.USER_TYPE === "ant" && includeFirstPartyOnlyBetas && !isEnvDefinedFalsy(process.env.USE_CONNECTOR_TEXT_SUMMARIZATION) && (isEnvTruthy(process.env.USE_CONNECTOR_TEXT_SUMMARIZATION) || getFeatureValue_CACHED_MAY_BE_STALE("tengu_slate_prism", false))) {
- betaHeaders.push(SUMMARIZE_CONNECTOR_TEXT_BETA_HEADER);
- }
- const antOptedIntoToolClearing = isEnvTruthy(process.env.USE_API_CONTEXT_MANAGEMENT) && process.env.USER_TYPE === "ant";
- const thinkingPreservationEnabled = modelSupportsContextManagement(model);
- if (shouldIncludeFirstPartyOnlyBetas() && (antOptedIntoToolClearing || thinkingPreservationEnabled)) {
- betaHeaders.push(CONTEXT_MANAGEMENT_BETA_HEADER);
- }
- const strictToolsEnabled = checkStatsigFeatureGate_CACHED_MAY_BE_STALE("tengu_tool_pear");
- const tokenEfficientToolsEnabled = !strictToolsEnabled && getFeatureValue_CACHED_MAY_BE_STALE("tengu_amber_json_tools", false);
- if (includeFirstPartyOnlyBetas && modelSupportsStructuredOutputs(model) && strictToolsEnabled) {
- betaHeaders.push(STRUCTURED_OUTPUTS_BETA_HEADER);
- }
- if (process.env.USER_TYPE === "ant" && includeFirstPartyOnlyBetas && tokenEfficientToolsEnabled) {
- betaHeaders.push(TOKEN_EFFICIENT_TOOLS_BETA_HEADER);
- }
- if (provider5 === "vertex" && vertexModelSupportsWebSearch(model)) {
- betaHeaders.push(WEB_SEARCH_BETA_HEADER);
- }
- if (provider5 === "foundry") {
- betaHeaders.push(WEB_SEARCH_BETA_HEADER);
- }
- if (includeFirstPartyOnlyBetas) {
- betaHeaders.push(PROMPT_CACHING_SCOPE_BETA_HEADER);
- }
- if (process.env.ANTHROPIC_BETAS) {
- betaHeaders.push(...process.env.ANTHROPIC_BETAS.split(",").map((_) => _.trim()).filter(Boolean));
- }
- return betaHeaders;
- });
- getModelBetas = memoize_default((model) => {
- const modelBetas = getAllModelBetas(model);
- if (getAPIProvider() === "bedrock") {
- return modelBetas.filter((b4) => !BEDROCK_EXTRA_PARAMS_HEADERS.has(b4));
- }
- return modelBetas;
- });
- getBedrockExtraBodyParamsBetas = memoize_default((model) => {
- const modelBetas = getAllModelBetas(model);
- return modelBetas.filter((b4) => BEDROCK_EXTRA_PARAMS_HEADERS.has(b4));
- });
-});
-
-// src/utils/secureStorage/fallbackStorage.ts
-function createFallbackStorage(primary, secondary) {
- return {
- name: `${primary.name}-with-${secondary.name}-fallback`,
- read() {
- const result = primary.read();
- if (result !== null && result !== undefined) {
- return result;
- }
- return secondary.read() || {};
- },
- async readAsync() {
- const result = await primary.readAsync();
- if (result !== null && result !== undefined) {
- return result;
- }
- return await secondary.readAsync() || {};
- },
- update(data) {
- const primaryDataBefore = primary.read();
- const result = primary.update(data);
- if (result.success) {
- if (primaryDataBefore === null) {
- secondary.delete();
- }
- return result;
- }
- const fallbackResult = secondary.update(data);
- if (fallbackResult.success) {
- if (primaryDataBefore !== null) {
- primary.delete();
- }
- return {
- success: true,
- warning: fallbackResult.warning
- };
- }
- return { success: false };
- },
- delete() {
- const primarySuccess = primary.delete();
- const secondarySuccess = secondary.delete();
- return primarySuccess || secondarySuccess;
- }
- };
-}
-
-// src/utils/secureStorage/macOsKeychainStorage.ts
-async function doReadAsync() {
- try {
- const storageServiceName = getMacOsKeychainStorageServiceName(CREDENTIALS_SERVICE_SUFFIX);
- const username = getUsername();
- const { stdout, code } = await execFileNoThrow("security", ["find-generic-password", "-a", username, "-w", "-s", storageServiceName], { useCwd: false, preserveOutputOnError: false });
- if (code === 0 && stdout) {
- return jsonParse(stdout.trim());
- }
- } catch (_e4) {}
- return null;
-}
-function isMacOsKeychainLocked() {
- if (keychainLockedCache !== undefined)
- return keychainLockedCache;
- if (process.platform !== "darwin") {
- keychainLockedCache = false;
- return false;
- }
- try {
- const result = execaSync("security", ["show-keychain-info"], {
- reject: false,
- stdio: ["ignore", "pipe", "pipe"]
- });
- keychainLockedCache = result.exitCode === 36;
- } catch {
- keychainLockedCache = false;
- }
- return keychainLockedCache;
-}
-var SECURITY_STDIN_LINE_LIMIT, macOsKeychainStorage, keychainLockedCache;
-var init_macOsKeychainStorage = __esm(() => {
- init_execa();
- init_debug();
- init_execFileNoThrow();
- init_execFileNoThrowPortable();
- init_slowOperations();
- init_macOsKeychainHelpers();
- SECURITY_STDIN_LINE_LIMIT = 4096 - 64;
- macOsKeychainStorage = {
- name: "keychain",
- read() {
- const prev = keychainCacheState.cache;
- if (Date.now() - prev.cachedAt < KEYCHAIN_CACHE_TTL_MS) {
- return prev.data;
- }
- try {
- const storageServiceName = getMacOsKeychainStorageServiceName(CREDENTIALS_SERVICE_SUFFIX);
- const username = getUsername();
- const result = execSyncWithDefaults_DEPRECATED(`security find-generic-password -a "${username}" -w -s "${storageServiceName}"`);
- if (result) {
- const data = jsonParse(result);
- keychainCacheState.cache = { data, cachedAt: Date.now() };
- return data;
- }
- } catch (_e4) {}
- if (prev.data !== null) {
- logForDebugging("[keychain] read failed; serving stale cache", {
- level: "warn"
- });
- keychainCacheState.cache = { data: prev.data, cachedAt: Date.now() };
- return prev.data;
- }
- keychainCacheState.cache = { data: null, cachedAt: Date.now() };
- return null;
- },
- async readAsync() {
- const prev = keychainCacheState.cache;
- if (Date.now() - prev.cachedAt < KEYCHAIN_CACHE_TTL_MS) {
- return prev.data;
- }
- if (keychainCacheState.readInFlight) {
- return keychainCacheState.readInFlight;
- }
- const gen = keychainCacheState.generation;
- const promise2 = doReadAsync().then((data) => {
- if (gen === keychainCacheState.generation) {
- if (data === null && prev.data !== null) {
- logForDebugging("[keychain] readAsync failed; serving stale cache", {
- level: "warn"
- });
- }
- const next = data ?? prev.data;
- keychainCacheState.cache = { data: next, cachedAt: Date.now() };
- keychainCacheState.readInFlight = null;
- return next;
- }
- return data;
- });
- keychainCacheState.readInFlight = promise2;
- return promise2;
- },
- update(data) {
- clearKeychainCache();
- try {
- const storageServiceName = getMacOsKeychainStorageServiceName(CREDENTIALS_SERVICE_SUFFIX);
- const username = getUsername();
- const jsonString = jsonStringify(data);
- const hexValue = Buffer.from(jsonString, "utf-8").toString("hex");
- const command12 = `add-generic-password -U -a "${username}" -s "${storageServiceName}" -X "${hexValue}"
-`;
- let result;
- if (command12.length <= SECURITY_STDIN_LINE_LIMIT) {
- result = execaSync("security", ["-i"], {
- input: command12,
- stdio: ["pipe", "pipe", "pipe"],
- reject: false
- });
- } else {
- logForDebugging(`Keychain payload (${jsonString.length}B JSON) exceeds security -i stdin limit; using argv`, { level: "warn" });
- result = execaSync("security", [
- "add-generic-password",
- "-U",
- "-a",
- username,
- "-s",
- storageServiceName,
- "-X",
- hexValue
- ], { stdio: ["ignore", "pipe", "pipe"], reject: false });
- }
- if (result.exitCode !== 0) {
- return { success: false };
- }
- keychainCacheState.cache = { data, cachedAt: Date.now() };
- return { success: true };
- } catch (_e4) {
- return { success: false };
- }
- },
- delete() {
- clearKeychainCache();
- try {
- const storageServiceName = getMacOsKeychainStorageServiceName(CREDENTIALS_SERVICE_SUFFIX);
- const username = getUsername();
- execSyncWithDefaults_DEPRECATED(`security delete-generic-password -a "${username}" -s "${storageServiceName}"`);
- return true;
- } catch (_e4) {
- return false;
- }
- }
- };
-});
-
-// src/utils/secureStorage/plainTextStorage.ts
-import { chmodSync as chmodSync2 } from "fs";
-import { join as join23 } from "path";
-function getStoragePath() {
- const storageDir = getClaudeConfigHomeDir();
- const storageFileName = ".credentials.json";
- return { storageDir, storagePath: join23(storageDir, storageFileName) };
-}
-var plainTextStorage;
-var init_plainTextStorage = __esm(() => {
- init_envUtils();
- init_errors();
- init_fsOperations();
- init_slowOperations();
- plainTextStorage = {
- name: "plaintext",
- read() {
- const { storagePath } = getStoragePath();
- try {
- const data = getFsImplementation().readFileSync(storagePath, {
- encoding: "utf8"
- });
- return jsonParse(data);
- } catch {
- return null;
- }
- },
- async readAsync() {
- const { storagePath } = getStoragePath();
- try {
- const data = await getFsImplementation().readFile(storagePath, {
- encoding: "utf8"
- });
- return jsonParse(data);
- } catch {
- return null;
- }
- },
- update(data) {
- try {
- const { storageDir, storagePath } = getStoragePath();
- try {
- getFsImplementation().mkdirSync(storageDir);
- } catch (e4) {
- const code = getErrnoCode(e4);
- if (code !== "EEXIST") {
- throw e4;
- }
- }
- writeFileSync_DEPRECATED(storagePath, jsonStringify(data), {
- encoding: "utf8",
- flush: false
- });
- chmodSync2(storagePath, 384);
- return {
- success: true,
- warning: "Warning: Storing credentials in plaintext."
- };
- } catch {
- return { success: false };
- }
- },
- delete() {
- const { storagePath } = getStoragePath();
- try {
- getFsImplementation().unlinkSync(storagePath);
- return true;
- } catch (e4) {
- const code = getErrnoCode(e4);
- if (code === "ENOENT") {
- return true;
- }
- return false;
- }
- }
- };
-});
-
-// src/utils/secureStorage/index.ts
-function getSecureStorage() {
- if (process.platform === "darwin") {
- return createFallbackStorage(macOsKeychainStorage, plainTextStorage);
- }
- return plainTextStorage;
-}
-var init_secureStorage = __esm(() => {
- init_macOsKeychainStorage();
- init_plainTextStorage();
-});
-
-// src/utils/sleep.ts
-function sleep6(ms, signal, opts) {
- return new Promise((resolve9, reject) => {
- if (signal?.aborted) {
- if (opts?.throwOnAbort || opts?.abortError) {
- reject(opts.abortError?.() ?? new Error("aborted"));
- } else {
- resolve9();
- }
- return;
- }
- const timer = setTimeout((signal2, onAbort2, resolve10) => {
- signal2?.removeEventListener("abort", onAbort2);
- resolve10();
- }, ms, signal, onAbort, resolve9);
- function onAbort() {
- clearTimeout(timer);
- if (opts?.throwOnAbort || opts?.abortError) {
- reject(opts.abortError?.() ?? new Error("aborted"));
- } else {
- resolve9();
- }
- }
- signal?.addEventListener("abort", onAbort, { once: true });
- if (opts?.unref) {
- timer.unref();
- }
- });
-}
-
-// src/utils/toolSchemaCache.ts
-function getToolSchemaCache() {
- return TOOL_SCHEMA_CACHE;
-}
-function clearToolSchemaCache() {
- TOOL_SCHEMA_CACHE.clear();
-}
-var TOOL_SCHEMA_CACHE;
-var init_toolSchemaCache = __esm(() => {
- TOOL_SCHEMA_CACHE = new Map;
-});
-
-// src/utils/auth.ts
-var exports_auth = {};
-__export(exports_auth, {
- validateForceLoginOrg: () => validateForceLoginOrg,
- saveOAuthTokensIfNeeded: () => saveOAuthTokensIfNeeded,
- saveApiKey: () => saveApiKey,
- removeApiKey: () => removeApiKey,
- refreshGcpCredentialsIfNeeded: () => refreshGcpCredentialsIfNeeded,
- refreshGcpAuth: () => refreshGcpAuth,
- refreshAwsAuth: () => refreshAwsAuth,
- refreshAndGetAwsCredentials: () => refreshAndGetAwsCredentials,
- prefetchGcpCredentialsIfSafe: () => prefetchGcpCredentialsIfSafe,
- prefetchAwsCredentialsAndBedRockInfoIfSafe: () => prefetchAwsCredentialsAndBedRockInfoIfSafe,
- prefetchApiKeyFromApiKeyHelperIfSafe: () => prefetchApiKeyFromApiKeyHelperIfSafe,
- isUsing3PServices: () => isUsing3PServices,
- isTeamSubscriber: () => isTeamSubscriber,
- isTeamPremiumSubscriber: () => isTeamPremiumSubscriber,
- isProSubscriber: () => isProSubscriber,
- isOverageProvisioningAllowed: () => isOverageProvisioningAllowed,
- isOtelHeadersHelperFromProjectOrLocalSettings: () => isOtelHeadersHelperFromProjectOrLocalSettings,
- isMaxSubscriber: () => isMaxSubscriber,
- isGcpAuthRefreshFromProjectSettings: () => isGcpAuthRefreshFromProjectSettings,
- isEnterpriseSubscriber: () => isEnterpriseSubscriber,
- isCustomApiKeyApproved: () => isCustomApiKeyApproved,
- isConsumerSubscriber: () => isConsumerSubscriber,
- isClaudeAISubscriber: () => isClaudeAISubscriber,
- isAwsCredentialExportFromProjectSettings: () => isAwsCredentialExportFromProjectSettings,
- isAwsAuthRefreshFromProjectSettings: () => isAwsAuthRefreshFromProjectSettings,
- isAnthropicAuthEnabled: () => isAnthropicAuthEnabled,
- is1PApiCustomer: () => is1PApiCustomer,
- hasProfileScope: () => hasProfileScope,
- hasOpusAccess: () => hasOpusAccess,
- hasAnthropicApiKeyAuth: () => hasAnthropicApiKeyAuth,
- handleOAuth401Error: () => handleOAuth401Error,
- getSubscriptionType: () => getSubscriptionType,
- getSubscriptionName: () => getSubscriptionName,
- getRateLimitTier: () => getRateLimitTier,
- getOtelHeadersFromHelper: () => getOtelHeadersFromHelper,
- getOauthAccountInfo: () => getOauthAccountInfo,
- getConfiguredApiKeyHelper: () => getConfiguredApiKeyHelper,
- getClaudeAIOAuthTokensAsync: () => getClaudeAIOAuthTokensAsync,
- getClaudeAIOAuthTokens: () => getClaudeAIOAuthTokens,
- getAuthTokenSource: () => getAuthTokenSource,
- getApiKeyHelperElapsedMs: () => getApiKeyHelperElapsedMs,
- getApiKeyFromConfigOrMacOSKeychain: () => getApiKeyFromConfigOrMacOSKeychain,
- getApiKeyFromApiKeyHelperCached: () => getApiKeyFromApiKeyHelperCached,
- getApiKeyFromApiKeyHelper: () => getApiKeyFromApiKeyHelper,
- getAnthropicApiKeyWithSource: () => getAnthropicApiKeyWithSource,
- getAnthropicApiKey: () => getAnthropicApiKey,
- getAccountInformation: () => getAccountInformation,
- clearOAuthTokenCache: () => clearOAuthTokenCache,
- clearGcpCredentialsCache: () => clearGcpCredentialsCache,
- clearAwsCredentialsCache: () => clearAwsCredentialsCache,
- clearApiKeyHelperCache: () => clearApiKeyHelperCache,
- checkGcpCredentialsValid: () => checkGcpCredentialsValid,
- checkAndRefreshOAuthTokenIfNeeded: () => checkAndRefreshOAuthTokenIfNeeded,
- calculateApiKeyHelperTTL: () => calculateApiKeyHelperTTL
-});
-import { exec as exec2 } from "child_process";
-import { mkdir as mkdir4, stat as stat6 } from "fs/promises";
-import { join as join24 } from "path";
-function isManagedOAuthContext() {
- return isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) || process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop";
-}
-function isAnthropicAuthEnabled() {
- if (isBareMode())
- return false;
- if (process.env.ANTHROPIC_UNIX_SOCKET) {
- return !!process.env.CLAUDE_CODE_OAUTH_TOKEN;
- }
- const is3P = isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) || isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) || isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY);
- const settings = getSettings_DEPRECATED() || {};
- const apiKeyHelper = settings.apiKeyHelper;
- const hasExternalAuthToken = process.env.ANTHROPIC_AUTH_TOKEN || apiKeyHelper || process.env.CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR;
- const { source: apiKeySource } = getAnthropicApiKeyWithSource({
- skipRetrievingKeyFromApiKeyHelper: true
- });
- const hasExternalApiKey = apiKeySource === "ANTHROPIC_API_KEY" || apiKeySource === "apiKeyHelper";
- const shouldDisableAuth = is3P || hasExternalAuthToken && !isManagedOAuthContext() || hasExternalApiKey && !isManagedOAuthContext();
- return !shouldDisableAuth;
-}
-function getAuthTokenSource() {
- if (isBareMode()) {
- if (getConfiguredApiKeyHelper()) {
- return { source: "apiKeyHelper", hasToken: true };
- }
- return { source: "none", hasToken: false };
- }
- if (process.env.ANTHROPIC_AUTH_TOKEN && !isManagedOAuthContext()) {
- return { source: "ANTHROPIC_AUTH_TOKEN", hasToken: true };
- }
- if (process.env.CLAUDE_CODE_OAUTH_TOKEN) {
- return { source: "CLAUDE_CODE_OAUTH_TOKEN", hasToken: true };
- }
- const oauthTokenFromFd = getOAuthTokenFromFileDescriptor();
- if (oauthTokenFromFd) {
- if (process.env.CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR) {
- return {
- source: "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
- hasToken: true
- };
- }
- return {
- source: "CCR_OAUTH_TOKEN_FILE",
- hasToken: true
- };
- }
- const apiKeyHelper = getConfiguredApiKeyHelper();
- if (apiKeyHelper && !isManagedOAuthContext()) {
- return { source: "apiKeyHelper", hasToken: true };
- }
- const oauthTokens = getClaudeAIOAuthTokens();
- if (shouldUseClaudeAIAuth(oauthTokens?.scopes) && oauthTokens?.accessToken) {
- return { source: "claude.ai", hasToken: true };
- }
- return { source: "none", hasToken: false };
-}
-function getAnthropicApiKey() {
- const { key } = getAnthropicApiKeyWithSource();
- return key;
-}
-function hasAnthropicApiKeyAuth() {
- const { key, source } = getAnthropicApiKeyWithSource({
- skipRetrievingKeyFromApiKeyHelper: true
- });
- return key !== null && source !== "none";
-}
-function getAnthropicApiKeyWithSource(opts = {}) {
- if (isBareMode()) {
- if (process.env.ANTHROPIC_API_KEY) {
- return { key: process.env.ANTHROPIC_API_KEY, source: "ANTHROPIC_API_KEY" };
- }
- if (getConfiguredApiKeyHelper()) {
- return {
- key: opts.skipRetrievingKeyFromApiKeyHelper ? null : getApiKeyFromApiKeyHelperCached(),
- source: "apiKeyHelper"
- };
- }
- return { key: null, source: "none" };
- }
- const apiKeyEnv = isRunningOnHomespace() ? undefined : process.env.ANTHROPIC_API_KEY;
- if (preferThirdPartyAuthentication() && apiKeyEnv) {
- return {
- key: apiKeyEnv,
- source: "ANTHROPIC_API_KEY"
- };
- }
- if (isEnvTruthy(process.env.CI) || false) {
- const apiKeyFromFd2 = getApiKeyFromFileDescriptor();
- if (apiKeyFromFd2) {
- return {
- key: apiKeyFromFd2,
- source: "ANTHROPIC_API_KEY"
- };
- }
- if (!apiKeyEnv && !process.env.CLAUDE_CODE_OAUTH_TOKEN && !process.env.CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR) {
- throw new Error("ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN env var is required");
- }
- if (apiKeyEnv) {
- return {
- key: apiKeyEnv,
- source: "ANTHROPIC_API_KEY"
- };
- }
- return {
- key: null,
- source: "none"
- };
- }
- if (apiKeyEnv && getGlobalConfig().customApiKeyResponses?.approved?.includes(normalizeApiKeyForConfig(apiKeyEnv))) {
- return {
- key: apiKeyEnv,
- source: "ANTHROPIC_API_KEY"
- };
- }
- const apiKeyFromFd = getApiKeyFromFileDescriptor();
- if (apiKeyFromFd) {
- return {
- key: apiKeyFromFd,
- source: "ANTHROPIC_API_KEY"
- };
- }
- const apiKeyHelperCommand = getConfiguredApiKeyHelper();
- if (apiKeyHelperCommand) {
- if (opts.skipRetrievingKeyFromApiKeyHelper) {
- return {
- key: null,
- source: "apiKeyHelper"
- };
- }
- return {
- key: getApiKeyFromApiKeyHelperCached(),
- source: "apiKeyHelper"
- };
- }
- const apiKeyFromConfigOrMacOSKeychain = getApiKeyFromConfigOrMacOSKeychain();
- if (apiKeyFromConfigOrMacOSKeychain) {
- return apiKeyFromConfigOrMacOSKeychain;
- }
- return {
- key: null,
- source: "none"
- };
-}
-function getConfiguredApiKeyHelper() {
- if (isBareMode()) {
- return getSettingsForSource("flagSettings")?.apiKeyHelper;
- }
- const mergedSettings = getSettings_DEPRECATED() || {};
- return mergedSettings.apiKeyHelper;
-}
-function isApiKeyHelperFromProjectOrLocalSettings() {
- const apiKeyHelper = getConfiguredApiKeyHelper();
- if (!apiKeyHelper) {
- return false;
- }
- const projectSettings = getSettingsForSource("projectSettings");
- const localSettings = getSettingsForSource("localSettings");
- return projectSettings?.apiKeyHelper === apiKeyHelper || localSettings?.apiKeyHelper === apiKeyHelper;
-}
-function getConfiguredAwsAuthRefresh() {
- const mergedSettings = getSettings_DEPRECATED() || {};
- return mergedSettings.awsAuthRefresh;
-}
-function isAwsAuthRefreshFromProjectSettings() {
- const awsAuthRefresh = getConfiguredAwsAuthRefresh();
- if (!awsAuthRefresh) {
- return false;
- }
- const projectSettings = getSettingsForSource("projectSettings");
- const localSettings = getSettingsForSource("localSettings");
- return projectSettings?.awsAuthRefresh === awsAuthRefresh || localSettings?.awsAuthRefresh === awsAuthRefresh;
-}
-function getConfiguredAwsCredentialExport() {
- const mergedSettings = getSettings_DEPRECATED() || {};
- return mergedSettings.awsCredentialExport;
-}
-function isAwsCredentialExportFromProjectSettings() {
- const awsCredentialExport = getConfiguredAwsCredentialExport();
- if (!awsCredentialExport) {
- return false;
- }
- const projectSettings = getSettingsForSource("projectSettings");
- const localSettings = getSettingsForSource("localSettings");
- return projectSettings?.awsCredentialExport === awsCredentialExport || localSettings?.awsCredentialExport === awsCredentialExport;
-}
-function calculateApiKeyHelperTTL() {
- const envTtl = process.env.CLAUDE_CODE_API_KEY_HELPER_TTL_MS;
- if (envTtl) {
- const parsed = parseInt(envTtl, 10);
- if (!Number.isNaN(parsed) && parsed >= 0) {
- return parsed;
- }
- logForDebugging(`Found CLAUDE_CODE_API_KEY_HELPER_TTL_MS env var, but it was not a valid number. Got ${envTtl}`, { level: "error" });
- }
- return DEFAULT_API_KEY_HELPER_TTL;
-}
-function getApiKeyHelperElapsedMs() {
- const startedAt = _apiKeyHelperInflight?.startedAt;
- return startedAt ? Date.now() - startedAt : 0;
-}
-async function getApiKeyFromApiKeyHelper(isNonInteractiveSession) {
- if (!getConfiguredApiKeyHelper())
- return null;
- const ttl = calculateApiKeyHelperTTL();
- if (_apiKeyHelperCache) {
- if (Date.now() - _apiKeyHelperCache.timestamp < ttl) {
- return _apiKeyHelperCache.value;
- }
- if (!_apiKeyHelperInflight) {
- _apiKeyHelperInflight = {
- promise: _runAndCache(isNonInteractiveSession, false, _apiKeyHelperEpoch),
- startedAt: null
- };
- }
- return _apiKeyHelperCache.value;
- }
- if (_apiKeyHelperInflight)
- return _apiKeyHelperInflight.promise;
- _apiKeyHelperInflight = {
- promise: _runAndCache(isNonInteractiveSession, true, _apiKeyHelperEpoch),
- startedAt: Date.now()
- };
- return _apiKeyHelperInflight.promise;
-}
-async function _runAndCache(isNonInteractiveSession, isCold, epoch) {
- try {
- const value = await _executeApiKeyHelper(isNonInteractiveSession);
- if (epoch !== _apiKeyHelperEpoch)
- return value;
- if (value !== null) {
- _apiKeyHelperCache = { value, timestamp: Date.now() };
- }
- return value;
- } catch (e4) {
- if (epoch !== _apiKeyHelperEpoch)
- return " ";
- const detail = e4 instanceof Error ? e4.message : String(e4);
- console.error(source_default.red(`apiKeyHelper failed: ${detail}`));
- logForDebugging(`Error getting API key from apiKeyHelper: ${detail}`, {
- level: "error"
- });
- if (!isCold && _apiKeyHelperCache && _apiKeyHelperCache.value !== " ") {
- _apiKeyHelperCache = { ..._apiKeyHelperCache, timestamp: Date.now() };
- return _apiKeyHelperCache.value;
- }
- _apiKeyHelperCache = { value: " ", timestamp: Date.now() };
- return " ";
- } finally {
- if (epoch === _apiKeyHelperEpoch) {
- _apiKeyHelperInflight = null;
- }
- }
-}
-async function _executeApiKeyHelper(isNonInteractiveSession) {
- const apiKeyHelper = getConfiguredApiKeyHelper();
- if (!apiKeyHelper) {
- return null;
- }
- if (isApiKeyHelperFromProjectOrLocalSettings()) {
- const hasTrust = checkHasTrustDialogAccepted();
- if (!hasTrust && !isNonInteractiveSession) {
- const error46 = new Error(`Security: apiKeyHelper executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`);
- logAntError("apiKeyHelper invoked before trust check", error46);
- logEvent("tengu_apiKeyHelper_missing_trust11", {});
- return null;
- }
- }
- const result = await execa(apiKeyHelper, {
- shell: true,
- timeout: 10 * 60 * 1000,
- reject: false
- });
- if (result.failed) {
- const why = result.timedOut ? "timed out" : `exited ${result.exitCode}`;
- const stderr = result.stderr?.trim();
- throw new Error(stderr ? `${why}: ${stderr}` : why);
- }
- const stdout = result.stdout?.trim();
- if (!stdout) {
- throw new Error("did not return a value");
- }
- return stdout;
-}
-function getApiKeyFromApiKeyHelperCached() {
- return _apiKeyHelperCache?.value ?? null;
-}
-function clearApiKeyHelperCache() {
- _apiKeyHelperEpoch++;
- _apiKeyHelperCache = null;
- _apiKeyHelperInflight = null;
-}
-function prefetchApiKeyFromApiKeyHelperIfSafe(isNonInteractiveSession) {
- if (isApiKeyHelperFromProjectOrLocalSettings() && !checkHasTrustDialogAccepted()) {
- return;
- }
- getApiKeyFromApiKeyHelper(isNonInteractiveSession);
-}
-async function runAwsAuthRefresh() {
- const awsAuthRefresh = getConfiguredAwsAuthRefresh();
- if (!awsAuthRefresh) {
- return false;
- }
- if (isAwsAuthRefreshFromProjectSettings()) {
- const hasTrust = checkHasTrustDialogAccepted();
- if (!hasTrust && !getIsNonInteractiveSession()) {
- const error46 = new Error(`Security: awsAuthRefresh executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`);
- logAntError("awsAuthRefresh invoked before trust check", error46);
- logEvent("tengu_awsAuthRefresh_missing_trust", {});
- return false;
- }
- }
- try {
- logForDebugging("Fetching AWS caller identity for AWS auth refresh command");
- await checkStsCallerIdentity();
- logForDebugging("Fetched AWS caller identity, skipping AWS auth refresh command");
- return false;
- } catch {
- return refreshAwsAuth(awsAuthRefresh);
- }
-}
-function refreshAwsAuth(awsAuthRefresh) {
- logForDebugging("Running AWS auth refresh command");
- const authStatusManager = AwsAuthStatusManager.getInstance();
- authStatusManager.startAuthentication();
- return new Promise((resolve9) => {
- const refreshProc = exec2(awsAuthRefresh, {
- timeout: AWS_AUTH_REFRESH_TIMEOUT_MS
- });
- refreshProc.stdout.on("data", (data) => {
- const output = data.toString().trim();
- if (output) {
- authStatusManager.addOutput(output);
- logForDebugging(output, { level: "debug" });
- }
- });
- refreshProc.stderr.on("data", (data) => {
- const error46 = data.toString().trim();
- if (error46) {
- authStatusManager.setError(error46);
- logForDebugging(error46, { level: "error" });
- }
- });
- refreshProc.on("close", (code, signal) => {
- if (code === 0) {
- logForDebugging("AWS auth refresh completed successfully");
- authStatusManager.endAuthentication(true);
- resolve9(true);
- } else {
- const timedOut = signal === "SIGTERM";
- const message = timedOut ? source_default.red("AWS auth refresh timed out after 3 minutes. Run your auth command manually in a separate terminal.") : source_default.red("Error running awsAuthRefresh (in settings or ~/.claude.json):");
- console.error(message);
- authStatusManager.endAuthentication(false);
- resolve9(false);
- }
- });
- });
-}
-async function getAwsCredsFromCredentialExport() {
- const awsCredentialExport = getConfiguredAwsCredentialExport();
- if (!awsCredentialExport) {
- return null;
- }
- if (isAwsCredentialExportFromProjectSettings()) {
- const hasTrust = checkHasTrustDialogAccepted();
- if (!hasTrust && !getIsNonInteractiveSession()) {
- const error46 = new Error(`Security: awsCredentialExport executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`);
- logAntError("awsCredentialExport invoked before trust check", error46);
- logEvent("tengu_awsCredentialExport_missing_trust", {});
- return null;
- }
- }
- try {
- logForDebugging("Fetching AWS caller identity for credential export command");
- await checkStsCallerIdentity();
- logForDebugging("Fetched AWS caller identity, skipping AWS credential export command");
- return null;
- } catch {
- try {
- logForDebugging("Running AWS credential export command");
- const result = await execa(awsCredentialExport, {
- shell: true,
- reject: false
- });
- if (result.exitCode !== 0 || !result.stdout) {
- throw new Error("awsCredentialExport did not return a valid value");
- }
- const awsOutput = jsonParse(result.stdout.trim());
- if (!isValidAwsStsOutput(awsOutput)) {
- throw new Error("awsCredentialExport did not return valid AWS STS output structure");
- }
- logForDebugging("AWS credentials retrieved from awsCredentialExport");
- return {
- accessKeyId: awsOutput.Credentials.AccessKeyId,
- secretAccessKey: awsOutput.Credentials.SecretAccessKey,
- sessionToken: awsOutput.Credentials.SessionToken
- };
- } catch (e4) {
- const message = source_default.red("Error getting AWS credentials from awsCredentialExport (in settings or ~/.claude.json):");
- if (e4 instanceof Error) {
- console.error(message, e4.message);
- } else {
- console.error(message, e4);
- }
- return null;
- }
- }
-}
-function clearAwsCredentialsCache() {
- refreshAndGetAwsCredentials.cache.clear();
-}
-function getConfiguredGcpAuthRefresh() {
- const mergedSettings = getSettings_DEPRECATED() || {};
- return mergedSettings.gcpAuthRefresh;
-}
-function isGcpAuthRefreshFromProjectSettings() {
- const gcpAuthRefresh = getConfiguredGcpAuthRefresh();
- if (!gcpAuthRefresh) {
- return false;
- }
- const projectSettings = getSettingsForSource("projectSettings");
- const localSettings = getSettingsForSource("localSettings");
- return projectSettings?.gcpAuthRefresh === gcpAuthRefresh || localSettings?.gcpAuthRefresh === gcpAuthRefresh;
-}
-async function checkGcpCredentialsValid() {
- try {
- const { GoogleAuth: GoogleAuth2 } = await Promise.resolve().then(() => __toESM(require_src6(), 1));
- const auth13 = new GoogleAuth2({
- scopes: ["https://www.googleapis.com/auth/cloud-platform"]
- });
- const probe = (async () => {
- const client15 = await auth13.getClient();
- await client15.getAccessToken();
- })();
- const timeout = sleep6(GCP_CREDENTIALS_CHECK_TIMEOUT_MS).then(() => {
- throw new GcpCredentialsTimeoutError("GCP credentials check timed out");
- });
- await Promise.race([probe, timeout]);
- return true;
- } catch {
- return false;
- }
-}
-async function runGcpAuthRefresh() {
- const gcpAuthRefresh = getConfiguredGcpAuthRefresh();
- if (!gcpAuthRefresh) {
- return false;
- }
- if (isGcpAuthRefreshFromProjectSettings()) {
- const hasTrust = checkHasTrustDialogAccepted();
- if (!hasTrust && !getIsNonInteractiveSession()) {
- const error46 = new Error(`Security: gcpAuthRefresh executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`);
- logAntError("gcpAuthRefresh invoked before trust check", error46);
- logEvent("tengu_gcpAuthRefresh_missing_trust", {});
- return false;
- }
- }
- try {
- logForDebugging("Checking GCP credentials validity for auth refresh");
- const isValid = await checkGcpCredentialsValid();
- if (isValid) {
- logForDebugging("GCP credentials are valid, skipping auth refresh command");
- return false;
- }
- } catch {}
- return refreshGcpAuth(gcpAuthRefresh);
-}
-function refreshGcpAuth(gcpAuthRefresh) {
- logForDebugging("Running GCP auth refresh command");
- const authStatusManager = AwsAuthStatusManager.getInstance();
- authStatusManager.startAuthentication();
- return new Promise((resolve9) => {
- const refreshProc = exec2(gcpAuthRefresh, {
- timeout: GCP_AUTH_REFRESH_TIMEOUT_MS
- });
- refreshProc.stdout.on("data", (data) => {
- const output = data.toString().trim();
- if (output) {
- authStatusManager.addOutput(output);
- logForDebugging(output, { level: "debug" });
- }
- });
- refreshProc.stderr.on("data", (data) => {
- const error46 = data.toString().trim();
- if (error46) {
- authStatusManager.setError(error46);
- logForDebugging(error46, { level: "error" });
- }
- });
- refreshProc.on("close", (code, signal) => {
- if (code === 0) {
- logForDebugging("GCP auth refresh completed successfully");
- authStatusManager.endAuthentication(true);
- resolve9(true);
- } else {
- const timedOut = signal === "SIGTERM";
- const message = timedOut ? source_default.red("GCP auth refresh timed out after 3 minutes. Run your auth command manually in a separate terminal.") : source_default.red("Error running gcpAuthRefresh (in settings or ~/.claude.json):");
- console.error(message);
- authStatusManager.endAuthentication(false);
- resolve9(false);
- }
- });
- });
-}
-function clearGcpCredentialsCache() {
- refreshGcpCredentialsIfNeeded.cache.clear();
-}
-function prefetchGcpCredentialsIfSafe() {
- const gcpAuthRefresh = getConfiguredGcpAuthRefresh();
- if (!gcpAuthRefresh) {
- return;
- }
- if (isGcpAuthRefreshFromProjectSettings()) {
- const hasTrust = checkHasTrustDialogAccepted();
- if (!hasTrust && !getIsNonInteractiveSession()) {
- return;
- }
- }
- refreshGcpCredentialsIfNeeded();
-}
-function prefetchAwsCredentialsAndBedRockInfoIfSafe() {
- const awsAuthRefresh = getConfiguredAwsAuthRefresh();
- const awsCredentialExport = getConfiguredAwsCredentialExport();
- if (!awsAuthRefresh && !awsCredentialExport) {
- return;
- }
- if (isAwsAuthRefreshFromProjectSettings() || isAwsCredentialExportFromProjectSettings()) {
- const hasTrust = checkHasTrustDialogAccepted();
- if (!hasTrust && !getIsNonInteractiveSession()) {
- return;
- }
- }
- refreshAndGetAwsCredentials();
- getModelStrings2();
-}
-function isValidApiKey(apiKey) {
- return /^[a-zA-Z0-9-_]+$/.test(apiKey);
-}
-async function saveApiKey(apiKey) {
- if (!isValidApiKey(apiKey)) {
- throw new Error("Invalid API key format. API key must contain only alphanumeric characters, dashes, and underscores.");
- }
- await maybeRemoveApiKeyFromMacOSKeychain();
- let savedToKeychain = false;
- if (process.platform === "darwin") {
- try {
- const storageServiceName = getMacOsKeychainStorageServiceName();
- const username = getUsername();
- const hexValue = Buffer.from(apiKey, "utf-8").toString("hex");
- const command12 = `add-generic-password -U -a "${username}" -s "${storageServiceName}" -X "${hexValue}"
-`;
- await execa("security", ["-i"], {
- input: command12,
- reject: false
- });
- logEvent("tengu_api_key_saved_to_keychain", {});
- savedToKeychain = true;
- } catch (e4) {
- logError2(e4);
- logEvent("tengu_api_key_keychain_error", {
- error: errorMessage(e4)
- });
- logEvent("tengu_api_key_saved_to_config", {});
- }
- } else {
- logEvent("tengu_api_key_saved_to_config", {});
- }
- const normalizedKey = normalizeApiKeyForConfig(apiKey);
- saveGlobalConfig((current) => {
- const approved = current.customApiKeyResponses?.approved ?? [];
- return {
- ...current,
- primaryApiKey: savedToKeychain ? current.primaryApiKey : apiKey,
- customApiKeyResponses: {
- ...current.customApiKeyResponses,
- approved: approved.includes(normalizedKey) ? approved : [...approved, normalizedKey],
- rejected: current.customApiKeyResponses?.rejected ?? []
- }
- };
- });
- getApiKeyFromConfigOrMacOSKeychain.cache.clear?.();
- clearLegacyApiKeyPrefetch();
-}
-function isCustomApiKeyApproved(apiKey) {
- const config8 = getGlobalConfig();
- const normalizedKey = normalizeApiKeyForConfig(apiKey);
- return config8.customApiKeyResponses?.approved?.includes(normalizedKey) ?? false;
-}
-async function removeApiKey() {
- await maybeRemoveApiKeyFromMacOSKeychain();
- saveGlobalConfig((current) => ({
- ...current,
- primaryApiKey: undefined
- }));
- getApiKeyFromConfigOrMacOSKeychain.cache.clear?.();
- clearLegacyApiKeyPrefetch();
-}
-async function maybeRemoveApiKeyFromMacOSKeychain() {
- try {
- await maybeRemoveApiKeyFromMacOSKeychainThrows();
- } catch (e4) {
- logError2(e4);
- }
-}
-function saveOAuthTokensIfNeeded(tokens) {
- if (!shouldUseClaudeAIAuth(tokens.scopes)) {
- logEvent("tengu_oauth_tokens_not_claude_ai", {});
- return { success: true };
- }
- if (!tokens.refreshToken || !tokens.expiresAt) {
- logEvent("tengu_oauth_tokens_inference_only", {});
- return { success: true };
- }
- const secureStorage = getSecureStorage();
- const storageBackend = secureStorage.name;
- try {
- const storageData = secureStorage.read() || {};
- const existingOauth = storageData.claudeAiOauth;
- storageData.claudeAiOauth = {
- accessToken: tokens.accessToken,
- refreshToken: tokens.refreshToken,
- expiresAt: tokens.expiresAt,
- scopes: tokens.scopes,
- subscriptionType: tokens.subscriptionType ?? existingOauth?.subscriptionType ?? null,
- rateLimitTier: tokens.rateLimitTier ?? existingOauth?.rateLimitTier ?? null
- };
- const updateStatus = secureStorage.update(storageData);
- if (updateStatus.success) {
- logEvent("tengu_oauth_tokens_saved", { storageBackend });
- } else {
- logEvent("tengu_oauth_tokens_save_failed", { storageBackend });
- }
- getClaudeAIOAuthTokens.cache?.clear?.();
- clearBetasCaches();
- clearToolSchemaCache();
- return updateStatus;
- } catch (error46) {
- logError2(error46);
- logEvent("tengu_oauth_tokens_save_exception", {
- storageBackend,
- error: errorMessage(error46)
- });
- return { success: false, warning: "Failed to save OAuth tokens" };
- }
-}
-function clearOAuthTokenCache() {
- getClaudeAIOAuthTokens.cache?.clear?.();
- clearKeychainCache();
-}
-async function invalidateOAuthCacheIfDiskChanged() {
- try {
- const { mtimeMs } = await stat6(join24(getClaudeConfigHomeDir(), ".credentials.json"));
- if (mtimeMs !== lastCredentialsMtimeMs) {
- lastCredentialsMtimeMs = mtimeMs;
- clearOAuthTokenCache();
- }
- } catch {
- getClaudeAIOAuthTokens.cache?.clear?.();
- }
-}
-function handleOAuth401Error(failedAccessToken) {
- const pending = pending401Handlers.get(failedAccessToken);
- if (pending)
- return pending;
- const promise2 = handleOAuth401ErrorImpl(failedAccessToken).finally(() => {
- pending401Handlers.delete(failedAccessToken);
- });
- pending401Handlers.set(failedAccessToken, promise2);
- return promise2;
-}
-async function handleOAuth401ErrorImpl(failedAccessToken) {
- clearOAuthTokenCache();
- const currentTokens = await getClaudeAIOAuthTokensAsync();
- if (!currentTokens?.refreshToken) {
- return false;
- }
- if (currentTokens.accessToken !== failedAccessToken) {
- logEvent("tengu_oauth_401_recovered_from_keychain", {});
- return true;
- }
- return checkAndRefreshOAuthTokenIfNeeded(0, true);
-}
-async function getClaudeAIOAuthTokensAsync() {
- if (isBareMode())
- return null;
- if (process.env.CLAUDE_CODE_OAUTH_TOKEN || getOAuthTokenFromFileDescriptor()) {
- return getClaudeAIOAuthTokens();
- }
- try {
- const secureStorage = getSecureStorage();
- const storageData = await secureStorage.readAsync();
- const oauthData = storageData?.claudeAiOauth;
- if (!oauthData?.accessToken) {
- return null;
- }
- return oauthData;
- } catch (error46) {
- logError2(error46);
- return null;
- }
-}
-function checkAndRefreshOAuthTokenIfNeeded(retryCount = 0, force = false) {
- if (retryCount === 0 && !force) {
- if (pendingRefreshCheck) {
- return pendingRefreshCheck;
- }
- const promise2 = checkAndRefreshOAuthTokenIfNeededImpl(retryCount, force);
- pendingRefreshCheck = promise2.finally(() => {
- pendingRefreshCheck = null;
- });
- return pendingRefreshCheck;
- }
- return checkAndRefreshOAuthTokenIfNeededImpl(retryCount, force);
-}
-async function checkAndRefreshOAuthTokenIfNeededImpl(retryCount, force) {
- const MAX_RETRIES = 5;
- await invalidateOAuthCacheIfDiskChanged();
- const tokens = getClaudeAIOAuthTokens();
- if (!force) {
- if (!tokens?.refreshToken || !isOAuthTokenExpired(tokens.expiresAt)) {
- return false;
- }
- }
- if (!tokens?.refreshToken) {
- return false;
- }
- if (!shouldUseClaudeAIAuth(tokens.scopes)) {
- return false;
- }
- getClaudeAIOAuthTokens.cache?.clear?.();
- clearKeychainCache();
- const freshTokens = await getClaudeAIOAuthTokensAsync();
- if (!freshTokens?.refreshToken || !isOAuthTokenExpired(freshTokens.expiresAt)) {
- return false;
- }
- const claudeDir = getClaudeConfigHomeDir();
- await mkdir4(claudeDir, { recursive: true });
- let release;
- try {
- logEvent("tengu_oauth_token_refresh_lock_acquiring", {});
- release = await lock(claudeDir);
- logEvent("tengu_oauth_token_refresh_lock_acquired", {});
- } catch (err) {
- if (err.code === "ELOCKED") {
- if (retryCount < MAX_RETRIES) {
- logEvent("tengu_oauth_token_refresh_lock_retry", {
- retryCount: retryCount + 1
- });
- await sleep6(1000 + Math.random() * 1000);
- return checkAndRefreshOAuthTokenIfNeededImpl(retryCount + 1, force);
- }
- logEvent("tengu_oauth_token_refresh_lock_retry_limit_reached", {
- maxRetries: MAX_RETRIES
- });
- return false;
- }
- logError2(err);
- logEvent("tengu_oauth_token_refresh_lock_error", {
- error: errorMessage(err)
- });
- return false;
- }
- try {
- getClaudeAIOAuthTokens.cache?.clear?.();
- clearKeychainCache();
- const lockedTokens = await getClaudeAIOAuthTokensAsync();
- if (!lockedTokens?.refreshToken || !isOAuthTokenExpired(lockedTokens.expiresAt)) {
- logEvent("tengu_oauth_token_refresh_race_resolved", {});
- return false;
- }
- logEvent("tengu_oauth_token_refresh_starting", {});
- const refreshedTokens = await refreshOAuthToken(lockedTokens.refreshToken, {
- scopes: shouldUseClaudeAIAuth(lockedTokens.scopes) ? undefined : lockedTokens.scopes
- });
- saveOAuthTokensIfNeeded(refreshedTokens);
- getClaudeAIOAuthTokens.cache?.clear?.();
- clearKeychainCache();
- return true;
- } catch (error46) {
- logError2(error46);
- getClaudeAIOAuthTokens.cache?.clear?.();
- clearKeychainCache();
- const currentTokens = await getClaudeAIOAuthTokensAsync();
- if (currentTokens && !isOAuthTokenExpired(currentTokens.expiresAt)) {
- logEvent("tengu_oauth_token_refresh_race_recovered", {});
- return true;
- }
- return false;
- } finally {
- logEvent("tengu_oauth_token_refresh_lock_releasing", {});
- await release();
- logEvent("tengu_oauth_token_refresh_lock_released", {});
- }
-}
-function isClaudeAISubscriber() {
- if (!isAnthropicAuthEnabled()) {
- return false;
- }
- return shouldUseClaudeAIAuth(getClaudeAIOAuthTokens()?.scopes);
-}
-function hasProfileScope() {
- return getClaudeAIOAuthTokens()?.scopes?.includes(CLAUDE_AI_PROFILE_SCOPE) ?? false;
-}
-function is1PApiCustomer() {
- if (isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) || isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) || isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY)) {
- return false;
- }
- if (isClaudeAISubscriber()) {
- return false;
- }
- return true;
-}
-function getOauthAccountInfo() {
- return isAnthropicAuthEnabled() ? getGlobalConfig().oauthAccount : undefined;
-}
-function isOverageProvisioningAllowed() {
- const accountInfo = getOauthAccountInfo();
- const billingType = accountInfo?.billingType;
- if (!isClaudeAISubscriber() || !billingType) {
- return false;
- }
- if (billingType !== "stripe_subscription" && billingType !== "stripe_subscription_contracted" && billingType !== "apple_subscription" && billingType !== "google_play_subscription") {
- return false;
- }
- return true;
-}
-function hasOpusAccess() {
- const subscriptionType = getSubscriptionType();
- return subscriptionType === "max" || subscriptionType === "enterprise" || subscriptionType === "team" || subscriptionType === "pro" || subscriptionType === null;
-}
-function getSubscriptionType() {
- if (shouldUseMockSubscription()) {
- return getMockSubscriptionType();
- }
- if (!isAnthropicAuthEnabled()) {
- return null;
- }
- const oauthTokens = getClaudeAIOAuthTokens();
- if (!oauthTokens) {
- return null;
- }
- return oauthTokens.subscriptionType ?? null;
-}
-function isMaxSubscriber() {
- return getSubscriptionType() === "max";
-}
-function isTeamSubscriber() {
- return getSubscriptionType() === "team";
-}
-function isTeamPremiumSubscriber() {
- return getSubscriptionType() === "team" && getRateLimitTier() === "default_claude_max_5x";
-}
-function isEnterpriseSubscriber() {
- return getSubscriptionType() === "enterprise";
-}
-function isProSubscriber() {
- return getSubscriptionType() === "pro";
-}
-function getRateLimitTier() {
- if (!isAnthropicAuthEnabled()) {
- return null;
- }
- const oauthTokens = getClaudeAIOAuthTokens();
- if (!oauthTokens) {
- return null;
- }
- return oauthTokens.rateLimitTier ?? null;
-}
-function getSubscriptionName() {
- const subscriptionType = getSubscriptionType();
- switch (subscriptionType) {
- case "enterprise":
- return "Claude Enterprise";
- case "team":
- return "Claude Team";
- case "max":
- return "Claude Max";
- case "pro":
- return "Claude Pro";
- default:
- return "Claude API";
- }
-}
-function isUsing3PServices() {
- return !!(isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) || isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) || isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY));
-}
-function getConfiguredOtelHeadersHelper() {
- const mergedSettings = getSettings_DEPRECATED() || {};
- return mergedSettings.otelHeadersHelper;
-}
-function isOtelHeadersHelperFromProjectOrLocalSettings() {
- const otelHeadersHelper = getConfiguredOtelHeadersHelper();
- if (!otelHeadersHelper) {
- return false;
- }
- const projectSettings = getSettingsForSource("projectSettings");
- const localSettings = getSettingsForSource("localSettings");
- return projectSettings?.otelHeadersHelper === otelHeadersHelper || localSettings?.otelHeadersHelper === otelHeadersHelper;
-}
-function getOtelHeadersFromHelper() {
- const otelHeadersHelper = getConfiguredOtelHeadersHelper();
- if (!otelHeadersHelper) {
- return {};
- }
- const debounceMs = parseInt(process.env.CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS || DEFAULT_OTEL_HEADERS_DEBOUNCE_MS.toString());
- if (cachedOtelHeaders && Date.now() - cachedOtelHeadersTimestamp < debounceMs) {
- return cachedOtelHeaders;
- }
- if (isOtelHeadersHelperFromProjectOrLocalSettings()) {
- const hasTrust = checkHasTrustDialogAccepted();
- if (!hasTrust) {
- return {};
- }
- }
- try {
- const result = execSyncWithDefaults_DEPRECATED(otelHeadersHelper, {
- timeout: 30000
- })?.toString().trim();
- if (!result) {
- throw new Error("otelHeadersHelper did not return a valid value");
- }
- const headers = jsonParse(result);
- if (typeof headers !== "object" || headers === null || Array.isArray(headers)) {
- throw new Error("otelHeadersHelper must return a JSON object with string key-value pairs");
- }
- for (const [key, value] of Object.entries(headers)) {
- if (typeof value !== "string") {
- throw new Error(`otelHeadersHelper returned non-string value for key "${key}": ${typeof value}`);
- }
- }
- cachedOtelHeaders = headers;
- cachedOtelHeadersTimestamp = Date.now();
- return cachedOtelHeaders;
- } catch (error46) {
- logError2(new Error(`Error getting OpenTelemetry headers from otelHeadersHelper (in settings): ${errorMessage(error46)}`));
- throw error46;
- }
-}
-function isConsumerPlan(plan) {
- return plan === "max" || plan === "pro";
-}
-function isConsumerSubscriber() {
- const subscriptionType = getSubscriptionType();
- return isClaudeAISubscriber() && subscriptionType !== null && isConsumerPlan(subscriptionType);
-}
-function getAccountInformation() {
- const apiProvider = getAPIProvider();
- if (apiProvider !== "firstParty") {
- return;
- }
- const { source: authTokenSource } = getAuthTokenSource();
- const accountInfo = {};
- if (authTokenSource === "CLAUDE_CODE_OAUTH_TOKEN" || authTokenSource === "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR") {
- accountInfo.tokenSource = authTokenSource;
- } else if (isClaudeAISubscriber()) {
- accountInfo.subscription = getSubscriptionName();
- } else {
- accountInfo.tokenSource = authTokenSource;
- }
- const { key: apiKey, source: apiKeySource } = getAnthropicApiKeyWithSource();
- if (apiKey) {
- accountInfo.apiKeySource = apiKeySource;
- }
- if (authTokenSource === "claude.ai" || apiKeySource === "/login managed key") {
- const orgName = getOauthAccountInfo()?.organizationName;
- if (orgName) {
- accountInfo.organization = orgName;
- }
- }
- const email3 = getOauthAccountInfo()?.emailAddress;
- if ((authTokenSource === "claude.ai" || apiKeySource === "/login managed key") && email3) {
- accountInfo.email = email3;
- }
- return accountInfo;
-}
-async function validateForceLoginOrg() {
- if (process.env.ANTHROPIC_UNIX_SOCKET) {
- return { valid: true };
- }
- if (!isAnthropicAuthEnabled()) {
- return { valid: true };
- }
- const requiredOrgUuid = getSettingsForSource("policySettings")?.forceLoginOrgUUID;
- if (!requiredOrgUuid) {
- return { valid: true };
- }
- await checkAndRefreshOAuthTokenIfNeeded();
- const tokens = getClaudeAIOAuthTokens();
- if (!tokens) {
- return { valid: true };
- }
- const { source } = getAuthTokenSource();
- const isEnvVarToken = source === "CLAUDE_CODE_OAUTH_TOKEN" || source === "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
- const profile7 = await getOauthProfileFromOauthToken(tokens.accessToken);
- if (!profile7) {
- return {
- valid: false,
- message: `Unable to verify organization for the current authentication token.
-This machine requires organization ${requiredOrgUuid} but the profile could not be fetched.
-This may be a network error, or the token may lack the user:profile scope required for
-verification (tokens from 'claude setup-token' do not include this scope).
-Try again, or obtain a full-scope token via 'claude auth login'.`
- };
- }
- const tokenOrgUuid = profile7.organization.uuid;
- if (tokenOrgUuid === requiredOrgUuid) {
- return { valid: true };
- }
- if (isEnvVarToken) {
- const envVarName = source === "CLAUDE_CODE_OAUTH_TOKEN" ? "CLAUDE_CODE_OAUTH_TOKEN" : "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
- return {
- valid: false,
- message: `The ${envVarName} environment variable provides a token for a
-different organization than required by this machine's managed settings.
-
-Required organization: ${requiredOrgUuid}
-Token organization: ${tokenOrgUuid}
-
-Remove the environment variable or obtain a token for the correct organization.`
- };
- }
- return {
- valid: false,
- message: `Your authentication token belongs to organization ${tokenOrgUuid},
-but this machine requires organization ${requiredOrgUuid}.
-
-Please log in with the correct organization: claude auth login`
- };
-}
-var DEFAULT_API_KEY_HELPER_TTL, _apiKeyHelperCache = null, _apiKeyHelperInflight = null, _apiKeyHelperEpoch = 0, DEFAULT_AWS_STS_TTL, AWS_AUTH_REFRESH_TIMEOUT_MS, refreshAndGetAwsCredentials, GCP_CREDENTIALS_CHECK_TIMEOUT_MS = 5000, DEFAULT_GCP_CREDENTIAL_TTL = 3600000, GCP_AUTH_REFRESH_TIMEOUT_MS = 180000, refreshGcpCredentialsIfNeeded, getApiKeyFromConfigOrMacOSKeychain, getClaudeAIOAuthTokens, lastCredentialsMtimeMs = 0, pending401Handlers, pendingRefreshCheck = null, cachedOtelHeaders = null, cachedOtelHeadersTimestamp = 0, DEFAULT_OTEL_HEADERS_DEBOUNCE_MS = 1740000, GcpCredentialsTimeoutError;
-var init_auth14 = __esm(() => {
- init_source();
- init_execa();
- init_memoize();
- init_oauth();
- init_analytics();
- init_modelStrings();
- init_providers();
- init_state();
- init_mockRateLimits();
- init_client7();
- init_getOauthProfile();
- init_authFileDescriptor();
- init_authPortable();
- init_aws();
- init_awsAuthStatusManager();
- init_betas2();
- init_config();
- init_debug();
- init_envUtils();
- init_errors();
- init_execFileNoThrow();
- init_log2();
- init_memoize2();
- init_secureStorage();
- init_keychainPrefetch();
- init_macOsKeychainHelpers();
- init_settings2();
- init_slowOperations();
- init_toolSchemaCache();
- DEFAULT_API_KEY_HELPER_TTL = 5 * 60 * 1000;
- DEFAULT_AWS_STS_TTL = 60 * 60 * 1000;
- AWS_AUTH_REFRESH_TIMEOUT_MS = 3 * 60 * 1000;
- refreshAndGetAwsCredentials = memoizeWithTTLAsync(async () => {
- const refreshed = await runAwsAuthRefresh();
- const credentials = await getAwsCredsFromCredentialExport();
- if (refreshed || credentials) {
- await clearAwsIniCache();
- }
- return credentials;
- }, DEFAULT_AWS_STS_TTL);
- refreshGcpCredentialsIfNeeded = memoizeWithTTLAsync(async () => {
- const refreshed = await runGcpAuthRefresh();
- return refreshed;
- }, DEFAULT_GCP_CREDENTIAL_TTL);
- getApiKeyFromConfigOrMacOSKeychain = memoize_default(() => {
- if (isBareMode())
- return null;
- if (process.platform === "darwin") {
- const prefetch = getLegacyApiKeyPrefetchResult();
- if (prefetch) {
- if (prefetch.stdout) {
- return { key: prefetch.stdout, source: "/login managed key" };
- }
- } else {
- const storageServiceName = getMacOsKeychainStorageServiceName();
- try {
- const result = execSyncWithDefaults_DEPRECATED(`security find-generic-password -a $USER -w -s "${storageServiceName}"`);
- if (result) {
- return { key: result, source: "/login managed key" };
- }
- } catch (e4) {
- logError2(e4);
- }
- }
- }
- const config8 = getGlobalConfig();
- if (!config8.primaryApiKey) {
- return null;
- }
- return { key: config8.primaryApiKey, source: "/login managed key" };
- });
- getClaudeAIOAuthTokens = memoize_default(() => {
- if (isBareMode())
- return null;
- if (process.env.CLAUDE_CODE_OAUTH_TOKEN) {
- return {
- accessToken: process.env.CLAUDE_CODE_OAUTH_TOKEN,
- refreshToken: null,
- expiresAt: null,
- scopes: ["user:inference"],
- subscriptionType: null,
- rateLimitTier: null
- };
- }
- const oauthTokenFromFd = getOAuthTokenFromFileDescriptor();
- if (oauthTokenFromFd) {
- return {
- accessToken: oauthTokenFromFd,
- refreshToken: null,
- expiresAt: null,
- scopes: ["user:inference"],
- subscriptionType: null,
- rateLimitTier: null
- };
- }
- try {
- const secureStorage = getSecureStorage();
- const storageData = secureStorage.read();
- const oauthData = storageData?.claudeAiOauth;
- if (!oauthData?.accessToken) {
- return null;
- }
- return oauthData;
- } catch (error46) {
- logError2(error46);
- return null;
- }
- });
- pending401Handlers = new Map;
- GcpCredentialsTimeoutError = class GcpCredentialsTimeoutError extends Error {
- };
-});
-
-// src/utils/userAgent.ts
-function getClaudeCodeUserAgent() {
- return `claude-code/${MACRO.VERSION}`;
-}
-
-// src/utils/workloadContext.ts
-import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
-function getWorkload() {
- return workloadStorage.getStore()?.workload;
-}
-function runWithWorkload(workload, fn) {
- return workloadStorage.run({ workload }, fn);
-}
-var workloadStorage;
-var init_workloadContext = __esm(() => {
- workloadStorage = new AsyncLocalStorage2;
-});
-
-// src/utils/http.ts
-function getUserAgent() {
- const agentSdkVersion = process.env.CLAUDE_AGENT_SDK_VERSION ? `, agent-sdk/${process.env.CLAUDE_AGENT_SDK_VERSION}` : "";
- const clientApp = process.env.CLAUDE_AGENT_SDK_CLIENT_APP ? `, client-app/${process.env.CLAUDE_AGENT_SDK_CLIENT_APP}` : "";
- const workload = getWorkload();
- const workloadSuffix = workload ? `, workload/${workload}` : "";
- return `claude-cli/${MACRO.VERSION} (${process.env.USER_TYPE}, ${process.env.CLAUDE_CODE_ENTRYPOINT ?? "cli"}${agentSdkVersion}${clientApp}${workloadSuffix})`;
-}
-function getMCPUserAgent() {
- const parts = [];
- if (process.env.CLAUDE_CODE_ENTRYPOINT) {
- parts.push(process.env.CLAUDE_CODE_ENTRYPOINT);
- }
- if (process.env.CLAUDE_AGENT_SDK_VERSION) {
- parts.push(`agent-sdk/${process.env.CLAUDE_AGENT_SDK_VERSION}`);
- }
- if (process.env.CLAUDE_AGENT_SDK_CLIENT_APP) {
- parts.push(`client-app/${process.env.CLAUDE_AGENT_SDK_CLIENT_APP}`);
- }
- const suffix = parts.length > 0 ? ` (${parts.join(", ")})` : "";
- return `claude-code/${MACRO.VERSION}${suffix}`;
-}
-function getWebFetchUserAgent() {
- return `Claude-User (${getClaudeCodeUserAgent()}; +https://support.anthropic.com/)`;
-}
-function getAuthHeaders2() {
- if (isClaudeAISubscriber()) {
- const oauthTokens = getClaudeAIOAuthTokens();
- if (!oauthTokens?.accessToken) {
- return {
- headers: {},
- error: "No OAuth token available"
- };
- }
- return {
- headers: {
- Authorization: `Bearer ${oauthTokens.accessToken}`,
- "anthropic-beta": OAUTH_BETA_HEADER
- }
- };
- }
- const apiKey = getAnthropicApiKey();
- if (!apiKey) {
- return {
- headers: {},
- error: "No API key available"
- };
- }
- return {
- headers: {
- "x-api-key": apiKey
- }
- };
-}
-async function withOAuth401Retry(request2, opts) {
- try {
- return await request2();
- } catch (err) {
- if (!axios_default.isAxiosError(err))
- throw err;
- const status = err.response?.status;
- const isAuthError = status === 401 || opts?.also403Revoked && status === 403 && typeof err.response?.data === "string" && err.response.data.includes("OAuth token has been revoked");
- if (!isAuthError)
- throw err;
- const failedAccessToken = getClaudeAIOAuthTokens()?.accessToken;
- if (!failedAccessToken)
- throw err;
- await handleOAuth401Error(failedAccessToken);
- return await request2();
- }
-}
-var init_http8 = __esm(() => {
- init_axios2();
- init_oauth();
- init_auth14();
- init_workloadContext();
-});
-
-// src/utils/user.ts
-async function initUser() {
- if (cachedEmail === null && !emailFetchPromise) {
- emailFetchPromise = getEmailAsync();
- cachedEmail = await emailFetchPromise;
- emailFetchPromise = null;
- getCoreUserData.cache.clear?.();
- }
-}
-function resetUserCache() {
- cachedEmail = null;
- emailFetchPromise = null;
- getCoreUserData.cache.clear?.();
- getGitEmail.cache.clear?.();
-}
-function getUserForGrowthBook() {
- return getCoreUserData(true);
-}
-function getEmail() {
- if (cachedEmail !== null) {
- return cachedEmail;
- }
- const oauthAccount = getOauthAccountInfo();
- if (oauthAccount?.emailAddress) {
- return oauthAccount.emailAddress;
- }
- if (process.env.USER_TYPE !== "ant") {
- return;
- }
- if (process.env.COO_CREATOR) {
- return `${process.env.COO_CREATOR}@anthropic.com`;
- }
- return;
-}
-async function getEmailAsync() {
- const oauthAccount = getOauthAccountInfo();
- if (oauthAccount?.emailAddress) {
- return oauthAccount.emailAddress;
- }
- if (process.env.USER_TYPE !== "ant") {
- return;
- }
- if (process.env.COO_CREATOR) {
- return `${process.env.COO_CREATOR}@anthropic.com`;
- }
- return getGitEmail();
-}
-var cachedEmail = null, emailFetchPromise = null, getCoreUserData, getGitEmail;
-var init_user = __esm(() => {
- init_execa();
- init_memoize();
- init_state();
- init_auth14();
- init_config();
- init_cwd();
- init_env();
- init_envUtils();
- getCoreUserData = memoize_default((includeAnalyticsMetadata) => {
- const deviceId = getOrCreateUserID();
- const config8 = getGlobalConfig();
- let subscriptionType;
- let rateLimitTier;
- let firstTokenTime;
- if (includeAnalyticsMetadata) {
- subscriptionType = getSubscriptionType() ?? undefined;
- rateLimitTier = getRateLimitTier() ?? undefined;
- if (subscriptionType && config8.claudeCodeFirstTokenDate) {
- const configFirstTokenTime = new Date(config8.claudeCodeFirstTokenDate).getTime();
- if (!isNaN(configFirstTokenTime)) {
- firstTokenTime = configFirstTokenTime;
- }
- }
- }
- const oauthAccount = getOauthAccountInfo();
- const organizationUuid = oauthAccount?.organizationUuid;
- const accountUuid = oauthAccount?.accountUuid;
- return {
- deviceId,
- sessionId: getSessionId(),
- email: getEmail(),
- appVersion: MACRO.VERSION,
- platform: getHostPlatformForAnalytics(),
- organizationUuid,
- accountUuid,
- userType: process.env.USER_TYPE,
- subscriptionType,
- rateLimitTier,
- firstTokenTime,
- ...isEnvTruthy(process.env.GITHUB_ACTIONS) && {
- githubActionsMetadata: {
- actor: process.env.GITHUB_ACTOR,
- actorId: process.env.GITHUB_ACTOR_ID,
- repository: process.env.GITHUB_REPOSITORY,
- repositoryId: process.env.GITHUB_REPOSITORY_ID,
- repositoryOwner: process.env.GITHUB_REPOSITORY_OWNER,
- repositoryOwnerId: process.env.GITHUB_REPOSITORY_OWNER_ID
- }
- }
- };
- });
- getGitEmail = memoize_default(async () => {
- const result = await execa("git config --get user.email", {
- shell: true,
- reject: false,
- cwd: getCwd()
- });
- return result.exitCode === 0 && result.stdout ? result.stdout.trim() : undefined;
- });
-});
-
-// node_modules/@opentelemetry/api/build/src/version.js
-var require_version3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.VERSION = undefined;
- exports.VERSION = "1.9.1";
-});
-
-// node_modules/@opentelemetry/api/build/src/internal/semver.js
-var require_semver3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isCompatible = exports._makeCompatibilityCheck = undefined;
- var version_1 = require_version3();
- var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
- function _makeCompatibilityCheck(ownVersion) {
- const acceptedVersions = new Set([ownVersion]);
- const rejectedVersions = new Set;
- const myVersionMatch = ownVersion.match(re);
- if (!myVersionMatch) {
- return () => false;
- }
- const ownVersionParsed = {
- major: +myVersionMatch[1],
- minor: +myVersionMatch[2],
- patch: +myVersionMatch[3],
- prerelease: myVersionMatch[4]
- };
- if (ownVersionParsed.prerelease != null) {
- return function isExactmatch(globalVersion) {
- return globalVersion === ownVersion;
- };
- }
- function _reject(v6) {
- rejectedVersions.add(v6);
- return false;
- }
- function _accept(v6) {
- acceptedVersions.add(v6);
- return true;
- }
- return function isCompatible(globalVersion) {
- if (acceptedVersions.has(globalVersion)) {
- return true;
- }
- if (rejectedVersions.has(globalVersion)) {
- return false;
- }
- const globalVersionMatch = globalVersion.match(re);
- if (!globalVersionMatch) {
- return _reject(globalVersion);
- }
- const globalVersionParsed = {
- major: +globalVersionMatch[1],
- minor: +globalVersionMatch[2],
- patch: +globalVersionMatch[3],
- prerelease: globalVersionMatch[4]
- };
- if (globalVersionParsed.prerelease != null) {
- return _reject(globalVersion);
- }
- if (ownVersionParsed.major !== globalVersionParsed.major) {
- return _reject(globalVersion);
- }
- if (ownVersionParsed.major === 0) {
- if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
- return _accept(globalVersion);
- }
- return _reject(globalVersion);
- }
- if (ownVersionParsed.minor <= globalVersionParsed.minor) {
- return _accept(globalVersion);
- }
- return _reject(globalVersion);
- };
- }
- exports._makeCompatibilityCheck = _makeCompatibilityCheck;
- exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION);
-});
-
-// node_modules/@opentelemetry/api/build/src/internal/global-utils.js
-var require_global_utils = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = undefined;
- var version_1 = require_version3();
- var semver_1 = require_semver3();
- var major = version_1.VERSION.split(".")[0];
- var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);
- var _global2 = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {};
- function registerGlobal(type, instance, diag, allowOverride = false) {
- var _a8;
- const api2 = _global2[GLOBAL_OPENTELEMETRY_API_KEY] = (_a8 = _global2[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a8 !== undefined ? _a8 : {
- version: version_1.VERSION
- };
- if (!allowOverride && api2[type]) {
- const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
- diag.error(err.stack || err.message);
- return false;
- }
- if (api2.version !== version_1.VERSION) {
- const err = new Error(`@opentelemetry/api: Registration of version v${api2.version} for ${type} does not match previously registered API v${version_1.VERSION}`);
- diag.error(err.stack || err.message);
- return false;
- }
- api2[type] = instance;
- diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`);
- return true;
- }
- exports.registerGlobal = registerGlobal;
- function getGlobal2(type) {
- var _a8, _b2;
- const globalVersion = (_a8 = _global2[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a8 === undefined ? undefined : _a8.version;
- if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) {
- return;
- }
- return (_b2 = _global2[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b2 === undefined ? undefined : _b2[type];
- }
- exports.getGlobal = getGlobal2;
- function unregisterGlobal(type, diag) {
- diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`);
- const api2 = _global2[GLOBAL_OPENTELEMETRY_API_KEY];
- if (api2) {
- delete api2[type];
- }
- }
- exports.unregisterGlobal = unregisterGlobal;
-});
-
-// node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js
-var require_ComponentLogger = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.DiagComponentLogger = undefined;
- var global_utils_1 = require_global_utils();
-
- class DiagComponentLogger {
- constructor(props) {
- this._namespace = props.namespace || "DiagComponentLogger";
- }
- debug(...args) {
- return logProxy("debug", this._namespace, args);
- }
- error(...args) {
- return logProxy("error", this._namespace, args);
- }
- info(...args) {
- return logProxy("info", this._namespace, args);
- }
- warn(...args) {
- return logProxy("warn", this._namespace, args);
- }
- verbose(...args) {
- return logProxy("verbose", this._namespace, args);
- }
- }
- exports.DiagComponentLogger = DiagComponentLogger;
- function logProxy(funcName, namespace, args) {
- const logger34 = (0, global_utils_1.getGlobal)("diag");
- if (!logger34) {
- return;
- }
- return logger34[funcName](namespace, ...args);
- }
-});
-
-// node_modules/@opentelemetry/api/build/src/diag/types.js
-var require_types = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.DiagLogLevel = undefined;
- var DiagLogLevel;
- (function(DiagLogLevel2) {
- DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
- DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
- DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
- DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
- DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
- DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
- DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
- })(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {}));
-});
-
-// node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js
-var require_logLevelLogger = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.createLogLevelDiagLogger = undefined;
- var types_1 = require_types();
- function createLogLevelDiagLogger(maxLevel, logger34) {
- if (maxLevel < types_1.DiagLogLevel.NONE) {
- maxLevel = types_1.DiagLogLevel.NONE;
- } else if (maxLevel > types_1.DiagLogLevel.ALL) {
- maxLevel = types_1.DiagLogLevel.ALL;
- }
- logger34 = logger34 || {};
- function _filterFunc(funcName, theLevel) {
- const theFunc = logger34[funcName];
- if (typeof theFunc === "function" && maxLevel >= theLevel) {
- return theFunc.bind(logger34);
- }
- return function() {};
- }
- return {
- error: _filterFunc("error", types_1.DiagLogLevel.ERROR),
- warn: _filterFunc("warn", types_1.DiagLogLevel.WARN),
- info: _filterFunc("info", types_1.DiagLogLevel.INFO),
- debug: _filterFunc("debug", types_1.DiagLogLevel.DEBUG),
- verbose: _filterFunc("verbose", types_1.DiagLogLevel.VERBOSE)
- };
- }
- exports.createLogLevelDiagLogger = createLogLevelDiagLogger;
-});
-
-// node_modules/@opentelemetry/api/build/src/api/diag.js
-var require_diag = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.DiagAPI = undefined;
- var ComponentLogger_1 = require_ComponentLogger();
- var logLevelLogger_1 = require_logLevelLogger();
- var types_1 = require_types();
- var global_utils_1 = require_global_utils();
- var API_NAME = "diag";
-
- class DiagAPI {
- static instance() {
- if (!this._instance) {
- this._instance = new DiagAPI;
- }
- return this._instance;
- }
- constructor() {
- function _logProxy(funcName) {
- return function(...args) {
- const logger34 = (0, global_utils_1.getGlobal)("diag");
- if (!logger34)
- return;
- return logger34[funcName](...args);
- };
- }
- const self2 = this;
- const setLogger = (logger34, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => {
- var _a8, _b2, _c4;
- if (logger34 === self2) {
- const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
- self2.error((_a8 = err.stack) !== null && _a8 !== undefined ? _a8 : err.message);
- return false;
- }
- if (typeof optionsOrLogLevel === "number") {
- optionsOrLogLevel = {
- logLevel: optionsOrLogLevel
- };
- }
- const oldLogger = (0, global_utils_1.getGlobal)("diag");
- const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b2 = optionsOrLogLevel.logLevel) !== null && _b2 !== undefined ? _b2 : types_1.DiagLogLevel.INFO, logger34);
- if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
- const stack = (_c4 = new Error().stack) !== null && _c4 !== undefined ? _c4 : "";
- oldLogger.warn(`Current logger will be overwritten from ${stack}`);
- newLogger.warn(`Current logger will overwrite one already registered from ${stack}`);
- }
- return (0, global_utils_1.registerGlobal)("diag", newLogger, self2, true);
- };
- self2.setLogger = setLogger;
- self2.disable = () => {
- (0, global_utils_1.unregisterGlobal)(API_NAME, self2);
- };
- self2.createComponentLogger = (options2) => {
- return new ComponentLogger_1.DiagComponentLogger(options2);
- };
- self2.verbose = _logProxy("verbose");
- self2.debug = _logProxy("debug");
- self2.info = _logProxy("info");
- self2.warn = _logProxy("warn");
- self2.error = _logProxy("error");
- }
- }
- exports.DiagAPI = DiagAPI;
-});
-
-// node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js
-var require_baggage_impl = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.BaggageImpl = undefined;
-
- class BaggageImpl {
- constructor(entries) {
- this._entries = entries ? new Map(entries) : new Map;
- }
- getEntry(key) {
- const entry = this._entries.get(key);
- if (!entry) {
- return;
- }
- return Object.assign({}, entry);
- }
- getAllEntries() {
- return Array.from(this._entries.entries());
- }
- setEntry(key, entry) {
- const newBaggage = new BaggageImpl(this._entries);
- newBaggage._entries.set(key, entry);
- return newBaggage;
- }
- removeEntry(key) {
- const newBaggage = new BaggageImpl(this._entries);
- newBaggage._entries.delete(key);
- return newBaggage;
- }
- removeEntries(...keys2) {
- const newBaggage = new BaggageImpl(this._entries);
- for (const key of keys2) {
- newBaggage._entries.delete(key);
- }
- return newBaggage;
- }
- clear() {
- return new BaggageImpl;
- }
- }
- exports.BaggageImpl = BaggageImpl;
-});
-
-// node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js
-var require_symbol = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.baggageEntryMetadataSymbol = undefined;
- exports.baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata");
-});
-
-// node_modules/@opentelemetry/api/build/src/baggage/utils.js
-var require_utils2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.baggageEntryMetadataFromString = exports.createBaggage = undefined;
- var diag_1 = require_diag();
- var baggage_impl_1 = require_baggage_impl();
- var symbol_1 = require_symbol();
- var diag = diag_1.DiagAPI.instance();
- function createBaggage(entries = {}) {
- return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries)));
- }
- exports.createBaggage = createBaggage;
- function baggageEntryMetadataFromString(str) {
- if (typeof str !== "string") {
- diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`);
- str = "";
- }
- return {
- __TYPE__: symbol_1.baggageEntryMetadataSymbol,
- toString() {
- return str;
- }
- };
- }
- exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString;
-});
-
-// node_modules/@opentelemetry/api/build/src/context/context.js
-var require_context = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ROOT_CONTEXT = exports.createContextKey = undefined;
- function createContextKey(description) {
- return Symbol.for(description);
- }
- exports.createContextKey = createContextKey;
-
- class BaseContext {
- constructor(parentContext) {
- const self2 = this;
- self2._currentContext = parentContext ? new Map(parentContext) : new Map;
- self2.getValue = (key) => self2._currentContext.get(key);
- self2.setValue = (key, value) => {
- const context3 = new BaseContext(self2._currentContext);
- context3._currentContext.set(key, value);
- return context3;
- };
- self2.deleteValue = (key) => {
- const context3 = new BaseContext(self2._currentContext);
- context3._currentContext.delete(key);
- return context3;
- };
- }
- }
- exports.ROOT_CONTEXT = new BaseContext;
-});
-
-// node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js
-var require_consoleLogger = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.DiagConsoleLogger = exports._originalConsoleMethods = undefined;
- var consoleMap = [
- { n: "error", c: "error" },
- { n: "warn", c: "warn" },
- { n: "info", c: "info" },
- { n: "debug", c: "debug" },
- { n: "verbose", c: "trace" }
- ];
- exports._originalConsoleMethods = {};
- if (typeof console !== "undefined") {
- const keys2 = [
- "error",
- "warn",
- "info",
- "debug",
- "trace",
- "log"
- ];
- for (const key of keys2) {
- if (typeof console[key] === "function") {
- exports._originalConsoleMethods[key] = console[key];
- }
- }
- }
-
- class DiagConsoleLogger {
- constructor() {
- function _consoleFunc(funcName) {
- return function(...args) {
- let theFunc = exports._originalConsoleMethods[funcName];
- if (typeof theFunc !== "function") {
- theFunc = exports._originalConsoleMethods["log"];
- }
- if (typeof theFunc !== "function" && console) {
- theFunc = console[funcName];
- if (typeof theFunc !== "function") {
- theFunc = console.log;
- }
- }
- if (typeof theFunc === "function") {
- return theFunc.apply(console, args);
- }
- };
- }
- for (let i5 = 0;i5 < consoleMap.length; i5++) {
- this[consoleMap[i5].n] = _consoleFunc(consoleMap[i5].c);
- }
- }
- }
- exports.DiagConsoleLogger = DiagConsoleLogger;
-});
-
-// node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js
-var require_NoopMeter = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_GAUGE_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopGaugeMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = undefined;
-
- class NoopMeter {
- constructor() {}
- createGauge(_name, _options) {
- return exports.NOOP_GAUGE_METRIC;
- }
- createHistogram(_name, _options) {
- return exports.NOOP_HISTOGRAM_METRIC;
- }
- createCounter(_name, _options) {
- return exports.NOOP_COUNTER_METRIC;
- }
- createUpDownCounter(_name, _options) {
- return exports.NOOP_UP_DOWN_COUNTER_METRIC;
- }
- createObservableGauge(_name, _options) {
- return exports.NOOP_OBSERVABLE_GAUGE_METRIC;
- }
- createObservableCounter(_name, _options) {
- return exports.NOOP_OBSERVABLE_COUNTER_METRIC;
- }
- createObservableUpDownCounter(_name, _options) {
- return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
- }
- addBatchObservableCallback(_callback, _observables) {}
- removeBatchObservableCallback(_callback) {}
- }
- exports.NoopMeter = NoopMeter;
-
- class NoopMetric {
- }
- exports.NoopMetric = NoopMetric;
-
- class NoopCounterMetric extends NoopMetric {
- add(_value, _attributes) {}
- }
- exports.NoopCounterMetric = NoopCounterMetric;
-
- class NoopUpDownCounterMetric extends NoopMetric {
- add(_value, _attributes) {}
- }
- exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric;
-
- class NoopGaugeMetric extends NoopMetric {
- record(_value, _attributes) {}
- }
- exports.NoopGaugeMetric = NoopGaugeMetric;
-
- class NoopHistogramMetric extends NoopMetric {
- record(_value, _attributes) {}
- }
- exports.NoopHistogramMetric = NoopHistogramMetric;
-
- class NoopObservableMetric {
- addCallback(_callback) {}
- removeCallback(_callback) {}
- }
- exports.NoopObservableMetric = NoopObservableMetric;
-
- class NoopObservableCounterMetric extends NoopObservableMetric {
- }
- exports.NoopObservableCounterMetric = NoopObservableCounterMetric;
-
- class NoopObservableGaugeMetric extends NoopObservableMetric {
- }
- exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric;
-
- class NoopObservableUpDownCounterMetric extends NoopObservableMetric {
- }
- exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric;
- exports.NOOP_METER = new NoopMeter;
- exports.NOOP_COUNTER_METRIC = new NoopCounterMetric;
- exports.NOOP_GAUGE_METRIC = new NoopGaugeMetric;
- exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric;
- exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric;
- exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric;
- exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric;
- exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric;
- function createNoopMeter() {
- return exports.NOOP_METER;
- }
- exports.createNoopMeter = createNoopMeter;
-});
-
-// node_modules/@opentelemetry/api/build/src/metrics/Metric.js
-var require_Metric = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ValueType = undefined;
- var ValueType;
- (function(ValueType2) {
- ValueType2[ValueType2["INT"] = 0] = "INT";
- ValueType2[ValueType2["DOUBLE"] = 1] = "DOUBLE";
- })(ValueType = exports.ValueType || (exports.ValueType = {}));
-});
-
-// node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js
-var require_TextMapPropagator = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.defaultTextMapSetter = exports.defaultTextMapGetter = undefined;
- exports.defaultTextMapGetter = {
- get(carrier, key) {
- if (carrier == null) {
- return;
- }
- return carrier[key];
- },
- keys(carrier) {
- if (carrier == null) {
- return [];
- }
- return Object.keys(carrier);
- }
- };
- exports.defaultTextMapSetter = {
- set(carrier, key, value) {
- if (carrier == null) {
- return;
- }
- carrier[key] = value;
- }
- };
-});
-
-// node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js
-var require_NoopContextManager = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.NoopContextManager = undefined;
- var context_1 = require_context();
-
- class NoopContextManager {
- active() {
- return context_1.ROOT_CONTEXT;
- }
- with(_context, fn, thisArg, ...args) {
- return fn.call(thisArg, ...args);
- }
- bind(_context, target) {
- return target;
- }
- enable() {
- return this;
- }
- disable() {
- return this;
- }
- }
- exports.NoopContextManager = NoopContextManager;
-});
-
-// node_modules/@opentelemetry/api/build/src/api/context.js
-var require_context2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ContextAPI = undefined;
- var NoopContextManager_1 = require_NoopContextManager();
- var global_utils_1 = require_global_utils();
- var diag_1 = require_diag();
- var API_NAME = "context";
- var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager;
-
- class ContextAPI {
- constructor() {}
- static getInstance() {
- if (!this._instance) {
- this._instance = new ContextAPI;
- }
- return this._instance;
- }
- setGlobalContextManager(contextManager) {
- return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance());
- }
- active() {
- return this._getContextManager().active();
- }
- with(context3, fn, thisArg, ...args) {
- return this._getContextManager().with(context3, fn, thisArg, ...args);
- }
- bind(context3, target) {
- return this._getContextManager().bind(context3, target);
- }
- _getContextManager() {
- return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER;
- }
- disable() {
- this._getContextManager().disable();
- (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
- }
- }
- exports.ContextAPI = ContextAPI;
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/trace_flags.js
-var require_trace_flags = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.TraceFlags = undefined;
- var TraceFlags;
- (function(TraceFlags2) {
- TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
- TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
- })(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {}));
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js
-var require_invalid_span_constants = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = undefined;
- var trace_flags_1 = require_trace_flags();
- exports.INVALID_SPANID = "0000000000000000";
- exports.INVALID_TRACEID = "00000000000000000000000000000000";
- exports.INVALID_SPAN_CONTEXT = {
- traceId: exports.INVALID_TRACEID,
- spanId: exports.INVALID_SPANID,
- traceFlags: trace_flags_1.TraceFlags.NONE
- };
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js
-var require_NonRecordingSpan = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.NonRecordingSpan = undefined;
- var invalid_span_constants_1 = require_invalid_span_constants();
-
- class NonRecordingSpan {
- constructor(spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) {
- this._spanContext = spanContext;
- }
- spanContext() {
- return this._spanContext;
- }
- setAttribute(_key, _value) {
- return this;
- }
- setAttributes(_attributes) {
- return this;
- }
- addEvent(_name, _attributes) {
- return this;
- }
- addLink(_link) {
- return this;
- }
- addLinks(_links) {
- return this;
- }
- setStatus(_status) {
- return this;
- }
- updateName(_name) {
- return this;
- }
- end(_endTime) {}
- isRecording() {
- return false;
- }
- recordException(_exception, _time) {}
- }
- exports.NonRecordingSpan = NonRecordingSpan;
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/context-utils.js
-var require_context_utils = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = undefined;
- var context_1 = require_context();
- var NonRecordingSpan_1 = require_NonRecordingSpan();
- var context_2 = require_context2();
- var SPAN_KEY = (0, context_1.createContextKey)("OpenTelemetry Context Key SPAN");
- function getSpan(context3) {
- return context3.getValue(SPAN_KEY) || undefined;
- }
- exports.getSpan = getSpan;
- function getActiveSpan() {
- return getSpan(context_2.ContextAPI.getInstance().active());
- }
- exports.getActiveSpan = getActiveSpan;
- function setSpan(context3, span) {
- return context3.setValue(SPAN_KEY, span);
- }
- exports.setSpan = setSpan;
- function deleteSpan(context3) {
- return context3.deleteValue(SPAN_KEY);
- }
- exports.deleteSpan = deleteSpan;
- function setSpanContext(context3, spanContext) {
- return setSpan(context3, new NonRecordingSpan_1.NonRecordingSpan(spanContext));
- }
- exports.setSpanContext = setSpanContext;
- function getSpanContext(context3) {
- var _a8;
- return (_a8 = getSpan(context3)) === null || _a8 === undefined ? undefined : _a8.spanContext();
- }
- exports.getSpanContext = getSpanContext;
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js
-var require_spancontext_utils = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = undefined;
- var invalid_span_constants_1 = require_invalid_span_constants();
- var NonRecordingSpan_1 = require_NonRecordingSpan();
- var isHex = new Uint8Array([
- 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
- ]);
- function isValidHex(id, length) {
- if (typeof id !== "string" || id.length !== length)
- return false;
- let r4 = 0;
- for (let i5 = 0;i5 < id.length; i5 += 4) {
- r4 += (isHex[id.charCodeAt(i5)] | 0) + (isHex[id.charCodeAt(i5 + 1)] | 0) + (isHex[id.charCodeAt(i5 + 2)] | 0) + (isHex[id.charCodeAt(i5 + 3)] | 0);
- }
- return r4 === length;
- }
- function isValidTraceId(traceId) {
- return isValidHex(traceId, 32) && traceId !== invalid_span_constants_1.INVALID_TRACEID;
- }
- exports.isValidTraceId = isValidTraceId;
- function isValidSpanId(spanId) {
- return isValidHex(spanId, 16) && spanId !== invalid_span_constants_1.INVALID_SPANID;
- }
- exports.isValidSpanId = isValidSpanId;
- function isSpanContextValid(spanContext) {
- return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
- }
- exports.isSpanContextValid = isSpanContextValid;
- function wrapSpanContext(spanContext) {
- return new NonRecordingSpan_1.NonRecordingSpan(spanContext);
- }
- exports.wrapSpanContext = wrapSpanContext;
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js
-var require_NoopTracer = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.NoopTracer = undefined;
- var context_1 = require_context2();
- var context_utils_1 = require_context_utils();
- var NonRecordingSpan_1 = require_NonRecordingSpan();
- var spancontext_utils_1 = require_spancontext_utils();
- var contextApi = context_1.ContextAPI.getInstance();
-
- class NoopTracer {
- startSpan(name3, options2, context3 = contextApi.active()) {
- const root2 = Boolean(options2 === null || options2 === undefined ? undefined : options2.root);
- if (root2) {
- return new NonRecordingSpan_1.NonRecordingSpan;
- }
- const parentFromContext = context3 && (0, context_utils_1.getSpanContext)(context3);
- if (isSpanContext(parentFromContext) && (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) {
- return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext);
- } else {
- return new NonRecordingSpan_1.NonRecordingSpan;
- }
- }
- startActiveSpan(name3, arg2, arg3, arg4) {
- let opts;
- let ctx;
- let fn;
- if (arguments.length < 2) {
- return;
- } else if (arguments.length === 2) {
- fn = arg2;
- } else if (arguments.length === 3) {
- opts = arg2;
- fn = arg3;
- } else {
- opts = arg2;
- ctx = arg3;
- fn = arg4;
- }
- const parentContext = ctx !== null && ctx !== undefined ? ctx : contextApi.active();
- const span = this.startSpan(name3, opts, parentContext);
- const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span);
- return contextApi.with(contextWithSpanSet, fn, undefined, span);
- }
- }
- exports.NoopTracer = NoopTracer;
- function isSpanContext(spanContext) {
- return spanContext !== null && typeof spanContext === "object" && "spanId" in spanContext && typeof spanContext["spanId"] === "string" && "traceId" in spanContext && typeof spanContext["traceId"] === "string" && "traceFlags" in spanContext && typeof spanContext["traceFlags"] === "number";
- }
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js
-var require_ProxyTracer = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ProxyTracer = undefined;
- var NoopTracer_1 = require_NoopTracer();
- var NOOP_TRACER = new NoopTracer_1.NoopTracer;
-
- class ProxyTracer {
- constructor(provider5, name3, version6, options2) {
- this._provider = provider5;
- this.name = name3;
- this.version = version6;
- this.options = options2;
- }
- startSpan(name3, options2, context3) {
- return this._getTracer().startSpan(name3, options2, context3);
- }
- startActiveSpan(_name, _options, _context, _fn) {
- const tracer = this._getTracer();
- return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
- }
- _getTracer() {
- if (this._delegate) {
- return this._delegate;
- }
- const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
- if (!tracer) {
- return NOOP_TRACER;
- }
- this._delegate = tracer;
- return this._delegate;
- }
- }
- exports.ProxyTracer = ProxyTracer;
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js
-var require_NoopTracerProvider = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.NoopTracerProvider = undefined;
- var NoopTracer_1 = require_NoopTracer();
-
- class NoopTracerProvider {
- getTracer(_name, _version, _options) {
- return new NoopTracer_1.NoopTracer;
- }
- }
- exports.NoopTracerProvider = NoopTracerProvider;
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js
-var require_ProxyTracerProvider = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ProxyTracerProvider = undefined;
- var ProxyTracer_1 = require_ProxyTracer();
- var NoopTracerProvider_1 = require_NoopTracerProvider();
- var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider;
-
- class ProxyTracerProvider {
- getTracer(name3, version6, options2) {
- var _a8;
- return (_a8 = this.getDelegateTracer(name3, version6, options2)) !== null && _a8 !== undefined ? _a8 : new ProxyTracer_1.ProxyTracer(this, name3, version6, options2);
- }
- getDelegate() {
- var _a8;
- return (_a8 = this._delegate) !== null && _a8 !== undefined ? _a8 : NOOP_TRACER_PROVIDER;
- }
- setDelegate(delegate) {
- this._delegate = delegate;
- }
- getDelegateTracer(name3, version6, options2) {
- var _a8;
- return (_a8 = this._delegate) === null || _a8 === undefined ? undefined : _a8.getTracer(name3, version6, options2);
- }
- }
- exports.ProxyTracerProvider = ProxyTracerProvider;
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js
-var require_SamplingResult = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.SamplingDecision = undefined;
- var SamplingDecision;
- (function(SamplingDecision2) {
- SamplingDecision2[SamplingDecision2["NOT_RECORD"] = 0] = "NOT_RECORD";
- SamplingDecision2[SamplingDecision2["RECORD"] = 1] = "RECORD";
- SamplingDecision2[SamplingDecision2["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
- })(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {}));
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/span_kind.js
-var require_span_kind = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.SpanKind = undefined;
- var SpanKind;
- (function(SpanKind2) {
- SpanKind2[SpanKind2["INTERNAL"] = 0] = "INTERNAL";
- SpanKind2[SpanKind2["SERVER"] = 1] = "SERVER";
- SpanKind2[SpanKind2["CLIENT"] = 2] = "CLIENT";
- SpanKind2[SpanKind2["PRODUCER"] = 3] = "PRODUCER";
- SpanKind2[SpanKind2["CONSUMER"] = 4] = "CONSUMER";
- })(SpanKind = exports.SpanKind || (exports.SpanKind = {}));
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/status.js
-var require_status = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.SpanStatusCode = undefined;
- var SpanStatusCode;
- (function(SpanStatusCode2) {
- SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
- SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
- SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
- })(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {}));
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js
-var require_tracestate_validators = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.validateValue = exports.validateKey = undefined;
- var VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]";
- var VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;
- var VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;
- var VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);
- var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
- var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
- function validateKey(key) {
- return VALID_KEY_REGEX.test(key);
- }
- exports.validateKey = validateKey;
- function validateValue(value) {
- return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value);
- }
- exports.validateValue = validateValue;
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js
-var require_tracestate_impl = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.TraceStateImpl = undefined;
- var tracestate_validators_1 = require_tracestate_validators();
- var MAX_TRACE_STATE_ITEMS = 32;
- var MAX_TRACE_STATE_LEN = 512;
- var LIST_MEMBERS_SEPARATOR = ",";
- var LIST_MEMBER_KEY_VALUE_SPLITTER = "=";
-
- class TraceStateImpl {
- constructor(rawTraceState) {
- this._internalState = new Map;
- if (rawTraceState)
- this._parse(rawTraceState);
- }
- set(key, value) {
- const traceState = this._clone();
- if (traceState._internalState.has(key)) {
- traceState._internalState.delete(key);
- }
- traceState._internalState.set(key, value);
- return traceState;
- }
- unset(key) {
- const traceState = this._clone();
- traceState._internalState.delete(key);
- return traceState;
- }
- get(key) {
- return this._internalState.get(key);
- }
- serialize() {
- return Array.from(this._internalState.keys()).reduceRight((agg, key) => {
- agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));
- return agg;
- }, []).join(LIST_MEMBERS_SEPARATOR);
- }
- _parse(rawTraceState) {
- if (rawTraceState.length > MAX_TRACE_STATE_LEN)
- return;
- this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR).reduceRight((agg, part) => {
- const listMember = part.trim();
- const i5 = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
- if (i5 !== -1) {
- const key = listMember.slice(0, i5);
- const value = listMember.slice(i5 + 1, part.length);
- if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) {
- agg.set(key, value);
- } else {}
- }
- return agg;
- }, new Map);
- if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {
- this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS));
- }
- }
- _keys() {
- return Array.from(this._internalState.keys()).reverse();
- }
- _clone() {
- const traceState = new TraceStateImpl;
- traceState._internalState = new Map(this._internalState);
- return traceState;
- }
- }
- exports.TraceStateImpl = TraceStateImpl;
-});
-
-// node_modules/@opentelemetry/api/build/src/trace/internal/utils.js
-var require_utils3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.createTraceState = undefined;
- var tracestate_impl_1 = require_tracestate_impl();
- function createTraceState(rawTraceState) {
- return new tracestate_impl_1.TraceStateImpl(rawTraceState);
- }
- exports.createTraceState = createTraceState;
-});
-
-// node_modules/@opentelemetry/api/build/src/context-api.js
-var require_context_api = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.context = undefined;
- var context_1 = require_context2();
- exports.context = context_1.ContextAPI.getInstance();
-});
-
-// node_modules/@opentelemetry/api/build/src/diag-api.js
-var require_diag_api = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.diag = undefined;
- var diag_1 = require_diag();
- exports.diag = diag_1.DiagAPI.instance();
-});
-
-// node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js
-var require_NoopMeterProvider = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = undefined;
- var NoopMeter_1 = require_NoopMeter();
-
- class NoopMeterProvider {
- getMeter(_name, _version, _options) {
- return NoopMeter_1.NOOP_METER;
- }
- }
- exports.NoopMeterProvider = NoopMeterProvider;
- exports.NOOP_METER_PROVIDER = new NoopMeterProvider;
-});
-
-// node_modules/@opentelemetry/api/build/src/api/metrics.js
-var require_metrics = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.MetricsAPI = undefined;
- var NoopMeterProvider_1 = require_NoopMeterProvider();
- var global_utils_1 = require_global_utils();
- var diag_1 = require_diag();
- var API_NAME = "metrics";
-
- class MetricsAPI {
- constructor() {}
- static getInstance() {
- if (!this._instance) {
- this._instance = new MetricsAPI;
- }
- return this._instance;
- }
- setGlobalMeterProvider(provider5) {
- return (0, global_utils_1.registerGlobal)(API_NAME, provider5, diag_1.DiagAPI.instance());
- }
- getMeterProvider() {
- return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER;
- }
- getMeter(name3, version6, options2) {
- return this.getMeterProvider().getMeter(name3, version6, options2);
- }
- disable() {
- (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
- }
- }
- exports.MetricsAPI = MetricsAPI;
-});
-
-// node_modules/@opentelemetry/api/build/src/metrics-api.js
-var require_metrics_api = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.metrics = undefined;
- var metrics_1 = require_metrics();
- exports.metrics = metrics_1.MetricsAPI.getInstance();
-});
-
-// node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js
-var require_NoopTextMapPropagator = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.NoopTextMapPropagator = undefined;
-
- class NoopTextMapPropagator {
- inject(_context, _carrier) {}
- extract(context3, _carrier) {
- return context3;
- }
- fields() {
- return [];
- }
- }
- exports.NoopTextMapPropagator = NoopTextMapPropagator;
-});
-
-// node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js
-var require_context_helpers = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = undefined;
- var context_1 = require_context2();
- var context_2 = require_context();
- var BAGGAGE_KEY = (0, context_2.createContextKey)("OpenTelemetry Baggage Key");
- function getBaggage(context3) {
- return context3.getValue(BAGGAGE_KEY) || undefined;
- }
- exports.getBaggage = getBaggage;
- function getActiveBaggage() {
- return getBaggage(context_1.ContextAPI.getInstance().active());
- }
- exports.getActiveBaggage = getActiveBaggage;
- function setBaggage(context3, baggage) {
- return context3.setValue(BAGGAGE_KEY, baggage);
- }
- exports.setBaggage = setBaggage;
- function deleteBaggage(context3) {
- return context3.deleteValue(BAGGAGE_KEY);
- }
- exports.deleteBaggage = deleteBaggage;
-});
-
-// node_modules/@opentelemetry/api/build/src/api/propagation.js
-var require_propagation = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.PropagationAPI = undefined;
- var global_utils_1 = require_global_utils();
- var NoopTextMapPropagator_1 = require_NoopTextMapPropagator();
- var TextMapPropagator_1 = require_TextMapPropagator();
- var context_helpers_1 = require_context_helpers();
- var utils_1 = require_utils2();
- var diag_1 = require_diag();
- var API_NAME = "propagation";
- var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator;
-
- class PropagationAPI {
- constructor() {
- this.createBaggage = utils_1.createBaggage;
- this.getBaggage = context_helpers_1.getBaggage;
- this.getActiveBaggage = context_helpers_1.getActiveBaggage;
- this.setBaggage = context_helpers_1.setBaggage;
- this.deleteBaggage = context_helpers_1.deleteBaggage;
- }
- static getInstance() {
- if (!this._instance) {
- this._instance = new PropagationAPI;
- }
- return this._instance;
- }
- setGlobalPropagator(propagator) {
- return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance());
- }
- inject(context3, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) {
- return this._getGlobalPropagator().inject(context3, carrier, setter);
- }
- extract(context3, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) {
- return this._getGlobalPropagator().extract(context3, carrier, getter);
- }
- fields() {
- return this._getGlobalPropagator().fields();
- }
- disable() {
- (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
- }
- _getGlobalPropagator() {
- return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;
- }
- }
- exports.PropagationAPI = PropagationAPI;
-});
-
-// node_modules/@opentelemetry/api/build/src/propagation-api.js
-var require_propagation_api = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.propagation = undefined;
- var propagation_1 = require_propagation();
- exports.propagation = propagation_1.PropagationAPI.getInstance();
-});
-
-// node_modules/@opentelemetry/api/build/src/api/trace.js
-var require_trace = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.TraceAPI = undefined;
- var global_utils_1 = require_global_utils();
- var ProxyTracerProvider_1 = require_ProxyTracerProvider();
- var spancontext_utils_1 = require_spancontext_utils();
- var context_utils_1 = require_context_utils();
- var diag_1 = require_diag();
- var API_NAME = "trace";
-
- class TraceAPI {
- constructor() {
- this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider;
- this.wrapSpanContext = spancontext_utils_1.wrapSpanContext;
- this.isSpanContextValid = spancontext_utils_1.isSpanContextValid;
- this.deleteSpan = context_utils_1.deleteSpan;
- this.getSpan = context_utils_1.getSpan;
- this.getActiveSpan = context_utils_1.getActiveSpan;
- this.getSpanContext = context_utils_1.getSpanContext;
- this.setSpan = context_utils_1.setSpan;
- this.setSpanContext = context_utils_1.setSpanContext;
- }
- static getInstance() {
- if (!this._instance) {
- this._instance = new TraceAPI;
- }
- return this._instance;
- }
- setGlobalTracerProvider(provider5) {
- const success2 = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance());
- if (success2) {
- this._proxyTracerProvider.setDelegate(provider5);
- }
- return success2;
- }
- getTracerProvider() {
- return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider;
- }
- getTracer(name3, version6) {
- return this.getTracerProvider().getTracer(name3, version6);
- }
- disable() {
- (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
- this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider;
- }
- }
- exports.TraceAPI = TraceAPI;
-});
-
-// node_modules/@opentelemetry/api/build/src/trace-api.js
-var require_trace_api = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.trace = undefined;
- var trace_1 = require_trace();
- exports.trace = trace_1.TraceAPI.getInstance();
-});
-
-// node_modules/@opentelemetry/api/build/src/index.js
-var require_src7 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = undefined;
- var utils_1 = require_utils2();
- Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function() {
- return utils_1.baggageEntryMetadataFromString;
- } });
- var context_1 = require_context();
- Object.defineProperty(exports, "createContextKey", { enumerable: true, get: function() {
- return context_1.createContextKey;
- } });
- Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function() {
- return context_1.ROOT_CONTEXT;
- } });
- var consoleLogger_1 = require_consoleLogger();
- Object.defineProperty(exports, "DiagConsoleLogger", { enumerable: true, get: function() {
- return consoleLogger_1.DiagConsoleLogger;
- } });
- var types_1 = require_types();
- Object.defineProperty(exports, "DiagLogLevel", { enumerable: true, get: function() {
- return types_1.DiagLogLevel;
- } });
- var NoopMeter_1 = require_NoopMeter();
- Object.defineProperty(exports, "createNoopMeter", { enumerable: true, get: function() {
- return NoopMeter_1.createNoopMeter;
- } });
- var Metric_1 = require_Metric();
- Object.defineProperty(exports, "ValueType", { enumerable: true, get: function() {
- return Metric_1.ValueType;
- } });
- var TextMapPropagator_1 = require_TextMapPropagator();
- Object.defineProperty(exports, "defaultTextMapGetter", { enumerable: true, get: function() {
- return TextMapPropagator_1.defaultTextMapGetter;
- } });
- Object.defineProperty(exports, "defaultTextMapSetter", { enumerable: true, get: function() {
- return TextMapPropagator_1.defaultTextMapSetter;
- } });
- var ProxyTracer_1 = require_ProxyTracer();
- Object.defineProperty(exports, "ProxyTracer", { enumerable: true, get: function() {
- return ProxyTracer_1.ProxyTracer;
- } });
- var ProxyTracerProvider_1 = require_ProxyTracerProvider();
- Object.defineProperty(exports, "ProxyTracerProvider", { enumerable: true, get: function() {
- return ProxyTracerProvider_1.ProxyTracerProvider;
- } });
- var SamplingResult_1 = require_SamplingResult();
- Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function() {
- return SamplingResult_1.SamplingDecision;
- } });
- var span_kind_1 = require_span_kind();
- Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function() {
- return span_kind_1.SpanKind;
- } });
- var status_1 = require_status();
- Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function() {
- return status_1.SpanStatusCode;
- } });
- var trace_flags_1 = require_trace_flags();
- Object.defineProperty(exports, "TraceFlags", { enumerable: true, get: function() {
- return trace_flags_1.TraceFlags;
- } });
- var utils_2 = require_utils3();
- Object.defineProperty(exports, "createTraceState", { enumerable: true, get: function() {
- return utils_2.createTraceState;
- } });
- var spancontext_utils_1 = require_spancontext_utils();
- Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function() {
- return spancontext_utils_1.isSpanContextValid;
- } });
- Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function() {
- return spancontext_utils_1.isValidTraceId;
- } });
- Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function() {
- return spancontext_utils_1.isValidSpanId;
- } });
- var invalid_span_constants_1 = require_invalid_span_constants();
- Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function() {
- return invalid_span_constants_1.INVALID_SPANID;
- } });
- Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function() {
- return invalid_span_constants_1.INVALID_TRACEID;
- } });
- Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function() {
- return invalid_span_constants_1.INVALID_SPAN_CONTEXT;
- } });
- var context_api_1 = require_context_api();
- Object.defineProperty(exports, "context", { enumerable: true, get: function() {
- return context_api_1.context;
- } });
- var diag_api_1 = require_diag_api();
- Object.defineProperty(exports, "diag", { enumerable: true, get: function() {
- return diag_api_1.diag;
- } });
- var metrics_api_1 = require_metrics_api();
- Object.defineProperty(exports, "metrics", { enumerable: true, get: function() {
- return metrics_api_1.metrics;
- } });
- var propagation_api_1 = require_propagation_api();
- Object.defineProperty(exports, "propagation", { enumerable: true, get: function() {
- return propagation_api_1.propagation;
- } });
- var trace_api_1 = require_trace_api();
- Object.defineProperty(exports, "trace", { enumerable: true, get: function() {
- return trace_api_1.trace;
- } });
- exports.default = {
- context: context_api_1.context,
- diag: diag_api_1.diag,
- metrics: metrics_api_1.metrics,
- propagation: propagation_api_1.propagation,
- trace: trace_api_1.trace
- };
-});
-
-// node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js
-var require_suppress_tracing = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isTracingSuppressed = exports.unsuppressTracing = exports.suppressTracing = undefined;
- var api_1 = require_src7();
- var SUPPRESS_TRACING_KEY = (0, api_1.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
- function suppressTracing(context3) {
- return context3.setValue(SUPPRESS_TRACING_KEY, true);
- }
- exports.suppressTracing = suppressTracing;
- function unsuppressTracing(context3) {
- return context3.deleteValue(SUPPRESS_TRACING_KEY);
- }
- exports.unsuppressTracing = unsuppressTracing;
- function isTracingSuppressed(context3) {
- return context3.getValue(SUPPRESS_TRACING_KEY) === true;
- }
- exports.isTracingSuppressed = isTracingSuppressed;
-});
-
-// node_modules/@opentelemetry/core/build/src/baggage/constants.js
-var require_constants4 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.BAGGAGE_MAX_TOTAL_LENGTH = exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = exports.BAGGAGE_MAX_NAME_VALUE_PAIRS = exports.BAGGAGE_HEADER = exports.BAGGAGE_ITEMS_SEPARATOR = exports.BAGGAGE_PROPERTIES_SEPARATOR = exports.BAGGAGE_KEY_PAIR_SEPARATOR = undefined;
- exports.BAGGAGE_KEY_PAIR_SEPARATOR = "=";
- exports.BAGGAGE_PROPERTIES_SEPARATOR = ";";
- exports.BAGGAGE_ITEMS_SEPARATOR = ",";
- exports.BAGGAGE_HEADER = "baggage";
- exports.BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;
- exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;
- exports.BAGGAGE_MAX_TOTAL_LENGTH = 8192;
-});
-
-// node_modules/@opentelemetry/core/build/src/baggage/utils.js
-var require_utils4 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.parseKeyPairsIntoRecord = exports.parsePairKeyValue = exports.getKeyPairs = exports.serializeKeyPairs = undefined;
- var api_1 = require_src7();
- var constants_1 = require_constants4();
- function serializeKeyPairs(keyPairs) {
- return keyPairs.reduce((hValue, current) => {
- const value = `${hValue}${hValue !== "" ? constants_1.BAGGAGE_ITEMS_SEPARATOR : ""}${current}`;
- return value.length > constants_1.BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;
- }, "");
- }
- exports.serializeKeyPairs = serializeKeyPairs;
- function getKeyPairs(baggage) {
- return baggage.getAllEntries().map(([key, value]) => {
- let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;
- if (value.metadata !== undefined) {
- entry += constants_1.BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();
- }
- return entry;
- });
- }
- exports.getKeyPairs = getKeyPairs;
- function parsePairKeyValue(entry) {
- if (!entry)
- return;
- const metadataSeparatorIndex = entry.indexOf(constants_1.BAGGAGE_PROPERTIES_SEPARATOR);
- const keyPairPart = metadataSeparatorIndex === -1 ? entry : entry.substring(0, metadataSeparatorIndex);
- const separatorIndex = keyPairPart.indexOf(constants_1.BAGGAGE_KEY_PAIR_SEPARATOR);
- if (separatorIndex <= 0)
- return;
- const rawKey = keyPairPart.substring(0, separatorIndex).trim();
- const rawValue = keyPairPart.substring(separatorIndex + 1).trim();
- if (!rawKey || !rawValue)
- return;
- let key;
- let value;
- try {
- key = decodeURIComponent(rawKey);
- value = decodeURIComponent(rawValue);
- } catch {
- return;
- }
- let metadata;
- if (metadataSeparatorIndex !== -1 && metadataSeparatorIndex < entry.length - 1) {
- const metadataString = entry.substring(metadataSeparatorIndex + 1);
- metadata = (0, api_1.baggageEntryMetadataFromString)(metadataString);
- }
- return { key, value, metadata };
- }
- exports.parsePairKeyValue = parsePairKeyValue;
- function parseKeyPairsIntoRecord(value) {
- const result = {};
- if (typeof value === "string" && value.length > 0) {
- value.split(constants_1.BAGGAGE_ITEMS_SEPARATOR).forEach((entry) => {
- const keyPair = parsePairKeyValue(entry);
- if (keyPair !== undefined && keyPair.value.length > 0) {
- result[keyPair.key] = keyPair.value;
- }
- });
- }
- return result;
- }
- exports.parseKeyPairsIntoRecord = parseKeyPairsIntoRecord;
-});
-
-// node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js
-var require_W3CBaggagePropagator = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.W3CBaggagePropagator = undefined;
- var api_1 = require_src7();
- var suppress_tracing_1 = require_suppress_tracing();
- var constants_1 = require_constants4();
- var utils_1 = require_utils4();
-
- class W3CBaggagePropagator {
- inject(context3, carrier, setter) {
- const baggage = api_1.propagation.getBaggage(context3);
- if (!baggage || (0, suppress_tracing_1.isTracingSuppressed)(context3))
- return;
- const keyPairs = (0, utils_1.getKeyPairs)(baggage).filter((pair) => {
- return pair.length <= constants_1.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS;
- }).slice(0, constants_1.BAGGAGE_MAX_NAME_VALUE_PAIRS);
- const headerValue = (0, utils_1.serializeKeyPairs)(keyPairs);
- if (headerValue.length > 0) {
- setter.set(carrier, constants_1.BAGGAGE_HEADER, headerValue);
- }
- }
- extract(context3, carrier, getter) {
- const headerValue = getter.get(carrier, constants_1.BAGGAGE_HEADER);
- const baggageString = Array.isArray(headerValue) ? headerValue.join(constants_1.BAGGAGE_ITEMS_SEPARATOR) : headerValue;
- if (!baggageString)
- return context3;
- const baggage = {};
- if (baggageString.length === 0) {
- return context3;
- }
- const pairs = baggageString.split(constants_1.BAGGAGE_ITEMS_SEPARATOR);
- pairs.forEach((entry) => {
- const keyPair = (0, utils_1.parsePairKeyValue)(entry);
- if (keyPair) {
- const baggageEntry = { value: keyPair.value };
- if (keyPair.metadata) {
- baggageEntry.metadata = keyPair.metadata;
- }
- baggage[keyPair.key] = baggageEntry;
- }
- });
- if (Object.entries(baggage).length === 0) {
- return context3;
- }
- return api_1.propagation.setBaggage(context3, api_1.propagation.createBaggage(baggage));
- }
- fields() {
- return [constants_1.BAGGAGE_HEADER];
- }
- }
- exports.W3CBaggagePropagator = W3CBaggagePropagator;
-});
-
-// node_modules/@opentelemetry/core/build/src/common/anchored-clock.js
-var require_anchored_clock = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AnchoredClock = undefined;
-
- class AnchoredClock {
- _monotonicClock;
- _epochMillis;
- _performanceMillis;
- constructor(systemClock, monotonicClock) {
- this._monotonicClock = monotonicClock;
- this._epochMillis = systemClock.now();
- this._performanceMillis = monotonicClock.now();
- }
- now() {
- const delta = this._monotonicClock.now() - this._performanceMillis;
- return this._epochMillis + delta;
- }
- }
- exports.AnchoredClock = AnchoredClock;
-});
-
-// node_modules/@opentelemetry/core/build/src/common/attributes.js
-var require_attributes = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isAttributeValue = exports.isAttributeKey = exports.sanitizeAttributes = undefined;
- var api_1 = require_src7();
- function sanitizeAttributes(attributes) {
- const out = {};
- if (typeof attributes !== "object" || attributes == null) {
- return out;
- }
- for (const key in attributes) {
- if (!Object.prototype.hasOwnProperty.call(attributes, key)) {
- continue;
- }
- if (!isAttributeKey(key)) {
- api_1.diag.warn(`Invalid attribute key: ${key}`);
- continue;
- }
- const val = attributes[key];
- if (!isAttributeValue(val)) {
- api_1.diag.warn(`Invalid attribute value set for key: ${key}`);
- continue;
- }
- if (Array.isArray(val)) {
- out[key] = val.slice();
- } else {
- out[key] = val;
- }
- }
- return out;
- }
- exports.sanitizeAttributes = sanitizeAttributes;
- function isAttributeKey(key) {
- return typeof key === "string" && key !== "";
- }
- exports.isAttributeKey = isAttributeKey;
- function isAttributeValue(val) {
- if (val == null) {
- return true;
- }
- if (Array.isArray(val)) {
- return isHomogeneousAttributeValueArray(val);
- }
- return isValidPrimitiveAttributeValueType(typeof val);
- }
- exports.isAttributeValue = isAttributeValue;
- function isHomogeneousAttributeValueArray(arr) {
- let type;
- for (const element of arr) {
- if (element == null)
- continue;
- const elementType = typeof element;
- if (elementType === type) {
- continue;
- }
- if (!type) {
- if (isValidPrimitiveAttributeValueType(elementType)) {
- type = elementType;
- continue;
- }
- return false;
- }
- return false;
- }
- return true;
- }
- function isValidPrimitiveAttributeValueType(valType) {
- switch (valType) {
- case "number":
- case "boolean":
- case "string":
- return true;
- }
- return false;
- }
-});
-
-// node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js
-var require_logging_error_handler = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.loggingErrorHandler = undefined;
- var api_1 = require_src7();
- function loggingErrorHandler() {
- return (ex) => {
- api_1.diag.error(stringifyException(ex));
- };
- }
- exports.loggingErrorHandler = loggingErrorHandler;
- function stringifyException(ex) {
- if (typeof ex === "string") {
- return ex;
- } else {
- return JSON.stringify(flattenException(ex));
- }
- }
- function flattenException(ex) {
- const result = {};
- let current = ex;
- while (current !== null) {
- Object.getOwnPropertyNames(current).forEach((propertyName) => {
- if (result[propertyName])
- return;
- const value = current[propertyName];
- if (value) {
- result[propertyName] = String(value);
- }
- });
- current = Object.getPrototypeOf(current);
- }
- return result;
- }
-});
-
-// node_modules/@opentelemetry/core/build/src/common/global-error-handler.js
-var require_global_error_handler = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.globalErrorHandler = exports.setGlobalErrorHandler = undefined;
- var logging_error_handler_1 = require_logging_error_handler();
- var delegateHandler = (0, logging_error_handler_1.loggingErrorHandler)();
- function setGlobalErrorHandler(handler) {
- delegateHandler = handler;
- }
- exports.setGlobalErrorHandler = setGlobalErrorHandler;
- function globalErrorHandler(ex) {
- try {
- delegateHandler(ex);
- } catch {}
- }
- exports.globalErrorHandler = globalErrorHandler;
-});
-
-// node_modules/@opentelemetry/core/build/src/platform/node/environment.js
-var require_environment = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getStringListFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports.getNumberFromEnv = undefined;
- var api_1 = require_src7();
- var util_1 = __require("util");
- function getNumberFromEnv(key) {
- const raw = process.env[key];
- if (raw == null || raw.trim() === "") {
- return;
- }
- const value = Number(raw);
- if (isNaN(value)) {
- api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw)} for ${key}, expected a number, using defaults`);
- return;
- }
- return value;
- }
- exports.getNumberFromEnv = getNumberFromEnv;
- function getStringFromEnv(key) {
- const raw = process.env[key];
- if (raw == null || raw.trim() === "") {
- return;
- }
- return raw;
- }
- exports.getStringFromEnv = getStringFromEnv;
- function getBooleanFromEnv(key) {
- const raw = process.env[key]?.trim().toLowerCase();
- if (raw == null || raw === "") {
- return false;
- }
- if (raw === "true") {
- return true;
- } else if (raw === "false") {
- return false;
- } else {
- api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`);
- return false;
- }
- }
- exports.getBooleanFromEnv = getBooleanFromEnv;
- function getStringListFromEnv(key) {
- return getStringFromEnv(key)?.split(",").map((v6) => v6.trim()).filter((s4) => s4 !== "");
- }
- exports.getStringListFromEnv = getStringListFromEnv;
-});
-
-// node_modules/@opentelemetry/core/build/src/common/globalThis.js
-var require_globalThis = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports._globalThis = undefined;
- exports._globalThis = globalThis;
-});
-
-// node_modules/@opentelemetry/core/build/src/version.js
-var require_version4 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.VERSION = undefined;
- exports.VERSION = "2.6.1";
-});
-
-// node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js
-var require_utils5 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.createConstMap = undefined;
- function createConstMap(values2) {
- let res = {};
- const len = values2.length;
- for (let lp = 0;lp < len; lp++) {
- const val = values2[lp];
- if (val) {
- res[String(val).toUpperCase().replace(/[-.]/g, "_")] = val;
- }
- }
- return res;
- }
- exports.createConstMap = createConstMap;
-});
-
-// node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js
-var require_SemanticAttributes = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.SEMATTRS_NET_HOST_CARRIER_ICC = exports.SEMATTRS_NET_HOST_CARRIER_MNC = exports.SEMATTRS_NET_HOST_CARRIER_MCC = exports.SEMATTRS_NET_HOST_CARRIER_NAME = exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = exports.SEMATTRS_NET_HOST_NAME = exports.SEMATTRS_NET_HOST_PORT = exports.SEMATTRS_NET_HOST_IP = exports.SEMATTRS_NET_PEER_NAME = exports.SEMATTRS_NET_PEER_PORT = exports.SEMATTRS_NET_PEER_IP = exports.SEMATTRS_NET_TRANSPORT = exports.SEMATTRS_FAAS_INVOKED_REGION = exports.SEMATTRS_FAAS_INVOKED_PROVIDER = exports.SEMATTRS_FAAS_INVOKED_NAME = exports.SEMATTRS_FAAS_COLDSTART = exports.SEMATTRS_FAAS_CRON = exports.SEMATTRS_FAAS_TIME = exports.SEMATTRS_FAAS_DOCUMENT_NAME = exports.SEMATTRS_FAAS_DOCUMENT_TIME = exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = exports.SEMATTRS_FAAS_EXECUTION = exports.SEMATTRS_FAAS_TRIGGER = exports.SEMATTRS_EXCEPTION_ESCAPED = exports.SEMATTRS_EXCEPTION_STACKTRACE = exports.SEMATTRS_EXCEPTION_MESSAGE = exports.SEMATTRS_EXCEPTION_TYPE = exports.SEMATTRS_DB_SQL_TABLE = exports.SEMATTRS_DB_MONGODB_COLLECTION = exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = exports.SEMATTRS_DB_HBASE_NAMESPACE = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = exports.SEMATTRS_DB_CASSANDRA_TABLE = exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = exports.SEMATTRS_DB_OPERATION = exports.SEMATTRS_DB_STATEMENT = exports.SEMATTRS_DB_NAME = exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = exports.SEMATTRS_DB_USER = exports.SEMATTRS_DB_CONNECTION_STRING = exports.SEMATTRS_DB_SYSTEM = exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = undefined;
- exports.SEMATTRS_MESSAGING_DESTINATION_KIND = exports.SEMATTRS_MESSAGING_DESTINATION = exports.SEMATTRS_MESSAGING_SYSTEM = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = exports.SEMATTRS_AWS_DYNAMODB_COUNT = exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_SELECT = exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = exports.SEMATTRS_AWS_DYNAMODB_LIMIT = exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = exports.SEMATTRS_HTTP_CLIENT_IP = exports.SEMATTRS_HTTP_ROUTE = exports.SEMATTRS_HTTP_SERVER_NAME = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = exports.SEMATTRS_HTTP_USER_AGENT = exports.SEMATTRS_HTTP_FLAVOR = exports.SEMATTRS_HTTP_STATUS_CODE = exports.SEMATTRS_HTTP_SCHEME = exports.SEMATTRS_HTTP_HOST = exports.SEMATTRS_HTTP_TARGET = exports.SEMATTRS_HTTP_URL = exports.SEMATTRS_HTTP_METHOD = exports.SEMATTRS_CODE_LINENO = exports.SEMATTRS_CODE_FILEPATH = exports.SEMATTRS_CODE_NAMESPACE = exports.SEMATTRS_CODE_FUNCTION = exports.SEMATTRS_THREAD_NAME = exports.SEMATTRS_THREAD_ID = exports.SEMATTRS_ENDUSER_SCOPE = exports.SEMATTRS_ENDUSER_ROLE = exports.SEMATTRS_ENDUSER_ID = exports.SEMATTRS_PEER_SERVICE = undefined;
- exports.DBSYSTEMVALUES_FILEMAKER = exports.DBSYSTEMVALUES_DERBY = exports.DBSYSTEMVALUES_FIREBIRD = exports.DBSYSTEMVALUES_ADABAS = exports.DBSYSTEMVALUES_CACHE = exports.DBSYSTEMVALUES_EDB = exports.DBSYSTEMVALUES_FIRSTSQL = exports.DBSYSTEMVALUES_INGRES = exports.DBSYSTEMVALUES_HANADB = exports.DBSYSTEMVALUES_MAXDB = exports.DBSYSTEMVALUES_PROGRESS = exports.DBSYSTEMVALUES_HSQLDB = exports.DBSYSTEMVALUES_CLOUDSCAPE = exports.DBSYSTEMVALUES_HIVE = exports.DBSYSTEMVALUES_REDSHIFT = exports.DBSYSTEMVALUES_POSTGRESQL = exports.DBSYSTEMVALUES_DB2 = exports.DBSYSTEMVALUES_ORACLE = exports.DBSYSTEMVALUES_MYSQL = exports.DBSYSTEMVALUES_MSSQL = exports.DBSYSTEMVALUES_OTHER_SQL = exports.SemanticAttributes = exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_ID = exports.SEMATTRS_MESSAGE_TYPE = exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = exports.SEMATTRS_RPC_JSONRPC_VERSION = exports.SEMATTRS_RPC_GRPC_STATUS_CODE = exports.SEMATTRS_RPC_METHOD = exports.SEMATTRS_RPC_SERVICE = exports.SEMATTRS_RPC_SYSTEM = exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = exports.SEMATTRS_MESSAGING_CONSUMER_ID = exports.SEMATTRS_MESSAGING_OPERATION = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = exports.SEMATTRS_MESSAGING_CONVERSATION_ID = exports.SEMATTRS_MESSAGING_MESSAGE_ID = exports.SEMATTRS_MESSAGING_URL = exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = exports.SEMATTRS_MESSAGING_PROTOCOL = exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = undefined;
- exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = exports.FaasDocumentOperationValues = exports.FAASDOCUMENTOPERATIONVALUES_DELETE = exports.FAASDOCUMENTOPERATIONVALUES_EDIT = exports.FAASDOCUMENTOPERATIONVALUES_INSERT = exports.FaasTriggerValues = exports.FAASTRIGGERVALUES_OTHER = exports.FAASTRIGGERVALUES_TIMER = exports.FAASTRIGGERVALUES_PUBSUB = exports.FAASTRIGGERVALUES_HTTP = exports.FAASTRIGGERVALUES_DATASOURCE = exports.DbCassandraConsistencyLevelValues = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = exports.DbSystemValues = exports.DBSYSTEMVALUES_COCKROACHDB = exports.DBSYSTEMVALUES_MEMCACHED = exports.DBSYSTEMVALUES_ELASTICSEARCH = exports.DBSYSTEMVALUES_GEODE = exports.DBSYSTEMVALUES_NEO4J = exports.DBSYSTEMVALUES_DYNAMODB = exports.DBSYSTEMVALUES_COSMOSDB = exports.DBSYSTEMVALUES_COUCHDB = exports.DBSYSTEMVALUES_COUCHBASE = exports.DBSYSTEMVALUES_REDIS = exports.DBSYSTEMVALUES_MONGODB = exports.DBSYSTEMVALUES_HBASE = exports.DBSYSTEMVALUES_CASSANDRA = exports.DBSYSTEMVALUES_COLDFUSION = exports.DBSYSTEMVALUES_H2 = exports.DBSYSTEMVALUES_VERTICA = exports.DBSYSTEMVALUES_TERADATA = exports.DBSYSTEMVALUES_SYBASE = exports.DBSYSTEMVALUES_SQLITE = exports.DBSYSTEMVALUES_POINTBASE = exports.DBSYSTEMVALUES_PERVASIVE = exports.DBSYSTEMVALUES_NETEZZA = exports.DBSYSTEMVALUES_MARIADB = exports.DBSYSTEMVALUES_INTERBASE = exports.DBSYSTEMVALUES_INSTANTDB = exports.DBSYSTEMVALUES_INFORMIX = undefined;
- exports.MESSAGINGOPERATIONVALUES_RECEIVE = exports.MessagingDestinationKindValues = exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = exports.HttpFlavorValues = exports.HTTPFLAVORVALUES_QUIC = exports.HTTPFLAVORVALUES_SPDY = exports.HTTPFLAVORVALUES_HTTP_2_0 = exports.HTTPFLAVORVALUES_HTTP_1_1 = exports.HTTPFLAVORVALUES_HTTP_1_0 = exports.NetHostConnectionSubtypeValues = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = exports.NetHostConnectionTypeValues = exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = exports.NETHOSTCONNECTIONTYPEVALUES_CELL = exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = exports.NetTransportValues = exports.NETTRANSPORTVALUES_OTHER = exports.NETTRANSPORTVALUES_INPROC = exports.NETTRANSPORTVALUES_PIPE = exports.NETTRANSPORTVALUES_UNIX = exports.NETTRANSPORTVALUES_IP = exports.NETTRANSPORTVALUES_IP_UDP = exports.NETTRANSPORTVALUES_IP_TCP = exports.FaasInvokedProviderValues = exports.FAASINVOKEDPROVIDERVALUES_GCP = exports.FAASINVOKEDPROVIDERVALUES_AZURE = exports.FAASINVOKEDPROVIDERVALUES_AWS = undefined;
- exports.MessageTypeValues = exports.MESSAGETYPEVALUES_RECEIVED = exports.MESSAGETYPEVALUES_SENT = exports.RpcGrpcStatusCodeValues = exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = exports.RPCGRPCSTATUSCODEVALUES_ABORTED = exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = exports.RPCGRPCSTATUSCODEVALUES_OK = exports.MessagingOperationValues = exports.MESSAGINGOPERATIONVALUES_PROCESS = undefined;
- var utils_1 = require_utils5();
- var TMP_AWS_LAMBDA_INVOKED_ARN = "aws.lambda.invoked_arn";
- var TMP_DB_SYSTEM = "db.system";
- var TMP_DB_CONNECTION_STRING = "db.connection_string";
- var TMP_DB_USER = "db.user";
- var TMP_DB_JDBC_DRIVER_CLASSNAME = "db.jdbc.driver_classname";
- var TMP_DB_NAME = "db.name";
- var TMP_DB_STATEMENT = "db.statement";
- var TMP_DB_OPERATION = "db.operation";
- var TMP_DB_MSSQL_INSTANCE_NAME = "db.mssql.instance_name";
- var TMP_DB_CASSANDRA_KEYSPACE = "db.cassandra.keyspace";
- var TMP_DB_CASSANDRA_PAGE_SIZE = "db.cassandra.page_size";
- var TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = "db.cassandra.consistency_level";
- var TMP_DB_CASSANDRA_TABLE = "db.cassandra.table";
- var TMP_DB_CASSANDRA_IDEMPOTENCE = "db.cassandra.idempotence";
- var TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = "db.cassandra.speculative_execution_count";
- var TMP_DB_CASSANDRA_COORDINATOR_ID = "db.cassandra.coordinator.id";
- var TMP_DB_CASSANDRA_COORDINATOR_DC = "db.cassandra.coordinator.dc";
- var TMP_DB_HBASE_NAMESPACE = "db.hbase.namespace";
- var TMP_DB_REDIS_DATABASE_INDEX = "db.redis.database_index";
- var TMP_DB_MONGODB_COLLECTION = "db.mongodb.collection";
- var TMP_DB_SQL_TABLE = "db.sql.table";
- var TMP_EXCEPTION_TYPE = "exception.type";
- var TMP_EXCEPTION_MESSAGE = "exception.message";
- var TMP_EXCEPTION_STACKTRACE = "exception.stacktrace";
- var TMP_EXCEPTION_ESCAPED = "exception.escaped";
- var TMP_FAAS_TRIGGER = "faas.trigger";
- var TMP_FAAS_EXECUTION = "faas.execution";
- var TMP_FAAS_DOCUMENT_COLLECTION = "faas.document.collection";
- var TMP_FAAS_DOCUMENT_OPERATION = "faas.document.operation";
- var TMP_FAAS_DOCUMENT_TIME = "faas.document.time";
- var TMP_FAAS_DOCUMENT_NAME = "faas.document.name";
- var TMP_FAAS_TIME = "faas.time";
- var TMP_FAAS_CRON = "faas.cron";
- var TMP_FAAS_COLDSTART = "faas.coldstart";
- var TMP_FAAS_INVOKED_NAME = "faas.invoked_name";
- var TMP_FAAS_INVOKED_PROVIDER = "faas.invoked_provider";
- var TMP_FAAS_INVOKED_REGION = "faas.invoked_region";
- var TMP_NET_TRANSPORT = "net.transport";
- var TMP_NET_PEER_IP = "net.peer.ip";
- var TMP_NET_PEER_PORT = "net.peer.port";
- var TMP_NET_PEER_NAME = "net.peer.name";
- var TMP_NET_HOST_IP = "net.host.ip";
- var TMP_NET_HOST_PORT = "net.host.port";
- var TMP_NET_HOST_NAME = "net.host.name";
- var TMP_NET_HOST_CONNECTION_TYPE = "net.host.connection.type";
- var TMP_NET_HOST_CONNECTION_SUBTYPE = "net.host.connection.subtype";
- var TMP_NET_HOST_CARRIER_NAME = "net.host.carrier.name";
- var TMP_NET_HOST_CARRIER_MCC = "net.host.carrier.mcc";
- var TMP_NET_HOST_CARRIER_MNC = "net.host.carrier.mnc";
- var TMP_NET_HOST_CARRIER_ICC = "net.host.carrier.icc";
- var TMP_PEER_SERVICE = "peer.service";
- var TMP_ENDUSER_ID = "enduser.id";
- var TMP_ENDUSER_ROLE = "enduser.role";
- var TMP_ENDUSER_SCOPE = "enduser.scope";
- var TMP_THREAD_ID = "thread.id";
- var TMP_THREAD_NAME = "thread.name";
- var TMP_CODE_FUNCTION = "code.function";
- var TMP_CODE_NAMESPACE = "code.namespace";
- var TMP_CODE_FILEPATH = "code.filepath";
- var TMP_CODE_LINENO = "code.lineno";
- var TMP_HTTP_METHOD = "http.method";
- var TMP_HTTP_URL = "http.url";
- var TMP_HTTP_TARGET = "http.target";
- var TMP_HTTP_HOST = "http.host";
- var TMP_HTTP_SCHEME = "http.scheme";
- var TMP_HTTP_STATUS_CODE = "http.status_code";
- var TMP_HTTP_FLAVOR = "http.flavor";
- var TMP_HTTP_USER_AGENT = "http.user_agent";
- var TMP_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length";
- var TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed";
- var TMP_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length";
- var TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed";
- var TMP_HTTP_SERVER_NAME = "http.server_name";
- var TMP_HTTP_ROUTE = "http.route";
- var TMP_HTTP_CLIENT_IP = "http.client_ip";
- var TMP_AWS_DYNAMODB_TABLE_NAMES = "aws.dynamodb.table_names";
- var TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = "aws.dynamodb.consumed_capacity";
- var TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = "aws.dynamodb.item_collection_metrics";
- var TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = "aws.dynamodb.provisioned_read_capacity";
- var TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = "aws.dynamodb.provisioned_write_capacity";
- var TMP_AWS_DYNAMODB_CONSISTENT_READ = "aws.dynamodb.consistent_read";
- var TMP_AWS_DYNAMODB_PROJECTION = "aws.dynamodb.projection";
- var TMP_AWS_DYNAMODB_LIMIT = "aws.dynamodb.limit";
- var TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = "aws.dynamodb.attributes_to_get";
- var TMP_AWS_DYNAMODB_INDEX_NAME = "aws.dynamodb.index_name";
- var TMP_AWS_DYNAMODB_SELECT = "aws.dynamodb.select";
- var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = "aws.dynamodb.global_secondary_indexes";
- var TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = "aws.dynamodb.local_secondary_indexes";
- var TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = "aws.dynamodb.exclusive_start_table";
- var TMP_AWS_DYNAMODB_TABLE_COUNT = "aws.dynamodb.table_count";
- var TMP_AWS_DYNAMODB_SCAN_FORWARD = "aws.dynamodb.scan_forward";
- var TMP_AWS_DYNAMODB_SEGMENT = "aws.dynamodb.segment";
- var TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = "aws.dynamodb.total_segments";
- var TMP_AWS_DYNAMODB_COUNT = "aws.dynamodb.count";
- var TMP_AWS_DYNAMODB_SCANNED_COUNT = "aws.dynamodb.scanned_count";
- var TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = "aws.dynamodb.attribute_definitions";
- var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = "aws.dynamodb.global_secondary_index_updates";
- var TMP_MESSAGING_SYSTEM = "messaging.system";
- var TMP_MESSAGING_DESTINATION = "messaging.destination";
- var TMP_MESSAGING_DESTINATION_KIND = "messaging.destination_kind";
- var TMP_MESSAGING_TEMP_DESTINATION = "messaging.temp_destination";
- var TMP_MESSAGING_PROTOCOL = "messaging.protocol";
- var TMP_MESSAGING_PROTOCOL_VERSION = "messaging.protocol_version";
- var TMP_MESSAGING_URL = "messaging.url";
- var TMP_MESSAGING_MESSAGE_ID = "messaging.message_id";
- var TMP_MESSAGING_CONVERSATION_ID = "messaging.conversation_id";
- var TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = "messaging.message_payload_size_bytes";
- var TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = "messaging.message_payload_compressed_size_bytes";
- var TMP_MESSAGING_OPERATION = "messaging.operation";
- var TMP_MESSAGING_CONSUMER_ID = "messaging.consumer_id";
- var TMP_MESSAGING_RABBITMQ_ROUTING_KEY = "messaging.rabbitmq.routing_key";
- var TMP_MESSAGING_KAFKA_MESSAGE_KEY = "messaging.kafka.message_key";
- var TMP_MESSAGING_KAFKA_CONSUMER_GROUP = "messaging.kafka.consumer_group";
- var TMP_MESSAGING_KAFKA_CLIENT_ID = "messaging.kafka.client_id";
- var TMP_MESSAGING_KAFKA_PARTITION = "messaging.kafka.partition";
- var TMP_MESSAGING_KAFKA_TOMBSTONE = "messaging.kafka.tombstone";
- var TMP_RPC_SYSTEM = "rpc.system";
- var TMP_RPC_SERVICE = "rpc.service";
- var TMP_RPC_METHOD = "rpc.method";
- var TMP_RPC_GRPC_STATUS_CODE = "rpc.grpc.status_code";
- var TMP_RPC_JSONRPC_VERSION = "rpc.jsonrpc.version";
- var TMP_RPC_JSONRPC_REQUEST_ID = "rpc.jsonrpc.request_id";
- var TMP_RPC_JSONRPC_ERROR_CODE = "rpc.jsonrpc.error_code";
- var TMP_RPC_JSONRPC_ERROR_MESSAGE = "rpc.jsonrpc.error_message";
- var TMP_MESSAGE_TYPE = "message.type";
- var TMP_MESSAGE_ID = "message.id";
- var TMP_MESSAGE_COMPRESSED_SIZE = "message.compressed_size";
- var TMP_MESSAGE_UNCOMPRESSED_SIZE = "message.uncompressed_size";
- exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN;
- exports.SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM;
- exports.SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING;
- exports.SEMATTRS_DB_USER = TMP_DB_USER;
- exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME;
- exports.SEMATTRS_DB_NAME = TMP_DB_NAME;
- exports.SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT;
- exports.SEMATTRS_DB_OPERATION = TMP_DB_OPERATION;
- exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME;
- exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE;
- exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE;
- exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL;
- exports.SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE;
- exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE;
- exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT;
- exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID;
- exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC;
- exports.SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE;
- exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX;
- exports.SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION;
- exports.SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE;
- exports.SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE;
- exports.SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE;
- exports.SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE;
- exports.SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED;
- exports.SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER;
- exports.SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION;
- exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION;
- exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION;
- exports.SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME;
- exports.SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME;
- exports.SEMATTRS_FAAS_TIME = TMP_FAAS_TIME;
- exports.SEMATTRS_FAAS_CRON = TMP_FAAS_CRON;
- exports.SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART;
- exports.SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME;
- exports.SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER;
- exports.SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION;
- exports.SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT;
- exports.SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP;
- exports.SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT;
- exports.SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME;
- exports.SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP;
- exports.SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT;
- exports.SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME;
- exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE;
- exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE;
- exports.SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME;
- exports.SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC;
- exports.SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC;
- exports.SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC;
- exports.SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE;
- exports.SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID;
- exports.SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE;
- exports.SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE;
- exports.SEMATTRS_THREAD_ID = TMP_THREAD_ID;
- exports.SEMATTRS_THREAD_NAME = TMP_THREAD_NAME;
- exports.SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION;
- exports.SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE;
- exports.SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH;
- exports.SEMATTRS_CODE_LINENO = TMP_CODE_LINENO;
- exports.SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD;
- exports.SEMATTRS_HTTP_URL = TMP_HTTP_URL;
- exports.SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET;
- exports.SEMATTRS_HTTP_HOST = TMP_HTTP_HOST;
- exports.SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME;
- exports.SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE;
- exports.SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR;
- exports.SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT;
- exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH;
- exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED;
- exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH;
- exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED;
- exports.SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME;
- exports.SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE;
- exports.SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP;
- exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES;
- exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY;
- exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS;
- exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY;
- exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY;
- exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ;
- exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION;
- exports.SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT;
- exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET;
- exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME;
- exports.SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT;
- exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES;
- exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES;
- exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE;
- exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT;
- exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD;
- exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT;
- exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS;
- exports.SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT;
- exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT;
- exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS;
- exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES;
- exports.SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM;
- exports.SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION;
- exports.SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND;
- exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION;
- exports.SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL;
- exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION;
- exports.SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL;
- exports.SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID;
- exports.SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID;
- exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES;
- exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES;
- exports.SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION;
- exports.SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID;
- exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY;
- exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY;
- exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP;
- exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID;
- exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION;
- exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE;
- exports.SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM;
- exports.SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE;
- exports.SEMATTRS_RPC_METHOD = TMP_RPC_METHOD;
- exports.SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE;
- exports.SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION;
- exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID;
- exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE;
- exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE;
- exports.SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE;
- exports.SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID;
- exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE;
- exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE;
- exports.SemanticAttributes = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_AWS_LAMBDA_INVOKED_ARN,
- TMP_DB_SYSTEM,
- TMP_DB_CONNECTION_STRING,
- TMP_DB_USER,
- TMP_DB_JDBC_DRIVER_CLASSNAME,
- TMP_DB_NAME,
- TMP_DB_STATEMENT,
- TMP_DB_OPERATION,
- TMP_DB_MSSQL_INSTANCE_NAME,
- TMP_DB_CASSANDRA_KEYSPACE,
- TMP_DB_CASSANDRA_PAGE_SIZE,
- TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,
- TMP_DB_CASSANDRA_TABLE,
- TMP_DB_CASSANDRA_IDEMPOTENCE,
- TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,
- TMP_DB_CASSANDRA_COORDINATOR_ID,
- TMP_DB_CASSANDRA_COORDINATOR_DC,
- TMP_DB_HBASE_NAMESPACE,
- TMP_DB_REDIS_DATABASE_INDEX,
- TMP_DB_MONGODB_COLLECTION,
- TMP_DB_SQL_TABLE,
- TMP_EXCEPTION_TYPE,
- TMP_EXCEPTION_MESSAGE,
- TMP_EXCEPTION_STACKTRACE,
- TMP_EXCEPTION_ESCAPED,
- TMP_FAAS_TRIGGER,
- TMP_FAAS_EXECUTION,
- TMP_FAAS_DOCUMENT_COLLECTION,
- TMP_FAAS_DOCUMENT_OPERATION,
- TMP_FAAS_DOCUMENT_TIME,
- TMP_FAAS_DOCUMENT_NAME,
- TMP_FAAS_TIME,
- TMP_FAAS_CRON,
- TMP_FAAS_COLDSTART,
- TMP_FAAS_INVOKED_NAME,
- TMP_FAAS_INVOKED_PROVIDER,
- TMP_FAAS_INVOKED_REGION,
- TMP_NET_TRANSPORT,
- TMP_NET_PEER_IP,
- TMP_NET_PEER_PORT,
- TMP_NET_PEER_NAME,
- TMP_NET_HOST_IP,
- TMP_NET_HOST_PORT,
- TMP_NET_HOST_NAME,
- TMP_NET_HOST_CONNECTION_TYPE,
- TMP_NET_HOST_CONNECTION_SUBTYPE,
- TMP_NET_HOST_CARRIER_NAME,
- TMP_NET_HOST_CARRIER_MCC,
- TMP_NET_HOST_CARRIER_MNC,
- TMP_NET_HOST_CARRIER_ICC,
- TMP_PEER_SERVICE,
- TMP_ENDUSER_ID,
- TMP_ENDUSER_ROLE,
- TMP_ENDUSER_SCOPE,
- TMP_THREAD_ID,
- TMP_THREAD_NAME,
- TMP_CODE_FUNCTION,
- TMP_CODE_NAMESPACE,
- TMP_CODE_FILEPATH,
- TMP_CODE_LINENO,
- TMP_HTTP_METHOD,
- TMP_HTTP_URL,
- TMP_HTTP_TARGET,
- TMP_HTTP_HOST,
- TMP_HTTP_SCHEME,
- TMP_HTTP_STATUS_CODE,
- TMP_HTTP_FLAVOR,
- TMP_HTTP_USER_AGENT,
- TMP_HTTP_REQUEST_CONTENT_LENGTH,
- TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,
- TMP_HTTP_RESPONSE_CONTENT_LENGTH,
- TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,
- TMP_HTTP_SERVER_NAME,
- TMP_HTTP_ROUTE,
- TMP_HTTP_CLIENT_IP,
- TMP_AWS_DYNAMODB_TABLE_NAMES,
- TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,
- TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,
- TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,
- TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,
- TMP_AWS_DYNAMODB_CONSISTENT_READ,
- TMP_AWS_DYNAMODB_PROJECTION,
- TMP_AWS_DYNAMODB_LIMIT,
- TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,
- TMP_AWS_DYNAMODB_INDEX_NAME,
- TMP_AWS_DYNAMODB_SELECT,
- TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,
- TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,
- TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,
- TMP_AWS_DYNAMODB_TABLE_COUNT,
- TMP_AWS_DYNAMODB_SCAN_FORWARD,
- TMP_AWS_DYNAMODB_SEGMENT,
- TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,
- TMP_AWS_DYNAMODB_COUNT,
- TMP_AWS_DYNAMODB_SCANNED_COUNT,
- TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,
- TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,
- TMP_MESSAGING_SYSTEM,
- TMP_MESSAGING_DESTINATION,
- TMP_MESSAGING_DESTINATION_KIND,
- TMP_MESSAGING_TEMP_DESTINATION,
- TMP_MESSAGING_PROTOCOL,
- TMP_MESSAGING_PROTOCOL_VERSION,
- TMP_MESSAGING_URL,
- TMP_MESSAGING_MESSAGE_ID,
- TMP_MESSAGING_CONVERSATION_ID,
- TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,
- TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,
- TMP_MESSAGING_OPERATION,
- TMP_MESSAGING_CONSUMER_ID,
- TMP_MESSAGING_RABBITMQ_ROUTING_KEY,
- TMP_MESSAGING_KAFKA_MESSAGE_KEY,
- TMP_MESSAGING_KAFKA_CONSUMER_GROUP,
- TMP_MESSAGING_KAFKA_CLIENT_ID,
- TMP_MESSAGING_KAFKA_PARTITION,
- TMP_MESSAGING_KAFKA_TOMBSTONE,
- TMP_RPC_SYSTEM,
- TMP_RPC_SERVICE,
- TMP_RPC_METHOD,
- TMP_RPC_GRPC_STATUS_CODE,
- TMP_RPC_JSONRPC_VERSION,
- TMP_RPC_JSONRPC_REQUEST_ID,
- TMP_RPC_JSONRPC_ERROR_CODE,
- TMP_RPC_JSONRPC_ERROR_MESSAGE,
- TMP_MESSAGE_TYPE,
- TMP_MESSAGE_ID,
- TMP_MESSAGE_COMPRESSED_SIZE,
- TMP_MESSAGE_UNCOMPRESSED_SIZE
- ]);
- var TMP_DBSYSTEMVALUES_OTHER_SQL = "other_sql";
- var TMP_DBSYSTEMVALUES_MSSQL = "mssql";
- var TMP_DBSYSTEMVALUES_MYSQL = "mysql";
- var TMP_DBSYSTEMVALUES_ORACLE = "oracle";
- var TMP_DBSYSTEMVALUES_DB2 = "db2";
- var TMP_DBSYSTEMVALUES_POSTGRESQL = "postgresql";
- var TMP_DBSYSTEMVALUES_REDSHIFT = "redshift";
- var TMP_DBSYSTEMVALUES_HIVE = "hive";
- var TMP_DBSYSTEMVALUES_CLOUDSCAPE = "cloudscape";
- var TMP_DBSYSTEMVALUES_HSQLDB = "hsqldb";
- var TMP_DBSYSTEMVALUES_PROGRESS = "progress";
- var TMP_DBSYSTEMVALUES_MAXDB = "maxdb";
- var TMP_DBSYSTEMVALUES_HANADB = "hanadb";
- var TMP_DBSYSTEMVALUES_INGRES = "ingres";
- var TMP_DBSYSTEMVALUES_FIRSTSQL = "firstsql";
- var TMP_DBSYSTEMVALUES_EDB = "edb";
- var TMP_DBSYSTEMVALUES_CACHE = "cache";
- var TMP_DBSYSTEMVALUES_ADABAS = "adabas";
- var TMP_DBSYSTEMVALUES_FIREBIRD = "firebird";
- var TMP_DBSYSTEMVALUES_DERBY = "derby";
- var TMP_DBSYSTEMVALUES_FILEMAKER = "filemaker";
- var TMP_DBSYSTEMVALUES_INFORMIX = "informix";
- var TMP_DBSYSTEMVALUES_INSTANTDB = "instantdb";
- var TMP_DBSYSTEMVALUES_INTERBASE = "interbase";
- var TMP_DBSYSTEMVALUES_MARIADB = "mariadb";
- var TMP_DBSYSTEMVALUES_NETEZZA = "netezza";
- var TMP_DBSYSTEMVALUES_PERVASIVE = "pervasive";
- var TMP_DBSYSTEMVALUES_POINTBASE = "pointbase";
- var TMP_DBSYSTEMVALUES_SQLITE = "sqlite";
- var TMP_DBSYSTEMVALUES_SYBASE = "sybase";
- var TMP_DBSYSTEMVALUES_TERADATA = "teradata";
- var TMP_DBSYSTEMVALUES_VERTICA = "vertica";
- var TMP_DBSYSTEMVALUES_H2 = "h2";
- var TMP_DBSYSTEMVALUES_COLDFUSION = "coldfusion";
- var TMP_DBSYSTEMVALUES_CASSANDRA = "cassandra";
- var TMP_DBSYSTEMVALUES_HBASE = "hbase";
- var TMP_DBSYSTEMVALUES_MONGODB = "mongodb";
- var TMP_DBSYSTEMVALUES_REDIS = "redis";
- var TMP_DBSYSTEMVALUES_COUCHBASE = "couchbase";
- var TMP_DBSYSTEMVALUES_COUCHDB = "couchdb";
- var TMP_DBSYSTEMVALUES_COSMOSDB = "cosmosdb";
- var TMP_DBSYSTEMVALUES_DYNAMODB = "dynamodb";
- var TMP_DBSYSTEMVALUES_NEO4J = "neo4j";
- var TMP_DBSYSTEMVALUES_GEODE = "geode";
- var TMP_DBSYSTEMVALUES_ELASTICSEARCH = "elasticsearch";
- var TMP_DBSYSTEMVALUES_MEMCACHED = "memcached";
- var TMP_DBSYSTEMVALUES_COCKROACHDB = "cockroachdb";
- exports.DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL;
- exports.DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL;
- exports.DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL;
- exports.DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE;
- exports.DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2;
- exports.DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL;
- exports.DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT;
- exports.DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE;
- exports.DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE;
- exports.DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB;
- exports.DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS;
- exports.DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB;
- exports.DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB;
- exports.DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES;
- exports.DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL;
- exports.DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB;
- exports.DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE;
- exports.DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS;
- exports.DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD;
- exports.DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY;
- exports.DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER;
- exports.DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX;
- exports.DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB;
- exports.DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE;
- exports.DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB;
- exports.DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA;
- exports.DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE;
- exports.DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE;
- exports.DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE;
- exports.DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE;
- exports.DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA;
- exports.DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA;
- exports.DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2;
- exports.DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION;
- exports.DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA;
- exports.DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE;
- exports.DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB;
- exports.DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS;
- exports.DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE;
- exports.DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB;
- exports.DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB;
- exports.DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB;
- exports.DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J;
- exports.DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE;
- exports.DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH;
- exports.DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED;
- exports.DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB;
- exports.DbSystemValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_DBSYSTEMVALUES_OTHER_SQL,
- TMP_DBSYSTEMVALUES_MSSQL,
- TMP_DBSYSTEMVALUES_MYSQL,
- TMP_DBSYSTEMVALUES_ORACLE,
- TMP_DBSYSTEMVALUES_DB2,
- TMP_DBSYSTEMVALUES_POSTGRESQL,
- TMP_DBSYSTEMVALUES_REDSHIFT,
- TMP_DBSYSTEMVALUES_HIVE,
- TMP_DBSYSTEMVALUES_CLOUDSCAPE,
- TMP_DBSYSTEMVALUES_HSQLDB,
- TMP_DBSYSTEMVALUES_PROGRESS,
- TMP_DBSYSTEMVALUES_MAXDB,
- TMP_DBSYSTEMVALUES_HANADB,
- TMP_DBSYSTEMVALUES_INGRES,
- TMP_DBSYSTEMVALUES_FIRSTSQL,
- TMP_DBSYSTEMVALUES_EDB,
- TMP_DBSYSTEMVALUES_CACHE,
- TMP_DBSYSTEMVALUES_ADABAS,
- TMP_DBSYSTEMVALUES_FIREBIRD,
- TMP_DBSYSTEMVALUES_DERBY,
- TMP_DBSYSTEMVALUES_FILEMAKER,
- TMP_DBSYSTEMVALUES_INFORMIX,
- TMP_DBSYSTEMVALUES_INSTANTDB,
- TMP_DBSYSTEMVALUES_INTERBASE,
- TMP_DBSYSTEMVALUES_MARIADB,
- TMP_DBSYSTEMVALUES_NETEZZA,
- TMP_DBSYSTEMVALUES_PERVASIVE,
- TMP_DBSYSTEMVALUES_POINTBASE,
- TMP_DBSYSTEMVALUES_SQLITE,
- TMP_DBSYSTEMVALUES_SYBASE,
- TMP_DBSYSTEMVALUES_TERADATA,
- TMP_DBSYSTEMVALUES_VERTICA,
- TMP_DBSYSTEMVALUES_H2,
- TMP_DBSYSTEMVALUES_COLDFUSION,
- TMP_DBSYSTEMVALUES_CASSANDRA,
- TMP_DBSYSTEMVALUES_HBASE,
- TMP_DBSYSTEMVALUES_MONGODB,
- TMP_DBSYSTEMVALUES_REDIS,
- TMP_DBSYSTEMVALUES_COUCHBASE,
- TMP_DBSYSTEMVALUES_COUCHDB,
- TMP_DBSYSTEMVALUES_COSMOSDB,
- TMP_DBSYSTEMVALUES_DYNAMODB,
- TMP_DBSYSTEMVALUES_NEO4J,
- TMP_DBSYSTEMVALUES_GEODE,
- TMP_DBSYSTEMVALUES_ELASTICSEARCH,
- TMP_DBSYSTEMVALUES_MEMCACHED,
- TMP_DBSYSTEMVALUES_COCKROACHDB
- ]);
- var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = "all";
- var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = "each_quorum";
- var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = "quorum";
- var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = "local_quorum";
- var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = "one";
- var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = "two";
- var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = "three";
- var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = "local_one";
- var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = "any";
- var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = "serial";
- var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = "local_serial";
- exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL;
- exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM;
- exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM;
- exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM;
- exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE;
- exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO;
- exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE;
- exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE;
- exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY;
- exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL;
- exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL;
- exports.DbCassandraConsistencyLevelValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,
- TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,
- TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,
- TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,
- TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,
- TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,
- TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,
- TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,
- TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,
- TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,
- TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL
- ]);
- var TMP_FAASTRIGGERVALUES_DATASOURCE = "datasource";
- var TMP_FAASTRIGGERVALUES_HTTP = "http";
- var TMP_FAASTRIGGERVALUES_PUBSUB = "pubsub";
- var TMP_FAASTRIGGERVALUES_TIMER = "timer";
- var TMP_FAASTRIGGERVALUES_OTHER = "other";
- exports.FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE;
- exports.FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP;
- exports.FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB;
- exports.FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER;
- exports.FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER;
- exports.FaasTriggerValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_FAASTRIGGERVALUES_DATASOURCE,
- TMP_FAASTRIGGERVALUES_HTTP,
- TMP_FAASTRIGGERVALUES_PUBSUB,
- TMP_FAASTRIGGERVALUES_TIMER,
- TMP_FAASTRIGGERVALUES_OTHER
- ]);
- var TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = "insert";
- var TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = "edit";
- var TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = "delete";
- exports.FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT;
- exports.FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT;
- exports.FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE;
- exports.FaasDocumentOperationValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,
- TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,
- TMP_FAASDOCUMENTOPERATIONVALUES_DELETE
- ]);
- var TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud";
- var TMP_FAASINVOKEDPROVIDERVALUES_AWS = "aws";
- var TMP_FAASINVOKEDPROVIDERVALUES_AZURE = "azure";
- var TMP_FAASINVOKEDPROVIDERVALUES_GCP = "gcp";
- exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD;
- exports.FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS;
- exports.FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE;
- exports.FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP;
- exports.FaasInvokedProviderValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,
- TMP_FAASINVOKEDPROVIDERVALUES_AWS,
- TMP_FAASINVOKEDPROVIDERVALUES_AZURE,
- TMP_FAASINVOKEDPROVIDERVALUES_GCP
- ]);
- var TMP_NETTRANSPORTVALUES_IP_TCP = "ip_tcp";
- var TMP_NETTRANSPORTVALUES_IP_UDP = "ip_udp";
- var TMP_NETTRANSPORTVALUES_IP = "ip";
- var TMP_NETTRANSPORTVALUES_UNIX = "unix";
- var TMP_NETTRANSPORTVALUES_PIPE = "pipe";
- var TMP_NETTRANSPORTVALUES_INPROC = "inproc";
- var TMP_NETTRANSPORTVALUES_OTHER = "other";
- exports.NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP;
- exports.NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP;
- exports.NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP;
- exports.NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX;
- exports.NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE;
- exports.NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC;
- exports.NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER;
- exports.NetTransportValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_NETTRANSPORTVALUES_IP_TCP,
- TMP_NETTRANSPORTVALUES_IP_UDP,
- TMP_NETTRANSPORTVALUES_IP,
- TMP_NETTRANSPORTVALUES_UNIX,
- TMP_NETTRANSPORTVALUES_PIPE,
- TMP_NETTRANSPORTVALUES_INPROC,
- TMP_NETTRANSPORTVALUES_OTHER
- ]);
- var TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = "wifi";
- var TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = "wired";
- var TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = "cell";
- var TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = "unavailable";
- var TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = "unknown";
- exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI;
- exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED;
- exports.NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL;
- exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE;
- exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN;
- exports.NetHostConnectionTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,
- TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,
- TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,
- TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,
- TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN
- ]);
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = "gprs";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = "edge";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = "umts";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = "cdma";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = "evdo_0";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = "evdo_a";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = "cdma2000_1xrtt";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = "hsdpa";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = "hsupa";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = "hspa";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = "iden";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = "evdo_b";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = "lte";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = "ehrpd";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = "hspap";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = "gsm";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = "td_scdma";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = "iwlan";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = "nr";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = "nrnsa";
- var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = "lte_ca";
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA;
- exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA;
- exports.NetHostConnectionSubtypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,
- TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA
- ]);
- var TMP_HTTPFLAVORVALUES_HTTP_1_0 = "1.0";
- var TMP_HTTPFLAVORVALUES_HTTP_1_1 = "1.1";
- var TMP_HTTPFLAVORVALUES_HTTP_2_0 = "2.0";
- var TMP_HTTPFLAVORVALUES_SPDY = "SPDY";
- var TMP_HTTPFLAVORVALUES_QUIC = "QUIC";
- exports.HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0;
- exports.HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1;
- exports.HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0;
- exports.HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY;
- exports.HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC;
- exports.HttpFlavorValues = {
- HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0,
- HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1,
- HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0,
- SPDY: TMP_HTTPFLAVORVALUES_SPDY,
- QUIC: TMP_HTTPFLAVORVALUES_QUIC
- };
- var TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = "queue";
- var TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = "topic";
- exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE;
- exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC;
- exports.MessagingDestinationKindValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,
- TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC
- ]);
- var TMP_MESSAGINGOPERATIONVALUES_RECEIVE = "receive";
- var TMP_MESSAGINGOPERATIONVALUES_PROCESS = "process";
- exports.MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE;
- exports.MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS;
- exports.MessagingOperationValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_MESSAGINGOPERATIONVALUES_RECEIVE,
- TMP_MESSAGINGOPERATIONVALUES_PROCESS
- ]);
- var TMP_RPCGRPCSTATUSCODEVALUES_OK = 0;
- var TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1;
- var TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2;
- var TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3;
- var TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4;
- var TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5;
- var TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6;
- var TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7;
- var TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8;
- var TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9;
- var TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10;
- var TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11;
- var TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12;
- var TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13;
- var TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14;
- var TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15;
- var TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16;
- exports.RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK;
- exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED;
- exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN;
- exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT;
- exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED;
- exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND;
- exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS;
- exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED;
- exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED;
- exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION;
- exports.RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED;
- exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE;
- exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED;
- exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL;
- exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE;
- exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS;
- exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED;
- exports.RpcGrpcStatusCodeValues = {
- OK: TMP_RPCGRPCSTATUSCODEVALUES_OK,
- CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,
- UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,
- INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,
- DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,
- NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,
- ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,
- PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,
- RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,
- FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,
- ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,
- OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,
- UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,
- INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,
- UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,
- DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,
- UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED
- };
- var TMP_MESSAGETYPEVALUES_SENT = "SENT";
- var TMP_MESSAGETYPEVALUES_RECEIVED = "RECEIVED";
- exports.MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT;
- exports.MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED;
- exports.MessageTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_MESSAGETYPEVALUES_SENT,
- TMP_MESSAGETYPEVALUES_RECEIVED
- ]);
-});
-
-// node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js
-var require_trace2 = __commonJS((exports) => {
- var __createBinding2 = exports && exports.__createBinding || (Object.create ? function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- var desc = Object.getOwnPropertyDescriptor(m4, k4);
- if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() {
- return m4[k4];
- } };
- }
- Object.defineProperty(o5, k22, desc);
- } : function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- });
- var __exportStar2 = exports && exports.__exportStar || function(m4, exports2) {
- for (var p4 in m4)
- if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
- __createBinding2(exports2, m4, p4);
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- __exportStar2(require_SemanticAttributes(), exports);
-});
-
-// node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js
-var require_SemanticResourceAttributes = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.SEMRESATTRS_K8S_STATEFULSET_NAME = exports.SEMRESATTRS_K8S_STATEFULSET_UID = exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = exports.SEMRESATTRS_K8S_REPLICASET_NAME = exports.SEMRESATTRS_K8S_REPLICASET_UID = exports.SEMRESATTRS_K8S_CONTAINER_NAME = exports.SEMRESATTRS_K8S_POD_NAME = exports.SEMRESATTRS_K8S_POD_UID = exports.SEMRESATTRS_K8S_NAMESPACE_NAME = exports.SEMRESATTRS_K8S_NODE_UID = exports.SEMRESATTRS_K8S_NODE_NAME = exports.SEMRESATTRS_K8S_CLUSTER_NAME = exports.SEMRESATTRS_HOST_IMAGE_VERSION = exports.SEMRESATTRS_HOST_IMAGE_ID = exports.SEMRESATTRS_HOST_IMAGE_NAME = exports.SEMRESATTRS_HOST_ARCH = exports.SEMRESATTRS_HOST_TYPE = exports.SEMRESATTRS_HOST_NAME = exports.SEMRESATTRS_HOST_ID = exports.SEMRESATTRS_FAAS_MAX_MEMORY = exports.SEMRESATTRS_FAAS_INSTANCE = exports.SEMRESATTRS_FAAS_VERSION = exports.SEMRESATTRS_FAAS_ID = exports.SEMRESATTRS_FAAS_NAME = exports.SEMRESATTRS_DEVICE_MODEL_NAME = exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = exports.SEMRESATTRS_DEVICE_ID = exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = exports.SEMRESATTRS_CONTAINER_RUNTIME = exports.SEMRESATTRS_CONTAINER_ID = exports.SEMRESATTRS_CONTAINER_NAME = exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = exports.SEMRESATTRS_AWS_ECS_TASK_ARN = exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = exports.SEMRESATTRS_CLOUD_PLATFORM = exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = exports.SEMRESATTRS_CLOUD_REGION = exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = exports.SEMRESATTRS_CLOUD_PROVIDER = undefined;
- exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = exports.CLOUDPLATFORMVALUES_AZURE_AKS = exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = exports.CLOUDPLATFORMVALUES_AZURE_VM = exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = exports.CLOUDPLATFORMVALUES_AWS_EKS = exports.CLOUDPLATFORMVALUES_AWS_ECS = exports.CLOUDPLATFORMVALUES_AWS_EC2 = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = exports.CloudProviderValues = exports.CLOUDPROVIDERVALUES_GCP = exports.CLOUDPROVIDERVALUES_AZURE = exports.CLOUDPROVIDERVALUES_AWS = exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = exports.SemanticResourceAttributes = exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = exports.SEMRESATTRS_WEBENGINE_VERSION = exports.SEMRESATTRS_WEBENGINE_NAME = exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = exports.SEMRESATTRS_TELEMETRY_SDK_NAME = exports.SEMRESATTRS_SERVICE_VERSION = exports.SEMRESATTRS_SERVICE_INSTANCE_ID = exports.SEMRESATTRS_SERVICE_NAMESPACE = exports.SEMRESATTRS_SERVICE_NAME = exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = exports.SEMRESATTRS_PROCESS_OWNER = exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = exports.SEMRESATTRS_PROCESS_COMMAND_LINE = exports.SEMRESATTRS_PROCESS_COMMAND = exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = exports.SEMRESATTRS_PROCESS_PID = exports.SEMRESATTRS_OS_VERSION = exports.SEMRESATTRS_OS_NAME = exports.SEMRESATTRS_OS_DESCRIPTION = exports.SEMRESATTRS_OS_TYPE = exports.SEMRESATTRS_K8S_CRONJOB_NAME = exports.SEMRESATTRS_K8S_CRONJOB_UID = exports.SEMRESATTRS_K8S_JOB_NAME = exports.SEMRESATTRS_K8S_JOB_UID = exports.SEMRESATTRS_K8S_DAEMONSET_NAME = exports.SEMRESATTRS_K8S_DAEMONSET_UID = undefined;
- exports.TelemetrySdkLanguageValues = exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = exports.TELEMETRYSDKLANGUAGEVALUES_PHP = exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = exports.TELEMETRYSDKLANGUAGEVALUES_GO = exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = exports.TELEMETRYSDKLANGUAGEVALUES_CPP = exports.OsTypeValues = exports.OSTYPEVALUES_Z_OS = exports.OSTYPEVALUES_SOLARIS = exports.OSTYPEVALUES_AIX = exports.OSTYPEVALUES_HPUX = exports.OSTYPEVALUES_DRAGONFLYBSD = exports.OSTYPEVALUES_OPENBSD = exports.OSTYPEVALUES_NETBSD = exports.OSTYPEVALUES_FREEBSD = exports.OSTYPEVALUES_DARWIN = exports.OSTYPEVALUES_LINUX = exports.OSTYPEVALUES_WINDOWS = exports.HostArchValues = exports.HOSTARCHVALUES_X86 = exports.HOSTARCHVALUES_PPC64 = exports.HOSTARCHVALUES_PPC32 = exports.HOSTARCHVALUES_IA64 = exports.HOSTARCHVALUES_ARM64 = exports.HOSTARCHVALUES_ARM32 = exports.HOSTARCHVALUES_AMD64 = exports.AwsEcsLaunchtypeValues = exports.AWSECSLAUNCHTYPEVALUES_FARGATE = exports.AWSECSLAUNCHTYPEVALUES_EC2 = exports.CloudPlatformValues = exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = undefined;
- var utils_1 = require_utils5();
- var TMP_CLOUD_PROVIDER = "cloud.provider";
- var TMP_CLOUD_ACCOUNT_ID = "cloud.account.id";
- var TMP_CLOUD_REGION = "cloud.region";
- var TMP_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone";
- var TMP_CLOUD_PLATFORM = "cloud.platform";
- var TMP_AWS_ECS_CONTAINER_ARN = "aws.ecs.container.arn";
- var TMP_AWS_ECS_CLUSTER_ARN = "aws.ecs.cluster.arn";
- var TMP_AWS_ECS_LAUNCHTYPE = "aws.ecs.launchtype";
- var TMP_AWS_ECS_TASK_ARN = "aws.ecs.task.arn";
- var TMP_AWS_ECS_TASK_FAMILY = "aws.ecs.task.family";
- var TMP_AWS_ECS_TASK_REVISION = "aws.ecs.task.revision";
- var TMP_AWS_EKS_CLUSTER_ARN = "aws.eks.cluster.arn";
- var TMP_AWS_LOG_GROUP_NAMES = "aws.log.group.names";
- var TMP_AWS_LOG_GROUP_ARNS = "aws.log.group.arns";
- var TMP_AWS_LOG_STREAM_NAMES = "aws.log.stream.names";
- var TMP_AWS_LOG_STREAM_ARNS = "aws.log.stream.arns";
- var TMP_CONTAINER_NAME = "container.name";
- var TMP_CONTAINER_ID = "container.id";
- var TMP_CONTAINER_RUNTIME = "container.runtime";
- var TMP_CONTAINER_IMAGE_NAME = "container.image.name";
- var TMP_CONTAINER_IMAGE_TAG = "container.image.tag";
- var TMP_DEPLOYMENT_ENVIRONMENT = "deployment.environment";
- var TMP_DEVICE_ID = "device.id";
- var TMP_DEVICE_MODEL_IDENTIFIER = "device.model.identifier";
- var TMP_DEVICE_MODEL_NAME = "device.model.name";
- var TMP_FAAS_NAME = "faas.name";
- var TMP_FAAS_ID = "faas.id";
- var TMP_FAAS_VERSION = "faas.version";
- var TMP_FAAS_INSTANCE = "faas.instance";
- var TMP_FAAS_MAX_MEMORY = "faas.max_memory";
- var TMP_HOST_ID = "host.id";
- var TMP_HOST_NAME = "host.name";
- var TMP_HOST_TYPE = "host.type";
- var TMP_HOST_ARCH = "host.arch";
- var TMP_HOST_IMAGE_NAME = "host.image.name";
- var TMP_HOST_IMAGE_ID = "host.image.id";
- var TMP_HOST_IMAGE_VERSION = "host.image.version";
- var TMP_K8S_CLUSTER_NAME = "k8s.cluster.name";
- var TMP_K8S_NODE_NAME = "k8s.node.name";
- var TMP_K8S_NODE_UID = "k8s.node.uid";
- var TMP_K8S_NAMESPACE_NAME = "k8s.namespace.name";
- var TMP_K8S_POD_UID = "k8s.pod.uid";
- var TMP_K8S_POD_NAME = "k8s.pod.name";
- var TMP_K8S_CONTAINER_NAME = "k8s.container.name";
- var TMP_K8S_REPLICASET_UID = "k8s.replicaset.uid";
- var TMP_K8S_REPLICASET_NAME = "k8s.replicaset.name";
- var TMP_K8S_DEPLOYMENT_UID = "k8s.deployment.uid";
- var TMP_K8S_DEPLOYMENT_NAME = "k8s.deployment.name";
- var TMP_K8S_STATEFULSET_UID = "k8s.statefulset.uid";
- var TMP_K8S_STATEFULSET_NAME = "k8s.statefulset.name";
- var TMP_K8S_DAEMONSET_UID = "k8s.daemonset.uid";
- var TMP_K8S_DAEMONSET_NAME = "k8s.daemonset.name";
- var TMP_K8S_JOB_UID = "k8s.job.uid";
- var TMP_K8S_JOB_NAME = "k8s.job.name";
- var TMP_K8S_CRONJOB_UID = "k8s.cronjob.uid";
- var TMP_K8S_CRONJOB_NAME = "k8s.cronjob.name";
- var TMP_OS_TYPE = "os.type";
- var TMP_OS_DESCRIPTION = "os.description";
- var TMP_OS_NAME = "os.name";
- var TMP_OS_VERSION = "os.version";
- var TMP_PROCESS_PID = "process.pid";
- var TMP_PROCESS_EXECUTABLE_NAME = "process.executable.name";
- var TMP_PROCESS_EXECUTABLE_PATH = "process.executable.path";
- var TMP_PROCESS_COMMAND = "process.command";
- var TMP_PROCESS_COMMAND_LINE = "process.command_line";
- var TMP_PROCESS_COMMAND_ARGS = "process.command_args";
- var TMP_PROCESS_OWNER = "process.owner";
- var TMP_PROCESS_RUNTIME_NAME = "process.runtime.name";
- var TMP_PROCESS_RUNTIME_VERSION = "process.runtime.version";
- var TMP_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description";
- var TMP_SERVICE_NAME = "service.name";
- var TMP_SERVICE_NAMESPACE = "service.namespace";
- var TMP_SERVICE_INSTANCE_ID = "service.instance.id";
- var TMP_SERVICE_VERSION = "service.version";
- var TMP_TELEMETRY_SDK_NAME = "telemetry.sdk.name";
- var TMP_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language";
- var TMP_TELEMETRY_SDK_VERSION = "telemetry.sdk.version";
- var TMP_TELEMETRY_AUTO_VERSION = "telemetry.auto.version";
- var TMP_WEBENGINE_NAME = "webengine.name";
- var TMP_WEBENGINE_VERSION = "webengine.version";
- var TMP_WEBENGINE_DESCRIPTION = "webengine.description";
- exports.SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER;
- exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID;
- exports.SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION;
- exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE;
- exports.SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM;
- exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN;
- exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN;
- exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE;
- exports.SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN;
- exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY;
- exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION;
- exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN;
- exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES;
- exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS;
- exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES;
- exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS;
- exports.SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME;
- exports.SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID;
- exports.SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME;
- exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME;
- exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG;
- exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT;
- exports.SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID;
- exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER;
- exports.SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME;
- exports.SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME;
- exports.SEMRESATTRS_FAAS_ID = TMP_FAAS_ID;
- exports.SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION;
- exports.SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE;
- exports.SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY;
- exports.SEMRESATTRS_HOST_ID = TMP_HOST_ID;
- exports.SEMRESATTRS_HOST_NAME = TMP_HOST_NAME;
- exports.SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE;
- exports.SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH;
- exports.SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME;
- exports.SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID;
- exports.SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION;
- exports.SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME;
- exports.SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME;
- exports.SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID;
- exports.SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME;
- exports.SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID;
- exports.SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME;
- exports.SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME;
- exports.SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID;
- exports.SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME;
- exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID;
- exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME;
- exports.SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID;
- exports.SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME;
- exports.SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID;
- exports.SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME;
- exports.SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID;
- exports.SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME;
- exports.SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID;
- exports.SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME;
- exports.SEMRESATTRS_OS_TYPE = TMP_OS_TYPE;
- exports.SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION;
- exports.SEMRESATTRS_OS_NAME = TMP_OS_NAME;
- exports.SEMRESATTRS_OS_VERSION = TMP_OS_VERSION;
- exports.SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID;
- exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME;
- exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH;
- exports.SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND;
- exports.SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE;
- exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS;
- exports.SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER;
- exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME;
- exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION;
- exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION;
- exports.SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME;
- exports.SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE;
- exports.SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID;
- exports.SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION;
- exports.SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME;
- exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE;
- exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION;
- exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION;
- exports.SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME;
- exports.SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION;
- exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION;
- exports.SemanticResourceAttributes = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_CLOUD_PROVIDER,
- TMP_CLOUD_ACCOUNT_ID,
- TMP_CLOUD_REGION,
- TMP_CLOUD_AVAILABILITY_ZONE,
- TMP_CLOUD_PLATFORM,
- TMP_AWS_ECS_CONTAINER_ARN,
- TMP_AWS_ECS_CLUSTER_ARN,
- TMP_AWS_ECS_LAUNCHTYPE,
- TMP_AWS_ECS_TASK_ARN,
- TMP_AWS_ECS_TASK_FAMILY,
- TMP_AWS_ECS_TASK_REVISION,
- TMP_AWS_EKS_CLUSTER_ARN,
- TMP_AWS_LOG_GROUP_NAMES,
- TMP_AWS_LOG_GROUP_ARNS,
- TMP_AWS_LOG_STREAM_NAMES,
- TMP_AWS_LOG_STREAM_ARNS,
- TMP_CONTAINER_NAME,
- TMP_CONTAINER_ID,
- TMP_CONTAINER_RUNTIME,
- TMP_CONTAINER_IMAGE_NAME,
- TMP_CONTAINER_IMAGE_TAG,
- TMP_DEPLOYMENT_ENVIRONMENT,
- TMP_DEVICE_ID,
- TMP_DEVICE_MODEL_IDENTIFIER,
- TMP_DEVICE_MODEL_NAME,
- TMP_FAAS_NAME,
- TMP_FAAS_ID,
- TMP_FAAS_VERSION,
- TMP_FAAS_INSTANCE,
- TMP_FAAS_MAX_MEMORY,
- TMP_HOST_ID,
- TMP_HOST_NAME,
- TMP_HOST_TYPE,
- TMP_HOST_ARCH,
- TMP_HOST_IMAGE_NAME,
- TMP_HOST_IMAGE_ID,
- TMP_HOST_IMAGE_VERSION,
- TMP_K8S_CLUSTER_NAME,
- TMP_K8S_NODE_NAME,
- TMP_K8S_NODE_UID,
- TMP_K8S_NAMESPACE_NAME,
- TMP_K8S_POD_UID,
- TMP_K8S_POD_NAME,
- TMP_K8S_CONTAINER_NAME,
- TMP_K8S_REPLICASET_UID,
- TMP_K8S_REPLICASET_NAME,
- TMP_K8S_DEPLOYMENT_UID,
- TMP_K8S_DEPLOYMENT_NAME,
- TMP_K8S_STATEFULSET_UID,
- TMP_K8S_STATEFULSET_NAME,
- TMP_K8S_DAEMONSET_UID,
- TMP_K8S_DAEMONSET_NAME,
- TMP_K8S_JOB_UID,
- TMP_K8S_JOB_NAME,
- TMP_K8S_CRONJOB_UID,
- TMP_K8S_CRONJOB_NAME,
- TMP_OS_TYPE,
- TMP_OS_DESCRIPTION,
- TMP_OS_NAME,
- TMP_OS_VERSION,
- TMP_PROCESS_PID,
- TMP_PROCESS_EXECUTABLE_NAME,
- TMP_PROCESS_EXECUTABLE_PATH,
- TMP_PROCESS_COMMAND,
- TMP_PROCESS_COMMAND_LINE,
- TMP_PROCESS_COMMAND_ARGS,
- TMP_PROCESS_OWNER,
- TMP_PROCESS_RUNTIME_NAME,
- TMP_PROCESS_RUNTIME_VERSION,
- TMP_PROCESS_RUNTIME_DESCRIPTION,
- TMP_SERVICE_NAME,
- TMP_SERVICE_NAMESPACE,
- TMP_SERVICE_INSTANCE_ID,
- TMP_SERVICE_VERSION,
- TMP_TELEMETRY_SDK_NAME,
- TMP_TELEMETRY_SDK_LANGUAGE,
- TMP_TELEMETRY_SDK_VERSION,
- TMP_TELEMETRY_AUTO_VERSION,
- TMP_WEBENGINE_NAME,
- TMP_WEBENGINE_VERSION,
- TMP_WEBENGINE_DESCRIPTION
- ]);
- var TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud";
- var TMP_CLOUDPROVIDERVALUES_AWS = "aws";
- var TMP_CLOUDPROVIDERVALUES_AZURE = "azure";
- var TMP_CLOUDPROVIDERVALUES_GCP = "gcp";
- exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD;
- exports.CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS;
- exports.CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE;
- exports.CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP;
- exports.CloudProviderValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,
- TMP_CLOUDPROVIDERVALUES_AWS,
- TMP_CLOUDPROVIDERVALUES_AZURE,
- TMP_CLOUDPROVIDERVALUES_GCP
- ]);
- var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = "alibaba_cloud_ecs";
- var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = "alibaba_cloud_fc";
- var TMP_CLOUDPLATFORMVALUES_AWS_EC2 = "aws_ec2";
- var TMP_CLOUDPLATFORMVALUES_AWS_ECS = "aws_ecs";
- var TMP_CLOUDPLATFORMVALUES_AWS_EKS = "aws_eks";
- var TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = "aws_lambda";
- var TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = "aws_elastic_beanstalk";
- var TMP_CLOUDPLATFORMVALUES_AZURE_VM = "azure_vm";
- var TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = "azure_container_instances";
- var TMP_CLOUDPLATFORMVALUES_AZURE_AKS = "azure_aks";
- var TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = "azure_functions";
- var TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = "azure_app_service";
- var TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = "gcp_compute_engine";
- var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = "gcp_cloud_run";
- var TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = "gcp_kubernetes_engine";
- var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = "gcp_cloud_functions";
- var TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = "gcp_app_engine";
- exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS;
- exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC;
- exports.CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2;
- exports.CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS;
- exports.CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS;
- exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA;
- exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK;
- exports.CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM;
- exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES;
- exports.CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS;
- exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS;
- exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE;
- exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE;
- exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN;
- exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE;
- exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS;
- exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE;
- exports.CloudPlatformValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,
- TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,
- TMP_CLOUDPLATFORMVALUES_AWS_EC2,
- TMP_CLOUDPLATFORMVALUES_AWS_ECS,
- TMP_CLOUDPLATFORMVALUES_AWS_EKS,
- TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,
- TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,
- TMP_CLOUDPLATFORMVALUES_AZURE_VM,
- TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,
- TMP_CLOUDPLATFORMVALUES_AZURE_AKS,
- TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,
- TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,
- TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,
- TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,
- TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,
- TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,
- TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE
- ]);
- var TMP_AWSECSLAUNCHTYPEVALUES_EC2 = "ec2";
- var TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = "fargate";
- exports.AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2;
- exports.AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE;
- exports.AwsEcsLaunchtypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_AWSECSLAUNCHTYPEVALUES_EC2,
- TMP_AWSECSLAUNCHTYPEVALUES_FARGATE
- ]);
- var TMP_HOSTARCHVALUES_AMD64 = "amd64";
- var TMP_HOSTARCHVALUES_ARM32 = "arm32";
- var TMP_HOSTARCHVALUES_ARM64 = "arm64";
- var TMP_HOSTARCHVALUES_IA64 = "ia64";
- var TMP_HOSTARCHVALUES_PPC32 = "ppc32";
- var TMP_HOSTARCHVALUES_PPC64 = "ppc64";
- var TMP_HOSTARCHVALUES_X86 = "x86";
- exports.HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64;
- exports.HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32;
- exports.HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64;
- exports.HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64;
- exports.HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32;
- exports.HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64;
- exports.HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86;
- exports.HostArchValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_HOSTARCHVALUES_AMD64,
- TMP_HOSTARCHVALUES_ARM32,
- TMP_HOSTARCHVALUES_ARM64,
- TMP_HOSTARCHVALUES_IA64,
- TMP_HOSTARCHVALUES_PPC32,
- TMP_HOSTARCHVALUES_PPC64,
- TMP_HOSTARCHVALUES_X86
- ]);
- var TMP_OSTYPEVALUES_WINDOWS = "windows";
- var TMP_OSTYPEVALUES_LINUX = "linux";
- var TMP_OSTYPEVALUES_DARWIN = "darwin";
- var TMP_OSTYPEVALUES_FREEBSD = "freebsd";
- var TMP_OSTYPEVALUES_NETBSD = "netbsd";
- var TMP_OSTYPEVALUES_OPENBSD = "openbsd";
- var TMP_OSTYPEVALUES_DRAGONFLYBSD = "dragonflybsd";
- var TMP_OSTYPEVALUES_HPUX = "hpux";
- var TMP_OSTYPEVALUES_AIX = "aix";
- var TMP_OSTYPEVALUES_SOLARIS = "solaris";
- var TMP_OSTYPEVALUES_Z_OS = "z_os";
- exports.OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS;
- exports.OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX;
- exports.OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN;
- exports.OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD;
- exports.OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD;
- exports.OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD;
- exports.OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD;
- exports.OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX;
- exports.OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX;
- exports.OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS;
- exports.OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS;
- exports.OsTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_OSTYPEVALUES_WINDOWS,
- TMP_OSTYPEVALUES_LINUX,
- TMP_OSTYPEVALUES_DARWIN,
- TMP_OSTYPEVALUES_FREEBSD,
- TMP_OSTYPEVALUES_NETBSD,
- TMP_OSTYPEVALUES_OPENBSD,
- TMP_OSTYPEVALUES_DRAGONFLYBSD,
- TMP_OSTYPEVALUES_HPUX,
- TMP_OSTYPEVALUES_AIX,
- TMP_OSTYPEVALUES_SOLARIS,
- TMP_OSTYPEVALUES_Z_OS
- ]);
- var TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = "cpp";
- var TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = "dotnet";
- var TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = "erlang";
- var TMP_TELEMETRYSDKLANGUAGEVALUES_GO = "go";
- var TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = "java";
- var TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = "nodejs";
- var TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = "php";
- var TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = "python";
- var TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = "ruby";
- var TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = "webjs";
- exports.TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP;
- exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET;
- exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG;
- exports.TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO;
- exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA;
- exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS;
- exports.TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP;
- exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON;
- exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY;
- exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS;
- exports.TelemetrySdkLanguageValues = /* @__PURE__ */ (0, utils_1.createConstMap)([
- TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,
- TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,
- TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,
- TMP_TELEMETRYSDKLANGUAGEVALUES_GO,
- TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,
- TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,
- TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,
- TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,
- TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,
- TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS
- ]);
-});
-
-// node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js
-var require_resource = __commonJS((exports) => {
- var __createBinding2 = exports && exports.__createBinding || (Object.create ? function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- var desc = Object.getOwnPropertyDescriptor(m4, k4);
- if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() {
- return m4[k4];
- } };
- }
- Object.defineProperty(o5, k22, desc);
- } : function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- });
- var __exportStar2 = exports && exports.__exportStar || function(m4, exports2) {
- for (var p4 in m4)
- if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
- __createBinding2(exports2, m4, p4);
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- __exportStar2(require_SemanticResourceAttributes(), exports);
-});
-
-// node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js
-var require_stable_attributes = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ATTR_EXCEPTION_TYPE = exports.ATTR_EXCEPTION_STACKTRACE = exports.ATTR_EXCEPTION_MESSAGE = exports.ATTR_EXCEPTION_ESCAPED = exports.ERROR_TYPE_VALUE_OTHER = exports.ATTR_ERROR_TYPE = exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = exports.ATTR_DOTNET_GC_HEAP_GENERATION = exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = exports.DB_SYSTEM_NAME_VALUE_MYSQL = exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = exports.DB_SYSTEM_NAME_VALUE_MARIADB = exports.ATTR_DB_SYSTEM_NAME = exports.ATTR_DB_STORED_PROCEDURE_NAME = exports.ATTR_DB_RESPONSE_STATUS_CODE = exports.ATTR_DB_QUERY_TEXT = exports.ATTR_DB_QUERY_SUMMARY = exports.ATTR_DB_OPERATION_NAME = exports.ATTR_DB_OPERATION_BATCH_SIZE = exports.ATTR_DB_NAMESPACE = exports.ATTR_DB_COLLECTION_NAME = exports.ATTR_CODE_STACKTRACE = exports.ATTR_CODE_LINE_NUMBER = exports.ATTR_CODE_FUNCTION_NAME = exports.ATTR_CODE_FILE_PATH = exports.ATTR_CODE_COLUMN_NUMBER = exports.ATTR_CLIENT_PORT = exports.ATTR_CLIENT_ADDRESS = exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = undefined;
- exports.OTEL_STATUS_CODE_VALUE_ERROR = exports.ATTR_OTEL_STATUS_CODE = exports.ATTR_OTEL_SCOPE_VERSION = exports.ATTR_OTEL_SCOPE_NAME = exports.NETWORK_TYPE_VALUE_IPV6 = exports.NETWORK_TYPE_VALUE_IPV4 = exports.ATTR_NETWORK_TYPE = exports.NETWORK_TRANSPORT_VALUE_UNIX = exports.NETWORK_TRANSPORT_VALUE_UDP = exports.NETWORK_TRANSPORT_VALUE_TCP = exports.NETWORK_TRANSPORT_VALUE_QUIC = exports.NETWORK_TRANSPORT_VALUE_PIPE = exports.ATTR_NETWORK_TRANSPORT = exports.ATTR_NETWORK_PROTOCOL_VERSION = exports.ATTR_NETWORK_PROTOCOL_NAME = exports.ATTR_NETWORK_PEER_PORT = exports.ATTR_NETWORK_PEER_ADDRESS = exports.ATTR_NETWORK_LOCAL_PORT = exports.ATTR_NETWORK_LOCAL_ADDRESS = exports.JVM_THREAD_STATE_VALUE_WAITING = exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = exports.JVM_THREAD_STATE_VALUE_TERMINATED = exports.JVM_THREAD_STATE_VALUE_RUNNABLE = exports.JVM_THREAD_STATE_VALUE_NEW = exports.JVM_THREAD_STATE_VALUE_BLOCKED = exports.ATTR_JVM_THREAD_STATE = exports.ATTR_JVM_THREAD_DAEMON = exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = exports.JVM_MEMORY_TYPE_VALUE_HEAP = exports.ATTR_JVM_MEMORY_TYPE = exports.ATTR_JVM_MEMORY_POOL_NAME = exports.ATTR_JVM_GC_NAME = exports.ATTR_JVM_GC_ACTION = exports.ATTR_HTTP_ROUTE = exports.ATTR_HTTP_RESPONSE_STATUS_CODE = exports.ATTR_HTTP_RESPONSE_HEADER = exports.ATTR_HTTP_REQUEST_RESEND_COUNT = exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = exports.HTTP_REQUEST_METHOD_VALUE_TRACE = exports.HTTP_REQUEST_METHOD_VALUE_PUT = exports.HTTP_REQUEST_METHOD_VALUE_POST = exports.HTTP_REQUEST_METHOD_VALUE_PATCH = exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = exports.HTTP_REQUEST_METHOD_VALUE_HEAD = exports.HTTP_REQUEST_METHOD_VALUE_GET = exports.HTTP_REQUEST_METHOD_VALUE_DELETE = exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = exports.HTTP_REQUEST_METHOD_VALUE_OTHER = exports.ATTR_HTTP_REQUEST_METHOD = exports.ATTR_HTTP_REQUEST_HEADER = undefined;
- exports.ATTR_USER_AGENT_ORIGINAL = exports.ATTR_URL_SCHEME = exports.ATTR_URL_QUERY = exports.ATTR_URL_PATH = exports.ATTR_URL_FULL = exports.ATTR_URL_FRAGMENT = exports.ATTR_TELEMETRY_SDK_VERSION = exports.ATTR_TELEMETRY_SDK_NAME = exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = exports.ATTR_TELEMETRY_SDK_LANGUAGE = exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = exports.ATTR_SIGNALR_TRANSPORT = exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = exports.ATTR_SIGNALR_CONNECTION_STATUS = exports.ATTR_SERVICE_VERSION = exports.ATTR_SERVICE_NAMESPACE = exports.ATTR_SERVICE_NAME = exports.ATTR_SERVICE_INSTANCE_ID = exports.ATTR_SERVER_PORT = exports.ATTR_SERVER_ADDRESS = exports.ATTR_OTEL_STATUS_DESCRIPTION = exports.OTEL_STATUS_CODE_VALUE_OK = undefined;
- exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = "aspnetcore.diagnostics.exception.result";
- exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted";
- exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled";
- exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped";
- exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled";
- exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = "aspnetcore.diagnostics.handler.type";
- exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = "aspnetcore.rate_limiting.policy";
- exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = "aspnetcore.rate_limiting.result";
- exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired";
- exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter";
- exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter";
- exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled";
- exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = "aspnetcore.request.is_unhandled";
- exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = "aspnetcore.routing.is_fallback";
- exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = "aspnetcore.routing.match_status";
- exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure";
- exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success";
- exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = "aspnetcore.user.is_authenticated";
- exports.ATTR_CLIENT_ADDRESS = "client.address";
- exports.ATTR_CLIENT_PORT = "client.port";
- exports.ATTR_CODE_COLUMN_NUMBER = "code.column.number";
- exports.ATTR_CODE_FILE_PATH = "code.file.path";
- exports.ATTR_CODE_FUNCTION_NAME = "code.function.name";
- exports.ATTR_CODE_LINE_NUMBER = "code.line.number";
- exports.ATTR_CODE_STACKTRACE = "code.stacktrace";
- exports.ATTR_DB_COLLECTION_NAME = "db.collection.name";
- exports.ATTR_DB_NAMESPACE = "db.namespace";
- exports.ATTR_DB_OPERATION_BATCH_SIZE = "db.operation.batch.size";
- exports.ATTR_DB_OPERATION_NAME = "db.operation.name";
- exports.ATTR_DB_QUERY_SUMMARY = "db.query.summary";
- exports.ATTR_DB_QUERY_TEXT = "db.query.text";
- exports.ATTR_DB_RESPONSE_STATUS_CODE = "db.response.status_code";
- exports.ATTR_DB_STORED_PROCEDURE_NAME = "db.stored_procedure.name";
- exports.ATTR_DB_SYSTEM_NAME = "db.system.name";
- exports.DB_SYSTEM_NAME_VALUE_MARIADB = "mariadb";
- exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = "microsoft.sql_server";
- exports.DB_SYSTEM_NAME_VALUE_MYSQL = "mysql";
- exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = "postgresql";
- exports.ATTR_DOTNET_GC_HEAP_GENERATION = "dotnet.gc.heap.generation";
- exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = "gen0";
- exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = "gen1";
- exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = "gen2";
- exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = "loh";
- exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = "poh";
- exports.ATTR_ERROR_TYPE = "error.type";
- exports.ERROR_TYPE_VALUE_OTHER = "_OTHER";
- exports.ATTR_EXCEPTION_ESCAPED = "exception.escaped";
- exports.ATTR_EXCEPTION_MESSAGE = "exception.message";
- exports.ATTR_EXCEPTION_STACKTRACE = "exception.stacktrace";
- exports.ATTR_EXCEPTION_TYPE = "exception.type";
- var ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`;
- exports.ATTR_HTTP_REQUEST_HEADER = ATTR_HTTP_REQUEST_HEADER;
- exports.ATTR_HTTP_REQUEST_METHOD = "http.request.method";
- exports.HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER";
- exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT";
- exports.HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE";
- exports.HTTP_REQUEST_METHOD_VALUE_GET = "GET";
- exports.HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD";
- exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS";
- exports.HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH";
- exports.HTTP_REQUEST_METHOD_VALUE_POST = "POST";
- exports.HTTP_REQUEST_METHOD_VALUE_PUT = "PUT";
- exports.HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE";
- exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original";
- exports.ATTR_HTTP_REQUEST_RESEND_COUNT = "http.request.resend_count";
- var ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`;
- exports.ATTR_HTTP_RESPONSE_HEADER = ATTR_HTTP_RESPONSE_HEADER;
- exports.ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code";
- exports.ATTR_HTTP_ROUTE = "http.route";
- exports.ATTR_JVM_GC_ACTION = "jvm.gc.action";
- exports.ATTR_JVM_GC_NAME = "jvm.gc.name";
- exports.ATTR_JVM_MEMORY_POOL_NAME = "jvm.memory.pool.name";
- exports.ATTR_JVM_MEMORY_TYPE = "jvm.memory.type";
- exports.JVM_MEMORY_TYPE_VALUE_HEAP = "heap";
- exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap";
- exports.ATTR_JVM_THREAD_DAEMON = "jvm.thread.daemon";
- exports.ATTR_JVM_THREAD_STATE = "jvm.thread.state";
- exports.JVM_THREAD_STATE_VALUE_BLOCKED = "blocked";
- exports.JVM_THREAD_STATE_VALUE_NEW = "new";
- exports.JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable";
- exports.JVM_THREAD_STATE_VALUE_TERMINATED = "terminated";
- exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting";
- exports.JVM_THREAD_STATE_VALUE_WAITING = "waiting";
- exports.ATTR_NETWORK_LOCAL_ADDRESS = "network.local.address";
- exports.ATTR_NETWORK_LOCAL_PORT = "network.local.port";
- exports.ATTR_NETWORK_PEER_ADDRESS = "network.peer.address";
- exports.ATTR_NETWORK_PEER_PORT = "network.peer.port";
- exports.ATTR_NETWORK_PROTOCOL_NAME = "network.protocol.name";
- exports.ATTR_NETWORK_PROTOCOL_VERSION = "network.protocol.version";
- exports.ATTR_NETWORK_TRANSPORT = "network.transport";
- exports.NETWORK_TRANSPORT_VALUE_PIPE = "pipe";
- exports.NETWORK_TRANSPORT_VALUE_QUIC = "quic";
- exports.NETWORK_TRANSPORT_VALUE_TCP = "tcp";
- exports.NETWORK_TRANSPORT_VALUE_UDP = "udp";
- exports.NETWORK_TRANSPORT_VALUE_UNIX = "unix";
- exports.ATTR_NETWORK_TYPE = "network.type";
- exports.NETWORK_TYPE_VALUE_IPV4 = "ipv4";
- exports.NETWORK_TYPE_VALUE_IPV6 = "ipv6";
- exports.ATTR_OTEL_SCOPE_NAME = "otel.scope.name";
- exports.ATTR_OTEL_SCOPE_VERSION = "otel.scope.version";
- exports.ATTR_OTEL_STATUS_CODE = "otel.status_code";
- exports.OTEL_STATUS_CODE_VALUE_ERROR = "ERROR";
- exports.OTEL_STATUS_CODE_VALUE_OK = "OK";
- exports.ATTR_OTEL_STATUS_DESCRIPTION = "otel.status_description";
- exports.ATTR_SERVER_ADDRESS = "server.address";
- exports.ATTR_SERVER_PORT = "server.port";
- exports.ATTR_SERVICE_INSTANCE_ID = "service.instance.id";
- exports.ATTR_SERVICE_NAME = "service.name";
- exports.ATTR_SERVICE_NAMESPACE = "service.namespace";
- exports.ATTR_SERVICE_VERSION = "service.version";
- exports.ATTR_SIGNALR_CONNECTION_STATUS = "signalr.connection.status";
- exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown";
- exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure";
- exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout";
- exports.ATTR_SIGNALR_TRANSPORT = "signalr.transport";
- exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling";
- exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events";
- exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets";
- exports.ATTR_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift";
- exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs";
- exports.ATTR_TELEMETRY_SDK_NAME = "telemetry.sdk.name";
- exports.ATTR_TELEMETRY_SDK_VERSION = "telemetry.sdk.version";
- exports.ATTR_URL_FRAGMENT = "url.fragment";
- exports.ATTR_URL_FULL = "url.full";
- exports.ATTR_URL_PATH = "url.path";
- exports.ATTR_URL_QUERY = "url.query";
- exports.ATTR_URL_SCHEME = "url.scheme";
- exports.ATTR_USER_AGENT_ORIGINAL = "user_agent.original";
-});
-
-// node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js
-var require_stable_metrics = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = exports.METRIC_KESTREL_REJECTED_CONNECTIONS = exports.METRIC_KESTREL_QUEUED_REQUESTS = exports.METRIC_KESTREL_QUEUED_CONNECTIONS = exports.METRIC_KESTREL_CONNECTION_DURATION = exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = exports.METRIC_JVM_THREAD_COUNT = exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = exports.METRIC_JVM_MEMORY_USED = exports.METRIC_JVM_MEMORY_LIMIT = exports.METRIC_JVM_MEMORY_COMMITTED = exports.METRIC_JVM_GC_DURATION = exports.METRIC_JVM_CPU_TIME = exports.METRIC_JVM_CPU_RECENT_UTILIZATION = exports.METRIC_JVM_CPU_COUNT = exports.METRIC_JVM_CLASS_UNLOADED = exports.METRIC_JVM_CLASS_LOADED = exports.METRIC_JVM_CLASS_COUNT = exports.METRIC_HTTP_SERVER_REQUEST_DURATION = exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = exports.METRIC_DOTNET_TIMER_COUNT = exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = exports.METRIC_DOTNET_PROCESS_CPU_TIME = exports.METRIC_DOTNET_PROCESS_CPU_COUNT = exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = exports.METRIC_DOTNET_JIT_COMPILED_METHODS = exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = exports.METRIC_DOTNET_JIT_COMPILATION_TIME = exports.METRIC_DOTNET_GC_PAUSE_TIME = exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = exports.METRIC_DOTNET_GC_COLLECTIONS = exports.METRIC_DOTNET_EXCEPTIONS = exports.METRIC_DOTNET_ASSEMBLY_COUNT = exports.METRIC_DB_CLIENT_OPERATION_DURATION = exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = undefined;
- exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = undefined;
- exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = "aspnetcore.diagnostics.exceptions";
- exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = "aspnetcore.rate_limiting.active_request_leases";
- exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = "aspnetcore.rate_limiting.queued_requests";
- exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = "aspnetcore.rate_limiting.request.time_in_queue";
- exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = "aspnetcore.rate_limiting.request_lease.duration";
- exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = "aspnetcore.rate_limiting.requests";
- exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = "aspnetcore.routing.match_attempts";
- exports.METRIC_DB_CLIENT_OPERATION_DURATION = "db.client.operation.duration";
- exports.METRIC_DOTNET_ASSEMBLY_COUNT = "dotnet.assembly.count";
- exports.METRIC_DOTNET_EXCEPTIONS = "dotnet.exceptions";
- exports.METRIC_DOTNET_GC_COLLECTIONS = "dotnet.gc.collections";
- exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = "dotnet.gc.heap.total_allocated";
- exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = "dotnet.gc.last_collection.heap.fragmentation.size";
- exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = "dotnet.gc.last_collection.heap.size";
- exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = "dotnet.gc.last_collection.memory.committed_size";
- exports.METRIC_DOTNET_GC_PAUSE_TIME = "dotnet.gc.pause.time";
- exports.METRIC_DOTNET_JIT_COMPILATION_TIME = "dotnet.jit.compilation.time";
- exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = "dotnet.jit.compiled_il.size";
- exports.METRIC_DOTNET_JIT_COMPILED_METHODS = "dotnet.jit.compiled_methods";
- exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = "dotnet.monitor.lock_contentions";
- exports.METRIC_DOTNET_PROCESS_CPU_COUNT = "dotnet.process.cpu.count";
- exports.METRIC_DOTNET_PROCESS_CPU_TIME = "dotnet.process.cpu.time";
- exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = "dotnet.process.memory.working_set";
- exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = "dotnet.thread_pool.queue.length";
- exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = "dotnet.thread_pool.thread.count";
- exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = "dotnet.thread_pool.work_item.count";
- exports.METRIC_DOTNET_TIMER_COUNT = "dotnet.timer.count";
- exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = "http.client.request.duration";
- exports.METRIC_HTTP_SERVER_REQUEST_DURATION = "http.server.request.duration";
- exports.METRIC_JVM_CLASS_COUNT = "jvm.class.count";
- exports.METRIC_JVM_CLASS_LOADED = "jvm.class.loaded";
- exports.METRIC_JVM_CLASS_UNLOADED = "jvm.class.unloaded";
- exports.METRIC_JVM_CPU_COUNT = "jvm.cpu.count";
- exports.METRIC_JVM_CPU_RECENT_UTILIZATION = "jvm.cpu.recent_utilization";
- exports.METRIC_JVM_CPU_TIME = "jvm.cpu.time";
- exports.METRIC_JVM_GC_DURATION = "jvm.gc.duration";
- exports.METRIC_JVM_MEMORY_COMMITTED = "jvm.memory.committed";
- exports.METRIC_JVM_MEMORY_LIMIT = "jvm.memory.limit";
- exports.METRIC_JVM_MEMORY_USED = "jvm.memory.used";
- exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = "jvm.memory.used_after_last_gc";
- exports.METRIC_JVM_THREAD_COUNT = "jvm.thread.count";
- exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = "kestrel.active_connections";
- exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = "kestrel.active_tls_handshakes";
- exports.METRIC_KESTREL_CONNECTION_DURATION = "kestrel.connection.duration";
- exports.METRIC_KESTREL_QUEUED_CONNECTIONS = "kestrel.queued_connections";
- exports.METRIC_KESTREL_QUEUED_REQUESTS = "kestrel.queued_requests";
- exports.METRIC_KESTREL_REJECTED_CONNECTIONS = "kestrel.rejected_connections";
- exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = "kestrel.tls_handshake.duration";
- exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = "kestrel.upgraded_connections";
- exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = "signalr.server.active_connections";
- exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = "signalr.server.connection.duration";
-});
-
-// node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js
-var require_stable_events = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.EVENT_EXCEPTION = undefined;
- exports.EVENT_EXCEPTION = "exception";
-});
-
-// node_modules/@opentelemetry/semantic-conventions/build/src/index.js
-var require_src8 = __commonJS((exports) => {
- var __createBinding2 = exports && exports.__createBinding || (Object.create ? function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- var desc = Object.getOwnPropertyDescriptor(m4, k4);
- if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() {
- return m4[k4];
- } };
- }
- Object.defineProperty(o5, k22, desc);
- } : function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- });
- var __exportStar2 = exports && exports.__exportStar || function(m4, exports2) {
- for (var p4 in m4)
- if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
- __createBinding2(exports2, m4, p4);
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- __exportStar2(require_trace2(), exports);
- __exportStar2(require_resource(), exports);
- __exportStar2(require_stable_attributes(), exports);
- __exportStar2(require_stable_metrics(), exports);
- __exportStar2(require_stable_events(), exports);
-});
-
-// node_modules/@opentelemetry/core/build/src/semconv.js
-var require_semconv = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ATTR_PROCESS_RUNTIME_NAME = undefined;
- exports.ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name";
-});
-
-// node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js
-var require_sdk_info = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.SDK_INFO = undefined;
- var version_1 = require_version4();
- var semantic_conventions_1 = require_src8();
- var semconv_1 = require_semconv();
- exports.SDK_INFO = {
- [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: "opentelemetry",
- [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: "node",
- [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: semantic_conventions_1.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,
- [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: version_1.VERSION
- };
-});
-
-// node_modules/@opentelemetry/core/build/src/platform/node/index.js
-var require_node2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.otperformance = exports.SDK_INFO = exports._globalThis = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = undefined;
- var environment_1 = require_environment();
- Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function() {
- return environment_1.getStringFromEnv;
- } });
- Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function() {
- return environment_1.getBooleanFromEnv;
- } });
- Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function() {
- return environment_1.getNumberFromEnv;
- } });
- Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function() {
- return environment_1.getStringListFromEnv;
- } });
- var globalThis_1 = require_globalThis();
- Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function() {
- return globalThis_1._globalThis;
- } });
- var sdk_info_1 = require_sdk_info();
- Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function() {
- return sdk_info_1.SDK_INFO;
- } });
- exports.otperformance = performance;
-});
-
-// node_modules/@opentelemetry/core/build/src/platform/index.js
-var require_platform = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getStringFromEnv = exports.getBooleanFromEnv = exports.otperformance = exports._globalThis = exports.SDK_INFO = undefined;
- var node_1 = require_node2();
- Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function() {
- return node_1.SDK_INFO;
- } });
- Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function() {
- return node_1._globalThis;
- } });
- Object.defineProperty(exports, "otperformance", { enumerable: true, get: function() {
- return node_1.otperformance;
- } });
- Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function() {
- return node_1.getBooleanFromEnv;
- } });
- Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function() {
- return node_1.getStringFromEnv;
- } });
- Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function() {
- return node_1.getNumberFromEnv;
- } });
- Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function() {
- return node_1.getStringListFromEnv;
- } });
-});
-
-// node_modules/@opentelemetry/core/build/src/common/time.js
-var require_time = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.addHrTimes = exports.isTimeInput = exports.isTimeInputHrTime = exports.hrTimeToMicroseconds = exports.hrTimeToMilliseconds = exports.hrTimeToNanoseconds = exports.hrTimeToTimeStamp = exports.hrTimeDuration = exports.timeInputToHrTime = exports.hrTime = exports.getTimeOrigin = exports.millisToHrTime = undefined;
- var platform_1 = require_platform();
- var NANOSECOND_DIGITS = 9;
- var NANOSECOND_DIGITS_IN_MILLIS = 6;
- var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);
- var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);
- function millisToHrTime(epochMillis) {
- const epochSeconds = epochMillis / 1000;
- const seconds = Math.trunc(epochSeconds);
- const nanos = Math.round(epochMillis % 1000 * MILLISECONDS_TO_NANOSECONDS);
- return [seconds, nanos];
- }
- exports.millisToHrTime = millisToHrTime;
- function getTimeOrigin() {
- return platform_1.otperformance.timeOrigin;
- }
- exports.getTimeOrigin = getTimeOrigin;
- function hrTime(performanceNow) {
- const timeOrigin = millisToHrTime(platform_1.otperformance.timeOrigin);
- const now = millisToHrTime(typeof performanceNow === "number" ? performanceNow : platform_1.otperformance.now());
- return addHrTimes(timeOrigin, now);
- }
- exports.hrTime = hrTime;
- function timeInputToHrTime(time3) {
- if (isTimeInputHrTime(time3)) {
- return time3;
- } else if (typeof time3 === "number") {
- if (time3 < platform_1.otperformance.timeOrigin) {
- return hrTime(time3);
- } else {
- return millisToHrTime(time3);
- }
- } else if (time3 instanceof Date) {
- return millisToHrTime(time3.getTime());
- } else {
- throw TypeError("Invalid input type");
- }
- }
- exports.timeInputToHrTime = timeInputToHrTime;
- function hrTimeDuration(startTime, endTime) {
- let seconds = endTime[0] - startTime[0];
- let nanos = endTime[1] - startTime[1];
- if (nanos < 0) {
- seconds -= 1;
- nanos += SECOND_TO_NANOSECONDS;
- }
- return [seconds, nanos];
- }
- exports.hrTimeDuration = hrTimeDuration;
- function hrTimeToTimeStamp(time3) {
- const precision = NANOSECOND_DIGITS;
- const tmp = `${"0".repeat(precision)}${time3[1]}Z`;
- const nanoString = tmp.substring(tmp.length - precision - 1);
- const date5 = new Date(time3[0] * 1000).toISOString();
- return date5.replace("000Z", nanoString);
- }
- exports.hrTimeToTimeStamp = hrTimeToTimeStamp;
- function hrTimeToNanoseconds(time3) {
- return time3[0] * SECOND_TO_NANOSECONDS + time3[1];
- }
- exports.hrTimeToNanoseconds = hrTimeToNanoseconds;
- function hrTimeToMilliseconds(time3) {
- return time3[0] * 1000 + time3[1] / 1e6;
- }
- exports.hrTimeToMilliseconds = hrTimeToMilliseconds;
- function hrTimeToMicroseconds(time3) {
- return time3[0] * 1e6 + time3[1] / 1000;
- }
- exports.hrTimeToMicroseconds = hrTimeToMicroseconds;
- function isTimeInputHrTime(value) {
- return Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number";
- }
- exports.isTimeInputHrTime = isTimeInputHrTime;
- function isTimeInput(value) {
- return isTimeInputHrTime(value) || typeof value === "number" || value instanceof Date;
- }
- exports.isTimeInput = isTimeInput;
- function addHrTimes(time1, time22) {
- const out = [time1[0] + time22[0], time1[1] + time22[1]];
- if (out[1] >= SECOND_TO_NANOSECONDS) {
- out[1] -= SECOND_TO_NANOSECONDS;
- out[0] += 1;
- }
- return out;
- }
- exports.addHrTimes = addHrTimes;
-});
-
-// node_modules/@opentelemetry/core/build/src/common/timer-util.js
-var require_timer_util = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.unrefTimer = undefined;
- function unrefTimer(timer) {
- if (typeof timer !== "number") {
- timer.unref();
- }
- }
- exports.unrefTimer = unrefTimer;
-});
-
-// node_modules/@opentelemetry/core/build/src/ExportResult.js
-var require_ExportResult = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ExportResultCode = undefined;
- var ExportResultCode;
- (function(ExportResultCode2) {
- ExportResultCode2[ExportResultCode2["SUCCESS"] = 0] = "SUCCESS";
- ExportResultCode2[ExportResultCode2["FAILED"] = 1] = "FAILED";
- })(ExportResultCode = exports.ExportResultCode || (exports.ExportResultCode = {}));
-});
-
-// node_modules/@opentelemetry/core/build/src/propagation/composite.js
-var require_composite = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.CompositePropagator = undefined;
- var api_1 = require_src7();
-
- class CompositePropagator {
- _propagators;
- _fields;
- constructor(config8 = {}) {
- this._propagators = config8.propagators ?? [];
- this._fields = Array.from(new Set(this._propagators.map((p4) => typeof p4.fields === "function" ? p4.fields() : []).reduce((x3, y3) => x3.concat(y3), [])));
- }
- inject(context3, carrier, setter) {
- for (const propagator of this._propagators) {
- try {
- propagator.inject(context3, carrier, setter);
- } catch (err) {
- api_1.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`);
- }
- }
- }
- extract(context3, carrier, getter) {
- return this._propagators.reduce((ctx, propagator) => {
- try {
- return propagator.extract(ctx, carrier, getter);
- } catch (err) {
- api_1.diag.warn(`Failed to extract with ${propagator.constructor.name}. Err: ${err.message}`);
- }
- return ctx;
- }, context3);
- }
- fields() {
- return this._fields.slice();
- }
- }
- exports.CompositePropagator = CompositePropagator;
-});
-
-// node_modules/@opentelemetry/core/build/src/internal/validators.js
-var require_validators = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.validateValue = exports.validateKey = undefined;
- var VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]";
- var VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;
- var VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;
- var VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);
- var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
- var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
- function validateKey(key) {
- return VALID_KEY_REGEX.test(key);
- }
- exports.validateKey = validateKey;
- function validateValue(value) {
- return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value);
- }
- exports.validateValue = validateValue;
-});
-
-// node_modules/@opentelemetry/core/build/src/trace/TraceState.js
-var require_TraceState = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.TraceState = undefined;
- var validators_1 = require_validators();
- var MAX_TRACE_STATE_ITEMS = 32;
- var MAX_TRACE_STATE_LEN = 512;
- var LIST_MEMBERS_SEPARATOR = ",";
- var LIST_MEMBER_KEY_VALUE_SPLITTER = "=";
-
- class TraceState {
- _internalState = new Map;
- constructor(rawTraceState) {
- if (rawTraceState)
- this._parse(rawTraceState);
- }
- set(key, value) {
- const traceState = this._clone();
- if (traceState._internalState.has(key)) {
- traceState._internalState.delete(key);
- }
- traceState._internalState.set(key, value);
- return traceState;
- }
- unset(key) {
- const traceState = this._clone();
- traceState._internalState.delete(key);
- return traceState;
- }
- get(key) {
- return this._internalState.get(key);
- }
- serialize() {
- return this._keys().reduce((agg, key) => {
- agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));
- return agg;
- }, []).join(LIST_MEMBERS_SEPARATOR);
- }
- _parse(rawTraceState) {
- if (rawTraceState.length > MAX_TRACE_STATE_LEN)
- return;
- this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR).reverse().reduce((agg, part) => {
- const listMember = part.trim();
- const i5 = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
- if (i5 !== -1) {
- const key = listMember.slice(0, i5);
- const value = listMember.slice(i5 + 1, part.length);
- if ((0, validators_1.validateKey)(key) && (0, validators_1.validateValue)(value)) {
- agg.set(key, value);
- } else {}
- }
- return agg;
- }, new Map);
- if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {
- this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS));
- }
- }
- _keys() {
- return Array.from(this._internalState.keys()).reverse();
- }
- _clone() {
- const traceState = new TraceState;
- traceState._internalState = new Map(this._internalState);
- return traceState;
- }
- }
- exports.TraceState = TraceState;
-});
-
-// node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js
-var require_W3CTraceContextPropagator = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.W3CTraceContextPropagator = exports.parseTraceParent = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = undefined;
- var api_1 = require_src7();
- var suppress_tracing_1 = require_suppress_tracing();
- var TraceState_1 = require_TraceState();
- exports.TRACE_PARENT_HEADER = "traceparent";
- exports.TRACE_STATE_HEADER = "tracestate";
- var VERSION7 = "00";
- var VERSION_PART = "(?!ff)[\\da-f]{2}";
- var TRACE_ID_PART = "(?![0]{32})[\\da-f]{32}";
- var PARENT_ID_PART = "(?![0]{16})[\\da-f]{16}";
- var FLAGS_PART = "[\\da-f]{2}";
- var TRACE_PARENT_REGEX = new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`);
- function parseTraceParent(traceParent) {
- const match = TRACE_PARENT_REGEX.exec(traceParent);
- if (!match)
- return null;
- if (match[1] === "00" && match[5])
- return null;
- return {
- traceId: match[2],
- spanId: match[3],
- traceFlags: parseInt(match[4], 16)
- };
- }
- exports.parseTraceParent = parseTraceParent;
-
- class W3CTraceContextPropagator {
- inject(context3, carrier, setter) {
- const spanContext = api_1.trace.getSpanContext(context3);
- if (!spanContext || (0, suppress_tracing_1.isTracingSuppressed)(context3) || !(0, api_1.isSpanContextValid)(spanContext))
- return;
- const traceParent = `${VERSION7}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags || api_1.TraceFlags.NONE).toString(16)}`;
- setter.set(carrier, exports.TRACE_PARENT_HEADER, traceParent);
- if (spanContext.traceState) {
- setter.set(carrier, exports.TRACE_STATE_HEADER, spanContext.traceState.serialize());
- }
- }
- extract(context3, carrier, getter) {
- const traceParentHeader = getter.get(carrier, exports.TRACE_PARENT_HEADER);
- if (!traceParentHeader)
- return context3;
- const traceParent = Array.isArray(traceParentHeader) ? traceParentHeader[0] : traceParentHeader;
- if (typeof traceParent !== "string")
- return context3;
- const spanContext = parseTraceParent(traceParent);
- if (!spanContext)
- return context3;
- spanContext.isRemote = true;
- const traceStateHeader = getter.get(carrier, exports.TRACE_STATE_HEADER);
- if (traceStateHeader) {
- const state3 = Array.isArray(traceStateHeader) ? traceStateHeader.join(",") : traceStateHeader;
- spanContext.traceState = new TraceState_1.TraceState(typeof state3 === "string" ? state3 : undefined);
- }
- return api_1.trace.setSpanContext(context3, spanContext);
- }
- fields() {
- return [exports.TRACE_PARENT_HEADER, exports.TRACE_STATE_HEADER];
- }
- }
- exports.W3CTraceContextPropagator = W3CTraceContextPropagator;
-});
-
-// node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js
-var require_rpc_metadata = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getRPCMetadata = exports.deleteRPCMetadata = exports.setRPCMetadata = exports.RPCType = undefined;
- var api_1 = require_src7();
- var RPC_METADATA_KEY = (0, api_1.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA");
- var RPCType;
- (function(RPCType2) {
- RPCType2["HTTP"] = "http";
- })(RPCType = exports.RPCType || (exports.RPCType = {}));
- function setRPCMetadata(context3, meta) {
- return context3.setValue(RPC_METADATA_KEY, meta);
- }
- exports.setRPCMetadata = setRPCMetadata;
- function deleteRPCMetadata(context3) {
- return context3.deleteValue(RPC_METADATA_KEY);
- }
- exports.deleteRPCMetadata = deleteRPCMetadata;
- function getRPCMetadata(context3) {
- return context3.getValue(RPC_METADATA_KEY);
- }
- exports.getRPCMetadata = getRPCMetadata;
-});
-
-// node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js
-var require_lodash_merge = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isPlainObject = undefined;
- var objectTag6 = "[object Object]";
- var nullTag2 = "[object Null]";
- var undefinedTag2 = "[object Undefined]";
- var funcProto4 = Function.prototype;
- var funcToString4 = funcProto4.toString;
- var objectCtorString2 = funcToString4.call(Object);
- var getPrototypeOf2 = Object.getPrototypeOf;
- var objectProto17 = Object.prototype;
- var hasOwnProperty15 = objectProto17.hasOwnProperty;
- var symToStringTag3 = Symbol ? Symbol.toStringTag : undefined;
- var nativeObjectToString3 = objectProto17.toString;
- function isPlainObject5(value) {
- if (!isObjectLike2(value) || baseGetTag2(value) !== objectTag6) {
- return false;
- }
- const proto2 = getPrototypeOf2(value);
- if (proto2 === null) {
- return true;
- }
- const Ctor = hasOwnProperty15.call(proto2, "constructor") && proto2.constructor;
- return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString4.call(Ctor) === objectCtorString2;
- }
- exports.isPlainObject = isPlainObject5;
- function isObjectLike2(value) {
- return value != null && typeof value == "object";
- }
- function baseGetTag2(value) {
- if (value == null) {
- return value === undefined ? undefinedTag2 : nullTag2;
- }
- return symToStringTag3 && symToStringTag3 in Object(value) ? getRawTag2(value) : objectToString4(value);
- }
- function getRawTag2(value) {
- const isOwn = hasOwnProperty15.call(value, symToStringTag3), tag2 = value[symToStringTag3];
- let unmasked = false;
- try {
- value[symToStringTag3] = undefined;
- unmasked = true;
- } catch {}
- const result = nativeObjectToString3.call(value);
- if (unmasked) {
- if (isOwn) {
- value[symToStringTag3] = tag2;
- } else {
- delete value[symToStringTag3];
- }
- }
- return result;
- }
- function objectToString4(value) {
- return nativeObjectToString3.call(value);
- }
-});
-
-// node_modules/@opentelemetry/core/build/src/utils/merge.js
-var require_merge = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.merge = undefined;
- var lodash_merge_1 = require_lodash_merge();
- var MAX_LEVEL = 20;
- function merge3(...args) {
- let result = args.shift();
- const objects = new WeakMap;
- while (args.length > 0) {
- result = mergeTwoObjects(result, args.shift(), 0, objects);
- }
- return result;
- }
- exports.merge = merge3;
- function takeValue(value) {
- if (isArray9(value)) {
- return value.slice();
- }
- return value;
- }
- function mergeTwoObjects(one, two, level = 0, objects) {
- let result;
- if (level > MAX_LEVEL) {
- return;
- }
- level++;
- if (isPrimitive(one) || isPrimitive(two) || isFunction4(two)) {
- result = takeValue(two);
- } else if (isArray9(one)) {
- result = one.slice();
- if (isArray9(two)) {
- for (let i5 = 0, j4 = two.length;i5 < j4; i5++) {
- result.push(takeValue(two[i5]));
- }
- } else if (isObject6(two)) {
- const keys2 = Object.keys(two);
- for (let i5 = 0, j4 = keys2.length;i5 < j4; i5++) {
- const key = keys2[i5];
- result[key] = takeValue(two[key]);
- }
- }
- } else if (isObject6(one)) {
- if (isObject6(two)) {
- if (!shouldMerge(one, two)) {
- return two;
- }
- result = Object.assign({}, one);
- const keys2 = Object.keys(two);
- for (let i5 = 0, j4 = keys2.length;i5 < j4; i5++) {
- const key = keys2[i5];
- const twoValue = two[key];
- if (isPrimitive(twoValue)) {
- if (typeof twoValue === "undefined") {
- delete result[key];
- } else {
- result[key] = twoValue;
- }
- } else {
- const obj1 = result[key];
- const obj2 = twoValue;
- if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) {
- delete result[key];
- } else {
- if (isObject6(obj1) && isObject6(obj2)) {
- const arr1 = objects.get(obj1) || [];
- const arr2 = objects.get(obj2) || [];
- arr1.push({ obj: one, key });
- arr2.push({ obj: two, key });
- objects.set(obj1, arr1);
- objects.set(obj2, arr2);
- }
- result[key] = mergeTwoObjects(result[key], twoValue, level, objects);
- }
- }
- }
- } else {
- result = two;
- }
- }
- return result;
- }
- function wasObjectReferenced(obj, key, objects) {
- const arr = objects.get(obj[key]) || [];
- for (let i5 = 0, j4 = arr.length;i5 < j4; i5++) {
- const info = arr[i5];
- if (info.key === key && info.obj === obj) {
- return true;
- }
- }
- return false;
- }
- function isArray9(value) {
- return Array.isArray(value);
- }
- function isFunction4(value) {
- return typeof value === "function";
- }
- function isObject6(value) {
- return !isPrimitive(value) && !isArray9(value) && !isFunction4(value) && typeof value === "object";
- }
- function isPrimitive(value) {
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined" || value instanceof Date || value instanceof RegExp || value === null;
- }
- function shouldMerge(one, two) {
- if (!(0, lodash_merge_1.isPlainObject)(one) || !(0, lodash_merge_1.isPlainObject)(two)) {
- return false;
- }
- return true;
- }
-});
-
-// node_modules/@opentelemetry/core/build/src/utils/timeout.js
-var require_timeout = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.callWithTimeout = exports.TimeoutError = undefined;
-
- class TimeoutError extends Error {
- constructor(message) {
- super(message);
- Object.setPrototypeOf(this, TimeoutError.prototype);
- }
- }
- exports.TimeoutError = TimeoutError;
- function callWithTimeout(promise2, timeout) {
- let timeoutHandle;
- const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) {
- timeoutHandle = setTimeout(function timeoutHandler() {
- reject(new TimeoutError("Operation timed out."));
- }, timeout);
- });
- return Promise.race([promise2, timeoutPromise]).then((result) => {
- clearTimeout(timeoutHandle);
- return result;
- }, (reason) => {
- clearTimeout(timeoutHandle);
- throw reason;
- });
- }
- exports.callWithTimeout = callWithTimeout;
-});
-
-// node_modules/@opentelemetry/core/build/src/utils/url.js
-var require_url = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isUrlIgnored = exports.urlMatches = undefined;
- function urlMatches(url3, urlToMatch) {
- if (typeof urlToMatch === "string") {
- return url3 === urlToMatch;
- } else {
- return !!url3.match(urlToMatch);
- }
- }
- exports.urlMatches = urlMatches;
- function isUrlIgnored(url3, ignoredUrls) {
- if (!ignoredUrls) {
- return false;
- }
- for (const ignoreUrl of ignoredUrls) {
- if (urlMatches(url3, ignoreUrl)) {
- return true;
- }
- }
- return false;
- }
- exports.isUrlIgnored = isUrlIgnored;
-});
-
-// node_modules/@opentelemetry/core/build/src/utils/promise.js
-var require_promise = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Deferred = undefined;
-
- class Deferred {
- _promise;
- _resolve;
- _reject;
- constructor() {
- this._promise = new Promise((resolve9, reject) => {
- this._resolve = resolve9;
- this._reject = reject;
- });
- }
- get promise() {
- return this._promise;
- }
- resolve(val) {
- this._resolve(val);
- }
- reject(err) {
- this._reject(err);
- }
- }
- exports.Deferred = Deferred;
-});
-
-// node_modules/@opentelemetry/core/build/src/utils/callback.js
-var require_callback = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.BindOnceFuture = undefined;
- var promise_1 = require_promise();
-
- class BindOnceFuture {
- _isCalled = false;
- _deferred = new promise_1.Deferred;
- _callback;
- _that;
- constructor(callback, that) {
- this._callback = callback;
- this._that = that;
- }
- get isCalled() {
- return this._isCalled;
- }
- get promise() {
- return this._deferred.promise;
- }
- call(...args) {
- if (!this._isCalled) {
- this._isCalled = true;
- try {
- Promise.resolve(this._callback.call(this._that, ...args)).then((val) => this._deferred.resolve(val), (err) => this._deferred.reject(err));
- } catch (err) {
- this._deferred.reject(err);
- }
- }
- return this._deferred.promise;
- }
- }
- exports.BindOnceFuture = BindOnceFuture;
-});
-
-// node_modules/@opentelemetry/core/build/src/utils/configuration.js
-var require_configuration = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.diagLogLevelFromString = undefined;
- var api_1 = require_src7();
- var logLevelMap = {
- ALL: api_1.DiagLogLevel.ALL,
- VERBOSE: api_1.DiagLogLevel.VERBOSE,
- DEBUG: api_1.DiagLogLevel.DEBUG,
- INFO: api_1.DiagLogLevel.INFO,
- WARN: api_1.DiagLogLevel.WARN,
- ERROR: api_1.DiagLogLevel.ERROR,
- NONE: api_1.DiagLogLevel.NONE
- };
- function diagLogLevelFromString(value) {
- if (value == null) {
- return;
- }
- const resolvedLogLevel = logLevelMap[value.toUpperCase()];
- if (resolvedLogLevel == null) {
- api_1.diag.warn(`Unknown log level "${value}", expected one of ${Object.keys(logLevelMap)}, using default`);
- return api_1.DiagLogLevel.INFO;
- }
- return resolvedLogLevel;
- }
- exports.diagLogLevelFromString = diagLogLevelFromString;
-});
-
-// node_modules/@opentelemetry/core/build/src/internal/exporter.js
-var require_exporter = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports._export = undefined;
- var api_1 = require_src7();
- var suppress_tracing_1 = require_suppress_tracing();
- function _export(exporter, arg) {
- return new Promise((resolve9) => {
- api_1.context.with((0, suppress_tracing_1.suppressTracing)(api_1.context.active()), () => {
- exporter.export(arg, resolve9);
- });
- });
- }
- exports._export = _export;
-});
-
-// node_modules/@opentelemetry/core/build/src/index.js
-var require_src9 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.internal = exports.diagLogLevelFromString = exports.BindOnceFuture = exports.urlMatches = exports.isUrlIgnored = exports.callWithTimeout = exports.TimeoutError = exports.merge = exports.TraceState = exports.unsuppressTracing = exports.suppressTracing = exports.isTracingSuppressed = exports.setRPCMetadata = exports.getRPCMetadata = exports.deleteRPCMetadata = exports.RPCType = exports.parseTraceParent = exports.W3CTraceContextPropagator = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = exports.CompositePropagator = exports.otperformance = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports._globalThis = exports.SDK_INFO = exports.parseKeyPairsIntoRecord = exports.ExportResultCode = exports.unrefTimer = exports.timeInputToHrTime = exports.millisToHrTime = exports.isTimeInputHrTime = exports.isTimeInput = exports.hrTimeToTimeStamp = exports.hrTimeToNanoseconds = exports.hrTimeToMilliseconds = exports.hrTimeToMicroseconds = exports.hrTimeDuration = exports.hrTime = exports.getTimeOrigin = exports.addHrTimes = exports.loggingErrorHandler = exports.setGlobalErrorHandler = exports.globalErrorHandler = exports.sanitizeAttributes = exports.isAttributeValue = exports.AnchoredClock = exports.W3CBaggagePropagator = undefined;
- var W3CBaggagePropagator_1 = require_W3CBaggagePropagator();
- Object.defineProperty(exports, "W3CBaggagePropagator", { enumerable: true, get: function() {
- return W3CBaggagePropagator_1.W3CBaggagePropagator;
- } });
- var anchored_clock_1 = require_anchored_clock();
- Object.defineProperty(exports, "AnchoredClock", { enumerable: true, get: function() {
- return anchored_clock_1.AnchoredClock;
- } });
- var attributes_1 = require_attributes();
- Object.defineProperty(exports, "isAttributeValue", { enumerable: true, get: function() {
- return attributes_1.isAttributeValue;
- } });
- Object.defineProperty(exports, "sanitizeAttributes", { enumerable: true, get: function() {
- return attributes_1.sanitizeAttributes;
- } });
- var global_error_handler_1 = require_global_error_handler();
- Object.defineProperty(exports, "globalErrorHandler", { enumerable: true, get: function() {
- return global_error_handler_1.globalErrorHandler;
- } });
- Object.defineProperty(exports, "setGlobalErrorHandler", { enumerable: true, get: function() {
- return global_error_handler_1.setGlobalErrorHandler;
- } });
- var logging_error_handler_1 = require_logging_error_handler();
- Object.defineProperty(exports, "loggingErrorHandler", { enumerable: true, get: function() {
- return logging_error_handler_1.loggingErrorHandler;
- } });
- var time_1 = require_time();
- Object.defineProperty(exports, "addHrTimes", { enumerable: true, get: function() {
- return time_1.addHrTimes;
- } });
- Object.defineProperty(exports, "getTimeOrigin", { enumerable: true, get: function() {
- return time_1.getTimeOrigin;
- } });
- Object.defineProperty(exports, "hrTime", { enumerable: true, get: function() {
- return time_1.hrTime;
- } });
- Object.defineProperty(exports, "hrTimeDuration", { enumerable: true, get: function() {
- return time_1.hrTimeDuration;
- } });
- Object.defineProperty(exports, "hrTimeToMicroseconds", { enumerable: true, get: function() {
- return time_1.hrTimeToMicroseconds;
- } });
- Object.defineProperty(exports, "hrTimeToMilliseconds", { enumerable: true, get: function() {
- return time_1.hrTimeToMilliseconds;
- } });
- Object.defineProperty(exports, "hrTimeToNanoseconds", { enumerable: true, get: function() {
- return time_1.hrTimeToNanoseconds;
- } });
- Object.defineProperty(exports, "hrTimeToTimeStamp", { enumerable: true, get: function() {
- return time_1.hrTimeToTimeStamp;
- } });
- Object.defineProperty(exports, "isTimeInput", { enumerable: true, get: function() {
- return time_1.isTimeInput;
- } });
- Object.defineProperty(exports, "isTimeInputHrTime", { enumerable: true, get: function() {
- return time_1.isTimeInputHrTime;
- } });
- Object.defineProperty(exports, "millisToHrTime", { enumerable: true, get: function() {
- return time_1.millisToHrTime;
- } });
- Object.defineProperty(exports, "timeInputToHrTime", { enumerable: true, get: function() {
- return time_1.timeInputToHrTime;
- } });
- var timer_util_1 = require_timer_util();
- Object.defineProperty(exports, "unrefTimer", { enumerable: true, get: function() {
- return timer_util_1.unrefTimer;
- } });
- var ExportResult_1 = require_ExportResult();
- Object.defineProperty(exports, "ExportResultCode", { enumerable: true, get: function() {
- return ExportResult_1.ExportResultCode;
- } });
- var utils_1 = require_utils4();
- Object.defineProperty(exports, "parseKeyPairsIntoRecord", { enumerable: true, get: function() {
- return utils_1.parseKeyPairsIntoRecord;
- } });
- var platform_1 = require_platform();
- Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function() {
- return platform_1.SDK_INFO;
- } });
- Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function() {
- return platform_1._globalThis;
- } });
- Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function() {
- return platform_1.getStringFromEnv;
- } });
- Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function() {
- return platform_1.getBooleanFromEnv;
- } });
- Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function() {
- return platform_1.getNumberFromEnv;
- } });
- Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function() {
- return platform_1.getStringListFromEnv;
- } });
- Object.defineProperty(exports, "otperformance", { enumerable: true, get: function() {
- return platform_1.otperformance;
- } });
- var composite_1 = require_composite();
- Object.defineProperty(exports, "CompositePropagator", { enumerable: true, get: function() {
- return composite_1.CompositePropagator;
- } });
- var W3CTraceContextPropagator_1 = require_W3CTraceContextPropagator();
- Object.defineProperty(exports, "TRACE_PARENT_HEADER", { enumerable: true, get: function() {
- return W3CTraceContextPropagator_1.TRACE_PARENT_HEADER;
- } });
- Object.defineProperty(exports, "TRACE_STATE_HEADER", { enumerable: true, get: function() {
- return W3CTraceContextPropagator_1.TRACE_STATE_HEADER;
- } });
- Object.defineProperty(exports, "W3CTraceContextPropagator", { enumerable: true, get: function() {
- return W3CTraceContextPropagator_1.W3CTraceContextPropagator;
- } });
- Object.defineProperty(exports, "parseTraceParent", { enumerable: true, get: function() {
- return W3CTraceContextPropagator_1.parseTraceParent;
- } });
- var rpc_metadata_1 = require_rpc_metadata();
- Object.defineProperty(exports, "RPCType", { enumerable: true, get: function() {
- return rpc_metadata_1.RPCType;
- } });
- Object.defineProperty(exports, "deleteRPCMetadata", { enumerable: true, get: function() {
- return rpc_metadata_1.deleteRPCMetadata;
- } });
- Object.defineProperty(exports, "getRPCMetadata", { enumerable: true, get: function() {
- return rpc_metadata_1.getRPCMetadata;
- } });
- Object.defineProperty(exports, "setRPCMetadata", { enumerable: true, get: function() {
- return rpc_metadata_1.setRPCMetadata;
- } });
- var suppress_tracing_1 = require_suppress_tracing();
- Object.defineProperty(exports, "isTracingSuppressed", { enumerable: true, get: function() {
- return suppress_tracing_1.isTracingSuppressed;
- } });
- Object.defineProperty(exports, "suppressTracing", { enumerable: true, get: function() {
- return suppress_tracing_1.suppressTracing;
- } });
- Object.defineProperty(exports, "unsuppressTracing", { enumerable: true, get: function() {
- return suppress_tracing_1.unsuppressTracing;
- } });
- var TraceState_1 = require_TraceState();
- Object.defineProperty(exports, "TraceState", { enumerable: true, get: function() {
- return TraceState_1.TraceState;
- } });
- var merge_1 = require_merge();
- Object.defineProperty(exports, "merge", { enumerable: true, get: function() {
- return merge_1.merge;
- } });
- var timeout_1 = require_timeout();
- Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function() {
- return timeout_1.TimeoutError;
- } });
- Object.defineProperty(exports, "callWithTimeout", { enumerable: true, get: function() {
- return timeout_1.callWithTimeout;
- } });
- var url_1 = require_url();
- Object.defineProperty(exports, "isUrlIgnored", { enumerable: true, get: function() {
- return url_1.isUrlIgnored;
- } });
- Object.defineProperty(exports, "urlMatches", { enumerable: true, get: function() {
- return url_1.urlMatches;
- } });
- var callback_1 = require_callback();
- Object.defineProperty(exports, "BindOnceFuture", { enumerable: true, get: function() {
- return callback_1.BindOnceFuture;
- } });
- var configuration_1 = require_configuration();
- Object.defineProperty(exports, "diagLogLevelFromString", { enumerable: true, get: function() {
- return configuration_1.diagLogLevelFromString;
- } });
- var exporter_1 = require_exporter();
- exports.internal = {
- _export: exporter_1._export
- };
-});
-
-// node_modules/@opentelemetry/resources/build/src/default-service-name.js
-var require_default_service_name = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports._clearDefaultServiceNameCache = exports.defaultServiceName = undefined;
- var serviceName;
- function defaultServiceName() {
- if (serviceName === undefined) {
- try {
- const argv0 = globalThis.process.argv0;
- serviceName = argv0 ? `unknown_service:${argv0}` : "unknown_service";
- } catch {
- serviceName = "unknown_service";
- }
- }
- return serviceName;
- }
- exports.defaultServiceName = defaultServiceName;
- function _clearDefaultServiceNameCache() {
- serviceName = undefined;
- }
- exports._clearDefaultServiceNameCache = _clearDefaultServiceNameCache;
-});
-
-// node_modules/@opentelemetry/resources/build/src/utils.js
-var require_utils6 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isPromiseLike = undefined;
- var isPromiseLike = (val) => {
- return val !== null && typeof val === "object" && typeof val.then === "function";
- };
- exports.isPromiseLike = isPromiseLike;
-});
-
-// node_modules/@opentelemetry/resources/build/src/ResourceImpl.js
-var require_ResourceImpl = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.defaultResource = exports.emptyResource = exports.resourceFromDetectedResource = exports.resourceFromAttributes = undefined;
- var api_1 = require_src7();
- var core_1 = require_src9();
- var semantic_conventions_1 = require_src8();
- var default_service_name_1 = require_default_service_name();
- var utils_1 = require_utils6();
-
- class ResourceImpl {
- _rawAttributes;
- _asyncAttributesPending = false;
- _schemaUrl;
- _memoizedAttributes;
- static FromAttributeList(attributes, options2) {
- const res = new ResourceImpl({}, options2);
- res._rawAttributes = guardedRawAttributes(attributes);
- res._asyncAttributesPending = attributes.filter(([_, val]) => (0, utils_1.isPromiseLike)(val)).length > 0;
- return res;
- }
- constructor(resource, options2) {
- const attributes = resource.attributes ?? {};
- this._rawAttributes = Object.entries(attributes).map(([k4, v6]) => {
- if ((0, utils_1.isPromiseLike)(v6)) {
- this._asyncAttributesPending = true;
- }
- return [k4, v6];
- });
- this._rawAttributes = guardedRawAttributes(this._rawAttributes);
- this._schemaUrl = validateSchemaUrl(options2?.schemaUrl);
- }
- get asyncAttributesPending() {
- return this._asyncAttributesPending;
- }
- async waitForAsyncAttributes() {
- if (!this.asyncAttributesPending) {
- return;
- }
- for (let i5 = 0;i5 < this._rawAttributes.length; i5++) {
- const [k4, v6] = this._rawAttributes[i5];
- this._rawAttributes[i5] = [k4, (0, utils_1.isPromiseLike)(v6) ? await v6 : v6];
- }
- this._asyncAttributesPending = false;
- }
- get attributes() {
- if (this.asyncAttributesPending) {
- api_1.diag.error("Accessing resource attributes before async attributes settled");
- }
- if (this._memoizedAttributes) {
- return this._memoizedAttributes;
- }
- const attrs = {};
- for (const [k4, v6] of this._rawAttributes) {
- if ((0, utils_1.isPromiseLike)(v6)) {
- api_1.diag.debug(`Unsettled resource attribute ${k4} skipped`);
- continue;
- }
- if (v6 != null) {
- attrs[k4] ??= v6;
- }
- }
- if (!this._asyncAttributesPending) {
- this._memoizedAttributes = attrs;
- }
- return attrs;
- }
- getRawAttributes() {
- return this._rawAttributes;
- }
- get schemaUrl() {
- return this._schemaUrl;
- }
- merge(resource) {
- if (resource == null)
- return this;
- const mergedSchemaUrl = mergeSchemaUrl(this, resource);
- const mergedOptions = mergedSchemaUrl ? { schemaUrl: mergedSchemaUrl } : undefined;
- return ResourceImpl.FromAttributeList([...resource.getRawAttributes(), ...this.getRawAttributes()], mergedOptions);
- }
- }
- function resourceFromAttributes(attributes, options2) {
- return ResourceImpl.FromAttributeList(Object.entries(attributes), options2);
- }
- exports.resourceFromAttributes = resourceFromAttributes;
- function resourceFromDetectedResource(detectedResource, options2) {
- return new ResourceImpl(detectedResource, options2);
- }
- exports.resourceFromDetectedResource = resourceFromDetectedResource;
- function emptyResource() {
- return resourceFromAttributes({});
- }
- exports.emptyResource = emptyResource;
- function defaultResource() {
- return resourceFromAttributes({
- [semantic_conventions_1.ATTR_SERVICE_NAME]: (0, default_service_name_1.defaultServiceName)(),
- [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE],
- [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME],
- [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]
- });
- }
- exports.defaultResource = defaultResource;
- function guardedRawAttributes(attributes) {
- return attributes.map(([k4, v6]) => {
- if ((0, utils_1.isPromiseLike)(v6)) {
- return [
- k4,
- v6.catch((err) => {
- api_1.diag.debug("promise rejection for resource attribute: %s - %s", k4, err);
- return;
- })
- ];
- }
- return [k4, v6];
- });
- }
- function validateSchemaUrl(schemaUrl) {
- if (typeof schemaUrl === "string" || schemaUrl === undefined) {
- return schemaUrl;
- }
- api_1.diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.", schemaUrl);
- return;
- }
- function mergeSchemaUrl(old, updating) {
- const oldSchemaUrl = old?.schemaUrl;
- const updatingSchemaUrl = updating?.schemaUrl;
- const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === "";
- const isUpdatingEmpty = updatingSchemaUrl === undefined || updatingSchemaUrl === "";
- if (isOldEmpty) {
- return updatingSchemaUrl;
- }
- if (isUpdatingEmpty) {
- return oldSchemaUrl;
- }
- if (oldSchemaUrl === updatingSchemaUrl) {
- return oldSchemaUrl;
- }
- api_1.diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.', oldSchemaUrl, updatingSchemaUrl);
- return;
- }
-});
-
-// node_modules/@opentelemetry/resources/build/src/detect-resources.js
-var require_detect_resources = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.detectResources = undefined;
- var api_1 = require_src7();
- var ResourceImpl_1 = require_ResourceImpl();
- var detectResources = (config8 = {}) => {
- const resources = (config8.detectors || []).map((d4) => {
- try {
- const resource = (0, ResourceImpl_1.resourceFromDetectedResource)(d4.detect(config8));
- api_1.diag.debug(`${d4.constructor.name} found resource.`, resource);
- return resource;
- } catch (e4) {
- api_1.diag.debug(`${d4.constructor.name} failed: ${e4.message}`);
- return (0, ResourceImpl_1.emptyResource)();
- }
- });
- return resources.reduce((acc, resource) => acc.merge(resource), (0, ResourceImpl_1.emptyResource)());
- };
- exports.detectResources = detectResources;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js
-var require_EnvDetector = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.envDetector = undefined;
- var api_1 = require_src7();
- var semantic_conventions_1 = require_src8();
- var core_1 = require_src9();
-
- class EnvDetector {
- _MAX_LENGTH = 255;
- _COMMA_SEPARATOR = ",";
- _LABEL_KEY_VALUE_SPLITTER = "=";
- detect(_config) {
- const attributes = {};
- const rawAttributes = (0, core_1.getStringFromEnv)("OTEL_RESOURCE_ATTRIBUTES");
- const serviceName = (0, core_1.getStringFromEnv)("OTEL_SERVICE_NAME");
- if (rawAttributes) {
- try {
- const parsedAttributes = this._parseResourceAttributes(rawAttributes);
- Object.assign(attributes, parsedAttributes);
- } catch (e4) {
- api_1.diag.debug(`EnvDetector failed: ${e4 instanceof Error ? e4.message : e4}`);
- }
- }
- if (serviceName) {
- attributes[semantic_conventions_1.ATTR_SERVICE_NAME] = serviceName;
- }
- return { attributes };
- }
- _parseResourceAttributes(rawEnvAttributes) {
- if (!rawEnvAttributes)
- return {};
- const attributes = {};
- const rawAttributes = rawEnvAttributes.split(this._COMMA_SEPARATOR);
- for (const rawAttribute of rawAttributes) {
- const keyValuePair = rawAttribute.split(this._LABEL_KEY_VALUE_SPLITTER);
- if (keyValuePair.length !== 2) {
- throw new Error(`Invalid format for OTEL_RESOURCE_ATTRIBUTES: "${rawAttribute}". ` + `Expected format: key=value. The ',' and '=' characters must be percent-encoded in keys and values.`);
- }
- const [rawKey, rawValue] = keyValuePair;
- const key = rawKey.trim();
- const value = rawValue.trim();
- if (key.length === 0) {
- throw new Error(`Invalid OTEL_RESOURCE_ATTRIBUTES: empty attribute key in "${rawAttribute}".`);
- }
- let decodedKey;
- let decodedValue;
- try {
- decodedKey = decodeURIComponent(key);
- decodedValue = decodeURIComponent(value);
- } catch (e4) {
- throw new Error(`Failed to percent-decode OTEL_RESOURCE_ATTRIBUTES entry "${rawAttribute}": ${e4 instanceof Error ? e4.message : e4}`);
- }
- if (decodedKey.length > this._MAX_LENGTH) {
- throw new Error(`Attribute key exceeds the maximum length of ${this._MAX_LENGTH} characters: "${decodedKey}".`);
- }
- if (decodedValue.length > this._MAX_LENGTH) {
- throw new Error(`Attribute value exceeds the maximum length of ${this._MAX_LENGTH} characters for key "${decodedKey}".`);
- }
- attributes[decodedKey] = decodedValue;
- }
- return attributes;
- }
- }
- exports.envDetector = new EnvDetector;
-});
-
-// node_modules/@opentelemetry/resources/build/src/semconv.js
-var require_semconv2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ATTR_WEBENGINE_VERSION = exports.ATTR_WEBENGINE_NAME = exports.ATTR_WEBENGINE_DESCRIPTION = exports.ATTR_SERVICE_NAMESPACE = exports.ATTR_SERVICE_INSTANCE_ID = exports.ATTR_PROCESS_RUNTIME_VERSION = exports.ATTR_PROCESS_RUNTIME_NAME = exports.ATTR_PROCESS_RUNTIME_DESCRIPTION = exports.ATTR_PROCESS_PID = exports.ATTR_PROCESS_OWNER = exports.ATTR_PROCESS_EXECUTABLE_PATH = exports.ATTR_PROCESS_EXECUTABLE_NAME = exports.ATTR_PROCESS_COMMAND_ARGS = exports.ATTR_PROCESS_COMMAND = exports.ATTR_OS_VERSION = exports.ATTR_OS_TYPE = exports.ATTR_K8S_POD_NAME = exports.ATTR_K8S_NAMESPACE_NAME = exports.ATTR_K8S_DEPLOYMENT_NAME = exports.ATTR_K8S_CLUSTER_NAME = exports.ATTR_HOST_TYPE = exports.ATTR_HOST_NAME = exports.ATTR_HOST_IMAGE_VERSION = exports.ATTR_HOST_IMAGE_NAME = exports.ATTR_HOST_IMAGE_ID = exports.ATTR_HOST_ID = exports.ATTR_HOST_ARCH = exports.ATTR_CONTAINER_NAME = exports.ATTR_CONTAINER_IMAGE_TAGS = exports.ATTR_CONTAINER_IMAGE_NAME = exports.ATTR_CONTAINER_ID = exports.ATTR_CLOUD_REGION = exports.ATTR_CLOUD_PROVIDER = exports.ATTR_CLOUD_AVAILABILITY_ZONE = exports.ATTR_CLOUD_ACCOUNT_ID = undefined;
- exports.ATTR_CLOUD_ACCOUNT_ID = "cloud.account.id";
- exports.ATTR_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone";
- exports.ATTR_CLOUD_PROVIDER = "cloud.provider";
- exports.ATTR_CLOUD_REGION = "cloud.region";
- exports.ATTR_CONTAINER_ID = "container.id";
- exports.ATTR_CONTAINER_IMAGE_NAME = "container.image.name";
- exports.ATTR_CONTAINER_IMAGE_TAGS = "container.image.tags";
- exports.ATTR_CONTAINER_NAME = "container.name";
- exports.ATTR_HOST_ARCH = "host.arch";
- exports.ATTR_HOST_ID = "host.id";
- exports.ATTR_HOST_IMAGE_ID = "host.image.id";
- exports.ATTR_HOST_IMAGE_NAME = "host.image.name";
- exports.ATTR_HOST_IMAGE_VERSION = "host.image.version";
- exports.ATTR_HOST_NAME = "host.name";
- exports.ATTR_HOST_TYPE = "host.type";
- exports.ATTR_K8S_CLUSTER_NAME = "k8s.cluster.name";
- exports.ATTR_K8S_DEPLOYMENT_NAME = "k8s.deployment.name";
- exports.ATTR_K8S_NAMESPACE_NAME = "k8s.namespace.name";
- exports.ATTR_K8S_POD_NAME = "k8s.pod.name";
- exports.ATTR_OS_TYPE = "os.type";
- exports.ATTR_OS_VERSION = "os.version";
- exports.ATTR_PROCESS_COMMAND = "process.command";
- exports.ATTR_PROCESS_COMMAND_ARGS = "process.command_args";
- exports.ATTR_PROCESS_EXECUTABLE_NAME = "process.executable.name";
- exports.ATTR_PROCESS_EXECUTABLE_PATH = "process.executable.path";
- exports.ATTR_PROCESS_OWNER = "process.owner";
- exports.ATTR_PROCESS_PID = "process.pid";
- exports.ATTR_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description";
- exports.ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name";
- exports.ATTR_PROCESS_RUNTIME_VERSION = "process.runtime.version";
- exports.ATTR_SERVICE_INSTANCE_ID = "service.instance.id";
- exports.ATTR_SERVICE_NAMESPACE = "service.namespace";
- exports.ATTR_WEBENGINE_DESCRIPTION = "webengine.description";
- exports.ATTR_WEBENGINE_NAME = "webengine.name";
- exports.ATTR_WEBENGINE_VERSION = "webengine.version";
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js
-var require_execAsync = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.execAsync = undefined;
- var child_process3 = __require("child_process");
- var util10 = __require("util");
- exports.execAsync = util10.promisify(child_process3.exec);
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js
-var require_getMachineId_darwin = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getMachineId = undefined;
- var execAsync_1 = require_execAsync();
- var api_1 = require_src7();
- async function getMachineId() {
- try {
- const result = await (0, execAsync_1.execAsync)('ioreg -rd1 -c "IOPlatformExpertDevice"');
- const idLine = result.stdout.split(`
-`).find((line) => line.includes("IOPlatformUUID"));
- if (!idLine) {
- return;
- }
- const parts = idLine.split('" = "');
- if (parts.length === 2) {
- return parts[1].slice(0, -1);
- }
- } catch (e4) {
- api_1.diag.debug(`error reading machine id: ${e4}`);
- }
- return;
- }
- exports.getMachineId = getMachineId;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js
-var require_getMachineId_linux = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getMachineId = undefined;
- var fs_1 = __require("fs");
- var api_1 = require_src7();
- async function getMachineId() {
- const paths2 = ["/etc/machine-id", "/var/lib/dbus/machine-id"];
- for (const path14 of paths2) {
- try {
- const result = await fs_1.promises.readFile(path14, { encoding: "utf8" });
- return result.trim();
- } catch (e4) {
- api_1.diag.debug(`error reading machine id: ${e4}`);
- }
- }
- return;
- }
- exports.getMachineId = getMachineId;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js
-var require_getMachineId_bsd = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getMachineId = undefined;
- var fs_1 = __require("fs");
- var execAsync_1 = require_execAsync();
- var api_1 = require_src7();
- async function getMachineId() {
- try {
- const result = await fs_1.promises.readFile("/etc/hostid", { encoding: "utf8" });
- return result.trim();
- } catch (e4) {
- api_1.diag.debug(`error reading machine id: ${e4}`);
- }
- try {
- const result = await (0, execAsync_1.execAsync)("kenv -q smbios.system.uuid");
- return result.stdout.trim();
- } catch (e4) {
- api_1.diag.debug(`error reading machine id: ${e4}`);
- }
- return;
- }
- exports.getMachineId = getMachineId;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js
-var require_getMachineId_win = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getMachineId = undefined;
- var process20 = __require("process");
- var execAsync_1 = require_execAsync();
- var api_1 = require_src7();
- async function getMachineId() {
- const args = "QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid";
- let command12 = "%windir%\\System32\\REG.exe";
- if (process20.arch === "ia32" && "PROCESSOR_ARCHITEW6432" in process20.env) {
- command12 = "%windir%\\sysnative\\cmd.exe /c " + command12;
- }
- try {
- const result = await (0, execAsync_1.execAsync)(`${command12} ${args}`);
- const parts = result.stdout.split("REG_SZ");
- if (parts.length === 2) {
- return parts[1].trim();
- }
- } catch (e4) {
- api_1.diag.debug(`error reading machine id: ${e4}`);
- }
- return;
- }
- exports.getMachineId = getMachineId;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js
-var require_getMachineId_unsupported = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getMachineId = undefined;
- var api_1 = require_src7();
- async function getMachineId() {
- api_1.diag.debug("could not read machine-id: unsupported platform");
- return;
- }
- exports.getMachineId = getMachineId;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js
-var require_getMachineId = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getMachineId = undefined;
- var process20 = __require("process");
- var getMachineIdImpl;
- async function getMachineId() {
- if (!getMachineIdImpl) {
- switch (process20.platform) {
- case "darwin":
- getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_darwin()))).getMachineId;
- break;
- case "linux":
- getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_linux()))).getMachineId;
- break;
- case "freebsd":
- getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_bsd()))).getMachineId;
- break;
- case "win32":
- getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_win()))).getMachineId;
- break;
- default:
- getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_unsupported()))).getMachineId;
- break;
- }
- }
- return getMachineIdImpl();
- }
- exports.getMachineId = getMachineId;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js
-var require_utils7 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.normalizeType = exports.normalizeArch = undefined;
- var normalizeArch5 = (nodeArchString) => {
- switch (nodeArchString) {
- case "arm":
- return "arm32";
- case "ppc":
- return "ppc32";
- case "x64":
- return "amd64";
- default:
- return nodeArchString;
- }
- };
- exports.normalizeArch = normalizeArch5;
- var normalizeType = (nodePlatform) => {
- switch (nodePlatform) {
- case "sunos":
- return "solaris";
- case "win32":
- return "windows";
- default:
- return nodePlatform;
- }
- };
- exports.normalizeType = normalizeType;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js
-var require_HostDetector = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.hostDetector = undefined;
- var semconv_1 = require_semconv2();
- var os_1 = __require("os");
- var getMachineId_1 = require_getMachineId();
- var utils_1 = require_utils7();
-
- class HostDetector {
- detect(_config) {
- const attributes = {
- [semconv_1.ATTR_HOST_NAME]: (0, os_1.hostname)(),
- [semconv_1.ATTR_HOST_ARCH]: (0, utils_1.normalizeArch)((0, os_1.arch)()),
- [semconv_1.ATTR_HOST_ID]: (0, getMachineId_1.getMachineId)()
- };
- return { attributes };
- }
- }
- exports.hostDetector = new HostDetector;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js
-var require_OSDetector = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.osDetector = undefined;
- var semconv_1 = require_semconv2();
- var os_1 = __require("os");
- var utils_1 = require_utils7();
-
- class OSDetector {
- detect(_config) {
- const attributes = {
- [semconv_1.ATTR_OS_TYPE]: (0, utils_1.normalizeType)((0, os_1.platform)()),
- [semconv_1.ATTR_OS_VERSION]: (0, os_1.release)()
- };
- return { attributes };
- }
- }
- exports.osDetector = new OSDetector;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js
-var require_ProcessDetector = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.processDetector = undefined;
- var api_1 = require_src7();
- var semconv_1 = require_semconv2();
- var os5 = __require("os");
-
- class ProcessDetector {
- detect(_config) {
- const attributes = {
- [semconv_1.ATTR_PROCESS_PID]: process.pid,
- [semconv_1.ATTR_PROCESS_EXECUTABLE_NAME]: process.title,
- [semconv_1.ATTR_PROCESS_EXECUTABLE_PATH]: process.execPath,
- [semconv_1.ATTR_PROCESS_COMMAND_ARGS]: [
- process.argv[0],
- ...process.execArgv,
- ...process.argv.slice(1)
- ],
- [semconv_1.ATTR_PROCESS_RUNTIME_VERSION]: process.versions.node,
- [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: "nodejs",
- [semconv_1.ATTR_PROCESS_RUNTIME_DESCRIPTION]: "Node.js"
- };
- if (process.argv.length > 1) {
- attributes[semconv_1.ATTR_PROCESS_COMMAND] = process.argv[1];
- }
- try {
- const userInfo3 = os5.userInfo();
- attributes[semconv_1.ATTR_PROCESS_OWNER] = userInfo3.username;
- } catch (e4) {
- api_1.diag.debug(`error obtaining process owner: ${e4}`);
- }
- return { attributes };
- }
- }
- exports.processDetector = new ProcessDetector;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js
-var require_ServiceInstanceIdDetector = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.serviceInstanceIdDetector = undefined;
- var semconv_1 = require_semconv2();
- var crypto_1 = __require("crypto");
-
- class ServiceInstanceIdDetector {
- detect(_config) {
- return {
- attributes: {
- [semconv_1.ATTR_SERVICE_INSTANCE_ID]: (0, crypto_1.randomUUID)()
- }
- };
- }
- }
- exports.serviceInstanceIdDetector = new ServiceInstanceIdDetector;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js
-var require_node3 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = undefined;
- var HostDetector_1 = require_HostDetector();
- Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function() {
- return HostDetector_1.hostDetector;
- } });
- var OSDetector_1 = require_OSDetector();
- Object.defineProperty(exports, "osDetector", { enumerable: true, get: function() {
- return OSDetector_1.osDetector;
- } });
- var ProcessDetector_1 = require_ProcessDetector();
- Object.defineProperty(exports, "processDetector", { enumerable: true, get: function() {
- return ProcessDetector_1.processDetector;
- } });
- var ServiceInstanceIdDetector_1 = require_ServiceInstanceIdDetector();
- Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function() {
- return ServiceInstanceIdDetector_1.serviceInstanceIdDetector;
- } });
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js
-var require_platform2 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = undefined;
- var node_1 = require_node3();
- Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function() {
- return node_1.hostDetector;
- } });
- Object.defineProperty(exports, "osDetector", { enumerable: true, get: function() {
- return node_1.osDetector;
- } });
- Object.defineProperty(exports, "processDetector", { enumerable: true, get: function() {
- return node_1.processDetector;
- } });
- Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function() {
- return node_1.serviceInstanceIdDetector;
- } });
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js
-var require_NoopDetector = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.noopDetector = exports.NoopDetector = undefined;
-
- class NoopDetector {
- detect() {
- return {
- attributes: {}
- };
- }
- }
- exports.NoopDetector = NoopDetector;
- exports.noopDetector = new NoopDetector;
-});
-
-// node_modules/@opentelemetry/resources/build/src/detectors/index.js
-var require_detectors = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.noopDetector = exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = exports.envDetector = undefined;
- var EnvDetector_1 = require_EnvDetector();
- Object.defineProperty(exports, "envDetector", { enumerable: true, get: function() {
- return EnvDetector_1.envDetector;
- } });
- var platform_1 = require_platform2();
- Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function() {
- return platform_1.hostDetector;
- } });
- Object.defineProperty(exports, "osDetector", { enumerable: true, get: function() {
- return platform_1.osDetector;
- } });
- Object.defineProperty(exports, "processDetector", { enumerable: true, get: function() {
- return platform_1.processDetector;
- } });
- Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function() {
- return platform_1.serviceInstanceIdDetector;
- } });
- var NoopDetector_1 = require_NoopDetector();
- Object.defineProperty(exports, "noopDetector", { enumerable: true, get: function() {
- return NoopDetector_1.noopDetector;
- } });
-});
-
-// node_modules/@opentelemetry/resources/build/src/index.js
-var require_src10 = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.defaultServiceName = exports.emptyResource = exports.defaultResource = exports.resourceFromAttributes = exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = exports.envDetector = exports.detectResources = undefined;
- var detect_resources_1 = require_detect_resources();
- Object.defineProperty(exports, "detectResources", { enumerable: true, get: function() {
- return detect_resources_1.detectResources;
- } });
- var detectors_1 = require_detectors();
- Object.defineProperty(exports, "envDetector", { enumerable: true, get: function() {
- return detectors_1.envDetector;
- } });
- Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function() {
- return detectors_1.hostDetector;
- } });
- Object.defineProperty(exports, "osDetector", { enumerable: true, get: function() {
- return detectors_1.osDetector;
- } });
- Object.defineProperty(exports, "processDetector", { enumerable: true, get: function() {
- return detectors_1.processDetector;
- } });
- Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function() {
- return detectors_1.serviceInstanceIdDetector;
- } });
- var ResourceImpl_1 = require_ResourceImpl();
- Object.defineProperty(exports, "resourceFromAttributes", { enumerable: true, get: function() {
- return ResourceImpl_1.resourceFromAttributes;
- } });
- Object.defineProperty(exports, "defaultResource", { enumerable: true, get: function() {
- return ResourceImpl_1.defaultResource;
- } });
- Object.defineProperty(exports, "emptyResource", { enumerable: true, get: function() {
- return ResourceImpl_1.emptyResource;
- } });
- var default_service_name_1 = require_default_service_name();
- Object.defineProperty(exports, "defaultServiceName", { enumerable: true, get: function() {
- return default_service_name_1.defaultServiceName;
- } });
-});
-
-// node_modules/@opentelemetry/api-logs/build/esm/types/LogRecord.js
-var SeverityNumber;
-var init_LogRecord = __esm(() => {
- (function(SeverityNumber2) {
- SeverityNumber2[SeverityNumber2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
- SeverityNumber2[SeverityNumber2["TRACE"] = 1] = "TRACE";
- SeverityNumber2[SeverityNumber2["TRACE2"] = 2] = "TRACE2";
- SeverityNumber2[SeverityNumber2["TRACE3"] = 3] = "TRACE3";
- SeverityNumber2[SeverityNumber2["TRACE4"] = 4] = "TRACE4";
- SeverityNumber2[SeverityNumber2["DEBUG"] = 5] = "DEBUG";
- SeverityNumber2[SeverityNumber2["DEBUG2"] = 6] = "DEBUG2";
- SeverityNumber2[SeverityNumber2["DEBUG3"] = 7] = "DEBUG3";
- SeverityNumber2[SeverityNumber2["DEBUG4"] = 8] = "DEBUG4";
- SeverityNumber2[SeverityNumber2["INFO"] = 9] = "INFO";
- SeverityNumber2[SeverityNumber2["INFO2"] = 10] = "INFO2";
- SeverityNumber2[SeverityNumber2["INFO3"] = 11] = "INFO3";
- SeverityNumber2[SeverityNumber2["INFO4"] = 12] = "INFO4";
- SeverityNumber2[SeverityNumber2["WARN"] = 13] = "WARN";
- SeverityNumber2[SeverityNumber2["WARN2"] = 14] = "WARN2";
- SeverityNumber2[SeverityNumber2["WARN3"] = 15] = "WARN3";
- SeverityNumber2[SeverityNumber2["WARN4"] = 16] = "WARN4";
- SeverityNumber2[SeverityNumber2["ERROR"] = 17] = "ERROR";
- SeverityNumber2[SeverityNumber2["ERROR2"] = 18] = "ERROR2";
- SeverityNumber2[SeverityNumber2["ERROR3"] = 19] = "ERROR3";
- SeverityNumber2[SeverityNumber2["ERROR4"] = 20] = "ERROR4";
- SeverityNumber2[SeverityNumber2["FATAL"] = 21] = "FATAL";
- SeverityNumber2[SeverityNumber2["FATAL2"] = 22] = "FATAL2";
- SeverityNumber2[SeverityNumber2["FATAL3"] = 23] = "FATAL3";
- SeverityNumber2[SeverityNumber2["FATAL4"] = 24] = "FATAL4";
- })(SeverityNumber || (SeverityNumber = {}));
-});
-
-// node_modules/@opentelemetry/api-logs/build/esm/NoopLogger.js
-class NoopLogger {
- emit(_logRecord) {}
-}
-var NOOP_LOGGER2;
-var init_NoopLogger = __esm(() => {
- NOOP_LOGGER2 = new NoopLogger;
-});
-
-// node_modules/@opentelemetry/api-logs/build/esm/internal/global-utils.js
-function makeGetter(requiredVersion, instance, fallback) {
- return (version6) => version6 === requiredVersion ? instance : fallback;
-}
-var GLOBAL_LOGS_API_KEY, _global2, API_BACKWARDS_COMPATIBILITY_VERSION = 1;
-var init_global_utils = __esm(() => {
- GLOBAL_LOGS_API_KEY = Symbol.for("io.opentelemetry.js.api.logs");
- _global2 = globalThis;
-});
-
-// node_modules/@opentelemetry/api-logs/build/esm/NoopLoggerProvider.js
-class NoopLoggerProvider {
- getLogger(_name, _version, _options) {
- return new NoopLogger;
- }
-}
-var NOOP_LOGGER_PROVIDER;
-var init_NoopLoggerProvider = __esm(() => {
- init_NoopLogger();
- NOOP_LOGGER_PROVIDER = new NoopLoggerProvider;
-});
-
-// node_modules/@opentelemetry/api-logs/build/esm/ProxyLogger.js
-class ProxyLogger {
- constructor(provider5, name3, version6, options2) {
- this._provider = provider5;
- this.name = name3;
- this.version = version6;
- this.options = options2;
- }
- emit(logRecord) {
- this._getLogger().emit(logRecord);
- }
- _getLogger() {
- if (this._delegate) {
- return this._delegate;
- }
- const logger34 = this._provider._getDelegateLogger(this.name, this.version, this.options);
- if (!logger34) {
- return NOOP_LOGGER2;
- }
- this._delegate = logger34;
- return this._delegate;
- }
-}
-var init_ProxyLogger = __esm(() => {
- init_NoopLogger();
-});
-
-// node_modules/@opentelemetry/api-logs/build/esm/ProxyLoggerProvider.js
-class ProxyLoggerProvider {
- getLogger(name3, version6, options2) {
- var _a8;
- return (_a8 = this._getDelegateLogger(name3, version6, options2)) !== null && _a8 !== undefined ? _a8 : new ProxyLogger(this, name3, version6, options2);
- }
- _getDelegate() {
- var _a8;
- return (_a8 = this._delegate) !== null && _a8 !== undefined ? _a8 : NOOP_LOGGER_PROVIDER;
- }
- _setDelegate(delegate) {
- this._delegate = delegate;
- }
- _getDelegateLogger(name3, version6, options2) {
- var _a8;
- return (_a8 = this._delegate) === null || _a8 === undefined ? undefined : _a8.getLogger(name3, version6, options2);
- }
-}
-var init_ProxyLoggerProvider = __esm(() => {
- init_NoopLoggerProvider();
- init_ProxyLogger();
-});
-
-// node_modules/@opentelemetry/api-logs/build/esm/api/logs.js
-class LogsAPI {
- constructor() {
- this._proxyLoggerProvider = new ProxyLoggerProvider;
- }
- static getInstance() {
- if (!this._instance) {
- this._instance = new LogsAPI;
- }
- return this._instance;
- }
- setGlobalLoggerProvider(provider5) {
- if (_global2[GLOBAL_LOGS_API_KEY]) {
- return this.getLoggerProvider();
- }
- _global2[GLOBAL_LOGS_API_KEY] = makeGetter(API_BACKWARDS_COMPATIBILITY_VERSION, provider5, NOOP_LOGGER_PROVIDER);
- this._proxyLoggerProvider._setDelegate(provider5);
- return provider5;
- }
- getLoggerProvider() {
- var _a8, _b2;
- return (_b2 = (_a8 = _global2[GLOBAL_LOGS_API_KEY]) === null || _a8 === undefined ? undefined : _a8.call(_global2, API_BACKWARDS_COMPATIBILITY_VERSION)) !== null && _b2 !== undefined ? _b2 : this._proxyLoggerProvider;
- }
- getLogger(name3, version6, options2) {
- return this.getLoggerProvider().getLogger(name3, version6, options2);
- }
- disable() {
- delete _global2[GLOBAL_LOGS_API_KEY];
- this._proxyLoggerProvider = new ProxyLoggerProvider;
- }
-}
-var init_logs = __esm(() => {
- init_global_utils();
- init_NoopLoggerProvider();
- init_ProxyLoggerProvider();
-});
-
-// node_modules/@opentelemetry/api-logs/build/esm/index.js
-var logs;
-var init_esm10 = __esm(() => {
- init_LogRecord();
- init_NoopLogger();
- init_logs();
- logs = LogsAPI.getInstance();
-});
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/utils/validation.js
-function isLogAttributeValue(val) {
- return isLogAttributeValueInternal(val, new WeakSet);
-}
-function isLogAttributeValueInternal(val, visited) {
- if (val == null) {
- return true;
- }
- if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
- return true;
- }
- if (val instanceof Uint8Array) {
- return true;
- }
- if (typeof val === "object") {
- if (visited.has(val)) {
- return false;
- }
- visited.add(val);
- if (Array.isArray(val)) {
- return val.every((item) => isLogAttributeValueInternal(item, visited));
- }
- const obj = val;
- if (obj.constructor !== Object && obj.constructor !== undefined) {
- return false;
- }
- return Object.values(obj).every((item) => isLogAttributeValueInternal(item, visited));
- }
- return false;
-}
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/LogRecordImpl.js
-class LogRecordImpl {
- hrTime;
- hrTimeObserved;
- spanContext;
- resource;
- instrumentationScope;
- attributes = {};
- _severityText;
- _severityNumber;
- _body;
- _eventName;
- _attributesCount = 0;
- _droppedAttributesCount = 0;
- _isReadonly = false;
- _logRecordLimits;
- set severityText(severityText) {
- if (this._isLogRecordReadonly()) {
- return;
- }
- this._severityText = severityText;
- }
- get severityText() {
- return this._severityText;
- }
- set severityNumber(severityNumber) {
- if (this._isLogRecordReadonly()) {
- return;
- }
- this._severityNumber = severityNumber;
- }
- get severityNumber() {
- return this._severityNumber;
- }
- set body(body) {
- if (this._isLogRecordReadonly()) {
- return;
- }
- this._body = body;
- }
- get body() {
- return this._body;
- }
- get eventName() {
- return this._eventName;
- }
- set eventName(eventName) {
- if (this._isLogRecordReadonly()) {
- return;
- }
- this._eventName = eventName;
- }
- get droppedAttributesCount() {
- return this._droppedAttributesCount;
- }
- constructor(_sharedState, instrumentationScope, logRecord) {
- const { timestamp, observedTimestamp, eventName, severityNumber, severityText, body, attributes = {}, exception, context: context3 } = logRecord;
- const now = Date.now();
- this.hrTime = import_core48.timeInputToHrTime(timestamp ?? now);
- this.hrTimeObserved = import_core48.timeInputToHrTime(observedTimestamp ?? now);
- if (context3) {
- const spanContext = api2.trace.getSpanContext(context3);
- if (spanContext && api2.isSpanContextValid(spanContext)) {
- this.spanContext = spanContext;
- }
- }
- this.severityNumber = severityNumber;
- this.severityText = severityText;
- this.body = body;
- this.resource = _sharedState.resource;
- this.instrumentationScope = instrumentationScope;
- this._logRecordLimits = _sharedState.logRecordLimits;
- this._eventName = eventName;
- this.setAttributes(attributes);
- if (exception != null) {
- this._setException(exception);
- }
- }
- setAttribute(key, value) {
- if (this._isLogRecordReadonly()) {
- return this;
- }
- if (key.length === 0) {
- api2.diag.warn(`Invalid attribute key: ${key}`);
- return this;
- }
- if (!isLogAttributeValue(value)) {
- api2.diag.warn(`Invalid attribute value set for key: ${key}`);
- return this;
- }
- const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);
- if (isNewKey && this._attributesCount >= this._logRecordLimits.attributeCountLimit) {
- this._droppedAttributesCount++;
- if (this._droppedAttributesCount === 1) {
- api2.diag.warn("Dropping extra attributes.");
- }
- return this;
- }
- this.attributes[key] = this._truncateToSize(value);
- if (isNewKey) {
- this._attributesCount++;
- }
- return this;
- }
- setAttributes(attributes) {
- for (const [k4, v6] of Object.entries(attributes)) {
- this.setAttribute(k4, v6);
- }
- return this;
- }
- setBody(body) {
- this.body = body;
- return this;
- }
- setEventName(eventName) {
- this.eventName = eventName;
- return this;
- }
- setSeverityNumber(severityNumber) {
- this.severityNumber = severityNumber;
- return this;
- }
- setSeverityText(severityText) {
- this.severityText = severityText;
- return this;
- }
- _makeReadonly() {
- this._isReadonly = true;
- }
- _truncateToSize(value) {
- const limit = this._logRecordLimits.attributeValueLengthLimit;
- if (limit <= 0) {
- api2.diag.warn(`Attribute value limit must be positive, got ${limit}`);
- return value;
- }
- if (value == null) {
- return value;
- }
- if (typeof value === "string") {
- return this._truncateToLimitUtil(value, limit);
- }
- if (value instanceof Uint8Array) {
- return value;
- }
- if (Array.isArray(value)) {
- return value.map((val) => this._truncateToSize(val));
- }
- if (typeof value === "object") {
- const truncatedObj = {};
- for (const [k4, v6] of Object.entries(value)) {
- truncatedObj[k4] = this._truncateToSize(v6);
- }
- return truncatedObj;
- }
- return value;
- }
- _setException(exception) {
- let hasMinimumAttributes = false;
- if (typeof exception === "string" || typeof exception === "number") {
- if (!Object.hasOwn(this.attributes, import_semantic_conventions.ATTR_EXCEPTION_MESSAGE)) {
- this.setAttribute(import_semantic_conventions.ATTR_EXCEPTION_MESSAGE, String(exception));
- }
- hasMinimumAttributes = true;
- } else if (exception && typeof exception === "object") {
- const exceptionObj = exception;
- if (exceptionObj.code) {
- if (!Object.hasOwn(this.attributes, import_semantic_conventions.ATTR_EXCEPTION_TYPE)) {
- this.setAttribute(import_semantic_conventions.ATTR_EXCEPTION_TYPE, exceptionObj.code.toString());
- }
- hasMinimumAttributes = true;
- } else if (exceptionObj.name) {
- if (!Object.hasOwn(this.attributes, import_semantic_conventions.ATTR_EXCEPTION_TYPE)) {
- this.setAttribute(import_semantic_conventions.ATTR_EXCEPTION_TYPE, exceptionObj.name);
- }
- hasMinimumAttributes = true;
- }
- if (exceptionObj.message) {
- if (!Object.hasOwn(this.attributes, import_semantic_conventions.ATTR_EXCEPTION_MESSAGE)) {
- this.setAttribute(import_semantic_conventions.ATTR_EXCEPTION_MESSAGE, exceptionObj.message);
- }
- hasMinimumAttributes = true;
- }
- if (exceptionObj.stack) {
- if (!Object.hasOwn(this.attributes, import_semantic_conventions.ATTR_EXCEPTION_STACKTRACE)) {
- this.setAttribute(import_semantic_conventions.ATTR_EXCEPTION_STACKTRACE, exceptionObj.stack);
- }
- hasMinimumAttributes = true;
- }
- }
- if (!hasMinimumAttributes) {
- api2.diag.warn(`Failed to record an exception ${exception}`);
- }
- }
- _truncateToLimitUtil(value, limit) {
- if (value.length <= limit) {
- return value;
- }
- return value.substring(0, limit);
- }
- _isLogRecordReadonly() {
- if (this._isReadonly) {
- api2.diag.warn("Can not execute the operation on emitted log record");
- }
- return this._isReadonly;
- }
-}
-var api2, import_core48, import_semantic_conventions;
-var init_LogRecordImpl = __esm(() => {
- api2 = __toESM(require_src7(), 1);
- import_core48 = __toESM(require_src9(), 1);
- import_semantic_conventions = __toESM(require_src8(), 1);
-});
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/Logger.js
-class Logger2 {
- instrumentationScope;
- _sharedState;
- _loggerConfig;
- constructor(instrumentationScope, sharedState) {
- this.instrumentationScope = instrumentationScope;
- this._sharedState = sharedState;
- this._loggerConfig = this._sharedState.getLoggerConfig(this.instrumentationScope);
- }
- emit(logRecord) {
- const loggerConfig = this._loggerConfig;
- const currentContext = logRecord.context || import_api2.context.active();
- const recordSeverity = logRecord.severityNumber ?? SeverityNumber.UNSPECIFIED;
- if (recordSeverity !== SeverityNumber.UNSPECIFIED && recordSeverity < loggerConfig.minimumSeverity) {
- return;
- }
- if (loggerConfig.traceBased) {
- const spanContext = import_api2.trace.getSpanContext(currentContext);
- if (spanContext && import_api2.isSpanContextValid(spanContext)) {
- const isSampled = (spanContext.traceFlags & import_api2.TraceFlags.SAMPLED) === import_api2.TraceFlags.SAMPLED;
- if (!isSampled) {
- return;
- }
- }
- }
- const logRecordInstance = new LogRecordImpl(this._sharedState, this.instrumentationScope, {
- context: currentContext,
- ...logRecord
- });
- this._sharedState.activeProcessor.onEmit(logRecordInstance, currentContext);
- logRecordInstance._makeReadonly();
- }
-}
-var import_api2;
-var init_Logger2 = __esm(() => {
- init_esm10();
- init_LogRecordImpl();
- import_api2 = __toESM(require_src7(), 1);
-});
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/export/NoopLogRecordProcessor.js
-class NoopLogRecordProcessor {
- forceFlush() {
- return Promise.resolve();
- }
- onEmit(_logRecord, _context) {}
- shutdown() {
- return Promise.resolve();
- }
-}
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/MultiLogRecordProcessor.js
-class MultiLogRecordProcessor {
- processors;
- forceFlushTimeoutMillis;
- constructor(processors, forceFlushTimeoutMillis) {
- this.processors = processors;
- this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;
- }
- async forceFlush() {
- const timeout = this.forceFlushTimeoutMillis;
- await Promise.all(this.processors.map((processor) => import_core49.callWithTimeout(processor.forceFlush(), timeout)));
- }
- onEmit(logRecord, context4) {
- this.processors.forEach((processors) => processors.onEmit(logRecord, context4));
- }
- async shutdown() {
- await Promise.all(this.processors.map((processor) => processor.shutdown()));
- }
-}
-var import_core49;
-var init_MultiLogRecordProcessor = __esm(() => {
- import_core49 = __toESM(require_src9(), 1);
-});
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/internal/utils.js
-function getInstrumentationScopeKey(scope) {
- return `${scope.name}@${scope.version || ""}:${scope.schemaUrl || ""}`;
-}
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/internal/LoggerProviderSharedState.js
-class LoggerProviderSharedState {
- loggers = new Map;
- activeProcessor;
- registeredLogRecordProcessors = [];
- resource;
- forceFlushTimeoutMillis;
- logRecordLimits;
- processors;
- _loggerConfigurator;
- _loggerConfigs = new Map;
- constructor(resource, forceFlushTimeoutMillis, logRecordLimits, processors, loggerConfigurator) {
- this.resource = resource;
- this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;
- this.logRecordLimits = logRecordLimits;
- this.processors = processors;
- if (processors.length > 0) {
- this.registeredLogRecordProcessors = processors;
- this.activeProcessor = new MultiLogRecordProcessor(this.registeredLogRecordProcessors, this.forceFlushTimeoutMillis);
- } else {
- this.activeProcessor = new NoopLogRecordProcessor;
- }
- this._loggerConfigurator = loggerConfigurator ?? DEFAULT_LOGGER_CONFIGURATOR;
- }
- getLoggerConfig(instrumentationScope) {
- const key = getInstrumentationScopeKey(instrumentationScope);
- let config8 = this._loggerConfigs.get(key);
- if (config8) {
- return config8;
- }
- config8 = this._loggerConfigurator(instrumentationScope);
- this._loggerConfigs.set(key, config8);
- return config8;
- }
-}
-var DEFAULT_LOGGER_CONFIG, DEFAULT_LOGGER_CONFIGURATOR = () => ({
- ...DEFAULT_LOGGER_CONFIG
-});
-var init_LoggerProviderSharedState = __esm(() => {
- init_esm10();
- init_MultiLogRecordProcessor();
- DEFAULT_LOGGER_CONFIG = {
- disabled: false,
- minimumSeverity: SeverityNumber.UNSPECIFIED,
- traceBased: false
- };
-});
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/LoggerProvider.js
-class LoggerProvider {
- _shutdownOnce;
- _sharedState;
- constructor(config8 = {}) {
- const mergedConfig = {
- resource: config8.resource ?? import_resources.defaultResource(),
- forceFlushTimeoutMillis: config8.forceFlushTimeoutMillis ?? 30000,
- logRecordLimits: {
- attributeCountLimit: config8.logRecordLimits?.attributeCountLimit ?? 128,
- attributeValueLengthLimit: config8.logRecordLimits?.attributeValueLengthLimit ?? Infinity
- },
- loggerConfigurator: config8.loggerConfigurator ?? DEFAULT_LOGGER_CONFIGURATOR,
- processors: config8.processors ?? []
- };
- this._sharedState = new LoggerProviderSharedState(mergedConfig.resource, mergedConfig.forceFlushTimeoutMillis, mergedConfig.logRecordLimits, mergedConfig.processors, mergedConfig.loggerConfigurator);
- this._shutdownOnce = new import_core50.BindOnceFuture(this._shutdown, this);
- }
- getLogger(name3, version6, options2) {
- if (this._shutdownOnce.isCalled) {
- import_api3.diag.warn("A shutdown LoggerProvider cannot provide a Logger");
- return NOOP_LOGGER2;
- }
- if (!name3) {
- import_api3.diag.warn("Logger requested without instrumentation scope name.");
- }
- const loggerName = name3 || DEFAULT_LOGGER_NAME;
- const key = `${loggerName}@${version6 || ""}:${options2?.schemaUrl || ""}`;
- if (!this._sharedState.loggers.has(key)) {
- this._sharedState.loggers.set(key, new Logger2({ name: loggerName, version: version6, schemaUrl: options2?.schemaUrl }, this._sharedState));
- }
- return this._sharedState.loggers.get(key);
- }
- forceFlush() {
- if (this._shutdownOnce.isCalled) {
- import_api3.diag.warn("invalid attempt to force flush after LoggerProvider shutdown");
- return this._shutdownOnce.promise;
- }
- return this._sharedState.activeProcessor.forceFlush();
- }
- shutdown() {
- if (this._shutdownOnce.isCalled) {
- import_api3.diag.warn("shutdown may only be called once per LoggerProvider");
- return this._shutdownOnce.promise;
- }
- return this._shutdownOnce.call();
- }
- _shutdown() {
- return this._sharedState.activeProcessor.shutdown();
- }
-}
-var import_api3, import_resources, import_core50, DEFAULT_LOGGER_NAME = "unknown";
-var init_LoggerProvider = __esm(() => {
- init_esm10();
- init_Logger2();
- init_LoggerProviderSharedState();
- import_api3 = __toESM(require_src7(), 1);
- import_resources = __toESM(require_src10(), 1);
- import_core50 = __toESM(require_src9(), 1);
-});
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/export/ConsoleLogRecordExporter.js
-class ConsoleLogRecordExporter {
- export(logs2, resultCallback) {
- this._sendLogRecords(logs2, resultCallback);
- }
- shutdown() {
- return Promise.resolve();
- }
- _exportInfo(logRecord) {
- return {
- resource: {
- attributes: logRecord.resource.attributes
- },
- instrumentationScope: logRecord.instrumentationScope,
- timestamp: import_core51.hrTimeToMicroseconds(logRecord.hrTime),
- traceId: logRecord.spanContext?.traceId,
- spanId: logRecord.spanContext?.spanId,
- traceFlags: logRecord.spanContext?.traceFlags,
- severityText: logRecord.severityText,
- severityNumber: logRecord.severityNumber,
- eventName: logRecord.eventName,
- body: logRecord.body,
- attributes: logRecord.attributes
- };
- }
- _sendLogRecords(logRecords, done) {
- for (const logRecord of logRecords) {
- console.dir(this._exportInfo(logRecord), { depth: 3 });
- }
- done?.({ code: import_core51.ExportResultCode.SUCCESS });
- }
-}
-var import_core51;
-var init_ConsoleLogRecordExporter = __esm(() => {
- import_core51 = __toESM(require_src9(), 1);
-});
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/export/BatchLogRecordProcessorBase.js
-class BatchLogRecordProcessorBase {
- _maxExportBatchSize;
- _maxQueueSize;
- _scheduledDelayMillis;
- _exportTimeoutMillis;
- _exporter;
- _isExporting = false;
- _finishedLogRecords = [];
- _timer;
- _shutdownOnce;
- constructor(exporter, config8) {
- this._exporter = exporter;
- this._maxExportBatchSize = config8?.maxExportBatchSize ?? 512;
- this._maxQueueSize = config8?.maxQueueSize ?? 2048;
- this._scheduledDelayMillis = config8?.scheduledDelayMillis ?? 5000;
- this._exportTimeoutMillis = config8?.exportTimeoutMillis ?? 30000;
- this._shutdownOnce = new import_core52.BindOnceFuture(this._shutdown, this);
- if (this._maxExportBatchSize > this._maxQueueSize) {
- import_api4.diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");
- this._maxExportBatchSize = this._maxQueueSize;
- }
- }
- onEmit(logRecord) {
- if (this._shutdownOnce.isCalled) {
- return;
- }
- this._addToBuffer(logRecord);
- }
- forceFlush() {
- if (this._shutdownOnce.isCalled) {
- return this._shutdownOnce.promise;
- }
- return this._flushAll();
- }
- shutdown() {
- return this._shutdownOnce.call();
- }
- async _shutdown() {
- this.onShutdown();
- await this._flushAll();
- await this._exporter.shutdown();
- }
- _addToBuffer(logRecord) {
- if (this._finishedLogRecords.length >= this._maxQueueSize) {
- return;
- }
- this._finishedLogRecords.push(logRecord);
- this._maybeStartTimer();
- }
- _flushAll() {
- return new Promise((resolve9, reject) => {
- const promises = [];
- const batchCount = Math.ceil(this._finishedLogRecords.length / this._maxExportBatchSize);
- for (let i5 = 0;i5 < batchCount; i5++) {
- promises.push(this._flushOneBatch());
- }
- Promise.all(promises).then(() => {
- resolve9();
- }).catch(reject);
- });
- }
- _flushOneBatch() {
- this._clearTimer();
- if (this._finishedLogRecords.length === 0) {
- return Promise.resolve();
- }
- return import_core52.callWithTimeout(this._export(this._finishedLogRecords.splice(0, this._maxExportBatchSize)), this._exportTimeoutMillis);
- }
- _maybeStartTimer() {
- if (this._isExporting)
- return;
- const flush = () => {
- this._isExporting = true;
- this._flushOneBatch().then(() => {
- this._isExporting = false;
- if (this._finishedLogRecords.length > 0) {
- this._clearTimer();
- this._maybeStartTimer();
- }
- }).catch((e4) => {
- this._isExporting = false;
- import_core52.globalErrorHandler(e4);
- });
- };
- if (this._finishedLogRecords.length >= this._maxExportBatchSize) {
- return flush();
- }
- if (this._timer !== undefined)
- return;
- this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
- if (typeof this._timer !== "number") {
- this._timer.unref();
- }
- }
- _clearTimer() {
- if (this._timer !== undefined) {
- clearTimeout(this._timer);
- this._timer = undefined;
- }
- }
- _export(logRecords) {
- const doExport = () => import_core52.internal._export(this._exporter, logRecords).then((result) => {
- if (result.code !== import_core52.ExportResultCode.SUCCESS) {
- import_core52.globalErrorHandler(result.error ?? new Error(`BatchLogRecordProcessor: log record export failed (status ${result})`));
- }
- }).catch(import_core52.globalErrorHandler);
- const pendingResources = [];
- for (let i5 = 0;i5 < logRecords.length; i5++) {
- const resource = logRecords[i5].resource;
- if (resource.asyncAttributesPending && typeof resource.waitForAsyncAttributes === "function") {
- pendingResources.push(resource.waitForAsyncAttributes());
- }
- }
- if (pendingResources.length === 0) {
- return doExport();
- } else {
- return Promise.all(pendingResources).then(doExport, import_core52.globalErrorHandler);
- }
- }
-}
-var import_api4, import_core52;
-var init_BatchLogRecordProcessorBase = __esm(() => {
- import_api4 = __toESM(require_src7(), 1);
- import_core52 = __toESM(require_src9(), 1);
-});
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/platform/node/export/BatchLogRecordProcessor.js
-var BatchLogRecordProcessor;
-var init_BatchLogRecordProcessor = __esm(() => {
- init_BatchLogRecordProcessorBase();
- BatchLogRecordProcessor = class BatchLogRecordProcessor extends BatchLogRecordProcessorBase {
- onShutdown() {}
- };
-});
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/platform/node/index.js
-var init_node4 = __esm(() => {
- init_BatchLogRecordProcessor();
-});
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/platform/index.js
-var init_platform3 = __esm(() => {
- init_node4();
-});
-
-// node_modules/@opentelemetry/sdk-logs/build/esm/index.js
-var init_esm11 = __esm(() => {
- init_LoggerProvider();
- init_ConsoleLogRecordExporter();
- init_platform3();
-});
-
-// src/services/analytics/config.ts
-function isAnalyticsDisabled() {
- return isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) || isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) || isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY) || isTelemetryDisabled();
-}
-function isFeedbackSurveyDisabled() {
- return isTelemetryDisabled();
-}
-var init_config8 = __esm(() => {
- init_envUtils();
-});
-
-// src/types/generated/google/protobuf/timestamp.ts
-function createBaseTimestamp() {
- return { seconds: 0, nanos: 0 };
-}
-function isSet2(value) {
- return value !== null && value !== undefined;
-}
-var Timestamp;
-var init_timestamp = __esm(() => {
- Timestamp = {
- fromJSON(object2) {
- return {
- seconds: isSet2(object2.seconds) ? globalThis.Number(object2.seconds) : 0,
- nanos: isSet2(object2.nanos) ? globalThis.Number(object2.nanos) : 0
- };
- },
- toJSON(message) {
- const obj = {};
- if (message.seconds !== undefined) {
- obj.seconds = Math.round(message.seconds);
- }
- if (message.nanos !== undefined) {
- obj.nanos = Math.round(message.nanos);
- }
- return obj;
- },
- create(base2) {
- return Timestamp.fromPartial(base2 ?? {});
- },
- fromPartial(object2) {
- const message = createBaseTimestamp();
- message.seconds = object2.seconds ?? 0;
- message.nanos = object2.nanos ?? 0;
- return message;
- }
- };
-});
-
-// src/types/generated/events_mono/common/v1/auth.ts
-function createBasePublicApiAuth() {
- return { account_id: 0, organization_uuid: "", account_uuid: "" };
-}
-function isSet3(value) {
- return value !== null && value !== undefined;
-}
-var PublicApiAuth;
-var init_auth15 = __esm(() => {
- PublicApiAuth = {
- fromJSON(object2) {
- return {
- account_id: isSet3(object2.account_id) ? globalThis.Number(object2.account_id) : 0,
- organization_uuid: isSet3(object2.organization_uuid) ? globalThis.String(object2.organization_uuid) : "",
- account_uuid: isSet3(object2.account_uuid) ? globalThis.String(object2.account_uuid) : ""
- };
- },
- toJSON(message) {
- const obj = {};
- if (message.account_id !== undefined) {
- obj.account_id = Math.round(message.account_id);
- }
- if (message.organization_uuid !== undefined) {
- obj.organization_uuid = message.organization_uuid;
- }
- if (message.account_uuid !== undefined) {
- obj.account_uuid = message.account_uuid;
- }
- return obj;
- },
- create(base2) {
- return PublicApiAuth.fromPartial(base2 ?? {});
- },
- fromPartial(object2) {
- const message = createBasePublicApiAuth();
- message.account_id = object2.account_id ?? 0;
- message.organization_uuid = object2.organization_uuid ?? "";
- message.account_uuid = object2.account_uuid ?? "";
- return message;
- }
- };
-});
-
-// src/types/generated/events_mono/claude_code/v1/claude_code_internal_event.ts
-function createBaseGitHubActionsMetadata() {
- return { actor_id: "", repository_id: "", repository_owner_id: "" };
-}
-function createBaseEnvironmentMetadata() {
- return {
- platform: "",
- node_version: "",
- terminal: "",
- package_managers: "",
- runtimes: "",
- is_running_with_bun: false,
- is_ci: false,
- is_claubbit: false,
- is_github_action: false,
- is_claude_code_action: false,
- is_claude_ai_auth: false,
- version: "",
- github_event_name: "",
- github_actions_runner_environment: "",
- github_actions_runner_os: "",
- github_action_ref: "",
- wsl_version: "",
- github_actions_metadata: undefined,
- arch: "",
- is_claude_code_remote: false,
- remote_environment_type: "",
- claude_code_container_id: "",
- claude_code_remote_session_id: "",
- tags: [],
- deployment_environment: "",
- is_conductor: false,
- version_base: "",
- coworker_type: "",
- build_time: "",
- is_local_agent_mode: false,
- linux_distro_id: "",
- linux_distro_version: "",
- linux_kernel: "",
- vcs: "",
- platform_raw: ""
- };
-}
-function createBaseSlackContext() {
- return {
- slack_team_id: "",
- is_enterprise_install: false,
- trigger: "",
- creation_method: ""
- };
-}
-function createBaseClaudeCodeInternalEvent() {
- return {
- event_name: "",
- client_timestamp: undefined,
- model: "",
- session_id: "",
- user_type: "",
- betas: "",
- env: undefined,
- entrypoint: "",
- agent_sdk_version: "",
- is_interactive: false,
- client_type: "",
- process: "",
- additional_metadata: "",
- auth: undefined,
- server_timestamp: undefined,
- event_id: "",
- device_id: "",
- swe_bench_run_id: "",
- swe_bench_instance_id: "",
- swe_bench_task_id: "",
- email: "",
- agent_id: "",
- parent_session_id: "",
- agent_type: "",
- slack: undefined,
- team_name: "",
- skill_name: "",
- plugin_name: "",
- marketplace_name: ""
- };
-}
-function fromTimestamp(t4) {
- let millis = (t4.seconds || 0) * 1000;
- millis += (t4.nanos || 0) / 1e6;
- return new globalThis.Date(millis);
-}
-function fromJsonTimestamp(o5) {
- if (o5 instanceof globalThis.Date) {
- return o5;
- } else if (typeof o5 === "string") {
- return new globalThis.Date(o5);
- } else {
- return fromTimestamp(Timestamp.fromJSON(o5));
- }
-}
-function isSet4(value) {
- return value !== null && value !== undefined;
-}
-var GitHubActionsMetadata, EnvironmentMetadata, SlackContext, ClaudeCodeInternalEvent;
-var init_claude_code_internal_event = __esm(() => {
- init_timestamp();
- init_auth15();
- GitHubActionsMetadata = {
- fromJSON(object2) {
- return {
- actor_id: isSet4(object2.actor_id) ? globalThis.String(object2.actor_id) : "",
- repository_id: isSet4(object2.repository_id) ? globalThis.String(object2.repository_id) : "",
- repository_owner_id: isSet4(object2.repository_owner_id) ? globalThis.String(object2.repository_owner_id) : ""
- };
- },
- toJSON(message) {
- const obj = {};
- if (message.actor_id !== undefined) {
- obj.actor_id = message.actor_id;
- }
- if (message.repository_id !== undefined) {
- obj.repository_id = message.repository_id;
- }
- if (message.repository_owner_id !== undefined) {
- obj.repository_owner_id = message.repository_owner_id;
- }
- return obj;
- },
- create(base2) {
- return GitHubActionsMetadata.fromPartial(base2 ?? {});
- },
- fromPartial(object2) {
- const message = createBaseGitHubActionsMetadata();
- message.actor_id = object2.actor_id ?? "";
- message.repository_id = object2.repository_id ?? "";
- message.repository_owner_id = object2.repository_owner_id ?? "";
- return message;
- }
- };
- EnvironmentMetadata = {
- fromJSON(object2) {
- return {
- platform: isSet4(object2.platform) ? globalThis.String(object2.platform) : "",
- node_version: isSet4(object2.node_version) ? globalThis.String(object2.node_version) : "",
- terminal: isSet4(object2.terminal) ? globalThis.String(object2.terminal) : "",
- package_managers: isSet4(object2.package_managers) ? globalThis.String(object2.package_managers) : "",
- runtimes: isSet4(object2.runtimes) ? globalThis.String(object2.runtimes) : "",
- is_running_with_bun: isSet4(object2.is_running_with_bun) ? globalThis.Boolean(object2.is_running_with_bun) : false,
- is_ci: isSet4(object2.is_ci) ? globalThis.Boolean(object2.is_ci) : false,
- is_claubbit: isSet4(object2.is_claubbit) ? globalThis.Boolean(object2.is_claubbit) : false,
- is_github_action: isSet4(object2.is_github_action) ? globalThis.Boolean(object2.is_github_action) : false,
- is_claude_code_action: isSet4(object2.is_claude_code_action) ? globalThis.Boolean(object2.is_claude_code_action) : false,
- is_claude_ai_auth: isSet4(object2.is_claude_ai_auth) ? globalThis.Boolean(object2.is_claude_ai_auth) : false,
- version: isSet4(object2.version) ? globalThis.String(object2.version) : "",
- github_event_name: isSet4(object2.github_event_name) ? globalThis.String(object2.github_event_name) : "",
- github_actions_runner_environment: isSet4(object2.github_actions_runner_environment) ? globalThis.String(object2.github_actions_runner_environment) : "",
- github_actions_runner_os: isSet4(object2.github_actions_runner_os) ? globalThis.String(object2.github_actions_runner_os) : "",
- github_action_ref: isSet4(object2.github_action_ref) ? globalThis.String(object2.github_action_ref) : "",
- wsl_version: isSet4(object2.wsl_version) ? globalThis.String(object2.wsl_version) : "",
- github_actions_metadata: isSet4(object2.github_actions_metadata) ? GitHubActionsMetadata.fromJSON(object2.github_actions_metadata) : undefined,
- arch: isSet4(object2.arch) ? globalThis.String(object2.arch) : "",
- is_claude_code_remote: isSet4(object2.is_claude_code_remote) ? globalThis.Boolean(object2.is_claude_code_remote) : false,
- remote_environment_type: isSet4(object2.remote_environment_type) ? globalThis.String(object2.remote_environment_type) : "",
- claude_code_container_id: isSet4(object2.claude_code_container_id) ? globalThis.String(object2.claude_code_container_id) : "",
- claude_code_remote_session_id: isSet4(object2.claude_code_remote_session_id) ? globalThis.String(object2.claude_code_remote_session_id) : "",
- tags: globalThis.Array.isArray(object2?.tags) ? object2.tags.map((e4) => globalThis.String(e4)) : [],
- deployment_environment: isSet4(object2.deployment_environment) ? globalThis.String(object2.deployment_environment) : "",
- is_conductor: isSet4(object2.is_conductor) ? globalThis.Boolean(object2.is_conductor) : false,
- version_base: isSet4(object2.version_base) ? globalThis.String(object2.version_base) : "",
- coworker_type: isSet4(object2.coworker_type) ? globalThis.String(object2.coworker_type) : "",
- build_time: isSet4(object2.build_time) ? globalThis.String(object2.build_time) : "",
- is_local_agent_mode: isSet4(object2.is_local_agent_mode) ? globalThis.Boolean(object2.is_local_agent_mode) : false,
- linux_distro_id: isSet4(object2.linux_distro_id) ? globalThis.String(object2.linux_distro_id) : "",
- linux_distro_version: isSet4(object2.linux_distro_version) ? globalThis.String(object2.linux_distro_version) : "",
- linux_kernel: isSet4(object2.linux_kernel) ? globalThis.String(object2.linux_kernel) : "",
- vcs: isSet4(object2.vcs) ? globalThis.String(object2.vcs) : "",
- platform_raw: isSet4(object2.platform_raw) ? globalThis.String(object2.platform_raw) : ""
- };
- },
- toJSON(message) {
- const obj = {};
- if (message.platform !== undefined) {
- obj.platform = message.platform;
- }
- if (message.node_version !== undefined) {
- obj.node_version = message.node_version;
- }
- if (message.terminal !== undefined) {
- obj.terminal = message.terminal;
- }
- if (message.package_managers !== undefined) {
- obj.package_managers = message.package_managers;
- }
- if (message.runtimes !== undefined) {
- obj.runtimes = message.runtimes;
- }
- if (message.is_running_with_bun !== undefined) {
- obj.is_running_with_bun = message.is_running_with_bun;
- }
- if (message.is_ci !== undefined) {
- obj.is_ci = message.is_ci;
- }
- if (message.is_claubbit !== undefined) {
- obj.is_claubbit = message.is_claubbit;
- }
- if (message.is_github_action !== undefined) {
- obj.is_github_action = message.is_github_action;
- }
- if (message.is_claude_code_action !== undefined) {
- obj.is_claude_code_action = message.is_claude_code_action;
- }
- if (message.is_claude_ai_auth !== undefined) {
- obj.is_claude_ai_auth = message.is_claude_ai_auth;
- }
- if (message.version !== undefined) {
- obj.version = message.version;
- }
- if (message.github_event_name !== undefined) {
- obj.github_event_name = message.github_event_name;
- }
- if (message.github_actions_runner_environment !== undefined) {
- obj.github_actions_runner_environment = message.github_actions_runner_environment;
- }
- if (message.github_actions_runner_os !== undefined) {
- obj.github_actions_runner_os = message.github_actions_runner_os;
- }
- if (message.github_action_ref !== undefined) {
- obj.github_action_ref = message.github_action_ref;
- }
- if (message.wsl_version !== undefined) {
- obj.wsl_version = message.wsl_version;
- }
- if (message.github_actions_metadata !== undefined) {
- obj.github_actions_metadata = GitHubActionsMetadata.toJSON(message.github_actions_metadata);
- }
- if (message.arch !== undefined) {
- obj.arch = message.arch;
- }
- if (message.is_claude_code_remote !== undefined) {
- obj.is_claude_code_remote = message.is_claude_code_remote;
- }
- if (message.remote_environment_type !== undefined) {
- obj.remote_environment_type = message.remote_environment_type;
- }
- if (message.claude_code_container_id !== undefined) {
- obj.claude_code_container_id = message.claude_code_container_id;
- }
- if (message.claude_code_remote_session_id !== undefined) {
- obj.claude_code_remote_session_id = message.claude_code_remote_session_id;
- }
- if (message.tags?.length) {
- obj.tags = message.tags;
- }
- if (message.deployment_environment !== undefined) {
- obj.deployment_environment = message.deployment_environment;
- }
- if (message.is_conductor !== undefined) {
- obj.is_conductor = message.is_conductor;
- }
- if (message.version_base !== undefined) {
- obj.version_base = message.version_base;
- }
- if (message.coworker_type !== undefined) {
- obj.coworker_type = message.coworker_type;
- }
- if (message.build_time !== undefined) {
- obj.build_time = message.build_time;
- }
- if (message.is_local_agent_mode !== undefined) {
- obj.is_local_agent_mode = message.is_local_agent_mode;
- }
- if (message.linux_distro_id !== undefined) {
- obj.linux_distro_id = message.linux_distro_id;
- }
- if (message.linux_distro_version !== undefined) {
- obj.linux_distro_version = message.linux_distro_version;
- }
- if (message.linux_kernel !== undefined) {
- obj.linux_kernel = message.linux_kernel;
- }
- if (message.vcs !== undefined) {
- obj.vcs = message.vcs;
- }
- if (message.platform_raw !== undefined) {
- obj.platform_raw = message.platform_raw;
- }
- return obj;
- },
- create(base2) {
- return EnvironmentMetadata.fromPartial(base2 ?? {});
- },
- fromPartial(object2) {
- const message = createBaseEnvironmentMetadata();
- message.platform = object2.platform ?? "";
- message.node_version = object2.node_version ?? "";
- message.terminal = object2.terminal ?? "";
- message.package_managers = object2.package_managers ?? "";
- message.runtimes = object2.runtimes ?? "";
- message.is_running_with_bun = object2.is_running_with_bun ?? false;
- message.is_ci = object2.is_ci ?? false;
- message.is_claubbit = object2.is_claubbit ?? false;
- message.is_github_action = object2.is_github_action ?? false;
- message.is_claude_code_action = object2.is_claude_code_action ?? false;
- message.is_claude_ai_auth = object2.is_claude_ai_auth ?? false;
- message.version = object2.version ?? "";
- message.github_event_name = object2.github_event_name ?? "";
- message.github_actions_runner_environment = object2.github_actions_runner_environment ?? "";
- message.github_actions_runner_os = object2.github_actions_runner_os ?? "";
- message.github_action_ref = object2.github_action_ref ?? "";
- message.wsl_version = object2.wsl_version ?? "";
- message.github_actions_metadata = object2.github_actions_metadata !== undefined && object2.github_actions_metadata !== null ? GitHubActionsMetadata.fromPartial(object2.github_actions_metadata) : undefined;
- message.arch = object2.arch ?? "";
- message.is_claude_code_remote = object2.is_claude_code_remote ?? false;
- message.remote_environment_type = object2.remote_environment_type ?? "";
- message.claude_code_container_id = object2.claude_code_container_id ?? "";
- message.claude_code_remote_session_id = object2.claude_code_remote_session_id ?? "";
- message.tags = object2.tags?.map((e4) => e4) || [];
- message.deployment_environment = object2.deployment_environment ?? "";
- message.is_conductor = object2.is_conductor ?? false;
- message.version_base = object2.version_base ?? "";
- message.coworker_type = object2.coworker_type ?? "";
- message.build_time = object2.build_time ?? "";
- message.is_local_agent_mode = object2.is_local_agent_mode ?? false;
- message.linux_distro_id = object2.linux_distro_id ?? "";
- message.linux_distro_version = object2.linux_distro_version ?? "";
- message.linux_kernel = object2.linux_kernel ?? "";
- message.vcs = object2.vcs ?? "";
- message.platform_raw = object2.platform_raw ?? "";
- return message;
- }
- };
- SlackContext = {
- fromJSON(object2) {
- return {
- slack_team_id: isSet4(object2.slack_team_id) ? globalThis.String(object2.slack_team_id) : "",
- is_enterprise_install: isSet4(object2.is_enterprise_install) ? globalThis.Boolean(object2.is_enterprise_install) : false,
- trigger: isSet4(object2.trigger) ? globalThis.String(object2.trigger) : "",
- creation_method: isSet4(object2.creation_method) ? globalThis.String(object2.creation_method) : ""
- };
- },
- toJSON(message) {
- const obj = {};
- if (message.slack_team_id !== undefined) {
- obj.slack_team_id = message.slack_team_id;
- }
- if (message.is_enterprise_install !== undefined) {
- obj.is_enterprise_install = message.is_enterprise_install;
- }
- if (message.trigger !== undefined) {
- obj.trigger = message.trigger;
- }
- if (message.creation_method !== undefined) {
- obj.creation_method = message.creation_method;
- }
- return obj;
- },
- create(base2) {
- return SlackContext.fromPartial(base2 ?? {});
- },
- fromPartial(object2) {
- const message = createBaseSlackContext();
- message.slack_team_id = object2.slack_team_id ?? "";
- message.is_enterprise_install = object2.is_enterprise_install ?? false;
- message.trigger = object2.trigger ?? "";
- message.creation_method = object2.creation_method ?? "";
- return message;
- }
- };
- ClaudeCodeInternalEvent = {
- fromJSON(object2) {
- return {
- event_name: isSet4(object2.event_name) ? globalThis.String(object2.event_name) : "",
- client_timestamp: isSet4(object2.client_timestamp) ? fromJsonTimestamp(object2.client_timestamp) : undefined,
- model: isSet4(object2.model) ? globalThis.String(object2.model) : "",
- session_id: isSet4(object2.session_id) ? globalThis.String(object2.session_id) : "",
- user_type: isSet4(object2.user_type) ? globalThis.String(object2.user_type) : "",
- betas: isSet4(object2.betas) ? globalThis.String(object2.betas) : "",
- env: isSet4(object2.env) ? EnvironmentMetadata.fromJSON(object2.env) : undefined,
- entrypoint: isSet4(object2.entrypoint) ? globalThis.String(object2.entrypoint) : "",
- agent_sdk_version: isSet4(object2.agent_sdk_version) ? globalThis.String(object2.agent_sdk_version) : "",
- is_interactive: isSet4(object2.is_interactive) ? globalThis.Boolean(object2.is_interactive) : false,
- client_type: isSet4(object2.client_type) ? globalThis.String(object2.client_type) : "",
- process: isSet4(object2.process) ? globalThis.String(object2.process) : "",
- additional_metadata: isSet4(object2.additional_metadata) ? globalThis.String(object2.additional_metadata) : "",
- auth: isSet4(object2.auth) ? PublicApiAuth.fromJSON(object2.auth) : undefined,
- server_timestamp: isSet4(object2.server_timestamp) ? fromJsonTimestamp(object2.server_timestamp) : undefined,
- event_id: isSet4(object2.event_id) ? globalThis.String(object2.event_id) : "",
- device_id: isSet4(object2.device_id) ? globalThis.String(object2.device_id) : "",
- swe_bench_run_id: isSet4(object2.swe_bench_run_id) ? globalThis.String(object2.swe_bench_run_id) : "",
- swe_bench_instance_id: isSet4(object2.swe_bench_instance_id) ? globalThis.String(object2.swe_bench_instance_id) : "",
- swe_bench_task_id: isSet4(object2.swe_bench_task_id) ? globalThis.String(object2.swe_bench_task_id) : "",
- email: isSet4(object2.email) ? globalThis.String(object2.email) : "",
- agent_id: isSet4(object2.agent_id) ? globalThis.String(object2.agent_id) : "",
- parent_session_id: isSet4(object2.parent_session_id) ? globalThis.String(object2.parent_session_id) : "",
- agent_type: isSet4(object2.agent_type) ? globalThis.String(object2.agent_type) : "",
- slack: isSet4(object2.slack) ? SlackContext.fromJSON(object2.slack) : undefined,
- team_name: isSet4(object2.team_name) ? globalThis.String(object2.team_name) : "",
- skill_name: isSet4(object2.skill_name) ? globalThis.String(object2.skill_name) : "",
- plugin_name: isSet4(object2.plugin_name) ? globalThis.String(object2.plugin_name) : "",
- marketplace_name: isSet4(object2.marketplace_name) ? globalThis.String(object2.marketplace_name) : ""
- };
- },
- toJSON(message) {
- const obj = {};
- if (message.event_name !== undefined) {
- obj.event_name = message.event_name;
- }
- if (message.client_timestamp !== undefined) {
- obj.client_timestamp = message.client_timestamp.toISOString();
- }
- if (message.model !== undefined) {
- obj.model = message.model;
- }
- if (message.session_id !== undefined) {
- obj.session_id = message.session_id;
- }
- if (message.user_type !== undefined) {
- obj.user_type = message.user_type;
- }
- if (message.betas !== undefined) {
- obj.betas = message.betas;
- }
- if (message.env !== undefined) {
- obj.env = EnvironmentMetadata.toJSON(message.env);
- }
- if (message.entrypoint !== undefined) {
- obj.entrypoint = message.entrypoint;
- }
- if (message.agent_sdk_version !== undefined) {
- obj.agent_sdk_version = message.agent_sdk_version;
- }
- if (message.is_interactive !== undefined) {
- obj.is_interactive = message.is_interactive;
- }
- if (message.client_type !== undefined) {
- obj.client_type = message.client_type;
- }
- if (message.process !== undefined) {
- obj.process = message.process;
- }
- if (message.additional_metadata !== undefined) {
- obj.additional_metadata = message.additional_metadata;
- }
- if (message.auth !== undefined) {
- obj.auth = PublicApiAuth.toJSON(message.auth);
- }
- if (message.server_timestamp !== undefined) {
- obj.server_timestamp = message.server_timestamp.toISOString();
- }
- if (message.event_id !== undefined) {
- obj.event_id = message.event_id;
- }
- if (message.device_id !== undefined) {
- obj.device_id = message.device_id;
- }
- if (message.swe_bench_run_id !== undefined) {
- obj.swe_bench_run_id = message.swe_bench_run_id;
- }
- if (message.swe_bench_instance_id !== undefined) {
- obj.swe_bench_instance_id = message.swe_bench_instance_id;
- }
- if (message.swe_bench_task_id !== undefined) {
- obj.swe_bench_task_id = message.swe_bench_task_id;
- }
- if (message.email !== undefined) {
- obj.email = message.email;
- }
- if (message.agent_id !== undefined) {
- obj.agent_id = message.agent_id;
- }
- if (message.parent_session_id !== undefined) {
- obj.parent_session_id = message.parent_session_id;
- }
- if (message.agent_type !== undefined) {
- obj.agent_type = message.agent_type;
- }
- if (message.slack !== undefined) {
- obj.slack = SlackContext.toJSON(message.slack);
- }
- if (message.team_name !== undefined) {
- obj.team_name = message.team_name;
- }
- if (message.skill_name !== undefined) {
- obj.skill_name = message.skill_name;
- }
- if (message.plugin_name !== undefined) {
- obj.plugin_name = message.plugin_name;
- }
- if (message.marketplace_name !== undefined) {
- obj.marketplace_name = message.marketplace_name;
- }
- return obj;
- },
- create(base2) {
- return ClaudeCodeInternalEvent.fromPartial(base2 ?? {});
- },
- fromPartial(object2) {
- const message = createBaseClaudeCodeInternalEvent();
- message.event_name = object2.event_name ?? "";
- message.client_timestamp = object2.client_timestamp ?? undefined;
- message.model = object2.model ?? "";
- message.session_id = object2.session_id ?? "";
- message.user_type = object2.user_type ?? "";
- message.betas = object2.betas ?? "";
- message.env = object2.env !== undefined && object2.env !== null ? EnvironmentMetadata.fromPartial(object2.env) : undefined;
- message.entrypoint = object2.entrypoint ?? "";
- message.agent_sdk_version = object2.agent_sdk_version ?? "";
- message.is_interactive = object2.is_interactive ?? false;
- message.client_type = object2.client_type ?? "";
- message.process = object2.process ?? "";
- message.additional_metadata = object2.additional_metadata ?? "";
- message.auth = object2.auth !== undefined && object2.auth !== null ? PublicApiAuth.fromPartial(object2.auth) : undefined;
- message.server_timestamp = object2.server_timestamp ?? undefined;
- message.event_id = object2.event_id ?? "";
- message.device_id = object2.device_id ?? "";
- message.swe_bench_run_id = object2.swe_bench_run_id ?? "";
- message.swe_bench_instance_id = object2.swe_bench_instance_id ?? "";
- message.swe_bench_task_id = object2.swe_bench_task_id ?? "";
- message.email = object2.email ?? "";
- message.agent_id = object2.agent_id ?? "";
- message.parent_session_id = object2.parent_session_id ?? "";
- message.agent_type = object2.agent_type ?? "";
- message.slack = object2.slack !== undefined && object2.slack !== null ? SlackContext.fromPartial(object2.slack) : undefined;
- message.team_name = object2.team_name ?? "";
- message.skill_name = object2.skill_name ?? "";
- message.plugin_name = object2.plugin_name ?? "";
- message.marketplace_name = object2.marketplace_name ?? "";
- return message;
- }
- };
-});
-
-// src/types/generated/events_mono/growthbook/v1/growthbook_experiment_event.ts
-function createBaseGrowthbookExperimentEvent() {
- return {
- event_id: "",
- timestamp: undefined,
- experiment_id: "",
- variation_id: 0,
- environment: "",
- user_attributes: "",
- experiment_metadata: "",
- device_id: "",
- auth: undefined,
- session_id: "",
- anonymous_id: "",
- event_metadata_vars: ""
- };
-}
-function fromTimestamp2(t4) {
- let millis = (t4.seconds || 0) * 1000;
- millis += (t4.nanos || 0) / 1e6;
- return new globalThis.Date(millis);
-}
-function fromJsonTimestamp2(o5) {
- if (o5 instanceof globalThis.Date) {
- return o5;
- } else if (typeof o5 === "string") {
- return new globalThis.Date(o5);
- } else {
- return fromTimestamp2(Timestamp.fromJSON(o5));
- }
-}
-function isSet5(value) {
- return value !== null && value !== undefined;
-}
-var GrowthbookExperimentEvent;
-var init_growthbook_experiment_event = __esm(() => {
- init_timestamp();
- init_auth15();
- GrowthbookExperimentEvent = {
- fromJSON(object2) {
- return {
- event_id: isSet5(object2.event_id) ? globalThis.String(object2.event_id) : "",
- timestamp: isSet5(object2.timestamp) ? fromJsonTimestamp2(object2.timestamp) : undefined,
- experiment_id: isSet5(object2.experiment_id) ? globalThis.String(object2.experiment_id) : "",
- variation_id: isSet5(object2.variation_id) ? globalThis.Number(object2.variation_id) : 0,
- environment: isSet5(object2.environment) ? globalThis.String(object2.environment) : "",
- user_attributes: isSet5(object2.user_attributes) ? globalThis.String(object2.user_attributes) : "",
- experiment_metadata: isSet5(object2.experiment_metadata) ? globalThis.String(object2.experiment_metadata) : "",
- device_id: isSet5(object2.device_id) ? globalThis.String(object2.device_id) : "",
- auth: isSet5(object2.auth) ? PublicApiAuth.fromJSON(object2.auth) : undefined,
- session_id: isSet5(object2.session_id) ? globalThis.String(object2.session_id) : "",
- anonymous_id: isSet5(object2.anonymous_id) ? globalThis.String(object2.anonymous_id) : "",
- event_metadata_vars: isSet5(object2.event_metadata_vars) ? globalThis.String(object2.event_metadata_vars) : ""
- };
- },
- toJSON(message) {
- const obj = {};
- if (message.event_id !== undefined) {
- obj.event_id = message.event_id;
- }
- if (message.timestamp !== undefined) {
- obj.timestamp = message.timestamp.toISOString();
- }
- if (message.experiment_id !== undefined) {
- obj.experiment_id = message.experiment_id;
- }
- if (message.variation_id !== undefined) {
- obj.variation_id = Math.round(message.variation_id);
- }
- if (message.environment !== undefined) {
- obj.environment = message.environment;
- }
- if (message.user_attributes !== undefined) {
- obj.user_attributes = message.user_attributes;
- }
- if (message.experiment_metadata !== undefined) {
- obj.experiment_metadata = message.experiment_metadata;
- }
- if (message.device_id !== undefined) {
- obj.device_id = message.device_id;
- }
- if (message.auth !== undefined) {
- obj.auth = PublicApiAuth.toJSON(message.auth);
- }
- if (message.session_id !== undefined) {
- obj.session_id = message.session_id;
- }
- if (message.anonymous_id !== undefined) {
- obj.anonymous_id = message.anonymous_id;
- }
- if (message.event_metadata_vars !== undefined) {
- obj.event_metadata_vars = message.event_metadata_vars;
- }
- return obj;
- },
- create(base2) {
- return GrowthbookExperimentEvent.fromPartial(base2 ?? {});
- },
- fromPartial(object2) {
- const message = createBaseGrowthbookExperimentEvent();
- message.event_id = object2.event_id ?? "";
- message.timestamp = object2.timestamp ?? undefined;
- message.experiment_id = object2.experiment_id ?? "";
- message.variation_id = object2.variation_id ?? 0;
- message.environment = object2.environment ?? "";
- message.user_attributes = object2.user_attributes ?? "";
- message.experiment_metadata = object2.experiment_metadata ?? "";
- message.device_id = object2.device_id ?? "";
- message.auth = object2.auth !== undefined && object2.auth !== null ? PublicApiAuth.fromPartial(object2.auth) : undefined;
- message.session_id = object2.session_id ?? "";
- message.anonymous_id = object2.anonymous_id ?? "";
- message.event_metadata_vars = object2.event_metadata_vars ?? "";
- return message;
- }
- };
-});
-
-// src/utils/genericProcessUtils.ts
-function isProcessRunning(pid) {
- if (pid <= 1)
- return false;
- try {
- process.kill(pid, 0);
- return true;
- } catch {
- return false;
- }
-}
-async function getAncestorPidsAsync(pid, maxDepth = 10) {
- if (process.platform === "win32") {
- const script2 = `
- $pid = ${String(pid)}
- $ancestors = @()
- for ($i = 0; $i -lt ${maxDepth}; $i++) {
- $proc = Get-CimInstance Win32_Process -Filter "ProcessId=$pid" -ErrorAction SilentlyContinue
- if (-not $proc -or -not $proc.ParentProcessId -or $proc.ParentProcessId -eq 0) { break }
- $pid = $proc.ParentProcessId
- $ancestors += $pid
- }
- $ancestors -join ','
- `.trim();
- const result2 = await execFileNoThrowWithCwd("powershell.exe", ["-NoProfile", "-Command", script2], { timeout: 3000 });
- if (result2.code !== 0 || !result2.stdout?.trim()) {
- return [];
- }
- return result2.stdout.trim().split(",").filter(Boolean).map((p4) => parseInt(p4, 10)).filter((p4) => !isNaN(p4));
- }
- const script = `pid=${String(pid)}; for i in $(seq 1 ${maxDepth}); do ppid=$(ps -o ppid= -p $pid 2>/dev/null | tr -d ' '); if [ -z "$ppid" ] || [ "$ppid" = "0" ] || [ "$ppid" = "1" ]; then break; fi; echo $ppid; pid=$ppid; done`;
- const result = await execFileNoThrowWithCwd("sh", ["-c", script], {
- timeout: 3000
- });
- if (result.code !== 0 || !result.stdout?.trim()) {
- return [];
- }
- return result.stdout.trim().split(`
-`).filter(Boolean).map((p4) => parseInt(p4, 10)).filter((p4) => !isNaN(p4));
-}
-function getProcessCommand(pid) {
- try {
- const pidStr = String(pid);
- const command12 = process.platform === "win32" ? `powershell.exe -NoProfile -Command "(Get-CimInstance Win32_Process -Filter \\"ProcessId=${pidStr}\\").CommandLine"` : `ps -o command= -p ${pidStr}`;
- const result = execSyncWithDefaults_DEPRECATED(command12, { timeout: 1000 });
- return result ? result.trim() : null;
- } catch {
- return null;
- }
-}
-async function getAncestorCommandsAsync(pid, maxDepth = 10) {
- if (process.platform === "win32") {
- const script2 = `
- $currentPid = ${String(pid)}
- $commands = @()
- for ($i = 0; $i -lt ${maxDepth}; $i++) {
- $proc = Get-CimInstance Win32_Process -Filter "ProcessId=$currentPid" -ErrorAction SilentlyContinue
- if (-not $proc) { break }
- if ($proc.CommandLine) { $commands += $proc.CommandLine }
- if (-not $proc.ParentProcessId -or $proc.ParentProcessId -eq 0) { break }
- $currentPid = $proc.ParentProcessId
- }
- $commands -join [char]0
- `.trim();
- const result2 = await execFileNoThrowWithCwd("powershell.exe", ["-NoProfile", "-Command", script2], { timeout: 3000 });
- if (result2.code !== 0 || !result2.stdout?.trim()) {
- return [];
- }
- return result2.stdout.split("\x00").filter(Boolean);
- }
- const script = `currentpid=${String(pid)}; for i in $(seq 1 ${maxDepth}); do cmd=$(ps -o command= -p $currentpid 2>/dev/null); if [ -n "$cmd" ]; then printf '%s\\0' "$cmd"; fi; ppid=$(ps -o ppid= -p $currentpid 2>/dev/null | tr -d ' '); if [ -z "$ppid" ] || [ "$ppid" = "0" ] || [ "$ppid" = "1" ]; then break; fi; currentpid=$ppid; done`;
- const result = await execFileNoThrowWithCwd("sh", ["-c", script], {
- timeout: 3000
- });
- if (result.code !== 0 || !result.stdout?.trim()) {
- return [];
- }
- return result.stdout.split("\x00").filter(Boolean);
-}
-var init_genericProcessUtils = __esm(() => {
- init_execFileNoThrow();
-});
-
-// src/utils/envDynamic.ts
-import { stat as stat7 } from "fs/promises";
-function getIsBubblewrapSandbox() {
- return process.platform === "linux" && isEnvTruthy(process.env.CLAUDE_CODE_BUBBLEWRAP);
-}
-function isMuslEnvironment() {
- if (false)
- ;
- if (false)
- ;
- if (process.platform !== "linux")
- return false;
- return muslRuntimeCache ?? false;
-}
-async function detectJetBrainsIDEFromParentProcessAsync() {
- if (jetBrainsIDECache !== undefined) {
- return jetBrainsIDECache;
- }
- if (process.platform === "darwin") {
- jetBrainsIDECache = null;
- return null;
- }
- try {
- const commands7 = await getAncestorCommandsAsync(process.pid, 10);
- for (const command12 of commands7) {
- const lowerCommand = command12.toLowerCase();
- for (const ide of JETBRAINS_IDES) {
- if (lowerCommand.includes(ide)) {
- jetBrainsIDECache = ide;
- return ide;
- }
- }
- }
- } catch {}
- jetBrainsIDECache = null;
- return null;
-}
-async function getTerminalWithJetBrainsDetectionAsync() {
- if (process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm") {
- if (env2.platform !== "darwin") {
- const specificIDE = await detectJetBrainsIDEFromParentProcessAsync();
- return specificIDE || "pycharm";
- }
- }
- return env2.terminal;
-}
-function getTerminalWithJetBrainsDetection() {
- if (process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm") {
- if (env2.platform !== "darwin") {
- if (jetBrainsIDECache !== undefined) {
- return jetBrainsIDECache || "pycharm";
- }
- return "pycharm";
- }
- }
- return env2.terminal;
-}
-async function initJetBrainsDetection() {
- if (process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm") {
- await detectJetBrainsIDEFromParentProcessAsync();
- }
-}
-var getIsDocker, muslRuntimeCache = null, jetBrainsIDECache, envDynamic;
-var init_envDynamic = __esm(() => {
- init_memoize();
- init_env();
- init_envUtils();
- init_execFileNoThrow();
- init_genericProcessUtils();
- getIsDocker = memoize_default(async () => {
- if (process.platform !== "linux")
- return false;
- const { code } = await execFileNoThrow("test", ["-f", "/.dockerenv"]);
- return code === 0;
- });
- if (process.platform === "linux") {
- const muslArch = process.arch === "x64" ? "x86_64" : "aarch64";
- stat7(`/lib/libc.musl-${muslArch}.so.1`).then(() => {
- muslRuntimeCache = true;
- }, () => {
- muslRuntimeCache = false;
- });
- }
- envDynamic = {
- ...env2,
- terminal: getTerminalWithJetBrainsDetection(),
- getIsDocker,
- getIsBubblewrapSandbox,
- isMuslEnvironment,
- getTerminalWithJetBrainsDetectionAsync,
- initJetBrainsDetection
- };
-});
-
-// src/services/mcp/officialRegistry.ts
-function normalizeUrl(url3) {
- try {
- const u5 = new URL(url3);
- u5.search = "";
- return u5.toString().replace(/\/$/, "");
- } catch {
- return;
- }
-}
-async function prefetchOfficialMcpUrls() {
- if (process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC) {
- return;
- }
- try {
- const response7 = await axios_default.get("https://api.anthropic.com/mcp-registry/v0/servers?version=latest&visibility=commercial", { timeout: 5000 });
- const urls = new Set;
- for (const entry of response7.data.servers) {
- for (const remote of entry.server.remotes ?? []) {
- const normalized = normalizeUrl(remote.url);
- if (normalized) {
- urls.add(normalized);
- }
- }
- }
- officialUrls = urls;
- logForDebugging(`[mcp-registry] Loaded ${urls.size} official MCP URLs`);
- } catch (error46) {
- logForDebugging(`Failed to fetch MCP registry: ${errorMessage(error46)}`, {
- level: "error"
- });
- }
-}
-function isOfficialMcpUrl(normalizedUrl) {
- return officialUrls?.has(normalizedUrl) ?? false;
-}
-var officialUrls = undefined;
-var init_officialRegistry = __esm(() => {
- init_axios2();
- init_debug();
- init_errors();
-});
-
-// src/utils/agentSwarmsEnabled.ts
-function isAgentTeamsFlagSet() {
- return process.argv.includes("--agent-teams");
-}
-function isAgentSwarmsEnabled() {
- if (process.env.USER_TYPE === "ant") {
- return true;
- }
- if (!isEnvTruthy(process.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS) && !isAgentTeamsFlagSet()) {
- return false;
- }
- if (!getFeatureValue_CACHED_MAY_BE_STALE("tengu_amber_flint", true)) {
- return false;
- }
- return true;
-}
-var init_agentSwarmsEnabled = __esm(() => {
- init_growthbook();
- init_envUtils();
-});
-
-// src/utils/agentContext.ts
-import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
-function getAgentContext() {
- return agentContextStorage.getStore();
-}
-function runWithAgentContext(context4, fn) {
- return agentContextStorage.run(context4, fn);
-}
-function isSubagentContext(context4) {
- return context4?.agentType === "subagent";
-}
-function getSubagentLogName() {
- const context4 = getAgentContext();
- if (!isSubagentContext(context4) || !context4.subagentName) {
- return;
- }
- return context4.isBuiltIn ? context4.subagentName : "user-defined";
-}
-function consumeInvokingRequestId() {
- const context4 = getAgentContext();
- if (!context4?.invokingRequestId || context4.invocationEmitted) {
- return;
- }
- context4.invocationEmitted = true;
- return {
- invokingRequestId: context4.invokingRequestId,
- invocationKind: context4.invocationKind
- };
-}
-var agentContextStorage;
-var init_agentContext = __esm(() => {
- init_agentSwarmsEnabled();
- agentContextStorage = new AsyncLocalStorage3;
-});
-
-// src/utils/teammateContext.ts
-import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
-function getTeammateContext() {
- return teammateContextStorage.getStore();
-}
-function runWithTeammateContext(context4, fn) {
- return teammateContextStorage.run(context4, fn);
-}
-function isInProcessTeammate() {
- return teammateContextStorage.getStore() !== undefined;
-}
-function createTeammateContext(config8) {
- return {
- ...config8,
- isInProcess: true
- };
-}
-var teammateContextStorage;
-var init_teammateContext = __esm(() => {
- teammateContextStorage = new AsyncLocalStorage4;
-});
-
-// src/utils/teammate.ts
-var exports_teammate = {};
-__export(exports_teammate, {
- waitForTeammatesToBecomeIdle: () => waitForTeammatesToBecomeIdle,
- setDynamicTeamContext: () => setDynamicTeamContext,
- runWithTeammateContext: () => runWithTeammateContext,
- isTeammate: () => isTeammate,
- isTeamLead: () => isTeamLead,
- isPlanModeRequired: () => isPlanModeRequired,
- isInProcessTeammate: () => isInProcessTeammate,
- hasWorkingInProcessTeammates: () => hasWorkingInProcessTeammates,
- hasActiveInProcessTeammates: () => hasActiveInProcessTeammates,
- getTeammateContext: () => getTeammateContext,
- getTeammateColor: () => getTeammateColor,
- getTeamName: () => getTeamName,
- getParentSessionId: () => getParentSessionId2,
- getDynamicTeamContext: () => getDynamicTeamContext,
- getAgentName: () => getAgentName,
- getAgentId: () => getAgentId,
- createTeammateContext: () => createTeammateContext,
- clearDynamicTeamContext: () => clearDynamicTeamContext
-});
-function getParentSessionId2() {
- const inProcessCtx = getTeammateContext();
- if (inProcessCtx)
- return inProcessCtx.parentSessionId;
- return dynamicTeamContext?.parentSessionId;
-}
-function setDynamicTeamContext(context4) {
- dynamicTeamContext = context4;
-}
-function clearDynamicTeamContext() {
- dynamicTeamContext = null;
-}
-function getDynamicTeamContext() {
- return dynamicTeamContext;
-}
-function getAgentId() {
- const inProcessCtx = getTeammateContext();
- if (inProcessCtx)
- return inProcessCtx.agentId;
- return dynamicTeamContext?.agentId;
-}
-function getAgentName() {
- const inProcessCtx = getTeammateContext();
- if (inProcessCtx)
- return inProcessCtx.agentName;
- return dynamicTeamContext?.agentName;
-}
-function getTeamName(teamContext) {
- const inProcessCtx = getTeammateContext();
- if (inProcessCtx)
- return inProcessCtx.teamName;
- if (dynamicTeamContext?.teamName)
- return dynamicTeamContext.teamName;
- return teamContext?.teamName;
-}
-function isTeammate() {
- const inProcessCtx = getTeammateContext();
- if (inProcessCtx)
- return true;
- return !!(dynamicTeamContext?.agentId && dynamicTeamContext?.teamName);
-}
-function getTeammateColor() {
- const inProcessCtx = getTeammateContext();
- if (inProcessCtx)
- return inProcessCtx.color;
- return dynamicTeamContext?.color;
-}
-function isPlanModeRequired() {
- const inProcessCtx = getTeammateContext();
- if (inProcessCtx)
- return inProcessCtx.planModeRequired;
- if (dynamicTeamContext !== null) {
- return dynamicTeamContext.planModeRequired;
- }
- return isEnvTruthy(process.env.CLAUDE_CODE_PLAN_MODE_REQUIRED);
-}
-function isTeamLead(teamContext) {
- if (!teamContext?.leadAgentId) {
- return false;
- }
- const myAgentId = getAgentId();
- const leadAgentId = teamContext.leadAgentId;
- if (myAgentId === leadAgentId) {
- return true;
- }
- if (!myAgentId) {
- return true;
- }
- return false;
-}
-function hasActiveInProcessTeammates(appState) {
- for (const task of Object.values(appState.tasks)) {
- if (task.type === "in_process_teammate" && task.status === "running") {
- return true;
- }
- }
- return false;
-}
-function hasWorkingInProcessTeammates(appState) {
- for (const task of Object.values(appState.tasks)) {
- if (task.type === "in_process_teammate" && task.status === "running" && !task.isIdle) {
- return true;
- }
- }
- return false;
-}
-function waitForTeammatesToBecomeIdle(setAppState, appState) {
- const workingTaskIds = [];
- for (const [taskId, task] of Object.entries(appState.tasks)) {
- if (task.type === "in_process_teammate" && task.status === "running" && !task.isIdle) {
- workingTaskIds.push(taskId);
- }
- }
- if (workingTaskIds.length === 0) {
- return Promise.resolve();
- }
- return new Promise((resolve9) => {
- let remaining = workingTaskIds.length;
- const onIdle = () => {
- remaining--;
- if (remaining === 0) {
- resolve9();
- }
- };
- setAppState((prev) => {
- const newTasks = { ...prev.tasks };
- for (const taskId of workingTaskIds) {
- const task = newTasks[taskId];
- if (task && task.type === "in_process_teammate") {
- if (task.isIdle) {
- onIdle();
- } else {
- newTasks[taskId] = {
- ...task,
- onIdleCallbacks: [...task.onIdleCallbacks ?? [], onIdle]
- };
- }
- }
- }
- return { ...prev, tasks: newTasks };
- });
- });
-}
-var dynamicTeamContext = null;
-var init_teammate = __esm(() => {
- init_teammateContext();
- init_envUtils();
- init_teammateContext();
-});
-
-// src/services/analytics/metadata.ts
-import { extname as extname2 } from "path";
-function sanitizeToolNameForAnalytics(toolName) {
- if (toolName.startsWith("mcp__")) {
- return "mcp_tool";
- }
- return toolName;
-}
-function isToolDetailsLoggingEnabled() {
- return isEnvTruthy(process.env.OTEL_LOG_TOOL_DETAILS);
-}
-function isAnalyticsToolDetailsLoggingEnabled(mcpServerType, mcpServerBaseUrl) {
- if (process.env.CLAUDE_CODE_ENTRYPOINT === "local-agent") {
- return true;
- }
- if (mcpServerType === "claudeai-proxy") {
- return true;
- }
- if (mcpServerBaseUrl && isOfficialMcpUrl(mcpServerBaseUrl)) {
- return true;
- }
- return false;
-}
-function mcpToolDetailsForAnalytics(toolName, mcpServerType, mcpServerBaseUrl) {
- const details = extractMcpToolDetails(toolName);
- if (!details) {
- return {};
- }
- if (!BUILTIN_MCP_SERVER_NAMES.has(details.serverName) && !isAnalyticsToolDetailsLoggingEnabled(mcpServerType, mcpServerBaseUrl)) {
- return {};
- }
- return {
- mcpServerName: details.serverName,
- mcpToolName: details.mcpToolName
- };
-}
-function extractMcpToolDetails(toolName) {
- if (!toolName.startsWith("mcp__")) {
- return;
- }
- const parts = toolName.split("__");
- if (parts.length < 3) {
- return;
- }
- const serverName = parts[1];
- const mcpToolName = parts.slice(2).join("__");
- if (!serverName || !mcpToolName) {
- return;
- }
- return {
- serverName,
- mcpToolName
- };
-}
-function extractSkillName(toolName, input) {
- if (toolName !== "Skill") {
- return;
- }
- if (typeof input === "object" && input !== null && "skill" in input && typeof input.skill === "string") {
- return input.skill;
- }
- return;
-}
-function truncateToolInputValue(value, depth = 0) {
- if (typeof value === "string") {
- if (value.length > TOOL_INPUT_STRING_TRUNCATE_AT) {
- return `${value.slice(0, TOOL_INPUT_STRING_TRUNCATE_TO)}\u2026[${value.length} chars]`;
- }
- return value;
- }
- if (typeof value === "number" || typeof value === "boolean" || value === null || value === undefined) {
- return value;
- }
- if (depth >= TOOL_INPUT_MAX_DEPTH) {
- return "";
- }
- if (Array.isArray(value)) {
- const mapped = value.slice(0, TOOL_INPUT_MAX_COLLECTION_ITEMS).map((v6) => truncateToolInputValue(v6, depth + 1));
- if (value.length > TOOL_INPUT_MAX_COLLECTION_ITEMS) {
- mapped.push(`\u2026[${value.length} items]`);
- }
- return mapped;
- }
- if (typeof value === "object") {
- const entries = Object.entries(value).filter(([k4]) => !k4.startsWith("_"));
- const mapped = entries.slice(0, TOOL_INPUT_MAX_COLLECTION_ITEMS).map(([k4, v6]) => [k4, truncateToolInputValue(v6, depth + 1)]);
- if (entries.length > TOOL_INPUT_MAX_COLLECTION_ITEMS) {
- mapped.push(["\u2026", `${entries.length} keys`]);
- }
- return Object.fromEntries(mapped);
- }
- return String(value);
-}
-function extractToolInputForTelemetry(input) {
- if (!isToolDetailsLoggingEnabled()) {
- return;
- }
- const truncated = truncateToolInputValue(input);
- let json2 = jsonStringify(truncated);
- if (json2.length > TOOL_INPUT_MAX_JSON_CHARS) {
- json2 = json2.slice(0, TOOL_INPUT_MAX_JSON_CHARS) + "\u2026[truncated]";
- }
- return json2;
-}
-function getFileExtensionForAnalytics(filePath) {
- const ext = extname2(filePath).toLowerCase();
- if (!ext || ext === ".") {
- return;
- }
- const extension = ext.slice(1);
- if (extension.length > MAX_FILE_EXTENSION_LENGTH) {
- return "other";
- }
- return extension;
-}
-function getFileExtensionsFromBashCommand(command12, simulatedSedEditFilePath) {
- if (!command12.includes(".") && !simulatedSedEditFilePath)
- return;
- let result;
- const seen = new Set;
- if (simulatedSedEditFilePath) {
- const ext = getFileExtensionForAnalytics(simulatedSedEditFilePath);
- if (ext) {
- seen.add(ext);
- result = ext;
- }
- }
- for (const subcmd of command12.split(COMPOUND_OPERATOR_REGEX)) {
- if (!subcmd)
- continue;
- const tokens = subcmd.split(WHITESPACE_REGEX);
- if (tokens.length < 2)
- continue;
- const firstToken = tokens[0];
- const slashIdx = firstToken.lastIndexOf("/");
- const baseCmd = slashIdx >= 0 ? firstToken.slice(slashIdx + 1) : firstToken;
- if (!FILE_COMMANDS.has(baseCmd))
- continue;
- for (let i5 = 1;i5 < tokens.length; i5++) {
- const arg = tokens[i5];
- if (arg.charCodeAt(0) === 45)
- continue;
- const ext = getFileExtensionForAnalytics(arg);
- if (ext && !seen.has(ext)) {
- seen.add(ext);
- result = result ? result + "," + ext : ext;
- }
- }
- }
- if (!result)
- return;
- return result;
-}
-function getAgentIdentification() {
- const agentContext = getAgentContext();
- if (agentContext) {
- const result = {
- agentId: agentContext.agentId,
- parentSessionId: agentContext.parentSessionId,
- agentType: agentContext.agentType
- };
- if (agentContext.agentType === "teammate") {
- result.teamName = agentContext.teamName;
- }
- return result;
- }
- const agentId = getAgentId();
- const parentSessionId = getParentSessionId2();
- const teamName = getTeamName();
- const isSwarmAgent = isTeammate();
- const agentType = isSwarmAgent ? "teammate" : agentId ? "standalone" : undefined;
- if (agentId || agentType || parentSessionId || teamName) {
- return {
- ...agentId ? { agentId } : {},
- ...agentType ? { agentType } : {},
- ...parentSessionId ? { parentSessionId } : {},
- ...teamName ? { teamName } : {}
- };
- }
- const stateParentSessionId = getParentSessionId();
- if (stateParentSessionId) {
- return { parentSessionId: stateParentSessionId };
- }
- return {};
-}
-function buildProcessMetrics() {
- try {
- const mem = process.memoryUsage();
- const cpu = process.cpuUsage();
- const now = Date.now();
- let cpuPercent;
- if (prevCpuUsage && prevWallTimeMs) {
- const wallDeltaMs = now - prevWallTimeMs;
- if (wallDeltaMs > 0) {
- const userDeltaUs = cpu.user - prevCpuUsage.user;
- const systemDeltaUs = cpu.system - prevCpuUsage.system;
- cpuPercent = (userDeltaUs + systemDeltaUs) / (wallDeltaMs * 1000) * 100;
- }
- }
- prevCpuUsage = cpu;
- prevWallTimeMs = now;
- return {
- uptime: process.uptime(),
- rss: mem.rss,
- heapTotal: mem.heapTotal,
- heapUsed: mem.heapUsed,
- external: mem.external,
- arrayBuffers: mem.arrayBuffers,
- constrainedMemory: process.constrainedMemory(),
- cpuUsage: cpu,
- cpuPercent
- };
- } catch {
- return;
- }
-}
-async function getEventMetadata(options2 = {}) {
- const model = options2.model ? String(options2.model) : getMainLoopModel();
- const betas = typeof options2.betas === "string" ? options2.betas : getModelBetas(model).join(",");
- const [envContext, repoRemoteHash] = await Promise.all([
- buildEnvContext(),
- getRepoRemoteHash()
- ]);
- const processMetrics = buildProcessMetrics();
- const metadata = {
- model,
- sessionId: getSessionId(),
- userType: process.env.USER_TYPE || "",
- ...betas.length > 0 ? { betas } : {},
- envContext,
- ...process.env.CLAUDE_CODE_ENTRYPOINT && {
- entrypoint: process.env.CLAUDE_CODE_ENTRYPOINT
- },
- ...process.env.CLAUDE_AGENT_SDK_VERSION && {
- agentSdkVersion: process.env.CLAUDE_AGENT_SDK_VERSION
- },
- isInteractive: String(getIsInteractive()),
- clientType: getClientType(),
- ...processMetrics && { processMetrics },
- sweBenchRunId: process.env.SWE_BENCH_RUN_ID || "",
- sweBenchInstanceId: process.env.SWE_BENCH_INSTANCE_ID || "",
- sweBenchTaskId: process.env.SWE_BENCH_TASK_ID || "",
- ...getAgentIdentification(),
- ...getSubscriptionType() && {
- subscriptionType: getSubscriptionType()
- },
- ...{},
- ...repoRemoteHash && { rh: repoRemoteHash }
- };
- return metadata;
-}
-function to1PEventFormat(metadata, userMetadata, additionalMetadata = {}) {
- const {
- envContext,
- processMetrics,
- rh,
- kairosActive,
- skillMode,
- observerMode,
- ...coreFields
- } = metadata;
- const env5 = {
- platform: envContext.platform,
- platform_raw: envContext.platformRaw,
- arch: envContext.arch,
- node_version: envContext.nodeVersion,
- terminal: envContext.terminal || "unknown",
- package_managers: envContext.packageManagers,
- runtimes: envContext.runtimes,
- is_running_with_bun: envContext.isRunningWithBun,
- is_ci: envContext.isCi,
- is_claubbit: envContext.isClaubbit,
- is_claude_code_remote: envContext.isClaudeCodeRemote,
- is_local_agent_mode: envContext.isLocalAgentMode,
- is_conductor: envContext.isConductor,
- is_github_action: envContext.isGithubAction,
- is_claude_code_action: envContext.isClaudeCodeAction,
- is_claude_ai_auth: envContext.isClaudeAiAuth,
- version: envContext.version,
- build_time: envContext.buildTime,
- deployment_environment: envContext.deploymentEnvironment
- };
- if (envContext.remoteEnvironmentType) {
- env5.remote_environment_type = envContext.remoteEnvironmentType;
- }
- if (false) {}
- if (envContext.claudeCodeContainerId) {
- env5.claude_code_container_id = envContext.claudeCodeContainerId;
- }
- if (envContext.claudeCodeRemoteSessionId) {
- env5.claude_code_remote_session_id = envContext.claudeCodeRemoteSessionId;
- }
- if (envContext.tags) {
- env5.tags = envContext.tags.split(",").map((t4) => t4.trim()).filter(Boolean);
- }
- if (envContext.githubEventName) {
- env5.github_event_name = envContext.githubEventName;
- }
- if (envContext.githubActionsRunnerEnvironment) {
- env5.github_actions_runner_environment = envContext.githubActionsRunnerEnvironment;
- }
- if (envContext.githubActionsRunnerOs) {
- env5.github_actions_runner_os = envContext.githubActionsRunnerOs;
- }
- if (envContext.githubActionRef) {
- env5.github_action_ref = envContext.githubActionRef;
- }
- if (envContext.wslVersion) {
- env5.wsl_version = envContext.wslVersion;
- }
- if (envContext.linuxDistroId) {
- env5.linux_distro_id = envContext.linuxDistroId;
- }
- if (envContext.linuxDistroVersion) {
- env5.linux_distro_version = envContext.linuxDistroVersion;
- }
- if (envContext.linuxKernel) {
- env5.linux_kernel = envContext.linuxKernel;
- }
- if (envContext.vcs) {
- env5.vcs = envContext.vcs;
- }
- if (envContext.versionBase) {
- env5.version_base = envContext.versionBase;
- }
- const core2 = {
- session_id: coreFields.sessionId,
- model: coreFields.model,
- user_type: coreFields.userType,
- is_interactive: coreFields.isInteractive === "true",
- client_type: coreFields.clientType
- };
- if (coreFields.betas) {
- core2.betas = coreFields.betas;
- }
- if (coreFields.entrypoint) {
- core2.entrypoint = coreFields.entrypoint;
- }
- if (coreFields.agentSdkVersion) {
- core2.agent_sdk_version = coreFields.agentSdkVersion;
- }
- if (coreFields.sweBenchRunId) {
- core2.swe_bench_run_id = coreFields.sweBenchRunId;
- }
- if (coreFields.sweBenchInstanceId) {
- core2.swe_bench_instance_id = coreFields.sweBenchInstanceId;
- }
- if (coreFields.sweBenchTaskId) {
- core2.swe_bench_task_id = coreFields.sweBenchTaskId;
- }
- if (coreFields.agentId) {
- core2.agent_id = coreFields.agentId;
- }
- if (coreFields.parentSessionId) {
- core2.parent_session_id = coreFields.parentSessionId;
- }
- if (coreFields.agentType) {
- core2.agent_type = coreFields.agentType;
- }
- if (coreFields.teamName) {
- core2.team_name = coreFields.teamName;
- }
- if (userMetadata.githubActionsMetadata) {
- const ghMeta = userMetadata.githubActionsMetadata;
- env5.github_actions_metadata = {
- actor_id: ghMeta.actorId,
- repository_id: ghMeta.repositoryId,
- repository_owner_id: ghMeta.repositoryOwnerId
- };
- }
- let auth13;
- if (userMetadata.accountUuid || userMetadata.organizationUuid) {
- auth13 = {
- account_uuid: userMetadata.accountUuid,
- organization_uuid: userMetadata.organizationUuid
- };
- }
- return {
- env: env5,
- ...processMetrics && {
- process: Buffer.from(jsonStringify(processMetrics)).toString("base64")
- },
- ...auth13 && { auth: auth13 },
- core: core2,
- additional: {
- ...rh && { rh },
- ...kairosActive && { is_assistant_mode: true },
- ...skillMode && { skill_mode: skillMode },
- ...observerMode && { observer_mode: observerMode },
- ...additionalMetadata
- }
- };
-}
-var BUILTIN_MCP_SERVER_NAMES, TOOL_INPUT_STRING_TRUNCATE_AT = 512, TOOL_INPUT_STRING_TRUNCATE_TO = 128, TOOL_INPUT_MAX_JSON_CHARS, TOOL_INPUT_MAX_COLLECTION_ITEMS = 20, TOOL_INPUT_MAX_DEPTH = 2, MAX_FILE_EXTENSION_LENGTH = 10, FILE_COMMANDS, COMPOUND_OPERATOR_REGEX, WHITESPACE_REGEX, getVersionBase, buildEnvContext, prevCpuUsage = null, prevWallTimeMs = null;
-var init_metadata = __esm(() => {
- init_memoize();
- init_env();
- init_envDynamic();
- init_betas2();
- init_model();
- init_state();
- init_envUtils();
- init_officialRegistry();
- init_auth14();
- init_git();
- init_platform2();
- init_agentContext();
- init_slowOperations();
- init_teammate();
- BUILTIN_MCP_SERVER_NAMES = new Set([]);
- TOOL_INPUT_MAX_JSON_CHARS = 4 * 1024;
- FILE_COMMANDS = new Set([
- "rm",
- "mv",
- "cp",
- "touch",
- "mkdir",
- "chmod",
- "chown",
- "cat",
- "head",
- "tail",
- "sort",
- "stat",
- "diff",
- "wc",
- "grep",
- "rg",
- "sed"
- ]);
- COMPOUND_OPERATOR_REGEX = /\s*(?:&&|\|\||[;|])\s*/;
- WHITESPACE_REGEX = /\s+/;
- getVersionBase = memoize_default(() => {
- const match = MACRO.VERSION.match(/^\d+\.\d+\.\d+(?:-[a-z]+)?/);
- return match ? match[0] : undefined;
- });
- buildEnvContext = memoize_default(async () => {
- const [packageManagers, runtimes, linuxDistroInfo, vcs] = await Promise.all([
- env2.getPackageManagers(),
- env2.getRuntimes(),
- getLinuxDistroInfo(),
- detectVcs()
- ]);
- return {
- platform: getHostPlatformForAnalytics(),
- platformRaw: process.env.CLAUDE_CODE_HOST_PLATFORM || process.platform,
- arch: env2.arch,
- nodeVersion: env2.nodeVersion,
- terminal: envDynamic.terminal,
- packageManagers: packageManagers.join(","),
- runtimes: runtimes.join(","),
- isRunningWithBun: env2.isRunningWithBun(),
- isCi: isEnvTruthy(process.env.CI),
- isClaubbit: isEnvTruthy(process.env.CLAUBBIT),
- isClaudeCodeRemote: isEnvTruthy(process.env.CLAUDE_CODE_REMOTE),
- isLocalAgentMode: process.env.CLAUDE_CODE_ENTRYPOINT === "local-agent",
- isConductor: env2.isConductor(),
- ...process.env.CLAUDE_CODE_REMOTE_ENVIRONMENT_TYPE && {
- remoteEnvironmentType: process.env.CLAUDE_CODE_REMOTE_ENVIRONMENT_TYPE
- },
- ...{},
- ...process.env.CLAUDE_CODE_CONTAINER_ID && {
- claudeCodeContainerId: process.env.CLAUDE_CODE_CONTAINER_ID
- },
- ...process.env.CLAUDE_CODE_REMOTE_SESSION_ID && {
- claudeCodeRemoteSessionId: process.env.CLAUDE_CODE_REMOTE_SESSION_ID
- },
- ...process.env.CLAUDE_CODE_TAGS && {
- tags: process.env.CLAUDE_CODE_TAGS
- },
- isGithubAction: isEnvTruthy(process.env.GITHUB_ACTIONS),
- isClaudeCodeAction: isEnvTruthy(process.env.CLAUDE_CODE_ACTION),
- isClaudeAiAuth: isClaudeAISubscriber(),
- version: MACRO.VERSION,
- versionBase: getVersionBase(),
- buildTime: MACRO.BUILD_TIME,
- deploymentEnvironment: env2.detectDeploymentEnvironment(),
- ...isEnvTruthy(process.env.GITHUB_ACTIONS) && {
- githubEventName: process.env.GITHUB_EVENT_NAME,
- githubActionsRunnerEnvironment: process.env.RUNNER_ENVIRONMENT,
- githubActionsRunnerOs: process.env.RUNNER_OS,
- githubActionRef: process.env.GITHUB_ACTION_PATH?.includes("claude-code-action/") ? process.env.GITHUB_ACTION_PATH.split("claude-code-action/")[1] : undefined
- },
- ...getWslVersion() && { wslVersion: getWslVersion() },
- ...linuxDistroInfo ?? {},
- ...vcs.length > 0 ? { vcs: vcs.join(",") } : {}
- };
- });
-});
-
-// src/services/analytics/firstPartyEventLoggingExporter.ts
-import { randomUUID as randomUUID5 } from "crypto";
-import { appendFile as appendFile3, mkdir as mkdir5, readdir as readdir4, unlink as unlink2, writeFile as writeFile4 } from "fs/promises";
-import * as path14 from "path";
-function getStorageDir() {
- return path14.join(getClaudeConfigHomeDir(), "telemetry");
-}
-
-class FirstPartyEventLoggingExporter {
- endpoint;
- timeout;
- maxBatchSize;
- skipAuth;
- batchDelayMs;
- baseBackoffDelayMs;
- maxBackoffDelayMs;
- maxAttempts;
- isKilled;
- pendingExports = [];
- isShutdown = false;
- schedule;
- cancelBackoff = null;
- attempts = 0;
- isRetrying = false;
- lastExportErrorContext;
- constructor(options2 = {}) {
- const baseUrl = options2.baseUrl || (process.env.ANTHROPIC_BASE_URL === "https://api-staging.anthropic.com" ? "https://api-staging.anthropic.com" : "https://api.anthropic.com");
- this.endpoint = `${baseUrl}${options2.path || "/api/event_logging/batch"}`;
- this.timeout = options2.timeout || 1e4;
- this.maxBatchSize = options2.maxBatchSize || 200;
- this.skipAuth = options2.skipAuth ?? false;
- this.batchDelayMs = options2.batchDelayMs || 100;
- this.baseBackoffDelayMs = options2.baseBackoffDelayMs || 500;
- this.maxBackoffDelayMs = options2.maxBackoffDelayMs || 30000;
- this.maxAttempts = options2.maxAttempts ?? 8;
- this.isKilled = options2.isKilled ?? (() => false);
- this.schedule = options2.schedule ?? ((fn, ms) => {
- const t4 = setTimeout(fn, ms);
- return () => clearTimeout(t4);
- });
- this.retryPreviousBatches();
- }
- async getQueuedEventCount() {
- return (await this.loadEventsFromCurrentBatch()).length;
- }
- getCurrentBatchFilePath() {
- return path14.join(getStorageDir(), `${FILE_PREFIX}${getSessionId()}.${BATCH_UUID}.json`);
- }
- async loadEventsFromFile(filePath) {
- try {
- return await readJSONLFile(filePath);
- } catch {
- return [];
- }
- }
- async loadEventsFromCurrentBatch() {
- return this.loadEventsFromFile(this.getCurrentBatchFilePath());
- }
- async saveEventsToFile(filePath, events) {
- try {
- if (events.length === 0) {
- try {
- await unlink2(filePath);
- } catch {}
- } else {
- await mkdir5(getStorageDir(), { recursive: true });
- const content = events.map((e4) => jsonStringify(e4)).join(`
-`) + `
-`;
- await writeFile4(filePath, content, "utf8");
- }
- } catch (error46) {
- logError2(error46);
- }
- }
- async appendEventsToFile(filePath, events) {
- if (events.length === 0)
- return;
- try {
- await mkdir5(getStorageDir(), { recursive: true });
- const content = events.map((e4) => jsonStringify(e4)).join(`
-`) + `
-`;
- await appendFile3(filePath, content, "utf8");
- } catch (error46) {
- logError2(error46);
- }
- }
- async deleteFile(filePath) {
- try {
- await unlink2(filePath);
- } catch {}
- }
- async retryPreviousBatches() {
- try {
- const prefix = `${FILE_PREFIX}${getSessionId()}.`;
- let files;
- try {
- files = (await readdir4(getStorageDir())).filter((f4) => f4.startsWith(prefix) && f4.endsWith(".json")).filter((f4) => !f4.includes(BATCH_UUID));
- } catch (e4) {
- if (isFsInaccessible(e4))
- return;
- throw e4;
- }
- for (const file2 of files) {
- const filePath = path14.join(getStorageDir(), file2);
- this.retryFileInBackground(filePath);
- }
- } catch (error46) {
- logError2(error46);
- }
- }
- async retryFileInBackground(filePath) {
- if (this.attempts >= this.maxAttempts) {
- await this.deleteFile(filePath);
- return;
- }
- const events = await this.loadEventsFromFile(filePath);
- if (events.length === 0) {
- await this.deleteFile(filePath);
- return;
- }
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`1P event logging: retrying ${events.length} events from previous batch`);
- }
- const failedEvents = await this.sendEventsInBatches(events);
- if (failedEvents.length === 0) {
- await this.deleteFile(filePath);
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("1P event logging: previous batch retry succeeded");
- }
- } else {
- await this.saveEventsToFile(filePath, failedEvents);
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`1P event logging: previous batch retry failed, ${failedEvents.length} events remain`);
- }
- }
- }
- async export(logs2, resultCallback) {
- if (this.isShutdown) {
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("1P event logging export failed: Exporter has been shutdown");
- }
- resultCallback({
- code: import_core53.ExportResultCode.FAILED,
- error: new Error("Exporter has been shutdown")
- });
- return;
- }
- const exportPromise = this.doExport(logs2, resultCallback);
- this.pendingExports.push(exportPromise);
- exportPromise.finally(() => {
- const index2 = this.pendingExports.indexOf(exportPromise);
- if (index2 > -1) {
- this.pendingExports.splice(index2, 1);
- }
- });
- }
- async doExport(logs2, resultCallback) {
- try {
- const eventLogs = logs2.filter((log3) => log3.instrumentationScope?.name === "com.anthropic.claude_code.events");
- if (eventLogs.length === 0) {
- resultCallback({ code: import_core53.ExportResultCode.SUCCESS });
- return;
- }
- const events = this.transformLogsToEvents(eventLogs).events;
- if (events.length === 0) {
- resultCallback({ code: import_core53.ExportResultCode.SUCCESS });
- return;
- }
- if (this.attempts >= this.maxAttempts) {
- resultCallback({
- code: import_core53.ExportResultCode.FAILED,
- error: new Error(`Dropped ${events.length} events: max attempts (${this.maxAttempts}) reached`)
- });
- return;
- }
- const failedEvents = await this.sendEventsInBatches(events);
- this.attempts++;
- if (failedEvents.length > 0) {
- await this.queueFailedEvents(failedEvents);
- this.scheduleBackoffRetry();
- const context4 = this.lastExportErrorContext ? ` (${this.lastExportErrorContext})` : "";
- resultCallback({
- code: import_core53.ExportResultCode.FAILED,
- error: new Error(`Failed to export ${failedEvents.length} events${context4}`)
- });
- return;
- }
- this.resetBackoff();
- if (await this.getQueuedEventCount() > 0 && !this.isRetrying) {
- this.retryFailedEvents();
- }
- resultCallback({ code: import_core53.ExportResultCode.SUCCESS });
- } catch (error46) {
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`1P event logging export failed: ${errorMessage(error46)}`);
- }
- logError2(error46);
- resultCallback({
- code: import_core53.ExportResultCode.FAILED,
- error: toError(error46)
- });
- }
- }
- async sendEventsInBatches(events) {
- const batches = [];
- for (let i5 = 0;i5 < events.length; i5 += this.maxBatchSize) {
- batches.push(events.slice(i5, i5 + this.maxBatchSize));
- }
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`1P event logging: exporting ${events.length} events in ${batches.length} batch(es)`);
- }
- const failedBatchEvents = [];
- let lastErrorContext;
- for (let i5 = 0;i5 < batches.length; i5++) {
- const batch = batches[i5];
- try {
- await this.sendBatchWithRetry({ events: batch });
- } catch (error46) {
- lastErrorContext = getAxiosErrorContext(error46);
- for (let j4 = i5;j4 < batches.length; j4++) {
- failedBatchEvents.push(...batches[j4]);
- }
- if (process.env.USER_TYPE === "ant") {
- const skipped = batches.length - 1 - i5;
- logForDebugging(`1P event logging: batch ${i5 + 1}/${batches.length} failed (${lastErrorContext}); short-circuiting ${skipped} remaining batch(es)`);
- }
- break;
- }
- if (i5 < batches.length - 1 && this.batchDelayMs > 0) {
- await sleep6(this.batchDelayMs);
- }
- }
- if (failedBatchEvents.length > 0 && lastErrorContext) {
- this.lastExportErrorContext = lastErrorContext;
- }
- return failedBatchEvents;
- }
- async queueFailedEvents(events) {
- const filePath = this.getCurrentBatchFilePath();
- await this.appendEventsToFile(filePath, events);
- const context4 = this.lastExportErrorContext ? ` (${this.lastExportErrorContext})` : "";
- const message = `1P event logging: ${events.length} events failed to export${context4}`;
- logError2(new Error(message));
- }
- scheduleBackoffRetry() {
- if (this.cancelBackoff || this.isRetrying || this.isShutdown) {
- return;
- }
- const delay4 = Math.min(this.baseBackoffDelayMs * this.attempts * this.attempts, this.maxBackoffDelayMs);
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`1P event logging: scheduling backoff retry in ${delay4}ms (attempt ${this.attempts})`);
- }
- this.cancelBackoff = this.schedule(async () => {
- this.cancelBackoff = null;
- await this.retryFailedEvents();
- }, delay4);
- }
- async retryFailedEvents() {
- const filePath = this.getCurrentBatchFilePath();
- while (!this.isShutdown) {
- const events = await this.loadEventsFromFile(filePath);
- if (events.length === 0)
- break;
- if (this.attempts >= this.maxAttempts) {
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`1P event logging: max attempts (${this.maxAttempts}) reached, dropping ${events.length} events`);
- }
- await this.deleteFile(filePath);
- this.resetBackoff();
- return;
- }
- this.isRetrying = true;
- await this.deleteFile(filePath);
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`1P event logging: retrying ${events.length} failed events (attempt ${this.attempts + 1})`);
- }
- const failedEvents = await this.sendEventsInBatches(events);
- this.attempts++;
- this.isRetrying = false;
- if (failedEvents.length > 0) {
- await this.saveEventsToFile(filePath, failedEvents);
- this.scheduleBackoffRetry();
- return;
- }
- this.resetBackoff();
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("1P event logging: backoff retry succeeded");
- }
- }
- }
- resetBackoff() {
- this.attempts = 0;
- if (this.cancelBackoff) {
- this.cancelBackoff();
- this.cancelBackoff = null;
- }
- }
- async sendBatchWithRetry(payload) {
- if (this.isKilled()) {
- throw new Error("firstParty sink killswitch active");
- }
- const baseHeaders = {
- "Content-Type": "application/json",
- "User-Agent": getClaudeCodeUserAgent(),
- "x-service-name": "claude-code"
- };
- const hasTrust = checkHasTrustDialogAccepted() || getIsNonInteractiveSession();
- if (process.env.USER_TYPE === "ant" && !hasTrust) {
- logForDebugging("1P event logging: Trust not accepted");
- }
- let shouldSkipAuth = this.skipAuth || !hasTrust;
- if (!shouldSkipAuth && isClaudeAISubscriber()) {
- const tokens = getClaudeAIOAuthTokens();
- if (!hasProfileScope()) {
- shouldSkipAuth = true;
- } else if (tokens && isOAuthTokenExpired(tokens.expiresAt)) {
- shouldSkipAuth = true;
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("1P event logging: OAuth token expired, skipping auth to avoid 401");
- }
- }
- }
- const authResult = shouldSkipAuth ? { headers: {}, error: "trust not established or Oauth token expired" } : getAuthHeaders2();
- const useAuth = !authResult.error;
- if (!useAuth && process.env.USER_TYPE === "ant") {
- logForDebugging(`1P event logging: auth not available, sending without auth`);
- }
- const headers = useAuth ? { ...baseHeaders, ...authResult.headers } : baseHeaders;
- try {
- const response7 = await axios_default.post(this.endpoint, payload, {
- timeout: this.timeout,
- headers
- });
- this.logSuccess(payload.events.length, useAuth, response7.data);
- return;
- } catch (error46) {
- if (useAuth && axios_default.isAxiosError(error46) && error46.response?.status === 401) {
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("1P event logging: 401 auth error, retrying without auth");
- }
- const response7 = await axios_default.post(this.endpoint, payload, {
- timeout: this.timeout,
- headers: baseHeaders
- });
- this.logSuccess(payload.events.length, false, response7.data);
- return;
- }
- throw error46;
- }
- }
- logSuccess(eventCount, withAuth, responseData) {
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`1P event logging: ${eventCount} events exported successfully${withAuth ? " (with auth)" : " (without auth)"}`);
- logForDebugging(`API Response: ${jsonStringify(responseData, null, 2)}`);
- }
- }
- hrTimeToDate(hrTime) {
- const [seconds, nanoseconds] = hrTime;
- return new Date(seconds * 1000 + nanoseconds / 1e6);
- }
- transformLogsToEvents(logs2) {
- const events = [];
- for (const log3 of logs2) {
- const attributes = log3.attributes || {};
- if (attributes.event_type === "GrowthbookExperimentEvent") {
- const timestamp = this.hrTimeToDate(log3.hrTime);
- const account_uuid = attributes.account_uuid;
- const organization_uuid = attributes.organization_uuid;
- events.push({
- event_type: "GrowthbookExperimentEvent",
- event_data: GrowthbookExperimentEvent.toJSON({
- event_id: attributes.event_id,
- timestamp,
- experiment_id: attributes.experiment_id,
- variation_id: attributes.variation_id,
- environment: attributes.environment,
- user_attributes: attributes.user_attributes,
- experiment_metadata: attributes.experiment_metadata,
- device_id: attributes.device_id,
- session_id: attributes.session_id,
- auth: account_uuid || organization_uuid ? { account_uuid, organization_uuid } : undefined
- })
- });
- continue;
- }
- const eventName = attributes.event_name || log3.body || "unknown";
- const coreMetadata = attributes.core_metadata;
- const userMetadata = attributes.user_metadata;
- const eventMetadata = attributes.event_metadata || {};
- if (!coreMetadata) {
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`1P event logging: core_metadata missing for event ${eventName}`);
- }
- events.push({
- event_type: "ClaudeCodeInternalEvent",
- event_data: ClaudeCodeInternalEvent.toJSON({
- event_id: attributes.event_id,
- event_name: eventName,
- client_timestamp: this.hrTimeToDate(log3.hrTime),
- session_id: getSessionId(),
- additional_metadata: Buffer.from(jsonStringify({
- transform_error: "core_metadata attribute is missing"
- })).toString("base64")
- })
- });
- continue;
- }
- const formatted = to1PEventFormat(coreMetadata, userMetadata, eventMetadata);
- const {
- _PROTO_skill_name,
- _PROTO_plugin_name,
- _PROTO_marketplace_name,
- ...rest
- } = formatted.additional;
- const additionalMetadata = stripProtoFields(rest);
- events.push({
- event_type: "ClaudeCodeInternalEvent",
- event_data: ClaudeCodeInternalEvent.toJSON({
- event_id: attributes.event_id,
- event_name: eventName,
- client_timestamp: this.hrTimeToDate(log3.hrTime),
- device_id: attributes.user_id,
- email: userMetadata?.email,
- auth: formatted.auth,
- ...formatted.core,
- env: formatted.env,
- process: formatted.process,
- skill_name: typeof _PROTO_skill_name === "string" ? _PROTO_skill_name : undefined,
- plugin_name: typeof _PROTO_plugin_name === "string" ? _PROTO_plugin_name : undefined,
- marketplace_name: typeof _PROTO_marketplace_name === "string" ? _PROTO_marketplace_name : undefined,
- additional_metadata: Object.keys(additionalMetadata).length > 0 ? Buffer.from(jsonStringify(additionalMetadata)).toString("base64") : undefined
- })
- });
- }
- return { events };
- }
- async shutdown() {
- this.isShutdown = true;
- this.resetBackoff();
- await this.forceFlush();
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("1P event logging exporter shutdown complete");
- }
- }
- async forceFlush() {
- await Promise.all(this.pendingExports);
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("1P event logging exporter flush complete");
- }
- }
-}
-function getAxiosErrorContext(error46) {
- if (!axios_default.isAxiosError(error46)) {
- return errorMessage(error46);
- }
- const parts = [];
- const requestId = error46.response?.headers?.["request-id"];
- if (requestId) {
- parts.push(`request-id=${requestId}`);
- }
- if (error46.response?.status) {
- parts.push(`status=${error46.response.status}`);
- }
- if (error46.code) {
- parts.push(`code=${error46.code}`);
- }
- if (error46.message) {
- parts.push(error46.message);
- }
- return parts.join(", ");
-}
-var import_core53, BATCH_UUID, FILE_PREFIX = "1p_failed_events.";
-var init_firstPartyEventLoggingExporter = __esm(() => {
- init_axios2();
- init_state();
- init_claude_code_internal_event();
- init_growthbook_experiment_event();
- init_auth14();
- init_config();
- init_debug();
- init_envUtils();
- init_errors();
- init_http8();
- init_json();
- init_log2();
- init_slowOperations();
- init_client7();
- init_analytics();
- init_metadata();
- import_core53 = __toESM(require_src9(), 1);
- BATCH_UUID = randomUUID5();
-});
-
-// src/services/analytics/sinkKillswitch.ts
-function isSinkKilled(sink2) {
- const config8 = getDynamicConfig_CACHED_MAY_BE_STALE(SINK_KILLSWITCH_CONFIG_NAME, {});
- return config8?.[sink2] === true;
-}
-var SINK_KILLSWITCH_CONFIG_NAME = "tengu_frond_boric";
-var init_sinkKillswitch = __esm(() => {
- init_growthbook();
-});
-
-// src/services/analytics/firstPartyEventLogger.ts
-var exports_firstPartyEventLogger = {};
-__export(exports_firstPartyEventLogger, {
- shutdown1PEventLogging: () => shutdown1PEventLogging,
- shouldSampleEvent: () => shouldSampleEvent,
- reinitialize1PEventLoggingIfConfigChanged: () => reinitialize1PEventLoggingIfConfigChanged,
- logGrowthBookExperimentTo1P: () => logGrowthBookExperimentTo1P,
- logEventTo1P: () => logEventTo1P,
- is1PEventLoggingEnabled: () => is1PEventLoggingEnabled,
- initialize1PEventLogging: () => initialize1PEventLogging,
- getEventSamplingConfig: () => getEventSamplingConfig
-});
-import { randomUUID as randomUUID6 } from "crypto";
-function getEventSamplingConfig() {
- return getDynamicConfig_CACHED_MAY_BE_STALE(EVENT_SAMPLING_CONFIG_NAME, {});
-}
-function shouldSampleEvent(eventName) {
- const config8 = getEventSamplingConfig();
- const eventConfig = config8[eventName];
- if (!eventConfig) {
- return null;
- }
- const sampleRate = eventConfig.sample_rate;
- if (typeof sampleRate !== "number" || sampleRate < 0 || sampleRate > 1) {
- return null;
- }
- if (sampleRate >= 1) {
- return null;
- }
- if (sampleRate <= 0) {
- return 0;
- }
- return Math.random() < sampleRate ? sampleRate : 0;
-}
-function getBatchConfig() {
- return getDynamicConfig_CACHED_MAY_BE_STALE(BATCH_CONFIG_NAME, {});
-}
-async function shutdown1PEventLogging() {
- if (!firstPartyEventLoggerProvider) {
- return;
- }
- try {
- await firstPartyEventLoggerProvider.shutdown();
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("1P event logging: final shutdown complete");
- }
- } catch {}
-}
-function is1PEventLoggingEnabled() {
- return !isAnalyticsDisabled();
-}
-async function logEventTo1PAsync(firstPartyEventLogger2, eventName, metadata = {}) {
- try {
- const coreMetadata = await getEventMetadata({
- model: metadata.model,
- betas: metadata.betas
- });
- const attributes = {
- event_name: eventName,
- event_id: randomUUID6(),
- core_metadata: coreMetadata,
- user_metadata: getCoreUserData(true),
- event_metadata: metadata
- };
- const userId = getOrCreateUserID();
- if (userId) {
- attributes.user_id = userId;
- }
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`[ANT-ONLY] 1P event: ${eventName} ${jsonStringify(metadata, null, 0)}`);
- }
- firstPartyEventLogger2.emit({
- body: eventName,
- attributes
- });
- } catch (e4) {
- if (true) {
- throw e4;
- }
- if (process.env.USER_TYPE === "ant") {
- logError2(e4);
- }
- }
-}
-function logEventTo1P(eventName, metadata = {}) {
- if (!is1PEventLoggingEnabled()) {
- return;
- }
- if (!firstPartyEventLogger || isSinkKilled("firstParty")) {
- return;
- }
- logEventTo1PAsync(firstPartyEventLogger, eventName, metadata);
-}
-function getEnvironmentForGrowthBook() {
- return "production";
-}
-function logGrowthBookExperimentTo1P(data) {
- if (!is1PEventLoggingEnabled()) {
- return;
- }
- if (!firstPartyEventLogger || isSinkKilled("firstParty")) {
- return;
- }
- const userId = getOrCreateUserID();
- const { accountUuid, organizationUuid } = getCoreUserData(true);
- const attributes = {
- event_type: "GrowthbookExperimentEvent",
- event_id: randomUUID6(),
- experiment_id: data.experimentId,
- variation_id: data.variationId,
- ...userId && { device_id: userId },
- ...accountUuid && { account_uuid: accountUuid },
- ...organizationUuid && { organization_uuid: organizationUuid },
- ...data.userAttributes && {
- session_id: data.userAttributes.sessionId,
- user_attributes: jsonStringify(data.userAttributes)
- },
- ...data.experimentMetadata && {
- experiment_metadata: jsonStringify(data.experimentMetadata)
- },
- environment: getEnvironmentForGrowthBook()
- };
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`[ANT-ONLY] 1P GrowthBook experiment: ${data.experimentId} variation=${data.variationId}`);
- }
- firstPartyEventLogger.emit({
- body: "growthbook_experiment",
- attributes
- });
-}
-function initialize1PEventLogging() {
- profileCheckpoint("1p_event_logging_start");
- const enabled2 = is1PEventLoggingEnabled();
- if (!enabled2) {
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("1P event logging not enabled");
- }
- return;
- }
- const batchConfig = getBatchConfig();
- lastBatchConfig = batchConfig;
- profileCheckpoint("1p_event_after_growthbook_config");
- const scheduledDelayMillis = batchConfig.scheduledDelayMillis || parseInt(process.env.OTEL_LOGS_EXPORT_INTERVAL || DEFAULT_LOGS_EXPORT_INTERVAL_MS.toString());
- const maxExportBatchSize = batchConfig.maxExportBatchSize || DEFAULT_MAX_EXPORT_BATCH_SIZE;
- const maxQueueSize = batchConfig.maxQueueSize || DEFAULT_MAX_QUEUE_SIZE;
- const platform3 = getPlatform();
- const attributes = {
- [import_semantic_conventions2.ATTR_SERVICE_NAME]: "claude-code",
- [import_semantic_conventions2.ATTR_SERVICE_VERSION]: MACRO.VERSION
- };
- if (platform3 === "wsl") {
- const wslVersion = getWslVersion();
- if (wslVersion) {
- attributes["wsl.version"] = wslVersion;
- }
- }
- const resource = import_resources2.resourceFromAttributes(attributes);
- const eventLoggingExporter = new FirstPartyEventLoggingExporter({
- maxBatchSize: maxExportBatchSize,
- skipAuth: batchConfig.skipAuth,
- maxAttempts: batchConfig.maxAttempts,
- path: batchConfig.path,
- baseUrl: batchConfig.baseUrl,
- isKilled: () => isSinkKilled("firstParty")
- });
- firstPartyEventLoggerProvider = new LoggerProvider({
- resource,
- processors: [
- new BatchLogRecordProcessor(eventLoggingExporter, {
- scheduledDelayMillis,
- maxExportBatchSize,
- maxQueueSize
- })
- ]
- });
- firstPartyEventLogger = firstPartyEventLoggerProvider.getLogger("com.anthropic.claude_code.events", MACRO.VERSION);
-}
-async function reinitialize1PEventLoggingIfConfigChanged() {
- if (!is1PEventLoggingEnabled() || !firstPartyEventLoggerProvider) {
- return;
- }
- const newConfig = getBatchConfig();
- if (isEqual_default(newConfig, lastBatchConfig)) {
- return;
- }
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`1P event logging: ${BATCH_CONFIG_NAME} changed, reinitializing`);
- }
- const oldProvider = firstPartyEventLoggerProvider;
- const oldLogger = firstPartyEventLogger;
- firstPartyEventLogger = null;
- try {
- await oldProvider.forceFlush();
- } catch {}
- firstPartyEventLoggerProvider = null;
- try {
- initialize1PEventLogging();
- } catch (e4) {
- firstPartyEventLoggerProvider = oldProvider;
- firstPartyEventLogger = oldLogger;
- logError2(e4);
- return;
- }
- oldProvider.shutdown().catch(() => {});
-}
-var import_resources2, import_semantic_conventions2, EVENT_SAMPLING_CONFIG_NAME = "tengu_event_sampling_config", BATCH_CONFIG_NAME = "tengu_1p_event_batch_config", firstPartyEventLogger = null, firstPartyEventLoggerProvider = null, lastBatchConfig = null, DEFAULT_LOGS_EXPORT_INTERVAL_MS = 1e4, DEFAULT_MAX_EXPORT_BATCH_SIZE = 200, DEFAULT_MAX_QUEUE_SIZE = 8192;
-var init_firstPartyEventLogger = __esm(() => {
- init_esm11();
- init_lodash();
- init_config();
- init_debug();
- init_log2();
- init_platform2();
- init_slowOperations();
- init_startupProfiler();
- init_user();
- init_config8();
- init_firstPartyEventLoggingExporter();
- init_growthbook();
- init_metadata();
- init_sinkKillswitch();
- import_resources2 = __toESM(require_src10(), 1);
- import_semantic_conventions2 = __toESM(require_src8(), 1);
-});
-
-// src/services/analytics/growthbook.ts
-var exports_growthbook = {};
-__export(exports_growthbook, {
- stopPeriodicGrowthBookRefresh: () => stopPeriodicGrowthBookRefresh,
- setupPeriodicGrowthBookRefresh: () => setupPeriodicGrowthBookRefresh,
- setGrowthBookConfigOverride: () => setGrowthBookConfigOverride,
- resetGrowthBook: () => resetGrowthBook,
- refreshGrowthBookFeatures: () => refreshGrowthBookFeatures,
- refreshGrowthBookAfterAuthChange: () => refreshGrowthBookAfterAuthChange,
- onGrowthBookRefresh: () => onGrowthBookRefresh,
- initializeGrowthBook: () => initializeGrowthBook,
- hasGrowthBookEnvOverride: () => hasGrowthBookEnvOverride,
- getGrowthBookConfigOverrides: () => getGrowthBookConfigOverrides,
- getFeatureValue_DEPRECATED: () => getFeatureValue_DEPRECATED,
- getFeatureValue_CACHED_WITH_REFRESH: () => getFeatureValue_CACHED_WITH_REFRESH,
- getFeatureValue_CACHED_MAY_BE_STALE: () => getFeatureValue_CACHED_MAY_BE_STALE,
- getDynamicConfig_CACHED_MAY_BE_STALE: () => getDynamicConfig_CACHED_MAY_BE_STALE,
- getDynamicConfig_BLOCKS_ON_INIT: () => getDynamicConfig_BLOCKS_ON_INIT,
- getApiBaseUrlHost: () => getApiBaseUrlHost,
- getAllGrowthBookFeatures: () => getAllGrowthBookFeatures,
- clearGrowthBookConfigOverrides: () => clearGrowthBookConfigOverrides,
- checkStatsigFeatureGate_CACHED_MAY_BE_STALE: () => checkStatsigFeatureGate_CACHED_MAY_BE_STALE,
- checkSecurityRestrictionGate: () => checkSecurityRestrictionGate,
- checkGate_CACHED_OR_BLOCKING: () => checkGate_CACHED_OR_BLOCKING
-});
-function callSafe(listener) {
- try {
- Promise.resolve(listener()).catch((e4) => {
- logError2(e4);
- });
- } catch (e4) {
- logError2(e4);
- }
-}
-function onGrowthBookRefresh(listener) {
- let subscribed = true;
- const unsubscribe2 = refreshed.subscribe(() => callSafe(listener));
- if (remoteEvalFeatureValues.size > 0) {
- queueMicrotask(() => {
- if (subscribed && remoteEvalFeatureValues.size > 0) {
- callSafe(listener);
- }
- });
- }
- return () => {
- subscribed = false;
- unsubscribe2();
- };
-}
-function getEnvOverrides() {
- if (!envOverridesParsed) {
- envOverridesParsed = true;
- if (process.env.USER_TYPE === "ant") {
- const raw = process.env.CLAUDE_INTERNAL_FC_OVERRIDES;
- if (raw) {
- try {
- envOverrides = JSON.parse(raw);
- logForDebugging(`GrowthBook: Using env var overrides for ${Object.keys(envOverrides).length} features: ${Object.keys(envOverrides).join(", ")}`);
- } catch {
- logError2(new Error(`GrowthBook: Failed to parse CLAUDE_INTERNAL_FC_OVERRIDES: ${raw}`));
- }
- }
- }
- }
- return envOverrides;
-}
-function hasGrowthBookEnvOverride(feature) {
- const overrides = getEnvOverrides();
- return overrides !== null && feature in overrides;
-}
-function getConfigOverrides() {
- if (process.env.USER_TYPE !== "ant")
- return;
- try {
- return getGlobalConfig().growthBookOverrides;
- } catch {
- return;
- }
-}
-function getAllGrowthBookFeatures() {
- if (remoteEvalFeatureValues.size > 0) {
- return Object.fromEntries(remoteEvalFeatureValues);
- }
- return getGlobalConfig().cachedGrowthBookFeatures ?? {};
-}
-function getGrowthBookConfigOverrides() {
- return getConfigOverrides() ?? {};
-}
-function setGrowthBookConfigOverride(feature, value) {
- if (process.env.USER_TYPE !== "ant")
- return;
- try {
- saveGlobalConfig((c8) => {
- const current = c8.growthBookOverrides ?? {};
- if (value === undefined) {
- if (!(feature in current))
- return c8;
- const { [feature]: _, ...rest } = current;
- if (Object.keys(rest).length === 0) {
- const { growthBookOverrides: __, ...configWithout } = c8;
- return configWithout;
- }
- return { ...c8, growthBookOverrides: rest };
- }
- if (isEqual_default(current[feature], value))
- return c8;
- return { ...c8, growthBookOverrides: { ...current, [feature]: value } };
- });
- refreshed.emit();
- } catch (e4) {
- logError2(e4);
- }
-}
-function clearGrowthBookConfigOverrides() {
- if (process.env.USER_TYPE !== "ant")
- return;
- try {
- saveGlobalConfig((c8) => {
- if (!c8.growthBookOverrides || Object.keys(c8.growthBookOverrides).length === 0) {
- return c8;
- }
- const { growthBookOverrides: _, ...rest } = c8;
- return rest;
- });
- refreshed.emit();
- } catch (e4) {
- logError2(e4);
- }
-}
-function logExposureForFeature(feature) {
- if (loggedExposures.has(feature)) {
- return;
- }
- const expData = experimentDataByFeature.get(feature);
- if (expData) {
- loggedExposures.add(feature);
- logGrowthBookExperimentTo1P({
- experimentId: expData.experimentId,
- variationId: expData.variationId,
- userAttributes: getUserAttributes(),
- experimentMetadata: {
- feature_id: feature
- }
- });
- }
-}
-async function processRemoteEvalPayload(gbClient) {
- const payload = gbClient.getPayload();
- if (!payload?.features || Object.keys(payload.features).length === 0) {
- return false;
- }
- experimentDataByFeature.clear();
- const transformedFeatures = {};
- for (const [key, feature] of Object.entries(payload.features)) {
- const f4 = feature;
- if ("value" in f4 && !("defaultValue" in f4)) {
- transformedFeatures[key] = {
- ...f4,
- defaultValue: f4.value
- };
- } else {
- transformedFeatures[key] = f4;
- }
- if (f4.source === "experiment" && f4.experimentResult) {
- const expResult = f4.experimentResult;
- const exp = f4.experiment;
- if (exp?.key && expResult.variationId !== undefined) {
- experimentDataByFeature.set(key, {
- experimentId: exp.key,
- variationId: expResult.variationId
- });
- }
- }
- }
- await gbClient.setPayload({
- ...payload,
- features: transformedFeatures
- });
- remoteEvalFeatureValues.clear();
- for (const [key, feature] of Object.entries(transformedFeatures)) {
- const v6 = "value" in feature ? feature.value : feature.defaultValue;
- if (v6 !== undefined) {
- remoteEvalFeatureValues.set(key, v6);
- }
- }
- return true;
-}
-function syncRemoteEvalToDisk() {
- const fresh = Object.fromEntries(remoteEvalFeatureValues);
- const config8 = getGlobalConfig();
- if (isEqual_default(config8.cachedGrowthBookFeatures, fresh)) {
- return;
- }
- saveGlobalConfig((current) => ({
- ...current,
- cachedGrowthBookFeatures: fresh
- }));
-}
-function isGrowthBookEnabled() {
- return is1PEventLoggingEnabled();
-}
-function getApiBaseUrlHost() {
- const baseUrl = process.env.ANTHROPIC_BASE_URL;
- if (!baseUrl)
- return;
- try {
- const host = new URL(baseUrl).host;
- if (host === "api.anthropic.com")
- return;
- return host;
- } catch {
- return;
- }
-}
-function getUserAttributes() {
- const user = getUserForGrowthBook();
- let email3 = user.email;
- if (!email3 && process.env.USER_TYPE === "ant") {
- email3 = getGlobalConfig().oauthAccount?.emailAddress;
- }
- const apiBaseUrlHost = getApiBaseUrlHost();
- const attributes = {
- id: user.deviceId,
- sessionId: user.sessionId,
- deviceID: user.deviceId,
- platform: user.platform,
- ...apiBaseUrlHost && { apiBaseUrlHost },
- ...user.organizationUuid && { organizationUUID: user.organizationUuid },
- ...user.accountUuid && { accountUUID: user.accountUuid },
- ...user.userType && { userType: user.userType },
- ...user.subscriptionType && { subscriptionType: user.subscriptionType },
- ...user.rateLimitTier && { rateLimitTier: user.rateLimitTier },
- ...user.firstTokenTime && { firstTokenTime: user.firstTokenTime },
- ...email3 && { email: email3 },
- ...user.appVersion && { appVersion: user.appVersion },
- ...user.githubActionsMetadata && {
- githubActionsMetadata: user.githubActionsMetadata
- }
- };
- return attributes;
-}
-async function getFeatureValueInternal(feature, defaultValue, logExposure) {
- const overrides = getEnvOverrides();
- if (overrides && feature in overrides) {
- return overrides[feature];
- }
- const configOverrides = getConfigOverrides();
- if (configOverrides && feature in configOverrides) {
- return configOverrides[feature];
- }
- if (!isGrowthBookEnabled()) {
- return defaultValue;
- }
- const growthBookClient = await initializeGrowthBook();
- if (!growthBookClient) {
- return defaultValue;
- }
- let result;
- if (remoteEvalFeatureValues.has(feature)) {
- result = remoteEvalFeatureValues.get(feature);
- } else {
- result = growthBookClient.getFeatureValue(feature, defaultValue);
- }
- if (logExposure) {
- logExposureForFeature(feature);
- }
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`GrowthBook: getFeatureValue("${feature}") = ${jsonStringify(result)}`);
- }
- return result;
-}
-async function getFeatureValue_DEPRECATED(feature, defaultValue) {
- return getFeatureValueInternal(feature, defaultValue, true);
-}
-function getFeatureValue_CACHED_MAY_BE_STALE(feature, defaultValue) {
- const overrides = getEnvOverrides();
- if (overrides && feature in overrides) {
- return overrides[feature];
- }
- const configOverrides = getConfigOverrides();
- if (configOverrides && feature in configOverrides) {
- return configOverrides[feature];
- }
- if (!isGrowthBookEnabled()) {
- return defaultValue;
- }
- if (experimentDataByFeature.has(feature)) {
- logExposureForFeature(feature);
- } else {
- pendingExposures.add(feature);
- }
- if (remoteEvalFeatureValues.has(feature)) {
- return remoteEvalFeatureValues.get(feature);
- }
- try {
- const cached2 = getGlobalConfig().cachedGrowthBookFeatures?.[feature];
- return cached2 !== undefined ? cached2 : defaultValue;
- } catch {
- return defaultValue;
- }
-}
-function getFeatureValue_CACHED_WITH_REFRESH(feature, defaultValue, _refreshIntervalMs) {
- return getFeatureValue_CACHED_MAY_BE_STALE(feature, defaultValue);
-}
-function checkStatsigFeatureGate_CACHED_MAY_BE_STALE(gate) {
- const overrides = getEnvOverrides();
- if (overrides && gate in overrides) {
- return Boolean(overrides[gate]);
- }
- const configOverrides = getConfigOverrides();
- if (configOverrides && gate in configOverrides) {
- return Boolean(configOverrides[gate]);
- }
- if (!isGrowthBookEnabled()) {
- return false;
- }
- if (experimentDataByFeature.has(gate)) {
- logExposureForFeature(gate);
- } else {
- pendingExposures.add(gate);
- }
- const config8 = getGlobalConfig();
- const gbCached = config8.cachedGrowthBookFeatures?.[gate];
- if (gbCached !== undefined) {
- return Boolean(gbCached);
- }
- return config8.cachedStatsigGates?.[gate] ?? false;
-}
-async function checkSecurityRestrictionGate(gate) {
- const overrides = getEnvOverrides();
- if (overrides && gate in overrides) {
- return Boolean(overrides[gate]);
- }
- const configOverrides = getConfigOverrides();
- if (configOverrides && gate in configOverrides) {
- return Boolean(configOverrides[gate]);
- }
- if (!isGrowthBookEnabled()) {
- return false;
- }
- if (reinitializingPromise) {
- await reinitializingPromise;
- }
- const config8 = getGlobalConfig();
- const statsigCached = config8.cachedStatsigGates?.[gate];
- if (statsigCached !== undefined) {
- return Boolean(statsigCached);
- }
- const gbCached = config8.cachedGrowthBookFeatures?.[gate];
- if (gbCached !== undefined) {
- return Boolean(gbCached);
- }
- return false;
-}
-async function checkGate_CACHED_OR_BLOCKING(gate) {
- const overrides = getEnvOverrides();
- if (overrides && gate in overrides) {
- return Boolean(overrides[gate]);
- }
- const configOverrides = getConfigOverrides();
- if (configOverrides && gate in configOverrides) {
- return Boolean(configOverrides[gate]);
- }
- if (!isGrowthBookEnabled()) {
- return false;
- }
- const cached2 = getGlobalConfig().cachedGrowthBookFeatures?.[gate];
- if (cached2 === true) {
- if (experimentDataByFeature.has(gate)) {
- logExposureForFeature(gate);
- } else {
- pendingExposures.add(gate);
- }
- return true;
- }
- return getFeatureValueInternal(gate, false, true);
-}
-function refreshGrowthBookAfterAuthChange() {
- if (!isGrowthBookEnabled()) {
- return;
- }
- try {
- resetGrowthBook();
- refreshed.emit();
- reinitializingPromise = initializeGrowthBook().catch((error46) => {
- logError2(toError(error46));
- return null;
- }).finally(() => {
- reinitializingPromise = null;
- });
- } catch (error46) {
- if (true) {
- throw error46;
- }
- logError2(toError(error46));
- }
-}
-function resetGrowthBook() {
- stopPeriodicGrowthBookRefresh();
- if (currentBeforeExitHandler) {
- process.off("beforeExit", currentBeforeExitHandler);
- currentBeforeExitHandler = null;
- }
- if (currentExitHandler) {
- process.off("exit", currentExitHandler);
- currentExitHandler = null;
- }
- client15?.destroy();
- client15 = null;
- clientCreatedWithAuth = false;
- reinitializingPromise = null;
- experimentDataByFeature.clear();
- pendingExposures.clear();
- loggedExposures.clear();
- remoteEvalFeatureValues.clear();
- getGrowthBookClient.cache?.clear?.();
- initializeGrowthBook.cache?.clear?.();
- envOverrides = null;
- envOverridesParsed = false;
-}
-async function refreshGrowthBookFeatures() {
- if (!isGrowthBookEnabled()) {
- return;
- }
- try {
- const growthBookClient = await initializeGrowthBook();
- if (!growthBookClient) {
- return;
- }
- await growthBookClient.refreshFeatures();
- if (growthBookClient !== client15) {
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("GrowthBook: Skipping refresh processing for replaced client");
- }
- return;
- }
- const hadFeatures = await processRemoteEvalPayload(growthBookClient);
- if (growthBookClient !== client15)
- return;
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("GrowthBook: Light refresh completed");
- }
- if (hadFeatures) {
- syncRemoteEvalToDisk();
- refreshed.emit();
- }
- } catch (error46) {
- if (true) {
- throw error46;
- }
- logError2(toError(error46));
- }
-}
-function setupPeriodicGrowthBookRefresh() {
- if (!isGrowthBookEnabled()) {
- return;
- }
- if (refreshInterval) {
- clearInterval(refreshInterval);
- }
- refreshInterval = setInterval(() => {
- refreshGrowthBookFeatures();
- }, GROWTHBOOK_REFRESH_INTERVAL_MS);
- refreshInterval.unref?.();
- if (!beforeExitListener) {
- beforeExitListener = () => {
- stopPeriodicGrowthBookRefresh();
- };
- process.once("beforeExit", beforeExitListener);
- }
-}
-function stopPeriodicGrowthBookRefresh() {
- if (refreshInterval) {
- clearInterval(refreshInterval);
- refreshInterval = null;
- }
- if (beforeExitListener) {
- process.removeListener("beforeExit", beforeExitListener);
- beforeExitListener = null;
- }
-}
-async function getDynamicConfig_BLOCKS_ON_INIT(configName, defaultValue) {
- return getFeatureValue_DEPRECATED(configName, defaultValue);
-}
-function getDynamicConfig_CACHED_MAY_BE_STALE(configName, defaultValue) {
- return getFeatureValue_CACHED_MAY_BE_STALE(configName, defaultValue);
-}
-var client15 = null, currentBeforeExitHandler = null, currentExitHandler = null, clientCreatedWithAuth = false, experimentDataByFeature, remoteEvalFeatureValues, pendingExposures, loggedExposures, reinitializingPromise = null, refreshed, envOverrides = null, envOverridesParsed = false, getGrowthBookClient, initializeGrowthBook, GROWTHBOOK_REFRESH_INTERVAL_MS, refreshInterval = null, beforeExitListener = null;
-var init_growthbook = __esm(() => {
- init_esm();
- init_lodash();
- init_state();
- init_keys2();
- init_config();
- init_debug();
- init_errors();
- init_http8();
- init_log2();
- init_slowOperations();
- init_user();
- init_firstPartyEventLogger();
- experimentDataByFeature = new Map;
- remoteEvalFeatureValues = new Map;
- pendingExposures = new Set;
- loggedExposures = new Set;
- refreshed = createSignal();
- getGrowthBookClient = memoize_default(() => {
- if (!isGrowthBookEnabled()) {
- return null;
- }
- const attributes = getUserAttributes();
- const clientKey = getGrowthBookClientKey();
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`GrowthBook: Creating client with clientKey=${clientKey}, attributes: ${jsonStringify(attributes)}`);
- }
- const baseUrl = process.env.USER_TYPE === "ant" ? process.env.CLAUDE_CODE_GB_BASE_URL || "https://api.anthropic.com/" : "https://api.anthropic.com/";
- const hasTrust = checkHasTrustDialogAccepted() || getSessionTrustAccepted() || getIsNonInteractiveSession();
- const authHeaders = hasTrust ? getAuthHeaders2() : { headers: {}, error: "trust not established" };
- const hasAuth = !authHeaders.error;
- clientCreatedWithAuth = hasAuth;
- const thisClient = new GrowthBook({
- apiHost: baseUrl,
- clientKey,
- attributes,
- remoteEval: true,
- cacheKeyAttributes: ["id", "organizationUUID"],
- ...authHeaders.error ? {} : { apiHostRequestHeaders: authHeaders.headers },
- ...process.env.USER_TYPE === "ant" ? {
- log: (msg, ctx) => {
- logForDebugging(`GrowthBook: ${msg} ${jsonStringify(ctx)}`);
- }
- } : {}
- });
- client15 = thisClient;
- if (!hasAuth) {
- return { client: thisClient, initialized: Promise.resolve() };
- }
- const initialized = thisClient.init({ timeout: 5000 }).then(async (result) => {
- if (client15 !== thisClient) {
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("GrowthBook: Skipping init callback for replaced client");
- }
- return;
- }
- if (process.env.USER_TYPE === "ant") {
- logForDebugging(`GrowthBook initialized successfully, source: ${result.source}, success: ${result.success}`);
- }
- const hadFeatures = await processRemoteEvalPayload(thisClient);
- if (client15 !== thisClient)
- return;
- if (hadFeatures) {
- for (const feature of pendingExposures) {
- logExposureForFeature(feature);
- }
- pendingExposures.clear();
- syncRemoteEvalToDisk();
- refreshed.emit();
- }
- if (process.env.USER_TYPE === "ant") {
- const features = thisClient.getFeatures();
- if (features) {
- const featureKeys = Object.keys(features);
- logForDebugging(`GrowthBook loaded ${featureKeys.length} features: ${featureKeys.slice(0, 10).join(", ")}${featureKeys.length > 10 ? "..." : ""}`);
- }
- }
- }).catch((error46) => {
- if (process.env.USER_TYPE === "ant") {
- logError2(toError(error46));
- }
- });
- currentBeforeExitHandler = () => client15?.destroy();
- currentExitHandler = () => client15?.destroy();
- process.on("beforeExit", currentBeforeExitHandler);
- process.on("exit", currentExitHandler);
- return { client: thisClient, initialized };
- });
- initializeGrowthBook = memoize_default(async () => {
- let clientWrapper = getGrowthBookClient();
- if (!clientWrapper) {
- return null;
- }
- if (!clientCreatedWithAuth) {
- const hasTrust = checkHasTrustDialogAccepted() || getSessionTrustAccepted() || getIsNonInteractiveSession();
- if (hasTrust) {
- const currentAuth = getAuthHeaders2();
- if (!currentAuth.error) {
- if (process.env.USER_TYPE === "ant") {
- logForDebugging("GrowthBook: Auth became available after client creation, reinitializing");
- }
- resetGrowthBook();
- clientWrapper = getGrowthBookClient();
- if (!clientWrapper) {
- return null;
- }
- }
- }
- }
- await clientWrapper.initialized;
- setupPeriodicGrowthBookRefresh();
- return clientWrapper.client;
- });
- GROWTHBOOK_REFRESH_INTERVAL_MS = process.env.USER_TYPE !== "ant" ? 6 * 60 * 60 * 1000 : 20 * 60 * 1000;
-});
-
-// src/memdir/paths.ts
-import { homedir as homedir10 } from "os";
-import { isAbsolute as isAbsolute4, join as join26, normalize as normalize3, sep as sep4 } from "path";
-function isAutoMemoryEnabled() {
- const envVal = process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY;
- if (isEnvTruthy(envVal)) {
- return false;
- }
- if (isEnvDefinedFalsy(envVal)) {
- return true;
- }
- if (isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)) {
- return false;
- }
- if (isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) && !process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR) {
- return false;
- }
- const settings = getInitialSettings();
- if (settings.autoMemoryEnabled !== undefined) {
- return settings.autoMemoryEnabled;
- }
- return true;
-}
-function getMemoryBaseDir() {
- if (process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR) {
- return process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR;
- }
- return getClaudeConfigHomeDir();
-}
-function validateMemoryPath(raw, expandTilde) {
- if (!raw) {
- return;
- }
- let candidate = raw;
- if (expandTilde && (candidate.startsWith("~/") || candidate.startsWith("~\\"))) {
- const rest = candidate.slice(2);
- const restNorm = normalize3(rest || ".");
- if (restNorm === "." || restNorm === "..") {
- return;
- }
- candidate = join26(homedir10(), rest);
- }
- const normalized = normalize3(candidate).replace(/[/\\]+$/, "");
- if (!isAbsolute4(normalized) || normalized.length < 3 || /^[A-Za-z]:$/.test(normalized) || normalized.startsWith("\\\\") || normalized.startsWith("//") || normalized.includes("\x00")) {
- return;
- }
- return (normalized + sep4).normalize("NFC");
-}
-function getAutoMemPathOverride() {
- return validateMemoryPath(process.env.CLAUDE_COWORK_MEMORY_PATH_OVERRIDE, false);
-}
-function getAutoMemPathSetting() {
- const dir = getSettingsForSource("policySettings")?.autoMemoryDirectory ?? getSettingsForSource("flagSettings")?.autoMemoryDirectory ?? getSettingsForSource("localSettings")?.autoMemoryDirectory ?? getSettingsForSource("userSettings")?.autoMemoryDirectory;
- return validateMemoryPath(dir, true);
-}
-function hasAutoMemPathOverride() {
- return getAutoMemPathOverride() !== undefined;
-}
-function getAutoMemBase() {
- return findCanonicalGitRoot(getProjectRoot()) ?? getProjectRoot();
-}
-function getAutoMemEntrypoint() {
- return join26(getAutoMemPath(), AUTO_MEM_ENTRYPOINT_NAME);
-}
-function isAutoMemPath(absolutePath) {
- const normalizedPath = normalize3(absolutePath);
- return normalizedPath.startsWith(getAutoMemPath());
-}
-var AUTO_MEM_DIRNAME = "memory", AUTO_MEM_ENTRYPOINT_NAME = "MEMORY.md", getAutoMemPath;
-var init_paths = __esm(() => {
- init_memoize();
- init_state();
- init_growthbook();
- init_envUtils();
- init_git();
- init_path();
- init_settings2();
- getAutoMemPath = memoize_default(() => {
- const override = getAutoMemPathOverride() ?? getAutoMemPathSetting();
- if (override) {
- return override;
- }
- const projectsDir = join26(getMemoryBaseDir(), "projects");
- return (join26(projectsDir, sanitizePath2(getAutoMemBase()), AUTO_MEM_DIRNAME) + sep4).normalize("NFC");
- }, () => getProjectRoot());
-});
-
-// src/tools/BashTool/toolName.ts
-var BASH_TOOL_NAME = "Bash";
-
-// src/tools/GrepTool/prompt.ts
-function getDescription() {
- return `A powerful search tool built on ripgrep
-
- Usage:
- - ALWAYS use ${GREP_TOOL_NAME} for search tasks. NEVER invoke \`grep\` or \`rg\` as a ${BASH_TOOL_NAME} command. The ${GREP_TOOL_NAME} tool has been optimized for correct permissions and access.
- - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
- - Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")
- - Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts
- - Use ${AGENT_TOOL_NAME} tool for open-ended searches requiring multiple rounds
- - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use \`interface\\{\\}\` to find \`interface{}\` in Go code)
- - Multiline matching: By default patterns match within single lines only. For cross-line patterns like \`struct \\{[\\s\\S]*?field\`, use \`multiline: true\`
-`;
-}
-var GREP_TOOL_NAME = "Grep";
-var init_prompt = __esm(() => {
- init_constants3();
-});
-
-// src/tools/FileEditTool/constants.ts
-var FILE_EDIT_TOOL_NAME = "Edit", CLAUDE_FOLDER_PERMISSION_PATTERN = "/.claude/**", GLOBAL_CLAUDE_FOLDER_PERMISSION_PATTERN = "~/.claude/**", FILE_UNEXPECTEDLY_MODIFIED_ERROR = "File has been unexpectedly modified. Read it again before attempting to write it.";
-
-// src/utils/pdfUtils.ts
-function parsePDFPageRange(pages) {
- const trimmed = pages.trim();
- if (!trimmed) {
- return null;
- }
- if (trimmed.endsWith("-")) {
- const first2 = parseInt(trimmed.slice(0, -1), 10);
- if (isNaN(first2) || first2 < 1) {
- return null;
- }
- return { firstPage: first2, lastPage: Infinity };
- }
- const dashIndex = trimmed.indexOf("-");
- if (dashIndex === -1) {
- const page = parseInt(trimmed, 10);
- if (isNaN(page) || page < 1) {
- return null;
- }
- return { firstPage: page, lastPage: page };
- }
- const first = parseInt(trimmed.slice(0, dashIndex), 10);
- const last = parseInt(trimmed.slice(dashIndex + 1), 10);
- if (isNaN(first) || isNaN(last) || first < 1 || last < 1 || last < first) {
- return null;
- }
- return { firstPage: first, lastPage: last };
-}
-function isPDFSupported() {
- return !getMainLoopModel().toLowerCase().includes("claude-3-haiku");
-}
-function isPDFExtension(ext) {
- const normalized = ext.startsWith(".") ? ext.slice(1) : ext;
- return DOCUMENT_EXTENSIONS.has(normalized.toLowerCase());
-}
-var DOCUMENT_EXTENSIONS;
-var init_pdfUtils = __esm(() => {
- init_model();
- DOCUMENT_EXTENSIONS = new Set(["pdf"]);
-});
-
-// src/tools/FileReadTool/prompt.ts
-function renderPromptTemplate(lineFormat, maxSizeInstruction, offsetInstruction) {
- return `Reads a file from the local filesystem. You can access any file directly by using this tool.
-Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
-
-Usage:
-- The file_path parameter must be an absolute path, not a relative path
-- By default, it reads up to ${MAX_LINES_TO_READ} lines starting from the beginning of the file${maxSizeInstruction}
-${offsetInstruction}
-${lineFormat}
-- This tool allows Claude Code to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Claude Code is a multimodal LLM.${isPDFSupported() ? `
-- This tool can read PDF files (.pdf). For large PDFs (more than 10 pages), you MUST provide the pages parameter to read specific page ranges (e.g., pages: "1-5"). Reading a large PDF without the pages parameter will fail. Maximum 20 pages per request.` : ""}
-- This tool can read Jupyter notebooks (.ipynb files) and returns all cells with their outputs, combining code, text, and visualizations.
-- This tool can only read files, not directories. To read a directory, use an ls command via the ${BASH_TOOL_NAME} tool.
-- You will regularly be asked to read screenshots. If the user provides a path to a screenshot, ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths.
-- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`;
-}
-var FILE_READ_TOOL_NAME = "Read", FILE_UNCHANGED_STUB = "File unchanged since last read. The content from the earlier Read tool_result in this conversation is still current \u2014 refer to that instead of re-reading.", MAX_LINES_TO_READ = 2000, DESCRIPTION2 = "Read a file from the local filesystem.", LINE_FORMAT_INSTRUCTION = "- Results are returned using cat -n format, with line numbers starting at 1", OFFSET_INSTRUCTION_DEFAULT = "- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters", OFFSET_INSTRUCTION_TARGETED = "- When you already know which part of the file you need, only read that part. This can be important for larger files.";
-var init_prompt2 = __esm(() => {
- init_pdfUtils();
-});
-
-// src/tools/FileWriteTool/prompt.ts
-function getPreReadInstruction() {
- return `
-- If this is an existing file, you MUST use the ${FILE_READ_TOOL_NAME} tool first to read the file's contents. This tool will fail if you did not read the file first.`;
-}
-function getWriteToolDescription() {
- return `Writes a file to the local filesystem.
-
-Usage:
-- This tool will overwrite the existing file if there is one at the provided path.${getPreReadInstruction()}
-- Prefer the Edit tool for modifying existing files \u2014 it only sends the diff. Only use this tool to create new files or for complete rewrites.
-- NEVER create documentation files (*.md) or README files unless explicitly requested by the User.
-- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.`;
-}
-var FILE_WRITE_TOOL_NAME = "Write";
-var init_prompt3 = __esm(() => {
- init_prompt2();
-});
-
-// src/tools/GlobTool/prompt.ts
-var GLOB_TOOL_NAME = "Glob", DESCRIPTION3 = `- Fast file pattern matching tool that works with any codebase size
-- Supports glob patterns like "**/*.js" or "src/**/*.ts"
-- Returns matching file paths sorted by modification time
-- Use this tool when you need to find files by name patterns
-- When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead`;
-
-// src/tools/NotebookEditTool/constants.ts
-var NOTEBOOK_EDIT_TOOL_NAME = "NotebookEdit";
-
-// src/tools/REPLTool/constants.ts
-function isReplModeEnabled() {
- if (isEnvDefinedFalsy(process.env.CLAUDE_CODE_REPL))
- return false;
- if (isEnvTruthy(process.env.CLAUDE_REPL_MODE))
- return true;
- return process.env.USER_TYPE === "ant" && process.env.CLAUDE_CODE_ENTRYPOINT === "cli";
-}
-var REPL_TOOL_NAME = "REPL", REPL_ONLY_TOOLS;
-var init_constants11 = __esm(() => {
- init_envUtils();
- init_constants3();
- init_prompt2();
- init_prompt3();
- init_prompt();
- REPL_ONLY_TOOLS = new Set([
- FILE_READ_TOOL_NAME,
- FILE_WRITE_TOOL_NAME,
- FILE_EDIT_TOOL_NAME,
- GLOB_TOOL_NAME,
- GREP_TOOL_NAME,
- BASH_TOOL_NAME,
- NOTEBOOK_EDIT_TOOL_NAME,
- AGENT_TOOL_NAME
- ]);
-});
-
-// src/utils/embeddedTools.ts
-function hasEmbeddedSearchTools() {
- if (!isEnvTruthy(process.env.EMBEDDED_SEARCH_TOOLS))
- return false;
- const e4 = process.env.CLAUDE_CODE_ENTRYPOINT;
- return e4 !== "sdk-ts" && e4 !== "sdk-py" && e4 !== "sdk-cli" && e4 !== "local-agent";
-}
-function embeddedSearchToolsBinaryPath() {
- return process.execPath;
-}
-var init_embeddedTools = __esm(() => {
- init_envUtils();
-});
-
-// node_modules/react/cjs/react.development.js
-var require_react_development = __commonJS((exports, module) => {
- (function() {
- function defineDeprecationWarning(methodName, info) {
- Object.defineProperty(Component.prototype, methodName, {
- get: function() {
- console.warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]);
- }
- });
- }
- function getIteratorFn(maybeIterable) {
- if (maybeIterable === null || typeof maybeIterable !== "object")
- return null;
- maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
- return typeof maybeIterable === "function" ? maybeIterable : null;
- }
- function warnNoop(publicInstance, callerName) {
- publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass";
- var warningKey = publicInstance + "." + callerName;
- didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, publicInstance), didWarnStateUpdateForUnmountedComponent[warningKey] = true);
- }
- function Component(props, context4, updater) {
- this.props = props;
- this.context = context4;
- this.refs = emptyObject;
- this.updater = updater || ReactNoopUpdateQueue;
- }
- function ComponentDummy() {}
- function PureComponent(props, context4, updater) {
- this.props = props;
- this.context = context4;
- this.refs = emptyObject;
- this.updater = updater || ReactNoopUpdateQueue;
- }
- function noop10() {}
- function testStringCoercion(value) {
- return "" + value;
- }
- function checkKeyStringCoercion(value) {
- try {
- testStringCoercion(value);
- var JSCompiler_inline_result = false;
- } catch (e4) {
- JSCompiler_inline_result = true;
- }
- if (JSCompiler_inline_result) {
- JSCompiler_inline_result = console;
- var JSCompiler_temp_const = JSCompiler_inline_result.error;
- var JSCompiler_inline_result$jscomp$0 = typeof Symbol === "function" && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
- JSCompiler_temp_const.call(JSCompiler_inline_result, "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", JSCompiler_inline_result$jscomp$0);
- return testStringCoercion(value);
- }
- }
- function getComponentNameFromType(type) {
- if (type == null)
- return null;
- if (typeof type === "function")
- return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
- if (typeof type === "string")
- return type;
- switch (type) {
- case REACT_FRAGMENT_TYPE:
- return "Fragment";
- case REACT_PROFILER_TYPE:
- return "Profiler";
- case REACT_STRICT_MODE_TYPE:
- return "StrictMode";
- case REACT_SUSPENSE_TYPE:
- return "Suspense";
- case REACT_SUSPENSE_LIST_TYPE:
- return "SuspenseList";
- case REACT_ACTIVITY_TYPE:
- return "Activity";
- }
- if (typeof type === "object")
- switch (typeof type.tag === "number" && console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), type.$$typeof) {
- case REACT_PORTAL_TYPE:
- return "Portal";
- case REACT_CONTEXT_TYPE:
- return type.displayName || "Context";
- case REACT_CONSUMER_TYPE:
- return (type._context.displayName || "Context") + ".Consumer";
- case REACT_FORWARD_REF_TYPE:
- var innerType = type.render;
- type = type.displayName;
- type || (type = innerType.displayName || innerType.name || "", type = type !== "" ? "ForwardRef(" + type + ")" : "ForwardRef");
- return type;
- case REACT_MEMO_TYPE:
- return innerType = type.displayName || null, innerType !== null ? innerType : getComponentNameFromType(type.type) || "Memo";
- case REACT_LAZY_TYPE:
- innerType = type._payload;
- type = type._init;
- try {
- return getComponentNameFromType(type(innerType));
- } catch (x3) {}
- }
- return null;
- }
- function getTaskName(type) {
- if (type === REACT_FRAGMENT_TYPE)
- return "<>";
- if (typeof type === "object" && type !== null && type.$$typeof === REACT_LAZY_TYPE)
- return "<...>";
- try {
- var name3 = getComponentNameFromType(type);
- return name3 ? "<" + name3 + ">" : "<...>";
- } catch (x3) {
- return "<...>";
- }
- }
- function getOwner() {
- var dispatcher = ReactSharedInternals.A;
- return dispatcher === null ? null : dispatcher.getOwner();
- }
- function UnknownOwner() {
- return Error("react-stack-top-frame");
- }
- function hasValidKey(config8) {
- if (hasOwnProperty15.call(config8, "key")) {
- var getter = Object.getOwnPropertyDescriptor(config8, "key").get;
- if (getter && getter.isReactWarning)
- return false;
- }
- return config8.key !== undefined;
- }
- function defineKeyPropWarningGetter(props, displayName) {
- function warnAboutAccessingKey() {
- specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", displayName));
- }
- warnAboutAccessingKey.isReactWarning = true;
- Object.defineProperty(props, "key", {
- get: warnAboutAccessingKey,
- configurable: true
- });
- }
- function elementRefGetterWithDeprecationWarning() {
- var componentName = getComponentNameFromType(this.type);
- didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."));
- componentName = this.props.ref;
- return componentName !== undefined ? componentName : null;
- }
- function ReactElement(type, key, props, owner, debugStack, debugTask) {
- var refProp = props.ref;
- type = {
- $$typeof: REACT_ELEMENT_TYPE,
- type,
- key,
- props,
- _owner: owner
- };
- (refProp !== undefined ? refProp : null) !== null ? Object.defineProperty(type, "ref", {
- enumerable: false,
- get: elementRefGetterWithDeprecationWarning
- }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
- type._store = {};
- Object.defineProperty(type._store, "validated", {
- configurable: false,
- enumerable: false,
- writable: true,
- value: 0
- });
- Object.defineProperty(type, "_debugInfo", {
- configurable: false,
- enumerable: false,
- writable: true,
- value: null
- });
- Object.defineProperty(type, "_debugStack", {
- configurable: false,
- enumerable: false,
- writable: true,
- value: debugStack
- });
- Object.defineProperty(type, "_debugTask", {
- configurable: false,
- enumerable: false,
- writable: true,
- value: debugTask
- });
- Object.freeze && (Object.freeze(type.props), Object.freeze(type));
- return type;
- }
- function cloneAndReplaceKey(oldElement, newKey) {
- newKey = ReactElement(oldElement.type, newKey, oldElement.props, oldElement._owner, oldElement._debugStack, oldElement._debugTask);
- oldElement._store && (newKey._store.validated = oldElement._store.validated);
- return newKey;
- }
- function validateChildKeys(node) {
- isValidElement(node) ? node._store && (node._store.validated = 1) : typeof node === "object" && node !== null && node.$$typeof === REACT_LAZY_TYPE && (node._payload.status === "fulfilled" ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
- }
- function isValidElement(object2) {
- return typeof object2 === "object" && object2 !== null && object2.$$typeof === REACT_ELEMENT_TYPE;
- }
- function escape3(key) {
- var escaperLookup = { "=": "=0", ":": "=2" };
- return "$" + key.replace(/[=:]/g, function(match) {
- return escaperLookup[match];
- });
- }
- function getElementKey(element, index2) {
- return typeof element === "object" && element !== null && element.key != null ? (checkKeyStringCoercion(element.key), escape3("" + element.key)) : index2.toString(36);
- }
- function resolveThenable(thenable) {
- switch (thenable.status) {
- case "fulfilled":
- return thenable.value;
- case "rejected":
- throw thenable.reason;
- default:
- switch (typeof thenable.status === "string" ? thenable.then(noop10, noop10) : (thenable.status = "pending", thenable.then(function(fulfilledValue) {
- thenable.status === "pending" && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
- }, function(error46) {
- thenable.status === "pending" && (thenable.status = "rejected", thenable.reason = error46);
- })), thenable.status) {
- case "fulfilled":
- return thenable.value;
- case "rejected":
- throw thenable.reason;
- }
- }
- throw thenable;
- }
- function mapIntoArray(children, array2, escapedPrefix, nameSoFar, callback) {
- var type = typeof children;
- if (type === "undefined" || type === "boolean")
- children = null;
- var invokeCallback = false;
- if (children === null)
- invokeCallback = true;
- else
- switch (type) {
- case "bigint":
- case "string":
- case "number":
- invokeCallback = true;
- break;
- case "object":
- switch (children.$$typeof) {
- case REACT_ELEMENT_TYPE:
- case REACT_PORTAL_TYPE:
- invokeCallback = true;
- break;
- case REACT_LAZY_TYPE:
- return invokeCallback = children._init, mapIntoArray(invokeCallback(children._payload), array2, escapedPrefix, nameSoFar, callback);
- }
- }
- if (invokeCallback) {
- invokeCallback = children;
- callback = callback(invokeCallback);
- var childKey = nameSoFar === "" ? "." + getElementKey(invokeCallback, 0) : nameSoFar;
- isArrayImpl(callback) ? (escapedPrefix = "", childKey != null && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array2, escapedPrefix, "", function(c8) {
- return c8;
- })) : callback != null && (isValidElement(callback) && (callback.key != null && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey(callback, escapedPrefix + (callback.key == null || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace(userProvidedKeyEscapeRegex, "$&/") + "/") + childKey), nameSoFar !== "" && invokeCallback != null && isValidElement(invokeCallback) && invokeCallback.key == null && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array2.push(callback));
- return 1;
- }
- invokeCallback = 0;
- childKey = nameSoFar === "" ? "." : nameSoFar + ":";
- if (isArrayImpl(children))
- for (var i5 = 0;i5 < children.length; i5++)
- nameSoFar = children[i5], type = childKey + getElementKey(nameSoFar, i5), invokeCallback += mapIntoArray(nameSoFar, array2, escapedPrefix, type, callback);
- else if (i5 = getIteratorFn(children), typeof i5 === "function")
- for (i5 === children.entries && (didWarnAboutMaps || console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."), didWarnAboutMaps = true), children = i5.call(children), i5 = 0;!(nameSoFar = children.next()).done; )
- nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i5++), invokeCallback += mapIntoArray(nameSoFar, array2, escapedPrefix, type, callback);
- else if (type === "object") {
- if (typeof children.then === "function")
- return mapIntoArray(resolveThenable(children), array2, escapedPrefix, nameSoFar, callback);
- array2 = String(children);
- throw Error("Objects are not valid as a React child (found: " + (array2 === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : array2) + "). If you meant to render a collection of children, use an array instead.");
- }
- return invokeCallback;
- }
- function mapChildren(children, func, context4) {
- if (children == null)
- return children;
- var result = [], count3 = 0;
- mapIntoArray(children, result, "", "", function(child) {
- return func.call(context4, child, count3++);
- });
- return result;
- }
- function lazyInitializer(payload) {
- if (payload._status === -1) {
- var ioInfo = payload._ioInfo;
- ioInfo != null && (ioInfo.start = ioInfo.end = performance.now());
- ioInfo = payload._result;
- var thenable = ioInfo();
- thenable.then(function(moduleObject) {
- if (payload._status === 0 || payload._status === -1) {
- payload._status = 1;
- payload._result = moduleObject;
- var _ioInfo = payload._ioInfo;
- _ioInfo != null && (_ioInfo.end = performance.now());
- thenable.status === undefined && (thenable.status = "fulfilled", thenable.value = moduleObject);
- }
- }, function(error46) {
- if (payload._status === 0 || payload._status === -1) {
- payload._status = 2;
- payload._result = error46;
- var _ioInfo2 = payload._ioInfo;
- _ioInfo2 != null && (_ioInfo2.end = performance.now());
- thenable.status === undefined && (thenable.status = "rejected", thenable.reason = error46);
- }
- });
- ioInfo = payload._ioInfo;
- if (ioInfo != null) {
- ioInfo.value = thenable;
- var displayName = thenable.displayName;
- typeof displayName === "string" && (ioInfo.name = displayName);
- }
- payload._status === -1 && (payload._status = 0, payload._result = thenable);
- }
- if (payload._status === 1)
- return ioInfo = payload._result, ioInfo === undefined && console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
-
-Your code should look like:
- const MyComponent = lazy(() => import('./MyComponent'))
-
-Did you accidentally put curly braces around the import?`, ioInfo), "default" in ioInfo || console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
-
-Your code should look like:
- const MyComponent = lazy(() => import('./MyComponent'))`, ioInfo), ioInfo.default;
- throw payload._result;
- }
- function resolveDispatcher() {
- var dispatcher = ReactSharedInternals.H;
- dispatcher === null && console.error(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
-1. You might have mismatching versions of React and the renderer (such as React DOM)
-2. You might be breaking the Rules of Hooks
-3. You might have more than one copy of React in the same app
-See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`);
- return dispatcher;
- }
- function releaseAsyncTransition() {
- ReactSharedInternals.asyncTransitions--;
- }
- function enqueueTask(task) {
- if (enqueueTaskImpl === null)
- try {
- var requireString = ("require" + Math.random()).slice(0, 7);
- enqueueTaskImpl = (module && module[requireString]).call(module, "timers").setImmediate;
- } catch (_err) {
- enqueueTaskImpl = function(callback) {
- didWarnAboutMessageChannel === false && (didWarnAboutMessageChannel = true, typeof MessageChannel === "undefined" && console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));
- var channel = new MessageChannel;
- channel.port1.onmessage = callback;
- channel.port2.postMessage(undefined);
- };
- }
- return enqueueTaskImpl(task);
- }
- function aggregateErrors(errors6) {
- return 1 < errors6.length && typeof AggregateError === "function" ? new AggregateError(errors6) : errors6[0];
- }
- function popActScope(prevActQueue, prevActScopeDepth) {
- prevActScopeDepth !== actScopeDepth - 1 && console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. ");
- actScopeDepth = prevActScopeDepth;
- }
- function recursivelyFlushAsyncActWork(returnValue, resolve9, reject) {
- var queue = ReactSharedInternals.actQueue;
- if (queue !== null)
- if (queue.length !== 0)
- try {
- flushActQueue(queue);
- enqueueTask(function() {
- return recursivelyFlushAsyncActWork(returnValue, resolve9, reject);
- });
- return;
- } catch (error46) {
- ReactSharedInternals.thrownErrors.push(error46);
- }
- else
- ReactSharedInternals.actQueue = null;
- 0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve9(returnValue);
- }
- function flushActQueue(queue) {
- if (!isFlushing) {
- isFlushing = true;
- var i5 = 0;
- try {
- for (;i5 < queue.length; i5++) {
- var callback = queue[i5];
- do {
- ReactSharedInternals.didUsePromise = false;
- var continuation = callback(false);
- if (continuation !== null) {
- if (ReactSharedInternals.didUsePromise) {
- queue[i5] = callback;
- queue.splice(0, i5);
- return;
- }
- callback = continuation;
- } else
- break;
- } while (1);
- }
- queue.length = 0;
- } catch (error46) {
- queue.splice(0, i5 + 1), ReactSharedInternals.thrownErrors.push(error46);
- } finally {
- isFlushing = false;
- }
- }
- }
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
- var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = {
- isMounted: function() {
- return false;
- },
- enqueueForceUpdate: function(publicInstance) {
- warnNoop(publicInstance, "forceUpdate");
- },
- enqueueReplaceState: function(publicInstance) {
- warnNoop(publicInstance, "replaceState");
- },
- enqueueSetState: function(publicInstance) {
- warnNoop(publicInstance, "setState");
- }
- }, assign = Object.assign, emptyObject = {};
- Object.freeze(emptyObject);
- Component.prototype.isReactComponent = {};
- Component.prototype.setState = function(partialState, callback) {
- if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null)
- throw Error("takes an object of state variables to update or a function which returns an object of state variables.");
- this.updater.enqueueSetState(this, partialState, callback, "setState");
- };
- Component.prototype.forceUpdate = function(callback) {
- this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
- };
- var deprecatedAPIs = {
- isMounted: [
- "isMounted",
- "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
- ],
- replaceState: [
- "replaceState",
- "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
- ]
- };
- for (fnName in deprecatedAPIs)
- deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
- ComponentDummy.prototype = Component.prototype;
- deprecatedAPIs = PureComponent.prototype = new ComponentDummy;
- deprecatedAPIs.constructor = PureComponent;
- assign(deprecatedAPIs, Component.prototype);
- deprecatedAPIs.isPureReactComponent = true;
- var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = {
- H: null,
- A: null,
- T: null,
- S: null,
- actQueue: null,
- asyncTransitions: 0,
- isBatchingLegacy: false,
- didScheduleLegacyUpdate: false,
- didUsePromise: false,
- thrownErrors: [],
- getCurrentStack: null,
- recentlyCreatedOwnerStacks: 0
- }, hasOwnProperty15 = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() {
- return null;
- };
- deprecatedAPIs = {
- react_stack_bottom_frame: function(callStackForError) {
- return callStackForError();
- }
- };
- var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
- var didWarnAboutElementRef = {};
- var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind(deprecatedAPIs, UnknownOwner)();
- var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
- var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = typeof reportError === "function" ? reportError : function(error46) {
- if (typeof window === "object" && typeof window.ErrorEvent === "function") {
- var event = new window.ErrorEvent("error", {
- bubbles: true,
- cancelable: true,
- message: typeof error46 === "object" && error46 !== null && typeof error46.message === "string" ? String(error46.message) : String(error46),
- error: error46
- });
- if (!window.dispatchEvent(event))
- return;
- } else if (typeof process === "object" && typeof process.emit === "function") {
- process.emit("uncaughtException", error46);
- return;
- }
- console.error(error46);
- }, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = typeof queueMicrotask === "function" ? function(callback) {
- queueMicrotask(function() {
- return queueMicrotask(callback);
- });
- } : enqueueTask;
- deprecatedAPIs = Object.freeze({
- __proto__: null,
- c: function(size) {
- return resolveDispatcher().useMemoCache(size);
- }
- });
- var fnName = {
- map: mapChildren,
- forEach: function(children, forEachFunc, forEachContext) {
- mapChildren(children, function() {
- forEachFunc.apply(this, arguments);
- }, forEachContext);
- },
- count: function(children) {
- var n5 = 0;
- mapChildren(children, function() {
- n5++;
- });
- return n5;
- },
- toArray: function(children) {
- return mapChildren(children, function(child) {
- return child;
- }) || [];
- },
- only: function(children) {
- if (!isValidElement(children))
- throw Error("React.Children.only expected to receive a single React element child.");
- return children;
- }
- };
- exports.Activity = REACT_ACTIVITY_TYPE;
- exports.Children = fnName;
- exports.Component = Component;
- exports.Fragment = REACT_FRAGMENT_TYPE;
- exports.Profiler = REACT_PROFILER_TYPE;
- exports.PureComponent = PureComponent;
- exports.StrictMode = REACT_STRICT_MODE_TYPE;
- exports.Suspense = REACT_SUSPENSE_TYPE;
- exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
- exports.__COMPILER_RUNTIME = deprecatedAPIs;
- exports.act = function(callback) {
- var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth;
- actScopeDepth++;
- var queue = ReactSharedInternals.actQueue = prevActQueue !== null ? prevActQueue : [], didAwaitActCall = false;
- try {
- var result = callback();
- } catch (error46) {
- ReactSharedInternals.thrownErrors.push(error46);
- }
- if (0 < ReactSharedInternals.thrownErrors.length)
- throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
- if (result !== null && typeof result === "object" && typeof result.then === "function") {
- var thenable = result;
- queueSeveralMicrotasks(function() {
- didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"));
- });
- return {
- then: function(resolve9, reject) {
- didAwaitActCall = true;
- thenable.then(function(returnValue) {
- popActScope(prevActQueue, prevActScopeDepth);
- if (prevActScopeDepth === 0) {
- try {
- flushActQueue(queue), enqueueTask(function() {
- return recursivelyFlushAsyncActWork(returnValue, resolve9, reject);
- });
- } catch (error$0) {
- ReactSharedInternals.thrownErrors.push(error$0);
- }
- if (0 < ReactSharedInternals.thrownErrors.length) {
- var _thrownError = aggregateErrors(ReactSharedInternals.thrownErrors);
- ReactSharedInternals.thrownErrors.length = 0;
- reject(_thrownError);
- }
- } else
- resolve9(returnValue);
- }, function(error46) {
- popActScope(prevActQueue, prevActScopeDepth);
- 0 < ReactSharedInternals.thrownErrors.length ? (error46 = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(error46)) : reject(error46);
- });
- }
- };
- }
- var returnValue$jscomp$0 = result;
- popActScope(prevActQueue, prevActScopeDepth);
- prevActScopeDepth === 0 && (flushActQueue(queue), queue.length !== 0 && queueSeveralMicrotasks(function() {
- didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"));
- }), ReactSharedInternals.actQueue = null);
- if (0 < ReactSharedInternals.thrownErrors.length)
- throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
- return {
- then: function(resolve9, reject) {
- didAwaitActCall = true;
- prevActScopeDepth === 0 ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
- return recursivelyFlushAsyncActWork(returnValue$jscomp$0, resolve9, reject);
- })) : resolve9(returnValue$jscomp$0);
- }
- };
- };
- exports.cache = function(fn) {
- return function() {
- return fn.apply(null, arguments);
- };
- };
- exports.cacheSignal = function() {
- return null;
- };
- exports.captureOwnerStack = function() {
- var getCurrentStack = ReactSharedInternals.getCurrentStack;
- return getCurrentStack === null ? null : getCurrentStack();
- };
- exports.cloneElement = function(element, config8, children) {
- if (element === null || element === undefined)
- throw Error("The argument must be a React element, but you passed " + element + ".");
- var props = assign({}, element.props), key = element.key, owner = element._owner;
- if (config8 != null) {
- var JSCompiler_inline_result;
- a: {
- if (hasOwnProperty15.call(config8, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor(config8, "ref").get) && JSCompiler_inline_result.isReactWarning) {
- JSCompiler_inline_result = false;
- break a;
- }
- JSCompiler_inline_result = config8.ref !== undefined;
- }
- JSCompiler_inline_result && (owner = getOwner());
- hasValidKey(config8) && (checkKeyStringCoercion(config8.key), key = "" + config8.key);
- for (propName in config8)
- !hasOwnProperty15.call(config8, propName) || propName === "key" || propName === "__self" || propName === "__source" || propName === "ref" && config8.ref === undefined || (props[propName] = config8[propName]);
- }
- var propName = arguments.length - 2;
- if (propName === 1)
- props.children = children;
- else if (1 < propName) {
- JSCompiler_inline_result = Array(propName);
- for (var i5 = 0;i5 < propName; i5++)
- JSCompiler_inline_result[i5] = arguments[i5 + 2];
- props.children = JSCompiler_inline_result;
- }
- props = ReactElement(element.type, key, props, owner, element._debugStack, element._debugTask);
- for (key = 2;key < arguments.length; key++)
- validateChildKeys(arguments[key]);
- return props;
- };
- exports.createContext = function(defaultValue) {
- defaultValue = {
- $$typeof: REACT_CONTEXT_TYPE,
- _currentValue: defaultValue,
- _currentValue2: defaultValue,
- _threadCount: 0,
- Provider: null,
- Consumer: null
- };
- defaultValue.Provider = defaultValue;
- defaultValue.Consumer = {
- $$typeof: REACT_CONSUMER_TYPE,
- _context: defaultValue
- };
- defaultValue._currentRenderer = null;
- defaultValue._currentRenderer2 = null;
- return defaultValue;
- };
- exports.createElement = function(type, config8, children) {
- for (var i5 = 2;i5 < arguments.length; i5++)
- validateChildKeys(arguments[i5]);
- i5 = {};
- var key = null;
- if (config8 != null)
- for (propName in didWarnAboutOldJSXRuntime || !("__self" in config8) || "key" in config8 || (didWarnAboutOldJSXRuntime = true, console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")), hasValidKey(config8) && (checkKeyStringCoercion(config8.key), key = "" + config8.key), config8)
- hasOwnProperty15.call(config8, propName) && propName !== "key" && propName !== "__self" && propName !== "__source" && (i5[propName] = config8[propName]);
- var childrenLength = arguments.length - 2;
- if (childrenLength === 1)
- i5.children = children;
- else if (1 < childrenLength) {
- for (var childArray = Array(childrenLength), _i3 = 0;_i3 < childrenLength; _i3++)
- childArray[_i3] = arguments[_i3 + 2];
- Object.freeze && Object.freeze(childArray);
- i5.children = childArray;
- }
- if (type && type.defaultProps)
- for (propName in childrenLength = type.defaultProps, childrenLength)
- i5[propName] === undefined && (i5[propName] = childrenLength[propName]);
- key && defineKeyPropWarningGetter(i5, typeof type === "function" ? type.displayName || type.name || "Unknown" : type);
- var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
- return ReactElement(type, key, i5, getOwner(), propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack, propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask);
- };
- exports.createRef = function() {
- var refObject = { current: null };
- Object.seal(refObject);
- return refObject;
- };
- exports.forwardRef = function(render) {
- render != null && render.$$typeof === REACT_MEMO_TYPE ? console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).") : typeof render !== "function" ? console.error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render) : render.length !== 0 && render.length !== 2 && console.error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined.");
- render != null && render.defaultProps != null && console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");
- var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }, ownName;
- Object.defineProperty(elementType, "displayName", {
- enumerable: false,
- configurable: true,
- get: function() {
- return ownName;
- },
- set: function(name3) {
- ownName = name3;
- render.name || render.displayName || (Object.defineProperty(render, "name", { value: name3 }), render.displayName = name3);
- }
- });
- return elementType;
- };
- exports.isValidElement = isValidElement;
- exports.lazy = function(ctor) {
- ctor = { _status: -1, _result: ctor };
- var lazyType = {
- $$typeof: REACT_LAZY_TYPE,
- _payload: ctor,
- _init: lazyInitializer
- }, ioInfo = {
- name: "lazy",
- start: -1,
- end: -1,
- value: null,
- owner: null,
- debugStack: Error("react-stack-top-frame"),
- debugTask: console.createTask ? console.createTask("lazy()") : null
- };
- ctor._ioInfo = ioInfo;
- lazyType._debugInfo = [{ awaited: ioInfo }];
- return lazyType;
- };
- exports.memo = function(type, compare) {
- type == null && console.error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type);
- compare = {
- $$typeof: REACT_MEMO_TYPE,
- type,
- compare: compare === undefined ? null : compare
- };
- var ownName;
- Object.defineProperty(compare, "displayName", {
- enumerable: false,
- configurable: true,
- get: function() {
- return ownName;
- },
- set: function(name3) {
- ownName = name3;
- type.name || type.displayName || (Object.defineProperty(type, "name", { value: name3 }), type.displayName = name3);
- }
- });
- return compare;
- };
- exports.startTransition = function(scope) {
- var prevTransition = ReactSharedInternals.T, currentTransition = {};
- currentTransition._updatedFibers = new Set;
- ReactSharedInternals.T = currentTransition;
- try {
- var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
- onStartTransitionFinish !== null && onStartTransitionFinish(currentTransition, returnValue);
- typeof returnValue === "object" && returnValue !== null && typeof returnValue.then === "function" && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop10, reportGlobalError));
- } catch (error46) {
- reportGlobalError(error46);
- } finally {
- prevTransition === null && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")), prevTransition !== null && currentTransition.types !== null && (prevTransition.types !== null && prevTransition.types !== currentTransition.types && console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
- }
- };
- exports.unstable_useCacheRefresh = function() {
- return resolveDispatcher().useCacheRefresh();
- };
- exports.use = function(usable) {
- return resolveDispatcher().use(usable);
- };
- exports.useActionState = function(action, initialState, permalink) {
- return resolveDispatcher().useActionState(action, initialState, permalink);
- };
- exports.useCallback = function(callback, deps) {
- return resolveDispatcher().useCallback(callback, deps);
- };
- exports.useContext = function(Context) {
- var dispatcher = resolveDispatcher();
- Context.$$typeof === REACT_CONSUMER_TYPE && console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?");
- return dispatcher.useContext(Context);
- };
- exports.useDebugValue = function(value, formatterFn) {
- return resolveDispatcher().useDebugValue(value, formatterFn);
- };
- exports.useDeferredValue = function(value, initialValue) {
- return resolveDispatcher().useDeferredValue(value, initialValue);
- };
- exports.useEffect = function(create, deps) {
- create == null && console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?");
- return resolveDispatcher().useEffect(create, deps);
- };
- exports.useEffectEvent = function(callback) {
- return resolveDispatcher().useEffectEvent(callback);
- };
- exports.useId = function() {
- return resolveDispatcher().useId();
- };
- exports.useImperativeHandle = function(ref, create, deps) {
- return resolveDispatcher().useImperativeHandle(ref, create, deps);
- };
- exports.useInsertionEffect = function(create, deps) {
- create == null && console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?");
- return resolveDispatcher().useInsertionEffect(create, deps);
- };
- exports.useLayoutEffect = function(create, deps) {
- create == null && console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?");
- return resolveDispatcher().useLayoutEffect(create, deps);
- };
- exports.useMemo = function(create, deps) {
- return resolveDispatcher().useMemo(create, deps);
- };
- exports.useOptimistic = function(passthrough, reducer) {
- return resolveDispatcher().useOptimistic(passthrough, reducer);
- };
- exports.useReducer = function(reducer, initialArg, init) {
- return resolveDispatcher().useReducer(reducer, initialArg, init);
- };
- exports.useRef = function(initialValue) {
- return resolveDispatcher().useRef(initialValue);
- };
- exports.useState = function(initialState) {
- return resolveDispatcher().useState(initialState);
- };
- exports.useSyncExternalStore = function(subscribe2, getSnapshot, getServerSnapshot) {
- return resolveDispatcher().useSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot);
- };
- exports.useTransition = function() {
- return resolveDispatcher().useTransition();
- };
- exports.version = "19.2.4";
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
- })();
-});
-
-// node_modules/react/index.js
-var require_react = __commonJS((exports, module) => {
- var react_development = __toESM(require_react_development());
- if (false) {} else {
- module.exports = react_development;
- }
-});
-
-// node_modules/react/cjs/react-compiler-runtime.development.js
-var require_react_compiler_runtime_development = __commonJS((exports) => {
- var react = __toESM(require_react());
- (function() {
- var ReactSharedInternals = react.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
- exports.c = function(size) {
- var dispatcher = ReactSharedInternals.H;
- dispatcher === null && console.error(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
-1. You might have mismatching versions of React and the renderer (such as React DOM)
-2. You might be breaking the Rules of Hooks
-3. You might have more than one copy of React in the same app
-See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`);
- return dispatcher.useMemoCache(size);
- };
- })();
-});
-
-// node_modules/react/compiler-runtime.js
-var require_compiler_runtime = __commonJS((exports, module) => {
- var react_compiler_runtime_development = __toESM(require_react_compiler_runtime_development());
- if (false) {} else {
- module.exports = react_compiler_runtime_development;
- }
-});
-
-// src/ink/events/event.ts
-class Event2 {
- _didStopImmediatePropagation = false;
- didStopImmediatePropagation() {
- return this._didStopImmediatePropagation;
- }
- stopImmediatePropagation() {
- this._didStopImmediatePropagation = true;
- }
-}
-
-// src/ink/events/emitter.ts
-import { EventEmitter as NodeEventEmitter } from "events";
-var EventEmitter3;
-var init_emitter = __esm(() => {
- EventEmitter3 = class EventEmitter3 extends NodeEventEmitter {
- constructor() {
- super();
- this.setMaxListeners(0);
- }
- emit(type, ...args) {
- if (type === "error") {
- return super.emit(type, ...args);
- }
- const listeners = this.rawListeners(type);
- if (listeners.length === 0) {
- return false;
- }
- const ccEvent = args[0] instanceof Event2 ? args[0] : null;
- for (const listener of listeners) {
- listener.apply(this, args);
- if (ccEvent?.didStopImmediatePropagation()) {
- break;
- }
- }
- return true;
- }
- };
-});
-
-// src/ink/components/StdinContext.ts
-var import_react, StdinContext, StdinContext_default;
-var init_StdinContext = __esm(() => {
- init_emitter();
- import_react = __toESM(require_react(), 1);
- StdinContext = import_react.createContext({
- stdin: process.stdin,
- internal_eventEmitter: new EventEmitter3,
- setRawMode() {},
- isRawModeSupported: false,
- internal_exitOnCtrlC: true,
- internal_querier: null
- });
- StdinContext.displayName = "InternalStdinContext";
- StdinContext_default = StdinContext;
-});
-
-// src/ink/hooks/use-stdin.ts
-var import_react2, useStdin = () => import_react2.useContext(StdinContext_default), use_stdin_default;
-var init_use_stdin = __esm(() => {
- init_StdinContext();
- import_react2 = __toESM(require_react(), 1);
- use_stdin_default = useStdin;
-});
-
-// src/utils/systemTheme.ts
-function getSystemThemeName() {
- if (cachedSystemTheme === undefined) {
- cachedSystemTheme = detectFromColorFgBg() ?? "dark";
- }
- return cachedSystemTheme;
-}
-function resolveThemeSetting(setting) {
- if (setting === "auto") {
- return getSystemThemeName();
- }
- return setting;
-}
-function detectFromColorFgBg() {
- const colorfgbg = process.env["COLORFGBG"];
- if (!colorfgbg)
- return;
- const parts = colorfgbg.split(";");
- const bg = parts[parts.length - 1];
- if (bg === undefined || bg === "")
- return;
- const bgNum = Number(bg);
- if (!Number.isInteger(bgNum) || bgNum < 0 || bgNum > 15)
- return;
- return bgNum <= 6 || bgNum === 8 ? "dark" : "light";
-}
-var cachedSystemTheme;
-
-// node_modules/react/cjs/react-jsx-dev-runtime.development.js
-var require_react_jsx_dev_runtime_development = __commonJS((exports) => {
- var React = __toESM(require_react());
- (function() {
- function getComponentNameFromType(type) {
- if (type == null)
- return null;
- if (typeof type === "function")
- return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
- if (typeof type === "string")
- return type;
- switch (type) {
- case REACT_FRAGMENT_TYPE:
- return "Fragment";
- case REACT_PROFILER_TYPE:
- return "Profiler";
- case REACT_STRICT_MODE_TYPE:
- return "StrictMode";
- case REACT_SUSPENSE_TYPE:
- return "Suspense";
- case REACT_SUSPENSE_LIST_TYPE:
- return "SuspenseList";
- case REACT_ACTIVITY_TYPE:
- return "Activity";
- }
- if (typeof type === "object")
- switch (typeof type.tag === "number" && console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), type.$$typeof) {
- case REACT_PORTAL_TYPE:
- return "Portal";
- case REACT_CONTEXT_TYPE:
- return type.displayName || "Context";
- case REACT_CONSUMER_TYPE:
- return (type._context.displayName || "Context") + ".Consumer";
- case REACT_FORWARD_REF_TYPE:
- var innerType = type.render;
- type = type.displayName;
- type || (type = innerType.displayName || innerType.name || "", type = type !== "" ? "ForwardRef(" + type + ")" : "ForwardRef");
- return type;
- case REACT_MEMO_TYPE:
- return innerType = type.displayName || null, innerType !== null ? innerType : getComponentNameFromType(type.type) || "Memo";
- case REACT_LAZY_TYPE:
- innerType = type._payload;
- type = type._init;
- try {
- return getComponentNameFromType(type(innerType));
- } catch (x3) {}
- }
- return null;
- }
- function testStringCoercion(value) {
- return "" + value;
- }
- function checkKeyStringCoercion(value) {
- try {
- testStringCoercion(value);
- var JSCompiler_inline_result = false;
- } catch (e4) {
- JSCompiler_inline_result = true;
- }
- if (JSCompiler_inline_result) {
- JSCompiler_inline_result = console;
- var JSCompiler_temp_const = JSCompiler_inline_result.error;
- var JSCompiler_inline_result$jscomp$0 = typeof Symbol === "function" && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
- JSCompiler_temp_const.call(JSCompiler_inline_result, "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", JSCompiler_inline_result$jscomp$0);
- return testStringCoercion(value);
- }
- }
- function getTaskName(type) {
- if (type === REACT_FRAGMENT_TYPE)
- return "<>";
- if (typeof type === "object" && type !== null && type.$$typeof === REACT_LAZY_TYPE)
- return "<...>";
- try {
- var name3 = getComponentNameFromType(type);
- return name3 ? "<" + name3 + ">" : "<...>";
- } catch (x3) {
- return "<...>";
- }
- }
- function getOwner() {
- var dispatcher = ReactSharedInternals.A;
- return dispatcher === null ? null : dispatcher.getOwner();
- }
- function UnknownOwner() {
- return Error("react-stack-top-frame");
- }
- function hasValidKey(config8) {
- if (hasOwnProperty15.call(config8, "key")) {
- var getter = Object.getOwnPropertyDescriptor(config8, "key").get;
- if (getter && getter.isReactWarning)
- return false;
- }
- return config8.key !== undefined;
- }
- function defineKeyPropWarningGetter(props, displayName) {
- function warnAboutAccessingKey() {
- specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", displayName));
- }
- warnAboutAccessingKey.isReactWarning = true;
- Object.defineProperty(props, "key", {
- get: warnAboutAccessingKey,
- configurable: true
- });
- }
- function elementRefGetterWithDeprecationWarning() {
- var componentName = getComponentNameFromType(this.type);
- didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."));
- componentName = this.props.ref;
- return componentName !== undefined ? componentName : null;
- }
- function ReactElement(type, key, props, owner, debugStack, debugTask) {
- var refProp = props.ref;
- type = {
- $$typeof: REACT_ELEMENT_TYPE,
- type,
- key,
- props,
- _owner: owner
- };
- (refProp !== undefined ? refProp : null) !== null ? Object.defineProperty(type, "ref", {
- enumerable: false,
- get: elementRefGetterWithDeprecationWarning
- }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
- type._store = {};
- Object.defineProperty(type._store, "validated", {
- configurable: false,
- enumerable: false,
- writable: true,
- value: 0
- });
- Object.defineProperty(type, "_debugInfo", {
- configurable: false,
- enumerable: false,
- writable: true,
- value: null
- });
- Object.defineProperty(type, "_debugStack", {
- configurable: false,
- enumerable: false,
- writable: true,
- value: debugStack
- });
- Object.defineProperty(type, "_debugTask", {
- configurable: false,
- enumerable: false,
- writable: true,
- value: debugTask
- });
- Object.freeze && (Object.freeze(type.props), Object.freeze(type));
- return type;
- }
- function jsxDEVImpl(type, config8, maybeKey, isStaticChildren, debugStack, debugTask) {
- var children = config8.children;
- if (children !== undefined)
- if (isStaticChildren)
- if (isArrayImpl(children)) {
- for (isStaticChildren = 0;isStaticChildren < children.length; isStaticChildren++)
- validateChildKeys(children[isStaticChildren]);
- Object.freeze && Object.freeze(children);
- } else
- console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
- else
- validateChildKeys(children);
- if (hasOwnProperty15.call(config8, "key")) {
- children = getComponentNameFromType(type);
- var keys2 = Object.keys(config8).filter(function(k4) {
- return k4 !== "key";
- });
- isStaticChildren = 0 < keys2.length ? "{key: someKey, " + keys2.join(": ..., ") + ": ...}" : "{key: someKey}";
- didWarnAboutKeySpread[children + isStaticChildren] || (keys2 = 0 < keys2.length ? "{" + keys2.join(": ..., ") + ": ...}" : "{}", console.error(`A props object containing a "key" prop is being spread into JSX:
- let props = %s;
- <%s {...props} />
-React keys must be passed directly to JSX without using spread:
- let props = %s;
- <%s key={someKey} {...props} />`, isStaticChildren, children, keys2, children), didWarnAboutKeySpread[children + isStaticChildren] = true);
- }
- children = null;
- maybeKey !== undefined && (checkKeyStringCoercion(maybeKey), children = "" + maybeKey);
- hasValidKey(config8) && (checkKeyStringCoercion(config8.key), children = "" + config8.key);
- if ("key" in config8) {
- maybeKey = {};
- for (var propName in config8)
- propName !== "key" && (maybeKey[propName] = config8[propName]);
- } else
- maybeKey = config8;
- children && defineKeyPropWarningGetter(maybeKey, typeof type === "function" ? type.displayName || type.name || "Unknown" : type);
- return ReactElement(type, children, maybeKey, getOwner(), debugStack, debugTask);
- }
- function validateChildKeys(node) {
- isValidElement(node) ? node._store && (node._store.validated = 1) : typeof node === "object" && node !== null && node.$$typeof === REACT_LAZY_TYPE && (node._payload.status === "fulfilled" ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
- }
- function isValidElement(object2) {
- return typeof object2 === "object" && object2 !== null && object2.$$typeof === REACT_ELEMENT_TYPE;
- }
- var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty15 = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
- return null;
- };
- React = {
- react_stack_bottom_frame: function(callStackForError) {
- return callStackForError();
- }
- };
- var specialPropKeyWarningShown;
- var didWarnAboutElementRef = {};
- var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(React, UnknownOwner)();
- var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
- var didWarnAboutKeySpread = {};
- exports.Fragment = REACT_FRAGMENT_TYPE;
- exports.jsxDEV = function(type, config8, maybeKey, isStaticChildren) {
- var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
- return jsxDEVImpl(type, config8, maybeKey, isStaticChildren, trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack, trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask);
- };
- })();
-});
-
-// node_modules/react/jsx-dev-runtime.js
-var require_jsx_dev_runtime = __commonJS((exports, module) => {
- var react_jsx_dev_runtime_development = __toESM(require_react_jsx_dev_runtime_development());
- if (false) {} else {
- module.exports = react_jsx_dev_runtime_development;
- }
-});
-
-// src/components/design-system/ThemeProvider.tsx
-function defaultInitialTheme() {
- return getGlobalConfig().theme;
-}
-function defaultSaveTheme(setting) {
- saveGlobalConfig((current) => ({
- ...current,
- theme: setting
- }));
-}
-function ThemeProvider({
- children,
- initialState,
- onThemeSave = defaultSaveTheme
-}) {
- const [themeSetting, setThemeSetting] = import_react3.useState(initialState ?? defaultInitialTheme);
- const [previewTheme, setPreviewTheme] = import_react3.useState(null);
- const [systemTheme, setSystemTheme] = import_react3.useState(() => (initialState ?? themeSetting) === "auto" ? getSystemThemeName() : "dark");
- const activeSetting = previewTheme ?? themeSetting;
- const {
- internal_querier
- } = use_stdin_default();
- import_react3.useEffect(() => {
- if (false) {}
- }, [activeSetting, internal_querier]);
- const currentTheme = activeSetting === "auto" ? systemTheme : activeSetting;
- const value = import_react3.useMemo(() => ({
- themeSetting,
- setThemeSetting: (newSetting) => {
- setThemeSetting(newSetting);
- setPreviewTheme(null);
- if (newSetting === "auto") {
- setSystemTheme(getSystemThemeName());
- }
- onThemeSave?.(newSetting);
- },
- setPreviewTheme: (newSetting_0) => {
- setPreviewTheme(newSetting_0);
- if (newSetting_0 === "auto") {
- setSystemTheme(getSystemThemeName());
- }
- },
- savePreview: () => {
- if (previewTheme !== null) {
- setThemeSetting(previewTheme);
- setPreviewTheme(null);
- onThemeSave?.(previewTheme);
- }
- },
- cancelPreview: () => {
- if (previewTheme !== null) {
- setPreviewTheme(null);
- }
- },
- currentTheme
- }), [themeSetting, previewTheme, currentTheme, onThemeSave]);
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemeContext.Provider, {
- value,
- children
- }, undefined, false, undefined, this);
-}
-function useTheme() {
- const $2 = import_compiler_runtime.c(3);
- const {
- currentTheme,
- setThemeSetting
- } = import_react3.useContext(ThemeContext);
- let t0;
- if ($2[0] !== currentTheme || $2[1] !== setThemeSetting) {
- t0 = [currentTheme, setThemeSetting];
- $2[0] = currentTheme;
- $2[1] = setThemeSetting;
- $2[2] = t0;
- } else {
- t0 = $2[2];
- }
- return t0;
-}
-function useThemeSetting() {
- return import_react3.useContext(ThemeContext).themeSetting;
-}
-function usePreviewTheme() {
- const $2 = import_compiler_runtime.c(4);
- const {
- setPreviewTheme,
- savePreview,
- cancelPreview
- } = import_react3.useContext(ThemeContext);
- let t0;
- if ($2[0] !== cancelPreview || $2[1] !== savePreview || $2[2] !== setPreviewTheme) {
- t0 = {
- setPreviewTheme,
- savePreview,
- cancelPreview
- };
- $2[0] = cancelPreview;
- $2[1] = savePreview;
- $2[2] = setPreviewTheme;
- $2[3] = t0;
- } else {
- t0 = $2[3];
- }
- return t0;
-}
-var import_compiler_runtime, import_react3, jsx_dev_runtime, DEFAULT_THEME = "dark", ThemeContext;
-var init_ThemeProvider = __esm(() => {
- init_use_stdin();
- init_config();
- import_compiler_runtime = __toESM(require_compiler_runtime(), 1);
- import_react3 = __toESM(require_react(), 1);
- jsx_dev_runtime = __toESM(require_jsx_dev_runtime(), 1);
- ThemeContext = import_react3.createContext({
- themeSetting: DEFAULT_THEME,
- setThemeSetting: () => {},
- setPreviewTheme: () => {},
- savePreview: () => {},
- cancelPreview: () => {},
- currentTheme: DEFAULT_THEME
- });
-});
-
-// node_modules/auto-bind/index.js
-function autoBind(self2, { include, exclude } = {}) {
- const filter2 = (key) => {
- const match = (pattern) => typeof pattern === "string" ? key === pattern : pattern.test(key);
- if (include) {
- return include.some(match);
- }
- if (exclude) {
- return !exclude.some(match);
- }
- return true;
- };
- for (const [object2, key] of getAllProperties(self2.constructor.prototype)) {
- if (key === "constructor" || !filter2(key)) {
- continue;
- }
- const descriptor = Reflect.getOwnPropertyDescriptor(object2, key);
- if (descriptor && typeof descriptor.value === "function") {
- self2[key] = self2[key].bind(self2);
- }
- }
- return self2;
-}
-var getAllProperties = (object2) => {
- const properties = new Set;
- do {
- for (const key of Reflect.ownKeys(object2)) {
- properties.add([object2, key]);
- }
- } while ((object2 = Reflect.getPrototypeOf(object2)) && object2 !== Object.prototype);
- return properties;
-};
-
-// node_modules/lodash-es/now.js
-var now = function() {
- return _root_default.Date.now();
-}, now_default;
-var init_now = __esm(() => {
- init__root();
- now_default = now;
-});
-
-// node_modules/lodash-es/_trimmedEndIndex.js
-function trimmedEndIndex(string4) {
- var index2 = string4.length;
- while (index2-- && reWhitespace.test(string4.charAt(index2))) {}
- return index2;
-}
-var reWhitespace, _trimmedEndIndex_default;
-var init__trimmedEndIndex = __esm(() => {
- reWhitespace = /\s/;
- _trimmedEndIndex_default = trimmedEndIndex;
-});
-
-// node_modules/lodash-es/_baseTrim.js
-function baseTrim(string4) {
- return string4 ? string4.slice(0, _trimmedEndIndex_default(string4) + 1).replace(reTrimStart, "") : string4;
-}
-var reTrimStart, _baseTrim_default;
-var init__baseTrim = __esm(() => {
- init__trimmedEndIndex();
- reTrimStart = /^\s+/;
- _baseTrim_default = baseTrim;
-});
-
-// node_modules/lodash-es/toNumber.js
-function toNumber(value) {
- if (typeof value == "number") {
- return value;
- }
- if (isSymbol_default(value)) {
- return NAN;
- }
- if (isObject_default(value)) {
- var other2 = typeof value.valueOf == "function" ? value.valueOf() : value;
- value = isObject_default(other2) ? other2 + "" : other2;
- }
- if (typeof value != "string") {
- return value === 0 ? value : +value;
- }
- value = _baseTrim_default(value);
- var isBinary = reIsBinary.test(value);
- return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
-}
-var NAN, reIsBadHex, reIsBinary, reIsOctal, freeParseInt, toNumber_default;
-var init_toNumber = __esm(() => {
- init__baseTrim();
- init_isObject();
- init_isSymbol();
- NAN = 0 / 0;
- reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
- reIsBinary = /^0b[01]+$/i;
- reIsOctal = /^0o[0-7]+$/i;
- freeParseInt = parseInt;
- toNumber_default = toNumber;
-});
-
-// node_modules/lodash-es/debounce.js
-function debounce(func, wait, options2) {
- var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
- if (typeof func != "function") {
- throw new TypeError(FUNC_ERROR_TEXT2);
- }
- wait = toNumber_default(wait) || 0;
- if (isObject_default(options2)) {
- leading = !!options2.leading;
- maxing = "maxWait" in options2;
- maxWait = maxing ? nativeMax2(toNumber_default(options2.maxWait) || 0, wait) : maxWait;
- trailing = "trailing" in options2 ? !!options2.trailing : trailing;
- }
- function invokeFunc(time3) {
- var args = lastArgs, thisArg = lastThis;
- lastArgs = lastThis = undefined;
- lastInvokeTime = time3;
- result = func.apply(thisArg, args);
- return result;
- }
- function leadingEdge(time3) {
- lastInvokeTime = time3;
- timerId = setTimeout(timerExpired, wait);
- return leading ? invokeFunc(time3) : result;
- }
- function remainingWait(time3) {
- var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
- return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
- }
- function shouldInvoke(time3) {
- var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime;
- return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
- }
- function timerExpired() {
- var time3 = now_default();
- if (shouldInvoke(time3)) {
- return trailingEdge(time3);
- }
- timerId = setTimeout(timerExpired, remainingWait(time3));
- }
- function trailingEdge(time3) {
- timerId = undefined;
- if (trailing && lastArgs) {
- return invokeFunc(time3);
- }
- lastArgs = lastThis = undefined;
- return result;
- }
- function cancel() {
- if (timerId !== undefined) {
- clearTimeout(timerId);
- }
- lastInvokeTime = 0;
- lastArgs = lastCallTime = lastThis = timerId = undefined;
- }
- function flush() {
- return timerId === undefined ? result : trailingEdge(now_default());
- }
- function debounced() {
- var time3 = now_default(), isInvoking = shouldInvoke(time3);
- lastArgs = arguments;
- lastThis = this;
- lastCallTime = time3;
- if (isInvoking) {
- if (timerId === undefined) {
- return leadingEdge(lastCallTime);
- }
- if (maxing) {
- clearTimeout(timerId);
- timerId = setTimeout(timerExpired, wait);
- return invokeFunc(lastCallTime);
- }
- }
- if (timerId === undefined) {
- timerId = setTimeout(timerExpired, wait);
- }
- return result;
- }
- debounced.cancel = cancel;
- debounced.flush = flush;
- return debounced;
-}
-var FUNC_ERROR_TEXT2 = "Expected a function", nativeMax2, nativeMin, debounce_default;
-var init_debounce = __esm(() => {
- init_isObject();
- init_now();
- init_toNumber();
- nativeMax2 = Math.max;
- nativeMin = Math.min;
- debounce_default = debounce;
-});
-
-// node_modules/lodash-es/throttle.js
-function throttle2(func, wait, options2) {
- var leading = true, trailing = true;
- if (typeof func != "function") {
- throw new TypeError(FUNC_ERROR_TEXT3);
- }
- if (isObject_default(options2)) {
- leading = "leading" in options2 ? !!options2.leading : leading;
- trailing = "trailing" in options2 ? !!options2.trailing : trailing;
- }
- return debounce_default(func, wait, {
- leading,
- maxWait: wait,
- trailing
- });
-}
-var FUNC_ERROR_TEXT3 = "Expected a function", throttle_default2;
-var init_throttle2 = __esm(() => {
- init_debounce();
- init_isObject();
- throttle_default2 = throttle2;
-});
-
-// node_modules/react-reconciler/cjs/react-reconciler-constants.development.js
-var require_react_reconciler_constants_development = __commonJS((exports) => {
- exports.ConcurrentRoot = 1, exports.ContinuousEventPriority = 8, exports.DefaultEventPriority = 32, exports.DiscreteEventPriority = 2, exports.IdleEventPriority = 268435456, exports.LegacyRoot = 0, exports.NoEventPriority = 0;
-});
-
-// node_modules/react-reconciler/constants.js
-var require_constants5 = __commonJS((exports, module) => {
- if (false) {} else {
- module.exports = require_react_reconciler_constants_development();
- }
-});
-
-// src/native-ts/yoga-layout/enums.ts
-var Align, Direction, Display, Edge, Errata, FlexDirection, Gutter, Justify, MeasureMode, Overflow, PositionType, Unit, Wrap;
-var init_enums3 = __esm(() => {
- Align = {
- Auto: 0,
- FlexStart: 1,
- Center: 2,
- FlexEnd: 3,
- Stretch: 4,
- Baseline: 5,
- SpaceBetween: 6,
- SpaceAround: 7,
- SpaceEvenly: 8
- };
- Direction = {
- Inherit: 0,
- LTR: 1,
- RTL: 2
- };
- Display = {
- Flex: 0,
- None: 1,
- Contents: 2
- };
- Edge = {
- Left: 0,
- Top: 1,
- Right: 2,
- Bottom: 3,
- Start: 4,
- End: 5,
- Horizontal: 6,
- Vertical: 7,
- All: 8
- };
- Errata = {
- None: 0,
- StretchFlexBasis: 1,
- AbsolutePositionWithoutInsetsExcludesPadding: 2,
- AbsolutePercentAgainstInnerSize: 4,
- All: 2147483647,
- Classic: 2147483646
- };
- FlexDirection = {
- Column: 0,
- ColumnReverse: 1,
- Row: 2,
- RowReverse: 3
- };
- Gutter = {
- Column: 0,
- Row: 1,
- All: 2
- };
- Justify = {
- FlexStart: 0,
- Center: 1,
- FlexEnd: 2,
- SpaceBetween: 3,
- SpaceAround: 4,
- SpaceEvenly: 5
- };
- MeasureMode = {
- Undefined: 0,
- Exactly: 1,
- AtMost: 2
- };
- Overflow = {
- Visible: 0,
- Hidden: 1,
- Scroll: 2
- };
- PositionType = {
- Static: 0,
- Relative: 1,
- Absolute: 2
- };
- Unit = {
- Undefined: 0,
- Point: 1,
- Percent: 2,
- Auto: 3
- };
- Wrap = {
- NoWrap: 0,
- Wrap: 1,
- WrapReverse: 2
- };
-});
-
-// src/native-ts/yoga-layout/index.ts
-function pointValue(v6) {
- return { unit: Unit.Point, value: v6 };
-}
-function percentValue(v6) {
- return { unit: Unit.Percent, value: v6 };
-}
-function resolveValue(v6, ownerSize) {
- switch (v6.unit) {
- case Unit.Point:
- return v6.value;
- case Unit.Percent:
- return isNaN(ownerSize) ? NaN : v6.value * ownerSize / 100;
- default:
- return NaN;
- }
-}
-function isDefined(n5) {
- return !isNaN(n5);
-}
-function sameFloat(a5, b4) {
- return a5 === b4 || a5 !== a5 && b4 !== b4;
-}
-function defaultStyle() {
- return {
- direction: Direction.Inherit,
- flexDirection: FlexDirection.Column,
- justifyContent: Justify.FlexStart,
- alignItems: Align.Stretch,
- alignSelf: Align.Auto,
- alignContent: Align.FlexStart,
- flexWrap: Wrap.NoWrap,
- overflow: Overflow.Visible,
- display: Display.Flex,
- positionType: PositionType.Relative,
- flexGrow: 0,
- flexShrink: 0,
- flexBasis: AUTO_VALUE,
- margin: new Array(9).fill(UNDEFINED_VALUE),
- padding: new Array(9).fill(UNDEFINED_VALUE),
- border: new Array(9).fill(UNDEFINED_VALUE),
- position: new Array(9).fill(UNDEFINED_VALUE),
- gap: new Array(3).fill(UNDEFINED_VALUE),
- width: AUTO_VALUE,
- height: AUTO_VALUE,
- minWidth: UNDEFINED_VALUE,
- minHeight: UNDEFINED_VALUE,
- maxWidth: UNDEFINED_VALUE,
- maxHeight: UNDEFINED_VALUE
- };
-}
-function resolveEdge(edges, physicalEdge, ownerSize, allowAuto = false) {
- let v6 = edges[physicalEdge];
- if (v6.unit === Unit.Undefined) {
- if (physicalEdge === EDGE_LEFT || physicalEdge === EDGE_RIGHT) {
- v6 = edges[Edge.Horizontal];
- } else {
- v6 = edges[Edge.Vertical];
- }
- }
- if (v6.unit === Unit.Undefined) {
- v6 = edges[Edge.All];
- }
- if (v6.unit === Unit.Undefined) {
- if (physicalEdge === EDGE_LEFT)
- v6 = edges[Edge.Start];
- if (physicalEdge === EDGE_RIGHT)
- v6 = edges[Edge.End];
- }
- if (v6.unit === Unit.Undefined)
- return 0;
- if (v6.unit === Unit.Auto)
- return allowAuto ? NaN : 0;
- return resolveValue(v6, ownerSize);
-}
-function resolveEdgeRaw(edges, physicalEdge) {
- let v6 = edges[physicalEdge];
- if (v6.unit === Unit.Undefined) {
- if (physicalEdge === EDGE_LEFT || physicalEdge === EDGE_RIGHT) {
- v6 = edges[Edge.Horizontal];
- } else {
- v6 = edges[Edge.Vertical];
- }
- }
- if (v6.unit === Unit.Undefined)
- v6 = edges[Edge.All];
- if (v6.unit === Unit.Undefined) {
- if (physicalEdge === EDGE_LEFT)
- v6 = edges[Edge.Start];
- if (physicalEdge === EDGE_RIGHT)
- v6 = edges[Edge.End];
- }
- return v6;
-}
-function isMarginAuto(edges, physicalEdge) {
- return resolveEdgeRaw(edges, physicalEdge).unit === Unit.Auto;
-}
-function hasAnyAutoEdge(edges) {
- for (let i5 = 0;i5 < 9; i5++)
- if (edges[i5].unit === 3)
- return true;
- return false;
-}
-function hasAnyDefinedEdge(edges) {
- for (let i5 = 0;i5 < 9; i5++)
- if (edges[i5].unit !== 0)
- return true;
- return false;
-}
-function resolveEdges4Into(edges, ownerSize, out) {
- const eH = edges[6];
- const eV = edges[7];
- const eA = edges[8];
- const eS = edges[4];
- const eE = edges[5];
- const pctDenom = isNaN(ownerSize) ? NaN : ownerSize / 100;
- let v6 = edges[0];
- if (v6.unit === 0)
- v6 = eH;
- if (v6.unit === 0)
- v6 = eA;
- if (v6.unit === 0)
- v6 = eS;
- out[0] = v6.unit === 1 ? v6.value : v6.unit === 2 ? v6.value * pctDenom : 0;
- v6 = edges[1];
- if (v6.unit === 0)
- v6 = eV;
- if (v6.unit === 0)
- v6 = eA;
- out[1] = v6.unit === 1 ? v6.value : v6.unit === 2 ? v6.value * pctDenom : 0;
- v6 = edges[2];
- if (v6.unit === 0)
- v6 = eH;
- if (v6.unit === 0)
- v6 = eA;
- if (v6.unit === 0)
- v6 = eE;
- out[2] = v6.unit === 1 ? v6.value : v6.unit === 2 ? v6.value * pctDenom : 0;
- v6 = edges[3];
- if (v6.unit === 0)
- v6 = eV;
- if (v6.unit === 0)
- v6 = eA;
- out[3] = v6.unit === 1 ? v6.value : v6.unit === 2 ? v6.value * pctDenom : 0;
-}
-function isRow(dir) {
- return dir === FlexDirection.Row || dir === FlexDirection.RowReverse;
-}
-function isReverse(dir) {
- return dir === FlexDirection.RowReverse || dir === FlexDirection.ColumnReverse;
-}
-function crossAxis(dir) {
- return isRow(dir) ? FlexDirection.Column : FlexDirection.Row;
-}
-function leadingEdge(dir) {
- switch (dir) {
- case FlexDirection.Row:
- return EDGE_LEFT;
- case FlexDirection.RowReverse:
- return EDGE_RIGHT;
- case FlexDirection.Column:
- return EDGE_TOP;
- case FlexDirection.ColumnReverse:
- return EDGE_BOTTOM;
- }
-}
-function trailingEdge(dir) {
- switch (dir) {
- case FlexDirection.Row:
- return EDGE_RIGHT;
- case FlexDirection.RowReverse:
- return EDGE_LEFT;
- case FlexDirection.Column:
- return EDGE_BOTTOM;
- case FlexDirection.ColumnReverse:
- return EDGE_TOP;
- }
-}
-function createConfig() {
- const config8 = {
- pointScaleFactor: 1,
- errata: Errata.None,
- useWebDefaults: false,
- free() {},
- isExperimentalFeatureEnabled() {
- return false;
- },
- setExperimentalFeatureEnabled() {},
- setPointScaleFactor(f4) {
- config8.pointScaleFactor = f4;
- },
- getErrata() {
- return config8.errata;
- },
- setErrata(e4) {
- config8.errata = e4;
- },
- setUseWebDefaults(v6) {
- config8.useWebDefaults = v6;
- }
- };
- return config8;
-}
-
-class Node {
- style;
- layout;
- parent;
- children;
- measureFunc;
- config;
- isDirty_;
- isReferenceBaseline_;
- _flexBasis = 0;
- _mainSize = 0;
- _crossSize = 0;
- _lineIndex = 0;
- _hasAutoMargin = false;
- _hasPosition = false;
- _hasPadding = false;
- _hasBorder = false;
- _hasMargin = false;
- _lW = NaN;
- _lH = NaN;
- _lWM = 0;
- _lHM = 0;
- _lOW = NaN;
- _lOH = NaN;
- _lFW = false;
- _lFH = false;
- _lOutW = NaN;
- _lOutH = NaN;
- _hasL = false;
- _mW = NaN;
- _mH = NaN;
- _mWM = 0;
- _mHM = 0;
- _mOW = NaN;
- _mOH = NaN;
- _mOutW = NaN;
- _mOutH = NaN;
- _hasM = false;
- _fbBasis = NaN;
- _fbOwnerW = NaN;
- _fbOwnerH = NaN;
- _fbAvailMain = NaN;
- _fbAvailCross = NaN;
- _fbCrossMode = 0;
- _fbGen = -1;
- _cIn = null;
- _cOut = null;
- _cGen = -1;
- _cN = 0;
- _cWr = 0;
- constructor(config8) {
- this.style = defaultStyle();
- this.layout = {
- left: 0,
- top: 0,
- width: 0,
- height: 0,
- border: [0, 0, 0, 0],
- padding: [0, 0, 0, 0],
- margin: [0, 0, 0, 0]
- };
- this.parent = null;
- this.children = [];
- this.measureFunc = null;
- this.config = config8 ?? DEFAULT_CONFIG;
- this.isDirty_ = true;
- this.isReferenceBaseline_ = false;
- _yogaLiveNodes++;
- }
- insertChild(child, index2) {
- child.parent = this;
- this.children.splice(index2, 0, child);
- this.markDirty();
- }
- removeChild(child) {
- const idx = this.children.indexOf(child);
- if (idx >= 0) {
- this.children.splice(idx, 1);
- child.parent = null;
- this.markDirty();
- }
- }
- getChild(index2) {
- return this.children[index2];
- }
- getChildCount() {
- return this.children.length;
- }
- getParent() {
- return this.parent;
- }
- free() {
- this.parent = null;
- this.children = [];
- this.measureFunc = null;
- this._cIn = null;
- this._cOut = null;
- _yogaLiveNodes--;
- }
- freeRecursive() {
- for (const c8 of this.children)
- c8.freeRecursive();
- this.free();
- }
- reset() {
- this.style = defaultStyle();
- this.children = [];
- this.parent = null;
- this.measureFunc = null;
- this.isDirty_ = true;
- this._hasAutoMargin = false;
- this._hasPosition = false;
- this._hasPadding = false;
- this._hasBorder = false;
- this._hasMargin = false;
- this._hasL = false;
- this._hasM = false;
- this._cN = 0;
- this._cWr = 0;
- this._fbBasis = NaN;
- }
- markDirty() {
- this.isDirty_ = true;
- if (this.parent && !this.parent.isDirty_)
- this.parent.markDirty();
- }
- isDirty() {
- return this.isDirty_;
- }
- hasNewLayout() {
- return true;
- }
- markLayoutSeen() {}
- setMeasureFunc(fn) {
- this.measureFunc = fn;
- this.markDirty();
- }
- unsetMeasureFunc() {
- this.measureFunc = null;
- this.markDirty();
- }
- getComputedLeft() {
- return this.layout.left;
- }
- getComputedTop() {
- return this.layout.top;
- }
- getComputedWidth() {
- return this.layout.width;
- }
- getComputedHeight() {
- return this.layout.height;
- }
- getComputedRight() {
- const p4 = this.parent;
- return p4 ? p4.layout.width - this.layout.left - this.layout.width : 0;
- }
- getComputedBottom() {
- const p4 = this.parent;
- return p4 ? p4.layout.height - this.layout.top - this.layout.height : 0;
- }
- getComputedLayout() {
- return {
- left: this.layout.left,
- top: this.layout.top,
- right: this.getComputedRight(),
- bottom: this.getComputedBottom(),
- width: this.layout.width,
- height: this.layout.height
- };
- }
- getComputedBorder(edge) {
- return this.layout.border[physicalEdge(edge)];
- }
- getComputedPadding(edge) {
- return this.layout.padding[physicalEdge(edge)];
- }
- getComputedMargin(edge) {
- return this.layout.margin[physicalEdge(edge)];
- }
- setWidth(v6) {
- this.style.width = parseDimension(v6);
- this.markDirty();
- }
- setWidthPercent(v6) {
- this.style.width = percentValue(v6);
- this.markDirty();
- }
- setWidthAuto() {
- this.style.width = AUTO_VALUE;
- this.markDirty();
- }
- setHeight(v6) {
- this.style.height = parseDimension(v6);
- this.markDirty();
- }
- setHeightPercent(v6) {
- this.style.height = percentValue(v6);
- this.markDirty();
- }
- setHeightAuto() {
- this.style.height = AUTO_VALUE;
- this.markDirty();
- }
- setMinWidth(v6) {
- this.style.minWidth = parseDimension(v6);
- this.markDirty();
- }
- setMinWidthPercent(v6) {
- this.style.minWidth = percentValue(v6);
- this.markDirty();
- }
- setMinHeight(v6) {
- this.style.minHeight = parseDimension(v6);
- this.markDirty();
- }
- setMinHeightPercent(v6) {
- this.style.minHeight = percentValue(v6);
- this.markDirty();
- }
- setMaxWidth(v6) {
- this.style.maxWidth = parseDimension(v6);
- this.markDirty();
- }
- setMaxWidthPercent(v6) {
- this.style.maxWidth = percentValue(v6);
- this.markDirty();
- }
- setMaxHeight(v6) {
- this.style.maxHeight = parseDimension(v6);
- this.markDirty();
- }
- setMaxHeightPercent(v6) {
- this.style.maxHeight = percentValue(v6);
- this.markDirty();
- }
- setFlexDirection(dir) {
- this.style.flexDirection = dir;
- this.markDirty();
- }
- setFlexGrow(v6) {
- this.style.flexGrow = v6 ?? 0;
- this.markDirty();
- }
- setFlexShrink(v6) {
- this.style.flexShrink = v6 ?? 0;
- this.markDirty();
- }
- setFlex(v6) {
- if (v6 === undefined || isNaN(v6)) {
- this.style.flexGrow = 0;
- this.style.flexShrink = 0;
- } else if (v6 > 0) {
- this.style.flexGrow = v6;
- this.style.flexShrink = 1;
- this.style.flexBasis = pointValue(0);
- } else if (v6 < 0) {
- this.style.flexGrow = 0;
- this.style.flexShrink = -v6;
- } else {
- this.style.flexGrow = 0;
- this.style.flexShrink = 0;
- }
- this.markDirty();
- }
- setFlexBasis(v6) {
- this.style.flexBasis = parseDimension(v6);
- this.markDirty();
- }
- setFlexBasisPercent(v6) {
- this.style.flexBasis = percentValue(v6);
- this.markDirty();
- }
- setFlexBasisAuto() {
- this.style.flexBasis = AUTO_VALUE;
- this.markDirty();
- }
- setFlexWrap(wrap) {
- this.style.flexWrap = wrap;
- this.markDirty();
- }
- setAlignItems(a5) {
- this.style.alignItems = a5;
- this.markDirty();
- }
- setAlignSelf(a5) {
- this.style.alignSelf = a5;
- this.markDirty();
- }
- setAlignContent(a5) {
- this.style.alignContent = a5;
- this.markDirty();
- }
- setJustifyContent(j4) {
- this.style.justifyContent = j4;
- this.markDirty();
- }
- setDisplay(d4) {
- this.style.display = d4;
- this.markDirty();
- }
- getDisplay() {
- return this.style.display;
- }
- setPositionType(t4) {
- this.style.positionType = t4;
- this.markDirty();
- }
- setPosition(edge, v6) {
- this.style.position[edge] = parseDimension(v6);
- this._hasPosition = hasAnyDefinedEdge(this.style.position);
- this.markDirty();
- }
- setPositionPercent(edge, v6) {
- this.style.position[edge] = percentValue(v6);
- this._hasPosition = true;
- this.markDirty();
- }
- setPositionAuto(edge) {
- this.style.position[edge] = AUTO_VALUE;
- this._hasPosition = true;
- this.markDirty();
- }
- setOverflow(o5) {
- this.style.overflow = o5;
- this.markDirty();
- }
- setDirection(d4) {
- this.style.direction = d4;
- this.markDirty();
- }
- setBoxSizing(_) {}
- setMargin(edge, v6) {
- const val = parseDimension(v6);
- this.style.margin[edge] = val;
- if (val.unit === Unit.Auto)
- this._hasAutoMargin = true;
- else
- this._hasAutoMargin = hasAnyAutoEdge(this.style.margin);
- this._hasMargin = this._hasAutoMargin || hasAnyDefinedEdge(this.style.margin);
- this.markDirty();
- }
- setMarginPercent(edge, v6) {
- this.style.margin[edge] = percentValue(v6);
- this._hasAutoMargin = hasAnyAutoEdge(this.style.margin);
- this._hasMargin = true;
- this.markDirty();
- }
- setMarginAuto(edge) {
- this.style.margin[edge] = AUTO_VALUE;
- this._hasAutoMargin = true;
- this._hasMargin = true;
- this.markDirty();
- }
- setPadding(edge, v6) {
- this.style.padding[edge] = parseDimension(v6);
- this._hasPadding = hasAnyDefinedEdge(this.style.padding);
- this.markDirty();
- }
- setPaddingPercent(edge, v6) {
- this.style.padding[edge] = percentValue(v6);
- this._hasPadding = true;
- this.markDirty();
- }
- setBorder(edge, v6) {
- this.style.border[edge] = v6 === undefined ? UNDEFINED_VALUE : pointValue(v6);
- this._hasBorder = hasAnyDefinedEdge(this.style.border);
- this.markDirty();
- }
- setGap(gutter, v6) {
- this.style.gap[gutter] = parseDimension(v6);
- this.markDirty();
- }
- setGapPercent(gutter, v6) {
- this.style.gap[gutter] = percentValue(v6);
- this.markDirty();
- }
- getFlexDirection() {
- return this.style.flexDirection;
- }
- getJustifyContent() {
- return this.style.justifyContent;
- }
- getAlignItems() {
- return this.style.alignItems;
- }
- getAlignSelf() {
- return this.style.alignSelf;
- }
- getAlignContent() {
- return this.style.alignContent;
- }
- getFlexGrow() {
- return this.style.flexGrow;
- }
- getFlexShrink() {
- return this.style.flexShrink;
- }
- getFlexBasis() {
- return this.style.flexBasis;
- }
- getFlexWrap() {
- return this.style.flexWrap;
- }
- getWidth() {
- return this.style.width;
- }
- getHeight() {
- return this.style.height;
- }
- getOverflow() {
- return this.style.overflow;
- }
- getPositionType() {
- return this.style.positionType;
- }
- getDirection() {
- return this.style.direction;
- }
- copyStyle(_) {}
- setDirtiedFunc(_) {}
- unsetDirtiedFunc() {}
- setIsReferenceBaseline(v6) {
- this.isReferenceBaseline_ = v6;
- this.markDirty();
- }
- isReferenceBaseline() {
- return this.isReferenceBaseline_;
- }
- setAspectRatio(_) {}
- getAspectRatio() {
- return NaN;
- }
- setAlwaysFormsContainingBlock(_) {}
- calculateLayout(ownerWidth, ownerHeight, _direction) {
- _yogaNodesVisited = 0;
- _yogaMeasureCalls = 0;
- _yogaCacheHits = 0;
- _generation++;
- const w2 = ownerWidth === undefined ? NaN : ownerWidth;
- const h5 = ownerHeight === undefined ? NaN : ownerHeight;
- layoutNode(this, w2, h5, isDefined(w2) ? MeasureMode.Exactly : MeasureMode.Undefined, isDefined(h5) ? MeasureMode.Exactly : MeasureMode.Undefined, w2, h5, true);
- const mar = this.layout.margin;
- const posL = resolveValue(resolveEdgeRaw(this.style.position, EDGE_LEFT), isDefined(w2) ? w2 : 0);
- const posT = resolveValue(resolveEdgeRaw(this.style.position, EDGE_TOP), isDefined(w2) ? w2 : 0);
- this.layout.left = mar[EDGE_LEFT] + (isDefined(posL) ? posL : 0);
- this.layout.top = mar[EDGE_TOP] + (isDefined(posT) ? posT : 0);
- roundLayout(this, this.config.pointScaleFactor, 0, 0);
- }
-}
-function cacheWrite(node, aW, aH, wM, hM, oW, oH, fW, fH, wasDirty) {
- if (!node._cIn) {
- node._cIn = new Float64Array(CACHE_SLOTS * 8);
- node._cOut = new Float64Array(CACHE_SLOTS * 2);
- }
- if (wasDirty && node._cGen !== _generation) {
- node._cN = 0;
- node._cWr = 0;
- }
- const i5 = node._cWr++ % CACHE_SLOTS;
- if (node._cN < CACHE_SLOTS)
- node._cN = node._cWr;
- const o5 = i5 * 8;
- const cIn = node._cIn;
- cIn[o5] = aW;
- cIn[o5 + 1] = aH;
- cIn[o5 + 2] = wM;
- cIn[o5 + 3] = hM;
- cIn[o5 + 4] = oW;
- cIn[o5 + 5] = oH;
- cIn[o5 + 6] = fW ? 1 : 0;
- cIn[o5 + 7] = fH ? 1 : 0;
- node._cOut[i5 * 2] = node.layout.width;
- node._cOut[i5 * 2 + 1] = node.layout.height;
- node._cGen = _generation;
-}
-function commitCacheOutputs(node, performLayout) {
- if (performLayout) {
- node._lOutW = node.layout.width;
- node._lOutH = node.layout.height;
- } else {
- node._mOutW = node.layout.width;
- node._mOutH = node.layout.height;
- }
-}
-function getYogaCounters() {
- return {
- visited: _yogaNodesVisited,
- measured: _yogaMeasureCalls,
- cacheHits: _yogaCacheHits,
- live: _yogaLiveNodes
- };
-}
-function layoutNode(node, availableWidth, availableHeight, widthMode, heightMode, ownerWidth, ownerHeight, performLayout, forceWidth = false, forceHeight = false) {
- _yogaNodesVisited++;
- const style = node.style;
- const layout = node.layout;
- const sameGen = node._cGen === _generation && !performLayout;
- if (!node.isDirty_ || sameGen) {
- if (!node.isDirty_ && node._hasL && node._lWM === widthMode && node._lHM === heightMode && node._lFW === forceWidth && node._lFH === forceHeight && sameFloat(node._lW, availableWidth) && sameFloat(node._lH, availableHeight) && sameFloat(node._lOW, ownerWidth) && sameFloat(node._lOH, ownerHeight)) {
- _yogaCacheHits++;
- layout.width = node._lOutW;
- layout.height = node._lOutH;
- return;
- }
- if (node._cN > 0 && (sameGen || !node.isDirty_)) {
- const cIn = node._cIn;
- for (let i5 = 0;i5 < node._cN; i5++) {
- const o5 = i5 * 8;
- if (cIn[o5 + 2] === widthMode && cIn[o5 + 3] === heightMode && cIn[o5 + 6] === (forceWidth ? 1 : 0) && cIn[o5 + 7] === (forceHeight ? 1 : 0) && sameFloat(cIn[o5], availableWidth) && sameFloat(cIn[o5 + 1], availableHeight) && sameFloat(cIn[o5 + 4], ownerWidth) && sameFloat(cIn[o5 + 5], ownerHeight)) {
- layout.width = node._cOut[i5 * 2];
- layout.height = node._cOut[i5 * 2 + 1];
- _yogaCacheHits++;
- return;
- }
- }
- }
- if (!node.isDirty_ && !performLayout && node._hasM && node._mWM === widthMode && node._mHM === heightMode && sameFloat(node._mW, availableWidth) && sameFloat(node._mH, availableHeight) && sameFloat(node._mOW, ownerWidth) && sameFloat(node._mOH, ownerHeight)) {
- layout.width = node._mOutW;
- layout.height = node._mOutH;
- _yogaCacheHits++;
- return;
- }
- }
- const wasDirty = node.isDirty_;
- if (performLayout) {
- node._lW = availableWidth;
- node._lH = availableHeight;
- node._lWM = widthMode;
- node._lHM = heightMode;
- node._lOW = ownerWidth;
- node._lOH = ownerHeight;
- node._lFW = forceWidth;
- node._lFH = forceHeight;
- node._hasL = true;
- node.isDirty_ = false;
- if (wasDirty)
- node._hasM = false;
- } else {
- node._mW = availableWidth;
- node._mH = availableHeight;
- node._mWM = widthMode;
- node._mHM = heightMode;
- node._mOW = ownerWidth;
- node._mOH = ownerHeight;
- node._hasM = true;
- if (wasDirty)
- node._hasL = false;
- }
- const pad = layout.padding;
- const bor = layout.border;
- const mar = layout.margin;
- if (node._hasPadding)
- resolveEdges4Into(style.padding, ownerWidth, pad);
- else
- pad[0] = pad[1] = pad[2] = pad[3] = 0;
- if (node._hasBorder)
- resolveEdges4Into(style.border, ownerWidth, bor);
- else
- bor[0] = bor[1] = bor[2] = bor[3] = 0;
- if (node._hasMargin)
- resolveEdges4Into(style.margin, ownerWidth, mar);
- else
- mar[0] = mar[1] = mar[2] = mar[3] = 0;
- const paddingBorderWidth = pad[0] + pad[2] + bor[0] + bor[2];
- const paddingBorderHeight = pad[1] + pad[3] + bor[1] + bor[3];
- const styleWidth = forceWidth ? NaN : resolveValue(style.width, ownerWidth);
- const styleHeight = forceHeight ? NaN : resolveValue(style.height, ownerHeight);
- let width = availableWidth;
- let height = availableHeight;
- let wMode = widthMode;
- let hMode = heightMode;
- if (isDefined(styleWidth)) {
- width = styleWidth;
- wMode = MeasureMode.Exactly;
- }
- if (isDefined(styleHeight)) {
- height = styleHeight;
- hMode = MeasureMode.Exactly;
- }
- width = boundAxis(style, true, width, ownerWidth, ownerHeight);
- height = boundAxis(style, false, height, ownerWidth, ownerHeight);
- if (node.measureFunc && node.children.length === 0) {
- const innerW = wMode === MeasureMode.Undefined ? NaN : Math.max(0, width - paddingBorderWidth);
- const innerH = hMode === MeasureMode.Undefined ? NaN : Math.max(0, height - paddingBorderHeight);
- _yogaMeasureCalls++;
- const measured = node.measureFunc(innerW, wMode, innerH, hMode);
- node.layout.width = wMode === MeasureMode.Exactly ? width : boundAxis(style, true, (measured.width ?? 0) + paddingBorderWidth, ownerWidth, ownerHeight);
- node.layout.height = hMode === MeasureMode.Exactly ? height : boundAxis(style, false, (measured.height ?? 0) + paddingBorderHeight, ownerWidth, ownerHeight);
- commitCacheOutputs(node, performLayout);
- cacheWrite(node, availableWidth, availableHeight, widthMode, heightMode, ownerWidth, ownerHeight, forceWidth, forceHeight, wasDirty);
- return;
- }
- if (node.children.length === 0) {
- node.layout.width = wMode === MeasureMode.Exactly ? width : boundAxis(style, true, paddingBorderWidth, ownerWidth, ownerHeight);
- node.layout.height = hMode === MeasureMode.Exactly ? height : boundAxis(style, false, paddingBorderHeight, ownerWidth, ownerHeight);
- commitCacheOutputs(node, performLayout);
- cacheWrite(node, availableWidth, availableHeight, widthMode, heightMode, ownerWidth, ownerHeight, forceWidth, forceHeight, wasDirty);
- return;
- }
- const mainAxis = style.flexDirection;
- const crossAx = crossAxis(mainAxis);
- const isMainRow = isRow(mainAxis);
- const mainSize = isMainRow ? width : height;
- const crossSize = isMainRow ? height : width;
- const mainMode = isMainRow ? wMode : hMode;
- const crossMode = isMainRow ? hMode : wMode;
- const mainPadBorder = isMainRow ? paddingBorderWidth : paddingBorderHeight;
- const crossPadBorder = isMainRow ? paddingBorderHeight : paddingBorderWidth;
- const innerMainSize = isDefined(mainSize) ? Math.max(0, mainSize - mainPadBorder) : NaN;
- const innerCrossSize = isDefined(crossSize) ? Math.max(0, crossSize - crossPadBorder) : NaN;
- const gapMain = resolveGap(style, isMainRow ? Gutter.Column : Gutter.Row, innerMainSize);
- const flowChildren = [];
- const absChildren = [];
- collectLayoutChildren(node, flowChildren, absChildren);
- const ownerW = isDefined(width) ? width : NaN;
- const ownerH = isDefined(height) ? height : NaN;
- const isWrap = style.flexWrap !== Wrap.NoWrap;
- const gapCross = resolveGap(style, isMainRow ? Gutter.Row : Gutter.Column, innerCrossSize);
- for (const c8 of flowChildren) {
- c8._flexBasis = computeFlexBasis(c8, mainAxis, innerMainSize, innerCrossSize, crossMode, ownerW, ownerH);
- }
- const lines = [];
- if (!isWrap || !isDefined(innerMainSize) || flowChildren.length === 0) {
- for (const c8 of flowChildren)
- c8._lineIndex = 0;
- lines.push(flowChildren);
- } else {
- let lineStart = 0;
- let lineLen = 0;
- for (let i5 = 0;i5 < flowChildren.length; i5++) {
- const c8 = flowChildren[i5];
- const hypo = boundAxis(c8.style, isMainRow, c8._flexBasis, ownerW, ownerH);
- const outer = Math.max(0, hypo) + childMarginForAxis(c8, mainAxis, ownerW);
- const withGap = i5 > lineStart ? gapMain : 0;
- if (i5 > lineStart && lineLen + withGap + outer > innerMainSize) {
- lines.push(flowChildren.slice(lineStart, i5));
- lineStart = i5;
- lineLen = outer;
- } else {
- lineLen += withGap + outer;
- }
- c8._lineIndex = lines.length;
- }
- lines.push(flowChildren.slice(lineStart));
- }
- const lineCount = lines.length;
- const isBaseline = isBaselineLayout(node, flowChildren);
- const lineConsumedMain = new Array(lineCount);
- const lineCrossSizes = new Array(lineCount);
- const lineMaxAscent = isBaseline ? new Array(lineCount).fill(0) : [];
- let maxLineMain = 0;
- let totalLinesCross = 0;
- for (let li = 0;li < lineCount; li++) {
- const line = lines[li];
- const lineGap = line.length > 1 ? gapMain * (line.length - 1) : 0;
- let lineBasis = lineGap;
- for (const c8 of line) {
- lineBasis += c8._flexBasis + childMarginForAxis(c8, mainAxis, ownerW);
- }
- let availMain = innerMainSize;
- if (!isDefined(availMain)) {
- const mainOwner = isMainRow ? ownerWidth : ownerHeight;
- const minM = resolveValue(isMainRow ? style.minWidth : style.minHeight, mainOwner);
- const maxM = resolveValue(isMainRow ? style.maxWidth : style.maxHeight, mainOwner);
- if (isDefined(maxM) && lineBasis > maxM - mainPadBorder) {
- availMain = Math.max(0, maxM - mainPadBorder);
- } else if (isDefined(minM) && lineBasis < minM - mainPadBorder) {
- availMain = Math.max(0, minM - mainPadBorder);
- }
- }
- resolveFlexibleLengths(line, availMain, lineBasis, isMainRow, ownerW, ownerH);
- let lineCross = 0;
- for (const c8 of line) {
- const cStyle = c8.style;
- const childAlign = cStyle.alignSelf === Align.Auto ? style.alignItems : cStyle.alignSelf;
- const cMarginCross = childMarginForAxis(c8, crossAx, ownerW);
- let childCrossSize = NaN;
- let childCrossMode = MeasureMode.Undefined;
- const resolvedCrossStyle = resolveValue(isMainRow ? cStyle.height : cStyle.width, isMainRow ? ownerH : ownerW);
- const crossLeadE = isMainRow ? EDGE_TOP : EDGE_LEFT;
- const crossTrailE = isMainRow ? EDGE_BOTTOM : EDGE_RIGHT;
- const hasCrossAutoMargin = c8._hasAutoMargin && (isMarginAuto(cStyle.margin, crossLeadE) || isMarginAuto(cStyle.margin, crossTrailE));
- if (isDefined(resolvedCrossStyle)) {
- childCrossSize = resolvedCrossStyle;
- childCrossMode = MeasureMode.Exactly;
- } else if (childAlign === Align.Stretch && !hasCrossAutoMargin && !isWrap && isDefined(innerCrossSize) && crossMode === MeasureMode.Exactly) {
- childCrossSize = Math.max(0, innerCrossSize - cMarginCross);
- childCrossMode = MeasureMode.Exactly;
- } else if (!isWrap && isDefined(innerCrossSize)) {
- childCrossSize = Math.max(0, innerCrossSize - cMarginCross);
- childCrossMode = MeasureMode.AtMost;
- }
- const cw = isMainRow ? c8._mainSize : childCrossSize;
- const ch = isMainRow ? childCrossSize : c8._mainSize;
- layoutNode(c8, cw, ch, isMainRow ? MeasureMode.Exactly : childCrossMode, isMainRow ? childCrossMode : MeasureMode.Exactly, ownerW, ownerH, performLayout, isMainRow, !isMainRow);
- c8._crossSize = isMainRow ? c8.layout.height : c8.layout.width;
- lineCross = Math.max(lineCross, c8._crossSize + cMarginCross);
- }
- if (isBaseline) {
- let maxAscent = 0;
- let maxDescent = 0;
- for (const c8 of line) {
- if (resolveChildAlign(node, c8) !== Align.Baseline)
- continue;
- const mTop = resolveEdge(c8.style.margin, EDGE_TOP, ownerW);
- const mBot = resolveEdge(c8.style.margin, EDGE_BOTTOM, ownerW);
- const ascent = calculateBaseline(c8) + mTop;
- const descent = c8.layout.height + mTop + mBot - ascent;
- if (ascent > maxAscent)
- maxAscent = ascent;
- if (descent > maxDescent)
- maxDescent = descent;
- }
- lineMaxAscent[li] = maxAscent;
- if (maxAscent + maxDescent > lineCross) {
- lineCross = maxAscent + maxDescent;
- }
- }
- const mainLead = leadingEdge(mainAxis);
- const mainTrail = trailingEdge(mainAxis);
- let consumed = lineGap;
- for (const c8 of line) {
- const cm = c8.layout.margin;
- consumed += c8._mainSize + cm[mainLead] + cm[mainTrail];
- }
- lineConsumedMain[li] = consumed;
- lineCrossSizes[li] = lineCross;
- maxLineMain = Math.max(maxLineMain, consumed);
- totalLinesCross += lineCross;
- }
- const totalCrossGap = lineCount > 1 ? gapCross * (lineCount - 1) : 0;
- totalLinesCross += totalCrossGap;
- const isScroll = style.overflow === Overflow.Scroll;
- const contentMain = maxLineMain + mainPadBorder;
- const finalMainSize = mainMode === MeasureMode.Exactly ? mainSize : mainMode === MeasureMode.AtMost && isScroll ? Math.max(Math.min(mainSize, contentMain), mainPadBorder) : isWrap && lineCount > 1 && mainMode === MeasureMode.AtMost ? mainSize : contentMain;
- const contentCross = totalLinesCross + crossPadBorder;
- const finalCrossSize = crossMode === MeasureMode.Exactly ? crossSize : crossMode === MeasureMode.AtMost && isScroll ? Math.max(Math.min(crossSize, contentCross), crossPadBorder) : contentCross;
- node.layout.width = boundAxis(style, true, isMainRow ? finalMainSize : finalCrossSize, ownerWidth, ownerHeight);
- node.layout.height = boundAxis(style, false, isMainRow ? finalCrossSize : finalMainSize, ownerWidth, ownerHeight);
- commitCacheOutputs(node, performLayout);
- cacheWrite(node, availableWidth, availableHeight, widthMode, heightMode, ownerWidth, ownerHeight, forceWidth, forceHeight, wasDirty);
- if (!performLayout)
- return;
- const actualInnerMain = (isMainRow ? node.layout.width : node.layout.height) - mainPadBorder;
- const actualInnerCross = (isMainRow ? node.layout.height : node.layout.width) - crossPadBorder;
- const mainLeadEdgePhys = leadingEdge(mainAxis);
- const mainTrailEdgePhys = trailingEdge(mainAxis);
- const crossLeadEdgePhys = isMainRow ? EDGE_TOP : EDGE_LEFT;
- const crossTrailEdgePhys = isMainRow ? EDGE_BOTTOM : EDGE_RIGHT;
- const reversed = isReverse(mainAxis);
- const mainContainerSize = isMainRow ? node.layout.width : node.layout.height;
- const crossLead = pad[crossLeadEdgePhys] + bor[crossLeadEdgePhys];
- let lineCrossOffset = crossLead;
- let betweenLines = gapCross;
- const freeCross = actualInnerCross - totalLinesCross;
- if (lineCount === 1 && !isWrap && !isBaseline) {
- lineCrossSizes[0] = actualInnerCross;
- } else {
- const remCross = Math.max(0, freeCross);
- switch (style.alignContent) {
- case Align.FlexStart:
- break;
- case Align.Center:
- lineCrossOffset += freeCross / 2;
- break;
- case Align.FlexEnd:
- lineCrossOffset += freeCross;
- break;
- case Align.Stretch:
- if (lineCount > 0 && remCross > 0) {
- const add = remCross / lineCount;
- for (let i5 = 0;i5 < lineCount; i5++)
- lineCrossSizes[i5] += add;
- }
- break;
- case Align.SpaceBetween:
- if (lineCount > 1)
- betweenLines += remCross / (lineCount - 1);
- break;
- case Align.SpaceAround:
- if (lineCount > 0) {
- betweenLines += remCross / lineCount;
- lineCrossOffset += remCross / lineCount / 2;
- }
- break;
- case Align.SpaceEvenly:
- if (lineCount > 0) {
- betweenLines += remCross / (lineCount + 1);
- lineCrossOffset += remCross / (lineCount + 1);
- }
- break;
- default:
- break;
- }
- }
- const wrapReverse = style.flexWrap === Wrap.WrapReverse;
- const crossContainerSize = isMainRow ? node.layout.height : node.layout.width;
- let lineCrossPos = lineCrossOffset;
- for (let li = 0;li < lineCount; li++) {
- const line = lines[li];
- const lineCross = lineCrossSizes[li];
- const consumedMain = lineConsumedMain[li];
- const n5 = line.length;
- if (isWrap || crossMode !== MeasureMode.Exactly) {
- for (const c8 of line) {
- const cStyle = c8.style;
- const childAlign = cStyle.alignSelf === Align.Auto ? style.alignItems : cStyle.alignSelf;
- const crossStyleDef = isDefined(resolveValue(isMainRow ? cStyle.height : cStyle.width, isMainRow ? ownerH : ownerW));
- const hasCrossAutoMargin = c8._hasAutoMargin && (isMarginAuto(cStyle.margin, crossLeadEdgePhys) || isMarginAuto(cStyle.margin, crossTrailEdgePhys));
- if (childAlign === Align.Stretch && !crossStyleDef && !hasCrossAutoMargin) {
- const cMarginCross = childMarginForAxis(c8, crossAx, ownerW);
- const target = Math.max(0, lineCross - cMarginCross);
- if (c8._crossSize !== target) {
- const cw = isMainRow ? c8._mainSize : target;
- const ch = isMainRow ? target : c8._mainSize;
- layoutNode(c8, cw, ch, MeasureMode.Exactly, MeasureMode.Exactly, ownerW, ownerH, performLayout, isMainRow, !isMainRow);
- c8._crossSize = target;
- }
- }
- }
- }
- let mainOffset = pad[mainLeadEdgePhys] + bor[mainLeadEdgePhys];
- let betweenMain = gapMain;
- let numAutoMarginsMain = 0;
- for (const c8 of line) {
- if (!c8._hasAutoMargin)
- continue;
- if (isMarginAuto(c8.style.margin, mainLeadEdgePhys))
- numAutoMarginsMain++;
- if (isMarginAuto(c8.style.margin, mainTrailEdgePhys))
- numAutoMarginsMain++;
- }
- const freeMain = actualInnerMain - consumedMain;
- const remainingMain = Math.max(0, freeMain);
- const autoMarginMainSize = numAutoMarginsMain > 0 && remainingMain > 0 ? remainingMain / numAutoMarginsMain : 0;
- if (numAutoMarginsMain === 0) {
- switch (style.justifyContent) {
- case Justify.FlexStart:
- break;
- case Justify.Center:
- mainOffset += freeMain / 2;
- break;
- case Justify.FlexEnd:
- mainOffset += freeMain;
- break;
- case Justify.SpaceBetween:
- if (n5 > 1)
- betweenMain += remainingMain / (n5 - 1);
- break;
- case Justify.SpaceAround:
- if (n5 > 0) {
- betweenMain += remainingMain / n5;
- mainOffset += remainingMain / n5 / 2;
- }
- break;
- case Justify.SpaceEvenly:
- if (n5 > 0) {
- betweenMain += remainingMain / (n5 + 1);
- mainOffset += remainingMain / (n5 + 1);
- }
- break;
- }
- }
- const effectiveLineCrossPos = wrapReverse ? crossContainerSize - lineCrossPos - lineCross : lineCrossPos;
- let pos = mainOffset;
- for (const c8 of line) {
- const cMargin = c8.style.margin;
- const cLayoutMargin = c8.layout.margin;
- let autoMainLead = false;
- let autoMainTrail = false;
- let autoCrossLead = false;
- let autoCrossTrail = false;
- let mMainLead;
- let mMainTrail;
- let mCrossLead;
- let mCrossTrail;
- if (c8._hasAutoMargin) {
- autoMainLead = isMarginAuto(cMargin, mainLeadEdgePhys);
- autoMainTrail = isMarginAuto(cMargin, mainTrailEdgePhys);
- autoCrossLead = isMarginAuto(cMargin, crossLeadEdgePhys);
- autoCrossTrail = isMarginAuto(cMargin, crossTrailEdgePhys);
- mMainLead = autoMainLead ? autoMarginMainSize : cLayoutMargin[mainLeadEdgePhys];
- mMainTrail = autoMainTrail ? autoMarginMainSize : cLayoutMargin[mainTrailEdgePhys];
- mCrossLead = autoCrossLead ? 0 : cLayoutMargin[crossLeadEdgePhys];
- mCrossTrail = autoCrossTrail ? 0 : cLayoutMargin[crossTrailEdgePhys];
- } else {
- mMainLead = cLayoutMargin[mainLeadEdgePhys];
- mMainTrail = cLayoutMargin[mainTrailEdgePhys];
- mCrossLead = cLayoutMargin[crossLeadEdgePhys];
- mCrossTrail = cLayoutMargin[crossTrailEdgePhys];
- }
- const mainPos = reversed ? mainContainerSize - (pos + mMainLead) - c8._mainSize : pos + mMainLead;
- const childAlign = c8.style.alignSelf === Align.Auto ? style.alignItems : c8.style.alignSelf;
- let crossPos = effectiveLineCrossPos + mCrossLead;
- const crossFree = lineCross - c8._crossSize - mCrossLead - mCrossTrail;
- if (autoCrossLead && autoCrossTrail) {
- crossPos += Math.max(0, crossFree) / 2;
- } else if (autoCrossLead) {
- crossPos += Math.max(0, crossFree);
- } else if (autoCrossTrail) {} else {
- switch (childAlign) {
- case Align.FlexStart:
- case Align.Stretch:
- if (wrapReverse)
- crossPos += crossFree;
- break;
- case Align.Center:
- crossPos += crossFree / 2;
- break;
- case Align.FlexEnd:
- if (!wrapReverse)
- crossPos += crossFree;
- break;
- case Align.Baseline:
- if (isBaseline) {
- crossPos = effectiveLineCrossPos + lineMaxAscent[li] - calculateBaseline(c8);
- }
- break;
- default:
- break;
- }
- }
- let relX = 0;
- let relY = 0;
- if (c8._hasPosition) {
- const relLeft = resolveValue(resolveEdgeRaw(c8.style.position, EDGE_LEFT), ownerW);
- const relRight = resolveValue(resolveEdgeRaw(c8.style.position, EDGE_RIGHT), ownerW);
- const relTop = resolveValue(resolveEdgeRaw(c8.style.position, EDGE_TOP), ownerW);
- const relBottom = resolveValue(resolveEdgeRaw(c8.style.position, EDGE_BOTTOM), ownerW);
- relX = isDefined(relLeft) ? relLeft : isDefined(relRight) ? -relRight : 0;
- relY = isDefined(relTop) ? relTop : isDefined(relBottom) ? -relBottom : 0;
- }
- if (isMainRow) {
- c8.layout.left = mainPos + relX;
- c8.layout.top = crossPos + relY;
- } else {
- c8.layout.left = crossPos + relX;
- c8.layout.top = mainPos + relY;
- }
- pos += c8._mainSize + mMainLead + mMainTrail + betweenMain;
- }
- lineCrossPos += lineCross + betweenLines;
- }
- for (const c8 of absChildren) {
- layoutAbsoluteChild(node, c8, node.layout.width, node.layout.height, pad, bor);
- }
-}
-function layoutAbsoluteChild(parent, child, parentWidth, parentHeight, pad, bor) {
- const cs = child.style;
- const posLeft = resolveEdgeRaw(cs.position, EDGE_LEFT);
- const posRight = resolveEdgeRaw(cs.position, EDGE_RIGHT);
- const posTop = resolveEdgeRaw(cs.position, EDGE_TOP);
- const posBottom = resolveEdgeRaw(cs.position, EDGE_BOTTOM);
- const rLeft = resolveValue(posLeft, parentWidth);
- const rRight = resolveValue(posRight, parentWidth);
- const rTop = resolveValue(posTop, parentHeight);
- const rBottom = resolveValue(posBottom, parentHeight);
- const paddingBoxW = parentWidth - bor[0] - bor[2];
- const paddingBoxH = parentHeight - bor[1] - bor[3];
- let cw = resolveValue(cs.width, paddingBoxW);
- let ch = resolveValue(cs.height, paddingBoxH);
- if (!isDefined(cw) && isDefined(rLeft) && isDefined(rRight)) {
- cw = paddingBoxW - rLeft - rRight;
- }
- if (!isDefined(ch) && isDefined(rTop) && isDefined(rBottom)) {
- ch = paddingBoxH - rTop - rBottom;
- }
- layoutNode(child, cw, ch, isDefined(cw) ? MeasureMode.Exactly : MeasureMode.Undefined, isDefined(ch) ? MeasureMode.Exactly : MeasureMode.Undefined, paddingBoxW, paddingBoxH, true);
- const mL = resolveEdge(cs.margin, EDGE_LEFT, parentWidth);
- const mT = resolveEdge(cs.margin, EDGE_TOP, parentWidth);
- const mR = resolveEdge(cs.margin, EDGE_RIGHT, parentWidth);
- const mB = resolveEdge(cs.margin, EDGE_BOTTOM, parentWidth);
- const mainAxis = parent.style.flexDirection;
- const reversed = isReverse(mainAxis);
- const mainRow = isRow(mainAxis);
- const wrapReverse = parent.style.flexWrap === Wrap.WrapReverse;
- const alignment = cs.alignSelf === Align.Auto ? parent.style.alignItems : cs.alignSelf;
- let left;
- if (isDefined(rLeft)) {
- left = bor[0] + rLeft + mL;
- } else if (isDefined(rRight)) {
- left = parentWidth - bor[2] - rRight - child.layout.width - mR;
- } else if (mainRow) {
- const lead = pad[0] + bor[0];
- const trail = parentWidth - pad[2] - bor[2];
- left = reversed ? trail - child.layout.width - mR : justifyAbsolute(parent.style.justifyContent, lead, trail, child.layout.width) + mL;
- } else {
- left = alignAbsolute(alignment, pad[0] + bor[0], parentWidth - pad[2] - bor[2], child.layout.width, wrapReverse) + mL;
- }
- let top;
- if (isDefined(rTop)) {
- top = bor[1] + rTop + mT;
- } else if (isDefined(rBottom)) {
- top = parentHeight - bor[3] - rBottom - child.layout.height - mB;
- } else if (mainRow) {
- top = alignAbsolute(alignment, pad[1] + bor[1], parentHeight - pad[3] - bor[3], child.layout.height, wrapReverse) + mT;
- } else {
- const lead = pad[1] + bor[1];
- const trail = parentHeight - pad[3] - bor[3];
- top = reversed ? trail - child.layout.height - mB : justifyAbsolute(parent.style.justifyContent, lead, trail, child.layout.height) + mT;
- }
- child.layout.left = left;
- child.layout.top = top;
-}
-function justifyAbsolute(justify, leadEdge, trailEdge, childSize) {
- switch (justify) {
- case Justify.Center:
- return leadEdge + (trailEdge - leadEdge - childSize) / 2;
- case Justify.FlexEnd:
- return trailEdge - childSize;
- default:
- return leadEdge;
- }
-}
-function alignAbsolute(align, leadEdge, trailEdge, childSize, wrapReverse) {
- switch (align) {
- case Align.Center:
- return leadEdge + (trailEdge - leadEdge - childSize) / 2;
- case Align.FlexEnd:
- return wrapReverse ? leadEdge : trailEdge - childSize;
- default:
- return wrapReverse ? trailEdge - childSize : leadEdge;
- }
-}
-function computeFlexBasis(child, mainAxis, availableMain, availableCross, crossMode, ownerWidth, ownerHeight) {
- const sameGen = child._fbGen === _generation;
- if ((sameGen || !child.isDirty_) && child._fbCrossMode === crossMode && sameFloat(child._fbOwnerW, ownerWidth) && sameFloat(child._fbOwnerH, ownerHeight) && sameFloat(child._fbAvailMain, availableMain) && sameFloat(child._fbAvailCross, availableCross)) {
- return child._fbBasis;
- }
- const cs = child.style;
- const isMainRow = isRow(mainAxis);
- const basis = resolveValue(cs.flexBasis, availableMain);
- if (isDefined(basis)) {
- const b5 = Math.max(0, basis);
- child._fbBasis = b5;
- child._fbOwnerW = ownerWidth;
- child._fbOwnerH = ownerHeight;
- child._fbAvailMain = availableMain;
- child._fbAvailCross = availableCross;
- child._fbCrossMode = crossMode;
- child._fbGen = _generation;
- return b5;
- }
- const mainStyleDim = isMainRow ? cs.width : cs.height;
- const mainOwner = isMainRow ? ownerWidth : ownerHeight;
- const resolved = resolveValue(mainStyleDim, mainOwner);
- if (isDefined(resolved)) {
- const b5 = Math.max(0, resolved);
- child._fbBasis = b5;
- child._fbOwnerW = ownerWidth;
- child._fbOwnerH = ownerHeight;
- child._fbAvailMain = availableMain;
- child._fbAvailCross = availableCross;
- child._fbCrossMode = crossMode;
- child._fbGen = _generation;
- return b5;
- }
- const crossStyleDim = isMainRow ? cs.height : cs.width;
- const crossOwner = isMainRow ? ownerHeight : ownerWidth;
- let crossConstraint = resolveValue(crossStyleDim, crossOwner);
- let crossConstraintMode = isDefined(crossConstraint) ? MeasureMode.Exactly : MeasureMode.Undefined;
- if (!isDefined(crossConstraint) && isDefined(availableCross)) {
- crossConstraint = availableCross;
- crossConstraintMode = crossMode === MeasureMode.Exactly && isStretchAlign(child) ? MeasureMode.Exactly : MeasureMode.AtMost;
- }
- let mainConstraint = NaN;
- let mainConstraintMode = MeasureMode.Undefined;
- if (isMainRow && isDefined(availableMain) && hasMeasureFuncInSubtree(child)) {
- mainConstraint = availableMain;
- mainConstraintMode = MeasureMode.AtMost;
- }
- const mw = isMainRow ? mainConstraint : crossConstraint;
- const mh = isMainRow ? crossConstraint : mainConstraint;
- const mwMode = isMainRow ? mainConstraintMode : crossConstraintMode;
- const mhMode = isMainRow ? crossConstraintMode : mainConstraintMode;
- layoutNode(child, mw, mh, mwMode, mhMode, ownerWidth, ownerHeight, false);
- const b4 = isMainRow ? child.layout.width : child.layout.height;
- child._fbBasis = b4;
- child._fbOwnerW = ownerWidth;
- child._fbOwnerH = ownerHeight;
- child._fbAvailMain = availableMain;
- child._fbAvailCross = availableCross;
- child._fbCrossMode = crossMode;
- child._fbGen = _generation;
- return b4;
-}
-function hasMeasureFuncInSubtree(node) {
- if (node.measureFunc)
- return true;
- for (const c8 of node.children) {
- if (hasMeasureFuncInSubtree(c8))
- return true;
- }
- return false;
-}
-function resolveFlexibleLengths(children, availableInnerMain, totalFlexBasis, isMainRow, ownerW, ownerH) {
- const n5 = children.length;
- const frozen = new Array(n5).fill(false);
- const initialFree = isDefined(availableInnerMain) ? availableInnerMain - totalFlexBasis : 0;
- for (let i5 = 0;i5 < n5; i5++) {
- const c8 = children[i5];
- const clamped = boundAxis(c8.style, isMainRow, c8._flexBasis, ownerW, ownerH);
- const inflexible = !isDefined(availableInnerMain) || (initialFree >= 0 ? c8.style.flexGrow === 0 : c8.style.flexShrink === 0);
- if (inflexible) {
- c8._mainSize = Math.max(0, clamped);
- frozen[i5] = true;
- } else {
- c8._mainSize = c8._flexBasis;
- }
- }
- const unclamped = new Array(n5);
- for (let iter = 0;iter <= n5; iter++) {
- let frozenDelta = 0;
- let totalGrow = 0;
- let totalShrinkScaled = 0;
- let unfrozenCount = 0;
- for (let i5 = 0;i5 < n5; i5++) {
- const c8 = children[i5];
- if (frozen[i5]) {
- frozenDelta += c8._mainSize - c8._flexBasis;
- } else {
- totalGrow += c8.style.flexGrow;
- totalShrinkScaled += c8.style.flexShrink * c8._flexBasis;
- unfrozenCount++;
- }
- }
- if (unfrozenCount === 0)
- break;
- let remaining = initialFree - frozenDelta;
- if (remaining > 0 && totalGrow > 0 && totalGrow < 1) {
- const scaled = initialFree * totalGrow;
- if (scaled < remaining)
- remaining = scaled;
- } else if (remaining < 0 && totalShrinkScaled > 0) {
- let totalShrink = 0;
- for (let i5 = 0;i5 < n5; i5++) {
- if (!frozen[i5])
- totalShrink += children[i5].style.flexShrink;
- }
- if (totalShrink < 1) {
- const scaled = initialFree * totalShrink;
- if (scaled > remaining)
- remaining = scaled;
- }
- }
- let totalViolation = 0;
- for (let i5 = 0;i5 < n5; i5++) {
- if (frozen[i5])
- continue;
- const c8 = children[i5];
- let t4 = c8._flexBasis;
- if (remaining > 0 && totalGrow > 0) {
- t4 += remaining * c8.style.flexGrow / totalGrow;
- } else if (remaining < 0 && totalShrinkScaled > 0) {
- t4 += remaining * (c8.style.flexShrink * c8._flexBasis) / totalShrinkScaled;
- }
- unclamped[i5] = t4;
- const clamped = Math.max(0, boundAxis(c8.style, isMainRow, t4, ownerW, ownerH));
- c8._mainSize = clamped;
- totalViolation += clamped - t4;
- }
- if (totalViolation === 0)
- break;
- let anyFrozen = false;
- for (let i5 = 0;i5 < n5; i5++) {
- if (frozen[i5])
- continue;
- const v6 = children[i5]._mainSize - unclamped[i5];
- if (totalViolation > 0 && v6 > 0 || totalViolation < 0 && v6 < 0) {
- frozen[i5] = true;
- anyFrozen = true;
- }
- }
- if (!anyFrozen)
- break;
- }
-}
-function isStretchAlign(child) {
- const p4 = child.parent;
- if (!p4)
- return false;
- const align = child.style.alignSelf === Align.Auto ? p4.style.alignItems : child.style.alignSelf;
- return align === Align.Stretch;
-}
-function resolveChildAlign(parent, child) {
- return child.style.alignSelf === Align.Auto ? parent.style.alignItems : child.style.alignSelf;
-}
-function calculateBaseline(node) {
- let baselineChild = null;
- for (const c8 of node.children) {
- if (c8._lineIndex > 0)
- break;
- if (c8.style.positionType === PositionType.Absolute)
- continue;
- if (c8.style.display === Display.None)
- continue;
- if (resolveChildAlign(node, c8) === Align.Baseline || c8.isReferenceBaseline_) {
- baselineChild = c8;
- break;
- }
- if (baselineChild === null)
- baselineChild = c8;
- }
- if (baselineChild === null)
- return node.layout.height;
- return calculateBaseline(baselineChild) + baselineChild.layout.top;
-}
-function isBaselineLayout(node, flowChildren) {
- if (!isRow(node.style.flexDirection))
- return false;
- if (node.style.alignItems === Align.Baseline)
- return true;
- for (const c8 of flowChildren) {
- if (c8.style.alignSelf === Align.Baseline)
- return true;
- }
- return false;
-}
-function childMarginForAxis(child, axis, ownerWidth) {
- if (!child._hasMargin)
- return 0;
- const lead = resolveEdge(child.style.margin, leadingEdge(axis), ownerWidth);
- const trail = resolveEdge(child.style.margin, trailingEdge(axis), ownerWidth);
- return lead + trail;
-}
-function resolveGap(style, gutter, ownerSize) {
- let v6 = style.gap[gutter];
- if (v6.unit === Unit.Undefined)
- v6 = style.gap[Gutter.All];
- const r4 = resolveValue(v6, ownerSize);
- return isDefined(r4) ? Math.max(0, r4) : 0;
-}
-function boundAxis(style, isWidth, value, ownerWidth, ownerHeight) {
- const minV = isWidth ? style.minWidth : style.minHeight;
- const maxV = isWidth ? style.maxWidth : style.maxHeight;
- const minU = minV.unit;
- const maxU = maxV.unit;
- if (minU === 0 && maxU === 0)
- return value;
- const owner = isWidth ? ownerWidth : ownerHeight;
- let v6 = value;
- if (maxU === 1) {
- if (v6 > maxV.value)
- v6 = maxV.value;
- } else if (maxU === 2) {
- const m4 = maxV.value * owner / 100;
- if (m4 === m4 && v6 > m4)
- v6 = m4;
- }
- if (minU === 1) {
- if (v6 < minV.value)
- v6 = minV.value;
- } else if (minU === 2) {
- const m4 = minV.value * owner / 100;
- if (m4 === m4 && v6 < m4)
- v6 = m4;
- }
- return v6;
-}
-function zeroLayoutRecursive(node) {
- for (const c8 of node.children) {
- c8.layout.left = 0;
- c8.layout.top = 0;
- c8.layout.width = 0;
- c8.layout.height = 0;
- c8.isDirty_ = true;
- c8._hasL = false;
- c8._hasM = false;
- zeroLayoutRecursive(c8);
- }
-}
-function collectLayoutChildren(node, flow, abs) {
- for (const c8 of node.children) {
- const disp = c8.style.display;
- if (disp === Display.None) {
- c8.layout.left = 0;
- c8.layout.top = 0;
- c8.layout.width = 0;
- c8.layout.height = 0;
- zeroLayoutRecursive(c8);
- } else if (disp === Display.Contents) {
- c8.layout.left = 0;
- c8.layout.top = 0;
- c8.layout.width = 0;
- c8.layout.height = 0;
- collectLayoutChildren(c8, flow, abs);
- } else if (c8.style.positionType === PositionType.Absolute) {
- abs.push(c8);
- } else {
- flow.push(c8);
- }
- }
-}
-function roundLayout(node, scale, absLeft, absTop) {
- if (scale === 0)
- return;
- const l4 = node.layout;
- const nodeLeft = l4.left;
- const nodeTop = l4.top;
- const nodeWidth = l4.width;
- const nodeHeight = l4.height;
- const absNodeLeft = absLeft + nodeLeft;
- const absNodeTop = absTop + nodeTop;
- const isText = node.measureFunc !== null;
- l4.left = roundValue(nodeLeft, scale, false, isText);
- l4.top = roundValue(nodeTop, scale, false, isText);
- const absRight = absNodeLeft + nodeWidth;
- const absBottom = absNodeTop + nodeHeight;
- const hasFracW = !isWholeNumber(nodeWidth * scale);
- const hasFracH = !isWholeNumber(nodeHeight * scale);
- l4.width = roundValue(absRight, scale, isText && hasFracW, isText && !hasFracW) - roundValue(absNodeLeft, scale, false, isText);
- l4.height = roundValue(absBottom, scale, isText && hasFracH, isText && !hasFracH) - roundValue(absNodeTop, scale, false, isText);
- for (const c8 of node.children) {
- roundLayout(c8, scale, absNodeLeft, absNodeTop);
- }
-}
-function isWholeNumber(v6) {
- const frac = v6 - Math.floor(v6);
- return frac < 0.0001 || frac > 0.9999;
-}
-function roundValue(v6, scale, forceCeil, forceFloor) {
- let scaled = v6 * scale;
- let frac = scaled - Math.floor(scaled);
- if (frac < 0)
- frac += 1;
- if (frac < 0.0001) {
- scaled = Math.floor(scaled);
- } else if (frac > 0.9999) {
- scaled = Math.ceil(scaled);
- } else if (forceCeil) {
- scaled = Math.ceil(scaled);
- } else if (forceFloor) {
- scaled = Math.floor(scaled);
- } else {
- scaled = Math.floor(scaled) + (frac >= 0.4999 ? 1 : 0);
- }
- return scaled / scale;
-}
-function parseDimension(v6) {
- if (v6 === undefined)
- return UNDEFINED_VALUE;
- if (v6 === "auto")
- return AUTO_VALUE;
- if (typeof v6 === "number") {
- return Number.isFinite(v6) ? pointValue(v6) : UNDEFINED_VALUE;
- }
- if (typeof v6 === "string" && v6.endsWith("%")) {
- return percentValue(parseFloat(v6));
- }
- const n5 = parseFloat(v6);
- return isNaN(n5) ? UNDEFINED_VALUE : pointValue(n5);
-}
-function physicalEdge(edge) {
- switch (edge) {
- case Edge.Left:
- case Edge.Start:
- return EDGE_LEFT;
- case Edge.Top:
- return EDGE_TOP;
- case Edge.Right:
- case Edge.End:
- return EDGE_RIGHT;
- case Edge.Bottom:
- return EDGE_BOTTOM;
- default:
- return EDGE_LEFT;
- }
-}
-var UNDEFINED_VALUE, AUTO_VALUE, EDGE_LEFT = 0, EDGE_TOP = 1, EDGE_RIGHT = 2, EDGE_BOTTOM = 3, DEFAULT_CONFIG, CACHE_SLOTS = 4, _generation = 0, _yogaNodesVisited = 0, _yogaMeasureCalls = 0, _yogaCacheHits = 0, _yogaLiveNodes = 0, YOGA_INSTANCE, yoga_layout_default;
-var init_yoga_layout = __esm(() => {
- init_enums3();
- UNDEFINED_VALUE = { unit: Unit.Undefined, value: NaN };
- AUTO_VALUE = { unit: Unit.Auto, value: NaN };
- DEFAULT_CONFIG = createConfig();
- YOGA_INSTANCE = {
- Config: {
- create: createConfig,
- destroy() {}
- },
- Node: {
- create: (config8) => new Node(config8),
- createDefault: () => new Node,
- createWithConfig: (config8) => new Node(config8),
- destroy() {}
- }
- };
- yoga_layout_default = YOGA_INSTANCE;
-});
-
-// src/ink/colorize.ts
-function boostChalkLevelForXtermJs() {
- if (process.env.TERM_PROGRAM === "vscode" && source_default.level === 2) {
- source_default.level = 3;
- return true;
- }
- return false;
-}
-function clampChalkLevelForTmux() {
- if (process.env.CLAUDE_CODE_TMUX_TRUECOLOR)
- return false;
- if (process.env.TMUX && source_default.level > 2) {
- source_default.level = 2;
- return true;
- }
- return false;
-}
-function applyTextStyles(text, styles3) {
- let result = text;
- if (styles3.inverse) {
- result = source_default.inverse(result);
- }
- if (styles3.strikethrough) {
- result = source_default.strikethrough(result);
- }
- if (styles3.underline) {
- result = source_default.underline(result);
- }
- if (styles3.italic) {
- result = source_default.italic(result);
- }
- if (styles3.bold) {
- result = source_default.bold(result);
- }
- if (styles3.dim) {
- result = source_default.dim(result);
- }
- if (styles3.color) {
- result = colorize(result, styles3.color, "foreground");
- }
- if (styles3.backgroundColor) {
- result = colorize(result, styles3.backgroundColor, "background");
- }
- return result;
-}
-function applyColor(text, color) {
- if (!color) {
- return text;
- }
- return colorize(text, color, "foreground");
-}
-var CHALK_BOOSTED_FOR_XTERMJS, CHALK_CLAMPED_FOR_TMUX, RGB_REGEX, ANSI_REGEX, colorize = (str, color, type) => {
- if (!color) {
- return str;
- }
- if (color.startsWith("ansi:")) {
- const value = color.substring("ansi:".length);
- switch (value) {
- case "black":
- return type === "foreground" ? source_default.black(str) : source_default.bgBlack(str);
- case "red":
- return type === "foreground" ? source_default.red(str) : source_default.bgRed(str);
- case "green":
- return type === "foreground" ? source_default.green(str) : source_default.bgGreen(str);
- case "yellow":
- return type === "foreground" ? source_default.yellow(str) : source_default.bgYellow(str);
- case "blue":
- return type === "foreground" ? source_default.blue(str) : source_default.bgBlue(str);
- case "magenta":
- return type === "foreground" ? source_default.magenta(str) : source_default.bgMagenta(str);
- case "cyan":
- return type === "foreground" ? source_default.cyan(str) : source_default.bgCyan(str);
- case "white":
- return type === "foreground" ? source_default.white(str) : source_default.bgWhite(str);
- case "blackBright":
- return type === "foreground" ? source_default.blackBright(str) : source_default.bgBlackBright(str);
- case "redBright":
- return type === "foreground" ? source_default.redBright(str) : source_default.bgRedBright(str);
- case "greenBright":
- return type === "foreground" ? source_default.greenBright(str) : source_default.bgGreenBright(str);
- case "yellowBright":
- return type === "foreground" ? source_default.yellowBright(str) : source_default.bgYellowBright(str);
- case "blueBright":
- return type === "foreground" ? source_default.blueBright(str) : source_default.bgBlueBright(str);
- case "magentaBright":
- return type === "foreground" ? source_default.magentaBright(str) : source_default.bgMagentaBright(str);
- case "cyanBright":
- return type === "foreground" ? source_default.cyanBright(str) : source_default.bgCyanBright(str);
- case "whiteBright":
- return type === "foreground" ? source_default.whiteBright(str) : source_default.bgWhiteBright(str);
- }
- }
- if (color.startsWith("#")) {
- return type === "foreground" ? source_default.hex(color)(str) : source_default.bgHex(color)(str);
- }
- if (color.startsWith("ansi256")) {
- const matches = ANSI_REGEX.exec(color);
- if (!matches) {
- return str;
- }
- const value = Number(matches[1]);
- return type === "foreground" ? source_default.ansi256(value)(str) : source_default.bgAnsi256(value)(str);
- }
- if (color.startsWith("rgb")) {
- const matches = RGB_REGEX.exec(color);
- if (!matches) {
- return str;
- }
- const firstValue = Number(matches[1]);
- const secondValue = Number(matches[2]);
- const thirdValue = Number(matches[3]);
- return type === "foreground" ? source_default.rgb(firstValue, secondValue, thirdValue)(str) : source_default.bgRgb(firstValue, secondValue, thirdValue)(str);
- }
- return str;
-};
-var init_colorize = __esm(() => {
- init_source();
- CHALK_BOOSTED_FOR_XTERMJS = boostChalkLevelForXtermJs();
- CHALK_CLAMPED_FOR_TMUX = clampChalkLevelForTmux();
- RGB_REGEX = /^rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)$/;
- ANSI_REGEX = /^ansi256\(\s?(\d+)\s?\)$/;
-});
-
-// src/utils/earlyInput.ts
-function stopCapturingEarlyInput() {
- if (!isCapturing) {
- return;
- }
- isCapturing = false;
- if (readableHandler) {
- process.stdin.removeListener("readable", readableHandler);
- readableHandler = null;
- }
-}
-function consumeEarlyInput() {
- stopCapturingEarlyInput();
- const input = earlyInputBuffer.trim();
- earlyInputBuffer = "";
- return input;
-}
-function seedEarlyInput(text) {
- earlyInputBuffer = text;
-}
-var earlyInputBuffer = "", isCapturing = false, readableHandler = null;
-var init_earlyInput = __esm(() => {
- init_intl();
-});
-
-// src/utils/fullscreen.ts
-import { spawnSync as spawnSync2 } from "child_process";
-function isTmuxControlModeEnvHeuristic() {
- if (!process.env.TMUX)
- return false;
- if (process.env.TERM_PROGRAM !== "iTerm.app")
- return false;
- const term = process.env.TERM ?? "";
- return !term.startsWith("screen") && !term.startsWith("tmux");
-}
-function probeTmuxControlModeSync() {
- tmuxControlModeProbed = isTmuxControlModeEnvHeuristic();
- if (tmuxControlModeProbed)
- return;
- if (!process.env.TMUX)
- return;
- if (process.env.TERM_PROGRAM)
- return;
- let result;
- try {
- result = spawnSync2("tmux", ["display-message", "-p", "#{client_control_mode}"], { encoding: "utf8", timeout: 2000 });
- } catch {
- return;
- }
- if (result.status !== 0)
- return;
- tmuxControlModeProbed = result.stdout.trim() === "1";
-}
-function isTmuxControlMode() {
- if (tmuxControlModeProbed === undefined)
- probeTmuxControlModeSync();
- return tmuxControlModeProbed ?? false;
-}
-function isFullscreenEnvEnabled() {
- if (isEnvDefinedFalsy(process.env.CLAUDE_CODE_NO_FLICKER))
- return false;
- if (isEnvTruthy(process.env.CLAUDE_CODE_NO_FLICKER))
- return true;
- if (isTmuxControlMode()) {
- if (!loggedTmuxCcDisable) {
- loggedTmuxCcDisable = true;
- logForDebugging("fullscreen disabled: tmux -CC (iTerm2 integration mode) detected \xB7 set CLAUDE_CODE_NO_FLICKER=1 to override");
- }
- return false;
- }
- return process.env.USER_TYPE === "ant";
-}
-function isMouseTrackingEnabled() {
- return !isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_MOUSE);
-}
-function isMouseClicksDisabled() {
- return isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_MOUSE_CLICKS);
-}
-function isFullscreenActive() {
- return getIsInteractive() && isFullscreenEnvEnabled();
-}
-async function maybeGetTmuxMouseHint() {
- if (!process.env.TMUX)
- return null;
- if (!isFullscreenActive() || isTmuxControlMode())
- return null;
- if (checkedTmuxMouseHint)
- return null;
- checkedTmuxMouseHint = true;
- const { stdout, code } = await execFileNoThrow("tmux", ["show", "-Av", "mouse"], { useCwd: false, timeout: 2000 });
- if (code !== 0 || stdout.trim() === "on")
- return null;
- return "tmux detected \xB7 scroll with PgUp/PgDn \xB7 or add 'set -g mouse on' to ~/.tmux.conf for wheel scroll";
-}
-var loggedTmuxCcDisable = false, checkedTmuxMouseHint = false, tmuxControlModeProbed;
-var init_fullscreen = __esm(() => {
- init_state();
- init_debug();
- init_envUtils();
- init_execFileNoThrow();
-});
-
-// src/ink/termio/ansi.ts
-function isEscFinal(byte) {
- return byte >= 48 && byte <= 126;
-}
-var C0, ESC = "\x1B", BEL = "\x07", SEP = ";", ESC_TYPE;
-var init_ansi = __esm(() => {
- C0 = {
- NUL: 0,
- SOH: 1,
- STX: 2,
- ETX: 3,
- EOT: 4,
- ENQ: 5,
- ACK: 6,
- BEL: 7,
- BS: 8,
- HT: 9,
- LF: 10,
- VT: 11,
- FF: 12,
- CR: 13,
- SO: 14,
- SI: 15,
- DLE: 16,
- DC1: 17,
- DC2: 18,
- DC3: 19,
- DC4: 20,
- NAK: 21,
- SYN: 22,
- ETB: 23,
- CAN: 24,
- EM: 25,
- SUB: 26,
- ESC: 27,
- FS: 28,
- GS: 29,
- RS: 30,
- US: 31,
- DEL: 127
- };
- ESC_TYPE = {
- CSI: 91,
- OSC: 93,
- DCS: 80,
- APC: 95,
- PM: 94,
- SOS: 88,
- ST: 92
- };
-});
-
-// src/ink/termio/csi.ts
-function isCSIParam(byte) {
- return byte >= CSI_RANGE.PARAM_START && byte <= CSI_RANGE.PARAM_END;
-}
-function isCSIIntermediate(byte) {
- return byte >= CSI_RANGE.INTERMEDIATE_START && byte <= CSI_RANGE.INTERMEDIATE_END;
-}
-function isCSIFinal(byte) {
- return byte >= CSI_RANGE.FINAL_START && byte <= CSI_RANGE.FINAL_END;
-}
-function csi(...args) {
- if (args.length === 0)
- return CSI_PREFIX;
- if (args.length === 1)
- return `${CSI_PREFIX}${args[0]}`;
- const params = args.slice(0, -1);
- const final = args[args.length - 1];
- return `${CSI_PREFIX}${params.join(SEP)}${final}`;
-}
-function cursorUp(n5 = 1) {
- return n5 === 0 ? "" : csi(n5, "A");
-}
-function cursorDown(n5 = 1) {
- return n5 === 0 ? "" : csi(n5, "B");
-}
-function cursorForward(n5 = 1) {
- return n5 === 0 ? "" : csi(n5, "C");
-}
-function cursorBack(n5 = 1) {
- return n5 === 0 ? "" : csi(n5, "D");
-}
-function cursorTo(col) {
- return csi(col, "G");
-}
-function cursorPosition(row, col) {
- return csi(row, col, "H");
-}
-function cursorMove(x3, y3) {
- let result = "";
- if (x3 < 0) {
- result += cursorBack(-x3);
- } else if (x3 > 0) {
- result += cursorForward(x3);
- }
- if (y3 < 0) {
- result += cursorUp(-y3);
- } else if (y3 > 0) {
- result += cursorDown(y3);
- }
- return result;
-}
-function eraseLines(n5) {
- if (n5 <= 0)
- return "";
- let result = "";
- for (let i5 = 0;i5 < n5; i5++) {
- result += ERASE_LINE;
- if (i5 < n5 - 1) {
- result += cursorUp(1);
- }
- }
- result += CURSOR_LEFT;
- return result;
-}
-function scrollUp(n5 = 1) {
- return n5 === 0 ? "" : csi(n5, "S");
-}
-function scrollDown(n5 = 1) {
- return n5 === 0 ? "" : csi(n5, "T");
-}
-function setScrollRegion(top, bottom) {
- return csi(top, bottom, "r");
-}
-var CSI_PREFIX, CSI_RANGE, CSI, ERASE_DISPLAY, ERASE_LINE_REGION, CURSOR_STYLES, CURSOR_LEFT, CURSOR_HOME, CURSOR_SAVE, CURSOR_RESTORE, ERASE_LINE, ERASE_SCREEN, ERASE_SCROLLBACK, RESET_SCROLL_REGION, PASTE_START, PASTE_END, FOCUS_IN, FOCUS_OUT, ENABLE_KITTY_KEYBOARD, DISABLE_KITTY_KEYBOARD, ENABLE_MODIFY_OTHER_KEYS, DISABLE_MODIFY_OTHER_KEYS;
-var init_csi = __esm(() => {
- init_ansi();
- CSI_PREFIX = ESC + String.fromCharCode(ESC_TYPE.CSI);
- CSI_RANGE = {
- PARAM_START: 48,
- PARAM_END: 63,
- INTERMEDIATE_START: 32,
- INTERMEDIATE_END: 47,
- FINAL_START: 64,
- FINAL_END: 126
- };
- CSI = {
- CUU: 65,
- CUD: 66,
- CUF: 67,
- CUB: 68,
- CNL: 69,
- CPL: 70,
- CHA: 71,
- CUP: 72,
- CHT: 73,
- VPA: 100,
- HVP: 102,
- ED: 74,
- EL: 75,
- ECH: 88,
- IL: 76,
- DL: 77,
- ICH: 64,
- DCH: 80,
- SU: 83,
- SD: 84,
- SM: 104,
- RM: 108,
- SGR: 109,
- DSR: 110,
- DECSCUSR: 113,
- DECSTBM: 114,
- SCOSC: 115,
- SCORC: 117,
- CBT: 90
- };
- ERASE_DISPLAY = ["toEnd", "toStart", "all", "scrollback"];
- ERASE_LINE_REGION = ["toEnd", "toStart", "all"];
- CURSOR_STYLES = [
- { style: "block", blinking: true },
- { style: "block", blinking: true },
- { style: "block", blinking: false },
- { style: "underline", blinking: true },
- { style: "underline", blinking: false },
- { style: "bar", blinking: true },
- { style: "bar", blinking: false }
- ];
- CURSOR_LEFT = csi("G");
- CURSOR_HOME = csi("H");
- CURSOR_SAVE = csi("s");
- CURSOR_RESTORE = csi("u");
- ERASE_LINE = csi(2, "K");
- ERASE_SCREEN = csi(2, "J");
- ERASE_SCROLLBACK = csi(3, "J");
- RESET_SCROLL_REGION = csi("r");
- PASTE_START = csi("200~");
- PASTE_END = csi("201~");
- FOCUS_IN = csi("I");
- FOCUS_OUT = csi("O");
- ENABLE_KITTY_KEYBOARD = csi(">1u");
- DISABLE_KITTY_KEYBOARD = csi("4;2m");
- DISABLE_MODIFY_OTHER_KEYS = csi(">4m");
-});
-
-// src/ink/termio/tokenize.ts
-function createTokenizer(options2) {
- let currentState = "ground";
- let currentBuffer = "";
- const x10Mouse = options2?.x10Mouse ?? false;
- return {
- feed(input) {
- const result = tokenize5(input, currentState, currentBuffer, false, x10Mouse);
- currentState = result.state.state;
- currentBuffer = result.state.buffer;
- return result.tokens;
- },
- flush() {
- const result = tokenize5("", currentState, currentBuffer, true, x10Mouse);
- currentState = result.state.state;
- currentBuffer = result.state.buffer;
- return result.tokens;
- },
- reset() {
- currentState = "ground";
- currentBuffer = "";
- },
- buffer() {
- return currentBuffer;
- }
- };
-}
-function tokenize5(input, initialState, initialBuffer, flush, x10Mouse) {
- const tokens = [];
- const result = {
- state: initialState,
- buffer: ""
- };
- const data = initialBuffer + input;
- let i5 = 0;
- let textStart = 0;
- let seqStart = 0;
- const flushText = () => {
- if (i5 > textStart) {
- const text = data.slice(textStart, i5);
- if (text) {
- tokens.push({ type: "text", value: text });
- }
- }
- textStart = i5;
- };
- const emitSequence = (seq) => {
- if (seq) {
- tokens.push({ type: "sequence", value: seq });
- }
- result.state = "ground";
- textStart = i5;
- };
- while (i5 < data.length) {
- const code = data.charCodeAt(i5);
- switch (result.state) {
- case "ground":
- if (code === C0.ESC) {
- flushText();
- seqStart = i5;
- result.state = "escape";
- i5++;
- } else {
- i5++;
- }
- break;
- case "escape":
- if (code === ESC_TYPE.CSI) {
- result.state = "csi";
- i5++;
- } else if (code === ESC_TYPE.OSC) {
- result.state = "osc";
- i5++;
- } else if (code === ESC_TYPE.DCS) {
- result.state = "dcs";
- i5++;
- } else if (code === ESC_TYPE.APC) {
- result.state = "apc";
- i5++;
- } else if (code === 79) {
- result.state = "ss3";
- i5++;
- } else if (isCSIIntermediate(code)) {
- result.state = "escapeIntermediate";
- i5++;
- } else if (isEscFinal(code)) {
- i5++;
- emitSequence(data.slice(seqStart, i5));
- } else if (code === C0.ESC) {
- emitSequence(data.slice(seqStart, i5));
- seqStart = i5;
- result.state = "escape";
- i5++;
- } else {
- result.state = "ground";
- textStart = seqStart;
- }
- break;
- case "escapeIntermediate":
- if (isCSIIntermediate(code)) {
- i5++;
- } else if (isEscFinal(code)) {
- i5++;
- emitSequence(data.slice(seqStart, i5));
- } else {
- result.state = "ground";
- textStart = seqStart;
- }
- break;
- case "csi":
- if (x10Mouse && code === 77 && i5 - seqStart === 2 && (i5 + 1 >= data.length || data.charCodeAt(i5 + 1) >= 32) && (i5 + 2 >= data.length || data.charCodeAt(i5 + 2) >= 32) && (i5 + 3 >= data.length || data.charCodeAt(i5 + 3) >= 32)) {
- if (i5 + 4 <= data.length) {
- i5 += 4;
- emitSequence(data.slice(seqStart, i5));
- } else {
- i5 = data.length;
- }
- break;
- }
- if (isCSIFinal(code)) {
- i5++;
- emitSequence(data.slice(seqStart, i5));
- } else if (isCSIParam(code) || isCSIIntermediate(code)) {
- i5++;
- } else {
- result.state = "ground";
- textStart = seqStart;
- }
- break;
- case "ss3":
- if (code >= 64 && code <= 126) {
- i5++;
- emitSequence(data.slice(seqStart, i5));
- } else {
- result.state = "ground";
- textStart = seqStart;
- }
- break;
- case "osc":
- if (code === C0.BEL) {
- i5++;
- emitSequence(data.slice(seqStart, i5));
- } else if (code === C0.ESC && i5 + 1 < data.length && data.charCodeAt(i5 + 1) === ESC_TYPE.ST) {
- i5 += 2;
- emitSequence(data.slice(seqStart, i5));
- } else {
- i5++;
- }
- break;
- case "dcs":
- case "apc":
- if (code === C0.BEL) {
- i5++;
- emitSequence(data.slice(seqStart, i5));
- } else if (code === C0.ESC && i5 + 1 < data.length && data.charCodeAt(i5 + 1) === ESC_TYPE.ST) {
- i5 += 2;
- emitSequence(data.slice(seqStart, i5));
- } else {
- i5++;
- }
- break;
- }
- }
- if (result.state === "ground") {
- flushText();
- } else if (flush) {
- const remaining = data.slice(seqStart);
- if (remaining)
- tokens.push({ type: "sequence", value: remaining });
- result.state = "ground";
- } else {
- result.buffer = data.slice(seqStart);
- }
- return { tokens, state: result };
-}
-var init_tokenize = __esm(() => {
- init_ansi();
- init_csi();
-});
-
-// src/ink/parse-keypress.ts
-import { Buffer as Buffer14 } from "buffer";
-function createPasteKey(content) {
- return {
- kind: "key",
- name: "",
- fn: false,
- ctrl: false,
- meta: false,
- shift: false,
- option: false,
- super: false,
- sequence: content,
- raw: content,
- isPasted: true
- };
-}
-function parseTerminalResponse(s4) {
- if (s4.startsWith("\x1B[")) {
- let m4;
- if (m4 = DECRPM_RE.exec(s4)) {
- return {
- type: "decrpm",
- mode: parseInt(m4[1], 10),
- status: parseInt(m4[2], 10)
- };
- }
- if (m4 = DA1_RE.exec(s4)) {
- return { type: "da1", params: splitNumericParams(m4[1]) };
- }
- if (m4 = DA2_RE.exec(s4)) {
- return { type: "da2", params: splitNumericParams(m4[1]) };
- }
- if (m4 = KITTY_FLAGS_RE.exec(s4)) {
- return { type: "kittyKeyboard", flags: parseInt(m4[1], 10) };
- }
- if (m4 = CURSOR_POSITION_RE.exec(s4)) {
- return {
- type: "cursorPosition",
- row: parseInt(m4[1], 10),
- col: parseInt(m4[2], 10)
- };
- }
- return null;
- }
- if (s4.startsWith("\x1B]")) {
- const m4 = OSC_RESPONSE_RE.exec(s4);
- if (m4) {
- return { type: "osc", code: parseInt(m4[1], 10), data: m4[2] };
- }
- }
- if (s4.startsWith("\x1BP")) {
- const m4 = XTVERSION_RE.exec(s4);
- if (m4) {
- return { type: "xtversion", name: m4[1] };
- }
- }
- return null;
-}
-function splitNumericParams(params) {
- if (!params)
- return [];
- return params.split(";").map((p4) => parseInt(p4, 10));
-}
-function inputToString(input) {
- if (Buffer14.isBuffer(input)) {
- if (input[0] > 127 && input[1] === undefined) {
- input[0] -= 128;
- return "\x1B" + String(input);
- } else {
- return String(input);
- }
- } else if (input !== undefined && typeof input !== "string") {
- return String(input);
- } else if (!input) {
- return "";
- } else {
- return input;
- }
-}
-function parseMultipleKeypresses(prevState, input = "") {
- const isFlush = input === null;
- const inputString = isFlush ? "" : inputToString(input);
- const tokenizer = prevState._tokenizer ?? createTokenizer({ x10Mouse: true });
- const tokens = isFlush ? tokenizer.flush() : tokenizer.feed(inputString);
- const keys2 = [];
- let inPaste = prevState.mode === "IN_PASTE";
- let pasteBuffer = prevState.pasteBuffer;
- for (const token of tokens) {
- if (token.type === "sequence") {
- if (token.value === PASTE_START) {
- inPaste = true;
- pasteBuffer = "";
- } else if (token.value === PASTE_END) {
- keys2.push(createPasteKey(pasteBuffer));
- inPaste = false;
- pasteBuffer = "";
- } else if (inPaste) {
- pasteBuffer += token.value;
- } else {
- const response7 = parseTerminalResponse(token.value);
- if (response7) {
- keys2.push({ kind: "response", sequence: token.value, response: response7 });
- } else {
- const mouse = parseMouseEvent(token.value);
- if (mouse) {
- keys2.push(mouse);
- } else {
- keys2.push(parseKeypress(token.value));
- }
- }
- }
- } else if (token.type === "text") {
- if (inPaste) {
- pasteBuffer += token.value;
- } else if (/^\[<\d+;\d+;\d+[Mm]$/.test(token.value) || /^\[M[\x60-\x7f][\x20-\uffff]{2}$/.test(token.value)) {
- const resynthesized = "\x1B" + token.value;
- const mouse = parseMouseEvent(resynthesized);
- keys2.push(mouse ?? parseKeypress(resynthesized));
- } else {
- keys2.push(parseKeypress(token.value));
- }
- }
- }
- if (isFlush && inPaste && pasteBuffer) {
- keys2.push(createPasteKey(pasteBuffer));
- inPaste = false;
- pasteBuffer = "";
- }
- const newState = {
- mode: inPaste ? "IN_PASTE" : "NORMAL",
- incomplete: tokenizer.buffer(),
- pasteBuffer,
- _tokenizer: tokenizer
- };
- return [keys2, newState];
-}
-function decodeModifier(modifier) {
- const m4 = modifier - 1;
- return {
- shift: !!(m4 & 1),
- meta: !!(m4 & 2),
- ctrl: !!(m4 & 4),
- super: !!(m4 & 8)
- };
-}
-function keycodeToName(keycode) {
- switch (keycode) {
- case 9:
- return "tab";
- case 13:
- return "return";
- case 27:
- return "escape";
- case 32:
- return "space";
- case 127:
- return "backspace";
- case 57399:
- return "0";
- case 57400:
- return "1";
- case 57401:
- return "2";
- case 57402:
- return "3";
- case 57403:
- return "4";
- case 57404:
- return "5";
- case 57405:
- return "6";
- case 57406:
- return "7";
- case 57407:
- return "8";
- case 57408:
- return "9";
- case 57409:
- return ".";
- case 57410:
- return "/";
- case 57411:
- return "*";
- case 57412:
- return "-";
- case 57413:
- return "+";
- case 57414:
- return "return";
- case 57415:
- return "=";
- default:
- if (keycode >= 32 && keycode <= 126) {
- return String.fromCharCode(keycode).toLowerCase();
- }
- return;
- }
-}
-function parseMouseEvent(s4) {
- const match = SGR_MOUSE_RE.exec(s4);
- if (!match)
- return null;
- const button = parseInt(match[1], 10);
- if ((button & 64) !== 0)
- return null;
- return {
- kind: "mouse",
- button,
- action: match[4] === "M" ? "press" : "release",
- col: parseInt(match[2], 10),
- row: parseInt(match[3], 10),
- sequence: s4
- };
-}
-function parseKeypress(s4 = "") {
- let parts;
- const key = {
- kind: "key",
- name: "",
- fn: false,
- ctrl: false,
- meta: false,
- shift: false,
- option: false,
- super: false,
- sequence: s4,
- raw: s4,
- isPasted: false
- };
- key.sequence = key.sequence || s4 || key.name;
- let match;
- if (match = CSI_U_RE.exec(s4)) {
- const codepoint = parseInt(match[1], 10);
- const modifier = match[2] ? parseInt(match[2], 10) : 1;
- const mods = decodeModifier(modifier);
- const name3 = keycodeToName(codepoint);
- return {
- kind: "key",
- name: name3,
- fn: false,
- ctrl: mods.ctrl,
- meta: mods.meta,
- shift: mods.shift,
- option: false,
- super: mods.super,
- sequence: s4,
- raw: s4,
- isPasted: false
- };
- }
- if (match = MODIFY_OTHER_KEYS_RE.exec(s4)) {
- const mods = decodeModifier(parseInt(match[1], 10));
- const name3 = keycodeToName(parseInt(match[2], 10));
- return {
- kind: "key",
- name: name3,
- fn: false,
- ctrl: mods.ctrl,
- meta: mods.meta,
- shift: mods.shift,
- option: false,
- super: mods.super,
- sequence: s4,
- raw: s4,
- isPasted: false
- };
- }
- if (match = SGR_MOUSE_RE.exec(s4)) {
- const button = parseInt(match[1], 10);
- if ((button & 67) === 64)
- return createNavKey(s4, "wheelup", false);
- if ((button & 67) === 65)
- return createNavKey(s4, "wheeldown", false);
- return createNavKey(s4, "mouse", false);
- }
- if (s4.length === 6 && s4.startsWith("\x1B[M")) {
- const button = s4.charCodeAt(3) - 32;
- if ((button & 67) === 64)
- return createNavKey(s4, "wheelup", false);
- if ((button & 67) === 65)
- return createNavKey(s4, "wheeldown", false);
- return createNavKey(s4, "mouse", false);
- }
- if (s4 === "\r") {
- key.raw = undefined;
- key.name = "return";
- } else if (s4 === `
-`) {
- key.name = "enter";
- } else if (s4 === "\t") {
- key.name = "tab";
- } else if (s4 === "\b" || s4 === "\x1B\b") {
- key.name = "backspace";
- key.meta = s4.charAt(0) === "\x1B";
- } else if (s4 === "\x7F" || s4 === "\x1B\x7F") {
- key.name = "backspace";
- key.meta = s4.charAt(0) === "\x1B";
- } else if (s4 === "\x1B" || s4 === "\x1B\x1B") {
- key.name = "escape";
- key.meta = s4.length === 2;
- } else if (s4 === " " || s4 === "\x1B ") {
- key.name = "space";
- key.meta = s4.length === 2;
- } else if (s4 === "\x1F") {
- key.name = "_";
- key.ctrl = true;
- } else if (s4 <= "\x1A" && s4.length === 1) {
- key.name = String.fromCharCode(s4.charCodeAt(0) + 97 - 1);
- key.ctrl = true;
- } else if (s4.length === 1 && s4 >= "0" && s4 <= "9") {
- key.name = "number";
- } else if (s4.length === 1 && s4 >= "a" && s4 <= "z") {
- key.name = s4;
- } else if (s4.length === 1 && s4 >= "A" && s4 <= "Z") {
- key.name = s4.toLowerCase();
- key.shift = true;
- } else if (parts = META_KEY_CODE_RE.exec(s4)) {
- key.meta = true;
- key.shift = /^[A-Z]$/.test(parts[1]);
- } else if (parts = FN_KEY_RE.exec(s4)) {
- const segs = [...s4];
- if (segs[0] === "\x1B" && segs[1] === "\x1B") {
- key.option = true;
- }
- const code = [parts[1], parts[2], parts[4], parts[6]].filter(Boolean).join("");
- const modifier = (parts[3] || parts[5] || 1) - 1;
- key.ctrl = !!(modifier & 4);
- key.meta = !!(modifier & 2);
- key.super = !!(modifier & 8);
- key.shift = !!(modifier & 1);
- key.code = code;
- key.name = keyName[code];
- key.shift = isShiftKey(code) || key.shift;
- key.ctrl = isCtrlKey(code) || key.ctrl;
- }
- if (key.raw === "\x1Bb") {
- key.meta = true;
- key.name = "left";
- } else if (key.raw === "\x1Bf") {
- key.meta = true;
- key.name = "right";
- }
- switch (s4) {
- case "\x1B[1~":
- return createNavKey(s4, "home", false);
- case "\x1B[4~":
- return createNavKey(s4, "end", false);
- case "\x1B[5~":
- return createNavKey(s4, "pageup", false);
- case "\x1B[6~":
- return createNavKey(s4, "pagedown", false);
- case "\x1B[1;5D":
- return createNavKey(s4, "left", true);
- case "\x1B[1;5C":
- return createNavKey(s4, "right", true);
- }
- return key;
-}
-function createNavKey(s4, name3, ctrl) {
- return {
- kind: "key",
- name: name3,
- ctrl,
- meta: false,
- shift: false,
- option: false,
- super: false,
- fn: false,
- sequence: s4,
- raw: s4,
- isPasted: false
- };
-}
-var META_KEY_CODE_RE, FN_KEY_RE, CSI_U_RE, MODIFY_OTHER_KEYS_RE, DECRPM_RE, DA1_RE, DA2_RE, KITTY_FLAGS_RE, CURSOR_POSITION_RE, OSC_RESPONSE_RE, XTVERSION_RE, SGR_MOUSE_RE, INITIAL_STATE, keyName, nonAlphanumericKeys, isShiftKey = (code) => {
- return [
- "[a",
- "[b",
- "[c",
- "[d",
- "[e",
- "[2$",
- "[3$",
- "[5$",
- "[6$",
- "[7$",
- "[8$",
- "[Z"
- ].includes(code);
-}, isCtrlKey = (code) => {
- return [
- "Oa",
- "Ob",
- "Oc",
- "Od",
- "Oe",
- "[2^",
- "[3^",
- "[5^",
- "[6^",
- "[7^",
- "[8^"
- ].includes(code);
-};
-var init_parse_keypress = __esm(() => {
- init_csi();
- init_tokenize();
- META_KEY_CODE_RE = /^(?:\x1b)([a-zA-Z0-9])$/;
- FN_KEY_RE = /^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/;
- CSI_U_RE = /^\x1b\[(\d+)(?:;(\d+))?u/;
- MODIFY_OTHER_KEYS_RE = /^\x1b\[27;(\d+);(\d+)~/;
- DECRPM_RE = /^\x1b\[\?(\d+);(\d+)\$y$/;
- DA1_RE = /^\x1b\[\?([\d;]*)c$/;
- DA2_RE = /^\x1b\[>([\d;]*)c$/;
- KITTY_FLAGS_RE = /^\x1b\[\?(\d+)u$/;
- CURSOR_POSITION_RE = /^\x1b\[\?(\d+);(\d+)R$/;
- OSC_RESPONSE_RE = /^\x1b\](\d+);(.*?)(?:\x07|\x1b\\)$/s;
- XTVERSION_RE = /^\x1bP>\|(.*?)(?:\x07|\x1b\\)$/s;
- SGR_MOUSE_RE = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/;
- INITIAL_STATE = {
- mode: "NORMAL",
- incomplete: "",
- pasteBuffer: ""
- };
- keyName = {
- OP: "f1",
- OQ: "f2",
- OR: "f3",
- OS: "f4",
- Op: "0",
- Oq: "1",
- Or: "2",
- Os: "3",
- Ot: "4",
- Ou: "5",
- Ov: "6",
- Ow: "7",
- Ox: "8",
- Oy: "9",
- Oj: "*",
- Ok: "+",
- Ol: ",",
- Om: "-",
- On: ".",
- Oo: "/",
- OM: "return",
- "[11~": "f1",
- "[12~": "f2",
- "[13~": "f3",
- "[14~": "f4",
- "[[A": "f1",
- "[[B": "f2",
- "[[C": "f3",
- "[[D": "f4",
- "[[E": "f5",
- "[15~": "f5",
- "[17~": "f6",
- "[18~": "f7",
- "[19~": "f8",
- "[20~": "f9",
- "[21~": "f10",
- "[23~": "f11",
- "[24~": "f12",
- "[A": "up",
- "[B": "down",
- "[C": "right",
- "[D": "left",
- "[E": "clear",
- "[F": "end",
- "[H": "home",
- OA: "up",
- OB: "down",
- OC: "right",
- OD: "left",
- OE: "clear",
- OF: "end",
- OH: "home",
- "[1~": "home",
- "[2~": "insert",
- "[3~": "delete",
- "[4~": "end",
- "[5~": "pageup",
- "[6~": "pagedown",
- "[[5~": "pageup",
- "[[6~": "pagedown",
- "[7~": "home",
- "[8~": "end",
- "[a": "up",
- "[b": "down",
- "[c": "right",
- "[d": "left",
- "[e": "clear",
- "[2$": "insert",
- "[3$": "delete",
- "[5$": "pageup",
- "[6$": "pagedown",
- "[7$": "home",
- "[8$": "end",
- Oa: "up",
- Ob: "down",
- Oc: "right",
- Od: "left",
- Oe: "clear",
- "[2^": "insert",
- "[3^": "delete",
- "[5^": "pageup",
- "[6^": "pagedown",
- "[7^": "home",
- "[8^": "end",
- "[Z": "tab"
- };
- nonAlphanumericKeys = [
- ...Object.values(keyName).filter((v6) => v6.length > 1),
- "escape",
- "backspace",
- "wheelup",
- "wheeldown",
- "mouse"
- ];
-});
-
-// src/ink/events/input-event.ts
-function parseKey(keypress) {
- const key = {
- upArrow: keypress.name === "up",
- downArrow: keypress.name === "down",
- leftArrow: keypress.name === "left",
- rightArrow: keypress.name === "right",
- pageDown: keypress.name === "pagedown",
- pageUp: keypress.name === "pageup",
- wheelUp: keypress.name === "wheelup",
- wheelDown: keypress.name === "wheeldown",
- home: keypress.name === "home",
- end: keypress.name === "end",
- return: keypress.name === "return",
- escape: keypress.name === "escape",
- fn: keypress.fn,
- ctrl: keypress.ctrl,
- shift: keypress.shift,
- tab: keypress.name === "tab",
- backspace: keypress.name === "backspace",
- delete: keypress.name === "delete",
- meta: keypress.meta || keypress.name === "escape" || keypress.option,
- super: keypress.super
- };
- let input = keypress.ctrl ? keypress.name : keypress.sequence;
- if (input === undefined) {
- input = "";
- }
- if (keypress.ctrl && input === "space") {
- input = " ";
- }
- if (keypress.code && !keypress.name) {
- input = "";
- }
- if (!keypress.name && /^\[<\d+;\d+;\d+[Mm]/.test(input)) {
- input = "";
- }
- if (input.startsWith("\x1B")) {
- input = input.slice(1);
- }
- let processedAsSpecialSequence = false;
- if (/^\[\d/.test(input) && input.endsWith("u")) {
- if (!keypress.name) {
- input = "";
- } else {
- input = keypress.name === "space" ? " " : keypress.name === "escape" ? "" : keypress.name;
- }
- processedAsSpecialSequence = true;
- }
- if (input.startsWith("[27;") && input.endsWith("~")) {
- if (!keypress.name) {
- input = "";
- } else {
- input = keypress.name === "space" ? " " : keypress.name === "escape" ? "" : keypress.name;
- }
- processedAsSpecialSequence = true;
- }
- if (input.startsWith("O") && input.length === 2 && keypress.name && keypress.name.length === 1) {
- input = keypress.name;
- processedAsSpecialSequence = true;
- }
- if (!processedAsSpecialSequence && keypress.name && nonAlphanumericKeys.includes(keypress.name)) {
- input = "";
- }
- if (input.length === 1 && typeof input[0] === "string" && input[0] >= "A" && input[0] <= "Z") {
- key.shift = true;
- }
- return [key, input];
-}
-var InputEvent;
-var init_input_event = __esm(() => {
- init_parse_keypress();
- InputEvent = class InputEvent extends Event2 {
- keypress;
- key;
- input;
- constructor(keypress) {
- super();
- const [key, input] = parseKey(keypress);
- this.keypress = keypress;
- this.key = key;
- this.input = input;
- }
- };
-});
-
-// src/ink/events/terminal-focus-event.ts
-var TerminalFocusEvent;
-var init_terminal_focus_event = __esm(() => {
- TerminalFocusEvent = class TerminalFocusEvent extends Event2 {
- type;
- constructor(type) {
- super();
- this.type = type;
- }
- };
-});
-
-// node_modules/react-reconciler/node_modules/scheduler/cjs/scheduler.development.js
-var require_scheduler_development = __commonJS((exports) => {
- (function() {
- function performWorkUntilDeadline() {
- if (isMessageLoopRunning) {
- var currentTime = exports.unstable_now();
- startTime = currentTime;
- var hasMoreWork = true;
- try {
- a: {
- isHostCallbackScheduled = false;
- isHostTimeoutScheduled && (isHostTimeoutScheduled = false, localClearTimeout(taskTimeoutID), taskTimeoutID = -1);
- isPerformingWork = true;
- var previousPriorityLevel = currentPriorityLevel;
- try {
- b: {
- advanceTimers(currentTime);
- for (currentTask = peek(taskQueue);currentTask !== null && !(currentTask.expirationTime > currentTime && shouldYieldToHost()); ) {
- var callback = currentTask.callback;
- if (typeof callback === "function") {
- currentTask.callback = null;
- currentPriorityLevel = currentTask.priorityLevel;
- var continuationCallback = callback(currentTask.expirationTime <= currentTime);
- currentTime = exports.unstable_now();
- if (typeof continuationCallback === "function") {
- currentTask.callback = continuationCallback;
- advanceTimers(currentTime);
- hasMoreWork = true;
- break b;
- }
- currentTask === peek(taskQueue) && pop(taskQueue);
- advanceTimers(currentTime);
- } else
- pop(taskQueue);
- currentTask = peek(taskQueue);
- }
- if (currentTask !== null)
- hasMoreWork = true;
- else {
- var firstTimer = peek(timerQueue);
- firstTimer !== null && requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
- hasMoreWork = false;
- }
- }
- break a;
- } finally {
- currentTask = null, currentPriorityLevel = previousPriorityLevel, isPerformingWork = false;
- }
- hasMoreWork = undefined;
- }
- } finally {
- hasMoreWork ? schedulePerformWorkUntilDeadline() : isMessageLoopRunning = false;
- }
- }
- }
- function push(heap, node) {
- var index2 = heap.length;
- heap.push(node);
- a:
- for (;0 < index2; ) {
- var parentIndex = index2 - 1 >>> 1, parent = heap[parentIndex];
- if (0 < compare(parent, node))
- heap[parentIndex] = node, heap[index2] = parent, index2 = parentIndex;
- else
- break a;
- }
- }
- function peek(heap) {
- return heap.length === 0 ? null : heap[0];
- }
- function pop(heap) {
- if (heap.length === 0)
- return null;
- var first = heap[0], last = heap.pop();
- if (last !== first) {
- heap[0] = last;
- a:
- for (var index2 = 0, length = heap.length, halfLength = length >>> 1;index2 < halfLength; ) {
- var leftIndex = 2 * (index2 + 1) - 1, left = heap[leftIndex], rightIndex = leftIndex + 1, right = heap[rightIndex];
- if (0 > compare(left, last))
- rightIndex < length && 0 > compare(right, left) ? (heap[index2] = right, heap[rightIndex] = last, index2 = rightIndex) : (heap[index2] = left, heap[leftIndex] = last, index2 = leftIndex);
- else if (rightIndex < length && 0 > compare(right, last))
- heap[index2] = right, heap[rightIndex] = last, index2 = rightIndex;
- else
- break a;
- }
- }
- return first;
- }
- function compare(a5, b4) {
- var diff = a5.sortIndex - b4.sortIndex;
- return diff !== 0 ? diff : a5.id - b4.id;
- }
- function advanceTimers(currentTime) {
- for (var timer = peek(timerQueue);timer !== null; ) {
- if (timer.callback === null)
- pop(timerQueue);
- else if (timer.startTime <= currentTime)
- pop(timerQueue), timer.sortIndex = timer.expirationTime, push(taskQueue, timer);
- else
- break;
- timer = peek(timerQueue);
- }
- }
- function handleTimeout(currentTime) {
- isHostTimeoutScheduled = false;
- advanceTimers(currentTime);
- if (!isHostCallbackScheduled)
- if (peek(taskQueue) !== null)
- isHostCallbackScheduled = true, requestHostCallback();
- else {
- var firstTimer = peek(timerQueue);
- firstTimer !== null && requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
- }
- }
- function shouldYieldToHost() {
- return exports.unstable_now() - startTime < frameInterval ? false : true;
- }
- function requestHostCallback() {
- isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline());
- }
- function requestHostTimeout(callback, ms) {
- taskTimeoutID = localSetTimeout(function() {
- callback(exports.unstable_now());
- }, ms);
- }
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
- exports.unstable_now = undefined;
- if (typeof performance === "object" && typeof performance.now === "function") {
- var localPerformance = performance;
- exports.unstable_now = function() {
- return localPerformance.now();
- };
- } else {
- var localDate = Date, initialTime = localDate.now();
- exports.unstable_now = function() {
- return localDate.now() - initialTime;
- };
- }
- var taskQueue = [], timerQueue = [], taskIdCounter = 1, currentTask = null, currentPriorityLevel = 3, isPerformingWork = false, isHostCallbackScheduled = false, isHostTimeoutScheduled = false, localSetTimeout = typeof setTimeout === "function" ? setTimeout : null, localClearTimeout = typeof clearTimeout === "function" ? clearTimeout : null, localSetImmediate = typeof setImmediate !== "undefined" ? setImmediate : null, isMessageLoopRunning = false, taskTimeoutID = -1, frameInterval = 5, startTime = -1;
- if (typeof localSetImmediate === "function")
- var schedulePerformWorkUntilDeadline = function() {
- localSetImmediate(performWorkUntilDeadline);
- };
- else if (typeof MessageChannel !== "undefined") {
- var channel = new MessageChannel, port = channel.port2;
- channel.port1.onmessage = performWorkUntilDeadline;
- schedulePerformWorkUntilDeadline = function() {
- port.postMessage(null);
- };
- } else
- schedulePerformWorkUntilDeadline = function() {
- localSetTimeout(performWorkUntilDeadline, 0);
- };
- exports.unstable_IdlePriority = 5;
- exports.unstable_ImmediatePriority = 1;
- exports.unstable_LowPriority = 4;
- exports.unstable_NormalPriority = 3;
- exports.unstable_Profiling = null;
- exports.unstable_UserBlockingPriority = 2;
- exports.unstable_cancelCallback = function(task) {
- task.callback = null;
- };
- exports.unstable_continueExecution = function() {
- isHostCallbackScheduled || isPerformingWork || (isHostCallbackScheduled = true, requestHostCallback());
- };
- exports.unstable_forceFrameRate = function(fps) {
- 0 > fps || 125 < fps ? console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported") : frameInterval = 0 < fps ? Math.floor(1000 / fps) : 5;
- };
- exports.unstable_getCurrentPriorityLevel = function() {
- return currentPriorityLevel;
- };
- exports.unstable_getFirstCallbackNode = function() {
- return peek(taskQueue);
- };
- exports.unstable_next = function(eventHandler) {
- switch (currentPriorityLevel) {
- case 1:
- case 2:
- case 3:
- var priorityLevel = 3;
- break;
- default:
- priorityLevel = currentPriorityLevel;
- }
- var previousPriorityLevel = currentPriorityLevel;
- currentPriorityLevel = priorityLevel;
- try {
- return eventHandler();
- } finally {
- currentPriorityLevel = previousPriorityLevel;
- }
- };
- exports.unstable_pauseExecution = function() {};
- exports.unstable_requestPaint = function() {};
- exports.unstable_runWithPriority = function(priorityLevel, eventHandler) {
- switch (priorityLevel) {
- case 1:
- case 2:
- case 3:
- case 4:
- case 5:
- break;
- default:
- priorityLevel = 3;
- }
- var previousPriorityLevel = currentPriorityLevel;
- currentPriorityLevel = priorityLevel;
- try {
- return eventHandler();
- } finally {
- currentPriorityLevel = previousPriorityLevel;
- }
- };
- exports.unstable_scheduleCallback = function(priorityLevel, callback, options2) {
- var currentTime = exports.unstable_now();
- typeof options2 === "object" && options2 !== null ? (options2 = options2.delay, options2 = typeof options2 === "number" && 0 < options2 ? currentTime + options2 : currentTime) : options2 = currentTime;
- switch (priorityLevel) {
- case 1:
- var timeout = -1;
- break;
- case 2:
- timeout = 250;
- break;
- case 5:
- timeout = 1073741823;
- break;
- case 4:
- timeout = 1e4;
- break;
- default:
- timeout = 5000;
- }
- timeout = options2 + timeout;
- priorityLevel = {
- id: taskIdCounter++,
- callback,
- priorityLevel,
- startTime: options2,
- expirationTime: timeout,
- sortIndex: -1
- };
- options2 > currentTime ? (priorityLevel.sortIndex = options2, push(timerQueue, priorityLevel), peek(taskQueue) === null && priorityLevel === peek(timerQueue) && (isHostTimeoutScheduled ? (localClearTimeout(taskTimeoutID), taskTimeoutID = -1) : isHostTimeoutScheduled = true, requestHostTimeout(handleTimeout, options2 - currentTime))) : (priorityLevel.sortIndex = timeout, push(taskQueue, priorityLevel), isHostCallbackScheduled || isPerformingWork || (isHostCallbackScheduled = true, requestHostCallback()));
- return priorityLevel;
- };
- exports.unstable_shouldYield = shouldYieldToHost;
- exports.unstable_wrapCallback = function(callback) {
- var parentPriorityLevel = currentPriorityLevel;
- return function() {
- var previousPriorityLevel = currentPriorityLevel;
- currentPriorityLevel = parentPriorityLevel;
- try {
- return callback.apply(this, arguments);
- } finally {
- currentPriorityLevel = previousPriorityLevel;
- }
- };
- };
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
- })();
-});
-
-// node_modules/react-reconciler/node_modules/scheduler/index.js
-var require_scheduler = __commonJS((exports, module) => {
- var scheduler_development = __toESM(require_scheduler_development());
- if (false) {} else {
- module.exports = scheduler_development;
- }
-});
-
-// node_modules/react-reconciler/cjs/react-reconciler.development.js
-var require_react_reconciler_development = __commonJS((exports, module) => {
- var React2 = __toESM(require_react());
- var Scheduler = __toESM(require_scheduler());
- module.exports = function($$$config) {
- function findHook(fiber, id) {
- for (fiber = fiber.memoizedState;fiber !== null && 0 < id; )
- fiber = fiber.next, id--;
- return fiber;
- }
- function copyWithSetImpl(obj, path15, index2, value) {
- if (index2 >= path15.length)
- return value;
- var key = path15[index2], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
- updated[key] = copyWithSetImpl(obj[key], path15, index2 + 1, value);
- return updated;
- }
- function copyWithRename(obj, oldPath, newPath) {
- if (oldPath.length !== newPath.length)
- console.warn("copyWithRename() expects paths of the same length");
- else {
- for (var i5 = 0;i5 < newPath.length - 1; i5++)
- if (oldPath[i5] !== newPath[i5]) {
- console.warn("copyWithRename() expects paths to be the same except for the deepest key");
- return;
- }
- return copyWithRenameImpl(obj, oldPath, newPath, 0);
- }
- }
- function copyWithRenameImpl(obj, oldPath, newPath, index2) {
- var oldKey = oldPath[index2], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
- index2 + 1 === oldPath.length ? (updated[newPath[index2]] = updated[oldKey], isArrayImpl(updated) ? updated.splice(oldKey, 1) : delete updated[oldKey]) : updated[oldKey] = copyWithRenameImpl(obj[oldKey], oldPath, newPath, index2 + 1);
- return updated;
- }
- function copyWithDeleteImpl(obj, path15, index2) {
- var key = path15[index2], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
- if (index2 + 1 === path15.length)
- return isArrayImpl(updated) ? updated.splice(key, 1) : delete updated[key], updated;
- updated[key] = copyWithDeleteImpl(obj[key], path15, index2 + 1);
- return updated;
- }
- function shouldSuspendImpl() {
- return false;
- }
- function shouldErrorImpl() {
- return null;
- }
- function createFiber(tag2, pendingProps, key, mode) {
- return new FiberNode(tag2, pendingProps, key, mode);
- }
- function scheduleRoot(root2, element) {
- root2.context === emptyContextObject && (updateContainerSync(element, root2, null, null), flushSyncWork());
- }
- function scheduleRefresh(root2, update) {
- if (resolveFamily2 !== null) {
- var staleFamilies = update.staleFamilies;
- update = update.updatedFamilies;
- flushPassiveEffects();
- scheduleFibersWithFamiliesRecursively(root2.current, update, staleFamilies);
- flushSyncWork();
- }
- }
- function setRefreshHandler(handler) {
- resolveFamily2 = handler;
- }
- function warnInvalidHookAccess() {
- console.error("Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://react.dev/link/rules-of-hooks");
- }
- function warnInvalidContextAccess() {
- console.error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
- }
- function noop10() {}
- function warnForMissingKey() {}
- function setToSortedString(set2) {
- var array2 = [];
- set2.forEach(function(value) {
- array2.push(value);
- });
- return array2.sort().join(", ");
- }
- function getIteratorFn(maybeIterable) {
- if (maybeIterable === null || typeof maybeIterable !== "object")
- return null;
- maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
- return typeof maybeIterable === "function" ? maybeIterable : null;
- }
- function getComponentNameFromType(type) {
- if (type == null)
- return null;
- if (typeof type === "function")
- return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
- if (typeof type === "string")
- return type;
- switch (type) {
- case REACT_FRAGMENT_TYPE:
- return "Fragment";
- case REACT_PORTAL_TYPE:
- return "Portal";
- case REACT_PROFILER_TYPE:
- return "Profiler";
- case REACT_STRICT_MODE_TYPE:
- return "StrictMode";
- case REACT_SUSPENSE_TYPE:
- return "Suspense";
- case REACT_SUSPENSE_LIST_TYPE:
- return "SuspenseList";
- }
- if (typeof type === "object")
- switch (typeof type.tag === "number" && console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), type.$$typeof) {
- case REACT_CONTEXT_TYPE:
- return (type.displayName || "Context") + ".Provider";
- case REACT_CONSUMER_TYPE:
- return (type._context.displayName || "Context") + ".Consumer";
- case REACT_FORWARD_REF_TYPE:
- var innerType = type.render;
- type = type.displayName;
- type || (type = innerType.displayName || innerType.name || "", type = type !== "" ? "ForwardRef(" + type + ")" : "ForwardRef");
- return type;
- case REACT_MEMO_TYPE:
- return innerType = type.displayName || null, innerType !== null ? innerType : getComponentNameFromType(type.type) || "Memo";
- case REACT_LAZY_TYPE:
- innerType = type._payload;
- type = type._init;
- try {
- return getComponentNameFromType(type(innerType));
- } catch (x3) {}
- }
- return null;
- }
- function getComponentNameFromFiber(fiber) {
- var type = fiber.type;
- switch (fiber.tag) {
- case 24:
- return "Cache";
- case 9:
- return (type._context.displayName || "Context") + ".Consumer";
- case 10:
- return (type.displayName || "Context") + ".Provider";
- case 18:
- return "DehydratedFragment";
- case 11:
- return fiber = type.render, fiber = fiber.displayName || fiber.name || "", type.displayName || (fiber !== "" ? "ForwardRef(" + fiber + ")" : "ForwardRef");
- case 7:
- return "Fragment";
- case 26:
- case 27:
- case 5:
- return type;
- case 4:
- return "Portal";
- case 3:
- return "Root";
- case 6:
- return "Text";
- case 16:
- return getComponentNameFromType(type);
- case 8:
- return type === REACT_STRICT_MODE_TYPE ? "StrictMode" : "Mode";
- case 22:
- return "Offscreen";
- case 12:
- return "Profiler";
- case 21:
- return "Scope";
- case 13:
- return "Suspense";
- case 19:
- return "SuspenseList";
- case 25:
- return "TracingMarker";
- case 1:
- case 0:
- case 14:
- case 15:
- if (typeof type === "function")
- return type.displayName || type.name || null;
- if (typeof type === "string")
- return type;
- break;
- case 29:
- type = fiber._debugInfo;
- if (type != null) {
- for (var i5 = type.length - 1;0 <= i5; i5--)
- if (typeof type[i5].name === "string")
- return type[i5].name;
- }
- if (fiber.return !== null)
- return getComponentNameFromFiber(fiber.return);
- }
- return null;
- }
- function disabledLog() {}
- function disableLogs() {
- if (disabledDepth === 0) {
- prevLog = console.log;
- prevInfo = console.info;
- prevWarn = console.warn;
- prevError = console.error;
- prevGroup = console.group;
- prevGroupCollapsed = console.groupCollapsed;
- prevGroupEnd = console.groupEnd;
- var props = {
- configurable: true,
- enumerable: true,
- value: disabledLog,
- writable: true
- };
- Object.defineProperties(console, {
- info: props,
- log: props,
- warn: props,
- error: props,
- group: props,
- groupCollapsed: props,
- groupEnd: props
- });
- }
- disabledDepth++;
- }
- function reenableLogs() {
- disabledDepth--;
- if (disabledDepth === 0) {
- var props = { configurable: true, enumerable: true, writable: true };
- Object.defineProperties(console, {
- log: assign({}, props, { value: prevLog }),
- info: assign({}, props, { value: prevInfo }),
- warn: assign({}, props, { value: prevWarn }),
- error: assign({}, props, { value: prevError }),
- group: assign({}, props, { value: prevGroup }),
- groupCollapsed: assign({}, props, { value: prevGroupCollapsed }),
- groupEnd: assign({}, props, { value: prevGroupEnd })
- });
- }
- 0 > disabledDepth && console.error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
- }
- function describeBuiltInComponentFrame(name3) {
- if (prefix === undefined)
- try {
- throw Error();
- } catch (x3) {
- var match = x3.stack.trim().match(/\n( *(at )?)/);
- prefix = match && match[1] || "";
- suffix = -1 < x3.stack.indexOf(`
- at`) ? " ()" : -1 < x3.stack.indexOf("@") ? "@unknown:0:0" : "";
- }
- return `
-` + prefix + name3 + suffix;
- }
- function describeNativeComponentFrame(fn, construct) {
- if (!fn || reentry)
- return "";
- var frame = componentFrameCache.get(fn);
- if (frame !== undefined)
- return frame;
- reentry = true;
- frame = Error.prepareStackTrace;
- Error.prepareStackTrace = undefined;
- var previousDispatcher = null;
- previousDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = null;
- disableLogs();
- try {
- var RunInRootFrame = {
- DetermineComponentFrameRoot: function() {
- try {
- if (construct) {
- var Fake = function() {
- throw Error();
- };
- Object.defineProperty(Fake.prototype, "props", {
- set: function() {
- throw Error();
- }
- });
- if (typeof Reflect === "object" && Reflect.construct) {
- try {
- Reflect.construct(Fake, []);
- } catch (x3) {
- var control = x3;
- }
- Reflect.construct(fn, [], Fake);
- } else {
- try {
- Fake.call();
- } catch (x$0) {
- control = x$0;
- }
- fn.call(Fake.prototype);
- }
- } else {
- try {
- throw Error();
- } catch (x$1) {
- control = x$1;
- }
- (Fake = fn()) && typeof Fake.catch === "function" && Fake.catch(function() {});
- }
- } catch (sample) {
- if (sample && control && typeof sample.stack === "string")
- return [sample.stack, control.stack];
- }
- return [null, null];
- }
- };
- RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
- var namePropDescriptor = Object.getOwnPropertyDescriptor(RunInRootFrame.DetermineComponentFrameRoot, "name");
- namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(RunInRootFrame.DetermineComponentFrameRoot, "name", { value: "DetermineComponentFrameRoot" });
- var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
- if (sampleStack && controlStack) {
- var sampleLines = sampleStack.split(`
-`), controlLines = controlStack.split(`
-`);
- for (_RunInRootFrame$Deter = namePropDescriptor = 0;namePropDescriptor < sampleLines.length && !sampleLines[namePropDescriptor].includes("DetermineComponentFrameRoot"); )
- namePropDescriptor++;
- for (;_RunInRootFrame$Deter < controlLines.length && !controlLines[_RunInRootFrame$Deter].includes("DetermineComponentFrameRoot"); )
- _RunInRootFrame$Deter++;
- if (namePropDescriptor === sampleLines.length || _RunInRootFrame$Deter === controlLines.length)
- for (namePropDescriptor = sampleLines.length - 1, _RunInRootFrame$Deter = controlLines.length - 1;1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter && sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]; )
- _RunInRootFrame$Deter--;
- for (;1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter; namePropDescriptor--, _RunInRootFrame$Deter--)
- if (sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
- if (namePropDescriptor !== 1 || _RunInRootFrame$Deter !== 1) {
- do
- if (namePropDescriptor--, _RunInRootFrame$Deter--, 0 > _RunInRootFrame$Deter || sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
- var _frame = `
-` + sampleLines[namePropDescriptor].replace(" at new ", " at ");
- fn.displayName && _frame.includes("") && (_frame = _frame.replace("", fn.displayName));
- typeof fn === "function" && componentFrameCache.set(fn, _frame);
- return _frame;
- }
- while (1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter);
- }
- break;
- }
- }
- } finally {
- reentry = false, ReactSharedInternals.H = previousDispatcher, reenableLogs(), Error.prepareStackTrace = frame;
- }
- sampleLines = (sampleLines = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(sampleLines) : "";
- typeof fn === "function" && componentFrameCache.set(fn, sampleLines);
- return sampleLines;
- }
- function describeFiber(fiber) {
- switch (fiber.tag) {
- case 26:
- case 27:
- case 5:
- return describeBuiltInComponentFrame(fiber.type);
- case 16:
- return describeBuiltInComponentFrame("Lazy");
- case 13:
- return describeBuiltInComponentFrame("Suspense");
- case 19:
- return describeBuiltInComponentFrame("SuspenseList");
- case 0:
- case 15:
- return fiber = describeNativeComponentFrame(fiber.type, false), fiber;
- case 11:
- return fiber = describeNativeComponentFrame(fiber.type.render, false), fiber;
- case 1:
- return fiber = describeNativeComponentFrame(fiber.type, true), fiber;
- default:
- return "";
- }
- }
- function getStackByFiberInDevAndProd(workInProgress2) {
- try {
- var info = "";
- do {
- info += describeFiber(workInProgress2);
- var debugInfo = workInProgress2._debugInfo;
- if (debugInfo)
- for (var i5 = debugInfo.length - 1;0 <= i5; i5--) {
- var entry = debugInfo[i5];
- if (typeof entry.name === "string") {
- var JSCompiler_temp_const = info, env5 = entry.env;
- var JSCompiler_inline_result = describeBuiltInComponentFrame(entry.name + (env5 ? " [" + env5 + "]" : ""));
- info = JSCompiler_temp_const + JSCompiler_inline_result;
- }
- }
- workInProgress2 = workInProgress2.return;
- } while (workInProgress2);
- return info;
- } catch (x3) {
- return `
-Error generating stack: ` + x3.message + `
-` + x3.stack;
- }
- }
- function getCurrentFiberStackInDev() {
- return current === null ? "" : getStackByFiberInDevAndProd(current);
- }
- function runWithFiberInDEV(fiber, callback, arg0, arg1, arg2, arg3, arg4) {
- var previousFiber = current;
- ReactSharedInternals.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev;
- isRendering = false;
- current = fiber;
- try {
- return callback(arg0, arg1, arg2, arg3, arg4);
- } finally {
- current = previousFiber;
- }
- throw Error("runWithFiberInDEV should never be called in production. This is a bug in React.");
- }
- function getNearestMountedFiber(fiber) {
- var node = fiber, nearestMounted = fiber;
- if (fiber.alternate)
- for (;node.return; )
- node = node.return;
- else {
- fiber = node;
- do
- node = fiber, (node.flags & 4098) !== 0 && (nearestMounted = node.return), fiber = node.return;
- while (fiber);
- }
- return node.tag === 3 ? nearestMounted : null;
- }
- function assertIsMounted(fiber) {
- if (getNearestMountedFiber(fiber) !== fiber)
- throw Error("Unable to find node on an unmounted component.");
- }
- function findCurrentFiberUsingSlowPath(fiber) {
- var alternate = fiber.alternate;
- if (!alternate) {
- alternate = getNearestMountedFiber(fiber);
- if (alternate === null)
- throw Error("Unable to find node on an unmounted component.");
- return alternate !== fiber ? null : fiber;
- }
- for (var a5 = fiber, b4 = alternate;; ) {
- var parentA = a5.return;
- if (parentA === null)
- break;
- var parentB = parentA.alternate;
- if (parentB === null) {
- b4 = parentA.return;
- if (b4 !== null) {
- a5 = b4;
- continue;
- }
- break;
- }
- if (parentA.child === parentB.child) {
- for (parentB = parentA.child;parentB; ) {
- if (parentB === a5)
- return assertIsMounted(parentA), fiber;
- if (parentB === b4)
- return assertIsMounted(parentA), alternate;
- parentB = parentB.sibling;
- }
- throw Error("Unable to find node on an unmounted component.");
- }
- if (a5.return !== b4.return)
- a5 = parentA, b4 = parentB;
- else {
- for (var didFindChild = false, _child = parentA.child;_child; ) {
- if (_child === a5) {
- didFindChild = true;
- a5 = parentA;
- b4 = parentB;
- break;
- }
- if (_child === b4) {
- didFindChild = true;
- b4 = parentA;
- a5 = parentB;
- break;
- }
- _child = _child.sibling;
- }
- if (!didFindChild) {
- for (_child = parentB.child;_child; ) {
- if (_child === a5) {
- didFindChild = true;
- a5 = parentB;
- b4 = parentA;
- break;
- }
- if (_child === b4) {
- didFindChild = true;
- b4 = parentB;
- a5 = parentA;
- break;
- }
- _child = _child.sibling;
- }
- if (!didFindChild)
- throw Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");
- }
- }
- if (a5.alternate !== b4)
- throw Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");
- }
- if (a5.tag !== 3)
- throw Error("Unable to find node on an unmounted component.");
- return a5.stateNode.current === a5 ? fiber : alternate;
- }
- function findCurrentHostFiber(parent) {
- parent = findCurrentFiberUsingSlowPath(parent);
- return parent !== null ? findCurrentHostFiberImpl(parent) : null;
- }
- function findCurrentHostFiberImpl(node) {
- var tag2 = node.tag;
- if (tag2 === 5 || tag2 === 26 || tag2 === 27 || tag2 === 6)
- return node;
- for (node = node.child;node !== null; ) {
- tag2 = findCurrentHostFiberImpl(node);
- if (tag2 !== null)
- return tag2;
- node = node.sibling;
- }
- return null;
- }
- function findCurrentHostFiberWithNoPortalsImpl(node) {
- var tag2 = node.tag;
- if (tag2 === 5 || tag2 === 26 || tag2 === 27 || tag2 === 6)
- return node;
- for (node = node.child;node !== null; ) {
- if (node.tag !== 4 && (tag2 = findCurrentHostFiberWithNoPortalsImpl(node), tag2 !== null))
- return tag2;
- node = node.sibling;
- }
- return null;
- }
- function createCursor(defaultValue) {
- return { current: defaultValue };
- }
- function pop(cursor, fiber) {
- 0 > index$jscomp$0 ? console.error("Unexpected pop.") : (fiber !== fiberStack[index$jscomp$0] && console.error("Unexpected Fiber popped."), cursor.current = valueStack[index$jscomp$0], valueStack[index$jscomp$0] = null, fiberStack[index$jscomp$0] = null, index$jscomp$0--);
- }
- function push(cursor, value, fiber) {
- index$jscomp$0++;
- valueStack[index$jscomp$0] = cursor.current;
- fiberStack[index$jscomp$0] = fiber;
- cursor.current = value;
- }
- function clz32Fallback(x3) {
- x3 >>>= 0;
- return x3 === 0 ? 32 : 31 - (log$1(x3) / LN2 | 0) | 0;
- }
- function getLabelForLane(lane) {
- if (lane & 1)
- return "SyncHydrationLane";
- if (lane & 2)
- return "Sync";
- if (lane & 4)
- return "InputContinuousHydration";
- if (lane & 8)
- return "InputContinuous";
- if (lane & 16)
- return "DefaultHydration";
- if (lane & 32)
- return "Default";
- if (lane & 64)
- return "TransitionHydration";
- if (lane & 4194176)
- return "Transition";
- if (lane & 62914560)
- return "Retry";
- if (lane & 67108864)
- return "SelectiveHydration";
- if (lane & 134217728)
- return "IdleHydration";
- if (lane & 268435456)
- return "Idle";
- if (lane & 536870912)
- return "Offscreen";
- if (lane & 1073741824)
- return "Deferred";
- }
- function getHighestPriorityLanes(lanes) {
- var pendingSyncLanes = lanes & 42;
- if (pendingSyncLanes !== 0)
- return pendingSyncLanes;
- switch (lanes & -lanes) {
- case 1:
- return 1;
- case 2:
- return 2;
- case 4:
- return 4;
- case 8:
- return 8;
- case 16:
- return 16;
- case 32:
- return 32;
- case 64:
- return 64;
- case 128:
- case 256:
- case 512:
- case 1024:
- case 2048:
- case 4096:
- case 8192:
- case 16384:
- case 32768:
- case 65536:
- case 131072:
- case 262144:
- case 524288:
- case 1048576:
- case 2097152:
- return lanes & 4194176;
- case 4194304:
- case 8388608:
- case 16777216:
- case 33554432:
- return lanes & 62914560;
- case 67108864:
- return 67108864;
- case 134217728:
- return 134217728;
- case 268435456:
- return 268435456;
- case 536870912:
- return 536870912;
- case 1073741824:
- return 0;
- default:
- return console.error("Should have found matching lanes. This is a bug in React."), lanes;
- }
- }
- function getNextLanes(root2, wipLanes) {
- var pendingLanes = root2.pendingLanes;
- if (pendingLanes === 0)
- return 0;
- var nextLanes = 0, suspendedLanes = root2.suspendedLanes, pingedLanes = root2.pingedLanes, warmLanes = root2.warmLanes;
- root2 = root2.finishedLanes !== 0;
- var nonIdlePendingLanes = pendingLanes & 134217727;
- nonIdlePendingLanes !== 0 ? (pendingLanes = nonIdlePendingLanes & ~suspendedLanes, pendingLanes !== 0 ? nextLanes = getHighestPriorityLanes(pendingLanes) : (pingedLanes &= nonIdlePendingLanes, pingedLanes !== 0 ? nextLanes = getHighestPriorityLanes(pingedLanes) : root2 || (warmLanes = nonIdlePendingLanes & ~warmLanes, warmLanes !== 0 && (nextLanes = getHighestPriorityLanes(warmLanes))))) : (nonIdlePendingLanes = pendingLanes & ~suspendedLanes, nonIdlePendingLanes !== 0 ? nextLanes = getHighestPriorityLanes(nonIdlePendingLanes) : pingedLanes !== 0 ? nextLanes = getHighestPriorityLanes(pingedLanes) : root2 || (warmLanes = pendingLanes & ~warmLanes, warmLanes !== 0 && (nextLanes = getHighestPriorityLanes(warmLanes))));
- return nextLanes === 0 ? 0 : wipLanes !== 0 && wipLanes !== nextLanes && (wipLanes & suspendedLanes) === 0 && (suspendedLanes = nextLanes & -nextLanes, warmLanes = wipLanes & -wipLanes, suspendedLanes >= warmLanes || suspendedLanes === 32 && (warmLanes & 4194176) !== 0) ? wipLanes : nextLanes;
- }
- function checkIfRootIsPrerendering(root2, renderLanes2) {
- return (root2.pendingLanes & ~(root2.suspendedLanes & ~root2.pingedLanes) & renderLanes2) === 0;
- }
- function computeExpirationTime(lane, currentTime) {
- switch (lane) {
- case 1:
- case 2:
- case 4:
- case 8:
- return currentTime + 250;
- case 16:
- case 32:
- case 64:
- case 128:
- case 256:
- case 512:
- case 1024:
- case 2048:
- case 4096:
- case 8192:
- case 16384:
- case 32768:
- case 65536:
- case 131072:
- case 262144:
- case 524288:
- case 1048576:
- case 2097152:
- return currentTime + 5000;
- case 4194304:
- case 8388608:
- case 16777216:
- case 33554432:
- return -1;
- case 67108864:
- case 134217728:
- case 268435456:
- case 536870912:
- case 1073741824:
- return -1;
- default:
- return console.error("Should have found matching lanes. This is a bug in React."), -1;
- }
- }
- function claimNextTransitionLane() {
- var lane = nextTransitionLane;
- nextTransitionLane <<= 1;
- (nextTransitionLane & 4194176) === 0 && (nextTransitionLane = 128);
- return lane;
- }
- function claimNextRetryLane() {
- var lane = nextRetryLane;
- nextRetryLane <<= 1;
- (nextRetryLane & 62914560) === 0 && (nextRetryLane = 4194304);
- return lane;
- }
- function createLaneMap(initial) {
- for (var laneMap = [], i5 = 0;31 > i5; i5++)
- laneMap.push(initial);
- return laneMap;
- }
- function markRootUpdated$1(root2, updateLane) {
- root2.pendingLanes |= updateLane;
- updateLane !== 268435456 && (root2.suspendedLanes = 0, root2.pingedLanes = 0, root2.warmLanes = 0);
- }
- function markRootFinished(root2, finishedLanes, remainingLanes, spawnedLane, updatedLanes, suspendedRetryLanes) {
- var previouslyPendingLanes = root2.pendingLanes;
- root2.pendingLanes = remainingLanes;
- root2.suspendedLanes = 0;
- root2.pingedLanes = 0;
- root2.warmLanes = 0;
- root2.expiredLanes &= remainingLanes;
- root2.entangledLanes &= remainingLanes;
- root2.errorRecoveryDisabledLanes &= remainingLanes;
- root2.shellSuspendCounter = 0;
- var { entanglements, expirationTimes, hiddenUpdates } = root2;
- for (remainingLanes = previouslyPendingLanes & ~remainingLanes;0 < remainingLanes; ) {
- var index2 = 31 - clz32(remainingLanes), lane = 1 << index2;
- entanglements[index2] = 0;
- expirationTimes[index2] = -1;
- var hiddenUpdatesForLane = hiddenUpdates[index2];
- if (hiddenUpdatesForLane !== null)
- for (hiddenUpdates[index2] = null, index2 = 0;index2 < hiddenUpdatesForLane.length; index2++) {
- var update = hiddenUpdatesForLane[index2];
- update !== null && (update.lane &= -536870913);
- }
- remainingLanes &= ~lane;
- }
- spawnedLane !== 0 && markSpawnedDeferredLane(root2, spawnedLane, 0);
- suspendedRetryLanes !== 0 && updatedLanes === 0 && root2.tag !== 0 && (root2.suspendedLanes |= suspendedRetryLanes & ~(previouslyPendingLanes & ~finishedLanes));
- }
- function markSpawnedDeferredLane(root2, spawnedLane, entangledLanes) {
- root2.pendingLanes |= spawnedLane;
- root2.suspendedLanes &= ~spawnedLane;
- var spawnedLaneIndex = 31 - clz32(spawnedLane);
- root2.entangledLanes |= spawnedLane;
- root2.entanglements[spawnedLaneIndex] = root2.entanglements[spawnedLaneIndex] | 1073741824 | entangledLanes & 4194218;
- }
- function markRootEntangled(root2, entangledLanes) {
- var rootEntangledLanes = root2.entangledLanes |= entangledLanes;
- for (root2 = root2.entanglements;rootEntangledLanes; ) {
- var index2 = 31 - clz32(rootEntangledLanes), lane = 1 << index2;
- lane & entangledLanes | root2[index2] & entangledLanes && (root2[index2] |= entangledLanes);
- rootEntangledLanes &= ~lane;
- }
- }
- function addFiberToLanesMap(root2, fiber, lanes) {
- if (isDevToolsPresent)
- for (root2 = root2.pendingUpdatersLaneMap;0 < lanes; ) {
- var index2 = 31 - clz32(lanes), lane = 1 << index2;
- root2[index2].add(fiber);
- lanes &= ~lane;
- }
- }
- function movePendingFibersToMemoized(root2, lanes) {
- if (isDevToolsPresent)
- for (var { pendingUpdatersLaneMap, memoizedUpdaters } = root2;0 < lanes; ) {
- var index2 = 31 - clz32(lanes);
- root2 = 1 << index2;
- index2 = pendingUpdatersLaneMap[index2];
- 0 < index2.size && (index2.forEach(function(fiber) {
- var alternate = fiber.alternate;
- alternate !== null && memoizedUpdaters.has(alternate) || memoizedUpdaters.add(fiber);
- }), index2.clear());
- lanes &= ~root2;
- }
- }
- function lanesToEventPriority(lanes) {
- lanes &= -lanes;
- return 2 < lanes ? 8 < lanes ? (lanes & 134217727) !== 0 ? 32 : 268435456 : 8 : 2;
- }
- function injectInternals(internals) {
- if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined")
- return false;
- var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
- if (hook.isDisabled)
- return true;
- if (!hook.supportsFiber)
- return console.error("The installed version of React DevTools is too old and will not work with the current version of React. Please update React DevTools. https://react.dev/link/react-devtools"), true;
- try {
- rendererID = hook.inject(internals), injectedHook = hook;
- } catch (err) {
- console.error("React instrumentation encountered an error: %s.", err);
- }
- return hook.checkDCE ? true : false;
- }
- function onCommitRoot$1(root2, eventPriority) {
- if (injectedHook && typeof injectedHook.onCommitFiberRoot === "function")
- try {
- var didError = (root2.current.flags & 128) === 128;
- switch (eventPriority) {
- case 2:
- var schedulerPriority = ImmediatePriority;
- break;
- case 8:
- schedulerPriority = UserBlockingPriority;
- break;
- case 32:
- schedulerPriority = NormalPriority$1;
- break;
- case 268435456:
- schedulerPriority = IdlePriority;
- break;
- default:
- schedulerPriority = NormalPriority$1;
- }
- injectedHook.onCommitFiberRoot(rendererID, root2, schedulerPriority, didError);
- } catch (err) {
- hasLoggedError || (hasLoggedError = true, console.error("React instrumentation encountered an error: %s", err));
- }
- }
- function setIsStrictModeForDevtools(newIsStrictMode) {
- typeof log4 === "function" && unstable_setDisableYieldValue2(newIsStrictMode);
- if (injectedHook && typeof injectedHook.setStrictMode === "function")
- try {
- injectedHook.setStrictMode(rendererID, newIsStrictMode);
- } catch (err) {
- hasLoggedError || (hasLoggedError = true, console.error("React instrumentation encountered an error: %s", err));
- }
- }
- function injectProfilingHooks(profilingHooks) {
- injectedProfilingHooks = profilingHooks;
- }
- function markCommitStopped() {
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === "function" && injectedProfilingHooks.markCommitStopped();
- }
- function markComponentRenderStarted(fiber) {
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === "function" && injectedProfilingHooks.markComponentRenderStarted(fiber);
- }
- function markComponentRenderStopped() {
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === "function" && injectedProfilingHooks.markComponentRenderStopped();
- }
- function markRenderStarted(lanes) {
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === "function" && injectedProfilingHooks.markRenderStarted(lanes);
- }
- function markRenderStopped() {
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === "function" && injectedProfilingHooks.markRenderStopped();
- }
- function markStateUpdateScheduled(fiber, lane) {
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === "function" && injectedProfilingHooks.markStateUpdateScheduled(fiber, lane);
- }
- function is(x3, y3) {
- return x3 === y3 && (x3 !== 0 || 1 / x3 === 1 / y3) || x3 !== x3 && y3 !== y3;
- }
- function createCapturedValueAtFiber(value, source) {
- if (typeof value === "object" && value !== null) {
- var existing = CapturedStacks.get(value);
- if (existing !== undefined)
- return existing;
- source = {
- value,
- source,
- stack: getStackByFiberInDevAndProd(source)
- };
- CapturedStacks.set(value, source);
- return source;
- }
- return {
- value,
- source,
- stack: getStackByFiberInDevAndProd(source)
- };
- }
- function pushTreeFork(workInProgress2, totalChildren) {
- warnIfNotHydrating();
- forkStack[forkStackIndex++] = treeForkCount;
- forkStack[forkStackIndex++] = treeForkProvider;
- treeForkProvider = workInProgress2;
- treeForkCount = totalChildren;
- }
- function pushTreeId(workInProgress2, totalChildren, index2) {
- warnIfNotHydrating();
- idStack[idStackIndex++] = treeContextId;
- idStack[idStackIndex++] = treeContextOverflow;
- idStack[idStackIndex++] = treeContextProvider;
- treeContextProvider = workInProgress2;
- var baseIdWithLeadingBit = treeContextId;
- workInProgress2 = treeContextOverflow;
- var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
- baseIdWithLeadingBit &= ~(1 << baseLength);
- index2 += 1;
- var length = 32 - clz32(totalChildren) + baseLength;
- if (30 < length) {
- var numberOfOverflowBits = baseLength - baseLength % 5;
- length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
- baseIdWithLeadingBit >>= numberOfOverflowBits;
- baseLength -= numberOfOverflowBits;
- treeContextId = 1 << 32 - clz32(totalChildren) + baseLength | index2 << baseLength | baseIdWithLeadingBit;
- treeContextOverflow = length + workInProgress2;
- } else
- treeContextId = 1 << length | index2 << baseLength | baseIdWithLeadingBit, treeContextOverflow = workInProgress2;
- }
- function pushMaterializedTreeId(workInProgress2) {
- warnIfNotHydrating();
- workInProgress2.return !== null && (pushTreeFork(workInProgress2, 1), pushTreeId(workInProgress2, 1, 0));
- }
- function popTreeContext(workInProgress2) {
- for (;workInProgress2 === treeForkProvider; )
- treeForkProvider = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null, treeForkCount = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null;
- for (;workInProgress2 === treeContextProvider; )
- treeContextProvider = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextOverflow = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextId = idStack[--idStackIndex], idStack[idStackIndex] = null;
- }
- function warnIfNotHydrating() {
- isHydrating || console.error("Expected to be hydrating. This is a bug in React. Please file an issue.");
- }
- function requiredContext(c8) {
- c8 === null && console.error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.");
- return c8;
- }
- function pushHostContainer(fiber, nextRootInstance) {
- push(rootInstanceStackCursor, nextRootInstance, fiber);
- push(contextFiberStackCursor, fiber, fiber);
- push(contextStackCursor, null, fiber);
- nextRootInstance = getRootHostContext(nextRootInstance);
- pop(contextStackCursor, fiber);
- push(contextStackCursor, nextRootInstance, fiber);
- }
- function popHostContainer(fiber) {
- pop(contextStackCursor, fiber);
- pop(contextFiberStackCursor, fiber);
- pop(rootInstanceStackCursor, fiber);
- }
- function getHostContext() {
- return requiredContext(contextStackCursor.current);
- }
- function pushHostContext(fiber) {
- fiber.memoizedState !== null && push(hostTransitionProviderCursor, fiber, fiber);
- var context4 = requiredContext(contextStackCursor.current), nextContext = getChildHostContext(context4, fiber.type);
- context4 !== nextContext && (push(contextFiberStackCursor, fiber, fiber), push(contextStackCursor, nextContext, fiber));
- }
- function popHostContext(fiber) {
- contextFiberStackCursor.current === fiber && (pop(contextStackCursor, fiber), pop(contextFiberStackCursor, fiber));
- hostTransitionProviderCursor.current === fiber && (pop(hostTransitionProviderCursor, fiber), isPrimaryRenderer ? HostTransitionContext._currentValue = NotPendingTransition : HostTransitionContext._currentValue2 = NotPendingTransition);
- }
- function findNotableNode(node, indent) {
- return node.serverProps === undefined && node.serverTail.length === 0 && node.children.length === 1 && 3 < node.distanceFromLeaf && node.distanceFromLeaf > 15 - indent ? findNotableNode(node.children[0], indent) : node;
- }
- function indentation(indent) {
- return " " + " ".repeat(indent);
- }
- function added(indent) {
- return "+ " + " ".repeat(indent);
- }
- function removed(indent) {
- return "- " + " ".repeat(indent);
- }
- function describeFiberType(fiber) {
- switch (fiber.tag) {
- case 26:
- case 27:
- case 5:
- return fiber.type;
- case 16:
- return "Lazy";
- case 13:
- return "Suspense";
- case 19:
- return "SuspenseList";
- case 0:
- case 15:
- return fiber = fiber.type, fiber.displayName || fiber.name || null;
- case 11:
- return fiber = fiber.type.render, fiber.displayName || fiber.name || null;
- case 1:
- return fiber = fiber.type, fiber.displayName || fiber.name || null;
- default:
- return null;
- }
- }
- function describeTextNode(content, maxLength) {
- return needsEscaping.test(content) ? (content = JSON.stringify(content), content.length > maxLength - 2 ? 8 > maxLength ? '{"..."}' : "{" + content.slice(0, maxLength - 7) + '..."}' : "{" + content + "}") : content.length > maxLength ? 5 > maxLength ? '{"..."}' : content.slice(0, maxLength - 3) + "..." : content;
- }
- function describeTextDiff(clientText, serverProps, indent) {
- var maxLength = 120 - 2 * indent;
- if (serverProps === null)
- return added(indent) + describeTextNode(clientText, maxLength) + `
-`;
- if (typeof serverProps === "string") {
- for (var firstDiff = 0;firstDiff < serverProps.length && firstDiff < clientText.length && serverProps.charCodeAt(firstDiff) === clientText.charCodeAt(firstDiff); firstDiff++)
- ;
- firstDiff > maxLength - 8 && 10 < firstDiff && (clientText = "..." + clientText.slice(firstDiff - 8), serverProps = "..." + serverProps.slice(firstDiff - 8));
- return added(indent) + describeTextNode(clientText, maxLength) + `
-` + removed(indent) + describeTextNode(serverProps, maxLength) + `
-`;
- }
- return indentation(indent) + describeTextNode(clientText, maxLength) + `
-`;
- }
- function objectName(object2) {
- return Object.prototype.toString.call(object2).replace(/^\[object (.*)\]$/, function(m4, p0) {
- return p0;
- });
- }
- function describeValue(value, maxLength) {
- switch (typeof value) {
- case "string":
- return value = JSON.stringify(value), value.length > maxLength ? 5 > maxLength ? '"..."' : value.slice(0, maxLength - 4) + '..."' : value;
- case "object":
- if (value === null)
- return "null";
- if (isArrayImpl(value))
- return "[...]";
- if (value.$$typeof === REACT_ELEMENT_TYPE)
- return (maxLength = getComponentNameFromType(value.type)) ? "<" + maxLength + ">" : "<...>";
- var name3 = objectName(value);
- if (name3 === "Object") {
- name3 = "";
- maxLength -= 2;
- for (var propName in value)
- if (value.hasOwnProperty(propName)) {
- var jsonPropName = JSON.stringify(propName);
- jsonPropName !== '"' + propName + '"' && (propName = jsonPropName);
- maxLength -= propName.length - 2;
- jsonPropName = describeValue(value[propName], 15 > maxLength ? maxLength : 15);
- maxLength -= jsonPropName.length;
- if (0 > maxLength) {
- name3 += name3 === "" ? "..." : ", ...";
- break;
- }
- name3 += (name3 === "" ? "" : ",") + propName + ":" + jsonPropName;
- }
- return "{" + name3 + "}";
- }
- return name3;
- case "function":
- return (maxLength = value.displayName || value.name) ? "function " + maxLength : "function";
- default:
- return String(value);
- }
- }
- function describePropValue(value, maxLength) {
- return typeof value !== "string" || needsEscaping.test(value) ? "{" + describeValue(value, maxLength - 2) + "}" : value.length > maxLength - 2 ? 5 > maxLength ? '"..."' : '"' + value.slice(0, maxLength - 5) + '..."' : '"' + value + '"';
- }
- function describeExpandedElement(type, props, rowPrefix) {
- var remainingRowLength = 120 - rowPrefix.length - type.length, properties = [], propName;
- for (propName in props)
- if (props.hasOwnProperty(propName) && propName !== "children") {
- var propValue = describePropValue(props[propName], 120 - rowPrefix.length - propName.length - 1);
- remainingRowLength -= propName.length + propValue.length + 2;
- properties.push(propName + "=" + propValue);
- }
- return properties.length === 0 ? rowPrefix + "<" + type + `>
-` : 0 < remainingRowLength ? rowPrefix + "<" + type + " " + properties.join(" ") + `>
-` : rowPrefix + "<" + type + `
-` + rowPrefix + " " + properties.join(`
-` + rowPrefix + " ") + `
-` + rowPrefix + `>
-`;
- }
- function describePropertiesDiff(clientObject, serverObject, indent) {
- var properties = "", remainingServerProperties = assign({}, serverObject), propName;
- for (propName in clientObject)
- if (clientObject.hasOwnProperty(propName)) {
- delete remainingServerProperties[propName];
- var maxLength = 120 - 2 * indent - propName.length - 2, clientPropValue = describeValue(clientObject[propName], maxLength);
- serverObject.hasOwnProperty(propName) ? (maxLength = describeValue(serverObject[propName], maxLength), properties += added(indent) + propName + ": " + clientPropValue + `
-`, properties += removed(indent) + propName + ": " + maxLength + `
-`) : properties += added(indent) + propName + ": " + clientPropValue + `
-`;
- }
- for (var _propName in remainingServerProperties)
- remainingServerProperties.hasOwnProperty(_propName) && (clientObject = describeValue(remainingServerProperties[_propName], 120 - 2 * indent - _propName.length - 2), properties += removed(indent) + _propName + ": " + clientObject + `
-`);
- return properties;
- }
- function describeElementDiff(type, clientProps, serverProps, indent) {
- var content = "", serverPropNames = new Map;
- for (propName$jscomp$0 in serverProps)
- serverProps.hasOwnProperty(propName$jscomp$0) && serverPropNames.set(propName$jscomp$0.toLowerCase(), propName$jscomp$0);
- if (serverPropNames.size === 1 && serverPropNames.has("children"))
- content += describeExpandedElement(type, clientProps, indentation(indent));
- else {
- for (var _propName2 in clientProps)
- if (clientProps.hasOwnProperty(_propName2) && _propName2 !== "children") {
- var maxLength$jscomp$0 = 120 - 2 * (indent + 1) - _propName2.length - 1, serverPropName = serverPropNames.get(_propName2.toLowerCase());
- if (serverPropName !== undefined) {
- serverPropNames.delete(_propName2.toLowerCase());
- var propName$jscomp$0 = clientProps[_propName2];
- serverPropName = serverProps[serverPropName];
- var clientPropValue = describePropValue(propName$jscomp$0, maxLength$jscomp$0);
- maxLength$jscomp$0 = describePropValue(serverPropName, maxLength$jscomp$0);
- typeof propName$jscomp$0 === "object" && propName$jscomp$0 !== null && typeof serverPropName === "object" && serverPropName !== null && objectName(propName$jscomp$0) === "Object" && objectName(serverPropName) === "Object" && (2 < Object.keys(propName$jscomp$0).length || 2 < Object.keys(serverPropName).length || -1 < clientPropValue.indexOf("...") || -1 < maxLength$jscomp$0.indexOf("...")) ? content += indentation(indent + 1) + _propName2 + `={{
-` + describePropertiesDiff(propName$jscomp$0, serverPropName, indent + 2) + indentation(indent + 1) + `}}
-` : (content += added(indent + 1) + _propName2 + "=" + clientPropValue + `
-`, content += removed(indent + 1) + _propName2 + "=" + maxLength$jscomp$0 + `
-`);
- } else
- content += indentation(indent + 1) + _propName2 + "=" + describePropValue(clientProps[_propName2], maxLength$jscomp$0) + `
-`;
- }
- serverPropNames.forEach(function(propName) {
- if (propName !== "children") {
- var maxLength = 120 - 2 * (indent + 1) - propName.length - 1;
- content += removed(indent + 1) + propName + "=" + describePropValue(serverProps[propName], maxLength) + `
-`;
- }
- });
- content = content === "" ? indentation(indent) + "<" + type + `>
-` : indentation(indent) + "<" + type + `
-` + content + indentation(indent) + `>
-`;
- }
- type = serverProps.children;
- clientProps = clientProps.children;
- if (typeof type === "string" || typeof type === "number" || typeof type === "bigint") {
- serverPropNames = "";
- if (typeof clientProps === "string" || typeof clientProps === "number" || typeof clientProps === "bigint")
- serverPropNames = "" + clientProps;
- content += describeTextDiff(serverPropNames, "" + type, indent + 1);
- } else if (typeof clientProps === "string" || typeof clientProps === "number" || typeof clientProps === "bigint")
- content = type == null ? content + describeTextDiff("" + clientProps, null, indent + 1) : content + describeTextDiff("" + clientProps, undefined, indent + 1);
- return content;
- }
- function describeSiblingFiber(fiber, indent) {
- var type = describeFiberType(fiber);
- if (type === null) {
- type = "";
- for (fiber = fiber.child;fiber; )
- type += describeSiblingFiber(fiber, indent), fiber = fiber.sibling;
- return type;
- }
- return indentation(indent) + "<" + type + `>
-`;
- }
- function describeNode(node, indent) {
- var skipToNode = findNotableNode(node, indent);
- if (skipToNode !== node && (node.children.length !== 1 || node.children[0] !== skipToNode))
- return indentation(indent) + `...
-` + describeNode(skipToNode, indent + 1);
- skipToNode = "";
- var debugInfo = node.fiber._debugInfo;
- if (debugInfo)
- for (var i5 = 0;i5 < debugInfo.length; i5++) {
- var serverComponentName = debugInfo[i5].name;
- typeof serverComponentName === "string" && (skipToNode += indentation(indent) + "<" + serverComponentName + `>
-`, indent++);
- }
- debugInfo = "";
- i5 = node.fiber.pendingProps;
- if (node.fiber.tag === 6)
- debugInfo = describeTextDiff(i5, node.serverProps, indent), indent++;
- else if (serverComponentName = describeFiberType(node.fiber), serverComponentName !== null)
- if (node.serverProps === undefined) {
- debugInfo = indent;
- var maxLength = 120 - 2 * debugInfo - serverComponentName.length - 2, content = "";
- for (propName in i5)
- if (i5.hasOwnProperty(propName) && propName !== "children") {
- var propValue = describePropValue(i5[propName], 15);
- maxLength -= propName.length + propValue.length + 2;
- if (0 > maxLength) {
- content += " ...";
- break;
- }
- content += " " + propName + "=" + propValue;
- }
- debugInfo = indentation(debugInfo) + "<" + serverComponentName + content + `>
-`;
- indent++;
- } else
- node.serverProps === null ? (debugInfo = describeExpandedElement(serverComponentName, i5, added(indent)), indent++) : typeof node.serverProps === "string" ? console.error("Should not have matched a non HostText fiber to a Text node. This is a bug in React.") : (debugInfo = describeElementDiff(serverComponentName, i5, node.serverProps, indent), indent++);
- var propName = "";
- i5 = node.fiber.child;
- for (serverComponentName = 0;i5 && serverComponentName < node.children.length; )
- maxLength = node.children[serverComponentName], maxLength.fiber === i5 ? (propName += describeNode(maxLength, indent), serverComponentName++) : propName += describeSiblingFiber(i5, indent), i5 = i5.sibling;
- i5 && 0 < node.children.length && (propName += indentation(indent) + `...
-`);
- i5 = node.serverTail;
- node.serverProps === null && indent--;
- for (node = 0;node < i5.length; node++)
- serverComponentName = i5[node], propName = typeof serverComponentName === "string" ? propName + (removed(indent) + describeTextNode(serverComponentName, 120 - 2 * indent) + `
-`) : propName + describeExpandedElement(serverComponentName.type, serverComponentName.props, removed(indent));
- return skipToNode + debugInfo + propName;
- }
- function describeDiff(rootNode) {
- try {
- return `
-
-` + describeNode(rootNode, 0);
- } catch (x3) {
- return "";
- }
- }
- function buildHydrationDiffNode(fiber, distanceFromLeaf) {
- if (fiber.return === null) {
- if (hydrationDiffRootDEV === null)
- hydrationDiffRootDEV = {
- fiber,
- children: [],
- serverProps: undefined,
- serverTail: [],
- distanceFromLeaf
- };
- else {
- if (hydrationDiffRootDEV.fiber !== fiber)
- throw Error("Saw multiple hydration diff roots in a pass. This is a bug in React.");
- hydrationDiffRootDEV.distanceFromLeaf > distanceFromLeaf && (hydrationDiffRootDEV.distanceFromLeaf = distanceFromLeaf);
- }
- return hydrationDiffRootDEV;
- }
- var siblings = buildHydrationDiffNode(fiber.return, distanceFromLeaf + 1).children;
- if (0 < siblings.length && siblings[siblings.length - 1].fiber === fiber)
- return siblings = siblings[siblings.length - 1], siblings.distanceFromLeaf > distanceFromLeaf && (siblings.distanceFromLeaf = distanceFromLeaf), siblings;
- distanceFromLeaf = {
- fiber,
- children: [],
- serverProps: undefined,
- serverTail: [],
- distanceFromLeaf
- };
- siblings.push(distanceFromLeaf);
- return distanceFromLeaf;
- }
- function warnNonHydratedInstance(fiber, rejectedCandidate) {
- didSuspendOrErrorDEV || (fiber = buildHydrationDiffNode(fiber, 0), fiber.serverProps = null, rejectedCandidate !== null && (rejectedCandidate = describeHydratableInstanceForDevWarnings(rejectedCandidate), fiber.serverTail.push(rejectedCandidate)));
- }
- function throwOnHydrationMismatch(fiber) {
- var diff = "", diffRoot = hydrationDiffRootDEV;
- diffRoot !== null && (hydrationDiffRootDEV = null, diff = describeDiff(diffRoot));
- queueHydrationError(createCapturedValueAtFiber(Error(`Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:
-
-- A server/client branch \`if (typeof window !== 'undefined')\`.
-- Variable input such as \`Date.now()\` or \`Math.random()\` which changes each time it's called.
-- Date formatting in a user's locale which doesn't match the server.
-- External changing data without sending a snapshot of it along with the HTML.
-- Invalid HTML tag nesting.
-
-It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.
-
-https://react.dev/link/hydration-mismatch` + diff), fiber));
- throw HydrationMismatchException;
- }
- function prepareToHydrateHostInstance(fiber, hostContext) {
- if (!supportsHydration)
- throw Error("Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
- hydrateInstance(fiber.stateNode, fiber.type, fiber.memoizedProps, hostContext, fiber) || throwOnHydrationMismatch(fiber);
- }
- function popToNextHostParent(fiber) {
- for (hydrationParentFiber = fiber.return;hydrationParentFiber; )
- switch (hydrationParentFiber.tag) {
- case 3:
- case 27:
- rootOrSingletonContext = true;
- return;
- case 5:
- case 13:
- rootOrSingletonContext = false;
- return;
- default:
- hydrationParentFiber = hydrationParentFiber.return;
- }
- }
- function popHydrationState(fiber) {
- if (!supportsHydration || fiber !== hydrationParentFiber)
- return false;
- if (!isHydrating)
- return popToNextHostParent(fiber), isHydrating = true, false;
- var shouldClear = false;
- supportsSingletons ? fiber.tag !== 3 && fiber.tag !== 27 && (fiber.tag !== 5 || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps)) && (shouldClear = true) : fiber.tag !== 3 && (fiber.tag !== 5 || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps)) && (shouldClear = true);
- if (shouldClear && nextHydratableInstance) {
- for (shouldClear = nextHydratableInstance;shouldClear; ) {
- var diffNode = buildHydrationDiffNode(fiber, 0), description = describeHydratableInstanceForDevWarnings(shouldClear);
- diffNode.serverTail.push(description);
- shouldClear = description.type === "Suspense" ? getNextHydratableInstanceAfterSuspenseInstance(shouldClear) : getNextHydratableSibling(shouldClear);
- }
- throwOnHydrationMismatch(fiber);
- }
- popToNextHostParent(fiber);
- if (fiber.tag === 13) {
- if (!supportsHydration)
- throw Error("Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
- fiber = fiber.memoizedState;
- fiber = fiber !== null ? fiber.dehydrated : null;
- if (!fiber)
- throw Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
- nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance(fiber);
- } else
- nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
- return true;
- }
- function resetHydrationState() {
- supportsHydration && (nextHydratableInstance = hydrationParentFiber = null, didSuspendOrErrorDEV = isHydrating = false);
- }
- function queueHydrationError(error46) {
- hydrationErrors === null ? hydrationErrors = [error46] : hydrationErrors.push(error46);
- }
- function emitPendingHydrationWarnings() {
- var diffRoot = hydrationDiffRootDEV;
- diffRoot !== null && (hydrationDiffRootDEV = null, diffRoot = describeDiff(diffRoot), console.error(`A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:
-
-- A server/client branch \`if (typeof window !== 'undefined')\`.
-- Variable input such as \`Date.now()\` or \`Math.random()\` which changes each time it's called.
-- Date formatting in a user's locale which doesn't match the server.
-- External changing data without sending a snapshot of it along with the HTML.
-- Invalid HTML tag nesting.
-
-It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.
-
-%s%s`, "https://react.dev/link/hydration-mismatch", diffRoot));
- }
- function finishQueueingConcurrentUpdates() {
- for (var endIndex = concurrentQueuesIndex, i5 = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0;i5 < endIndex; ) {
- var fiber = concurrentQueues[i5];
- concurrentQueues[i5++] = null;
- var queue = concurrentQueues[i5];
- concurrentQueues[i5++] = null;
- var update = concurrentQueues[i5];
- concurrentQueues[i5++] = null;
- var lane = concurrentQueues[i5];
- concurrentQueues[i5++] = null;
- if (queue !== null && update !== null) {
- var pending = queue.pending;
- pending === null ? update.next = update : (update.next = pending.next, pending.next = update);
- queue.pending = update;
- }
- lane !== 0 && markUpdateLaneFromFiberToRoot(fiber, update, lane);
- }
- }
- function enqueueUpdate$1(fiber, queue, update, lane) {
- concurrentQueues[concurrentQueuesIndex++] = fiber;
- concurrentQueues[concurrentQueuesIndex++] = queue;
- concurrentQueues[concurrentQueuesIndex++] = update;
- concurrentQueues[concurrentQueuesIndex++] = lane;
- concurrentlyUpdatedLanes |= lane;
- fiber.lanes |= lane;
- fiber = fiber.alternate;
- fiber !== null && (fiber.lanes |= lane);
- }
- function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
- enqueueUpdate$1(fiber, queue, update, lane);
- return getRootForUpdatedFiber(fiber);
- }
- function enqueueConcurrentRenderForLane(fiber, lane) {
- enqueueUpdate$1(fiber, null, null, lane);
- return getRootForUpdatedFiber(fiber);
- }
- function markUpdateLaneFromFiberToRoot(sourceFiber, update, lane) {
- sourceFiber.lanes |= lane;
- var alternate = sourceFiber.alternate;
- alternate !== null && (alternate.lanes |= lane);
- for (var isHidden = false, parent = sourceFiber.return;parent !== null; )
- parent.childLanes |= lane, alternate = parent.alternate, alternate !== null && (alternate.childLanes |= lane), parent.tag === 22 && (sourceFiber = parent.stateNode, sourceFiber === null || sourceFiber._visibility & 1 || (isHidden = true)), sourceFiber = parent, parent = parent.return;
- isHidden && update !== null && sourceFiber.tag === 3 && (parent = sourceFiber.stateNode, isHidden = 31 - clz32(lane), parent = parent.hiddenUpdates, sourceFiber = parent[isHidden], sourceFiber === null ? parent[isHidden] = [update] : sourceFiber.push(update), update.lane = lane | 536870912);
- }
- function getRootForUpdatedFiber(sourceFiber) {
- if (nestedUpdateCount > NESTED_UPDATE_LIMIT)
- throw nestedPassiveUpdateCount = nestedUpdateCount = 0, rootWithPassiveNestedUpdates = rootWithNestedUpdates = null, Error("Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.");
- nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT && (nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null, console.error("Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."));
- sourceFiber.alternate === null && (sourceFiber.flags & 4098) !== 0 && warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
- for (var node = sourceFiber, parent = node.return;parent !== null; )
- node.alternate === null && (node.flags & 4098) !== 0 && warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber), node = parent, parent = node.return;
- return node.tag === 3 ? node.stateNode : null;
- }
- function pushNestedEffectDurations() {
- var prevEffectDuration = profilerEffectDuration;
- profilerEffectDuration = 0;
- return prevEffectDuration;
- }
- function popNestedEffectDurations(prevEffectDuration) {
- var elapsedTime = profilerEffectDuration;
- profilerEffectDuration = prevEffectDuration;
- return elapsedTime;
- }
- function bubbleNestedEffectDurations(prevEffectDuration) {
- var elapsedTime = profilerEffectDuration;
- profilerEffectDuration += prevEffectDuration;
- return elapsedTime;
- }
- function startProfilerTimer(fiber) {
- profilerStartTime = now2();
- 0 > fiber.actualStartTime && (fiber.actualStartTime = profilerStartTime);
- }
- function stopProfilerTimerIfRunningAndRecordDuration(fiber) {
- if (0 <= profilerStartTime) {
- var elapsedTime = now2() - profilerStartTime;
- fiber.actualDuration += elapsedTime;
- fiber.selfBaseDuration = elapsedTime;
- profilerStartTime = -1;
- }
- }
- function stopProfilerTimerIfRunningAndRecordIncompleteDuration(fiber) {
- if (0 <= profilerStartTime) {
- var elapsedTime = now2() - profilerStartTime;
- fiber.actualDuration += elapsedTime;
- profilerStartTime = -1;
- }
- }
- function recordEffectDuration() {
- if (0 <= profilerStartTime) {
- var elapsedTime = now2() - profilerStartTime;
- profilerStartTime = -1;
- profilerEffectDuration += elapsedTime;
- }
- }
- function startEffectTimer() {
- profilerStartTime = now2();
- }
- function transferActualDuration(fiber) {
- for (var child = fiber.child;child; )
- fiber.actualDuration += child.actualDuration, child = child.sibling;
- }
- function ensureRootIsScheduled(root2) {
- root2 !== lastScheduledRoot && root2.next === null && (lastScheduledRoot === null ? firstScheduledRoot = lastScheduledRoot = root2 : lastScheduledRoot = lastScheduledRoot.next = root2);
- mightHavePendingSyncWork = true;
- ReactSharedInternals.actQueue !== null ? didScheduleMicrotask_act || (didScheduleMicrotask_act = true, scheduleImmediateTask(processRootScheduleInMicrotask)) : didScheduleMicrotask || (didScheduleMicrotask = true, scheduleImmediateTask(processRootScheduleInMicrotask));
- }
- function flushSyncWorkAcrossRoots_impl(syncTransitionLanes, onlyLegacy) {
- if (!isFlushingWork && mightHavePendingSyncWork) {
- isFlushingWork = true;
- do {
- var didPerformSomeWork = false;
- for (var root2 = firstScheduledRoot;root2 !== null; ) {
- if (!onlyLegacy)
- if (syncTransitionLanes !== 0) {
- var pendingLanes = root2.pendingLanes;
- if (pendingLanes === 0)
- var nextLanes = 0;
- else {
- var { suspendedLanes, pingedLanes } = root2;
- nextLanes = (1 << 31 - clz32(42 | syncTransitionLanes) + 1) - 1;
- nextLanes &= pendingLanes & ~(suspendedLanes & ~pingedLanes);
- nextLanes = nextLanes & 201326677 ? nextLanes & 201326677 | 1 : nextLanes ? nextLanes | 2 : 0;
- }
- nextLanes !== 0 && (didPerformSomeWork = true, performSyncWorkOnRoot(root2, nextLanes));
- } else
- nextLanes = workInProgressRootRenderLanes, nextLanes = getNextLanes(root2, root2 === workInProgressRoot ? nextLanes : 0), (nextLanes & 3) === 0 || checkIfRootIsPrerendering(root2, nextLanes) || (didPerformSomeWork = true, performSyncWorkOnRoot(root2, nextLanes));
- root2 = root2.next;
- }
- } while (didPerformSomeWork);
- isFlushingWork = false;
- }
- }
- function processRootScheduleInMicrotask() {
- mightHavePendingSyncWork = didScheduleMicrotask_act = didScheduleMicrotask = false;
- var syncTransitionLanes = 0;
- currentEventTransitionLane !== 0 && (shouldAttemptEagerTransition() && (syncTransitionLanes = currentEventTransitionLane), currentEventTransitionLane = 0);
- for (var currentTime = now$1(), prev = null, root2 = firstScheduledRoot;root2 !== null; ) {
- var next = root2.next, nextLanes = scheduleTaskForRootDuringMicrotask(root2, currentTime);
- if (nextLanes === 0)
- root2.next = null, prev === null ? firstScheduledRoot = next : prev.next = next, next === null && (lastScheduledRoot = prev);
- else if (prev = root2, syncTransitionLanes !== 0 || (nextLanes & 3) !== 0)
- mightHavePendingSyncWork = true;
- root2 = next;
- }
- flushSyncWorkAcrossRoots_impl(syncTransitionLanes, false);
- }
- function scheduleTaskForRootDuringMicrotask(root2, currentTime) {
- for (var { suspendedLanes, pingedLanes, expirationTimes } = root2, lanes = root2.pendingLanes & -62914561;0 < lanes; ) {
- var index2 = 31 - clz32(lanes), lane = 1 << index2, expirationTime = expirationTimes[index2];
- if (expirationTime === -1) {
- if ((lane & suspendedLanes) === 0 || (lane & pingedLanes) !== 0)
- expirationTimes[index2] = computeExpirationTime(lane, currentTime);
- } else
- expirationTime <= currentTime && (root2.expiredLanes |= lane);
- lanes &= ~lane;
- }
- currentTime = workInProgressRoot;
- suspendedLanes = workInProgressRootRenderLanes;
- suspendedLanes = getNextLanes(root2, root2 === currentTime ? suspendedLanes : 0);
- pingedLanes = root2.callbackNode;
- if (suspendedLanes === 0 || root2 === currentTime && workInProgressSuspendedReason === SuspendedOnData || root2.cancelPendingCommit !== null)
- return pingedLanes !== null && cancelCallback(pingedLanes), root2.callbackNode = null, root2.callbackPriority = 0;
- if ((suspendedLanes & 3) === 0 || checkIfRootIsPrerendering(root2, suspendedLanes)) {
- currentTime = suspendedLanes & -suspendedLanes;
- if (currentTime !== root2.callbackPriority || ReactSharedInternals.actQueue !== null && pingedLanes !== fakeActCallbackNode$1)
- cancelCallback(pingedLanes);
- else
- return currentTime;
- switch (lanesToEventPriority(suspendedLanes)) {
- case 2:
- case 8:
- suspendedLanes = UserBlockingPriority;
- break;
- case 32:
- suspendedLanes = NormalPriority$1;
- break;
- case 268435456:
- suspendedLanes = IdlePriority;
- break;
- default:
- suspendedLanes = NormalPriority$1;
- }
- pingedLanes = performWorkOnRootViaSchedulerTask.bind(null, root2);
- ReactSharedInternals.actQueue !== null ? (ReactSharedInternals.actQueue.push(pingedLanes), suspendedLanes = fakeActCallbackNode$1) : suspendedLanes = scheduleCallback$3(suspendedLanes, pingedLanes);
- root2.callbackPriority = currentTime;
- root2.callbackNode = suspendedLanes;
- return currentTime;
- }
- pingedLanes !== null && cancelCallback(pingedLanes);
- root2.callbackPriority = 2;
- root2.callbackNode = null;
- return 2;
- }
- function performWorkOnRootViaSchedulerTask(root2, didTimeout) {
- nestedUpdateScheduled = currentUpdateIsNested = false;
- var originalCallbackNode = root2.callbackNode;
- if (flushPassiveEffects() && root2.callbackNode !== originalCallbackNode)
- return null;
- var workInProgressRootRenderLanes$jscomp$0 = workInProgressRootRenderLanes;
- workInProgressRootRenderLanes$jscomp$0 = getNextLanes(root2, root2 === workInProgressRoot ? workInProgressRootRenderLanes$jscomp$0 : 0);
- if (workInProgressRootRenderLanes$jscomp$0 === 0)
- return null;
- performWorkOnRoot(root2, workInProgressRootRenderLanes$jscomp$0, didTimeout);
- scheduleTaskForRootDuringMicrotask(root2, now$1());
- return root2.callbackNode != null && root2.callbackNode === originalCallbackNode ? performWorkOnRootViaSchedulerTask.bind(null, root2) : null;
- }
- function performSyncWorkOnRoot(root2, lanes) {
- if (flushPassiveEffects())
- return null;
- currentUpdateIsNested = nestedUpdateScheduled;
- nestedUpdateScheduled = false;
- performWorkOnRoot(root2, lanes, true);
- }
- function cancelCallback(callbackNode) {
- callbackNode !== fakeActCallbackNode$1 && callbackNode !== null && cancelCallback$1(callbackNode);
- }
- function scheduleImmediateTask(cb) {
- ReactSharedInternals.actQueue !== null && ReactSharedInternals.actQueue.push(function() {
- cb();
- return null;
- });
- supportsMicrotasks ? scheduleMicrotask(function() {
- (executionContext & (RenderContext | CommitContext)) !== NoContext ? scheduleCallback$3(ImmediatePriority, cb) : cb();
- }) : scheduleCallback$3(ImmediatePriority, cb);
- }
- function requestTransitionLane() {
- currentEventTransitionLane === 0 && (currentEventTransitionLane = claimNextTransitionLane());
- return currentEventTransitionLane;
- }
- function entangleAsyncAction(transition, thenable) {
- if (currentEntangledListeners === null) {
- var entangledListeners = currentEntangledListeners = [];
- currentEntangledPendingCount = 0;
- currentEntangledLane = requestTransitionLane();
- currentEntangledActionThenable = {
- status: "pending",
- value: undefined,
- then: function(resolve9) {
- entangledListeners.push(resolve9);
- }
- };
- }
- currentEntangledPendingCount++;
- thenable.then(pingEngtangledActionScope, pingEngtangledActionScope);
- return thenable;
- }
- function pingEngtangledActionScope() {
- if (--currentEntangledPendingCount === 0 && currentEntangledListeners !== null) {
- currentEntangledActionThenable !== null && (currentEntangledActionThenable.status = "fulfilled");
- var listeners = currentEntangledListeners;
- currentEntangledListeners = null;
- currentEntangledLane = 0;
- currentEntangledActionThenable = null;
- for (var i5 = 0;i5 < listeners.length; i5++)
- (0, listeners[i5])();
- }
- }
- function chainThenableValue(thenable, result) {
- var listeners = [], thenableWithOverride = {
- status: "pending",
- value: null,
- reason: null,
- then: function(resolve9) {
- listeners.push(resolve9);
- }
- };
- thenable.then(function() {
- thenableWithOverride.status = "fulfilled";
- thenableWithOverride.value = result;
- for (var i5 = 0;i5 < listeners.length; i5++)
- (0, listeners[i5])(result);
- }, function(error46) {
- thenableWithOverride.status = "rejected";
- thenableWithOverride.reason = error46;
- for (error46 = 0;error46 < listeners.length; error46++)
- (0, listeners[error46])(undefined);
- });
- return thenableWithOverride;
- }
- function initializeUpdateQueue(fiber) {
- fiber.updateQueue = {
- baseState: fiber.memoizedState,
- firstBaseUpdate: null,
- lastBaseUpdate: null,
- shared: { pending: null, lanes: 0, hiddenCallbacks: null },
- callbacks: null
- };
- }
- function cloneUpdateQueue(current2, workInProgress2) {
- current2 = current2.updateQueue;
- workInProgress2.updateQueue === current2 && (workInProgress2.updateQueue = {
- baseState: current2.baseState,
- firstBaseUpdate: current2.firstBaseUpdate,
- lastBaseUpdate: current2.lastBaseUpdate,
- shared: current2.shared,
- callbacks: null
- });
- }
- function createUpdate(lane) {
- return {
- lane,
- tag: UpdateState,
- payload: null,
- callback: null,
- next: null
- };
- }
- function enqueueUpdate(fiber, update, lane) {
- var updateQueue = fiber.updateQueue;
- if (updateQueue === null)
- return null;
- updateQueue = updateQueue.shared;
- if (currentlyProcessingQueue === updateQueue && !didWarnUpdateInsideUpdate) {
- var componentName2 = getComponentNameFromFiber(fiber);
- console.error(`An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback.
-
-Please update the following component: %s`, componentName2);
- didWarnUpdateInsideUpdate = true;
- }
- if ((executionContext & RenderContext) !== NoContext)
- return componentName2 = updateQueue.pending, componentName2 === null ? update.next = update : (update.next = componentName2.next, componentName2.next = update), updateQueue.pending = update, update = getRootForUpdatedFiber(fiber), markUpdateLaneFromFiberToRoot(fiber, null, lane), update;
- enqueueUpdate$1(fiber, updateQueue, update, lane);
- return getRootForUpdatedFiber(fiber);
- }
- function entangleTransitions(root2, fiber, lane) {
- fiber = fiber.updateQueue;
- if (fiber !== null && (fiber = fiber.shared, (lane & 4194176) !== 0)) {
- var queueLanes = fiber.lanes;
- queueLanes &= root2.pendingLanes;
- lane |= queueLanes;
- fiber.lanes = lane;
- markRootEntangled(root2, lane);
- }
- }
- function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
- var { updateQueue: queue, alternate: current2 } = workInProgress2;
- if (current2 !== null && (current2 = current2.updateQueue, queue === current2)) {
- var newFirst = null, newLast = null;
- queue = queue.firstBaseUpdate;
- if (queue !== null) {
- do {
- var clone3 = {
- lane: queue.lane,
- tag: queue.tag,
- payload: queue.payload,
- callback: null,
- next: null
- };
- newLast === null ? newFirst = newLast = clone3 : newLast = newLast.next = clone3;
- queue = queue.next;
- } while (queue !== null);
- newLast === null ? newFirst = newLast = capturedUpdate : newLast = newLast.next = capturedUpdate;
- } else
- newFirst = newLast = capturedUpdate;
- queue = {
- baseState: current2.baseState,
- firstBaseUpdate: newFirst,
- lastBaseUpdate: newLast,
- shared: current2.shared,
- callbacks: current2.callbacks
- };
- workInProgress2.updateQueue = queue;
- return;
- }
- workInProgress2 = queue.lastBaseUpdate;
- workInProgress2 === null ? queue.firstBaseUpdate = capturedUpdate : workInProgress2.next = capturedUpdate;
- queue.lastBaseUpdate = capturedUpdate;
- }
- function suspendIfUpdateReadFromEntangledAsyncAction() {
- if (didReadFromEntangledAsyncAction) {
- var entangledActionThenable = currentEntangledActionThenable;
- if (entangledActionThenable !== null)
- throw entangledActionThenable;
- }
- }
- function processUpdateQueue(workInProgress2, props, instance$jscomp$0, renderLanes2) {
- didReadFromEntangledAsyncAction = false;
- var queue = workInProgress2.updateQueue;
- hasForceUpdate = false;
- currentlyProcessingQueue = queue.shared;
- var { firstBaseUpdate, lastBaseUpdate } = queue, pendingQueue = queue.shared.pending;
- if (pendingQueue !== null) {
- queue.shared.pending = null;
- var lastPendingUpdate = pendingQueue, firstPendingUpdate = lastPendingUpdate.next;
- lastPendingUpdate.next = null;
- lastBaseUpdate === null ? firstBaseUpdate = firstPendingUpdate : lastBaseUpdate.next = firstPendingUpdate;
- lastBaseUpdate = lastPendingUpdate;
- var current2 = workInProgress2.alternate;
- current2 !== null && (current2 = current2.updateQueue, pendingQueue = current2.lastBaseUpdate, pendingQueue !== lastBaseUpdate && (pendingQueue === null ? current2.firstBaseUpdate = firstPendingUpdate : pendingQueue.next = firstPendingUpdate, current2.lastBaseUpdate = lastPendingUpdate));
- }
- if (firstBaseUpdate !== null) {
- var newState = queue.baseState;
- lastBaseUpdate = 0;
- current2 = firstPendingUpdate = lastPendingUpdate = null;
- pendingQueue = firstBaseUpdate;
- do {
- var updateLane = pendingQueue.lane & -536870913, isHiddenUpdate = updateLane !== pendingQueue.lane;
- if (isHiddenUpdate ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes2 & updateLane) === updateLane) {
- updateLane !== 0 && updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction = true);
- current2 !== null && (current2 = current2.next = {
- lane: 0,
- tag: pendingQueue.tag,
- payload: pendingQueue.payload,
- callback: null,
- next: null
- });
- a: {
- updateLane = workInProgress2;
- var partialState = pendingQueue;
- var nextProps = props, instance = instance$jscomp$0;
- switch (partialState.tag) {
- case ReplaceState:
- partialState = partialState.payload;
- if (typeof partialState === "function") {
- isDisallowedContextReadInDEV = true;
- var nextState = partialState.call(instance, newState, nextProps);
- if (updateLane.mode & 8) {
- setIsStrictModeForDevtools(true);
- try {
- partialState.call(instance, newState, nextProps);
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- isDisallowedContextReadInDEV = false;
- newState = nextState;
- break a;
- }
- newState = partialState;
- break a;
- case CaptureUpdate:
- updateLane.flags = updateLane.flags & -65537 | 128;
- case UpdateState:
- nextState = partialState.payload;
- if (typeof nextState === "function") {
- isDisallowedContextReadInDEV = true;
- partialState = nextState.call(instance, newState, nextProps);
- if (updateLane.mode & 8) {
- setIsStrictModeForDevtools(true);
- try {
- nextState.call(instance, newState, nextProps);
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- isDisallowedContextReadInDEV = false;
- } else
- partialState = nextState;
- if (partialState === null || partialState === undefined)
- break a;
- newState = assign({}, newState, partialState);
- break a;
- case ForceUpdate:
- hasForceUpdate = true;
- }
- }
- updateLane = pendingQueue.callback;
- updateLane !== null && (workInProgress2.flags |= 64, isHiddenUpdate && (workInProgress2.flags |= 8192), isHiddenUpdate = queue.callbacks, isHiddenUpdate === null ? queue.callbacks = [updateLane] : isHiddenUpdate.push(updateLane));
- } else
- isHiddenUpdate = {
- lane: updateLane,
- tag: pendingQueue.tag,
- payload: pendingQueue.payload,
- callback: pendingQueue.callback,
- next: null
- }, current2 === null ? (firstPendingUpdate = current2 = isHiddenUpdate, lastPendingUpdate = newState) : current2 = current2.next = isHiddenUpdate, lastBaseUpdate |= updateLane;
- pendingQueue = pendingQueue.next;
- if (pendingQueue === null)
- if (pendingQueue = queue.shared.pending, pendingQueue === null)
- break;
- else
- isHiddenUpdate = pendingQueue, pendingQueue = isHiddenUpdate.next, isHiddenUpdate.next = null, queue.lastBaseUpdate = isHiddenUpdate, queue.shared.pending = null;
- } while (1);
- current2 === null && (lastPendingUpdate = newState);
- queue.baseState = lastPendingUpdate;
- queue.firstBaseUpdate = firstPendingUpdate;
- queue.lastBaseUpdate = current2;
- firstBaseUpdate === null && (queue.shared.lanes = 0);
- workInProgressRootSkippedLanes |= lastBaseUpdate;
- workInProgress2.lanes = lastBaseUpdate;
- workInProgress2.memoizedState = newState;
- }
- currentlyProcessingQueue = null;
- }
- function callCallback(callback, context4) {
- if (typeof callback !== "function")
- throw Error("Invalid argument passed as callback. Expected a function. Instead received: " + callback);
- callback.call(context4);
- }
- function commitHiddenCallbacks(updateQueue, context4) {
- var hiddenCallbacks = updateQueue.shared.hiddenCallbacks;
- if (hiddenCallbacks !== null)
- for (updateQueue.shared.hiddenCallbacks = null, updateQueue = 0;updateQueue < hiddenCallbacks.length; updateQueue++)
- callCallback(hiddenCallbacks[updateQueue], context4);
- }
- function commitCallbacks(updateQueue, context4) {
- var callbacks = updateQueue.callbacks;
- if (callbacks !== null)
- for (updateQueue.callbacks = null, updateQueue = 0;updateQueue < callbacks.length; updateQueue++)
- callCallback(callbacks[updateQueue], context4);
- }
- function shallowEqual(objA, objB) {
- if (objectIs(objA, objB))
- return true;
- if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null)
- return false;
- var keysA = Object.keys(objA), keysB = Object.keys(objB);
- if (keysA.length !== keysB.length)
- return false;
- for (keysB = 0;keysB < keysA.length; keysB++) {
- var currentKey = keysA[keysB];
- if (!hasOwnProperty15.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey]))
- return false;
- }
- return true;
- }
- function createThenableState() {
- return { didWarnAboutUncachedPromise: false, thenables: [] };
- }
- function isThenableResolved(thenable) {
- thenable = thenable.status;
- return thenable === "fulfilled" || thenable === "rejected";
- }
- function noop$1() {}
- function trackUsedThenable(thenableState2, thenable, index2) {
- ReactSharedInternals.actQueue !== null && (ReactSharedInternals.didUsePromise = true);
- var trackedThenables = thenableState2.thenables;
- index2 = trackedThenables[index2];
- index2 === undefined ? trackedThenables.push(thenable) : index2 !== thenable && (thenableState2.didWarnAboutUncachedPromise || (thenableState2.didWarnAboutUncachedPromise = true, console.error("A component was suspended by an uncached promise. Creating promises inside a Client Component or hook is not yet supported, except via a Suspense-compatible library or framework.")), thenable.then(noop$1, noop$1), thenable = index2);
- switch (thenable.status) {
- case "fulfilled":
- return thenable.value;
- case "rejected":
- throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
- default:
- if (typeof thenable.status === "string")
- thenable.then(noop$1, noop$1);
- else {
- thenableState2 = workInProgressRoot;
- if (thenableState2 !== null && 100 < thenableState2.shellSuspendCounter)
- throw Error("async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server.");
- thenableState2 = thenable;
- thenableState2.status = "pending";
- thenableState2.then(function(fulfilledValue) {
- if (thenable.status === "pending") {
- var fulfilledThenable = thenable;
- fulfilledThenable.status = "fulfilled";
- fulfilledThenable.value = fulfilledValue;
- }
- }, function(error46) {
- if (thenable.status === "pending") {
- var rejectedThenable = thenable;
- rejectedThenable.status = "rejected";
- rejectedThenable.reason = error46;
- }
- });
- }
- switch (thenable.status) {
- case "fulfilled":
- return thenable.value;
- case "rejected":
- throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
- }
- suspendedThenable = thenable;
- needsToResetSuspendedThenableDEV = true;
- throw SuspenseException;
- }
- }
- function getSuspendedThenable() {
- if (suspendedThenable === null)
- throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue.");
- var thenable = suspendedThenable;
- suspendedThenable = null;
- needsToResetSuspendedThenableDEV = false;
- return thenable;
- }
- function checkIfUseWrappedInAsyncCatch(rejectedReason) {
- if (rejectedReason === SuspenseException)
- throw Error("Hooks are not supported inside an async component. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server.");
- }
- function pushDebugInfo(debugInfo) {
- var previousDebugInfo = currentDebugInfo;
- debugInfo != null && (currentDebugInfo = previousDebugInfo === null ? debugInfo : previousDebugInfo.concat(debugInfo));
- return previousDebugInfo;
- }
- function validateFragmentProps(element, fiber, returnFiber) {
- for (var keys2 = Object.keys(element.props), i5 = 0;i5 < keys2.length; i5++) {
- var key = keys2[i5];
- if (key !== "children" && key !== "key") {
- fiber === null && (fiber = createFiberFromElement(element, returnFiber.mode, 0), fiber._debugInfo = currentDebugInfo, fiber.return = returnFiber);
- runWithFiberInDEV(fiber, function(erroredKey) {
- console.error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", erroredKey);
- }, key);
- break;
- }
- }
- }
- function unwrapThenable(thenable) {
- var index2 = thenableIndexCounter$1;
- thenableIndexCounter$1 += 1;
- thenableState$1 === null && (thenableState$1 = createThenableState());
- return trackUsedThenable(thenableState$1, thenable, index2);
- }
- function coerceRef(workInProgress2, element) {
- element = element.props.ref;
- workInProgress2.ref = element !== undefined ? element : null;
- }
- function throwOnInvalidObjectType(returnFiber, newChild) {
- if (newChild.$$typeof === REACT_LEGACY_ELEMENT_TYPE)
- throw Error(`A React Element from an older version of React was rendered. This is not supported. It can happen if:
-- Multiple copies of the "react" package is used.
-- A library pre-bundled an old copy of "react" or "react/jsx-runtime".
-- A compiler tries to "inline" JSX instead of using the runtime.`);
- returnFiber = Object.prototype.toString.call(newChild);
- throw Error("Objects are not valid as a React child (found: " + (returnFiber === "[object Object]" ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : returnFiber) + "). If you meant to render a collection of children, use an array instead.");
- }
- function warnOnFunctionType(returnFiber, invalidChild) {
- var parentName = getComponentNameFromFiber(returnFiber) || "Component";
- ownerHasFunctionTypeWarning[parentName] || (ownerHasFunctionTypeWarning[parentName] = true, invalidChild = invalidChild.displayName || invalidChild.name || "Component", returnFiber.tag === 3 ? console.error(`Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.
- root.render(%s)`, invalidChild, invalidChild, invalidChild) : console.error(`Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.
- <%s>{%s}%s>`, invalidChild, invalidChild, parentName, invalidChild, parentName));
- }
- function warnOnSymbolType(returnFiber, invalidChild) {
- var parentName = getComponentNameFromFiber(returnFiber) || "Component";
- ownerHasSymbolTypeWarning[parentName] || (ownerHasSymbolTypeWarning[parentName] = true, invalidChild = String(invalidChild), returnFiber.tag === 3 ? console.error(`Symbols are not valid as a React child.
- root.render(%s)`, invalidChild) : console.error(`Symbols are not valid as a React child.
- <%s>%s%s>`, parentName, invalidChild, parentName));
- }
- function createChildReconciler(shouldTrackSideEffects) {
- function deleteChild(returnFiber, childToDelete) {
- if (shouldTrackSideEffects) {
- var deletions = returnFiber.deletions;
- deletions === null ? (returnFiber.deletions = [childToDelete], returnFiber.flags |= 16) : deletions.push(childToDelete);
- }
- }
- function deleteRemainingChildren(returnFiber, currentFirstChild) {
- if (!shouldTrackSideEffects)
- return null;
- for (;currentFirstChild !== null; )
- deleteChild(returnFiber, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
- return null;
- }
- function mapRemainingChildren(currentFirstChild) {
- for (var existingChildren = new Map;currentFirstChild !== null; )
- currentFirstChild.key !== null ? existingChildren.set(currentFirstChild.key, currentFirstChild) : existingChildren.set(currentFirstChild.index, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
- return existingChildren;
- }
- function useFiber(fiber, pendingProps) {
- fiber = createWorkInProgress(fiber, pendingProps);
- fiber.index = 0;
- fiber.sibling = null;
- return fiber;
- }
- function placeChild(newFiber, lastPlacedIndex, newIndex) {
- newFiber.index = newIndex;
- if (!shouldTrackSideEffects)
- return newFiber.flags |= 1048576, lastPlacedIndex;
- newIndex = newFiber.alternate;
- if (newIndex !== null)
- return newIndex = newIndex.index, newIndex < lastPlacedIndex ? (newFiber.flags |= 33554434, lastPlacedIndex) : newIndex;
- newFiber.flags |= 33554434;
- return lastPlacedIndex;
- }
- function placeSingleChild(newFiber) {
- shouldTrackSideEffects && newFiber.alternate === null && (newFiber.flags |= 33554434);
- return newFiber;
- }
- function updateTextNode(returnFiber, current2, textContent, lanes) {
- if (current2 === null || current2.tag !== 6)
- return current2 = createFiberFromText(textContent, returnFiber.mode, lanes), current2.return = returnFiber, current2._debugOwner = returnFiber, current2._debugInfo = currentDebugInfo, current2;
- current2 = useFiber(current2, textContent);
- current2.return = returnFiber;
- current2._debugInfo = currentDebugInfo;
- return current2;
- }
- function updateElement(returnFiber, current2, element, lanes) {
- var elementType = element.type;
- if (elementType === REACT_FRAGMENT_TYPE)
- return current2 = updateFragment(returnFiber, current2, element.props.children, lanes, element.key), validateFragmentProps(element, current2, returnFiber), current2;
- if (current2 !== null && (current2.elementType === elementType || isCompatibleFamilyForHotReloading(current2, element) || typeof elementType === "object" && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && callLazyInitInDEV(elementType) === current2.type))
- return current2 = useFiber(current2, element.props), coerceRef(current2, element), current2.return = returnFiber, current2._debugOwner = element._owner, current2._debugInfo = currentDebugInfo, current2;
- current2 = createFiberFromElement(element, returnFiber.mode, lanes);
- coerceRef(current2, element);
- current2.return = returnFiber;
- current2._debugInfo = currentDebugInfo;
- return current2;
- }
- function updatePortal(returnFiber, current2, portal, lanes) {
- if (current2 === null || current2.tag !== 4 || current2.stateNode.containerInfo !== portal.containerInfo || current2.stateNode.implementation !== portal.implementation)
- return current2 = createFiberFromPortal(portal, returnFiber.mode, lanes), current2.return = returnFiber, current2._debugInfo = currentDebugInfo, current2;
- current2 = useFiber(current2, portal.children || []);
- current2.return = returnFiber;
- current2._debugInfo = currentDebugInfo;
- return current2;
- }
- function updateFragment(returnFiber, current2, fragment, lanes, key) {
- if (current2 === null || current2.tag !== 7)
- return current2 = createFiberFromFragment(fragment, returnFiber.mode, lanes, key), current2.return = returnFiber, current2._debugOwner = returnFiber, current2._debugInfo = currentDebugInfo, current2;
- current2 = useFiber(current2, fragment);
- current2.return = returnFiber;
- current2._debugInfo = currentDebugInfo;
- return current2;
- }
- function createChild(returnFiber, newChild, lanes) {
- if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number" || typeof newChild === "bigint")
- return newChild = createFiberFromText("" + newChild, returnFiber.mode, lanes), newChild.return = returnFiber, newChild._debugOwner = returnFiber, newChild._debugInfo = currentDebugInfo, newChild;
- if (typeof newChild === "object" && newChild !== null) {
- switch (newChild.$$typeof) {
- case REACT_ELEMENT_TYPE:
- return lanes = createFiberFromElement(newChild, returnFiber.mode, lanes), coerceRef(lanes, newChild), lanes.return = returnFiber, returnFiber = pushDebugInfo(newChild._debugInfo), lanes._debugInfo = currentDebugInfo, currentDebugInfo = returnFiber, lanes;
- case REACT_PORTAL_TYPE:
- return newChild = createFiberFromPortal(newChild, returnFiber.mode, lanes), newChild.return = returnFiber, newChild._debugInfo = currentDebugInfo, newChild;
- case REACT_LAZY_TYPE:
- var _prevDebugInfo = pushDebugInfo(newChild._debugInfo);
- newChild = callLazyInitInDEV(newChild);
- returnFiber = createChild(returnFiber, newChild, lanes);
- currentDebugInfo = _prevDebugInfo;
- return returnFiber;
- }
- if (isArrayImpl(newChild) || getIteratorFn(newChild))
- return lanes = createFiberFromFragment(newChild, returnFiber.mode, lanes, null), lanes.return = returnFiber, lanes._debugOwner = returnFiber, returnFiber = pushDebugInfo(newChild._debugInfo), lanes._debugInfo = currentDebugInfo, currentDebugInfo = returnFiber, lanes;
- if (typeof newChild.then === "function")
- return _prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = createChild(returnFiber, unwrapThenable(newChild), lanes), currentDebugInfo = _prevDebugInfo, returnFiber;
- if (newChild.$$typeof === REACT_CONTEXT_TYPE)
- return createChild(returnFiber, readContextDuringReconciliation(returnFiber, newChild), lanes);
- throwOnInvalidObjectType(returnFiber, newChild);
- }
- typeof newChild === "function" && warnOnFunctionType(returnFiber, newChild);
- typeof newChild === "symbol" && warnOnSymbolType(returnFiber, newChild);
- return null;
- }
- function updateSlot(returnFiber, oldFiber, newChild, lanes) {
- var key = oldFiber !== null ? oldFiber.key : null;
- if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number" || typeof newChild === "bigint")
- return key !== null ? null : updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
- if (typeof newChild === "object" && newChild !== null) {
- switch (newChild.$$typeof) {
- case REACT_ELEMENT_TYPE:
- return newChild.key === key ? (key = pushDebugInfo(newChild._debugInfo), returnFiber = updateElement(returnFiber, oldFiber, newChild, lanes), currentDebugInfo = key, returnFiber) : null;
- case REACT_PORTAL_TYPE:
- return newChild.key === key ? updatePortal(returnFiber, oldFiber, newChild, lanes) : null;
- case REACT_LAZY_TYPE:
- return key = pushDebugInfo(newChild._debugInfo), newChild = callLazyInitInDEV(newChild), returnFiber = updateSlot(returnFiber, oldFiber, newChild, lanes), currentDebugInfo = key, returnFiber;
- }
- if (isArrayImpl(newChild) || getIteratorFn(newChild)) {
- if (key !== null)
- return null;
- key = pushDebugInfo(newChild._debugInfo);
- returnFiber = updateFragment(returnFiber, oldFiber, newChild, lanes, null);
- currentDebugInfo = key;
- return returnFiber;
- }
- if (typeof newChild.then === "function")
- return key = pushDebugInfo(newChild._debugInfo), returnFiber = updateSlot(returnFiber, oldFiber, unwrapThenable(newChild), lanes), currentDebugInfo = key, returnFiber;
- if (newChild.$$typeof === REACT_CONTEXT_TYPE)
- return updateSlot(returnFiber, oldFiber, readContextDuringReconciliation(returnFiber, newChild), lanes);
- throwOnInvalidObjectType(returnFiber, newChild);
- }
- typeof newChild === "function" && warnOnFunctionType(returnFiber, newChild);
- typeof newChild === "symbol" && warnOnSymbolType(returnFiber, newChild);
- return null;
- }
- function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
- if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number" || typeof newChild === "bigint")
- return existingChildren = existingChildren.get(newIdx) || null, updateTextNode(returnFiber, existingChildren, "" + newChild, lanes);
- if (typeof newChild === "object" && newChild !== null) {
- switch (newChild.$$typeof) {
- case REACT_ELEMENT_TYPE:
- return newIdx = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null, existingChildren = pushDebugInfo(newChild._debugInfo), returnFiber = updateElement(returnFiber, newIdx, newChild, lanes), currentDebugInfo = existingChildren, returnFiber;
- case REACT_PORTAL_TYPE:
- return existingChildren = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null, updatePortal(returnFiber, existingChildren, newChild, lanes);
- case REACT_LAZY_TYPE:
- var _prevDebugInfo7 = pushDebugInfo(newChild._debugInfo);
- newChild = callLazyInitInDEV(newChild);
- returnFiber = updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes);
- currentDebugInfo = _prevDebugInfo7;
- return returnFiber;
- }
- if (isArrayImpl(newChild) || getIteratorFn(newChild))
- return newIdx = existingChildren.get(newIdx) || null, existingChildren = pushDebugInfo(newChild._debugInfo), returnFiber = updateFragment(returnFiber, newIdx, newChild, lanes, null), currentDebugInfo = existingChildren, returnFiber;
- if (typeof newChild.then === "function")
- return _prevDebugInfo7 = pushDebugInfo(newChild._debugInfo), returnFiber = updateFromMap(existingChildren, returnFiber, newIdx, unwrapThenable(newChild), lanes), currentDebugInfo = _prevDebugInfo7, returnFiber;
- if (newChild.$$typeof === REACT_CONTEXT_TYPE)
- return updateFromMap(existingChildren, returnFiber, newIdx, readContextDuringReconciliation(returnFiber, newChild), lanes);
- throwOnInvalidObjectType(returnFiber, newChild);
- }
- typeof newChild === "function" && warnOnFunctionType(returnFiber, newChild);
- typeof newChild === "symbol" && warnOnSymbolType(returnFiber, newChild);
- return null;
- }
- function warnOnInvalidKey(returnFiber, workInProgress2, child, knownKeys) {
- if (typeof child !== "object" || child === null)
- return knownKeys;
- switch (child.$$typeof) {
- case REACT_ELEMENT_TYPE:
- case REACT_PORTAL_TYPE:
- warnForMissingKey(returnFiber, workInProgress2, child);
- var key = child.key;
- if (typeof key !== "string")
- break;
- if (knownKeys === null) {
- knownKeys = new Set;
- knownKeys.add(key);
- break;
- }
- if (!knownKeys.has(key)) {
- knownKeys.add(key);
- break;
- }
- runWithFiberInDEV(workInProgress2, function() {
- console.error("Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted \u2014 the behavior is unsupported and could change in a future version.", key);
- });
- break;
- case REACT_LAZY_TYPE:
- child = callLazyInitInDEV(child), warnOnInvalidKey(returnFiber, workInProgress2, child, knownKeys);
- }
- return knownKeys;
- }
- function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
- for (var knownKeys = null, resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null;oldFiber !== null && newIdx < newChildren.length; newIdx++) {
- oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
- var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes);
- if (newFiber === null) {
- oldFiber === null && (oldFiber = nextOldFiber);
- break;
- }
- knownKeys = warnOnInvalidKey(returnFiber, newFiber, newChildren[newIdx], knownKeys);
- shouldTrackSideEffects && oldFiber && newFiber.alternate === null && deleteChild(returnFiber, oldFiber);
- currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
- previousNewFiber === null ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
- previousNewFiber = newFiber;
- oldFiber = nextOldFiber;
- }
- if (newIdx === newChildren.length)
- return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
- if (oldFiber === null) {
- for (;newIdx < newChildren.length; newIdx++)
- oldFiber = createChild(returnFiber, newChildren[newIdx], lanes), oldFiber !== null && (knownKeys = warnOnInvalidKey(returnFiber, oldFiber, newChildren[newIdx], knownKeys), currentFirstChild = placeChild(oldFiber, currentFirstChild, newIdx), previousNewFiber === null ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
- isHydrating && pushTreeFork(returnFiber, newIdx);
- return resultingFirstChild;
- }
- for (oldFiber = mapRemainingChildren(oldFiber);newIdx < newChildren.length; newIdx++)
- nextOldFiber = updateFromMap(oldFiber, returnFiber, newIdx, newChildren[newIdx], lanes), nextOldFiber !== null && (knownKeys = warnOnInvalidKey(returnFiber, nextOldFiber, newChildren[newIdx], knownKeys), shouldTrackSideEffects && nextOldFiber.alternate !== null && oldFiber.delete(nextOldFiber.key === null ? newIdx : nextOldFiber.key), currentFirstChild = placeChild(nextOldFiber, currentFirstChild, newIdx), previousNewFiber === null ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
- shouldTrackSideEffects && oldFiber.forEach(function(child) {
- return deleteChild(returnFiber, child);
- });
- isHydrating && pushTreeFork(returnFiber, newIdx);
- return resultingFirstChild;
- }
- function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildren, lanes) {
- if (newChildren == null)
- throw Error("An iterable object provided no iterator.");
- for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null, knownKeys = null, step = newChildren.next();oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
- oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
- var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
- if (newFiber === null) {
- oldFiber === null && (oldFiber = nextOldFiber);
- break;
- }
- knownKeys = warnOnInvalidKey(returnFiber, newFiber, step.value, knownKeys);
- shouldTrackSideEffects && oldFiber && newFiber.alternate === null && deleteChild(returnFiber, oldFiber);
- currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
- previousNewFiber === null ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
- previousNewFiber = newFiber;
- oldFiber = nextOldFiber;
- }
- if (step.done)
- return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
- if (oldFiber === null) {
- for (;!step.done; newIdx++, step = newChildren.next())
- oldFiber = createChild(returnFiber, step.value, lanes), oldFiber !== null && (knownKeys = warnOnInvalidKey(returnFiber, oldFiber, step.value, knownKeys), currentFirstChild = placeChild(oldFiber, currentFirstChild, newIdx), previousNewFiber === null ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
- isHydrating && pushTreeFork(returnFiber, newIdx);
- return resultingFirstChild;
- }
- for (oldFiber = mapRemainingChildren(oldFiber);!step.done; newIdx++, step = newChildren.next())
- nextOldFiber = updateFromMap(oldFiber, returnFiber, newIdx, step.value, lanes), nextOldFiber !== null && (knownKeys = warnOnInvalidKey(returnFiber, nextOldFiber, step.value, knownKeys), shouldTrackSideEffects && nextOldFiber.alternate !== null && oldFiber.delete(nextOldFiber.key === null ? newIdx : nextOldFiber.key), currentFirstChild = placeChild(nextOldFiber, currentFirstChild, newIdx), previousNewFiber === null ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
- shouldTrackSideEffects && oldFiber.forEach(function(child) {
- return deleteChild(returnFiber, child);
- });
- isHydrating && pushTreeFork(returnFiber, newIdx);
- return resultingFirstChild;
- }
- function reconcileChildFibersImpl(returnFiber, currentFirstChild, newChild, lanes) {
- typeof newChild === "object" && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null && (validateFragmentProps(newChild, null, returnFiber), newChild = newChild.props.children);
- if (typeof newChild === "object" && newChild !== null) {
- switch (newChild.$$typeof) {
- case REACT_ELEMENT_TYPE:
- var prevDebugInfo = pushDebugInfo(newChild._debugInfo);
- a: {
- for (var key = newChild.key;currentFirstChild !== null; ) {
- if (currentFirstChild.key === key) {
- key = newChild.type;
- if (key === REACT_FRAGMENT_TYPE) {
- if (currentFirstChild.tag === 7) {
- deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
- lanes = useFiber(currentFirstChild, newChild.props.children);
- lanes.return = returnFiber;
- lanes._debugOwner = newChild._owner;
- lanes._debugInfo = currentDebugInfo;
- validateFragmentProps(newChild, lanes, returnFiber);
- returnFiber = lanes;
- break a;
- }
- } else if (currentFirstChild.elementType === key || isCompatibleFamilyForHotReloading(currentFirstChild, newChild) || typeof key === "object" && key !== null && key.$$typeof === REACT_LAZY_TYPE && callLazyInitInDEV(key) === currentFirstChild.type) {
- deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
- lanes = useFiber(currentFirstChild, newChild.props);
- coerceRef(lanes, newChild);
- lanes.return = returnFiber;
- lanes._debugOwner = newChild._owner;
- lanes._debugInfo = currentDebugInfo;
- returnFiber = lanes;
- break a;
- }
- deleteRemainingChildren(returnFiber, currentFirstChild);
- break;
- } else
- deleteChild(returnFiber, currentFirstChild);
- currentFirstChild = currentFirstChild.sibling;
- }
- newChild.type === REACT_FRAGMENT_TYPE ? (lanes = createFiberFromFragment(newChild.props.children, returnFiber.mode, lanes, newChild.key), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugInfo = currentDebugInfo, validateFragmentProps(newChild, lanes, returnFiber), returnFiber = lanes) : (lanes = createFiberFromElement(newChild, returnFiber.mode, lanes), coerceRef(lanes, newChild), lanes.return = returnFiber, lanes._debugInfo = currentDebugInfo, returnFiber = lanes);
- }
- returnFiber = placeSingleChild(returnFiber);
- currentDebugInfo = prevDebugInfo;
- return returnFiber;
- case REACT_PORTAL_TYPE:
- a: {
- prevDebugInfo = newChild;
- for (newChild = prevDebugInfo.key;currentFirstChild !== null; ) {
- if (currentFirstChild.key === newChild)
- if (currentFirstChild.tag === 4 && currentFirstChild.stateNode.containerInfo === prevDebugInfo.containerInfo && currentFirstChild.stateNode.implementation === prevDebugInfo.implementation) {
- deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
- lanes = useFiber(currentFirstChild, prevDebugInfo.children || []);
- lanes.return = returnFiber;
- returnFiber = lanes;
- break a;
- } else {
- deleteRemainingChildren(returnFiber, currentFirstChild);
- break;
- }
- else
- deleteChild(returnFiber, currentFirstChild);
- currentFirstChild = currentFirstChild.sibling;
- }
- lanes = createFiberFromPortal(prevDebugInfo, returnFiber.mode, lanes);
- lanes.return = returnFiber;
- returnFiber = lanes;
- }
- return placeSingleChild(returnFiber);
- case REACT_LAZY_TYPE:
- return prevDebugInfo = pushDebugInfo(newChild._debugInfo), newChild = callLazyInitInDEV(newChild), returnFiber = reconcileChildFibersImpl(returnFiber, currentFirstChild, newChild, lanes), currentDebugInfo = prevDebugInfo, returnFiber;
- }
- if (isArrayImpl(newChild))
- return prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes), currentDebugInfo = prevDebugInfo, returnFiber;
- if (getIteratorFn(newChild)) {
- prevDebugInfo = pushDebugInfo(newChild._debugInfo);
- key = getIteratorFn(newChild);
- if (typeof key !== "function")
- throw Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.");
- var newChildren = key.call(newChild);
- if (newChildren === newChild) {
- if (returnFiber.tag !== 0 || Object.prototype.toString.call(returnFiber.type) !== "[object GeneratorFunction]" || Object.prototype.toString.call(newChildren) !== "[object Generator]")
- didWarnAboutGenerators || console.error("Using Iterators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. You can also use an Iterable that can iterate multiple times over the same items."), didWarnAboutGenerators = true;
- } else
- newChild.entries !== key || didWarnAboutMaps || (console.error("Using Maps as children is not supported. Use an array of keyed ReactElements instead."), didWarnAboutMaps = true);
- returnFiber = reconcileChildrenIterator(returnFiber, currentFirstChild, newChildren, lanes);
- currentDebugInfo = prevDebugInfo;
- return returnFiber;
- }
- if (typeof newChild.then === "function")
- return prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = reconcileChildFibersImpl(returnFiber, currentFirstChild, unwrapThenable(newChild), lanes), currentDebugInfo = prevDebugInfo, returnFiber;
- if (newChild.$$typeof === REACT_CONTEXT_TYPE)
- return reconcileChildFibersImpl(returnFiber, currentFirstChild, readContextDuringReconciliation(returnFiber, newChild), lanes);
- throwOnInvalidObjectType(returnFiber, newChild);
- }
- if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number" || typeof newChild === "bigint")
- return prevDebugInfo = "" + newChild, currentFirstChild !== null && currentFirstChild.tag === 6 ? (deleteRemainingChildren(returnFiber, currentFirstChild.sibling), lanes = useFiber(currentFirstChild, prevDebugInfo), lanes.return = returnFiber, returnFiber = lanes) : (deleteRemainingChildren(returnFiber, currentFirstChild), lanes = createFiberFromText(prevDebugInfo, returnFiber.mode, lanes), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugInfo = currentDebugInfo, returnFiber = lanes), placeSingleChild(returnFiber);
- typeof newChild === "function" && warnOnFunctionType(returnFiber, newChild);
- typeof newChild === "symbol" && warnOnSymbolType(returnFiber, newChild);
- return deleteRemainingChildren(returnFiber, currentFirstChild);
- }
- return function(returnFiber, currentFirstChild, newChild, lanes) {
- var prevDebugInfo = currentDebugInfo;
- currentDebugInfo = null;
- try {
- thenableIndexCounter$1 = 0;
- var firstChildFiber = reconcileChildFibersImpl(returnFiber, currentFirstChild, newChild, lanes);
- thenableState$1 = null;
- return firstChildFiber;
- } catch (x3) {
- if (x3 === SuspenseException)
- throw x3;
- var fiber = createFiber(29, x3, null, returnFiber.mode);
- fiber.lanes = lanes;
- fiber.return = returnFiber;
- var debugInfo = fiber._debugInfo = currentDebugInfo;
- fiber._debugOwner = returnFiber._debugOwner;
- if (debugInfo != null) {
- for (var i5 = debugInfo.length - 1;0 <= i5; i5--)
- if (typeof debugInfo[i5].stack === "string") {
- fiber._debugOwner = debugInfo[i5];
- break;
- }
- }
- return fiber;
- } finally {
- currentDebugInfo = prevDebugInfo;
- }
- };
- }
- function pushHiddenContext(fiber, context4) {
- var prevEntangledRenderLanes = entangledRenderLanes;
- push(prevEntangledRenderLanesCursor, prevEntangledRenderLanes, fiber);
- push(currentTreeHiddenStackCursor, context4, fiber);
- entangledRenderLanes = prevEntangledRenderLanes | context4.baseLanes;
- }
- function reuseHiddenContextOnStack(fiber) {
- push(prevEntangledRenderLanesCursor, entangledRenderLanes, fiber);
- push(currentTreeHiddenStackCursor, currentTreeHiddenStackCursor.current, fiber);
- }
- function popHiddenContext(fiber) {
- entangledRenderLanes = prevEntangledRenderLanesCursor.current;
- pop(currentTreeHiddenStackCursor, fiber);
- pop(prevEntangledRenderLanesCursor, fiber);
- }
- function pushPrimaryTreeSuspenseHandler(handler) {
- var current2 = handler.alternate;
- push(suspenseStackCursor, suspenseStackCursor.current & SubtreeSuspenseContextMask, handler);
- push(suspenseHandlerStackCursor, handler, handler);
- shellBoundary === null && (current2 === null || currentTreeHiddenStackCursor.current !== null ? shellBoundary = handler : current2.memoizedState !== null && (shellBoundary = handler));
- }
- function pushOffscreenSuspenseHandler(fiber) {
- if (fiber.tag === 22) {
- if (push(suspenseStackCursor, suspenseStackCursor.current, fiber), push(suspenseHandlerStackCursor, fiber, fiber), shellBoundary === null) {
- var current2 = fiber.alternate;
- current2 !== null && current2.memoizedState !== null && (shellBoundary = fiber);
- }
- } else
- reuseSuspenseHandlerOnStack(fiber);
- }
- function reuseSuspenseHandlerOnStack(fiber) {
- push(suspenseStackCursor, suspenseStackCursor.current, fiber);
- push(suspenseHandlerStackCursor, suspenseHandlerStackCursor.current, fiber);
- }
- function popSuspenseHandler(fiber) {
- pop(suspenseHandlerStackCursor, fiber);
- shellBoundary === fiber && (shellBoundary = null);
- pop(suspenseStackCursor, fiber);
- }
- function findFirstSuspended(row) {
- for (var node = row;node !== null; ) {
- if (node.tag === 13) {
- var state3 = node.memoizedState;
- if (state3 !== null && (state3 = state3.dehydrated, state3 === null || isSuspenseInstancePending(state3) || isSuspenseInstanceFallback(state3)))
- return node;
- } else if (node.tag === 19 && node.memoizedProps.revealOrder !== undefined) {
- if ((node.flags & 128) !== 0)
- return node;
- } else if (node.child !== null) {
- node.child.return = node;
- node = node.child;
- continue;
- }
- if (node === row)
- break;
- for (;node.sibling === null; ) {
- if (node.return === null || node.return === row)
- return null;
- node = node.return;
- }
- node.sibling.return = node.return;
- node = node.sibling;
- }
- return null;
- }
- function mountHookTypesDev() {
- var hookName = currentHookNameInDev;
- hookTypesDev === null ? hookTypesDev = [hookName] : hookTypesDev.push(hookName);
- }
- function updateHookTypesDev() {
- var hookName = currentHookNameInDev;
- if (hookTypesDev !== null && (hookTypesUpdateIndexDev++, hookTypesDev[hookTypesUpdateIndexDev] !== hookName)) {
- var componentName2 = getComponentNameFromFiber(currentlyRenderingFiber$1);
- if (!didWarnAboutMismatchedHooksForComponent.has(componentName2) && (didWarnAboutMismatchedHooksForComponent.add(componentName2), hookTypesDev !== null)) {
- for (var table = "", i5 = 0;i5 <= hookTypesUpdateIndexDev; i5++) {
- var oldHookName = hookTypesDev[i5], newHookName = i5 === hookTypesUpdateIndexDev ? hookName : oldHookName;
- for (oldHookName = i5 + 1 + ". " + oldHookName;30 > oldHookName.length; )
- oldHookName += " ";
- oldHookName += newHookName + `
-`;
- table += oldHookName;
- }
- console.error(`React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks
-
- Previous render Next render
- ------------------------------------------------------
-%s ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-`, componentName2, table);
- }
- }
- }
- function checkDepsAreArrayDev(deps) {
- deps === undefined || deps === null || isArrayImpl(deps) || console.error("%s received a final argument that is not an array (instead, received `%s`). When specified, the final argument must be an array.", currentHookNameInDev, typeof deps);
- }
- function warnOnUseFormStateInDev() {
- var componentName2 = getComponentNameFromFiber(currentlyRenderingFiber$1);
- didWarnAboutUseFormState.has(componentName2) || (didWarnAboutUseFormState.add(componentName2), console.error("ReactDOM.useFormState has been renamed to React.useActionState. Please update %s to use React.useActionState.", componentName2));
- }
- function throwInvalidHookError() {
- throw Error(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
-1. You might have mismatching versions of React and the renderer (such as React DOM)
-2. You might be breaking the Rules of Hooks
-3. You might have more than one copy of React in the same app
-See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`);
- }
- function areHookInputsEqual(nextDeps, prevDeps) {
- if (ignorePreviousDependencies)
- return false;
- if (prevDeps === null)
- return console.error("%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.", currentHookNameInDev), false;
- nextDeps.length !== prevDeps.length && console.error(`The final argument passed to %s changed size between renders. The order and size of this array must remain constant.
-
-Previous: %s
-Incoming: %s`, currentHookNameInDev, "[" + prevDeps.join(", ") + "]", "[" + nextDeps.join(", ") + "]");
- for (var i5 = 0;i5 < prevDeps.length && i5 < nextDeps.length; i5++)
- if (!objectIs(nextDeps[i5], prevDeps[i5]))
- return false;
- return true;
- }
- function renderWithHooks(current2, workInProgress2, Component, props, secondArg, nextRenderLanes) {
- renderLanes = nextRenderLanes;
- currentlyRenderingFiber$1 = workInProgress2;
- hookTypesDev = current2 !== null ? current2._debugHookTypes : null;
- hookTypesUpdateIndexDev = -1;
- ignorePreviousDependencies = current2 !== null && current2.type !== workInProgress2.type;
- if (Object.prototype.toString.call(Component) === "[object AsyncFunction]" || Object.prototype.toString.call(Component) === "[object AsyncGeneratorFunction]")
- nextRenderLanes = getComponentNameFromFiber(currentlyRenderingFiber$1), didWarnAboutAsyncClientComponent.has(nextRenderLanes) || (didWarnAboutAsyncClientComponent.add(nextRenderLanes), console.error("async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server."));
- workInProgress2.memoizedState = null;
- workInProgress2.updateQueue = null;
- workInProgress2.lanes = 0;
- ReactSharedInternals.H = current2 !== null && current2.memoizedState !== null ? HooksDispatcherOnUpdateInDEV : hookTypesDev !== null ? HooksDispatcherOnMountWithHookTypesInDEV : HooksDispatcherOnMountInDEV;
- shouldDoubleInvokeUserFnsInHooksDEV = nextRenderLanes = (workInProgress2.mode & 8) !== NoMode;
- var children = callComponentInDEV(Component, props, secondArg);
- shouldDoubleInvokeUserFnsInHooksDEV = false;
- didScheduleRenderPhaseUpdateDuringThisPass && (children = renderWithHooksAgain(workInProgress2, Component, props, secondArg));
- if (nextRenderLanes) {
- setIsStrictModeForDevtools(true);
- try {
- children = renderWithHooksAgain(workInProgress2, Component, props, secondArg);
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- finishRenderingHooks(current2, workInProgress2);
- return children;
- }
- function finishRenderingHooks(current2, workInProgress2) {
- workInProgress2._debugHookTypes = hookTypesDev;
- workInProgress2.dependencies === null ? thenableState !== null && (workInProgress2.dependencies = {
- lanes: 0,
- firstContext: null,
- _debugThenableState: thenableState
- }) : workInProgress2.dependencies._debugThenableState = thenableState;
- ReactSharedInternals.H = ContextOnlyDispatcher;
- var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
- renderLanes = 0;
- hookTypesDev = currentHookNameInDev = workInProgressHook = currentHook = currentlyRenderingFiber$1 = null;
- hookTypesUpdateIndexDev = -1;
- current2 !== null && (current2.flags & 31457280) !== (workInProgress2.flags & 31457280) && console.error("Internal React error: Expected static flag was missing. Please notify the React team.");
- didScheduleRenderPhaseUpdate = false;
- thenableIndexCounter = 0;
- thenableState = null;
- if (didRenderTooFewHooks)
- throw Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement.");
- current2 === null || didReceiveUpdate || (current2 = current2.dependencies, current2 !== null && checkIfContextChanged(current2) && (didReceiveUpdate = true));
- needsToResetSuspendedThenableDEV ? (needsToResetSuspendedThenableDEV = false, current2 = true) : current2 = false;
- current2 && (workInProgress2 = getComponentNameFromFiber(workInProgress2) || "Unknown", didWarnAboutUseWrappedInTryCatch.has(workInProgress2) || didWarnAboutAsyncClientComponent.has(workInProgress2) || (didWarnAboutUseWrappedInTryCatch.add(workInProgress2), console.error("`use` was called from inside a try/catch block. This is not allowed and can lead to unexpected behavior. To handle errors triggered by `use`, wrap your component in a error boundary.")));
- }
- function renderWithHooksAgain(workInProgress2, Component, props, secondArg) {
- currentlyRenderingFiber$1 = workInProgress2;
- var numberOfReRenders = 0;
- do {
- didScheduleRenderPhaseUpdateDuringThisPass && (thenableState = null);
- thenableIndexCounter = 0;
- didScheduleRenderPhaseUpdateDuringThisPass = false;
- if (numberOfReRenders >= RE_RENDER_LIMIT)
- throw Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");
- numberOfReRenders += 1;
- ignorePreviousDependencies = false;
- workInProgressHook = currentHook = null;
- if (workInProgress2.updateQueue != null) {
- var children = workInProgress2.updateQueue;
- children.lastEffect = null;
- children.events = null;
- children.stores = null;
- children.memoCache != null && (children.memoCache.index = 0);
- }
- hookTypesUpdateIndexDev = -1;
- ReactSharedInternals.H = HooksDispatcherOnRerenderInDEV;
- children = callComponentInDEV(Component, props, secondArg);
- } while (didScheduleRenderPhaseUpdateDuringThisPass);
- return children;
- }
- function TransitionAwareHostComponent() {
- var dispatcher = ReactSharedInternals.H, maybeThenable = dispatcher.useState()[0];
- maybeThenable = typeof maybeThenable.then === "function" ? useThenable(maybeThenable) : maybeThenable;
- dispatcher = dispatcher.useState()[0];
- (currentHook !== null ? currentHook.memoizedState : null) !== dispatcher && (currentlyRenderingFiber$1.flags |= 1024);
- return maybeThenable;
- }
- function checkDidRenderIdHook() {
- var didRenderIdHook = localIdCounter !== 0;
- localIdCounter = 0;
- return didRenderIdHook;
- }
- function bailoutHooks(current2, workInProgress2, lanes) {
- workInProgress2.updateQueue = current2.updateQueue;
- workInProgress2.flags = (workInProgress2.mode & 16) !== NoMode ? workInProgress2.flags & -201328645 : workInProgress2.flags & -2053;
- current2.lanes &= ~lanes;
- }
- function resetHooksOnUnwind(workInProgress2) {
- if (didScheduleRenderPhaseUpdate) {
- for (workInProgress2 = workInProgress2.memoizedState;workInProgress2 !== null; ) {
- var queue = workInProgress2.queue;
- queue !== null && (queue.pending = null);
- workInProgress2 = workInProgress2.next;
- }
- didScheduleRenderPhaseUpdate = false;
- }
- renderLanes = 0;
- hookTypesDev = workInProgressHook = currentHook = currentlyRenderingFiber$1 = null;
- hookTypesUpdateIndexDev = -1;
- currentHookNameInDev = null;
- didScheduleRenderPhaseUpdateDuringThisPass = false;
- thenableIndexCounter = localIdCounter = 0;
- thenableState = null;
- }
- function mountWorkInProgressHook() {
- var hook = {
- memoizedState: null,
- baseState: null,
- baseQueue: null,
- queue: null,
- next: null
- };
- workInProgressHook === null ? currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook : workInProgressHook = workInProgressHook.next = hook;
- return workInProgressHook;
- }
- function updateWorkInProgressHook() {
- if (currentHook === null) {
- var nextCurrentHook = currentlyRenderingFiber$1.alternate;
- nextCurrentHook = nextCurrentHook !== null ? nextCurrentHook.memoizedState : null;
- } else
- nextCurrentHook = currentHook.next;
- var nextWorkInProgressHook = workInProgressHook === null ? currentlyRenderingFiber$1.memoizedState : workInProgressHook.next;
- if (nextWorkInProgressHook !== null)
- workInProgressHook = nextWorkInProgressHook, currentHook = nextCurrentHook;
- else {
- if (nextCurrentHook === null) {
- if (currentlyRenderingFiber$1.alternate === null)
- throw Error("Update hook called on initial render. This is likely a bug in React. Please file an issue.");
- throw Error("Rendered more hooks than during the previous render.");
- }
- currentHook = nextCurrentHook;
- nextCurrentHook = {
- memoizedState: currentHook.memoizedState,
- baseState: currentHook.baseState,
- baseQueue: currentHook.baseQueue,
- queue: currentHook.queue,
- next: null
- };
- workInProgressHook === null ? currentlyRenderingFiber$1.memoizedState = workInProgressHook = nextCurrentHook : workInProgressHook = workInProgressHook.next = nextCurrentHook;
- }
- return workInProgressHook;
- }
- function useThenable(thenable) {
- var index2 = thenableIndexCounter;
- thenableIndexCounter += 1;
- thenableState === null && (thenableState = createThenableState());
- thenable = trackUsedThenable(thenableState, thenable, index2);
- index2 = currentlyRenderingFiber$1;
- (workInProgressHook === null ? index2.memoizedState : workInProgressHook.next) === null && (index2 = index2.alternate, ReactSharedInternals.H = index2 !== null && index2.memoizedState !== null ? HooksDispatcherOnUpdateInDEV : HooksDispatcherOnMountInDEV);
- return thenable;
- }
- function use2(usable) {
- if (usable !== null && typeof usable === "object") {
- if (typeof usable.then === "function")
- return useThenable(usable);
- if (usable.$$typeof === REACT_CONTEXT_TYPE)
- return readContext(usable);
- }
- throw Error("An unsupported type was passed to use(): " + String(usable));
- }
- function useMemoCache(size) {
- var memoCache = null, updateQueue = currentlyRenderingFiber$1.updateQueue;
- updateQueue !== null && (memoCache = updateQueue.memoCache);
- if (memoCache == null) {
- var current2 = currentlyRenderingFiber$1.alternate;
- current2 !== null && (current2 = current2.updateQueue, current2 !== null && (current2 = current2.memoCache, current2 != null && (memoCache = {
- data: current2.data.map(function(array2) {
- return array2.slice();
- }),
- index: 0
- })));
- }
- memoCache == null && (memoCache = { data: [], index: 0 });
- updateQueue === null && (updateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber$1.updateQueue = updateQueue);
- updateQueue.memoCache = memoCache;
- updateQueue = memoCache.data[memoCache.index];
- if (updateQueue === undefined || ignorePreviousDependencies)
- for (updateQueue = memoCache.data[memoCache.index] = Array(size), current2 = 0;current2 < size; current2++)
- updateQueue[current2] = REACT_MEMO_CACHE_SENTINEL;
- else
- updateQueue.length !== size && console.error("Expected a constant size argument for each invocation of useMemoCache. The previous cache was allocated with size %s but size %s was requested.", updateQueue.length, size);
- memoCache.index++;
- return updateQueue;
- }
- function basicStateReducer(state3, action) {
- return typeof action === "function" ? action(state3) : action;
- }
- function mountReducer(reducer, initialArg, init) {
- var hook = mountWorkInProgressHook();
- if (init !== undefined) {
- var initialState = init(initialArg);
- if (shouldDoubleInvokeUserFnsInHooksDEV) {
- setIsStrictModeForDevtools(true);
- try {
- init(initialArg);
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- } else
- initialState = initialArg;
- hook.memoizedState = hook.baseState = initialState;
- reducer = {
- pending: null,
- lanes: 0,
- dispatch: null,
- lastRenderedReducer: reducer,
- lastRenderedState: initialState
- };
- hook.queue = reducer;
- reducer = reducer.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, reducer);
- return [hook.memoizedState, reducer];
- }
- function updateReducer(reducer) {
- var hook = updateWorkInProgressHook();
- return updateReducerImpl(hook, currentHook, reducer);
- }
- function updateReducerImpl(hook, current2, reducer) {
- var queue = hook.queue;
- if (queue === null)
- throw Error("Should have a queue. You are likely calling Hooks conditionally, which is not allowed. (https://react.dev/link/invalid-hook-call)");
- queue.lastRenderedReducer = reducer;
- var baseQueue = hook.baseQueue, pendingQueue = queue.pending;
- if (pendingQueue !== null) {
- if (baseQueue !== null) {
- var baseFirst = baseQueue.next;
- baseQueue.next = pendingQueue.next;
- pendingQueue.next = baseFirst;
- }
- current2.baseQueue !== baseQueue && console.error("Internal error: Expected work-in-progress queue to be a clone. This is a bug in React.");
- current2.baseQueue = baseQueue = pendingQueue;
- queue.pending = null;
- }
- pendingQueue = hook.baseState;
- if (baseQueue === null)
- hook.memoizedState = pendingQueue;
- else {
- current2 = baseQueue.next;
- var newBaseQueueFirst = baseFirst = null, newBaseQueueLast = null, update = current2, didReadFromEntangledAsyncAction2 = false;
- do {
- var updateLane = update.lane & -536870913;
- if (updateLane !== update.lane ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes & updateLane) === updateLane) {
- var revertLane = update.revertLane;
- if (revertLane === 0)
- newBaseQueueLast !== null && (newBaseQueueLast = newBaseQueueLast.next = {
- lane: 0,
- revertLane: 0,
- action: update.action,
- hasEagerState: update.hasEagerState,
- eagerState: update.eagerState,
- next: null
- }), updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction2 = true);
- else if ((renderLanes & revertLane) === revertLane) {
- update = update.next;
- revertLane === currentEntangledLane && (didReadFromEntangledAsyncAction2 = true);
- continue;
- } else
- updateLane = {
- lane: 0,
- revertLane: update.revertLane,
- action: update.action,
- hasEagerState: update.hasEagerState,
- eagerState: update.eagerState,
- next: null
- }, newBaseQueueLast === null ? (newBaseQueueFirst = newBaseQueueLast = updateLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = updateLane, currentlyRenderingFiber$1.lanes |= revertLane, workInProgressRootSkippedLanes |= revertLane;
- updateLane = update.action;
- shouldDoubleInvokeUserFnsInHooksDEV && reducer(pendingQueue, updateLane);
- pendingQueue = update.hasEagerState ? update.eagerState : reducer(pendingQueue, updateLane);
- } else
- revertLane = {
- lane: updateLane,
- revertLane: update.revertLane,
- action: update.action,
- hasEagerState: update.hasEagerState,
- eagerState: update.eagerState,
- next: null
- }, newBaseQueueLast === null ? (newBaseQueueFirst = newBaseQueueLast = revertLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = revertLane, currentlyRenderingFiber$1.lanes |= updateLane, workInProgressRootSkippedLanes |= updateLane;
- update = update.next;
- } while (update !== null && update !== current2);
- newBaseQueueLast === null ? baseFirst = pendingQueue : newBaseQueueLast.next = newBaseQueueFirst;
- if (!objectIs(pendingQueue, hook.memoizedState) && (didReceiveUpdate = true, didReadFromEntangledAsyncAction2 && (reducer = currentEntangledActionThenable, reducer !== null)))
- throw reducer;
- hook.memoizedState = pendingQueue;
- hook.baseState = baseFirst;
- hook.baseQueue = newBaseQueueLast;
- queue.lastRenderedState = pendingQueue;
- }
- baseQueue === null && (queue.lanes = 0);
- return [hook.memoizedState, queue.dispatch];
- }
- function rerenderReducer(reducer) {
- var hook = updateWorkInProgressHook(), queue = hook.queue;
- if (queue === null)
- throw Error("Should have a queue. You are likely calling Hooks conditionally, which is not allowed. (https://react.dev/link/invalid-hook-call)");
- queue.lastRenderedReducer = reducer;
- var { dispatch, pending: lastRenderPhaseUpdate } = queue, newState = hook.memoizedState;
- if (lastRenderPhaseUpdate !== null) {
- queue.pending = null;
- var update = lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
- do
- newState = reducer(newState, update.action), update = update.next;
- while (update !== lastRenderPhaseUpdate);
- objectIs(newState, hook.memoizedState) || (didReceiveUpdate = true);
- hook.memoizedState = newState;
- hook.baseQueue === null && (hook.baseState = newState);
- queue.lastRenderedState = newState;
- }
- return [newState, dispatch];
- }
- function mountSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot) {
- var fiber = currentlyRenderingFiber$1, hook = mountWorkInProgressHook();
- if (isHydrating) {
- if (getServerSnapshot === undefined)
- throw Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.");
- var nextSnapshot = getServerSnapshot();
- didWarnUncachedGetSnapshot || nextSnapshot === getServerSnapshot() || (console.error("The result of getServerSnapshot should be cached to avoid an infinite loop"), didWarnUncachedGetSnapshot = true);
- } else {
- nextSnapshot = getSnapshot();
- didWarnUncachedGetSnapshot || (getServerSnapshot = getSnapshot(), objectIs(nextSnapshot, getServerSnapshot) || (console.error("The result of getSnapshot should be cached to avoid an infinite loop"), didWarnUncachedGetSnapshot = true));
- if (workInProgressRoot === null)
- throw Error("Expected a work-in-progress root. This is a bug in React. Please file an issue.");
- (workInProgressRootRenderLanes & 60) !== 0 || pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
- }
- hook.memoizedState = nextSnapshot;
- getServerSnapshot = { value: nextSnapshot, getSnapshot };
- hook.queue = getServerSnapshot;
- mountEffect(subscribeToStore.bind(null, fiber, getServerSnapshot, subscribe2), [subscribe2]);
- fiber.flags |= 2048;
- pushEffect(HasEffect | Passive, updateStoreInstance.bind(null, fiber, getServerSnapshot, nextSnapshot, getSnapshot), { destroy: undefined }, null);
- return nextSnapshot;
- }
- function updateSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot) {
- var fiber = currentlyRenderingFiber$1, hook = updateWorkInProgressHook(), isHydrating$jscomp$0 = isHydrating;
- if (isHydrating$jscomp$0) {
- if (getServerSnapshot === undefined)
- throw Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.");
- getServerSnapshot = getServerSnapshot();
- } else if (getServerSnapshot = getSnapshot(), !didWarnUncachedGetSnapshot) {
- var cachedSnapshot = getSnapshot();
- objectIs(getServerSnapshot, cachedSnapshot) || (console.error("The result of getSnapshot should be cached to avoid an infinite loop"), didWarnUncachedGetSnapshot = true);
- }
- if (cachedSnapshot = !objectIs((currentHook || hook).memoizedState, getServerSnapshot))
- hook.memoizedState = getServerSnapshot, didReceiveUpdate = true;
- hook = hook.queue;
- var create = subscribeToStore.bind(null, fiber, hook, subscribe2);
- updateEffectImpl(2048, Passive, create, [subscribe2]);
- if (hook.getSnapshot !== getSnapshot || cachedSnapshot || workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) {
- fiber.flags |= 2048;
- pushEffect(HasEffect | Passive, updateStoreInstance.bind(null, fiber, hook, getServerSnapshot, getSnapshot), { destroy: undefined }, null);
- if (workInProgressRoot === null)
- throw Error("Expected a work-in-progress root. This is a bug in React. Please file an issue.");
- isHydrating$jscomp$0 || (renderLanes & 60) !== 0 || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
- }
- return getServerSnapshot;
- }
- function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
- fiber.flags |= 16384;
- fiber = { getSnapshot, value: renderedSnapshot };
- getSnapshot = currentlyRenderingFiber$1.updateQueue;
- getSnapshot === null ? (getSnapshot = createFunctionComponentUpdateQueue(), currentlyRenderingFiber$1.updateQueue = getSnapshot, getSnapshot.stores = [fiber]) : (renderedSnapshot = getSnapshot.stores, renderedSnapshot === null ? getSnapshot.stores = [fiber] : renderedSnapshot.push(fiber));
- }
- function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
- inst.value = nextSnapshot;
- inst.getSnapshot = getSnapshot;
- checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
- }
- function subscribeToStore(fiber, inst, subscribe2) {
- return subscribe2(function() {
- checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
- });
- }
- function checkIfSnapshotChanged(inst) {
- var latestGetSnapshot = inst.getSnapshot;
- inst = inst.value;
- try {
- var nextValue = latestGetSnapshot();
- return !objectIs(inst, nextValue);
- } catch (error46) {
- return true;
- }
- }
- function forceStoreRerender(fiber) {
- var root2 = enqueueConcurrentRenderForLane(fiber, 2);
- root2 !== null && scheduleUpdateOnFiber(root2, fiber, 2);
- }
- function mountStateImpl(initialState) {
- var hook = mountWorkInProgressHook();
- if (typeof initialState === "function") {
- var initialStateInitializer = initialState;
- initialState = initialStateInitializer();
- if (shouldDoubleInvokeUserFnsInHooksDEV) {
- setIsStrictModeForDevtools(true);
- try {
- initialStateInitializer();
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- }
- hook.memoizedState = hook.baseState = initialState;
- hook.queue = {
- pending: null,
- lanes: 0,
- dispatch: null,
- lastRenderedReducer: basicStateReducer,
- lastRenderedState: initialState
- };
- return hook;
- }
- function mountState(initialState) {
- initialState = mountStateImpl(initialState);
- var queue = initialState.queue, dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue);
- queue.dispatch = dispatch;
- return [initialState.memoizedState, dispatch];
- }
- function mountOptimistic(passthrough) {
- var hook = mountWorkInProgressHook();
- hook.memoizedState = hook.baseState = passthrough;
- var queue = {
- pending: null,
- lanes: 0,
- dispatch: null,
- lastRenderedReducer: null,
- lastRenderedState: null
- };
- hook.queue = queue;
- hook = dispatchOptimisticSetState.bind(null, currentlyRenderingFiber$1, true, queue);
- queue.dispatch = hook;
- return [passthrough, hook];
- }
- function updateOptimistic(passthrough, reducer) {
- var hook = updateWorkInProgressHook();
- return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
- }
- function updateOptimisticImpl(hook, current2, passthrough, reducer) {
- hook.baseState = passthrough;
- return updateReducerImpl(hook, currentHook, typeof reducer === "function" ? reducer : basicStateReducer);
- }
- function rerenderOptimistic(passthrough, reducer) {
- var hook = updateWorkInProgressHook();
- if (currentHook !== null)
- return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
- hook.baseState = passthrough;
- return [passthrough, hook.queue.dispatch];
- }
- function dispatchActionState(fiber, actionQueue, setPendingState, setState, payload) {
- if (isRenderPhaseUpdate(fiber))
- throw Error("Cannot update form state while rendering.");
- fiber = actionQueue.action;
- if (fiber !== null) {
- var actionNode = {
- payload,
- action: fiber,
- next: null,
- isTransition: true,
- status: "pending",
- value: null,
- reason: null,
- listeners: [],
- then: function(listener) {
- actionNode.listeners.push(listener);
- }
- };
- ReactSharedInternals.T !== null ? setPendingState(true) : actionNode.isTransition = false;
- setState(actionNode);
- setPendingState = actionQueue.pending;
- setPendingState === null ? (actionNode.next = actionQueue.pending = actionNode, runActionStateAction(actionQueue, actionNode)) : (actionNode.next = setPendingState.next, actionQueue.pending = setPendingState.next = actionNode);
- }
- }
- function runActionStateAction(actionQueue, node) {
- var { action, payload } = node, prevState = actionQueue.state;
- if (node.isTransition) {
- var prevTransition = ReactSharedInternals.T, currentTransition = {};
- ReactSharedInternals.T = currentTransition;
- ReactSharedInternals.T._updatedFibers = new Set;
- try {
- var returnValue = action(prevState, payload), onStartTransitionFinish = ReactSharedInternals.S;
- onStartTransitionFinish !== null && onStartTransitionFinish(currentTransition, returnValue);
- handleActionReturnValue(actionQueue, node, returnValue);
- } catch (error46) {
- onActionError(actionQueue, node, error46);
- } finally {
- ReactSharedInternals.T = prevTransition, prevTransition === null && currentTransition._updatedFibers && (actionQueue = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < actionQueue && console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."));
- }
- } else
- try {
- currentTransition = action(prevState, payload), handleActionReturnValue(actionQueue, node, currentTransition);
- } catch (error$2) {
- onActionError(actionQueue, node, error$2);
- }
- }
- function handleActionReturnValue(actionQueue, node, returnValue) {
- returnValue !== null && typeof returnValue === "object" && typeof returnValue.then === "function" ? (returnValue.then(function(nextState) {
- onActionSuccess(actionQueue, node, nextState);
- }, function(error46) {
- return onActionError(actionQueue, node, error46);
- }), node.isTransition || console.error("An async function was passed to useActionState, but it was dispatched outside of an action context. This is likely not what you intended. Either pass the dispatch function to an `action` prop, or dispatch manually inside `startTransition`")) : onActionSuccess(actionQueue, node, returnValue);
- }
- function onActionSuccess(actionQueue, actionNode, nextState) {
- actionNode.status = "fulfilled";
- actionNode.value = nextState;
- notifyActionListeners(actionNode);
- actionQueue.state = nextState;
- actionNode = actionQueue.pending;
- actionNode !== null && (nextState = actionNode.next, nextState === actionNode ? actionQueue.pending = null : (nextState = nextState.next, actionNode.next = nextState, runActionStateAction(actionQueue, nextState)));
- }
- function onActionError(actionQueue, actionNode, error46) {
- var last = actionQueue.pending;
- actionQueue.pending = null;
- if (last !== null) {
- last = last.next;
- do
- actionNode.status = "rejected", actionNode.reason = error46, notifyActionListeners(actionNode), actionNode = actionNode.next;
- while (actionNode !== last);
- }
- actionQueue.action = null;
- }
- function notifyActionListeners(actionNode) {
- actionNode = actionNode.listeners;
- for (var i5 = 0;i5 < actionNode.length; i5++)
- (0, actionNode[i5])();
- }
- function actionStateReducer(oldState, newState) {
- return newState;
- }
- function mountActionState(action, initialStateProp) {
- if (isHydrating) {
- var ssrFormState = workInProgressRoot.formState;
- if (ssrFormState !== null) {
- a: {
- var isMatching = currentlyRenderingFiber$1;
- if (isHydrating) {
- if (nextHydratableInstance) {
- var markerInstance = canHydrateFormStateMarker(nextHydratableInstance, rootOrSingletonContext);
- if (markerInstance) {
- nextHydratableInstance = getNextHydratableSibling(markerInstance);
- isMatching = isFormStateMarkerMatching(markerInstance);
- break a;
- }
- }
- throwOnHydrationMismatch(isMatching);
- }
- isMatching = false;
- }
- isMatching && (initialStateProp = ssrFormState[0]);
- }
- }
- ssrFormState = mountWorkInProgressHook();
- ssrFormState.memoizedState = ssrFormState.baseState = initialStateProp;
- isMatching = {
- pending: null,
- lanes: 0,
- dispatch: null,
- lastRenderedReducer: actionStateReducer,
- lastRenderedState: initialStateProp
- };
- ssrFormState.queue = isMatching;
- ssrFormState = dispatchSetState.bind(null, currentlyRenderingFiber$1, isMatching);
- isMatching.dispatch = ssrFormState;
- isMatching = mountStateImpl(false);
- var setPendingState = dispatchOptimisticSetState.bind(null, currentlyRenderingFiber$1, false, isMatching.queue);
- isMatching = mountWorkInProgressHook();
- markerInstance = {
- state: initialStateProp,
- dispatch: null,
- action,
- pending: null
- };
- isMatching.queue = markerInstance;
- ssrFormState = dispatchActionState.bind(null, currentlyRenderingFiber$1, markerInstance, setPendingState, ssrFormState);
- markerInstance.dispatch = ssrFormState;
- isMatching.memoizedState = action;
- return [initialStateProp, ssrFormState, false];
- }
- function updateActionState(action) {
- var stateHook = updateWorkInProgressHook();
- return updateActionStateImpl(stateHook, currentHook, action);
- }
- function updateActionStateImpl(stateHook, currentStateHook, action) {
- currentStateHook = updateReducerImpl(stateHook, currentStateHook, actionStateReducer)[0];
- stateHook = updateReducer(basicStateReducer)[0];
- currentStateHook = typeof currentStateHook === "object" && currentStateHook !== null && typeof currentStateHook.then === "function" ? useThenable(currentStateHook) : currentStateHook;
- var actionQueueHook = updateWorkInProgressHook(), actionQueue = actionQueueHook.queue, dispatch = actionQueue.dispatch;
- action !== actionQueueHook.memoizedState && (currentlyRenderingFiber$1.flags |= 2048, pushEffect(HasEffect | Passive, actionStateActionEffect.bind(null, actionQueue, action), { destroy: undefined }, null));
- return [currentStateHook, dispatch, stateHook];
- }
- function actionStateActionEffect(actionQueue, action) {
- actionQueue.action = action;
- }
- function rerenderActionState(action) {
- var stateHook = updateWorkInProgressHook(), currentStateHook = currentHook;
- if (currentStateHook !== null)
- return updateActionStateImpl(stateHook, currentStateHook, action);
- updateWorkInProgressHook();
- stateHook = stateHook.memoizedState;
- currentStateHook = updateWorkInProgressHook();
- var dispatch = currentStateHook.queue.dispatch;
- currentStateHook.memoizedState = action;
- return [stateHook, dispatch, false];
- }
- function pushEffect(tag2, create, inst, deps) {
- tag2 = { tag: tag2, create, inst, deps, next: null };
- create = currentlyRenderingFiber$1.updateQueue;
- create === null && (create = createFunctionComponentUpdateQueue(), currentlyRenderingFiber$1.updateQueue = create);
- inst = create.lastEffect;
- inst === null ? create.lastEffect = tag2.next = tag2 : (deps = inst.next, inst.next = tag2, tag2.next = deps, create.lastEffect = tag2);
- return tag2;
- }
- function mountRef(initialValue) {
- var hook = mountWorkInProgressHook();
- initialValue = { current: initialValue };
- return hook.memoizedState = initialValue;
- }
- function mountEffectImpl(fiberFlags, hookFlags, create, deps) {
- var hook = mountWorkInProgressHook();
- currentlyRenderingFiber$1.flags |= fiberFlags;
- hook.memoizedState = pushEffect(HasEffect | hookFlags, create, { destroy: undefined }, deps === undefined ? null : deps);
- }
- function updateEffectImpl(fiberFlags, hookFlags, create, deps) {
- var hook = updateWorkInProgressHook();
- deps = deps === undefined ? null : deps;
- var inst = hook.memoizedState.inst;
- currentHook !== null && deps !== null && areHookInputsEqual(deps, currentHook.memoizedState.deps) ? hook.memoizedState = pushEffect(hookFlags, create, inst, deps) : (currentlyRenderingFiber$1.flags |= fiberFlags, hook.memoizedState = pushEffect(HasEffect | hookFlags, create, inst, deps));
- }
- function mountEffect(create, deps) {
- (currentlyRenderingFiber$1.mode & 16) !== NoMode && (currentlyRenderingFiber$1.mode & 64) === NoMode ? mountEffectImpl(142608384, Passive, create, deps) : mountEffectImpl(8390656, Passive, create, deps);
- }
- function mountLayoutEffect(create, deps) {
- var fiberFlags = 4194308;
- (currentlyRenderingFiber$1.mode & 16) !== NoMode && (fiberFlags |= 67108864);
- return mountEffectImpl(fiberFlags, Layout, create, deps);
- }
- function imperativeHandleEffect(create, ref) {
- if (typeof ref === "function") {
- create = create();
- var refCleanup = ref(create);
- return function() {
- typeof refCleanup === "function" ? refCleanup() : ref(null);
- };
- }
- if (ref !== null && ref !== undefined)
- return ref.hasOwnProperty("current") || console.error("Expected useImperativeHandle() first argument to either be a ref callback or React.createRef() object. Instead received: %s.", "an object with keys {" + Object.keys(ref).join(", ") + "}"), create = create(), ref.current = create, function() {
- ref.current = null;
- };
- }
- function mountImperativeHandle(ref, create, deps) {
- typeof create !== "function" && console.error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create !== null ? typeof create : "null");
- deps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
- var fiberFlags = 4194308;
- (currentlyRenderingFiber$1.mode & 16) !== NoMode && (fiberFlags |= 67108864);
- mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), deps);
- }
- function updateImperativeHandle(ref, create, deps) {
- typeof create !== "function" && console.error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create !== null ? typeof create : "null");
- deps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
- updateEffectImpl(4, Layout, imperativeHandleEffect.bind(null, create, ref), deps);
- }
- function mountCallback(callback, deps) {
- mountWorkInProgressHook().memoizedState = [
- callback,
- deps === undefined ? null : deps
- ];
- return callback;
- }
- function updateCallback(callback, deps) {
- var hook = updateWorkInProgressHook();
- deps = deps === undefined ? null : deps;
- var prevState = hook.memoizedState;
- if (deps !== null && areHookInputsEqual(deps, prevState[1]))
- return prevState[0];
- hook.memoizedState = [callback, deps];
- return callback;
- }
- function mountMemo(nextCreate, deps) {
- var hook = mountWorkInProgressHook();
- deps = deps === undefined ? null : deps;
- var nextValue = nextCreate();
- if (shouldDoubleInvokeUserFnsInHooksDEV) {
- setIsStrictModeForDevtools(true);
- try {
- nextCreate();
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- hook.memoizedState = [nextValue, deps];
- return nextValue;
- }
- function updateMemo(nextCreate, deps) {
- var hook = updateWorkInProgressHook();
- deps = deps === undefined ? null : deps;
- var prevState = hook.memoizedState;
- if (deps !== null && areHookInputsEqual(deps, prevState[1]))
- return prevState[0];
- prevState = nextCreate();
- if (shouldDoubleInvokeUserFnsInHooksDEV) {
- setIsStrictModeForDevtools(true);
- try {
- nextCreate();
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- hook.memoizedState = [prevState, deps];
- return prevState;
- }
- function mountDeferredValue(value, initialValue) {
- var hook = mountWorkInProgressHook();
- return mountDeferredValueImpl(hook, value, initialValue);
- }
- function updateDeferredValue(value, initialValue) {
- var hook = updateWorkInProgressHook();
- return updateDeferredValueImpl(hook, currentHook.memoizedState, value, initialValue);
- }
- function rerenderDeferredValue(value, initialValue) {
- var hook = updateWorkInProgressHook();
- return currentHook === null ? mountDeferredValueImpl(hook, value, initialValue) : updateDeferredValueImpl(hook, currentHook.memoizedState, value, initialValue);
- }
- function mountDeferredValueImpl(hook, value, initialValue) {
- if (initialValue === undefined || (renderLanes & 1073741824) !== 0)
- return hook.memoizedState = value;
- hook.memoizedState = initialValue;
- hook = requestDeferredLane();
- currentlyRenderingFiber$1.lanes |= hook;
- workInProgressRootSkippedLanes |= hook;
- return initialValue;
- }
- function updateDeferredValueImpl(hook, prevValue, value, initialValue) {
- if (objectIs(value, prevValue))
- return value;
- if (currentTreeHiddenStackCursor.current !== null)
- return hook = mountDeferredValueImpl(hook, value, initialValue), objectIs(hook, prevValue) || (didReceiveUpdate = true), hook;
- if ((renderLanes & 42) === 0)
- return didReceiveUpdate = true, hook.memoizedState = value;
- hook = requestDeferredLane();
- currentlyRenderingFiber$1.lanes |= hook;
- workInProgressRootSkippedLanes |= hook;
- return prevValue;
- }
- function startTransition(fiber, queue, pendingState, finishedState, callback) {
- var previousPriority = getCurrentUpdatePriority();
- setCurrentUpdatePriority(previousPriority !== 0 && 8 > previousPriority ? previousPriority : 8);
- var prevTransition = ReactSharedInternals.T, currentTransition = {};
- ReactSharedInternals.T = currentTransition;
- dispatchOptimisticSetState(fiber, false, queue, pendingState);
- currentTransition._updatedFibers = new Set;
- try {
- var returnValue = callback(), onStartTransitionFinish = ReactSharedInternals.S;
- onStartTransitionFinish !== null && onStartTransitionFinish(currentTransition, returnValue);
- if (returnValue !== null && typeof returnValue === "object" && typeof returnValue.then === "function") {
- var thenableForFinishedState = chainThenableValue(returnValue, finishedState);
- dispatchSetStateInternal(fiber, queue, thenableForFinishedState, requestUpdateLane(fiber));
- } else
- dispatchSetStateInternal(fiber, queue, finishedState, requestUpdateLane(fiber));
- } catch (error46) {
- dispatchSetStateInternal(fiber, queue, { then: function() {}, status: "rejected", reason: error46 }, requestUpdateLane(fiber));
- } finally {
- setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition, prevTransition === null && currentTransition._updatedFibers && (fiber = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < fiber && console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."));
- }
- }
- function ensureFormComponentIsStateful(formFiber) {
- var existingStateHook = formFiber.memoizedState;
- if (existingStateHook !== null)
- return existingStateHook;
- existingStateHook = {
- memoizedState: NotPendingTransition,
- baseState: NotPendingTransition,
- baseQueue: null,
- queue: {
- pending: null,
- lanes: 0,
- dispatch: null,
- lastRenderedReducer: basicStateReducer,
- lastRenderedState: NotPendingTransition
- },
- next: null
- };
- var initialResetState = {};
- existingStateHook.next = {
- memoizedState: initialResetState,
- baseState: initialResetState,
- baseQueue: null,
- queue: {
- pending: null,
- lanes: 0,
- dispatch: null,
- lastRenderedReducer: basicStateReducer,
- lastRenderedState: initialResetState
- },
- next: null
- };
- formFiber.memoizedState = existingStateHook;
- formFiber = formFiber.alternate;
- formFiber !== null && (formFiber.memoizedState = existingStateHook);
- return existingStateHook;
- }
- function mountTransition() {
- var stateHook = mountStateImpl(false);
- stateHook = startTransition.bind(null, currentlyRenderingFiber$1, stateHook.queue, true, false);
- mountWorkInProgressHook().memoizedState = stateHook;
- return [false, stateHook];
- }
- function updateTransition() {
- var booleanOrThenable = updateReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
- return [
- typeof booleanOrThenable === "boolean" ? booleanOrThenable : useThenable(booleanOrThenable),
- start
- ];
- }
- function rerenderTransition() {
- var booleanOrThenable = rerenderReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
- return [
- typeof booleanOrThenable === "boolean" ? booleanOrThenable : useThenable(booleanOrThenable),
- start
- ];
- }
- function useHostTransitionStatus() {
- return readContext(HostTransitionContext);
- }
- function mountId() {
- var hook = mountWorkInProgressHook(), identifierPrefix = workInProgressRoot.identifierPrefix;
- if (isHydrating) {
- var treeId = treeContextOverflow;
- var idWithLeadingBit = treeContextId;
- treeId = (idWithLeadingBit & ~(1 << 32 - clz32(idWithLeadingBit) - 1)).toString(32) + treeId;
- identifierPrefix = ":" + identifierPrefix + "R" + treeId;
- treeId = localIdCounter++;
- 0 < treeId && (identifierPrefix += "H" + treeId.toString(32));
- identifierPrefix += ":";
- } else
- treeId = globalClientIdCounter++, identifierPrefix = ":" + identifierPrefix + "r" + treeId.toString(32) + ":";
- return hook.memoizedState = identifierPrefix;
- }
- function mountRefresh() {
- return mountWorkInProgressHook().memoizedState = refreshCache.bind(null, currentlyRenderingFiber$1);
- }
- function refreshCache(fiber, seedKey) {
- for (var provider5 = fiber.return;provider5 !== null; ) {
- switch (provider5.tag) {
- case 24:
- case 3:
- var lane = requestUpdateLane(provider5);
- fiber = createUpdate(lane);
- var root2 = enqueueUpdate(provider5, fiber, lane);
- root2 !== null && (scheduleUpdateOnFiber(root2, provider5, lane), entangleTransitions(root2, provider5, lane));
- provider5 = createCache();
- seedKey !== null && seedKey !== undefined && root2 !== null && console.error("The seed argument is not enabled outside experimental channels.");
- fiber.payload = { cache: provider5 };
- return;
- }
- provider5 = provider5.return;
- }
- }
- function dispatchReducerAction(fiber, queue, action, JSCompiler_OptimizeArgumentsArray_p0) {
- typeof JSCompiler_OptimizeArgumentsArray_p0 === "function" && console.error("State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().");
- JSCompiler_OptimizeArgumentsArray_p0 = requestUpdateLane(fiber);
- action = {
- lane: JSCompiler_OptimizeArgumentsArray_p0,
- revertLane: 0,
- action,
- hasEagerState: false,
- eagerState: null,
- next: null
- };
- isRenderPhaseUpdate(fiber) ? enqueueRenderPhaseUpdate(queue, action) : (action = enqueueConcurrentHookUpdate(fiber, queue, action, JSCompiler_OptimizeArgumentsArray_p0), action !== null && (scheduleUpdateOnFiber(action, fiber, JSCompiler_OptimizeArgumentsArray_p0), entangleTransitionUpdate(action, queue, JSCompiler_OptimizeArgumentsArray_p0)));
- markStateUpdateScheduled(fiber, JSCompiler_OptimizeArgumentsArray_p0);
- }
- function dispatchSetState(fiber, queue, action, JSCompiler_OptimizeArgumentsArray_p1) {
- typeof JSCompiler_OptimizeArgumentsArray_p1 === "function" && console.error("State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().");
- JSCompiler_OptimizeArgumentsArray_p1 = requestUpdateLane(fiber);
- dispatchSetStateInternal(fiber, queue, action, JSCompiler_OptimizeArgumentsArray_p1);
- markStateUpdateScheduled(fiber, JSCompiler_OptimizeArgumentsArray_p1);
- }
- function dispatchSetStateInternal(fiber, queue, action, lane) {
- var update = {
- lane,
- revertLane: 0,
- action,
- hasEagerState: false,
- eagerState: null,
- next: null
- };
- if (isRenderPhaseUpdate(fiber))
- enqueueRenderPhaseUpdate(queue, update);
- else {
- var alternate = fiber.alternate;
- if (fiber.lanes === 0 && (alternate === null || alternate.lanes === 0) && (alternate = queue.lastRenderedReducer, alternate !== null)) {
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
- try {
- var currentState = queue.lastRenderedState, eagerState = alternate(currentState, action);
- update.hasEagerState = true;
- update.eagerState = eagerState;
- if (objectIs(eagerState, currentState))
- return enqueueUpdate$1(fiber, queue, update, 0), workInProgressRoot === null && finishQueueingConcurrentUpdates(), false;
- } catch (error46) {} finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- }
- action = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
- if (action !== null)
- return scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane), true;
- }
- return false;
- }
- function dispatchOptimisticSetState(fiber, throwIfDuringRender, queue, action) {
- ReactSharedInternals.T === null && currentEntangledLane === 0 && console.error("An optimistic state update occurred outside a transition or action. To fix, move the update to an action, or wrap with startTransition.");
- action = {
- lane: 2,
- revertLane: requestTransitionLane(),
- action,
- hasEagerState: false,
- eagerState: null,
- next: null
- };
- if (isRenderPhaseUpdate(fiber)) {
- if (throwIfDuringRender)
- throw Error("Cannot update optimistic state while rendering.");
- console.error("Cannot call startTransition while rendering.");
- } else
- throwIfDuringRender = enqueueConcurrentHookUpdate(fiber, queue, action, 2), throwIfDuringRender !== null && scheduleUpdateOnFiber(throwIfDuringRender, fiber, 2);
- markStateUpdateScheduled(fiber, 2);
- }
- function isRenderPhaseUpdate(fiber) {
- var alternate = fiber.alternate;
- return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1;
- }
- function enqueueRenderPhaseUpdate(queue, update) {
- didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
- var pending = queue.pending;
- pending === null ? update.next = update : (update.next = pending.next, pending.next = update);
- queue.pending = update;
- }
- function entangleTransitionUpdate(root2, queue, lane) {
- if ((lane & 4194176) !== 0) {
- var queueLanes = queue.lanes;
- queueLanes &= root2.pendingLanes;
- lane |= queueLanes;
- queue.lanes = lane;
- markRootEntangled(root2, lane);
- }
- }
- function warnOnInvalidCallback(callback) {
- if (callback !== null && typeof callback !== "function") {
- var key = String(callback);
- didWarnOnInvalidCallback.has(key) || (didWarnOnInvalidCallback.add(key), console.error("Expected the last optional `callback` argument to be a function. Instead received: %s.", callback));
- }
- }
- function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
- var prevState = workInProgress2.memoizedState, partialState = getDerivedStateFromProps(nextProps, prevState);
- if (workInProgress2.mode & 8) {
- setIsStrictModeForDevtools(true);
- try {
- partialState = getDerivedStateFromProps(nextProps, prevState);
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- partialState === undefined && (ctor = getComponentNameFromType(ctor) || "Component", didWarnAboutUndefinedDerivedState.has(ctor) || (didWarnAboutUndefinedDerivedState.add(ctor), console.error("%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.", ctor)));
- prevState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
- workInProgress2.memoizedState = prevState;
- workInProgress2.lanes === 0 && (workInProgress2.updateQueue.baseState = prevState);
- }
- function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
- var instance = workInProgress2.stateNode;
- if (typeof instance.shouldComponentUpdate === "function") {
- oldProps = instance.shouldComponentUpdate(newProps, newState, nextContext);
- if (workInProgress2.mode & 8) {
- setIsStrictModeForDevtools(true);
- try {
- oldProps = instance.shouldComponentUpdate(newProps, newState, nextContext);
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- oldProps === undefined && console.error("%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.", getComponentNameFromType(ctor) || "Component");
- return oldProps;
- }
- return ctor.prototype && ctor.prototype.isPureReactComponent ? !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) : true;
- }
- function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) {
- var oldState = instance.state;
- typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps(newProps, nextContext);
- typeof instance.UNSAFE_componentWillReceiveProps === "function" && instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
- instance.state !== oldState && (workInProgress2 = getComponentNameFromFiber(workInProgress2) || "Component", didWarnAboutStateAssignmentForComponent.has(workInProgress2) || (didWarnAboutStateAssignmentForComponent.add(workInProgress2), console.error("%s.componentWillReceiveProps(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", workInProgress2)), classComponentUpdater.enqueueReplaceState(instance, instance.state, null));
- }
- function resolveClassComponentProps(Component, baseProps) {
- var newProps = baseProps;
- if ("ref" in baseProps) {
- newProps = {};
- for (var propName in baseProps)
- propName !== "ref" && (newProps[propName] = baseProps[propName]);
- }
- if (Component = Component.defaultProps) {
- newProps === baseProps && (newProps = assign({}, newProps));
- for (var _propName in Component)
- newProps[_propName] === undefined && (newProps[_propName] = Component[_propName]);
- }
- return newProps;
- }
- function logUncaughtError(root2, errorInfo) {
- try {
- componentName = errorInfo.source ? getComponentNameFromFiber(errorInfo.source) : null;
- errorBoundaryName = null;
- var error46 = errorInfo.value;
- if (ReactSharedInternals.actQueue !== null)
- ReactSharedInternals.thrownErrors.push(error46);
- else {
- var onUncaughtError = root2.onUncaughtError;
- onUncaughtError(error46, { componentStack: errorInfo.stack });
- }
- } catch (e4) {
- setTimeout(function() {
- throw e4;
- });
- }
- }
- function logCaughtError(root2, boundary, errorInfo) {
- try {
- componentName = errorInfo.source ? getComponentNameFromFiber(errorInfo.source) : null;
- errorBoundaryName = getComponentNameFromFiber(boundary);
- var onCaughtError = root2.onCaughtError;
- onCaughtError(errorInfo.value, {
- componentStack: errorInfo.stack,
- errorBoundary: boundary.tag === 1 ? boundary.stateNode : null
- });
- } catch (e4) {
- setTimeout(function() {
- throw e4;
- });
- }
- }
- function createRootErrorUpdate(root2, errorInfo, lane) {
- lane = createUpdate(lane);
- lane.tag = CaptureUpdate;
- lane.payload = { element: null };
- lane.callback = function() {
- runWithFiberInDEV(errorInfo.source, logUncaughtError, root2, errorInfo);
- };
- return lane;
- }
- function createClassErrorUpdate(lane) {
- lane = createUpdate(lane);
- lane.tag = CaptureUpdate;
- return lane;
- }
- function initializeClassErrorUpdate(update, root2, fiber, errorInfo) {
- var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
- if (typeof getDerivedStateFromError === "function") {
- var error46 = errorInfo.value;
- update.payload = function() {
- return getDerivedStateFromError(error46);
- };
- update.callback = function() {
- markFailedErrorBoundaryForHotReloading(fiber);
- runWithFiberInDEV(errorInfo.source, logCaughtError, root2, fiber, errorInfo);
- };
- }
- var inst = fiber.stateNode;
- inst !== null && typeof inst.componentDidCatch === "function" && (update.callback = function() {
- markFailedErrorBoundaryForHotReloading(fiber);
- runWithFiberInDEV(errorInfo.source, logCaughtError, root2, fiber, errorInfo);
- typeof getDerivedStateFromError !== "function" && (legacyErrorBoundariesThatAlreadyFailed === null ? legacyErrorBoundariesThatAlreadyFailed = new Set([this]) : legacyErrorBoundariesThatAlreadyFailed.add(this));
- callComponentDidCatchInDEV(this, errorInfo);
- typeof getDerivedStateFromError === "function" || (fiber.lanes & 2) === 0 && console.error("%s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI.", getComponentNameFromFiber(fiber) || "Unknown");
- });
- }
- function throwException(root2, returnFiber, sourceFiber, value, rootRenderLanes) {
- sourceFiber.flags |= 32768;
- isDevToolsPresent && restorePendingUpdaters(root2, rootRenderLanes);
- if (value !== null && typeof value === "object" && typeof value.then === "function") {
- returnFiber = sourceFiber.alternate;
- returnFiber !== null && propagateParentContextChanges(returnFiber, sourceFiber, rootRenderLanes, true);
- isHydrating && (didSuspendOrErrorDEV = true);
- sourceFiber = suspenseHandlerStackCursor.current;
- if (sourceFiber !== null) {
- switch (sourceFiber.tag) {
- case 13:
- return shellBoundary === null ? renderDidSuspendDelayIfPossible() : sourceFiber.alternate === null && workInProgressRootExitStatus === RootInProgress && (workInProgressRootExitStatus = RootSuspended), sourceFiber.flags &= -257, sourceFiber.flags |= 65536, sourceFiber.lanes = rootRenderLanes, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, returnFiber === null ? sourceFiber.updateQueue = new Set([value]) : returnFiber.add(value), attachPingListener(root2, value, rootRenderLanes)), false;
- case 22:
- return sourceFiber.flags |= 65536, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, returnFiber === null ? (returnFiber = {
- transitions: null,
- markerInstances: null,
- retryQueue: new Set([value])
- }, sourceFiber.updateQueue = returnFiber) : (sourceFiber = returnFiber.retryQueue, sourceFiber === null ? returnFiber.retryQueue = new Set([value]) : sourceFiber.add(value)), attachPingListener(root2, value, rootRenderLanes)), false;
- }
- throw Error("Unexpected Suspense handler tag (" + sourceFiber.tag + "). This is a bug in React.");
- }
- attachPingListener(root2, value, rootRenderLanes);
- renderDidSuspendDelayIfPossible();
- return false;
- }
- if (isHydrating)
- return didSuspendOrErrorDEV = true, returnFiber = suspenseHandlerStackCursor.current, returnFiber !== null ? ((returnFiber.flags & 65536) === 0 && (returnFiber.flags |= 256), returnFiber.flags |= 65536, returnFiber.lanes = rootRenderLanes, value !== HydrationMismatchException && queueHydrationError(createCapturedValueAtFiber(Error("There was an error while hydrating but React was able to recover by instead client rendering from the nearest Suspense boundary.", { cause: value }), sourceFiber))) : (value !== HydrationMismatchException && queueHydrationError(createCapturedValueAtFiber(Error("There was an error while hydrating but React was able to recover by instead client rendering the entire root.", { cause: value }), sourceFiber)), root2 = root2.current.alternate, root2.flags |= 65536, rootRenderLanes &= -rootRenderLanes, root2.lanes |= rootRenderLanes, value = createCapturedValueAtFiber(value, sourceFiber), rootRenderLanes = createRootErrorUpdate(root2.stateNode, value, rootRenderLanes), enqueueCapturedUpdate(root2, rootRenderLanes), workInProgressRootExitStatus !== RootSuspendedWithDelay && (workInProgressRootExitStatus = RootErrored)), false;
- var error46 = createCapturedValueAtFiber(Error("There was an error during concurrent rendering but React was able to recover by instead synchronously rendering the entire root.", { cause: value }), sourceFiber);
- workInProgressRootConcurrentErrors === null ? workInProgressRootConcurrentErrors = [error46] : workInProgressRootConcurrentErrors.push(error46);
- workInProgressRootExitStatus !== RootSuspendedWithDelay && (workInProgressRootExitStatus = RootErrored);
- if (returnFiber === null)
- return true;
- value = createCapturedValueAtFiber(value, sourceFiber);
- sourceFiber = returnFiber;
- do {
- switch (sourceFiber.tag) {
- case 3:
- return sourceFiber.flags |= 65536, root2 = rootRenderLanes & -rootRenderLanes, sourceFiber.lanes |= root2, root2 = createRootErrorUpdate(sourceFiber.stateNode, value, root2), enqueueCapturedUpdate(sourceFiber, root2), false;
- case 1:
- if (returnFiber = sourceFiber.type, error46 = sourceFiber.stateNode, (sourceFiber.flags & 128) === 0 && (typeof returnFiber.getDerivedStateFromError === "function" || error46 !== null && typeof error46.componentDidCatch === "function" && (legacyErrorBoundariesThatAlreadyFailed === null || !legacyErrorBoundariesThatAlreadyFailed.has(error46))))
- return sourceFiber.flags |= 65536, rootRenderLanes &= -rootRenderLanes, sourceFiber.lanes |= rootRenderLanes, rootRenderLanes = createClassErrorUpdate(rootRenderLanes), initializeClassErrorUpdate(rootRenderLanes, root2, sourceFiber, value), enqueueCapturedUpdate(sourceFiber, rootRenderLanes), false;
- }
- sourceFiber = sourceFiber.return;
- } while (sourceFiber !== null);
- return false;
- }
- function reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2) {
- workInProgress2.child = current2 === null ? mountChildFibers(workInProgress2, null, nextChildren, renderLanes2) : reconcileChildFibers(workInProgress2, current2.child, nextChildren, renderLanes2);
- }
- function updateForwardRef(current2, workInProgress2, Component, nextProps, renderLanes2) {
- Component = Component.render;
- var ref = workInProgress2.ref;
- if ("ref" in nextProps) {
- var propsWithoutRef = {};
- for (var key in nextProps)
- key !== "ref" && (propsWithoutRef[key] = nextProps[key]);
- } else
- propsWithoutRef = nextProps;
- prepareToReadContext(workInProgress2);
- markComponentRenderStarted(workInProgress2);
- nextProps = renderWithHooks(current2, workInProgress2, Component, propsWithoutRef, ref, renderLanes2);
- key = checkDidRenderIdHook();
- markComponentRenderStopped();
- if (current2 !== null && !didReceiveUpdate)
- return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
- isHydrating && key && pushMaterializedTreeId(workInProgress2);
- workInProgress2.flags |= 1;
- reconcileChildren(current2, workInProgress2, nextProps, renderLanes2);
- return workInProgress2.child;
- }
- function updateMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
- if (current2 === null) {
- var type = Component.type;
- if (typeof type === "function" && !shouldConstruct(type) && type.defaultProps === undefined && Component.compare === null)
- return Component = resolveFunctionForHotReloading(type), workInProgress2.tag = 15, workInProgress2.type = Component, validateFunctionComponentInDev(workInProgress2, type), updateSimpleMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2);
- current2 = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress2, workInProgress2.mode, renderLanes2);
- current2.ref = workInProgress2.ref;
- current2.return = workInProgress2;
- return workInProgress2.child = current2;
- }
- type = current2.child;
- if (!checkScheduledUpdateOrContext(current2, renderLanes2)) {
- var prevProps = type.memoizedProps;
- Component = Component.compare;
- Component = Component !== null ? Component : shallowEqual;
- if (Component(prevProps, nextProps) && current2.ref === workInProgress2.ref)
- return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
- }
- workInProgress2.flags |= 1;
- current2 = createWorkInProgress(type, nextProps);
- current2.ref = workInProgress2.ref;
- current2.return = workInProgress2;
- return workInProgress2.child = current2;
- }
- function updateSimpleMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
- if (current2 !== null) {
- var prevProps = current2.memoizedProps;
- if (shallowEqual(prevProps, nextProps) && current2.ref === workInProgress2.ref && workInProgress2.type === current2.type)
- if (didReceiveUpdate = false, workInProgress2.pendingProps = nextProps = prevProps, checkScheduledUpdateOrContext(current2, renderLanes2))
- (current2.flags & 131072) !== 0 && (didReceiveUpdate = true);
- else
- return workInProgress2.lanes = current2.lanes, bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
- }
- return updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2);
- }
- function updateOffscreenComponent(current2, workInProgress2, renderLanes2) {
- var nextProps = workInProgress2.pendingProps, nextChildren = nextProps.children, nextIsDetached = (workInProgress2.stateNode._pendingVisibility & 2) !== 0, prevState = current2 !== null ? current2.memoizedState : null;
- markRef(current2, workInProgress2);
- if (nextProps.mode === "hidden" || nextIsDetached) {
- if ((workInProgress2.flags & 128) !== 0) {
- nextProps = prevState !== null ? prevState.baseLanes | renderLanes2 : renderLanes2;
- if (current2 !== null) {
- nextChildren = workInProgress2.child = current2.child;
- for (nextIsDetached = 0;nextChildren !== null; )
- nextIsDetached = nextIsDetached | nextChildren.lanes | nextChildren.childLanes, nextChildren = nextChildren.sibling;
- workInProgress2.childLanes = nextIsDetached & ~nextProps;
- } else
- workInProgress2.childLanes = 0, workInProgress2.child = null;
- return deferHiddenOffscreenComponent(current2, workInProgress2, nextProps, renderLanes2);
- }
- if ((renderLanes2 & 536870912) !== 0)
- workInProgress2.memoizedState = { baseLanes: 0, cachePool: null }, current2 !== null && pushTransition(workInProgress2, prevState !== null ? prevState.cachePool : null), prevState !== null ? pushHiddenContext(workInProgress2, prevState) : reuseHiddenContextOnStack(workInProgress2), pushOffscreenSuspenseHandler(workInProgress2);
- else
- return workInProgress2.lanes = workInProgress2.childLanes = 536870912, deferHiddenOffscreenComponent(current2, workInProgress2, prevState !== null ? prevState.baseLanes | renderLanes2 : renderLanes2, renderLanes2);
- } else
- prevState !== null ? (pushTransition(workInProgress2, prevState.cachePool), pushHiddenContext(workInProgress2, prevState), reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.memoizedState = null) : (current2 !== null && pushTransition(workInProgress2, null), reuseHiddenContextOnStack(workInProgress2), reuseSuspenseHandlerOnStack(workInProgress2));
- reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
- return workInProgress2.child;
- }
- function deferHiddenOffscreenComponent(current2, workInProgress2, nextBaseLanes, renderLanes2) {
- var JSCompiler_inline_result = peekCacheFromPool();
- JSCompiler_inline_result = JSCompiler_inline_result === null ? null : {
- parent: isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2,
- pool: JSCompiler_inline_result
- };
- workInProgress2.memoizedState = {
- baseLanes: nextBaseLanes,
- cachePool: JSCompiler_inline_result
- };
- current2 !== null && pushTransition(workInProgress2, null);
- reuseHiddenContextOnStack(workInProgress2);
- pushOffscreenSuspenseHandler(workInProgress2);
- current2 !== null && propagateParentContextChanges(current2, workInProgress2, renderLanes2, true);
- return null;
- }
- function markRef(current2, workInProgress2) {
- var ref = workInProgress2.ref;
- if (ref === null)
- current2 !== null && current2.ref !== null && (workInProgress2.flags |= 2097664);
- else {
- if (typeof ref !== "function" && typeof ref !== "object")
- throw Error("Expected ref to be a function, an object returned by React.createRef(), or undefined/null.");
- if (current2 === null || current2.ref !== ref)
- workInProgress2.flags |= 2097664;
- }
- }
- function updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
- if (Component.prototype && typeof Component.prototype.render === "function") {
- var componentName2 = getComponentNameFromType(Component) || "Unknown";
- didWarnAboutBadClass[componentName2] || (console.error("The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.", componentName2, componentName2), didWarnAboutBadClass[componentName2] = true);
- }
- workInProgress2.mode & 8 && ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, null);
- current2 === null && (validateFunctionComponentInDev(workInProgress2, workInProgress2.type), Component.contextTypes && (componentName2 = getComponentNameFromType(Component) || "Unknown", didWarnAboutContextTypes[componentName2] || (didWarnAboutContextTypes[componentName2] = true, console.error("%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with React.useContext() instead. (https://react.dev/link/legacy-context)", componentName2))));
- prepareToReadContext(workInProgress2);
- markComponentRenderStarted(workInProgress2);
- Component = renderWithHooks(current2, workInProgress2, Component, nextProps, undefined, renderLanes2);
- nextProps = checkDidRenderIdHook();
- markComponentRenderStopped();
- if (current2 !== null && !didReceiveUpdate)
- return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
- isHydrating && nextProps && pushMaterializedTreeId(workInProgress2);
- workInProgress2.flags |= 1;
- reconcileChildren(current2, workInProgress2, Component, renderLanes2);
- return workInProgress2.child;
- }
- function replayFunctionComponent(current2, workInProgress2, nextProps, Component, secondArg, renderLanes2) {
- prepareToReadContext(workInProgress2);
- markComponentRenderStarted(workInProgress2);
- hookTypesUpdateIndexDev = -1;
- ignorePreviousDependencies = current2 !== null && current2.type !== workInProgress2.type;
- workInProgress2.updateQueue = null;
- nextProps = renderWithHooksAgain(workInProgress2, Component, nextProps, secondArg);
- finishRenderingHooks(current2, workInProgress2);
- Component = checkDidRenderIdHook();
- markComponentRenderStopped();
- if (current2 !== null && !didReceiveUpdate)
- return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
- isHydrating && Component && pushMaterializedTreeId(workInProgress2);
- workInProgress2.flags |= 1;
- reconcileChildren(current2, workInProgress2, nextProps, renderLanes2);
- return workInProgress2.child;
- }
- function updateClassComponent(current$jscomp$0, workInProgress2, Component, nextProps, renderLanes2) {
- switch (shouldErrorImpl(workInProgress2)) {
- case false:
- var _instance = workInProgress2.stateNode, state3 = new workInProgress2.type(workInProgress2.memoizedProps, _instance.context).state;
- _instance.updater.enqueueSetState(_instance, state3, null);
- break;
- case true:
- workInProgress2.flags |= 128;
- workInProgress2.flags |= 65536;
- _instance = Error("Simulated error coming from DevTools");
- var lane = renderLanes2 & -renderLanes2;
- workInProgress2.lanes |= lane;
- state3 = workInProgressRoot;
- if (state3 === null)
- throw Error("Expected a work-in-progress root. This is a bug in React. Please file an issue.");
- lane = createClassErrorUpdate(lane);
- initializeClassErrorUpdate(lane, state3, workInProgress2, createCapturedValueAtFiber(_instance, workInProgress2));
- enqueueCapturedUpdate(workInProgress2, lane);
- }
- prepareToReadContext(workInProgress2);
- if (workInProgress2.stateNode === null) {
- state3 = emptyContextObject;
- _instance = Component.contextType;
- "contextType" in Component && _instance !== null && (_instance === undefined || _instance.$$typeof !== REACT_CONTEXT_TYPE) && !didWarnAboutInvalidateContextType.has(Component) && (didWarnAboutInvalidateContextType.add(Component), lane = _instance === undefined ? " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file." : typeof _instance !== "object" ? " However, it is set to a " + typeof _instance + "." : _instance.$$typeof === REACT_CONSUMER_TYPE ? " Did you accidentally pass the Context.Consumer instead?" : " However, it is set to an object with keys {" + Object.keys(_instance).join(", ") + "}.", console.error("%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s", getComponentNameFromType(Component) || "Component", lane));
- typeof _instance === "object" && _instance !== null && (state3 = readContext(_instance));
- _instance = new Component(nextProps, state3);
- if (workInProgress2.mode & 8) {
- setIsStrictModeForDevtools(true);
- try {
- _instance = new Component(nextProps, state3);
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- state3 = workInProgress2.memoizedState = _instance.state !== null && _instance.state !== undefined ? _instance.state : null;
- _instance.updater = classComponentUpdater;
- workInProgress2.stateNode = _instance;
- _instance._reactInternals = workInProgress2;
- _instance._reactInternalInstance = fakeInternalInstance;
- typeof Component.getDerivedStateFromProps === "function" && state3 === null && (state3 = getComponentNameFromType(Component) || "Component", didWarnAboutUninitializedState.has(state3) || (didWarnAboutUninitializedState.add(state3), console.error("`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", state3, _instance.state === null ? "null" : "undefined", state3)));
- if (typeof Component.getDerivedStateFromProps === "function" || typeof _instance.getSnapshotBeforeUpdate === "function") {
- var foundWillUpdateName = lane = state3 = null;
- typeof _instance.componentWillMount === "function" && _instance.componentWillMount.__suppressDeprecationWarning !== true ? state3 = "componentWillMount" : typeof _instance.UNSAFE_componentWillMount === "function" && (state3 = "UNSAFE_componentWillMount");
- typeof _instance.componentWillReceiveProps === "function" && _instance.componentWillReceiveProps.__suppressDeprecationWarning !== true ? lane = "componentWillReceiveProps" : typeof _instance.UNSAFE_componentWillReceiveProps === "function" && (lane = "UNSAFE_componentWillReceiveProps");
- typeof _instance.componentWillUpdate === "function" && _instance.componentWillUpdate.__suppressDeprecationWarning !== true ? foundWillUpdateName = "componentWillUpdate" : typeof _instance.UNSAFE_componentWillUpdate === "function" && (foundWillUpdateName = "UNSAFE_componentWillUpdate");
- if (state3 !== null || lane !== null || foundWillUpdateName !== null) {
- _instance = getComponentNameFromType(Component) || "Component";
- var newApiName = typeof Component.getDerivedStateFromProps === "function" ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()";
- didWarnAboutLegacyLifecyclesAndDerivedState.has(_instance) || (didWarnAboutLegacyLifecyclesAndDerivedState.add(_instance), console.error(`Unsafe legacy lifecycles will not be called for components using new component APIs.
-
-%s uses %s but also contains the following legacy lifecycles:%s%s%s
-
-The above lifecycles should be removed. Learn more about this warning here:
-https://react.dev/link/unsafe-component-lifecycles`, _instance, newApiName, state3 !== null ? `
- ` + state3 : "", lane !== null ? `
- ` + lane : "", foundWillUpdateName !== null ? `
- ` + foundWillUpdateName : ""));
- }
- }
- _instance = workInProgress2.stateNode;
- state3 = getComponentNameFromType(Component) || "Component";
- _instance.render || (Component.prototype && typeof Component.prototype.render === "function" ? console.error("No `render` method found on the %s instance: did you accidentally return an object from the constructor?", state3) : console.error("No `render` method found on the %s instance: you may have forgotten to define `render`.", state3));
- !_instance.getInitialState || _instance.getInitialState.isReactClassApproved || _instance.state || console.error("getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?", state3);
- _instance.getDefaultProps && !_instance.getDefaultProps.isReactClassApproved && console.error("getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.", state3);
- _instance.contextType && console.error("contextType was defined as an instance property on %s. Use a static property to define contextType instead.", state3);
- Component.childContextTypes && !didWarnAboutChildContextTypes.has(Component) && (didWarnAboutChildContextTypes.add(Component), console.error("%s uses the legacy childContextTypes API which was removed in React 19. Use React.createContext() instead. (https://react.dev/link/legacy-context)", state3));
- Component.contextTypes && !didWarnAboutContextTypes$1.has(Component) && (didWarnAboutContextTypes$1.add(Component), console.error("%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with static contextType instead. (https://react.dev/link/legacy-context)", state3));
- typeof _instance.componentShouldUpdate === "function" && console.error("%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.", state3);
- Component.prototype && Component.prototype.isPureReactComponent && typeof _instance.shouldComponentUpdate !== "undefined" && console.error("%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.", getComponentNameFromType(Component) || "A pure component");
- typeof _instance.componentDidUnmount === "function" && console.error("%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?", state3);
- typeof _instance.componentDidReceiveProps === "function" && console.error("%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().", state3);
- typeof _instance.componentWillRecieveProps === "function" && console.error("%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", state3);
- typeof _instance.UNSAFE_componentWillRecieveProps === "function" && console.error("%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", state3);
- lane = _instance.props !== nextProps;
- _instance.props !== undefined && lane && console.error("When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.", state3);
- _instance.defaultProps && console.error("Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.", state3, state3);
- typeof _instance.getSnapshotBeforeUpdate !== "function" || typeof _instance.componentDidUpdate === "function" || didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(Component) || (didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(Component), console.error("%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.", getComponentNameFromType(Component)));
- typeof _instance.getDerivedStateFromProps === "function" && console.error("%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.", state3);
- typeof _instance.getDerivedStateFromError === "function" && console.error("%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.", state3);
- typeof Component.getSnapshotBeforeUpdate === "function" && console.error("%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.", state3);
- (lane = _instance.state) && (typeof lane !== "object" || isArrayImpl(lane)) && console.error("%s.state: must be set to an object or null", state3);
- typeof _instance.getChildContext === "function" && typeof Component.childContextTypes !== "object" && console.error("%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().", state3);
- _instance = workInProgress2.stateNode;
- _instance.props = nextProps;
- _instance.state = workInProgress2.memoizedState;
- _instance.refs = {};
- initializeUpdateQueue(workInProgress2);
- state3 = Component.contextType;
- _instance.context = typeof state3 === "object" && state3 !== null ? readContext(state3) : emptyContextObject;
- _instance.state === nextProps && (state3 = getComponentNameFromType(Component) || "Component", didWarnAboutDirectlyAssigningPropsToState.has(state3) || (didWarnAboutDirectlyAssigningPropsToState.add(state3), console.error("%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.", state3)));
- workInProgress2.mode & 8 && ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, _instance);
- ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress2, _instance);
- _instance.state = workInProgress2.memoizedState;
- state3 = Component.getDerivedStateFromProps;
- typeof state3 === "function" && (applyDerivedStateFromProps(workInProgress2, Component, state3, nextProps), _instance.state = workInProgress2.memoizedState);
- typeof Component.getDerivedStateFromProps === "function" || typeof _instance.getSnapshotBeforeUpdate === "function" || typeof _instance.UNSAFE_componentWillMount !== "function" && typeof _instance.componentWillMount !== "function" || (state3 = _instance.state, typeof _instance.componentWillMount === "function" && _instance.componentWillMount(), typeof _instance.UNSAFE_componentWillMount === "function" && _instance.UNSAFE_componentWillMount(), state3 !== _instance.state && (console.error("%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", getComponentNameFromFiber(workInProgress2) || "Component"), classComponentUpdater.enqueueReplaceState(_instance, _instance.state, null)), processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction(), _instance.state = workInProgress2.memoizedState);
- typeof _instance.componentDidMount === "function" && (workInProgress2.flags |= 4194308);
- (workInProgress2.mode & 16) !== NoMode && (workInProgress2.flags |= 67108864);
- _instance = true;
- } else if (current$jscomp$0 === null) {
- _instance = workInProgress2.stateNode;
- var unresolvedOldProps = workInProgress2.memoizedProps;
- lane = resolveClassComponentProps(Component, unresolvedOldProps);
- _instance.props = lane;
- var oldContext = _instance.context;
- foundWillUpdateName = Component.contextType;
- state3 = emptyContextObject;
- typeof foundWillUpdateName === "object" && foundWillUpdateName !== null && (state3 = readContext(foundWillUpdateName));
- newApiName = Component.getDerivedStateFromProps;
- foundWillUpdateName = typeof newApiName === "function" || typeof _instance.getSnapshotBeforeUpdate === "function";
- unresolvedOldProps = workInProgress2.pendingProps !== unresolvedOldProps;
- foundWillUpdateName || typeof _instance.UNSAFE_componentWillReceiveProps !== "function" && typeof _instance.componentWillReceiveProps !== "function" || (unresolvedOldProps || oldContext !== state3) && callComponentWillReceiveProps(workInProgress2, _instance, nextProps, state3);
- hasForceUpdate = false;
- var oldState = workInProgress2.memoizedState;
- _instance.state = oldState;
- processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2);
- suspendIfUpdateReadFromEntangledAsyncAction();
- oldContext = workInProgress2.memoizedState;
- unresolvedOldProps || oldState !== oldContext || hasForceUpdate ? (typeof newApiName === "function" && (applyDerivedStateFromProps(workInProgress2, Component, newApiName, nextProps), oldContext = workInProgress2.memoizedState), (lane = hasForceUpdate || checkShouldComponentUpdate(workInProgress2, Component, lane, nextProps, oldState, oldContext, state3)) ? (foundWillUpdateName || typeof _instance.UNSAFE_componentWillMount !== "function" && typeof _instance.componentWillMount !== "function" || (typeof _instance.componentWillMount === "function" && _instance.componentWillMount(), typeof _instance.UNSAFE_componentWillMount === "function" && _instance.UNSAFE_componentWillMount()), typeof _instance.componentDidMount === "function" && (workInProgress2.flags |= 4194308), (workInProgress2.mode & 16) !== NoMode && (workInProgress2.flags |= 67108864)) : (typeof _instance.componentDidMount === "function" && (workInProgress2.flags |= 4194308), (workInProgress2.mode & 16) !== NoMode && (workInProgress2.flags |= 67108864), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = oldContext), _instance.props = nextProps, _instance.state = oldContext, _instance.context = state3, _instance = lane) : (typeof _instance.componentDidMount === "function" && (workInProgress2.flags |= 4194308), (workInProgress2.mode & 16) !== NoMode && (workInProgress2.flags |= 67108864), _instance = false);
- } else {
- _instance = workInProgress2.stateNode;
- cloneUpdateQueue(current$jscomp$0, workInProgress2);
- state3 = workInProgress2.memoizedProps;
- foundWillUpdateName = resolveClassComponentProps(Component, state3);
- _instance.props = foundWillUpdateName;
- newApiName = workInProgress2.pendingProps;
- oldState = _instance.context;
- oldContext = Component.contextType;
- lane = emptyContextObject;
- typeof oldContext === "object" && oldContext !== null && (lane = readContext(oldContext));
- unresolvedOldProps = Component.getDerivedStateFromProps;
- (oldContext = typeof unresolvedOldProps === "function" || typeof _instance.getSnapshotBeforeUpdate === "function") || typeof _instance.UNSAFE_componentWillReceiveProps !== "function" && typeof _instance.componentWillReceiveProps !== "function" || (state3 !== newApiName || oldState !== lane) && callComponentWillReceiveProps(workInProgress2, _instance, nextProps, lane);
- hasForceUpdate = false;
- oldState = workInProgress2.memoizedState;
- _instance.state = oldState;
- processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2);
- suspendIfUpdateReadFromEntangledAsyncAction();
- var newState = workInProgress2.memoizedState;
- state3 !== newApiName || oldState !== newState || hasForceUpdate || current$jscomp$0 !== null && current$jscomp$0.dependencies !== null && checkIfContextChanged(current$jscomp$0.dependencies) ? (typeof unresolvedOldProps === "function" && (applyDerivedStateFromProps(workInProgress2, Component, unresolvedOldProps, nextProps), newState = workInProgress2.memoizedState), (foundWillUpdateName = hasForceUpdate || checkShouldComponentUpdate(workInProgress2, Component, foundWillUpdateName, nextProps, oldState, newState, lane) || current$jscomp$0 !== null && current$jscomp$0.dependencies !== null && checkIfContextChanged(current$jscomp$0.dependencies)) ? (oldContext || typeof _instance.UNSAFE_componentWillUpdate !== "function" && typeof _instance.componentWillUpdate !== "function" || (typeof _instance.componentWillUpdate === "function" && _instance.componentWillUpdate(nextProps, newState, lane), typeof _instance.UNSAFE_componentWillUpdate === "function" && _instance.UNSAFE_componentWillUpdate(nextProps, newState, lane)), typeof _instance.componentDidUpdate === "function" && (workInProgress2.flags |= 4), typeof _instance.getSnapshotBeforeUpdate === "function" && (workInProgress2.flags |= 1024)) : (typeof _instance.componentDidUpdate !== "function" || state3 === current$jscomp$0.memoizedProps && oldState === current$jscomp$0.memoizedState || (workInProgress2.flags |= 4), typeof _instance.getSnapshotBeforeUpdate !== "function" || state3 === current$jscomp$0.memoizedProps && oldState === current$jscomp$0.memoizedState || (workInProgress2.flags |= 1024), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = newState), _instance.props = nextProps, _instance.state = newState, _instance.context = lane, _instance = foundWillUpdateName) : (typeof _instance.componentDidUpdate !== "function" || state3 === current$jscomp$0.memoizedProps && oldState === current$jscomp$0.memoizedState || (workInProgress2.flags |= 4), typeof _instance.getSnapshotBeforeUpdate !== "function" || state3 === current$jscomp$0.memoizedProps && oldState === current$jscomp$0.memoizedState || (workInProgress2.flags |= 1024), _instance = false);
- }
- lane = _instance;
- markRef(current$jscomp$0, workInProgress2);
- state3 = (workInProgress2.flags & 128) !== 0;
- if (lane || state3) {
- lane = workInProgress2.stateNode;
- ReactSharedInternals.getCurrentStack = workInProgress2 === null ? null : getCurrentFiberStackInDev;
- isRendering = false;
- current = workInProgress2;
- if (state3 && typeof Component.getDerivedStateFromError !== "function")
- Component = null, profilerStartTime = -1;
- else {
- markComponentRenderStarted(workInProgress2);
- Component = callRenderInDEV(lane);
- if (workInProgress2.mode & 8) {
- setIsStrictModeForDevtools(true);
- try {
- callRenderInDEV(lane);
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- markComponentRenderStopped();
- }
- workInProgress2.flags |= 1;
- current$jscomp$0 !== null && state3 ? (workInProgress2.child = reconcileChildFibers(workInProgress2, current$jscomp$0.child, null, renderLanes2), workInProgress2.child = reconcileChildFibers(workInProgress2, null, Component, renderLanes2)) : reconcileChildren(current$jscomp$0, workInProgress2, Component, renderLanes2);
- workInProgress2.memoizedState = lane.state;
- current$jscomp$0 = workInProgress2.child;
- } else
- current$jscomp$0 = bailoutOnAlreadyFinishedWork(current$jscomp$0, workInProgress2, renderLanes2);
- renderLanes2 = workInProgress2.stateNode;
- _instance && renderLanes2.props !== nextProps && (didWarnAboutReassigningProps || console.error("It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.", getComponentNameFromFiber(workInProgress2) || "a component"), didWarnAboutReassigningProps = true);
- return current$jscomp$0;
- }
- function mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2) {
- resetHydrationState();
- workInProgress2.flags |= 256;
- reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
- return workInProgress2.child;
- }
- function validateFunctionComponentInDev(workInProgress2, Component) {
- Component && Component.childContextTypes && console.error(`childContextTypes cannot be defined on a function component.
- %s.childContextTypes = ...`, Component.displayName || Component.name || "Component");
- typeof Component.getDerivedStateFromProps === "function" && (workInProgress2 = getComponentNameFromType(Component) || "Unknown", didWarnAboutGetDerivedStateOnFunctionComponent[workInProgress2] || (console.error("%s: Function components do not support getDerivedStateFromProps.", workInProgress2), didWarnAboutGetDerivedStateOnFunctionComponent[workInProgress2] = true));
- typeof Component.contextType === "object" && Component.contextType !== null && (Component = getComponentNameFromType(Component) || "Unknown", didWarnAboutContextTypeOnFunctionComponent[Component] || (console.error("%s: Function components do not support contextType.", Component), didWarnAboutContextTypeOnFunctionComponent[Component] = true));
- }
- function mountSuspenseOffscreenState(renderLanes2) {
- return { baseLanes: renderLanes2, cachePool: getSuspendedCache() };
- }
- function getRemainingWorkInPrimaryTree(current2, primaryTreeDidDefer, renderLanes2) {
- current2 = current2 !== null ? current2.childLanes & ~renderLanes2 : 0;
- primaryTreeDidDefer && (current2 |= workInProgressDeferredLane);
- return current2;
- }
- function updateSuspenseComponent(current2, workInProgress2, renderLanes2) {
- var nextProps = workInProgress2.pendingProps;
- shouldSuspendImpl(workInProgress2) && (workInProgress2.flags |= 128);
- var showFallback = false, didSuspend = (workInProgress2.flags & 128) !== 0, JSCompiler_temp;
- (JSCompiler_temp = didSuspend) || (JSCompiler_temp = current2 !== null && current2.memoizedState === null ? false : (suspenseStackCursor.current & ForceSuspenseFallback) !== 0);
- JSCompiler_temp && (showFallback = true, workInProgress2.flags &= -129);
- JSCompiler_temp = (workInProgress2.flags & 32) !== 0;
- workInProgress2.flags &= -33;
- if (current2 === null) {
- if (isHydrating) {
- showFallback ? pushPrimaryTreeSuspenseHandler(workInProgress2) : reuseSuspenseHandlerOnStack(workInProgress2);
- if (isHydrating) {
- var nextInstance = nextHydratableInstance, JSCompiler_temp$jscomp$0;
- (JSCompiler_temp$jscomp$0 = !nextInstance) || (JSCompiler_temp$jscomp$0 = canHydrateSuspenseInstance(nextInstance, rootOrSingletonContext), JSCompiler_temp$jscomp$0 !== null ? (warnIfNotHydrating(), workInProgress2.memoizedState = {
- dehydrated: JSCompiler_temp$jscomp$0,
- treeContext: treeContextProvider !== null ? { id: treeContextId, overflow: treeContextOverflow } : null,
- retryLane: 536870912
- }, didSuspend = createFiber(18, null, null, NoMode), didSuspend.stateNode = JSCompiler_temp$jscomp$0, didSuspend.return = workInProgress2, workInProgress2.child = didSuspend, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, JSCompiler_temp$jscomp$0 = true) : JSCompiler_temp$jscomp$0 = false, JSCompiler_temp$jscomp$0 = !JSCompiler_temp$jscomp$0);
- JSCompiler_temp$jscomp$0 && (warnNonHydratedInstance(workInProgress2, nextInstance), throwOnHydrationMismatch(workInProgress2));
- }
- nextInstance = workInProgress2.memoizedState;
- if (nextInstance !== null && (nextInstance = nextInstance.dehydrated, nextInstance !== null))
- return isSuspenseInstanceFallback(nextInstance) ? workInProgress2.lanes = 16 : workInProgress2.lanes = 536870912, null;
- popSuspenseHandler(workInProgress2);
- }
- nextInstance = nextProps.children;
- nextProps = nextProps.fallback;
- if (showFallback)
- return reuseSuspenseHandlerOnStack(workInProgress2), showFallback = workInProgress2.mode, nextInstance = mountWorkInProgressOffscreenFiber({ mode: "hidden", children: nextInstance }, showFallback), nextProps = createFiberFromFragment(nextProps, showFallback, renderLanes2, null), nextInstance.return = workInProgress2, nextProps.return = workInProgress2, nextInstance.sibling = nextProps, workInProgress2.child = nextInstance, showFallback = workInProgress2.child, showFallback.memoizedState = mountSuspenseOffscreenState(renderLanes2), showFallback.childLanes = getRemainingWorkInPrimaryTree(current2, JSCompiler_temp, renderLanes2), workInProgress2.memoizedState = SUSPENDED_MARKER, nextProps;
- pushPrimaryTreeSuspenseHandler(workInProgress2);
- return mountSuspensePrimaryChildren(workInProgress2, nextInstance);
- }
- JSCompiler_temp$jscomp$0 = current2.memoizedState;
- if (JSCompiler_temp$jscomp$0 !== null && (nextInstance = JSCompiler_temp$jscomp$0.dehydrated, nextInstance !== null)) {
- if (didSuspend)
- workInProgress2.flags & 256 ? (pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags &= -257, workInProgress2 = retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2)) : workInProgress2.memoizedState !== null ? (reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.child = current2.child, workInProgress2.flags |= 128, workInProgress2 = null) : (reuseSuspenseHandlerOnStack(workInProgress2), showFallback = nextProps.fallback, nextInstance = workInProgress2.mode, nextProps = mountWorkInProgressOffscreenFiber({ mode: "visible", children: nextProps.children }, nextInstance), showFallback = createFiberFromFragment(showFallback, nextInstance, renderLanes2, null), showFallback.flags |= 2, nextProps.return = workInProgress2, showFallback.return = workInProgress2, nextProps.sibling = showFallback, workInProgress2.child = nextProps, reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2), nextProps = workInProgress2.child, nextProps.memoizedState = mountSuspenseOffscreenState(renderLanes2), nextProps.childLanes = getRemainingWorkInPrimaryTree(current2, JSCompiler_temp, renderLanes2), workInProgress2.memoizedState = SUSPENDED_MARKER, workInProgress2 = showFallback);
- else if (pushPrimaryTreeSuspenseHandler(workInProgress2), isHydrating && console.error("We should not be hydrating here. This is a bug in React. Please file a bug."), isSuspenseInstanceFallback(nextInstance))
- nextInstance = getSuspenseInstanceFallbackErrorDetails(nextInstance), JSCompiler_temp = nextInstance.digest, showFallback = nextInstance.message, nextProps = nextInstance.stack, nextInstance = nextInstance.componentStack, showFallback = showFallback ? Error(showFallback) : Error("The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering."), showFallback.stack = nextProps || "", showFallback.digest = JSCompiler_temp, JSCompiler_temp = nextInstance === undefined ? null : nextInstance, nextProps = {
- value: showFallback,
- source: null,
- stack: JSCompiler_temp
- }, typeof JSCompiler_temp === "string" && CapturedStacks.set(showFallback, nextProps), queueHydrationError(nextProps), workInProgress2 = retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2);
- else if (didReceiveUpdate || propagateParentContextChanges(current2, workInProgress2, renderLanes2, false), JSCompiler_temp = (renderLanes2 & current2.childLanes) !== 0, didReceiveUpdate || JSCompiler_temp) {
- JSCompiler_temp = workInProgressRoot;
- if (JSCompiler_temp !== null) {
- nextProps = renderLanes2 & -renderLanes2;
- if ((nextProps & 42) !== 0)
- nextProps = 1;
- else
- switch (nextProps) {
- case 2:
- nextProps = 1;
- break;
- case 8:
- nextProps = 4;
- break;
- case 32:
- nextProps = 16;
- break;
- case 128:
- case 256:
- case 512:
- case 1024:
- case 2048:
- case 4096:
- case 8192:
- case 16384:
- case 32768:
- case 65536:
- case 131072:
- case 262144:
- case 524288:
- case 1048576:
- case 2097152:
- case 4194304:
- case 8388608:
- case 16777216:
- case 33554432:
- nextProps = 64;
- break;
- case 268435456:
- nextProps = 134217728;
- break;
- default:
- nextProps = 0;
- }
- nextProps = (nextProps & (JSCompiler_temp.suspendedLanes | renderLanes2)) !== 0 ? 0 : nextProps;
- if (nextProps !== 0 && nextProps !== JSCompiler_temp$jscomp$0.retryLane)
- throw JSCompiler_temp$jscomp$0.retryLane = nextProps, enqueueConcurrentRenderForLane(current2, nextProps), scheduleUpdateOnFiber(JSCompiler_temp, current2, nextProps), SelectiveHydrationException;
- }
- isSuspenseInstancePending(nextInstance) || renderDidSuspendDelayIfPossible();
- workInProgress2 = retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2);
- } else
- isSuspenseInstancePending(nextInstance) ? (workInProgress2.flags |= 128, workInProgress2.child = current2.child, workInProgress2 = retryDehydratedSuspenseBoundary.bind(null, current2), registerSuspenseInstanceRetry(nextInstance, workInProgress2), workInProgress2 = null) : (current2 = JSCompiler_temp$jscomp$0.treeContext, supportsHydration && (nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(nextInstance), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, rootOrSingletonContext = false, current2 !== null && (warnIfNotHydrating(), idStack[idStackIndex++] = treeContextId, idStack[idStackIndex++] = treeContextOverflow, idStack[idStackIndex++] = treeContextProvider, treeContextId = current2.id, treeContextOverflow = current2.overflow, treeContextProvider = workInProgress2)), workInProgress2 = mountSuspensePrimaryChildren(workInProgress2, nextProps.children), workInProgress2.flags |= 4096);
- return workInProgress2;
- }
- if (showFallback)
- return reuseSuspenseHandlerOnStack(workInProgress2), showFallback = nextProps.fallback, nextInstance = workInProgress2.mode, JSCompiler_temp$jscomp$0 = current2.child, didSuspend = JSCompiler_temp$jscomp$0.sibling, nextProps = createWorkInProgress(JSCompiler_temp$jscomp$0, {
- mode: "hidden",
- children: nextProps.children
- }), nextProps.subtreeFlags = JSCompiler_temp$jscomp$0.subtreeFlags & 31457280, didSuspend !== null ? showFallback = createWorkInProgress(didSuspend, showFallback) : (showFallback = createFiberFromFragment(showFallback, nextInstance, renderLanes2, null), showFallback.flags |= 2), showFallback.return = workInProgress2, nextProps.return = workInProgress2, nextProps.sibling = showFallback, workInProgress2.child = nextProps, nextProps = showFallback, showFallback = workInProgress2.child, nextInstance = current2.child.memoizedState, nextInstance === null ? nextInstance = mountSuspenseOffscreenState(renderLanes2) : (JSCompiler_temp$jscomp$0 = nextInstance.cachePool, JSCompiler_temp$jscomp$0 !== null ? (didSuspend = isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2, JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0.parent !== didSuspend ? { parent: didSuspend, pool: didSuspend } : JSCompiler_temp$jscomp$0) : JSCompiler_temp$jscomp$0 = getSuspendedCache(), nextInstance = {
- baseLanes: nextInstance.baseLanes | renderLanes2,
- cachePool: JSCompiler_temp$jscomp$0
- }), showFallback.memoizedState = nextInstance, showFallback.childLanes = getRemainingWorkInPrimaryTree(current2, JSCompiler_temp, renderLanes2), workInProgress2.memoizedState = SUSPENDED_MARKER, nextProps;
- pushPrimaryTreeSuspenseHandler(workInProgress2);
- renderLanes2 = current2.child;
- current2 = renderLanes2.sibling;
- renderLanes2 = createWorkInProgress(renderLanes2, {
- mode: "visible",
- children: nextProps.children
- });
- renderLanes2.return = workInProgress2;
- renderLanes2.sibling = null;
- current2 !== null && (JSCompiler_temp = workInProgress2.deletions, JSCompiler_temp === null ? (workInProgress2.deletions = [current2], workInProgress2.flags |= 16) : JSCompiler_temp.push(current2));
- workInProgress2.child = renderLanes2;
- workInProgress2.memoizedState = null;
- return renderLanes2;
- }
- function mountSuspensePrimaryChildren(workInProgress2, primaryChildren) {
- primaryChildren = mountWorkInProgressOffscreenFiber({ mode: "visible", children: primaryChildren }, workInProgress2.mode);
- primaryChildren.return = workInProgress2;
- return workInProgress2.child = primaryChildren;
- }
- function mountWorkInProgressOffscreenFiber(offscreenProps, mode) {
- return createFiberFromOffscreen(offscreenProps, mode, 0, null);
- }
- function retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2) {
- reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
- current2 = mountSuspensePrimaryChildren(workInProgress2, workInProgress2.pendingProps.children);
- current2.flags |= 2;
- workInProgress2.memoizedState = null;
- return current2;
- }
- function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) {
- fiber.lanes |= renderLanes2;
- var alternate = fiber.alternate;
- alternate !== null && (alternate.lanes |= renderLanes2);
- scheduleContextWorkOnParentPath(fiber.return, renderLanes2, propagationRoot);
- }
- function validateSuspenseListNestedChild(childSlot, index2) {
- var isAnArray = isArrayImpl(childSlot);
- childSlot = !isAnArray && typeof getIteratorFn(childSlot) === "function";
- return isAnArray || childSlot ? (isAnArray = isAnArray ? "array" : "iterable", console.error("A nested %s was passed to row #%s in . Wrap it in an additional SuspenseList to configure its revealOrder: ... {%s} ... ", isAnArray, index2, isAnArray), false) : true;
- }
- function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode) {
- var renderState = workInProgress2.memoizedState;
- renderState === null ? workInProgress2.memoizedState = {
- isBackwards,
- rendering: null,
- renderingStartTime: 0,
- last: lastContentRow,
- tail,
- tailMode
- } : (renderState.isBackwards = isBackwards, renderState.rendering = null, renderState.renderingStartTime = 0, renderState.last = lastContentRow, renderState.tail = tail, renderState.tailMode = tailMode);
- }
- function updateSuspenseListComponent(current2, workInProgress2, renderLanes2) {
- var nextProps = workInProgress2.pendingProps, revealOrder = nextProps.revealOrder, tailMode = nextProps.tail;
- nextProps = nextProps.children;
- if (revealOrder !== undefined && revealOrder !== "forwards" && revealOrder !== "backwards" && revealOrder !== "together" && !didWarnAboutRevealOrder[revealOrder])
- if (didWarnAboutRevealOrder[revealOrder] = true, typeof revealOrder === "string")
- switch (revealOrder.toLowerCase()) {
- case "together":
- case "forwards":
- case "backwards":
- console.error('"%s" is not a valid value for revealOrder on . Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
- break;
- case "forward":
- case "backward":
- console.error('"%s" is not a valid value for revealOrder on . React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());
- break;
- default:
- console.error('"%s" is not a supported revealOrder on . Did you mean "together", "forwards" or "backwards"?', revealOrder);
- }
- else
- console.error('%s is not a supported value for revealOrder on . Did you mean "together", "forwards" or "backwards"?', revealOrder);
- tailMode === undefined || didWarnAboutTailOptions[tailMode] || (tailMode !== "collapsed" && tailMode !== "hidden" ? (didWarnAboutTailOptions[tailMode] = true, console.error('"%s" is not a supported value for tail on . Did you mean "collapsed" or "hidden"?', tailMode)) : revealOrder !== "forwards" && revealOrder !== "backwards" && (didWarnAboutTailOptions[tailMode] = true, console.error(' is only valid if revealOrder is "forwards" or "backwards". Did you mean to specify revealOrder="forwards"?', tailMode)));
- a:
- if ((revealOrder === "forwards" || revealOrder === "backwards") && nextProps !== undefined && nextProps !== null && nextProps !== false)
- if (isArrayImpl(nextProps))
- for (var i5 = 0;i5 < nextProps.length; i5++) {
- if (!validateSuspenseListNestedChild(nextProps[i5], i5))
- break a;
- }
- else if (i5 = getIteratorFn(nextProps), typeof i5 === "function") {
- if (i5 = i5.call(nextProps))
- for (var step = i5.next(), _i3 = 0;!step.done; step = i5.next()) {
- if (!validateSuspenseListNestedChild(step.value, _i3))
- break a;
- _i3++;
- }
- } else
- console.error('A single row was passed to a . This is not useful since it needs multiple rows. Did you mean to pass multiple children or an array?', revealOrder);
- reconcileChildren(current2, workInProgress2, nextProps, renderLanes2);
- nextProps = suspenseStackCursor.current;
- if ((nextProps & ForceSuspenseFallback) !== 0)
- nextProps = nextProps & SubtreeSuspenseContextMask | ForceSuspenseFallback, workInProgress2.flags |= 128;
- else {
- if (current2 !== null && (current2.flags & 128) !== 0)
- a:
- for (current2 = workInProgress2.child;current2 !== null; ) {
- if (current2.tag === 13)
- current2.memoizedState !== null && scheduleSuspenseWorkOnFiber(current2, renderLanes2, workInProgress2);
- else if (current2.tag === 19)
- scheduleSuspenseWorkOnFiber(current2, renderLanes2, workInProgress2);
- else if (current2.child !== null) {
- current2.child.return = current2;
- current2 = current2.child;
- continue;
- }
- if (current2 === workInProgress2)
- break a;
- for (;current2.sibling === null; ) {
- if (current2.return === null || current2.return === workInProgress2)
- break a;
- current2 = current2.return;
- }
- current2.sibling.return = current2.return;
- current2 = current2.sibling;
- }
- nextProps &= SubtreeSuspenseContextMask;
- }
- push(suspenseStackCursor, nextProps, workInProgress2);
- switch (revealOrder) {
- case "forwards":
- renderLanes2 = workInProgress2.child;
- for (revealOrder = null;renderLanes2 !== null; )
- current2 = renderLanes2.alternate, current2 !== null && findFirstSuspended(current2) === null && (revealOrder = renderLanes2), renderLanes2 = renderLanes2.sibling;
- renderLanes2 = revealOrder;
- renderLanes2 === null ? (revealOrder = workInProgress2.child, workInProgress2.child = null) : (revealOrder = renderLanes2.sibling, renderLanes2.sibling = null);
- initSuspenseListRenderState(workInProgress2, false, revealOrder, renderLanes2, tailMode);
- break;
- case "backwards":
- renderLanes2 = null;
- revealOrder = workInProgress2.child;
- for (workInProgress2.child = null;revealOrder !== null; ) {
- current2 = revealOrder.alternate;
- if (current2 !== null && findFirstSuspended(current2) === null) {
- workInProgress2.child = revealOrder;
- break;
- }
- current2 = revealOrder.sibling;
- revealOrder.sibling = renderLanes2;
- renderLanes2 = revealOrder;
- revealOrder = current2;
- }
- initSuspenseListRenderState(workInProgress2, true, renderLanes2, null, tailMode);
- break;
- case "together":
- initSuspenseListRenderState(workInProgress2, false, null, null, undefined);
- break;
- default:
- workInProgress2.memoizedState = null;
- }
- return workInProgress2.child;
- }
- function bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2) {
- current2 !== null && (workInProgress2.dependencies = current2.dependencies);
- profilerStartTime = -1;
- workInProgressRootSkippedLanes |= workInProgress2.lanes;
- if ((renderLanes2 & workInProgress2.childLanes) === 0)
- if (current2 !== null) {
- if (propagateParentContextChanges(current2, workInProgress2, renderLanes2, false), (renderLanes2 & workInProgress2.childLanes) === 0)
- return null;
- } else
- return null;
- if (current2 !== null && workInProgress2.child !== current2.child)
- throw Error("Resuming work not yet implemented.");
- if (workInProgress2.child !== null) {
- current2 = workInProgress2.child;
- renderLanes2 = createWorkInProgress(current2, current2.pendingProps);
- workInProgress2.child = renderLanes2;
- for (renderLanes2.return = workInProgress2;current2.sibling !== null; )
- current2 = current2.sibling, renderLanes2 = renderLanes2.sibling = createWorkInProgress(current2, current2.pendingProps), renderLanes2.return = workInProgress2;
- renderLanes2.sibling = null;
- }
- return workInProgress2.child;
- }
- function checkScheduledUpdateOrContext(current2, renderLanes2) {
- if ((current2.lanes & renderLanes2) !== 0)
- return true;
- current2 = current2.dependencies;
- return current2 !== null && checkIfContextChanged(current2) ? true : false;
- }
- function attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2) {
- switch (workInProgress2.tag) {
- case 3:
- pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
- pushProvider(workInProgress2, CacheContext, current2.memoizedState.cache);
- resetHydrationState();
- break;
- case 27:
- case 5:
- pushHostContext(workInProgress2);
- break;
- case 4:
- pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
- break;
- case 10:
- pushProvider(workInProgress2, workInProgress2.type, workInProgress2.memoizedProps.value);
- break;
- case 12:
- (renderLanes2 & workInProgress2.childLanes) !== 0 && (workInProgress2.flags |= 4);
- workInProgress2.flags |= 2048;
- var stateNode = workInProgress2.stateNode;
- stateNode.effectDuration = -0;
- stateNode.passiveEffectDuration = -0;
- break;
- case 13:
- stateNode = workInProgress2.memoizedState;
- if (stateNode !== null) {
- if (stateNode.dehydrated !== null)
- return pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags |= 128, null;
- if ((renderLanes2 & workInProgress2.child.childLanes) !== 0)
- return updateSuspenseComponent(current2, workInProgress2, renderLanes2);
- pushPrimaryTreeSuspenseHandler(workInProgress2);
- current2 = bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
- return current2 !== null ? current2.sibling : null;
- }
- pushPrimaryTreeSuspenseHandler(workInProgress2);
- break;
- case 19:
- var didSuspendBefore = (current2.flags & 128) !== 0;
- stateNode = (renderLanes2 & workInProgress2.childLanes) !== 0;
- stateNode || (propagateParentContextChanges(current2, workInProgress2, renderLanes2, false), stateNode = (renderLanes2 & workInProgress2.childLanes) !== 0);
- if (didSuspendBefore) {
- if (stateNode)
- return updateSuspenseListComponent(current2, workInProgress2, renderLanes2);
- workInProgress2.flags |= 128;
- }
- didSuspendBefore = workInProgress2.memoizedState;
- didSuspendBefore !== null && (didSuspendBefore.rendering = null, didSuspendBefore.tail = null, didSuspendBefore.lastEffect = null);
- push(suspenseStackCursor, suspenseStackCursor.current, workInProgress2);
- if (stateNode)
- break;
- else
- return null;
- case 22:
- case 23:
- return workInProgress2.lanes = 0, updateOffscreenComponent(current2, workInProgress2, renderLanes2);
- case 24:
- pushProvider(workInProgress2, CacheContext, current2.memoizedState.cache);
- }
- return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
- }
- function beginWork(current2, workInProgress2, renderLanes2) {
- if (workInProgress2._debugNeedsRemount && current2 !== null) {
- renderLanes2 = createFiberFromTypeAndProps(workInProgress2.type, workInProgress2.key, workInProgress2.pendingProps, workInProgress2._debugOwner || null, workInProgress2.mode, workInProgress2.lanes);
- var returnFiber = workInProgress2.return;
- if (returnFiber === null)
- throw Error("Cannot swap the root fiber.");
- current2.alternate = null;
- workInProgress2.alternate = null;
- renderLanes2.index = workInProgress2.index;
- renderLanes2.sibling = workInProgress2.sibling;
- renderLanes2.return = workInProgress2.return;
- renderLanes2.ref = workInProgress2.ref;
- renderLanes2._debugInfo = workInProgress2._debugInfo;
- if (workInProgress2 === returnFiber.child)
- returnFiber.child = renderLanes2;
- else {
- var prevSibling = returnFiber.child;
- if (prevSibling === null)
- throw Error("Expected parent to have a child.");
- for (;prevSibling.sibling !== workInProgress2; )
- if (prevSibling = prevSibling.sibling, prevSibling === null)
- throw Error("Expected to find the previous sibling.");
- prevSibling.sibling = renderLanes2;
- }
- workInProgress2 = returnFiber.deletions;
- workInProgress2 === null ? (returnFiber.deletions = [current2], returnFiber.flags |= 16) : workInProgress2.push(current2);
- renderLanes2.flags |= 2;
- return renderLanes2;
- }
- if (current2 !== null)
- if (current2.memoizedProps !== workInProgress2.pendingProps || workInProgress2.type !== current2.type)
- didReceiveUpdate = true;
- else {
- if (!checkScheduledUpdateOrContext(current2, renderLanes2) && (workInProgress2.flags & 128) === 0)
- return didReceiveUpdate = false, attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2);
- didReceiveUpdate = (current2.flags & 131072) !== 0 ? true : false;
- }
- else {
- didReceiveUpdate = false;
- if (returnFiber = isHydrating)
- warnIfNotHydrating(), returnFiber = (workInProgress2.flags & 1048576) !== 0;
- returnFiber && (returnFiber = workInProgress2.index, warnIfNotHydrating(), pushTreeId(workInProgress2, treeForkCount, returnFiber));
- }
- workInProgress2.lanes = 0;
- switch (workInProgress2.tag) {
- case 16:
- a:
- if (returnFiber = workInProgress2.pendingProps, current2 = callLazyInitInDEV(workInProgress2.elementType), workInProgress2.type = current2, typeof current2 === "function")
- shouldConstruct(current2) ? (returnFiber = resolveClassComponentProps(current2, returnFiber), workInProgress2.tag = 1, workInProgress2.type = current2 = resolveFunctionForHotReloading(current2), workInProgress2 = updateClassComponent(null, workInProgress2, current2, returnFiber, renderLanes2)) : (workInProgress2.tag = 0, validateFunctionComponentInDev(workInProgress2, current2), workInProgress2.type = current2 = resolveFunctionForHotReloading(current2), workInProgress2 = updateFunctionComponent(null, workInProgress2, current2, returnFiber, renderLanes2));
- else {
- if (current2 !== undefined && current2 !== null) {
- if (prevSibling = current2.$$typeof, prevSibling === REACT_FORWARD_REF_TYPE) {
- workInProgress2.tag = 11;
- workInProgress2.type = current2 = resolveForwardRefForHotReloading(current2);
- workInProgress2 = updateForwardRef(null, workInProgress2, current2, returnFiber, renderLanes2);
- break a;
- } else if (prevSibling === REACT_MEMO_TYPE) {
- workInProgress2.tag = 14;
- workInProgress2 = updateMemoComponent(null, workInProgress2, current2, returnFiber, renderLanes2);
- break a;
- }
- }
- workInProgress2 = "";
- current2 !== null && typeof current2 === "object" && current2.$$typeof === REACT_LAZY_TYPE && (workInProgress2 = " Did you wrap a component in React.lazy() more than once?");
- current2 = getComponentNameFromType(current2) || current2;
- throw Error("Element type is invalid. Received a promise that resolves to: " + current2 + ". Lazy element type must resolve to a class or function." + workInProgress2);
- }
- return workInProgress2;
- case 0:
- return updateFunctionComponent(current2, workInProgress2, workInProgress2.type, workInProgress2.pendingProps, renderLanes2);
- case 1:
- return returnFiber = workInProgress2.type, prevSibling = resolveClassComponentProps(returnFiber, workInProgress2.pendingProps), updateClassComponent(current2, workInProgress2, returnFiber, prevSibling, renderLanes2);
- case 3:
- a: {
- pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
- if (current2 === null)
- throw Error("Should have a current fiber. This is a bug in React.");
- var nextProps = workInProgress2.pendingProps;
- prevSibling = workInProgress2.memoizedState;
- returnFiber = prevSibling.element;
- cloneUpdateQueue(current2, workInProgress2);
- processUpdateQueue(workInProgress2, nextProps, null, renderLanes2);
- var nextState = workInProgress2.memoizedState;
- nextProps = nextState.cache;
- pushProvider(workInProgress2, CacheContext, nextProps);
- nextProps !== prevSibling.cache && propagateContextChanges(workInProgress2, [CacheContext], renderLanes2, true);
- suspendIfUpdateReadFromEntangledAsyncAction();
- nextProps = nextState.element;
- if (supportsHydration && prevSibling.isDehydrated)
- if (prevSibling = {
- element: nextProps,
- isDehydrated: false,
- cache: nextState.cache
- }, workInProgress2.updateQueue.baseState = prevSibling, workInProgress2.memoizedState = prevSibling, workInProgress2.flags & 256) {
- workInProgress2 = mountHostRootWithoutHydrating(current2, workInProgress2, nextProps, renderLanes2);
- break a;
- } else if (nextProps !== returnFiber) {
- returnFiber = createCapturedValueAtFiber(Error("This root received an early update, before anything was able hydrate. Switched the entire root to client rendering."), workInProgress2);
- queueHydrationError(returnFiber);
- workInProgress2 = mountHostRootWithoutHydrating(current2, workInProgress2, nextProps, renderLanes2);
- break a;
- } else
- for (supportsHydration && (nextHydratableInstance = getFirstHydratableChildWithinContainer(workInProgress2.stateNode.containerInfo), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, rootOrSingletonContext = true), current2 = mountChildFibers(workInProgress2, null, nextProps, renderLanes2), workInProgress2.child = current2;current2; )
- current2.flags = current2.flags & -3 | 4096, current2 = current2.sibling;
- else {
- resetHydrationState();
- if (nextProps === returnFiber) {
- workInProgress2 = bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
- break a;
- }
- reconcileChildren(current2, workInProgress2, nextProps, renderLanes2);
- }
- workInProgress2 = workInProgress2.child;
- }
- return workInProgress2;
- case 26:
- if (supportsResources)
- return markRef(current2, workInProgress2), current2 === null ? (current2 = getResource(workInProgress2.type, null, workInProgress2.pendingProps, null)) ? workInProgress2.memoizedState = current2 : isHydrating || (workInProgress2.stateNode = createHoistableInstance(workInProgress2.type, workInProgress2.pendingProps, requiredContext(rootInstanceStackCursor.current), workInProgress2)) : workInProgress2.memoizedState = getResource(workInProgress2.type, current2.memoizedProps, workInProgress2.pendingProps, current2.memoizedState), null;
- case 27:
- if (supportsSingletons)
- return pushHostContext(workInProgress2), current2 === null && supportsSingletons && isHydrating && (prevSibling = requiredContext(rootInstanceStackCursor.current), returnFiber = getHostContext(), prevSibling = workInProgress2.stateNode = resolveSingletonInstance(workInProgress2.type, workInProgress2.pendingProps, prevSibling, returnFiber, false), didSuspendOrErrorDEV || (returnFiber = diffHydratedPropsForDevWarnings(prevSibling, workInProgress2.type, workInProgress2.pendingProps, returnFiber), returnFiber !== null && (buildHydrationDiffNode(workInProgress2, 0).serverProps = returnFiber)), hydrationParentFiber = workInProgress2, rootOrSingletonContext = true, nextHydratableInstance = getFirstHydratableChild(prevSibling)), returnFiber = workInProgress2.pendingProps.children, current2 !== null || isHydrating ? reconcileChildren(current2, workInProgress2, returnFiber, renderLanes2) : workInProgress2.child = reconcileChildFibers(workInProgress2, null, returnFiber, renderLanes2), markRef(current2, workInProgress2), workInProgress2.child;
- case 5:
- return current2 === null && isHydrating && (nextProps = getHostContext(), returnFiber = validateHydratableInstance(workInProgress2.type, workInProgress2.pendingProps, nextProps), prevSibling = nextHydratableInstance, (nextState = !prevSibling) || (nextState = canHydrateInstance(prevSibling, workInProgress2.type, workInProgress2.pendingProps, rootOrSingletonContext), nextState !== null ? (workInProgress2.stateNode = nextState, didSuspendOrErrorDEV || (nextProps = diffHydratedPropsForDevWarnings(nextState, workInProgress2.type, workInProgress2.pendingProps, nextProps), nextProps !== null && (buildHydrationDiffNode(workInProgress2, 0).serverProps = nextProps)), hydrationParentFiber = workInProgress2, nextHydratableInstance = getFirstHydratableChild(nextState), rootOrSingletonContext = false, nextProps = true) : nextProps = false, nextState = !nextProps), nextState && (returnFiber && warnNonHydratedInstance(workInProgress2, prevSibling), throwOnHydrationMismatch(workInProgress2))), pushHostContext(workInProgress2), prevSibling = workInProgress2.type, nextProps = workInProgress2.pendingProps, nextState = current2 !== null ? current2.memoizedProps : null, returnFiber = nextProps.children, shouldSetTextContent(prevSibling, nextProps) ? returnFiber = null : nextState !== null && shouldSetTextContent(prevSibling, nextState) && (workInProgress2.flags |= 32), workInProgress2.memoizedState !== null && (prevSibling = renderWithHooks(current2, workInProgress2, TransitionAwareHostComponent, null, null, renderLanes2), isPrimaryRenderer ? HostTransitionContext._currentValue = prevSibling : HostTransitionContext._currentValue2 = prevSibling), markRef(current2, workInProgress2), reconcileChildren(current2, workInProgress2, returnFiber, renderLanes2), workInProgress2.child;
- case 6:
- return current2 === null && isHydrating && (current2 = workInProgress2.pendingProps, renderLanes2 = getHostContext(), current2 = validateHydratableTextInstance(current2, renderLanes2), renderLanes2 = nextHydratableInstance, (returnFiber = !renderLanes2) || (returnFiber = canHydrateTextInstance(renderLanes2, workInProgress2.pendingProps, rootOrSingletonContext), returnFiber !== null ? (workInProgress2.stateNode = returnFiber, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, returnFiber = true) : returnFiber = false, returnFiber = !returnFiber), returnFiber && (current2 && warnNonHydratedInstance(workInProgress2, renderLanes2), throwOnHydrationMismatch(workInProgress2))), null;
- case 13:
- return updateSuspenseComponent(current2, workInProgress2, renderLanes2);
- case 4:
- return pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo), returnFiber = workInProgress2.pendingProps, current2 === null ? workInProgress2.child = reconcileChildFibers(workInProgress2, null, returnFiber, renderLanes2) : reconcileChildren(current2, workInProgress2, returnFiber, renderLanes2), workInProgress2.child;
- case 11:
- return updateForwardRef(current2, workInProgress2, workInProgress2.type, workInProgress2.pendingProps, renderLanes2);
- case 7:
- return reconcileChildren(current2, workInProgress2, workInProgress2.pendingProps, renderLanes2), workInProgress2.child;
- case 8:
- return reconcileChildren(current2, workInProgress2, workInProgress2.pendingProps.children, renderLanes2), workInProgress2.child;
- case 12:
- return workInProgress2.flags |= 4, workInProgress2.flags |= 2048, returnFiber = workInProgress2.stateNode, returnFiber.effectDuration = -0, returnFiber.passiveEffectDuration = -0, reconcileChildren(current2, workInProgress2, workInProgress2.pendingProps.children, renderLanes2), workInProgress2.child;
- case 10:
- return returnFiber = workInProgress2.type, prevSibling = workInProgress2.pendingProps, nextProps = prevSibling.value, "value" in prevSibling || hasWarnedAboutUsingNoValuePropOnContextProvider || (hasWarnedAboutUsingNoValuePropOnContextProvider = true, console.error("The `value` prop is required for the ``. Did you misspell it or forget to pass it?")), pushProvider(workInProgress2, returnFiber, nextProps), reconcileChildren(current2, workInProgress2, prevSibling.children, renderLanes2), workInProgress2.child;
- case 9:
- return prevSibling = workInProgress2.type._context, returnFiber = workInProgress2.pendingProps.children, typeof returnFiber !== "function" && console.error("A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it."), prepareToReadContext(workInProgress2), prevSibling = readContext(prevSibling), markComponentRenderStarted(workInProgress2), returnFiber = callComponentInDEV(returnFiber, prevSibling, undefined), markComponentRenderStopped(), workInProgress2.flags |= 1, reconcileChildren(current2, workInProgress2, returnFiber, renderLanes2), workInProgress2.child;
- case 14:
- return updateMemoComponent(current2, workInProgress2, workInProgress2.type, workInProgress2.pendingProps, renderLanes2);
- case 15:
- return updateSimpleMemoComponent(current2, workInProgress2, workInProgress2.type, workInProgress2.pendingProps, renderLanes2);
- case 19:
- return updateSuspenseListComponent(current2, workInProgress2, renderLanes2);
- case 22:
- return updateOffscreenComponent(current2, workInProgress2, renderLanes2);
- case 24:
- return prepareToReadContext(workInProgress2), returnFiber = readContext(CacheContext), current2 === null ? (prevSibling = peekCacheFromPool(), prevSibling === null && (prevSibling = workInProgressRoot, nextProps = createCache(), prevSibling.pooledCache = nextProps, retainCache(nextProps), nextProps !== null && (prevSibling.pooledCacheLanes |= renderLanes2), prevSibling = nextProps), workInProgress2.memoizedState = {
- parent: returnFiber,
- cache: prevSibling
- }, initializeUpdateQueue(workInProgress2), pushProvider(workInProgress2, CacheContext, prevSibling)) : ((current2.lanes & renderLanes2) !== 0 && (cloneUpdateQueue(current2, workInProgress2), processUpdateQueue(workInProgress2, null, null, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction()), prevSibling = current2.memoizedState, nextProps = workInProgress2.memoizedState, prevSibling.parent !== returnFiber ? (prevSibling = {
- parent: returnFiber,
- cache: returnFiber
- }, workInProgress2.memoizedState = prevSibling, workInProgress2.lanes === 0 && (workInProgress2.memoizedState = workInProgress2.updateQueue.baseState = prevSibling), pushProvider(workInProgress2, CacheContext, returnFiber)) : (returnFiber = nextProps.cache, pushProvider(workInProgress2, CacheContext, returnFiber), returnFiber !== prevSibling.cache && propagateContextChanges(workInProgress2, [CacheContext], renderLanes2, true))), reconcileChildren(current2, workInProgress2, workInProgress2.pendingProps.children, renderLanes2), workInProgress2.child;
- case 29:
- throw workInProgress2.pendingProps;
- }
- throw Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue.");
- }
- function resetContextDependencies() {
- lastContextDependency = currentlyRenderingFiber = null;
- isDisallowedContextReadInDEV = false;
- }
- function pushProvider(providerFiber, context4, nextValue) {
- isPrimaryRenderer ? (push(valueCursor, context4._currentValue, providerFiber), context4._currentValue = nextValue, push(rendererCursorDEV, context4._currentRenderer, providerFiber), context4._currentRenderer !== undefined && context4._currentRenderer !== null && context4._currentRenderer !== rendererSigil && console.error("Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."), context4._currentRenderer = rendererSigil) : (push(valueCursor, context4._currentValue2, providerFiber), context4._currentValue2 = nextValue, push(renderer2CursorDEV, context4._currentRenderer2, providerFiber), context4._currentRenderer2 !== undefined && context4._currentRenderer2 !== null && context4._currentRenderer2 !== rendererSigil && console.error("Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."), context4._currentRenderer2 = rendererSigil);
- }
- function popProvider(context4, providerFiber) {
- var currentValue = valueCursor.current;
- isPrimaryRenderer ? (context4._currentValue = currentValue, currentValue = rendererCursorDEV.current, pop(rendererCursorDEV, providerFiber), context4._currentRenderer = currentValue) : (context4._currentValue2 = currentValue, currentValue = renderer2CursorDEV.current, pop(renderer2CursorDEV, providerFiber), context4._currentRenderer2 = currentValue);
- pop(valueCursor, providerFiber);
- }
- function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) {
- for (;parent !== null; ) {
- var alternate = parent.alternate;
- (parent.childLanes & renderLanes2) !== renderLanes2 ? (parent.childLanes |= renderLanes2, alternate !== null && (alternate.childLanes |= renderLanes2)) : alternate !== null && (alternate.childLanes & renderLanes2) !== renderLanes2 && (alternate.childLanes |= renderLanes2);
- if (parent === propagationRoot)
- break;
- parent = parent.return;
- }
- parent !== propagationRoot && console.error("Expected to find the propagation root when scheduling context work. This error is likely caused by a bug in React. Please file an issue.");
- }
- function propagateContextChanges(workInProgress2, contexts, renderLanes2, forcePropagateEntireTree) {
- var fiber = workInProgress2.child;
- fiber !== null && (fiber.return = workInProgress2);
- for (;fiber !== null; ) {
- var list2 = fiber.dependencies;
- if (list2 !== null) {
- var nextFiber = fiber.child;
- list2 = list2.firstContext;
- a:
- for (;list2 !== null; ) {
- var dependency = list2;
- list2 = fiber;
- for (var i5 = 0;i5 < contexts.length; i5++)
- if (dependency.context === contexts[i5]) {
- list2.lanes |= renderLanes2;
- dependency = list2.alternate;
- dependency !== null && (dependency.lanes |= renderLanes2);
- scheduleContextWorkOnParentPath(list2.return, renderLanes2, workInProgress2);
- forcePropagateEntireTree || (nextFiber = null);
- break a;
- }
- list2 = dependency.next;
- }
- } else if (fiber.tag === 18) {
- nextFiber = fiber.return;
- if (nextFiber === null)
- throw Error("We just came from a parent so we must have had a parent. This is a bug in React.");
- nextFiber.lanes |= renderLanes2;
- list2 = nextFiber.alternate;
- list2 !== null && (list2.lanes |= renderLanes2);
- scheduleContextWorkOnParentPath(nextFiber, renderLanes2, workInProgress2);
- nextFiber = null;
- } else
- nextFiber = fiber.child;
- if (nextFiber !== null)
- nextFiber.return = fiber;
- else
- for (nextFiber = fiber;nextFiber !== null; ) {
- if (nextFiber === workInProgress2) {
- nextFiber = null;
- break;
- }
- fiber = nextFiber.sibling;
- if (fiber !== null) {
- fiber.return = nextFiber.return;
- nextFiber = fiber;
- break;
- }
- nextFiber = nextFiber.return;
- }
- fiber = nextFiber;
- }
- }
- function propagateParentContextChanges(current2, workInProgress2, renderLanes2, forcePropagateEntireTree) {
- current2 = null;
- for (var parent = workInProgress2, isInsidePropagationBailout = false;parent !== null; ) {
- if (!isInsidePropagationBailout) {
- if ((parent.flags & 524288) !== 0)
- isInsidePropagationBailout = true;
- else if ((parent.flags & 262144) !== 0)
- break;
- }
- if (parent.tag === 10) {
- var currentParent = parent.alternate;
- if (currentParent === null)
- throw Error("Should have a current fiber. This is a bug in React.");
- currentParent = currentParent.memoizedProps;
- if (currentParent !== null) {
- var context4 = parent.type;
- objectIs(parent.pendingProps.value, currentParent.value) || (current2 !== null ? current2.push(context4) : current2 = [context4]);
- }
- } else if (parent === hostTransitionProviderCursor.current) {
- currentParent = parent.alternate;
- if (currentParent === null)
- throw Error("Should have a current fiber. This is a bug in React.");
- currentParent.memoizedState.memoizedState !== parent.memoizedState.memoizedState && (current2 !== null ? current2.push(HostTransitionContext) : current2 = [HostTransitionContext]);
- }
- parent = parent.return;
- }
- current2 !== null && propagateContextChanges(workInProgress2, current2, renderLanes2, forcePropagateEntireTree);
- workInProgress2.flags |= 262144;
- }
- function checkIfContextChanged(currentDependencies) {
- for (currentDependencies = currentDependencies.firstContext;currentDependencies !== null; ) {
- var context4 = currentDependencies.context;
- if (!objectIs(isPrimaryRenderer ? context4._currentValue : context4._currentValue2, currentDependencies.memoizedValue))
- return true;
- currentDependencies = currentDependencies.next;
- }
- return false;
- }
- function prepareToReadContext(workInProgress2) {
- currentlyRenderingFiber = workInProgress2;
- lastContextDependency = null;
- workInProgress2 = workInProgress2.dependencies;
- workInProgress2 !== null && (workInProgress2.firstContext = null);
- }
- function readContext(context4) {
- isDisallowedContextReadInDEV && console.error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
- return readContextForConsumer(currentlyRenderingFiber, context4);
- }
- function readContextDuringReconciliation(consumer2, context4) {
- currentlyRenderingFiber === null && prepareToReadContext(consumer2);
- return readContextForConsumer(consumer2, context4);
- }
- function readContextForConsumer(consumer2, context4) {
- var value = isPrimaryRenderer ? context4._currentValue : context4._currentValue2;
- context4 = { context: context4, memoizedValue: value, next: null };
- if (lastContextDependency === null) {
- if (consumer2 === null)
- throw Error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
- lastContextDependency = context4;
- consumer2.dependencies = {
- lanes: 0,
- firstContext: context4,
- _debugThenableState: null
- };
- consumer2.flags |= 524288;
- } else
- lastContextDependency = lastContextDependency.next = context4;
- return value;
- }
- function createCache() {
- return {
- controller: new AbortControllerLocal,
- data: new Map,
- refCount: 0
- };
- }
- function retainCache(cache5) {
- cache5.controller.signal.aborted && console.warn("A cache instance was retained after it was already freed. This likely indicates a bug in React.");
- cache5.refCount++;
- }
- function releaseCache(cache5) {
- cache5.refCount--;
- 0 > cache5.refCount && console.warn("A cache instance was released after it was already freed. This likely indicates a bug in React.");
- cache5.refCount === 0 && scheduleCallback$1(NormalPriority, function() {
- cache5.controller.abort();
- });
- }
- function peekCacheFromPool() {
- var cacheResumedFromPreviousRender = resumedCache.current;
- return cacheResumedFromPreviousRender !== null ? cacheResumedFromPreviousRender : workInProgressRoot.pooledCache;
- }
- function pushTransition(offscreenWorkInProgress, prevCachePool) {
- prevCachePool === null ? push(resumedCache, resumedCache.current, offscreenWorkInProgress) : push(resumedCache, prevCachePool.pool, offscreenWorkInProgress);
- }
- function getSuspendedCache() {
- var cacheFromPool = peekCacheFromPool();
- return cacheFromPool === null ? null : {
- parent: isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2,
- pool: cacheFromPool
- };
- }
- function markUpdate(workInProgress2) {
- workInProgress2.flags |= 4;
- }
- function doesRequireClone(current2, completedWork) {
- if (current2 !== null && current2.child === completedWork.child)
- return false;
- if ((completedWork.flags & 16) !== 0)
- return true;
- for (current2 = completedWork.child;current2 !== null; ) {
- if ((current2.flags & 13878) !== 0 || (current2.subtreeFlags & 13878) !== 0)
- return true;
- current2 = current2.sibling;
- }
- return false;
- }
- function appendAllChildren(parent, workInProgress2, needsVisibilityToggle, isHidden) {
- if (supportsMutation)
- for (needsVisibilityToggle = workInProgress2.child;needsVisibilityToggle !== null; ) {
- if (needsVisibilityToggle.tag === 5 || needsVisibilityToggle.tag === 6)
- appendInitialChild(parent, needsVisibilityToggle.stateNode);
- else if (!(needsVisibilityToggle.tag === 4 || supportsSingletons && needsVisibilityToggle.tag === 27) && needsVisibilityToggle.child !== null) {
- needsVisibilityToggle.child.return = needsVisibilityToggle;
- needsVisibilityToggle = needsVisibilityToggle.child;
- continue;
- }
- if (needsVisibilityToggle === workInProgress2)
- break;
- for (;needsVisibilityToggle.sibling === null; ) {
- if (needsVisibilityToggle.return === null || needsVisibilityToggle.return === workInProgress2)
- return;
- needsVisibilityToggle = needsVisibilityToggle.return;
- }
- needsVisibilityToggle.sibling.return = needsVisibilityToggle.return;
- needsVisibilityToggle = needsVisibilityToggle.sibling;
- }
- else if (supportsPersistence)
- for (var _node = workInProgress2.child;_node !== null; ) {
- if (_node.tag === 5) {
- var instance = _node.stateNode;
- needsVisibilityToggle && isHidden && (instance = cloneHiddenInstance(instance, _node.type, _node.memoizedProps));
- appendInitialChild(parent, instance);
- } else if (_node.tag === 6)
- instance = _node.stateNode, needsVisibilityToggle && isHidden && (instance = cloneHiddenTextInstance(instance, _node.memoizedProps)), appendInitialChild(parent, instance);
- else if (_node.tag !== 4) {
- if (_node.tag === 22 && _node.memoizedState !== null)
- instance = _node.child, instance !== null && (instance.return = _node), appendAllChildren(parent, _node, true, true);
- else if (_node.child !== null) {
- _node.child.return = _node;
- _node = _node.child;
- continue;
- }
- }
- if (_node === workInProgress2)
- break;
- for (;_node.sibling === null; ) {
- if (_node.return === null || _node.return === workInProgress2)
- return;
- _node = _node.return;
- }
- _node.sibling.return = _node.return;
- _node = _node.sibling;
- }
- }
- function appendAllChildrenToContainer(containerChildSet, workInProgress2, needsVisibilityToggle, isHidden) {
- if (supportsPersistence)
- for (var node = workInProgress2.child;node !== null; ) {
- if (node.tag === 5) {
- var instance = node.stateNode;
- needsVisibilityToggle && isHidden && (instance = cloneHiddenInstance(instance, node.type, node.memoizedProps));
- appendChildToContainerChildSet(containerChildSet, instance);
- } else if (node.tag === 6)
- instance = node.stateNode, needsVisibilityToggle && isHidden && (instance = cloneHiddenTextInstance(instance, node.memoizedProps)), appendChildToContainerChildSet(containerChildSet, instance);
- else if (node.tag !== 4) {
- if (node.tag === 22 && node.memoizedState !== null)
- instance = node.child, instance !== null && (instance.return = node), appendAllChildrenToContainer(containerChildSet, node, !(node.memoizedProps !== null && node.memoizedProps.mode === "manual"), true);
- else if (node.child !== null) {
- node.child.return = node;
- node = node.child;
- continue;
- }
- }
- if (node === workInProgress2)
- break;
- for (;node.sibling === null; ) {
- if (node.return === null || node.return === workInProgress2)
- return;
- node = node.return;
- }
- node.sibling.return = node.return;
- node = node.sibling;
- }
- }
- function updateHostContainer(current2, workInProgress2) {
- if (supportsPersistence && doesRequireClone(current2, workInProgress2)) {
- current2 = workInProgress2.stateNode;
- var container = current2.containerInfo, newChildSet = createContainerChildSet();
- appendAllChildrenToContainer(newChildSet, workInProgress2, false, false);
- current2.pendingChildren = newChildSet;
- markUpdate(workInProgress2);
- finalizeContainerChildren(container, newChildSet);
- }
- }
- function updateHostComponent(current2, workInProgress2, type, newProps) {
- if (supportsMutation)
- current2.memoizedProps !== newProps && markUpdate(workInProgress2);
- else if (supportsPersistence) {
- var { stateNode: currentInstance, memoizedProps: _oldProps } = current2;
- if ((current2 = doesRequireClone(current2, workInProgress2)) || _oldProps !== newProps) {
- var currentHostContext = getHostContext();
- _oldProps = cloneInstance(currentInstance, type, _oldProps, newProps, !current2, null);
- _oldProps === currentInstance ? workInProgress2.stateNode = currentInstance : (finalizeInitialChildren(_oldProps, type, newProps, currentHostContext) && markUpdate(workInProgress2), workInProgress2.stateNode = _oldProps, current2 ? appendAllChildren(_oldProps, workInProgress2, false, false) : markUpdate(workInProgress2));
- } else
- workInProgress2.stateNode = currentInstance;
- }
- }
- function preloadInstanceAndSuspendIfNeeded(workInProgress2, type, props) {
- if (maySuspendCommit(type, props)) {
- if (workInProgress2.flags |= 16777216, !preloadInstance(type, props))
- if (shouldRemainOnPreviousScreen())
- workInProgress2.flags |= 8192;
- else
- throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
- } else
- workInProgress2.flags &= -16777217;
- }
- function preloadResourceAndSuspendIfNeeded(workInProgress2, resource) {
- if (mayResourceSuspendCommit(resource)) {
- if (workInProgress2.flags |= 16777216, !preloadResource(resource))
- if (shouldRemainOnPreviousScreen())
- workInProgress2.flags |= 8192;
- else
- throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
- } else
- workInProgress2.flags &= -16777217;
- }
- function scheduleRetryEffect(workInProgress2, retryQueue) {
- retryQueue !== null && (workInProgress2.flags |= 4);
- workInProgress2.flags & 16384 && (retryQueue = workInProgress2.tag !== 22 ? claimNextRetryLane() : 536870912, workInProgress2.lanes |= retryQueue, workInProgressSuspendedRetryLanes |= retryQueue);
- }
- function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
- if (!isHydrating)
- switch (renderState.tailMode) {
- case "hidden":
- hasRenderedATailFallback = renderState.tail;
- for (var lastTailNode = null;hasRenderedATailFallback !== null; )
- hasRenderedATailFallback.alternate !== null && (lastTailNode = hasRenderedATailFallback), hasRenderedATailFallback = hasRenderedATailFallback.sibling;
- lastTailNode === null ? renderState.tail = null : lastTailNode.sibling = null;
- break;
- case "collapsed":
- lastTailNode = renderState.tail;
- for (var _lastTailNode = null;lastTailNode !== null; )
- lastTailNode.alternate !== null && (_lastTailNode = lastTailNode), lastTailNode = lastTailNode.sibling;
- _lastTailNode === null ? hasRenderedATailFallback || renderState.tail === null ? renderState.tail = null : renderState.tail.sibling = null : _lastTailNode.sibling = null;
- }
- }
- function bubbleProperties(completedWork) {
- var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child, newChildLanes = 0, subtreeFlags = 0;
- if (didBailout)
- if ((completedWork.mode & 2) !== NoMode) {
- for (var { selfBaseDuration: _treeBaseDuration, child: _child2 } = completedWork;_child2 !== null; )
- newChildLanes |= _child2.lanes | _child2.childLanes, subtreeFlags |= _child2.subtreeFlags & 31457280, subtreeFlags |= _child2.flags & 31457280, _treeBaseDuration += _child2.treeBaseDuration, _child2 = _child2.sibling;
- completedWork.treeBaseDuration = _treeBaseDuration;
- } else
- for (_treeBaseDuration = completedWork.child;_treeBaseDuration !== null; )
- newChildLanes |= _treeBaseDuration.lanes | _treeBaseDuration.childLanes, subtreeFlags |= _treeBaseDuration.subtreeFlags & 31457280, subtreeFlags |= _treeBaseDuration.flags & 31457280, _treeBaseDuration.return = completedWork, _treeBaseDuration = _treeBaseDuration.sibling;
- else if ((completedWork.mode & 2) !== NoMode) {
- _treeBaseDuration = completedWork.actualDuration;
- _child2 = completedWork.selfBaseDuration;
- for (var child = completedWork.child;child !== null; )
- newChildLanes |= child.lanes | child.childLanes, subtreeFlags |= child.subtreeFlags, subtreeFlags |= child.flags, _treeBaseDuration += child.actualDuration, _child2 += child.treeBaseDuration, child = child.sibling;
- completedWork.actualDuration = _treeBaseDuration;
- completedWork.treeBaseDuration = _child2;
- } else
- for (_treeBaseDuration = completedWork.child;_treeBaseDuration !== null; )
- newChildLanes |= _treeBaseDuration.lanes | _treeBaseDuration.childLanes, subtreeFlags |= _treeBaseDuration.subtreeFlags, subtreeFlags |= _treeBaseDuration.flags, _treeBaseDuration.return = completedWork, _treeBaseDuration = _treeBaseDuration.sibling;
- completedWork.subtreeFlags |= subtreeFlags;
- completedWork.childLanes = newChildLanes;
- return didBailout;
- }
- function completeWork(current2, workInProgress2, renderLanes2) {
- var newProps = workInProgress2.pendingProps;
- popTreeContext(workInProgress2);
- switch (workInProgress2.tag) {
- case 16:
- case 15:
- case 0:
- case 11:
- case 7:
- case 8:
- case 12:
- case 9:
- case 14:
- return bubbleProperties(workInProgress2), null;
- case 1:
- return bubbleProperties(workInProgress2), null;
- case 3:
- renderLanes2 = workInProgress2.stateNode;
- newProps = null;
- current2 !== null && (newProps = current2.memoizedState.cache);
- workInProgress2.memoizedState.cache !== newProps && (workInProgress2.flags |= 2048);
- popProvider(CacheContext, workInProgress2);
- popHostContainer(workInProgress2);
- renderLanes2.pendingContext && (renderLanes2.context = renderLanes2.pendingContext, renderLanes2.pendingContext = null);
- if (current2 === null || current2.child === null)
- popHydrationState(workInProgress2) ? (emitPendingHydrationWarnings(), markUpdate(workInProgress2)) : current2 === null || current2.memoizedState.isDehydrated && (workInProgress2.flags & 256) === 0 || (workInProgress2.flags |= 1024, hydrationErrors !== null && (queueRecoverableErrors(hydrationErrors), hydrationErrors = null));
- updateHostContainer(current2, workInProgress2);
- bubbleProperties(workInProgress2);
- return null;
- case 26:
- if (supportsResources) {
- renderLanes2 = workInProgress2.type;
- var nextResource = workInProgress2.memoizedState;
- current2 === null ? (markUpdate(workInProgress2), nextResource !== null ? (bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(workInProgress2, nextResource)) : (bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(workInProgress2, renderLanes2, newProps))) : nextResource ? nextResource !== current2.memoizedState ? (markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(workInProgress2, nextResource)) : (bubbleProperties(workInProgress2), workInProgress2.flags &= -16777217) : (supportsMutation ? current2.memoizedProps !== newProps && markUpdate(workInProgress2) : updateHostComponent(current2, workInProgress2, renderLanes2, newProps), bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(workInProgress2, renderLanes2, newProps));
- return null;
- }
- case 27:
- if (supportsSingletons) {
- popHostContext(workInProgress2);
- renderLanes2 = requiredContext(rootInstanceStackCursor.current);
- nextResource = workInProgress2.type;
- if (current2 !== null && workInProgress2.stateNode != null)
- supportsMutation ? current2.memoizedProps !== newProps && markUpdate(workInProgress2) : updateHostComponent(current2, workInProgress2, nextResource, newProps);
- else {
- if (!newProps) {
- if (workInProgress2.stateNode === null)
- throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
- bubbleProperties(workInProgress2);
- return null;
- }
- current2 = getHostContext();
- popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2, current2) : (current2 = resolveSingletonInstance(nextResource, newProps, renderLanes2, current2, true), workInProgress2.stateNode = current2, markUpdate(workInProgress2));
- }
- bubbleProperties(workInProgress2);
- return null;
- }
- case 5:
- popHostContext(workInProgress2);
- renderLanes2 = workInProgress2.type;
- if (current2 !== null && workInProgress2.stateNode != null)
- updateHostComponent(current2, workInProgress2, renderLanes2, newProps);
- else {
- if (!newProps) {
- if (workInProgress2.stateNode === null)
- throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
- bubbleProperties(workInProgress2);
- return null;
- }
- current2 = getHostContext();
- popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2, current2) : (nextResource = requiredContext(rootInstanceStackCursor.current), nextResource = createInstance2(renderLanes2, newProps, nextResource, current2, workInProgress2), appendAllChildren(nextResource, workInProgress2, false, false), workInProgress2.stateNode = nextResource, finalizeInitialChildren(nextResource, renderLanes2, newProps, current2) && markUpdate(workInProgress2));
- }
- bubbleProperties(workInProgress2);
- preloadInstanceAndSuspendIfNeeded(workInProgress2, workInProgress2.type, workInProgress2.pendingProps);
- return null;
- case 6:
- if (current2 && workInProgress2.stateNode != null)
- renderLanes2 = current2.memoizedProps, supportsMutation ? renderLanes2 !== newProps && markUpdate(workInProgress2) : supportsPersistence && (renderLanes2 !== newProps ? (current2 = requiredContext(rootInstanceStackCursor.current), renderLanes2 = getHostContext(), workInProgress2.stateNode = createTextInstance(newProps, current2, renderLanes2, workInProgress2), markUpdate(workInProgress2)) : workInProgress2.stateNode = current2.stateNode);
- else {
- if (typeof newProps !== "string" && workInProgress2.stateNode === null)
- throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
- current2 = requiredContext(rootInstanceStackCursor.current);
- renderLanes2 = getHostContext();
- if (popHydrationState(workInProgress2)) {
- if (!supportsHydration)
- throw Error("Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
- current2 = workInProgress2.stateNode;
- renderLanes2 = workInProgress2.memoizedProps;
- nextResource = !didSuspendOrErrorDEV;
- newProps = null;
- var returnFiber = hydrationParentFiber;
- if (returnFiber !== null)
- switch (returnFiber.tag) {
- case 3:
- nextResource && (nextResource = diffHydratedTextForDevWarnings(current2, renderLanes2, newProps), nextResource !== null && (buildHydrationDiffNode(workInProgress2, 0).serverProps = nextResource));
- break;
- case 27:
- case 5:
- newProps = returnFiber.memoizedProps, nextResource && (nextResource = diffHydratedTextForDevWarnings(current2, renderLanes2, newProps), nextResource !== null && (buildHydrationDiffNode(workInProgress2, 0).serverProps = nextResource));
- }
- hydrateTextInstance(current2, renderLanes2, workInProgress2, newProps) || throwOnHydrationMismatch(workInProgress2);
- } else
- workInProgress2.stateNode = createTextInstance(newProps, current2, renderLanes2, workInProgress2);
- }
- bubbleProperties(workInProgress2);
- return null;
- case 13:
- newProps = workInProgress2.memoizedState;
- if (current2 === null || current2.memoizedState !== null && current2.memoizedState.dehydrated !== null) {
- nextResource = popHydrationState(workInProgress2);
- if (newProps !== null && newProps.dehydrated !== null) {
- if (current2 === null) {
- if (!nextResource)
- throw Error("A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.");
- if (!supportsHydration)
- throw Error("Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
- nextResource = workInProgress2.memoizedState;
- nextResource = nextResource !== null ? nextResource.dehydrated : null;
- if (!nextResource)
- throw Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
- hydrateSuspenseInstance(nextResource, workInProgress2);
- bubbleProperties(workInProgress2);
- (workInProgress2.mode & 2) !== NoMode && newProps !== null && (nextResource = workInProgress2.child, nextResource !== null && (workInProgress2.treeBaseDuration -= nextResource.treeBaseDuration));
- } else
- emitPendingHydrationWarnings(), resetHydrationState(), (workInProgress2.flags & 128) === 0 && (workInProgress2.memoizedState = null), workInProgress2.flags |= 4, bubbleProperties(workInProgress2), (workInProgress2.mode & 2) !== NoMode && newProps !== null && (nextResource = workInProgress2.child, nextResource !== null && (workInProgress2.treeBaseDuration -= nextResource.treeBaseDuration));
- nextResource = false;
- } else
- hydrationErrors !== null && (queueRecoverableErrors(hydrationErrors), hydrationErrors = null), nextResource = true;
- if (!nextResource) {
- if (workInProgress2.flags & 256)
- return popSuspenseHandler(workInProgress2), workInProgress2;
- popSuspenseHandler(workInProgress2);
- return null;
- }
- }
- popSuspenseHandler(workInProgress2);
- if ((workInProgress2.flags & 128) !== 0)
- return workInProgress2.lanes = renderLanes2, (workInProgress2.mode & 2) !== NoMode && transferActualDuration(workInProgress2), workInProgress2;
- renderLanes2 = newProps !== null;
- current2 = current2 !== null && current2.memoizedState !== null;
- renderLanes2 && (newProps = workInProgress2.child, nextResource = null, newProps.alternate !== null && newProps.alternate.memoizedState !== null && newProps.alternate.memoizedState.cachePool !== null && (nextResource = newProps.alternate.memoizedState.cachePool.pool), returnFiber = null, newProps.memoizedState !== null && newProps.memoizedState.cachePool !== null && (returnFiber = newProps.memoizedState.cachePool.pool), returnFiber !== nextResource && (newProps.flags |= 2048));
- renderLanes2 !== current2 && renderLanes2 && (workInProgress2.child.flags |= 8192);
- scheduleRetryEffect(workInProgress2, workInProgress2.updateQueue);
- bubbleProperties(workInProgress2);
- (workInProgress2.mode & 2) !== NoMode && renderLanes2 && (current2 = workInProgress2.child, current2 !== null && (workInProgress2.treeBaseDuration -= current2.treeBaseDuration));
- return null;
- case 4:
- return popHostContainer(workInProgress2), updateHostContainer(current2, workInProgress2), current2 === null && preparePortalMount(workInProgress2.stateNode.containerInfo), bubbleProperties(workInProgress2), null;
- case 10:
- return popProvider(workInProgress2.type, workInProgress2), bubbleProperties(workInProgress2), null;
- case 19:
- pop(suspenseStackCursor, workInProgress2);
- nextResource = workInProgress2.memoizedState;
- if (nextResource === null)
- return bubbleProperties(workInProgress2), null;
- newProps = (workInProgress2.flags & 128) !== 0;
- returnFiber = nextResource.rendering;
- if (returnFiber === null)
- if (newProps)
- cutOffTailIfNeeded(nextResource, false);
- else {
- if (workInProgressRootExitStatus !== RootInProgress || current2 !== null && (current2.flags & 128) !== 0)
- for (current2 = workInProgress2.child;current2 !== null; ) {
- returnFiber = findFirstSuspended(current2);
- if (returnFiber !== null) {
- workInProgress2.flags |= 128;
- cutOffTailIfNeeded(nextResource, false);
- current2 = returnFiber.updateQueue;
- workInProgress2.updateQueue = current2;
- scheduleRetryEffect(workInProgress2, current2);
- workInProgress2.subtreeFlags = 0;
- current2 = renderLanes2;
- for (renderLanes2 = workInProgress2.child;renderLanes2 !== null; )
- resetWorkInProgress(renderLanes2, current2), renderLanes2 = renderLanes2.sibling;
- push(suspenseStackCursor, suspenseStackCursor.current & SubtreeSuspenseContextMask | ForceSuspenseFallback, workInProgress2);
- return workInProgress2.child;
- }
- current2 = current2.sibling;
- }
- nextResource.tail !== null && now$1() > workInProgressRootRenderTargetTime && (workInProgress2.flags |= 128, newProps = true, cutOffTailIfNeeded(nextResource, false), workInProgress2.lanes = 4194304);
- }
- else {
- if (!newProps)
- if (current2 = findFirstSuspended(returnFiber), current2 !== null) {
- if (workInProgress2.flags |= 128, newProps = true, current2 = current2.updateQueue, workInProgress2.updateQueue = current2, scheduleRetryEffect(workInProgress2, current2), cutOffTailIfNeeded(nextResource, true), nextResource.tail === null && nextResource.tailMode === "hidden" && !returnFiber.alternate && !isHydrating)
- return bubbleProperties(workInProgress2), null;
- } else
- 2 * now$1() - nextResource.renderingStartTime > workInProgressRootRenderTargetTime && renderLanes2 !== 536870912 && (workInProgress2.flags |= 128, newProps = true, cutOffTailIfNeeded(nextResource, false), workInProgress2.lanes = 4194304);
- nextResource.isBackwards ? (returnFiber.sibling = workInProgress2.child, workInProgress2.child = returnFiber) : (current2 = nextResource.last, current2 !== null ? current2.sibling = returnFiber : workInProgress2.child = returnFiber, nextResource.last = returnFiber);
- }
- if (nextResource.tail !== null)
- return current2 = nextResource.tail, nextResource.rendering = current2, nextResource.tail = current2.sibling, nextResource.renderingStartTime = now$1(), current2.sibling = null, renderLanes2 = suspenseStackCursor.current, renderLanes2 = newProps ? renderLanes2 & SubtreeSuspenseContextMask | ForceSuspenseFallback : renderLanes2 & SubtreeSuspenseContextMask, push(suspenseStackCursor, renderLanes2, workInProgress2), current2;
- bubbleProperties(workInProgress2);
- return null;
- case 22:
- case 23:
- return popSuspenseHandler(workInProgress2), popHiddenContext(workInProgress2), newProps = workInProgress2.memoizedState !== null, current2 !== null ? current2.memoizedState !== null !== newProps && (workInProgress2.flags |= 8192) : newProps && (workInProgress2.flags |= 8192), newProps ? (renderLanes2 & 536870912) !== 0 && (workInProgress2.flags & 128) === 0 && (bubbleProperties(workInProgress2), workInProgress2.subtreeFlags & 6 && (workInProgress2.flags |= 8192)) : bubbleProperties(workInProgress2), renderLanes2 = workInProgress2.updateQueue, renderLanes2 !== null && scheduleRetryEffect(workInProgress2, renderLanes2.retryQueue), renderLanes2 = null, current2 !== null && current2.memoizedState !== null && current2.memoizedState.cachePool !== null && (renderLanes2 = current2.memoizedState.cachePool.pool), newProps = null, workInProgress2.memoizedState !== null && workInProgress2.memoizedState.cachePool !== null && (newProps = workInProgress2.memoizedState.cachePool.pool), newProps !== renderLanes2 && (workInProgress2.flags |= 2048), current2 !== null && pop(resumedCache, workInProgress2), null;
- case 24:
- return renderLanes2 = null, current2 !== null && (renderLanes2 = current2.memoizedState.cache), workInProgress2.memoizedState.cache !== renderLanes2 && (workInProgress2.flags |= 2048), popProvider(CacheContext, workInProgress2), bubbleProperties(workInProgress2), null;
- case 25:
- return null;
- }
- throw Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue.");
- }
- function unwindWork(current2, workInProgress2) {
- popTreeContext(workInProgress2);
- switch (workInProgress2.tag) {
- case 1:
- return current2 = workInProgress2.flags, current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & 2) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
- case 3:
- return popProvider(CacheContext, workInProgress2), popHostContainer(workInProgress2), current2 = workInProgress2.flags, (current2 & 65536) !== 0 && (current2 & 128) === 0 ? (workInProgress2.flags = current2 & -65537 | 128, workInProgress2) : null;
- case 26:
- case 27:
- case 5:
- return popHostContext(workInProgress2), null;
- case 13:
- popSuspenseHandler(workInProgress2);
- current2 = workInProgress2.memoizedState;
- if (current2 !== null && current2.dehydrated !== null) {
- if (workInProgress2.alternate === null)
- throw Error("Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue.");
- resetHydrationState();
- }
- current2 = workInProgress2.flags;
- return current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & 2) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
- case 19:
- return pop(suspenseStackCursor, workInProgress2), null;
- case 4:
- return popHostContainer(workInProgress2), null;
- case 10:
- return popProvider(workInProgress2.type, workInProgress2), null;
- case 22:
- case 23:
- return popSuspenseHandler(workInProgress2), popHiddenContext(workInProgress2), current2 !== null && pop(resumedCache, workInProgress2), current2 = workInProgress2.flags, current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & 2) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
- case 24:
- return popProvider(CacheContext, workInProgress2), null;
- case 25:
- return null;
- default:
- return null;
- }
- }
- function unwindInterruptedWork(current2, interruptedWork) {
- popTreeContext(interruptedWork);
- switch (interruptedWork.tag) {
- case 3:
- popProvider(CacheContext, interruptedWork);
- popHostContainer(interruptedWork);
- break;
- case 26:
- case 27:
- case 5:
- popHostContext(interruptedWork);
- break;
- case 4:
- popHostContainer(interruptedWork);
- break;
- case 13:
- popSuspenseHandler(interruptedWork);
- break;
- case 19:
- pop(suspenseStackCursor, interruptedWork);
- break;
- case 10:
- popProvider(interruptedWork.type, interruptedWork);
- break;
- case 22:
- case 23:
- popSuspenseHandler(interruptedWork);
- popHiddenContext(interruptedWork);
- current2 !== null && pop(resumedCache, interruptedWork);
- break;
- case 24:
- popProvider(CacheContext, interruptedWork);
- }
- }
- function shouldProfile(current2) {
- return (current2.mode & 2) !== NoMode;
- }
- function commitHookLayoutEffects(finishedWork, hookFlags) {
- shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListMount(hookFlags, finishedWork), recordEffectDuration()) : commitHookEffectListMount(hookFlags, finishedWork);
- }
- function commitHookLayoutUnmountEffects(finishedWork, nearestMountedAncestor, hookFlags) {
- shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListUnmount(hookFlags, finishedWork, nearestMountedAncestor), recordEffectDuration()) : commitHookEffectListUnmount(hookFlags, finishedWork, nearestMountedAncestor);
- }
- function commitHookEffectListMount(flags, finishedWork) {
- try {
- var updateQueue = finishedWork.updateQueue, lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
- if (lastEffect !== null) {
- var firstEffect = lastEffect.next;
- updateQueue = firstEffect;
- do {
- if ((updateQueue.tag & flags) === flags && ((flags & Passive) !== NoFlags ? injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === "function" && injectedProfilingHooks.markComponentPassiveEffectMountStarted(finishedWork) : (flags & Layout) !== NoFlags && injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === "function" && injectedProfilingHooks.markComponentLayoutEffectMountStarted(finishedWork), lastEffect = undefined, (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = true), lastEffect = runWithFiberInDEV(finishedWork, callCreateInDEV, updateQueue), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = false), (flags & Passive) !== NoFlags ? injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === "function" && injectedProfilingHooks.markComponentPassiveEffectMountStopped() : (flags & Layout) !== NoFlags && injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === "function" && injectedProfilingHooks.markComponentLayoutEffectMountStopped(), lastEffect !== undefined && typeof lastEffect !== "function")) {
- var hookName = undefined;
- hookName = (updateQueue.tag & Layout) !== 0 ? "useLayoutEffect" : (updateQueue.tag & Insertion) !== 0 ? "useInsertionEffect" : "useEffect";
- var addendum = undefined;
- addendum = lastEffect === null ? " You returned null. If your effect does not require clean up, return undefined (or nothing)." : typeof lastEffect.then === "function" ? `
-
-It looks like you wrote ` + hookName + `(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:
-
-` + hookName + `(() => {
- async function fetchData() {
- // You can await here
- const response = await MyAPI.getData(someId);
- // ...
- }
- fetchData();
-}, [someId]); // Or [] if effect doesn't need props or state
-
-Learn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching` : " You returned: " + lastEffect;
- runWithFiberInDEV(finishedWork, function(n5, a5) {
- console.error("%s must not return anything besides a function, which is used for clean-up.%s", n5, a5);
- }, hookName, addendum);
- }
- updateQueue = updateQueue.next;
- } while (updateQueue !== firstEffect);
- }
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) {
- try {
- var updateQueue = finishedWork.updateQueue, lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
- if (lastEffect !== null) {
- var firstEffect = lastEffect.next;
- updateQueue = firstEffect;
- do {
- if ((updateQueue.tag & flags) === flags) {
- var inst = updateQueue.inst, destroy2 = inst.destroy;
- destroy2 !== undefined && (inst.destroy = undefined, (flags & Passive) !== NoFlags ? injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === "function" && injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(finishedWork) : (flags & Layout) !== NoFlags && injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === "function" && injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(finishedWork), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = true), runWithFiberInDEV(finishedWork, callDestroyInDEV, finishedWork, nearestMountedAncestor, destroy2), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = false), (flags & Passive) !== NoFlags ? injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === "function" && injectedProfilingHooks.markComponentPassiveEffectUnmountStopped() : (flags & Layout) !== NoFlags && injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === "function" && injectedProfilingHooks.markComponentLayoutEffectUnmountStopped());
- }
- updateQueue = updateQueue.next;
- } while (updateQueue !== firstEffect);
- }
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- function commitHookPassiveMountEffects(finishedWork, hookFlags) {
- shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListMount(hookFlags, finishedWork), recordEffectDuration()) : commitHookEffectListMount(hookFlags, finishedWork);
- }
- function commitHookPassiveUnmountEffects(finishedWork, nearestMountedAncestor, hookFlags) {
- shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListUnmount(hookFlags, finishedWork, nearestMountedAncestor), recordEffectDuration()) : commitHookEffectListUnmount(hookFlags, finishedWork, nearestMountedAncestor);
- }
- function commitClassCallbacks(finishedWork) {
- var updateQueue = finishedWork.updateQueue;
- if (updateQueue !== null) {
- var instance = finishedWork.stateNode;
- finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (instance.props !== finishedWork.memoizedProps && console.error("Expected %s props to match memoized props before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"), instance.state !== finishedWork.memoizedState && console.error("Expected %s state to match memoized state before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"));
- try {
- runWithFiberInDEV(finishedWork, commitCallbacks, updateQueue, instance);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- }
- function callGetSnapshotBeforeUpdates(instance, prevProps, prevState) {
- return instance.getSnapshotBeforeUpdate(prevProps, prevState);
- }
- function commitClassSnapshot(finishedWork, current2) {
- var { memoizedProps: prevProps, memoizedState: prevState } = current2;
- current2 = finishedWork.stateNode;
- finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (current2.props !== finishedWork.memoizedProps && console.error("Expected %s props to match memoized props before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"), current2.state !== finishedWork.memoizedState && console.error("Expected %s state to match memoized state before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"));
- try {
- var resolvedPrevProps = resolveClassComponentProps(finishedWork.type, prevProps, finishedWork.elementType === finishedWork.type);
- var snapshot = runWithFiberInDEV(finishedWork, callGetSnapshotBeforeUpdates, current2, resolvedPrevProps, prevState);
- prevProps = didWarnAboutUndefinedSnapshotBeforeUpdate;
- snapshot !== undefined || prevProps.has(finishedWork.type) || (prevProps.add(finishedWork.type), runWithFiberInDEV(finishedWork, function() {
- console.error("%s.getSnapshotBeforeUpdate(): A snapshot value (or null) must be returned. You have returned undefined.", getComponentNameFromFiber(finishedWork));
- }));
- current2.__reactInternalSnapshotBeforeUpdate = snapshot;
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- function safelyCallComponentWillUnmount(current2, nearestMountedAncestor, instance) {
- instance.props = resolveClassComponentProps(current2.type, current2.memoizedProps);
- instance.state = current2.memoizedState;
- shouldProfile(current2) ? (startEffectTimer(), runWithFiberInDEV(current2, callComponentWillUnmountInDEV, current2, nearestMountedAncestor, instance), recordEffectDuration()) : runWithFiberInDEV(current2, callComponentWillUnmountInDEV, current2, nearestMountedAncestor, instance);
- }
- function commitAttachRef(finishedWork) {
- var ref = finishedWork.ref;
- if (ref !== null) {
- var instance = finishedWork.stateNode;
- switch (finishedWork.tag) {
- case 26:
- case 27:
- case 5:
- instance = getPublicInstance(instance);
- }
- if (typeof ref === "function")
- if (shouldProfile(finishedWork))
- try {
- startEffectTimer(), finishedWork.refCleanup = ref(instance);
- } finally {
- recordEffectDuration();
- }
- else
- finishedWork.refCleanup = ref(instance);
- else
- typeof ref === "string" ? console.error("String refs are no longer supported.") : ref.hasOwnProperty("current") || console.error("Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().", getComponentNameFromFiber(finishedWork)), ref.current = instance;
- }
- }
- function safelyAttachRef(current2, nearestMountedAncestor) {
- try {
- runWithFiberInDEV(current2, commitAttachRef, current2);
- } catch (error46) {
- captureCommitPhaseError(current2, nearestMountedAncestor, error46);
- }
- }
- function safelyDetachRef(current2, nearestMountedAncestor) {
- var { ref, refCleanup } = current2;
- if (ref !== null)
- if (typeof refCleanup === "function")
- try {
- if (shouldProfile(current2))
- try {
- startEffectTimer(), runWithFiberInDEV(current2, refCleanup);
- } finally {
- recordEffectDuration(current2);
- }
- else
- runWithFiberInDEV(current2, refCleanup);
- } catch (error46) {
- captureCommitPhaseError(current2, nearestMountedAncestor, error46);
- } finally {
- current2.refCleanup = null, current2 = current2.alternate, current2 != null && (current2.refCleanup = null);
- }
- else if (typeof ref === "function")
- try {
- if (shouldProfile(current2))
- try {
- startEffectTimer(), runWithFiberInDEV(current2, ref, null);
- } finally {
- recordEffectDuration(current2);
- }
- else
- runWithFiberInDEV(current2, ref, null);
- } catch (error$3) {
- captureCommitPhaseError(current2, nearestMountedAncestor, error$3);
- }
- else
- ref.current = null;
- }
- function commitProfiler(finishedWork, current2, commitStartTime2, effectDuration) {
- var _finishedWork$memoize = finishedWork.memoizedProps, id = _finishedWork$memoize.id, onCommit = _finishedWork$memoize.onCommit;
- _finishedWork$memoize = _finishedWork$memoize.onRender;
- current2 = current2 === null ? "mount" : "update";
- currentUpdateIsNested && (current2 = "nested-update");
- typeof _finishedWork$memoize === "function" && _finishedWork$memoize(id, current2, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitStartTime2);
- typeof onCommit === "function" && onCommit(finishedWork.memoizedProps.id, current2, effectDuration, commitStartTime2);
- }
- function commitProfilerPostCommitImpl(finishedWork, current2, commitStartTime2, passiveEffectDuration) {
- var _finishedWork$memoize2 = finishedWork.memoizedProps;
- finishedWork = _finishedWork$memoize2.id;
- _finishedWork$memoize2 = _finishedWork$memoize2.onPostCommit;
- current2 = current2 === null ? "mount" : "update";
- currentUpdateIsNested && (current2 = "nested-update");
- typeof _finishedWork$memoize2 === "function" && _finishedWork$memoize2(finishedWork, current2, passiveEffectDuration, commitStartTime2);
- }
- function commitHostMount(finishedWork) {
- var { type, memoizedProps: props, stateNode: instance } = finishedWork;
- try {
- runWithFiberInDEV(finishedWork, commitMount, instance, type, props, finishedWork);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- function commitHostUpdate(finishedWork, newProps, oldProps) {
- try {
- runWithFiberInDEV(finishedWork, commitUpdate, finishedWork.stateNode, finishedWork.type, oldProps, newProps, finishedWork);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- function isHostParent(fiber) {
- return fiber.tag === 5 || fiber.tag === 3 || (supportsResources ? fiber.tag === 26 : false) || (supportsSingletons ? fiber.tag === 27 : false) || fiber.tag === 4;
- }
- function getHostSibling(fiber) {
- a:
- for (;; ) {
- for (;fiber.sibling === null; ) {
- if (fiber.return === null || isHostParent(fiber.return))
- return null;
- fiber = fiber.return;
- }
- fiber.sibling.return = fiber.return;
- for (fiber = fiber.sibling;fiber.tag !== 5 && fiber.tag !== 6 && (supportsSingletons ? fiber.tag !== 27 : 1) && fiber.tag !== 18; ) {
- if (fiber.flags & 2)
- continue a;
- if (fiber.child === null || fiber.tag === 4)
- continue a;
- else
- fiber.child.return = fiber, fiber = fiber.child;
- }
- if (!(fiber.flags & 2))
- return fiber.stateNode;
- }
- }
- function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
- var tag2 = node.tag;
- if (tag2 === 5 || tag2 === 6)
- node = node.stateNode, before ? insertInContainerBefore(parent, node, before) : appendChildToContainer(parent, node);
- else if (!(tag2 === 4 || supportsSingletons && tag2 === 27) && (node = node.child, node !== null))
- for (insertOrAppendPlacementNodeIntoContainer(node, before, parent), node = node.sibling;node !== null; )
- insertOrAppendPlacementNodeIntoContainer(node, before, parent), node = node.sibling;
- }
- function insertOrAppendPlacementNode(node, before, parent) {
- var tag2 = node.tag;
- if (tag2 === 5 || tag2 === 6)
- node = node.stateNode, before ? insertBefore(parent, node, before) : appendChild(parent, node);
- else if (!(tag2 === 4 || supportsSingletons && tag2 === 27) && (node = node.child, node !== null))
- for (insertOrAppendPlacementNode(node, before, parent), node = node.sibling;node !== null; )
- insertOrAppendPlacementNode(node, before, parent), node = node.sibling;
- }
- function commitPlacement(finishedWork) {
- if (supportsMutation && (!supportsSingletons || finishedWork.tag !== 27)) {
- a: {
- for (var parent = finishedWork.return;parent !== null; ) {
- if (isHostParent(parent)) {
- var parentFiber = parent;
- break a;
- }
- parent = parent.return;
- }
- throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
- }
- switch (parentFiber.tag) {
- case 27:
- if (supportsSingletons) {
- parent = parentFiber.stateNode;
- parentFiber = getHostSibling(finishedWork);
- insertOrAppendPlacementNode(finishedWork, parentFiber, parent);
- break;
- }
- case 5:
- parent = parentFiber.stateNode;
- parentFiber.flags & 32 && (resetTextContent(parent), parentFiber.flags &= -33);
- parentFiber = getHostSibling(finishedWork);
- insertOrAppendPlacementNode(finishedWork, parentFiber, parent);
- break;
- case 3:
- case 4:
- parent = parentFiber.stateNode.containerInfo;
- parentFiber = getHostSibling(finishedWork);
- insertOrAppendPlacementNodeIntoContainer(finishedWork, parentFiber, parent);
- break;
- default:
- throw Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.");
- }
- }
- }
- function commitHostPortalContainerChildren(portal, finishedWork, pendingChildren) {
- portal = portal.containerInfo;
- try {
- runWithFiberInDEV(finishedWork, replaceContainerChildren, portal, pendingChildren);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- function commitBeforeMutationEffects(root2, firstChild) {
- prepareForCommit(root2.containerInfo);
- for (nextEffect = firstChild;nextEffect !== null; )
- if (root2 = nextEffect, firstChild = root2.child, (root2.subtreeFlags & 1028) !== 0 && firstChild !== null)
- firstChild.return = root2, nextEffect = firstChild;
- else
- for (;nextEffect !== null; ) {
- firstChild = root2 = nextEffect;
- var { alternate: current2, flags } = firstChild;
- switch (firstChild.tag) {
- case 0:
- break;
- case 11:
- case 15:
- break;
- case 1:
- (flags & 1024) !== 0 && current2 !== null && commitClassSnapshot(firstChild, current2);
- break;
- case 3:
- (flags & 1024) !== 0 && supportsMutation && clearContainer(firstChild.stateNode.containerInfo);
- break;
- case 5:
- case 26:
- case 27:
- case 6:
- case 4:
- case 17:
- break;
- default:
- if ((flags & 1024) !== 0)
- throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");
- }
- firstChild = root2.sibling;
- if (firstChild !== null) {
- firstChild.return = root2.return;
- nextEffect = firstChild;
- break;
- }
- nextEffect = root2.return;
- }
- root2 = shouldFireAfterActiveInstanceBlur;
- shouldFireAfterActiveInstanceBlur = false;
- return root2;
- }
- function commitLayoutEffectOnFiber(finishedRoot, current2, finishedWork) {
- var flags = finishedWork.flags;
- switch (finishedWork.tag) {
- case 0:
- case 11:
- case 15:
- recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
- flags & 4 && commitHookLayoutEffects(finishedWork, Layout | HasEffect);
- break;
- case 1:
- recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
- if (flags & 4)
- if (finishedRoot = finishedWork.stateNode, current2 === null)
- finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (finishedRoot.props !== finishedWork.memoizedProps && console.error("Expected %s props to match memoized props before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"), finishedRoot.state !== finishedWork.memoizedState && console.error("Expected %s state to match memoized state before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance")), shouldProfile(finishedWork) ? (startEffectTimer(), runWithFiberInDEV(finishedWork, callComponentDidMountInDEV, finishedWork, finishedRoot), recordEffectDuration()) : runWithFiberInDEV(finishedWork, callComponentDidMountInDEV, finishedWork, finishedRoot);
- else {
- var prevProps = resolveClassComponentProps(finishedWork.type, current2.memoizedProps);
- current2 = current2.memoizedState;
- finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (finishedRoot.props !== finishedWork.memoizedProps && console.error("Expected %s props to match memoized props before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"), finishedRoot.state !== finishedWork.memoizedState && console.error("Expected %s state to match memoized state before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance"));
- shouldProfile(finishedWork) ? (startEffectTimer(), runWithFiberInDEV(finishedWork, callComponentDidUpdateInDEV, finishedWork, finishedRoot, prevProps, current2, finishedRoot.__reactInternalSnapshotBeforeUpdate), recordEffectDuration()) : runWithFiberInDEV(finishedWork, callComponentDidUpdateInDEV, finishedWork, finishedRoot, prevProps, current2, finishedRoot.__reactInternalSnapshotBeforeUpdate);
- }
- flags & 64 && commitClassCallbacks(finishedWork);
- flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
- break;
- case 3:
- current2 = pushNestedEffectDurations();
- recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
- if (flags & 64 && (flags = finishedWork.updateQueue, flags !== null)) {
- prevProps = null;
- if (finishedWork.child !== null)
- switch (finishedWork.child.tag) {
- case 27:
- case 5:
- prevProps = getPublicInstance(finishedWork.child.stateNode);
- break;
- case 1:
- prevProps = finishedWork.child.stateNode;
- }
- try {
- runWithFiberInDEV(finishedWork, commitCallbacks, flags, prevProps);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- finishedRoot.effectDuration += popNestedEffectDurations(current2);
- break;
- case 26:
- if (supportsResources) {
- recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
- flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
- break;
- }
- case 27:
- case 5:
- recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
- current2 === null && flags & 4 && commitHostMount(finishedWork);
- flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
- break;
- case 12:
- if (flags & 4) {
- flags = pushNestedEffectDurations();
- recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
- finishedRoot = finishedWork.stateNode;
- finishedRoot.effectDuration += bubbleNestedEffectDurations(flags);
- try {
- runWithFiberInDEV(finishedWork, commitProfiler, finishedWork, current2, commitStartTime, finishedRoot.effectDuration);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- } else
- recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
- break;
- case 13:
- recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
- flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
- break;
- case 22:
- prevProps = finishedWork.memoizedState !== null || offscreenSubtreeIsHidden;
- if (!prevProps) {
- current2 = current2 !== null && current2.memoizedState !== null || offscreenSubtreeWasHidden;
- var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
- offscreenSubtreeIsHidden = prevProps;
- (offscreenSubtreeWasHidden = current2) && !prevOffscreenSubtreeWasHidden ? recursivelyTraverseReappearLayoutEffects(finishedRoot, finishedWork, (finishedWork.subtreeFlags & 8772) !== 0) : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
- offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
- offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
- }
- flags & 512 && (finishedWork.memoizedProps.mode === "manual" ? safelyAttachRef(finishedWork, finishedWork.return) : safelyDetachRef(finishedWork, finishedWork.return));
- break;
- default:
- recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
- }
- }
- function detachFiberAfterEffects(fiber) {
- var alternate = fiber.alternate;
- alternate !== null && (fiber.alternate = null, detachFiberAfterEffects(alternate));
- fiber.child = null;
- fiber.deletions = null;
- fiber.sibling = null;
- fiber.tag === 5 && (alternate = fiber.stateNode, alternate !== null && detachDeletedInstance(alternate));
- fiber.stateNode = null;
- fiber._debugOwner = null;
- fiber.return = null;
- fiber.dependencies = null;
- fiber.memoizedProps = null;
- fiber.memoizedState = null;
- fiber.pendingProps = null;
- fiber.stateNode = null;
- fiber.updateQueue = null;
- }
- function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
- for (parent = parent.child;parent !== null; )
- commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent), parent = parent.sibling;
- }
- function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
- if (injectedHook && typeof injectedHook.onCommitFiberUnmount === "function")
- try {
- injectedHook.onCommitFiberUnmount(rendererID, deletedFiber);
- } catch (err) {
- hasLoggedError || (hasLoggedError = true, console.error("React instrumentation encountered an error: %s", err));
- }
- switch (deletedFiber.tag) {
- case 26:
- if (supportsResources) {
- offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
- recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
- deletedFiber.memoizedState ? releaseResource(deletedFiber.memoizedState) : deletedFiber.stateNode && unmountHoistable(deletedFiber.stateNode);
- break;
- }
- case 27:
- if (supportsSingletons) {
- offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
- var prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer;
- hostParent = deletedFiber.stateNode;
- recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
- releaseSingletonInstance(deletedFiber.stateNode);
- hostParent = prevHostParent;
- hostParentIsContainer = prevHostParentIsContainer;
- break;
- }
- case 5:
- offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
- case 6:
- if (supportsMutation) {
- if (prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer, hostParent = null, recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber), hostParent = prevHostParent, hostParentIsContainer = prevHostParentIsContainer, hostParent !== null)
- if (hostParentIsContainer)
- try {
- runWithFiberInDEV(deletedFiber, removeChildFromContainer, hostParent, deletedFiber.stateNode);
- } catch (error46) {
- captureCommitPhaseError(deletedFiber, nearestMountedAncestor, error46);
- }
- else
- try {
- runWithFiberInDEV(deletedFiber, removeChild, hostParent, deletedFiber.stateNode);
- } catch (error46) {
- captureCommitPhaseError(deletedFiber, nearestMountedAncestor, error46);
- }
- } else
- recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
- break;
- case 18:
- supportsMutation && hostParent !== null && (hostParentIsContainer ? clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode) : clearSuspenseBoundary(hostParent, deletedFiber.stateNode));
- break;
- case 4:
- supportsMutation ? (prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer, hostParent = deletedFiber.stateNode.containerInfo, hostParentIsContainer = true, recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber), hostParent = prevHostParent, hostParentIsContainer = prevHostParentIsContainer) : (supportsPersistence && commitHostPortalContainerChildren(deletedFiber.stateNode, deletedFiber, createContainerChildSet()), recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber));
- break;
- case 0:
- case 11:
- case 14:
- case 15:
- offscreenSubtreeWasHidden || commitHookEffectListUnmount(Insertion, deletedFiber, nearestMountedAncestor);
- offscreenSubtreeWasHidden || commitHookLayoutUnmountEffects(deletedFiber, nearestMountedAncestor, Layout);
- recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
- break;
- case 1:
- offscreenSubtreeWasHidden || (safelyDetachRef(deletedFiber, nearestMountedAncestor), prevHostParent = deletedFiber.stateNode, typeof prevHostParent.componentWillUnmount === "function" && safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, prevHostParent));
- recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
- break;
- case 21:
- recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
- break;
- case 22:
- offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
- offscreenSubtreeWasHidden = (prevHostParent = offscreenSubtreeWasHidden) || deletedFiber.memoizedState !== null;
- recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
- offscreenSubtreeWasHidden = prevHostParent;
- break;
- default:
- recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
- }
- }
- function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
- if (supportsHydration && finishedWork.memoizedState === null && (finishedRoot = finishedWork.alternate, finishedRoot !== null && (finishedRoot = finishedRoot.memoizedState, finishedRoot !== null && (finishedRoot = finishedRoot.dehydrated, finishedRoot !== null))))
- try {
- runWithFiberInDEV(finishedWork, commitHydratedSuspenseInstance, finishedRoot);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- function getRetryCache(finishedWork) {
- switch (finishedWork.tag) {
- case 13:
- case 19:
- var retryCache = finishedWork.stateNode;
- retryCache === null && (retryCache = finishedWork.stateNode = new PossiblyWeakSet);
- return retryCache;
- case 22:
- return finishedWork = finishedWork.stateNode, retryCache = finishedWork._retryCache, retryCache === null && (retryCache = finishedWork._retryCache = new PossiblyWeakSet), retryCache;
- default:
- throw Error("Unexpected Suspense handler tag (" + finishedWork.tag + "). This is a bug in React.");
- }
- }
- function attachSuspenseRetryListeners(finishedWork, wakeables) {
- var retryCache = getRetryCache(finishedWork);
- wakeables.forEach(function(wakeable) {
- var retry8 = resolveRetryWakeable.bind(null, finishedWork, wakeable);
- if (!retryCache.has(wakeable)) {
- retryCache.add(wakeable);
- if (isDevToolsPresent)
- if (inProgressLanes !== null && inProgressRoot !== null)
- restorePendingUpdaters(inProgressRoot, inProgressLanes);
- else
- throw Error("Expected finished root and lanes to be set. This is a bug in React.");
- wakeable.then(retry8, retry8);
- }
- });
- }
- function commitMutationEffects(root2, finishedWork, committedLanes) {
- inProgressLanes = committedLanes;
- inProgressRoot = root2;
- commitMutationEffectsOnFiber(finishedWork, root2);
- inProgressRoot = inProgressLanes = null;
- }
- function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) {
- var deletions = parentFiber.deletions;
- if (deletions !== null)
- for (var i5 = 0;i5 < deletions.length; i5++) {
- var root2 = root$jscomp$0, returnFiber = parentFiber, deletedFiber = deletions[i5];
- if (supportsMutation) {
- var parent = returnFiber;
- a:
- for (;parent !== null; ) {
- switch (parent.tag) {
- case 27:
- case 5:
- hostParent = parent.stateNode;
- hostParentIsContainer = false;
- break a;
- case 3:
- hostParent = parent.stateNode.containerInfo;
- hostParentIsContainer = true;
- break a;
- case 4:
- hostParent = parent.stateNode.containerInfo;
- hostParentIsContainer = true;
- break a;
- }
- parent = parent.return;
- }
- if (hostParent === null)
- throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
- commitDeletionEffectsOnFiber(root2, returnFiber, deletedFiber);
- hostParent = null;
- hostParentIsContainer = false;
- } else
- commitDeletionEffectsOnFiber(root2, returnFiber, deletedFiber);
- root2 = deletedFiber;
- returnFiber = root2.alternate;
- returnFiber !== null && (returnFiber.return = null);
- root2.return = null;
- }
- if (parentFiber.subtreeFlags & 13878)
- for (parentFiber = parentFiber.child;parentFiber !== null; )
- commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), parentFiber = parentFiber.sibling;
- }
- function commitMutationEffectsOnFiber(finishedWork, root2) {
- var { alternate: current2, flags } = finishedWork;
- switch (finishedWork.tag) {
- case 0:
- case 11:
- case 14:
- case 15:
- recursivelyTraverseMutationEffects(root2, finishedWork);
- commitReconciliationEffects(finishedWork);
- flags & 4 && (commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return), commitHookEffectListMount(Insertion | HasEffect, finishedWork), commitHookLayoutUnmountEffects(finishedWork, finishedWork.return, Layout | HasEffect));
- break;
- case 1:
- recursivelyTraverseMutationEffects(root2, finishedWork);
- commitReconciliationEffects(finishedWork);
- flags & 512 && (offscreenSubtreeWasHidden || current2 === null || safelyDetachRef(current2, current2.return));
- flags & 64 && offscreenSubtreeIsHidden && (finishedWork = finishedWork.updateQueue, finishedWork !== null && (flags = finishedWork.callbacks, flags !== null && (current2 = finishedWork.shared.hiddenCallbacks, finishedWork.shared.hiddenCallbacks = current2 === null ? flags : current2.concat(flags))));
- break;
- case 26:
- if (supportsResources) {
- var hoistableRoot = currentHoistableRoot;
- recursivelyTraverseMutationEffects(root2, finishedWork);
- commitReconciliationEffects(finishedWork);
- flags & 512 && (offscreenSubtreeWasHidden || current2 === null || safelyDetachRef(current2, current2.return));
- flags & 4 && (flags = current2 !== null ? current2.memoizedState : null, root2 = finishedWork.memoizedState, current2 === null ? root2 === null ? finishedWork.stateNode === null ? finishedWork.stateNode = hydrateHoistable(hoistableRoot, finishedWork.type, finishedWork.memoizedProps, finishedWork) : mountHoistable(hoistableRoot, finishedWork.type, finishedWork.stateNode) : finishedWork.stateNode = acquireResource(hoistableRoot, root2, finishedWork.memoizedProps) : flags !== root2 ? (flags === null ? current2.stateNode !== null && unmountHoistable(current2.stateNode) : releaseResource(flags), root2 === null ? mountHoistable(hoistableRoot, finishedWork.type, finishedWork.stateNode) : acquireResource(hoistableRoot, root2, finishedWork.memoizedProps)) : root2 === null && finishedWork.stateNode !== null && commitHostUpdate(finishedWork, finishedWork.memoizedProps, current2.memoizedProps));
- break;
- }
- case 27:
- if (supportsSingletons && flags & 4 && finishedWork.alternate === null) {
- hoistableRoot = finishedWork.stateNode;
- var props = finishedWork.memoizedProps;
- try {
- clearSingleton(hoistableRoot), runWithFiberInDEV(finishedWork, acquireSingletonInstance, finishedWork.type, props, hoistableRoot, finishedWork);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- case 5:
- recursivelyTraverseMutationEffects(root2, finishedWork);
- commitReconciliationEffects(finishedWork);
- flags & 512 && (offscreenSubtreeWasHidden || current2 === null || safelyDetachRef(current2, current2.return));
- if (supportsMutation) {
- if (finishedWork.flags & 32) {
- root2 = finishedWork.stateNode;
- try {
- runWithFiberInDEV(finishedWork, resetTextContent, root2);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- flags & 4 && finishedWork.stateNode != null && (root2 = finishedWork.memoizedProps, commitHostUpdate(finishedWork, root2, current2 !== null ? current2.memoizedProps : root2));
- flags & 1024 && (needsFormReset = true, finishedWork.type !== "form" && console.error("Unexpected host component type. Expected a form. This is a bug in React."));
- }
- break;
- case 6:
- recursivelyTraverseMutationEffects(root2, finishedWork);
- commitReconciliationEffects(finishedWork);
- if (flags & 4 && supportsMutation) {
- if (finishedWork.stateNode === null)
- throw Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.");
- flags = finishedWork.memoizedProps;
- current2 = current2 !== null ? current2.memoizedProps : flags;
- root2 = finishedWork.stateNode;
- try {
- runWithFiberInDEV(finishedWork, commitTextUpdate, root2, current2, flags);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- break;
- case 3:
- hoistableRoot = pushNestedEffectDurations();
- supportsResources ? (prepareToCommitHoistables(), props = currentHoistableRoot, currentHoistableRoot = getHoistableRoot(root2.containerInfo), recursivelyTraverseMutationEffects(root2, finishedWork), currentHoistableRoot = props) : recursivelyTraverseMutationEffects(root2, finishedWork);
- commitReconciliationEffects(finishedWork);
- if (flags & 4) {
- if (supportsMutation && supportsHydration && current2 !== null && current2.memoizedState.isDehydrated)
- try {
- runWithFiberInDEV(finishedWork, commitHydratedContainer, root2.containerInfo);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- if (supportsPersistence) {
- flags = root2.containerInfo;
- current2 = root2.pendingChildren;
- try {
- runWithFiberInDEV(finishedWork, replaceContainerChildren, flags, current2);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- }
- needsFormReset && (needsFormReset = false, recursivelyResetForms(finishedWork));
- root2.effectDuration += popNestedEffectDurations(hoistableRoot);
- break;
- case 4:
- supportsResources ? (current2 = currentHoistableRoot, currentHoistableRoot = getHoistableRoot(finishedWork.stateNode.containerInfo), recursivelyTraverseMutationEffects(root2, finishedWork), commitReconciliationEffects(finishedWork), currentHoistableRoot = current2) : (recursivelyTraverseMutationEffects(root2, finishedWork), commitReconciliationEffects(finishedWork));
- flags & 4 && supportsPersistence && commitHostPortalContainerChildren(finishedWork.stateNode, finishedWork, finishedWork.stateNode.pendingChildren);
- break;
- case 12:
- flags = pushNestedEffectDurations();
- recursivelyTraverseMutationEffects(root2, finishedWork);
- commitReconciliationEffects(finishedWork);
- finishedWork.stateNode.effectDuration += bubbleNestedEffectDurations(flags);
- break;
- case 13:
- recursivelyTraverseMutationEffects(root2, finishedWork);
- commitReconciliationEffects(finishedWork);
- finishedWork.child.flags & 8192 && finishedWork.memoizedState !== null !== (current2 !== null && current2.memoizedState !== null) && (globalMostRecentFallbackTime = now$1());
- flags & 4 && (flags = finishedWork.updateQueue, flags !== null && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
- break;
- case 22:
- flags & 512 && (offscreenSubtreeWasHidden || current2 === null || safelyDetachRef(current2, current2.return));
- hoistableRoot = finishedWork.memoizedState !== null;
- var wasHidden = current2 !== null && current2.memoizedState !== null, prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
- offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || hoistableRoot;
- offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden;
- recursivelyTraverseMutationEffects(root2, finishedWork);
- offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
- offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
- commitReconciliationEffects(finishedWork);
- root2 = finishedWork.stateNode;
- root2._current = finishedWork;
- root2._visibility &= -3;
- root2._visibility |= root2._pendingVisibility & 2;
- if (flags & 8192 && (root2._visibility = hoistableRoot ? root2._visibility & -2 : root2._visibility | 1, hoistableRoot && (root2 = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden, current2 === null || wasHidden || root2 || recursivelyTraverseDisappearLayoutEffects(finishedWork)), supportsMutation && (finishedWork.memoizedProps === null || finishedWork.memoizedProps.mode !== "manual")))
- a:
- if (current2 = null, supportsMutation)
- for (root2 = finishedWork;; ) {
- if (root2.tag === 5 || supportsResources && root2.tag === 26 || supportsSingletons && root2.tag === 27) {
- if (current2 === null) {
- wasHidden = current2 = root2;
- try {
- props = wasHidden.stateNode, hoistableRoot ? runWithFiberInDEV(wasHidden, hideInstance, props) : runWithFiberInDEV(wasHidden, unhideInstance, wasHidden.stateNode, wasHidden.memoizedProps);
- } catch (error46) {
- captureCommitPhaseError(wasHidden, wasHidden.return, error46);
- }
- }
- } else if (root2.tag === 6) {
- if (current2 === null) {
- wasHidden = root2;
- try {
- var instance = wasHidden.stateNode;
- hoistableRoot ? runWithFiberInDEV(wasHidden, hideTextInstance, instance) : runWithFiberInDEV(wasHidden, unhideTextInstance, instance, wasHidden.memoizedProps);
- } catch (error46) {
- captureCommitPhaseError(wasHidden, wasHidden.return, error46);
- }
- }
- } else if ((root2.tag !== 22 && root2.tag !== 23 || root2.memoizedState === null || root2 === finishedWork) && root2.child !== null) {
- root2.child.return = root2;
- root2 = root2.child;
- continue;
- }
- if (root2 === finishedWork)
- break a;
- for (;root2.sibling === null; ) {
- if (root2.return === null || root2.return === finishedWork)
- break a;
- current2 === root2 && (current2 = null);
- root2 = root2.return;
- }
- current2 === root2 && (current2 = null);
- root2.sibling.return = root2.return;
- root2 = root2.sibling;
- }
- flags & 4 && (flags = finishedWork.updateQueue, flags !== null && (current2 = flags.retryQueue, current2 !== null && (flags.retryQueue = null, attachSuspenseRetryListeners(finishedWork, current2))));
- break;
- case 19:
- recursivelyTraverseMutationEffects(root2, finishedWork);
- commitReconciliationEffects(finishedWork);
- flags & 4 && (flags = finishedWork.updateQueue, flags !== null && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
- break;
- case 21:
- break;
- default:
- recursivelyTraverseMutationEffects(root2, finishedWork), commitReconciliationEffects(finishedWork);
- }
- }
- function commitReconciliationEffects(finishedWork) {
- var flags = finishedWork.flags;
- if (flags & 2) {
- try {
- runWithFiberInDEV(finishedWork, commitPlacement, finishedWork);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- finishedWork.flags &= -3;
- }
- flags & 4096 && (finishedWork.flags &= -4097);
- }
- function recursivelyResetForms(parentFiber) {
- if (parentFiber.subtreeFlags & 1024)
- for (parentFiber = parentFiber.child;parentFiber !== null; ) {
- var fiber = parentFiber;
- recursivelyResetForms(fiber);
- fiber.tag === 5 && fiber.flags & 1024 && resetFormInstance(fiber.stateNode);
- parentFiber = parentFiber.sibling;
- }
- }
- function commitLayoutEffects(finishedWork, root2, committedLanes) {
- inProgressLanes = committedLanes;
- inProgressRoot = root2;
- commitLayoutEffectOnFiber(root2, finishedWork.alternate, finishedWork);
- inProgressRoot = inProgressLanes = null;
- }
- function recursivelyTraverseLayoutEffects(root2, parentFiber) {
- if (parentFiber.subtreeFlags & 8772)
- for (parentFiber = parentFiber.child;parentFiber !== null; )
- commitLayoutEffectOnFiber(root2, parentFiber.alternate, parentFiber), parentFiber = parentFiber.sibling;
- }
- function disappearLayoutEffects(finishedWork) {
- switch (finishedWork.tag) {
- case 0:
- case 11:
- case 14:
- case 15:
- commitHookLayoutUnmountEffects(finishedWork, finishedWork.return, Layout);
- recursivelyTraverseDisappearLayoutEffects(finishedWork);
- break;
- case 1:
- safelyDetachRef(finishedWork, finishedWork.return);
- var instance = finishedWork.stateNode;
- typeof instance.componentWillUnmount === "function" && safelyCallComponentWillUnmount(finishedWork, finishedWork.return, instance);
- recursivelyTraverseDisappearLayoutEffects(finishedWork);
- break;
- case 26:
- case 27:
- case 5:
- safelyDetachRef(finishedWork, finishedWork.return);
- recursivelyTraverseDisappearLayoutEffects(finishedWork);
- break;
- case 22:
- safelyDetachRef(finishedWork, finishedWork.return);
- finishedWork.memoizedState === null && recursivelyTraverseDisappearLayoutEffects(finishedWork);
- break;
- default:
- recursivelyTraverseDisappearLayoutEffects(finishedWork);
- }
- }
- function recursivelyTraverseDisappearLayoutEffects(parentFiber) {
- for (parentFiber = parentFiber.child;parentFiber !== null; )
- disappearLayoutEffects(parentFiber), parentFiber = parentFiber.sibling;
- }
- function reappearLayoutEffects(finishedRoot, current2, finishedWork, includeWorkInProgressEffects) {
- var flags = finishedWork.flags;
- switch (finishedWork.tag) {
- case 0:
- case 11:
- case 15:
- recursivelyTraverseReappearLayoutEffects(finishedRoot, finishedWork, includeWorkInProgressEffects);
- commitHookLayoutEffects(finishedWork, Layout);
- break;
- case 1:
- recursivelyTraverseReappearLayoutEffects(finishedRoot, finishedWork, includeWorkInProgressEffects);
- current2 = finishedWork.stateNode;
- typeof current2.componentDidMount === "function" && runWithFiberInDEV(finishedWork, callComponentDidMountInDEV, finishedWork, current2);
- current2 = finishedWork.updateQueue;
- if (current2 !== null) {
- finishedRoot = finishedWork.stateNode;
- try {
- runWithFiberInDEV(finishedWork, commitHiddenCallbacks, current2, finishedRoot);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- includeWorkInProgressEffects && flags & 64 && commitClassCallbacks(finishedWork);
- safelyAttachRef(finishedWork, finishedWork.return);
- break;
- case 26:
- case 27:
- case 5:
- recursivelyTraverseReappearLayoutEffects(finishedRoot, finishedWork, includeWorkInProgressEffects);
- includeWorkInProgressEffects && current2 === null && flags & 4 && commitHostMount(finishedWork);
- safelyAttachRef(finishedWork, finishedWork.return);
- break;
- case 12:
- if (includeWorkInProgressEffects && flags & 4) {
- flags = pushNestedEffectDurations();
- recursivelyTraverseReappearLayoutEffects(finishedRoot, finishedWork, includeWorkInProgressEffects);
- includeWorkInProgressEffects = finishedWork.stateNode;
- includeWorkInProgressEffects.effectDuration += bubbleNestedEffectDurations(flags);
- try {
- runWithFiberInDEV(finishedWork, commitProfiler, finishedWork, current2, commitStartTime, includeWorkInProgressEffects.effectDuration);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- } else
- recursivelyTraverseReappearLayoutEffects(finishedRoot, finishedWork, includeWorkInProgressEffects);
- break;
- case 13:
- recursivelyTraverseReappearLayoutEffects(finishedRoot, finishedWork, includeWorkInProgressEffects);
- includeWorkInProgressEffects && flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
- break;
- case 22:
- finishedWork.memoizedState === null && recursivelyTraverseReappearLayoutEffects(finishedRoot, finishedWork, includeWorkInProgressEffects);
- safelyAttachRef(finishedWork, finishedWork.return);
- break;
- default:
- recursivelyTraverseReappearLayoutEffects(finishedRoot, finishedWork, includeWorkInProgressEffects);
- }
- }
- function recursivelyTraverseReappearLayoutEffects(finishedRoot, parentFiber, includeWorkInProgressEffects) {
- includeWorkInProgressEffects = includeWorkInProgressEffects && (parentFiber.subtreeFlags & 8772) !== 0;
- for (parentFiber = parentFiber.child;parentFiber !== null; )
- reappearLayoutEffects(finishedRoot, parentFiber.alternate, parentFiber, includeWorkInProgressEffects), parentFiber = parentFiber.sibling;
- }
- function commitOffscreenPassiveMountEffects(current2, finishedWork) {
- var previousCache = null;
- current2 !== null && current2.memoizedState !== null && current2.memoizedState.cachePool !== null && (previousCache = current2.memoizedState.cachePool.pool);
- current2 = null;
- finishedWork.memoizedState !== null && finishedWork.memoizedState.cachePool !== null && (current2 = finishedWork.memoizedState.cachePool.pool);
- current2 !== previousCache && (current2 != null && retainCache(current2), previousCache != null && releaseCache(previousCache));
- }
- function commitCachePassiveMountEffect(current2, finishedWork) {
- current2 = null;
- finishedWork.alternate !== null && (current2 = finishedWork.alternate.memoizedState.cache);
- finishedWork = finishedWork.memoizedState.cache;
- finishedWork !== current2 && (retainCache(finishedWork), current2 != null && releaseCache(current2));
- }
- function recursivelyTraversePassiveMountEffects(root2, parentFiber, committedLanes, committedTransitions) {
- if (parentFiber.subtreeFlags & 10256)
- for (parentFiber = parentFiber.child;parentFiber !== null; )
- commitPassiveMountOnFiber(root2, parentFiber, committedLanes, committedTransitions), parentFiber = parentFiber.sibling;
- }
- function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
- var flags = finishedWork.flags;
- switch (finishedWork.tag) {
- case 0:
- case 11:
- case 15:
- recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork, committedLanes, committedTransitions);
- flags & 2048 && commitHookPassiveMountEffects(finishedWork, Passive | HasEffect);
- break;
- case 3:
- var prevEffectDuration = pushNestedEffectDurations();
- recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork, committedLanes, committedTransitions);
- flags & 2048 && (committedLanes = null, finishedWork.alternate !== null && (committedLanes = finishedWork.alternate.memoizedState.cache), finishedWork = finishedWork.memoizedState.cache, finishedWork !== committedLanes && (retainCache(finishedWork), committedLanes != null && releaseCache(committedLanes)));
- finishedRoot.passiveEffectDuration += popNestedEffectDurations(prevEffectDuration);
- break;
- case 12:
- if (flags & 2048) {
- prevEffectDuration = pushNestedEffectDurations();
- recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork, committedLanes, committedTransitions);
- finishedRoot = finishedWork.stateNode;
- finishedRoot.passiveEffectDuration += bubbleNestedEffectDurations(prevEffectDuration);
- try {
- runWithFiberInDEV(finishedWork, commitProfilerPostCommitImpl, finishedWork, finishedWork.alternate, commitStartTime, finishedRoot.passiveEffectDuration);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- } else
- recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork, committedLanes, committedTransitions);
- break;
- case 23:
- break;
- case 22:
- prevEffectDuration = finishedWork.stateNode;
- finishedWork.memoizedState !== null ? prevEffectDuration._visibility & 4 ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork, committedLanes, committedTransitions) : recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork) : prevEffectDuration._visibility & 4 ? recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork, committedLanes, committedTransitions) : (prevEffectDuration._visibility |= 4, recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork, committedLanes, committedTransitions, (finishedWork.subtreeFlags & 10256) !== 0));
- flags & 2048 && commitOffscreenPassiveMountEffects(finishedWork.alternate, finishedWork);
- break;
- case 24:
- recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork, committedLanes, committedTransitions);
- flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
- break;
- default:
- recursivelyTraversePassiveMountEffects(finishedRoot, finishedWork, committedLanes, committedTransitions);
- }
- }
- function recursivelyTraverseReconnectPassiveEffects(finishedRoot, parentFiber, committedLanes, committedTransitions, includeWorkInProgressEffects) {
- includeWorkInProgressEffects = includeWorkInProgressEffects && (parentFiber.subtreeFlags & 10256) !== 0;
- for (parentFiber = parentFiber.child;parentFiber !== null; )
- reconnectPassiveEffects(finishedRoot, parentFiber, committedLanes, committedTransitions, includeWorkInProgressEffects), parentFiber = parentFiber.sibling;
- }
- function reconnectPassiveEffects(finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects) {
- var flags = finishedWork.flags;
- switch (finishedWork.tag) {
- case 0:
- case 11:
- case 15:
- recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects);
- commitHookPassiveMountEffects(finishedWork, Passive);
- break;
- case 23:
- break;
- case 22:
- var _instance2 = finishedWork.stateNode;
- finishedWork.memoizedState !== null ? _instance2._visibility & 4 ? recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects) : recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork) : (_instance2._visibility |= 4, recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects));
- includeWorkInProgressEffects && flags & 2048 && commitOffscreenPassiveMountEffects(finishedWork.alternate, finishedWork);
- break;
- case 24:
- recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects);
- includeWorkInProgressEffects && flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
- break;
- default:
- recursivelyTraverseReconnectPassiveEffects(finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects);
- }
- }
- function recursivelyTraverseAtomicPassiveEffects(finishedRoot$jscomp$0, parentFiber) {
- if (parentFiber.subtreeFlags & 10256)
- for (parentFiber = parentFiber.child;parentFiber !== null; ) {
- var finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, flags = finishedWork.flags;
- switch (finishedWork.tag) {
- case 22:
- recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
- flags & 2048 && commitOffscreenPassiveMountEffects(finishedWork.alternate, finishedWork);
- break;
- case 24:
- recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
- flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
- break;
- default:
- recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
- }
- parentFiber = parentFiber.sibling;
- }
- }
- function recursivelyAccumulateSuspenseyCommit(parentFiber) {
- if (parentFiber.subtreeFlags & suspenseyCommitFlag)
- for (parentFiber = parentFiber.child;parentFiber !== null; )
- accumulateSuspenseyCommitOnFiber(parentFiber), parentFiber = parentFiber.sibling;
- }
- function accumulateSuspenseyCommitOnFiber(fiber) {
- switch (fiber.tag) {
- case 26:
- recursivelyAccumulateSuspenseyCommit(fiber);
- fiber.flags & suspenseyCommitFlag && (fiber.memoizedState !== null ? suspendResource(currentHoistableRoot, fiber.memoizedState, fiber.memoizedProps) : suspendInstance(fiber.type, fiber.memoizedProps));
- break;
- case 5:
- recursivelyAccumulateSuspenseyCommit(fiber);
- fiber.flags & suspenseyCommitFlag && suspendInstance(fiber.type, fiber.memoizedProps);
- break;
- case 3:
- case 4:
- if (supportsResources) {
- var previousHoistableRoot = currentHoistableRoot;
- currentHoistableRoot = getHoistableRoot(fiber.stateNode.containerInfo);
- recursivelyAccumulateSuspenseyCommit(fiber);
- currentHoistableRoot = previousHoistableRoot;
- } else
- recursivelyAccumulateSuspenseyCommit(fiber);
- break;
- case 22:
- fiber.memoizedState === null && (previousHoistableRoot = fiber.alternate, previousHoistableRoot !== null && previousHoistableRoot.memoizedState !== null ? (previousHoistableRoot = suspenseyCommitFlag, suspenseyCommitFlag = 16777216, recursivelyAccumulateSuspenseyCommit(fiber), suspenseyCommitFlag = previousHoistableRoot) : recursivelyAccumulateSuspenseyCommit(fiber));
- break;
- default:
- recursivelyAccumulateSuspenseyCommit(fiber);
- }
- }
- function detachAlternateSiblings(parentFiber) {
- var previousFiber = parentFiber.alternate;
- if (previousFiber !== null && (parentFiber = previousFiber.child, parentFiber !== null)) {
- previousFiber.child = null;
- do
- previousFiber = parentFiber.sibling, parentFiber.sibling = null, parentFiber = previousFiber;
- while (parentFiber !== null);
- }
- }
- function recursivelyTraversePassiveUnmountEffects(parentFiber) {
- var deletions = parentFiber.deletions;
- if ((parentFiber.flags & 16) !== 0) {
- if (deletions !== null)
- for (var i5 = 0;i5 < deletions.length; i5++) {
- var childToDelete = deletions[i5];
- nextEffect = childToDelete;
- commitPassiveUnmountEffectsInsideOfDeletedTree_begin(childToDelete, parentFiber);
- }
- detachAlternateSiblings(parentFiber);
- }
- if (parentFiber.subtreeFlags & 10256)
- for (parentFiber = parentFiber.child;parentFiber !== null; )
- commitPassiveUnmountOnFiber(parentFiber), parentFiber = parentFiber.sibling;
- }
- function commitPassiveUnmountOnFiber(finishedWork) {
- switch (finishedWork.tag) {
- case 0:
- case 11:
- case 15:
- recursivelyTraversePassiveUnmountEffects(finishedWork);
- finishedWork.flags & 2048 && commitHookPassiveUnmountEffects(finishedWork, finishedWork.return, Passive | HasEffect);
- break;
- case 3:
- var prevEffectDuration = pushNestedEffectDurations();
- recursivelyTraversePassiveUnmountEffects(finishedWork);
- finishedWork.stateNode.passiveEffectDuration += popNestedEffectDurations(prevEffectDuration);
- break;
- case 12:
- prevEffectDuration = pushNestedEffectDurations();
- recursivelyTraversePassiveUnmountEffects(finishedWork);
- finishedWork.stateNode.passiveEffectDuration += bubbleNestedEffectDurations(prevEffectDuration);
- break;
- case 22:
- prevEffectDuration = finishedWork.stateNode;
- finishedWork.memoizedState !== null && prevEffectDuration._visibility & 4 && (finishedWork.return === null || finishedWork.return.tag !== 13) ? (prevEffectDuration._visibility &= -5, recursivelyTraverseDisconnectPassiveEffects(finishedWork)) : recursivelyTraversePassiveUnmountEffects(finishedWork);
- break;
- default:
- recursivelyTraversePassiveUnmountEffects(finishedWork);
- }
- }
- function recursivelyTraverseDisconnectPassiveEffects(parentFiber) {
- var deletions = parentFiber.deletions;
- if ((parentFiber.flags & 16) !== 0) {
- if (deletions !== null)
- for (var i5 = 0;i5 < deletions.length; i5++) {
- var childToDelete = deletions[i5];
- nextEffect = childToDelete;
- commitPassiveUnmountEffectsInsideOfDeletedTree_begin(childToDelete, parentFiber);
- }
- detachAlternateSiblings(parentFiber);
- }
- for (parentFiber = parentFiber.child;parentFiber !== null; )
- disconnectPassiveEffect(parentFiber), parentFiber = parentFiber.sibling;
- }
- function disconnectPassiveEffect(finishedWork) {
- switch (finishedWork.tag) {
- case 0:
- case 11:
- case 15:
- commitHookPassiveUnmountEffects(finishedWork, finishedWork.return, Passive);
- recursivelyTraverseDisconnectPassiveEffects(finishedWork);
- break;
- case 22:
- var instance = finishedWork.stateNode;
- instance._visibility & 4 && (instance._visibility &= -5, recursivelyTraverseDisconnectPassiveEffects(finishedWork));
- break;
- default:
- recursivelyTraverseDisconnectPassiveEffects(finishedWork);
- }
- }
- function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
- for (;nextEffect !== null; ) {
- var fiber = nextEffect, current2 = fiber;
- switch (current2.tag) {
- case 0:
- case 11:
- case 15:
- commitHookPassiveUnmountEffects(current2, nearestMountedAncestor, Passive);
- break;
- case 23:
- case 22:
- current2.memoizedState !== null && current2.memoizedState.cachePool !== null && (current2 = current2.memoizedState.cachePool.pool, current2 != null && retainCache(current2));
- break;
- case 24:
- releaseCache(current2.memoizedState.cache);
- }
- current2 = fiber.child;
- if (current2 !== null)
- current2.return = fiber, nextEffect = current2;
- else
- a:
- for (fiber = deletedSubtreeRoot;nextEffect !== null; ) {
- current2 = nextEffect;
- var { sibling, return: returnFiber } = current2;
- detachFiberAfterEffects(current2);
- if (current2 === fiber) {
- nextEffect = null;
- break a;
- }
- if (sibling !== null) {
- sibling.return = returnFiber;
- nextEffect = sibling;
- break a;
- }
- nextEffect = returnFiber;
- }
- }
- }
- function findFiberRootForHostRoot(hostRoot) {
- var maybeFiber = getInstanceFromNode(hostRoot);
- if (maybeFiber != null) {
- if (typeof maybeFiber.memoizedProps["data-testname"] !== "string")
- throw Error("Invalid host root specified. Should be either a React container or a node with a testname attribute.");
- return maybeFiber;
- }
- hostRoot = findFiberRoot(hostRoot);
- if (hostRoot === null)
- throw Error("Could not find React container within specified host subtree.");
- return hostRoot.stateNode.current;
- }
- function matchSelector(fiber$jscomp$0, selector) {
- var tag2 = fiber$jscomp$0.tag;
- switch (selector.$$typeof) {
- case COMPONENT_TYPE:
- if (fiber$jscomp$0.type === selector.value)
- return true;
- break;
- case HAS_PSEUDO_CLASS_TYPE:
- a: {
- selector = selector.value;
- fiber$jscomp$0 = [fiber$jscomp$0, 0];
- for (tag2 = 0;tag2 < fiber$jscomp$0.length; ) {
- var fiber = fiber$jscomp$0[tag2++], tag$jscomp$0 = fiber.tag, selectorIndex = fiber$jscomp$0[tag2++], selector$jscomp$0 = selector[selectorIndex];
- if (tag$jscomp$0 !== 5 && tag$jscomp$0 !== 26 && tag$jscomp$0 !== 27 || !isHiddenSubtree(fiber)) {
- for (;selector$jscomp$0 != null && matchSelector(fiber, selector$jscomp$0); )
- selectorIndex++, selector$jscomp$0 = selector[selectorIndex];
- if (selectorIndex === selector.length) {
- selector = true;
- break a;
- } else
- for (fiber = fiber.child;fiber !== null; )
- fiber$jscomp$0.push(fiber, selectorIndex), fiber = fiber.sibling;
- }
- }
- selector = false;
- }
- return selector;
- case ROLE_TYPE:
- if ((tag2 === 5 || tag2 === 26 || tag2 === 27) && matchAccessibilityRole(fiber$jscomp$0.stateNode, selector.value))
- return true;
- break;
- case TEXT_TYPE:
- if (tag2 === 5 || tag2 === 6 || tag2 === 26 || tag2 === 27) {
- if (fiber$jscomp$0 = getTextContent(fiber$jscomp$0), fiber$jscomp$0 !== null && 0 <= fiber$jscomp$0.indexOf(selector.value))
- return true;
- }
- break;
- case TEST_NAME_TYPE:
- if (tag2 === 5 || tag2 === 26 || tag2 === 27) {
- if (fiber$jscomp$0 = fiber$jscomp$0.memoizedProps["data-testname"], typeof fiber$jscomp$0 === "string" && fiber$jscomp$0.toLowerCase() === selector.value.toLowerCase())
- return true;
- }
- break;
- default:
- throw Error("Invalid selector type specified.");
- }
- return false;
- }
- function selectorToString(selector) {
- switch (selector.$$typeof) {
- case COMPONENT_TYPE:
- return "<" + (getComponentNameFromType(selector.value) || "Unknown") + ">";
- case HAS_PSEUDO_CLASS_TYPE:
- return ":has(" + (selectorToString(selector) || "") + ")";
- case ROLE_TYPE:
- return '[role="' + selector.value + '"]';
- case TEXT_TYPE:
- return '"' + selector.value + '"';
- case TEST_NAME_TYPE:
- return '[data-testname="' + selector.value + '"]';
- default:
- throw Error("Invalid selector type specified.");
- }
- }
- function findPaths(root2, selectors) {
- var matchingFibers = [];
- root2 = [root2, 0];
- for (var index2 = 0;index2 < root2.length; ) {
- var fiber = root2[index2++], tag2 = fiber.tag, selectorIndex = root2[index2++], selector = selectors[selectorIndex];
- if (tag2 !== 5 && tag2 !== 26 && tag2 !== 27 || !isHiddenSubtree(fiber)) {
- for (;selector != null && matchSelector(fiber, selector); )
- selectorIndex++, selector = selectors[selectorIndex];
- if (selectorIndex === selectors.length)
- matchingFibers.push(fiber);
- else
- for (fiber = fiber.child;fiber !== null; )
- root2.push(fiber, selectorIndex), fiber = fiber.sibling;
- }
- }
- return matchingFibers;
- }
- function findAllNodes(hostRoot, selectors) {
- if (!supportsTestSelectors)
- throw Error("Test selector API is not supported by this renderer.");
- hostRoot = findFiberRootForHostRoot(hostRoot);
- hostRoot = findPaths(hostRoot, selectors);
- selectors = [];
- hostRoot = Array.from(hostRoot);
- for (var index2 = 0;index2 < hostRoot.length; ) {
- var node = hostRoot[index2++], tag2 = node.tag;
- if (tag2 === 5 || tag2 === 26 || tag2 === 27)
- isHiddenSubtree(node) || selectors.push(node.stateNode);
- else
- for (node = node.child;node !== null; )
- hostRoot.push(node), node = node.sibling;
- }
- return selectors;
- }
- function onCommitRoot() {
- supportsTestSelectors && commitHooks.forEach(function(commitHook) {
- return commitHook();
- });
- }
- function isConcurrentActEnvironment() {
- var isReactActEnvironmentGlobal = typeof IS_REACT_ACT_ENVIRONMENT !== "undefined" ? IS_REACT_ACT_ENVIRONMENT : undefined;
- isReactActEnvironmentGlobal || ReactSharedInternals.actQueue === null || console.error("The current testing environment is not configured to support act(...)");
- return isReactActEnvironmentGlobal;
- }
- function requestUpdateLane(fiber) {
- if ((executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== 0)
- return workInProgressRootRenderLanes & -workInProgressRootRenderLanes;
- var transition = ReactSharedInternals.T;
- return transition !== null ? (transition._updatedFibers || (transition._updatedFibers = new Set), transition._updatedFibers.add(fiber), fiber = currentEntangledLane, fiber !== 0 ? fiber : requestTransitionLane()) : resolveUpdatePriority();
- }
- function requestDeferredLane() {
- workInProgressDeferredLane === 0 && (workInProgressDeferredLane = (workInProgressRootRenderLanes & 536870912) === 0 || isHydrating ? claimNextTransitionLane() : 536870912);
- var suspenseHandler = suspenseHandlerStackCursor.current;
- suspenseHandler !== null && (suspenseHandler.flags |= 32);
- return workInProgressDeferredLane;
- }
- function scheduleUpdateOnFiber(root2, fiber, lane) {
- isRunningInsertionEffect && console.error("useInsertionEffect must not schedule updates.");
- isFlushingPassiveEffects && (didScheduleUpdateDuringPassiveEffects = true);
- if (root2 === workInProgressRoot && workInProgressSuspendedReason === SuspendedOnData || root2.cancelPendingCommit !== null)
- prepareFreshStack(root2, 0), markRootSuspended(root2, workInProgressRootRenderLanes, workInProgressDeferredLane, false);
- markRootUpdated$1(root2, lane);
- if ((executionContext & RenderContext) !== 0 && root2 === workInProgressRoot) {
- if (isRendering)
- switch (fiber.tag) {
- case 0:
- case 11:
- case 15:
- root2 = workInProgress && getComponentNameFromFiber(workInProgress) || "Unknown";
- didWarnAboutUpdateInRenderForAnotherComponent.has(root2) || (didWarnAboutUpdateInRenderForAnotherComponent.add(root2), fiber = getComponentNameFromFiber(fiber) || "Unknown", console.error("Cannot update a component (`%s`) while rendering a different component (`%s`). To locate the bad setState() call inside `%s`, follow the stack trace as described in https://react.dev/link/setstate-in-render", fiber, root2, root2));
- break;
- case 1:
- didWarnAboutUpdateInRender || (console.error("Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state."), didWarnAboutUpdateInRender = true);
- }
- } else
- isDevToolsPresent && addFiberToLanesMap(root2, fiber, lane), warnIfUpdatesNotWrappedWithActDEV(fiber), root2 === workInProgressRoot && ((executionContext & RenderContext) === NoContext && (workInProgressRootInterleavedUpdatedLanes |= lane), workInProgressRootExitStatus === RootSuspendedWithDelay && markRootSuspended(root2, workInProgressRootRenderLanes, workInProgressDeferredLane, false)), ensureRootIsScheduled(root2);
- }
- function performWorkOnRoot(root2, lanes, forceSync) {
- if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
- throw Error("Should not already be working.");
- var shouldTimeSlice = !forceSync && (lanes & 60) === 0 && (lanes & root2.expiredLanes) === 0 || checkIfRootIsPrerendering(root2, lanes), exitStatus = shouldTimeSlice ? renderRootConcurrent(root2, lanes) : renderRootSync(root2, lanes, true), renderWasConcurrent = shouldTimeSlice;
- do {
- if (exitStatus === RootInProgress) {
- workInProgressRootIsPrerendering && !shouldTimeSlice && markRootSuspended(root2, lanes, 0, false);
- break;
- } else if (exitStatus === RootDidNotComplete)
- markRootSuspended(root2, lanes, 0, !workInProgressRootDidSkipSuspendedSiblings);
- else {
- forceSync = root2.current.alternate;
- if (renderWasConcurrent && !isRenderConsistentWithExternalStores(forceSync)) {
- exitStatus = renderRootSync(root2, lanes, false);
- renderWasConcurrent = false;
- continue;
- }
- if (exitStatus === RootErrored) {
- renderWasConcurrent = lanes;
- if (root2.errorRecoveryDisabledLanes & renderWasConcurrent)
- var errorRetryLanes = 0;
- else
- errorRetryLanes = root2.pendingLanes & -536870913, errorRetryLanes = errorRetryLanes !== 0 ? errorRetryLanes : errorRetryLanes & 536870912 ? 536870912 : 0;
- if (errorRetryLanes !== 0) {
- lanes = errorRetryLanes;
- a: {
- exitStatus = root2;
- var errorRetryLanes$jscomp$0 = errorRetryLanes;
- errorRetryLanes = workInProgressRootConcurrentErrors;
- var wasRootDehydrated = supportsHydration && exitStatus.current.memoizedState.isDehydrated;
- wasRootDehydrated && (prepareFreshStack(exitStatus, errorRetryLanes$jscomp$0).flags |= 256);
- errorRetryLanes$jscomp$0 = renderRootSync(exitStatus, errorRetryLanes$jscomp$0, false);
- if (errorRetryLanes$jscomp$0 !== RootErrored) {
- if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) {
- exitStatus.errorRecoveryDisabledLanes |= renderWasConcurrent;
- workInProgressRootInterleavedUpdatedLanes |= renderWasConcurrent;
- exitStatus = RootSuspendedWithDelay;
- break a;
- }
- exitStatus = workInProgressRootRecoverableErrors;
- workInProgressRootRecoverableErrors = errorRetryLanes;
- exitStatus !== null && queueRecoverableErrors(exitStatus);
- }
- exitStatus = errorRetryLanes$jscomp$0;
- }
- renderWasConcurrent = false;
- if (exitStatus !== RootErrored)
- continue;
- }
- }
- if (exitStatus === RootFatalErrored) {
- prepareFreshStack(root2, 0);
- markRootSuspended(root2, lanes, 0, true);
- break;
- }
- a: {
- shouldTimeSlice = root2;
- switch (exitStatus) {
- case RootInProgress:
- case RootFatalErrored:
- throw Error("Root did not complete. This is a bug in React.");
- case RootSuspendedWithDelay:
- if ((lanes & 4194176) === lanes) {
- markRootSuspended(shouldTimeSlice, lanes, workInProgressDeferredLane, !workInProgressRootDidSkipSuspendedSiblings);
- break a;
- }
- break;
- case RootErrored:
- workInProgressRootRecoverableErrors = null;
- break;
- case RootSuspended:
- case RootCompleted:
- break;
- default:
- throw Error("Unknown root exit status.");
- }
- shouldTimeSlice.finishedWork = forceSync;
- shouldTimeSlice.finishedLanes = lanes;
- if (ReactSharedInternals.actQueue !== null)
- commitRoot(shouldTimeSlice, workInProgressRootRecoverableErrors, workInProgressTransitions, workInProgressRootDidIncludeRecursiveRenderUpdate, workInProgressDeferredLane, workInProgressRootInterleavedUpdatedLanes, workInProgressSuspendedRetryLanes, IMMEDIATE_COMMIT, -0, 0);
- else {
- if ((lanes & 62914560) === lanes && (exitStatus = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now$1(), 10 < exitStatus)) {
- markRootSuspended(shouldTimeSlice, lanes, workInProgressDeferredLane, !workInProgressRootDidSkipSuspendedSiblings);
- if (getNextLanes(shouldTimeSlice, 0) !== 0)
- break a;
- shouldTimeSlice.timeoutHandle = scheduleTimeout(commitRootWhenReady.bind(null, shouldTimeSlice, forceSync, workInProgressRootRecoverableErrors, workInProgressTransitions, workInProgressRootDidIncludeRecursiveRenderUpdate, lanes, workInProgressDeferredLane, workInProgressRootInterleavedUpdatedLanes, workInProgressSuspendedRetryLanes, workInProgressRootDidSkipSuspendedSiblings, THROTTLED_COMMIT, -0, 0), exitStatus);
- break a;
- }
- commitRootWhenReady(shouldTimeSlice, forceSync, workInProgressRootRecoverableErrors, workInProgressTransitions, workInProgressRootDidIncludeRecursiveRenderUpdate, lanes, workInProgressDeferredLane, workInProgressRootInterleavedUpdatedLanes, workInProgressSuspendedRetryLanes, workInProgressRootDidSkipSuspendedSiblings, IMMEDIATE_COMMIT, -0, 0);
- }
- }
- }
- break;
- } while (1);
- ensureRootIsScheduled(root2);
- }
- function queueRecoverableErrors(errors6) {
- workInProgressRootRecoverableErrors === null ? workInProgressRootRecoverableErrors = errors6 : workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors6);
- }
- function commitRootWhenReady(root2, finishedWork, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, lanes, spawnedLane, updatedLanes, suspendedRetryLanes, didSkipSuspendedSiblings, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
- var subtreeFlags = finishedWork.subtreeFlags;
- if (subtreeFlags & 8192 || (subtreeFlags & 16785408) === 16785408) {
- if (startSuspendingCommit(), accumulateSuspenseyCommitOnFiber(finishedWork), finishedWork = waitForCommitToBeReady(), finishedWork !== null) {
- root2.cancelPendingCommit = finishedWork(commitRoot.bind(null, root2, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, spawnedLane, updatedLanes, suspendedRetryLanes, SUSPENDED_COMMIT, completedRenderStartTime, completedRenderEndTime));
- markRootSuspended(root2, lanes, spawnedLane, !didSkipSuspendedSiblings);
- return;
- }
- }
- commitRoot(root2, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, spawnedLane, updatedLanes, suspendedRetryLanes, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime);
- }
- function isRenderConsistentWithExternalStores(finishedWork) {
- for (var node = finishedWork;; ) {
- var tag2 = node.tag;
- if ((tag2 === 0 || tag2 === 11 || tag2 === 15) && node.flags & 16384 && (tag2 = node.updateQueue, tag2 !== null && (tag2 = tag2.stores, tag2 !== null)))
- for (var i5 = 0;i5 < tag2.length; i5++) {
- var check3 = tag2[i5], getSnapshot = check3.getSnapshot;
- check3 = check3.value;
- try {
- if (!objectIs(getSnapshot(), check3))
- return false;
- } catch (error46) {
- return false;
- }
- }
- tag2 = node.child;
- if (node.subtreeFlags & 16384 && tag2 !== null)
- tag2.return = node, node = tag2;
- else {
- if (node === finishedWork)
- break;
- for (;node.sibling === null; ) {
- if (node.return === null || node.return === finishedWork)
- return true;
- node = node.return;
- }
- node.sibling.return = node.return;
- node = node.sibling;
- }
- }
- return true;
- }
- function markRootSuspended(root2, suspendedLanes, spawnedLane, didAttemptEntireTree) {
- suspendedLanes &= ~workInProgressRootPingedLanes;
- suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes;
- root2.suspendedLanes |= suspendedLanes;
- root2.pingedLanes &= ~suspendedLanes;
- didAttemptEntireTree && (root2.warmLanes |= suspendedLanes);
- didAttemptEntireTree = root2.expirationTimes;
- for (var lanes = suspendedLanes;0 < lanes; ) {
- var index2 = 31 - clz32(lanes), lane = 1 << index2;
- didAttemptEntireTree[index2] = -1;
- lanes &= ~lane;
- }
- spawnedLane !== 0 && markSpawnedDeferredLane(root2, spawnedLane, suspendedLanes);
- }
- function flushSyncWork() {
- return (executionContext & (RenderContext | CommitContext)) === NoContext ? (flushSyncWorkAcrossRoots_impl(0, false), false) : true;
- }
- function resetWorkInProgressStack() {
- if (workInProgress !== null) {
- if (workInProgressSuspendedReason === NotSuspended)
- var interruptedWork = workInProgress.return;
- else
- interruptedWork = workInProgress, resetContextDependencies(), resetHooksOnUnwind(interruptedWork), thenableState$1 = null, thenableIndexCounter$1 = 0, interruptedWork = workInProgress;
- for (;interruptedWork !== null; )
- unwindInterruptedWork(interruptedWork.alternate, interruptedWork), interruptedWork = interruptedWork.return;
- workInProgress = null;
- }
- }
- function prepareFreshStack(root2, lanes) {
- root2.finishedWork = null;
- root2.finishedLanes = 0;
- var timeoutHandle = root2.timeoutHandle;
- timeoutHandle !== noTimeout && (root2.timeoutHandle = noTimeout, cancelTimeout(timeoutHandle));
- timeoutHandle = root2.cancelPendingCommit;
- timeoutHandle !== null && (root2.cancelPendingCommit = null, timeoutHandle());
- resetWorkInProgressStack();
- workInProgressRoot = root2;
- workInProgress = timeoutHandle = createWorkInProgress(root2.current, null);
- workInProgressRootRenderLanes = lanes;
- workInProgressSuspendedReason = NotSuspended;
- workInProgressThrownValue = null;
- workInProgressRootDidSkipSuspendedSiblings = false;
- workInProgressRootIsPrerendering = checkIfRootIsPrerendering(root2, lanes);
- workInProgressRootDidAttachPingListener = false;
- workInProgressRootExitStatus = RootInProgress;
- workInProgressSuspendedRetryLanes = workInProgressDeferredLane = workInProgressRootPingedLanes = workInProgressRootInterleavedUpdatedLanes = workInProgressRootSkippedLanes = 0;
- workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = null;
- workInProgressRootDidIncludeRecursiveRenderUpdate = false;
- (lanes & 8) !== 0 && (lanes |= lanes & 32);
- var allEntangledLanes = root2.entangledLanes;
- if (allEntangledLanes !== 0)
- for (root2 = root2.entanglements, allEntangledLanes &= lanes;0 < allEntangledLanes; ) {
- var index2 = 31 - clz32(allEntangledLanes), lane = 1 << index2;
- lanes |= root2[index2];
- allEntangledLanes &= ~lane;
- }
- entangledRenderLanes = lanes;
- finishQueueingConcurrentUpdates();
- ReactStrictModeWarnings.discardPendingWarnings();
- return timeoutHandle;
- }
- function handleThrow(root2, thrownValue) {
- currentlyRenderingFiber$1 = null;
- ReactSharedInternals.H = ContextOnlyDispatcher;
- ReactSharedInternals.getCurrentStack = null;
- isRendering = false;
- current = null;
- thrownValue === SuspenseException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = SuspendedOnImmediate) : thrownValue === SuspenseyCommitException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = SuspendedOnInstance) : workInProgressSuspendedReason = thrownValue === SelectiveHydrationException ? SuspendedOnHydration : thrownValue !== null && typeof thrownValue === "object" && typeof thrownValue.then === "function" ? SuspendedOnDeprecatedThrowPromise : SuspendedOnError;
- workInProgressThrownValue = thrownValue;
- var erroredWork = workInProgress;
- if (erroredWork === null)
- workInProgressRootExitStatus = RootFatalErrored, logUncaughtError(root2, createCapturedValueAtFiber(thrownValue, root2.current));
- else
- switch (erroredWork.mode & 2 && stopProfilerTimerIfRunningAndRecordDuration(erroredWork), markComponentRenderStopped(), workInProgressSuspendedReason) {
- case SuspendedOnError:
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === "function" && injectedProfilingHooks.markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes);
- break;
- case SuspendedOnData:
- case SuspendedOnImmediate:
- case SuspendedOnDeprecatedThrowPromise:
- case SuspendedAndReadyToContinue:
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === "function" && injectedProfilingHooks.markComponentSuspended(erroredWork, thrownValue, workInProgressRootRenderLanes);
- }
- }
- function shouldRemainOnPreviousScreen() {
- var handler = suspenseHandlerStackCursor.current;
- return handler === null ? true : (workInProgressRootRenderLanes & 4194176) === workInProgressRootRenderLanes ? shellBoundary === null ? true : false : (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes || (workInProgressRootRenderLanes & 536870912) !== 0 ? handler === shellBoundary : false;
- }
- function pushDispatcher() {
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = ContextOnlyDispatcher;
- return prevDispatcher === null ? ContextOnlyDispatcher : prevDispatcher;
- }
- function pushAsyncDispatcher() {
- var prevAsyncDispatcher = ReactSharedInternals.A;
- ReactSharedInternals.A = DefaultAsyncDispatcher;
- return prevAsyncDispatcher;
- }
- function renderDidSuspendDelayIfPossible() {
- workInProgressRootExitStatus = RootSuspendedWithDelay;
- workInProgressRootDidSkipSuspendedSiblings || (workInProgressRootRenderLanes & 4194176) !== workInProgressRootRenderLanes && suspenseHandlerStackCursor.current !== null || (workInProgressRootIsPrerendering = true);
- (workInProgressRootSkippedLanes & 134217727) === 0 && (workInProgressRootInterleavedUpdatedLanes & 134217727) === 0 || workInProgressRoot === null || markRootSuspended(workInProgressRoot, workInProgressRootRenderLanes, workInProgressDeferredLane, false);
- }
- function renderRootSync(root2, lanes, shouldYieldForPrerendering) {
- var prevExecutionContext = executionContext;
- executionContext |= RenderContext;
- var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
- if (workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes) {
- if (isDevToolsPresent) {
- var memoizedUpdaters = root2.memoizedUpdaters;
- 0 < memoizedUpdaters.size && (restorePendingUpdaters(root2, workInProgressRootRenderLanes), memoizedUpdaters.clear());
- movePendingFibersToMemoized(root2, lanes);
- }
- workInProgressTransitions = null;
- prepareFreshStack(root2, lanes);
- }
- markRenderStarted(lanes);
- lanes = false;
- memoizedUpdaters = workInProgressRootExitStatus;
- a:
- do
- try {
- if (workInProgressSuspendedReason !== NotSuspended && workInProgress !== null) {
- var unitOfWork = workInProgress, thrownValue = workInProgressThrownValue;
- switch (workInProgressSuspendedReason) {
- case SuspendedOnHydration:
- resetWorkInProgressStack();
- memoizedUpdaters = RootDidNotComplete;
- break a;
- case SuspendedOnImmediate:
- case SuspendedOnData:
- case SuspendedOnDeprecatedThrowPromise:
- suspenseHandlerStackCursor.current === null && (lanes = true);
- var reason = workInProgressSuspendedReason;
- workInProgressSuspendedReason = NotSuspended;
- workInProgressThrownValue = null;
- throwAndUnwindWorkLoop(root2, unitOfWork, thrownValue, reason);
- if (shouldYieldForPrerendering && workInProgressRootIsPrerendering) {
- memoizedUpdaters = RootInProgress;
- break a;
- }
- break;
- default:
- reason = workInProgressSuspendedReason, workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root2, unitOfWork, thrownValue, reason);
- }
- }
- workLoopSync();
- memoizedUpdaters = workInProgressRootExitStatus;
- break;
- } catch (thrownValue$4) {
- handleThrow(root2, thrownValue$4);
- }
- while (1);
- lanes && root2.shellSuspendCounter++;
- resetContextDependencies();
- executionContext = prevExecutionContext;
- ReactSharedInternals.H = prevDispatcher;
- ReactSharedInternals.A = prevAsyncDispatcher;
- markRenderStopped();
- workInProgress === null && (workInProgressRoot = null, workInProgressRootRenderLanes = 0, finishQueueingConcurrentUpdates());
- return memoizedUpdaters;
- }
- function workLoopSync() {
- for (;workInProgress !== null; )
- performUnitOfWork(workInProgress);
- }
- function renderRootConcurrent(root2, lanes) {
- var prevExecutionContext = executionContext;
- executionContext |= RenderContext;
- var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
- if (workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes) {
- if (isDevToolsPresent) {
- var memoizedUpdaters = root2.memoizedUpdaters;
- 0 < memoizedUpdaters.size && (restorePendingUpdaters(root2, workInProgressRootRenderLanes), memoizedUpdaters.clear());
- movePendingFibersToMemoized(root2, lanes);
- }
- workInProgressTransitions = null;
- workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS;
- prepareFreshStack(root2, lanes);
- } else
- workInProgressRootIsPrerendering = checkIfRootIsPrerendering(root2, lanes);
- markRenderStarted(lanes);
- a:
- do
- try {
- if (workInProgressSuspendedReason !== NotSuspended && workInProgress !== null)
- b:
- switch (lanes = workInProgress, memoizedUpdaters = workInProgressThrownValue, workInProgressSuspendedReason) {
- case SuspendedOnError:
- workInProgressSuspendedReason = NotSuspended;
- workInProgressThrownValue = null;
- throwAndUnwindWorkLoop(root2, lanes, memoizedUpdaters, SuspendedOnError);
- break;
- case SuspendedOnData:
- if (isThenableResolved(memoizedUpdaters)) {
- workInProgressSuspendedReason = NotSuspended;
- workInProgressThrownValue = null;
- replaySuspendedUnitOfWork(lanes);
- break;
- }
- lanes = function() {
- workInProgressSuspendedReason === SuspendedOnData && workInProgressRoot === root2 && (workInProgressSuspendedReason = SuspendedAndReadyToContinue);
- ensureRootIsScheduled(root2);
- };
- memoizedUpdaters.then(lanes, lanes);
- break a;
- case SuspendedOnImmediate:
- workInProgressSuspendedReason = SuspendedAndReadyToContinue;
- break a;
- case SuspendedOnInstance:
- workInProgressSuspendedReason = SuspendedOnInstanceAndReadyToContinue;
- break a;
- case SuspendedAndReadyToContinue:
- isThenableResolved(memoizedUpdaters) ? (workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, replaySuspendedUnitOfWork(lanes)) : (workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root2, lanes, memoizedUpdaters, SuspendedAndReadyToContinue));
- break;
- case SuspendedOnInstanceAndReadyToContinue:
- var resource = null;
- switch (workInProgress.tag) {
- case 26:
- resource = workInProgress.memoizedState;
- case 5:
- case 27:
- var hostFiber = workInProgress, type = hostFiber.type, props = hostFiber.pendingProps;
- if (resource ? preloadResource(resource) : preloadInstance(type, props)) {
- workInProgressSuspendedReason = NotSuspended;
- workInProgressThrownValue = null;
- var sibling = hostFiber.sibling;
- if (sibling !== null)
- workInProgress = sibling;
- else {
- var returnFiber = hostFiber.return;
- returnFiber !== null ? (workInProgress = returnFiber, completeUnitOfWork(returnFiber)) : workInProgress = null;
- }
- break b;
- }
- break;
- default:
- console.error("Unexpected type of fiber triggered a suspensey commit. This is a bug in React.");
- }
- workInProgressSuspendedReason = NotSuspended;
- workInProgressThrownValue = null;
- throwAndUnwindWorkLoop(root2, lanes, memoizedUpdaters, SuspendedOnInstanceAndReadyToContinue);
- break;
- case SuspendedOnDeprecatedThrowPromise:
- workInProgressSuspendedReason = NotSuspended;
- workInProgressThrownValue = null;
- throwAndUnwindWorkLoop(root2, lanes, memoizedUpdaters, SuspendedOnDeprecatedThrowPromise);
- break;
- case SuspendedOnHydration:
- resetWorkInProgressStack();
- workInProgressRootExitStatus = RootDidNotComplete;
- break a;
- default:
- throw Error("Unexpected SuspendedReason. This is a bug in React.");
- }
- ReactSharedInternals.actQueue !== null ? workLoopSync() : workLoopConcurrent();
- break;
- } catch (thrownValue$5) {
- handleThrow(root2, thrownValue$5);
- }
- while (1);
- resetContextDependencies();
- ReactSharedInternals.H = prevDispatcher;
- ReactSharedInternals.A = prevAsyncDispatcher;
- executionContext = prevExecutionContext;
- if (workInProgress !== null)
- return injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === "function" && injectedProfilingHooks.markRenderYielded(), RootInProgress;
- markRenderStopped();
- workInProgressRoot = null;
- workInProgressRootRenderLanes = 0;
- finishQueueingConcurrentUpdates();
- return workInProgressRootExitStatus;
- }
- function workLoopConcurrent() {
- for (;workInProgress !== null && !shouldYield(); )
- performUnitOfWork(workInProgress);
- }
- function performUnitOfWork(unitOfWork) {
- var current2 = unitOfWork.alternate;
- (unitOfWork.mode & 2) !== NoMode ? (startProfilerTimer(unitOfWork), current2 = runWithFiberInDEV(unitOfWork, beginWork, current2, unitOfWork, entangledRenderLanes), stopProfilerTimerIfRunningAndRecordDuration(unitOfWork)) : current2 = runWithFiberInDEV(unitOfWork, beginWork, current2, unitOfWork, entangledRenderLanes);
- unitOfWork.memoizedProps = unitOfWork.pendingProps;
- current2 === null ? completeUnitOfWork(unitOfWork) : workInProgress = current2;
- }
- function replaySuspendedUnitOfWork(unitOfWork) {
- var next = runWithFiberInDEV(unitOfWork, replayBeginWork, unitOfWork);
- unitOfWork.memoizedProps = unitOfWork.pendingProps;
- next === null ? completeUnitOfWork(unitOfWork) : workInProgress = next;
- }
- function replayBeginWork(unitOfWork) {
- var current2 = unitOfWork.alternate, isProfilingMode = (unitOfWork.mode & 2) !== NoMode;
- isProfilingMode && startProfilerTimer(unitOfWork);
- switch (unitOfWork.tag) {
- case 15:
- case 0:
- current2 = replayFunctionComponent(current2, unitOfWork, unitOfWork.pendingProps, unitOfWork.type, undefined, workInProgressRootRenderLanes);
- break;
- case 11:
- current2 = replayFunctionComponent(current2, unitOfWork, unitOfWork.pendingProps, unitOfWork.type.render, unitOfWork.ref, workInProgressRootRenderLanes);
- break;
- case 5:
- resetHooksOnUnwind(unitOfWork);
- default:
- unwindInterruptedWork(current2, unitOfWork), unitOfWork = workInProgress = resetWorkInProgress(unitOfWork, entangledRenderLanes), current2 = beginWork(current2, unitOfWork, entangledRenderLanes);
- }
- isProfilingMode && stopProfilerTimerIfRunningAndRecordDuration(unitOfWork);
- return current2;
- }
- function throwAndUnwindWorkLoop(root2, unitOfWork, thrownValue, suspendedReason) {
- resetContextDependencies();
- resetHooksOnUnwind(unitOfWork);
- thenableState$1 = null;
- thenableIndexCounter$1 = 0;
- var returnFiber = unitOfWork.return;
- try {
- if (throwException(root2, returnFiber, unitOfWork, thrownValue, workInProgressRootRenderLanes)) {
- workInProgressRootExitStatus = RootFatalErrored;
- logUncaughtError(root2, createCapturedValueAtFiber(thrownValue, root2.current));
- workInProgress = null;
- return;
- }
- } catch (error46) {
- if (returnFiber !== null)
- throw workInProgress = returnFiber, error46;
- workInProgressRootExitStatus = RootFatalErrored;
- logUncaughtError(root2, createCapturedValueAtFiber(thrownValue, root2.current));
- workInProgress = null;
- return;
- }
- if (unitOfWork.flags & 32768) {
- if (isHydrating || suspendedReason === SuspendedOnError)
- root2 = true;
- else if (workInProgressRootIsPrerendering || (workInProgressRootRenderLanes & 536870912) !== 0)
- root2 = false;
- else if (workInProgressRootDidSkipSuspendedSiblings = root2 = true, suspendedReason === SuspendedOnData || suspendedReason === SuspendedOnImmediate || suspendedReason === SuspendedOnDeprecatedThrowPromise)
- suspendedReason = suspenseHandlerStackCursor.current, suspendedReason !== null && suspendedReason.tag === 13 && (suspendedReason.flags |= 16384);
- unwindUnitOfWork(unitOfWork, root2);
- } else
- completeUnitOfWork(unitOfWork);
- }
- function completeUnitOfWork(unitOfWork) {
- var completedWork = unitOfWork;
- do {
- if ((completedWork.flags & 32768) !== 0) {
- unwindUnitOfWork(completedWork, workInProgressRootDidSkipSuspendedSiblings);
- return;
- }
- var current2 = completedWork.alternate;
- unitOfWork = completedWork.return;
- startProfilerTimer(completedWork);
- current2 = runWithFiberInDEV(completedWork, completeWork, current2, completedWork, entangledRenderLanes);
- (completedWork.mode & 2) !== NoMode && stopProfilerTimerIfRunningAndRecordIncompleteDuration(completedWork);
- if (current2 !== null) {
- workInProgress = current2;
- return;
- }
- completedWork = completedWork.sibling;
- if (completedWork !== null) {
- workInProgress = completedWork;
- return;
- }
- workInProgress = completedWork = unitOfWork;
- } while (completedWork !== null);
- workInProgressRootExitStatus === RootInProgress && (workInProgressRootExitStatus = RootCompleted);
- }
- function unwindUnitOfWork(unitOfWork, skipSiblings) {
- do {
- var next = unwindWork(unitOfWork.alternate, unitOfWork);
- if (next !== null) {
- next.flags &= 32767;
- workInProgress = next;
- return;
- }
- if ((unitOfWork.mode & 2) !== NoMode) {
- stopProfilerTimerIfRunningAndRecordIncompleteDuration(unitOfWork);
- next = unitOfWork.actualDuration;
- for (var child = unitOfWork.child;child !== null; )
- next += child.actualDuration, child = child.sibling;
- unitOfWork.actualDuration = next;
- }
- next = unitOfWork.return;
- next !== null && (next.flags |= 32768, next.subtreeFlags = 0, next.deletions = null);
- if (!skipSiblings && (unitOfWork = unitOfWork.sibling, unitOfWork !== null)) {
- workInProgress = unitOfWork;
- return;
- }
- workInProgress = unitOfWork = next;
- } while (unitOfWork !== null);
- workInProgressRootExitStatus = RootDidNotComplete;
- workInProgress = null;
- }
- function commitRoot(root2, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, spawnedLane, updatedLanes, suspendedRetryLanes, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
- var prevTransition = ReactSharedInternals.T, previousUpdateLanePriority = getCurrentUpdatePriority();
- try {
- setCurrentUpdatePriority(2), ReactSharedInternals.T = null, commitRootImpl(root2, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, previousUpdateLanePriority, spawnedLane, updatedLanes, suspendedRetryLanes, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime);
- } finally {
- ReactSharedInternals.T = prevTransition, setCurrentUpdatePriority(previousUpdateLanePriority);
- }
- }
- function commitRootImpl(root2, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, renderPriorityLevel, spawnedLane, updatedLanes, suspendedRetryLanes) {
- do
- flushPassiveEffects();
- while (rootWithPendingPassiveEffects !== null);
- ReactStrictModeWarnings.flushLegacyContextWarning();
- ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
- if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
- throw Error("Should not already be working.");
- var finishedWork = root2.finishedWork;
- didIncludeRenderPhaseUpdate = root2.finishedLanes;
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === "function" && injectedProfilingHooks.markCommitStarted(didIncludeRenderPhaseUpdate);
- if (finishedWork === null)
- return markCommitStopped(), null;
- didIncludeRenderPhaseUpdate === 0 && console.error("root.finishedLanes should not be empty during a commit. This is a bug in React.");
- root2.finishedWork = null;
- root2.finishedLanes = 0;
- if (finishedWork === root2.current)
- throw Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue.");
- root2.callbackNode = null;
- root2.callbackPriority = 0;
- root2.cancelPendingCommit = null;
- var remainingLanes = finishedWork.lanes | finishedWork.childLanes;
- remainingLanes |= concurrentlyUpdatedLanes;
- markRootFinished(root2, didIncludeRenderPhaseUpdate, remainingLanes, spawnedLane, updatedLanes, suspendedRetryLanes);
- root2 === workInProgressRoot && (workInProgress = workInProgressRoot = null, workInProgressRootRenderLanes = 0);
- (finishedWork.subtreeFlags & 10256) === 0 && (finishedWork.flags & 10256) === 0 || rootDoesHavePassiveEffects || (rootDoesHavePassiveEffects = true, pendingPassiveEffectsRemainingLanes = remainingLanes, pendingPassiveTransitions = transitions, scheduleCallback(NormalPriority$1, function() {
- flushPassiveEffects(true);
- return null;
- }));
- commitStartTime = now2();
- transitions = (finishedWork.flags & 15990) !== 0;
- (finishedWork.subtreeFlags & 15990) !== 0 || transitions ? (transitions = ReactSharedInternals.T, ReactSharedInternals.T = null, spawnedLane = getCurrentUpdatePriority(), setCurrentUpdatePriority(2), updatedLanes = executionContext, executionContext |= CommitContext, commitBeforeMutationEffects(root2, finishedWork), commitMutationEffects(root2, finishedWork, didIncludeRenderPhaseUpdate), resetAfterCommit(root2.containerInfo), root2.current = finishedWork, injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === "function" && injectedProfilingHooks.markLayoutEffectsStarted(didIncludeRenderPhaseUpdate), commitLayoutEffects(finishedWork, root2, didIncludeRenderPhaseUpdate), injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === "function" && injectedProfilingHooks.markLayoutEffectsStopped(), requestPaint(), executionContext = updatedLanes, setCurrentUpdatePriority(spawnedLane), ReactSharedInternals.T = transitions) : root2.current = finishedWork;
- (transitions = rootDoesHavePassiveEffects) ? (rootDoesHavePassiveEffects = false, rootWithPendingPassiveEffects = root2, pendingPassiveEffectsLanes = didIncludeRenderPhaseUpdate) : (releaseRootPooledCache(root2, remainingLanes), nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null);
- remainingLanes = root2.pendingLanes;
- remainingLanes === 0 && (legacyErrorBoundariesThatAlreadyFailed = null);
- transitions || commitDoubleInvokeEffectsInDEV(root2);
- onCommitRoot$1(finishedWork.stateNode, renderPriorityLevel);
- isDevToolsPresent && root2.memoizedUpdaters.clear();
- onCommitRoot();
- ensureRootIsScheduled(root2);
- if (recoverableErrors !== null)
- for (renderPriorityLevel = root2.onRecoverableError, finishedWork = 0;finishedWork < recoverableErrors.length; finishedWork++)
- remainingLanes = recoverableErrors[finishedWork], transitions = makeErrorInfo(remainingLanes.stack), runWithFiberInDEV(remainingLanes.source, renderPriorityLevel, remainingLanes.value, transitions);
- (pendingPassiveEffectsLanes & 3) !== 0 && flushPassiveEffects();
- remainingLanes = root2.pendingLanes;
- (didIncludeRenderPhaseUpdate & 4194218) !== 0 && (remainingLanes & 42) !== 0 ? (nestedUpdateScheduled = true, root2 === rootWithNestedUpdates ? nestedUpdateCount++ : (nestedUpdateCount = 0, rootWithNestedUpdates = root2)) : nestedUpdateCount = 0;
- flushSyncWorkAcrossRoots_impl(0, false);
- markCommitStopped();
- return null;
- }
- function makeErrorInfo(componentStack) {
- componentStack = { componentStack };
- Object.defineProperty(componentStack, "digest", {
- get: function() {
- console.error('You are accessing "digest" from the errorInfo object passed to onRecoverableError. This property is no longer provided as part of errorInfo but can be accessed as a property of the Error instance itself.');
- }
- });
- return componentStack;
- }
- function releaseRootPooledCache(root2, remainingLanes) {
- (root2.pooledCacheLanes &= remainingLanes) === 0 && (remainingLanes = root2.pooledCache, remainingLanes != null && (root2.pooledCache = null, releaseCache(remainingLanes)));
- }
- function flushPassiveEffects() {
- if (rootWithPendingPassiveEffects !== null) {
- var root2 = rootWithPendingPassiveEffects, remainingLanes = pendingPassiveEffectsRemainingLanes;
- pendingPassiveEffectsRemainingLanes = 0;
- var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes), priority = 32 > renderPriority ? 32 : renderPriority;
- renderPriority = ReactSharedInternals.T;
- var previousPriority = getCurrentUpdatePriority();
- try {
- setCurrentUpdatePriority(priority);
- ReactSharedInternals.T = null;
- if (rootWithPendingPassiveEffects === null)
- var JSCompiler_inline_result = false;
- else {
- priority = pendingPassiveTransitions;
- pendingPassiveTransitions = null;
- var root$jscomp$0 = rootWithPendingPassiveEffects, lanes = pendingPassiveEffectsLanes;
- rootWithPendingPassiveEffects = null;
- pendingPassiveEffectsLanes = 0;
- if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
- throw Error("Cannot flush passive effects while already rendering.");
- isFlushingPassiveEffects = true;
- didScheduleUpdateDuringPassiveEffects = false;
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === "function" && injectedProfilingHooks.markPassiveEffectsStarted(lanes);
- var prevExecutionContext = executionContext;
- executionContext |= CommitContext;
- commitPassiveUnmountOnFiber(root$jscomp$0.current);
- commitPassiveMountOnFiber(root$jscomp$0, root$jscomp$0.current, lanes, priority);
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === "function" && injectedProfilingHooks.markPassiveEffectsStopped();
- commitDoubleInvokeEffectsInDEV(root$jscomp$0);
- executionContext = prevExecutionContext;
- flushSyncWorkAcrossRoots_impl(0, false);
- didScheduleUpdateDuringPassiveEffects ? root$jscomp$0 === rootWithPassiveNestedUpdates ? nestedPassiveUpdateCount++ : (nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = root$jscomp$0) : nestedPassiveUpdateCount = 0;
- didScheduleUpdateDuringPassiveEffects = isFlushingPassiveEffects = false;
- if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === "function")
- try {
- injectedHook.onPostCommitFiberRoot(rendererID, root$jscomp$0);
- } catch (err) {
- hasLoggedError || (hasLoggedError = true, console.error("React instrumentation encountered an error: %s", err));
- }
- var stateNode = root$jscomp$0.current.stateNode;
- stateNode.effectDuration = 0;
- stateNode.passiveEffectDuration = 0;
- JSCompiler_inline_result = true;
- }
- return JSCompiler_inline_result;
- } finally {
- setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = renderPriority, releaseRootPooledCache(root2, remainingLanes);
- }
- }
- return false;
- }
- function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error46) {
- sourceFiber = createCapturedValueAtFiber(error46, sourceFiber);
- sourceFiber = createRootErrorUpdate(rootFiber.stateNode, sourceFiber, 2);
- rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2);
- rootFiber !== null && (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber));
- }
- function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error46) {
- isRunningInsertionEffect = false;
- if (sourceFiber.tag === 3)
- captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error46);
- else {
- for (;nearestMountedAncestor !== null; ) {
- if (nearestMountedAncestor.tag === 3) {
- captureCommitPhaseErrorOnRoot(nearestMountedAncestor, sourceFiber, error46);
- return;
- }
- if (nearestMountedAncestor.tag === 1) {
- var instance = nearestMountedAncestor.stateNode;
- if (typeof nearestMountedAncestor.type.getDerivedStateFromError === "function" || typeof instance.componentDidCatch === "function" && (legacyErrorBoundariesThatAlreadyFailed === null || !legacyErrorBoundariesThatAlreadyFailed.has(instance))) {
- sourceFiber = createCapturedValueAtFiber(error46, sourceFiber);
- error46 = createClassErrorUpdate(2);
- instance = enqueueUpdate(nearestMountedAncestor, error46, 2);
- instance !== null && (initializeClassErrorUpdate(error46, instance, nearestMountedAncestor, sourceFiber), markRootUpdated$1(instance, 2), ensureRootIsScheduled(instance));
- return;
- }
- }
- nearestMountedAncestor = nearestMountedAncestor.return;
- }
- console.error(`Internal React error: Attempted to capture a commit phase error inside a detached tree. This indicates a bug in React. Potential causes include deleting the same fiber more than once, committing an already-finished tree, or an inconsistent return pointer.
-
-Error message:
-
-%s`, error46);
- }
- }
- function attachPingListener(root2, wakeable, lanes) {
- var pingCache = root2.pingCache;
- if (pingCache === null) {
- pingCache = root2.pingCache = new PossiblyWeakMap;
- var threadIDs = new Set;
- pingCache.set(wakeable, threadIDs);
- } else
- threadIDs = pingCache.get(wakeable), threadIDs === undefined && (threadIDs = new Set, pingCache.set(wakeable, threadIDs));
- threadIDs.has(lanes) || (workInProgressRootDidAttachPingListener = true, threadIDs.add(lanes), pingCache = pingSuspendedRoot.bind(null, root2, wakeable, lanes), isDevToolsPresent && restorePendingUpdaters(root2, lanes), wakeable.then(pingCache, pingCache));
- }
- function pingSuspendedRoot(root2, wakeable, pingedLanes) {
- var pingCache = root2.pingCache;
- pingCache !== null && pingCache.delete(wakeable);
- root2.pingedLanes |= root2.suspendedLanes & pingedLanes;
- root2.warmLanes &= ~pingedLanes;
- isConcurrentActEnvironment() && ReactSharedInternals.actQueue === null && console.error(`A suspended resource finished loading inside a test, but the event was not wrapped in act(...).
-
-When testing, code that resolves suspended data should be wrapped into act(...):
-
-act(() => {
- /* finish loading suspended data */
-});
-/* assert on the output */
-
-This ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act`);
- workInProgressRoot === root2 && (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes && now$1() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS ? (executionContext & RenderContext) === NoContext && prepareFreshStack(root2, 0) : workInProgressRootPingedLanes |= pingedLanes, workInProgressSuspendedRetryLanes === workInProgressRootRenderLanes && (workInProgressSuspendedRetryLanes = 0));
- ensureRootIsScheduled(root2);
- }
- function retryTimedOutBoundary(boundaryFiber, retryLane) {
- retryLane === 0 && (retryLane = claimNextRetryLane());
- boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
- boundaryFiber !== null && (markRootUpdated$1(boundaryFiber, retryLane), ensureRootIsScheduled(boundaryFiber));
- }
- function retryDehydratedSuspenseBoundary(boundaryFiber) {
- var suspenseState = boundaryFiber.memoizedState, retryLane = 0;
- suspenseState !== null && (retryLane = suspenseState.retryLane);
- retryTimedOutBoundary(boundaryFiber, retryLane);
- }
- function resolveRetryWakeable(boundaryFiber, wakeable) {
- var retryLane = 0;
- switch (boundaryFiber.tag) {
- case 13:
- var retryCache = boundaryFiber.stateNode;
- var suspenseState = boundaryFiber.memoizedState;
- suspenseState !== null && (retryLane = suspenseState.retryLane);
- break;
- case 19:
- retryCache = boundaryFiber.stateNode;
- break;
- case 22:
- retryCache = boundaryFiber.stateNode._retryCache;
- break;
- default:
- throw Error("Pinged unknown suspense boundary type. This is probably a bug in React.");
- }
- retryCache !== null && retryCache.delete(wakeable);
- retryTimedOutBoundary(boundaryFiber, retryLane);
- }
- function recursivelyTraverseAndDoubleInvokeEffectsInDEV(root$jscomp$0, parentFiber, isInStrictMode) {
- if ((parentFiber.subtreeFlags & 33562624) !== 0)
- for (parentFiber = parentFiber.child;parentFiber !== null; ) {
- var root2 = root$jscomp$0, fiber = parentFiber, isStrictModeFiber = fiber.type === REACT_STRICT_MODE_TYPE;
- isStrictModeFiber = isInStrictMode || isStrictModeFiber;
- fiber.tag !== 22 ? fiber.flags & 33554432 ? isStrictModeFiber && runWithFiberInDEV(fiber, doubleInvokeEffectsOnFiber, root2, fiber, (fiber.mode & 64) === NoMode) : recursivelyTraverseAndDoubleInvokeEffectsInDEV(root2, fiber, isStrictModeFiber) : fiber.memoizedState === null && (isStrictModeFiber && fiber.flags & 8192 ? runWithFiberInDEV(fiber, doubleInvokeEffectsOnFiber, root2, fiber) : fiber.subtreeFlags & 33554432 && runWithFiberInDEV(fiber, recursivelyTraverseAndDoubleInvokeEffectsInDEV, root2, fiber, isStrictModeFiber));
- parentFiber = parentFiber.sibling;
- }
- }
- function doubleInvokeEffectsOnFiber(root2, fiber) {
- var shouldDoubleInvokePassiveEffects = 2 < arguments.length && arguments[2] !== undefined ? arguments[2] : true;
- setIsStrictModeForDevtools(true);
- try {
- disappearLayoutEffects(fiber), shouldDoubleInvokePassiveEffects && disconnectPassiveEffect(fiber), reappearLayoutEffects(root2, fiber.alternate, fiber, false), shouldDoubleInvokePassiveEffects && reconnectPassiveEffects(root2, fiber, 0, null, false);
- } finally {
- setIsStrictModeForDevtools(false);
- }
- }
- function commitDoubleInvokeEffectsInDEV(root2) {
- var doubleInvokeEffects = true;
- root2.current.mode & 24 || (doubleInvokeEffects = false);
- recursivelyTraverseAndDoubleInvokeEffectsInDEV(root2, root2.current, doubleInvokeEffects);
- }
- function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
- if ((executionContext & RenderContext) === NoContext) {
- var tag2 = fiber.tag;
- if (tag2 === 3 || tag2 === 1 || tag2 === 0 || tag2 === 11 || tag2 === 14 || tag2 === 15) {
- tag2 = getComponentNameFromFiber(fiber) || "ReactComponent";
- if (didWarnStateUpdateForNotYetMountedComponent !== null) {
- if (didWarnStateUpdateForNotYetMountedComponent.has(tag2))
- return;
- didWarnStateUpdateForNotYetMountedComponent.add(tag2);
- } else
- didWarnStateUpdateForNotYetMountedComponent = new Set([tag2]);
- runWithFiberInDEV(fiber, function() {
- console.error("Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously later calls tries to update the component. Move this work to useEffect instead.");
- });
- }
- }
- }
- function restorePendingUpdaters(root2, lanes) {
- isDevToolsPresent && root2.memoizedUpdaters.forEach(function(schedulingFiber) {
- addFiberToLanesMap(root2, schedulingFiber, lanes);
- });
- }
- function scheduleCallback(priorityLevel, callback) {
- var actQueue = ReactSharedInternals.actQueue;
- return actQueue !== null ? (actQueue.push(callback), fakeActCallbackNode) : scheduleCallback$3(priorityLevel, callback);
- }
- function warnIfUpdatesNotWrappedWithActDEV(fiber) {
- isConcurrentActEnvironment() && ReactSharedInternals.actQueue === null && runWithFiberInDEV(fiber, function() {
- console.error(`An update to %s inside a test was not wrapped in act(...).
-
-When testing, code that causes React state updates should be wrapped into act(...):
-
-act(() => {
- /* fire events that update state */
-});
-/* assert on the output */
-
-This ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act`, getComponentNameFromFiber(fiber));
- });
- }
- function resolveFunctionForHotReloading(type) {
- if (resolveFamily2 === null)
- return type;
- var family = resolveFamily2(type);
- return family === undefined ? type : family.current;
- }
- function resolveForwardRefForHotReloading(type) {
- if (resolveFamily2 === null)
- return type;
- var family = resolveFamily2(type);
- return family === undefined ? type !== null && type !== undefined && typeof type.render === "function" && (family = resolveFunctionForHotReloading(type.render), type.render !== family) ? (family = { $$typeof: REACT_FORWARD_REF_TYPE, render: family }, type.displayName !== undefined && (family.displayName = type.displayName), family) : type : family.current;
- }
- function isCompatibleFamilyForHotReloading(fiber, element) {
- if (resolveFamily2 === null)
- return false;
- var prevType = fiber.elementType;
- element = element.type;
- var needsCompareFamilies = false, $$typeofNextType = typeof element === "object" && element !== null ? element.$$typeof : null;
- switch (fiber.tag) {
- case 1:
- typeof element === "function" && (needsCompareFamilies = true);
- break;
- case 0:
- typeof element === "function" ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
- break;
- case 11:
- $$typeofNextType === REACT_FORWARD_REF_TYPE ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
- break;
- case 14:
- case 15:
- $$typeofNextType === REACT_MEMO_TYPE ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
- break;
- default:
- return false;
- }
- return needsCompareFamilies && (fiber = resolveFamily2(prevType), fiber !== undefined && fiber === resolveFamily2(element)) ? true : false;
- }
- function markFailedErrorBoundaryForHotReloading(fiber) {
- resolveFamily2 !== null && typeof WeakSet === "function" && (failedBoundaries === null && (failedBoundaries = new WeakSet), failedBoundaries.add(fiber));
- }
- function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
- var { alternate, child, sibling, tag: tag2, type } = fiber, candidateType = null;
- switch (tag2) {
- case 0:
- case 15:
- case 1:
- candidateType = type;
- break;
- case 11:
- candidateType = type.render;
- }
- if (resolveFamily2 === null)
- throw Error("Expected resolveFamily to be set during hot reload.");
- var needsRender = false;
- type = false;
- candidateType !== null && (candidateType = resolveFamily2(candidateType), candidateType !== undefined && (staleFamilies.has(candidateType) ? type = true : updatedFamilies.has(candidateType) && (tag2 === 1 ? type = true : needsRender = true)));
- failedBoundaries !== null && (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) && (type = true);
- type && (fiber._debugNeedsRemount = true);
- if (type || needsRender)
- alternate = enqueueConcurrentRenderForLane(fiber, 2), alternate !== null && scheduleUpdateOnFiber(alternate, fiber, 2);
- child === null || type || scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
- sibling !== null && scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
- }
- function FiberNode(tag2, pendingProps, key, mode) {
- this.tag = tag2;
- this.key = key;
- this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
- this.index = 0;
- this.refCleanup = this.ref = null;
- this.pendingProps = pendingProps;
- this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
- this.mode = mode;
- this.subtreeFlags = this.flags = 0;
- this.deletions = null;
- this.childLanes = this.lanes = 0;
- this.alternate = null;
- this.actualDuration = -0;
- this.actualStartTime = -1.1;
- this.treeBaseDuration = this.selfBaseDuration = -0;
- this._debugOwner = this._debugInfo = null;
- this._debugNeedsRemount = false;
- this._debugHookTypes = null;
- hasBadMapPolyfill || typeof Object.preventExtensions !== "function" || Object.preventExtensions(this);
- }
- function shouldConstruct(Component) {
- Component = Component.prototype;
- return !(!Component || !Component.isReactComponent);
- }
- function createWorkInProgress(current2, pendingProps) {
- var workInProgress2 = current2.alternate;
- workInProgress2 === null ? (workInProgress2 = createFiber(current2.tag, pendingProps, current2.key, current2.mode), workInProgress2.elementType = current2.elementType, workInProgress2.type = current2.type, workInProgress2.stateNode = current2.stateNode, workInProgress2._debugOwner = current2._debugOwner, workInProgress2._debugHookTypes = current2._debugHookTypes, workInProgress2.alternate = current2, current2.alternate = workInProgress2) : (workInProgress2.pendingProps = pendingProps, workInProgress2.type = current2.type, workInProgress2.flags = 0, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.actualDuration = -0, workInProgress2.actualStartTime = -1.1);
- workInProgress2.flags = current2.flags & 31457280;
- workInProgress2.childLanes = current2.childLanes;
- workInProgress2.lanes = current2.lanes;
- workInProgress2.child = current2.child;
- workInProgress2.memoizedProps = current2.memoizedProps;
- workInProgress2.memoizedState = current2.memoizedState;
- workInProgress2.updateQueue = current2.updateQueue;
- pendingProps = current2.dependencies;
- workInProgress2.dependencies = pendingProps === null ? null : {
- lanes: pendingProps.lanes,
- firstContext: pendingProps.firstContext,
- _debugThenableState: pendingProps._debugThenableState
- };
- workInProgress2.sibling = current2.sibling;
- workInProgress2.index = current2.index;
- workInProgress2.ref = current2.ref;
- workInProgress2.refCleanup = current2.refCleanup;
- workInProgress2.selfBaseDuration = current2.selfBaseDuration;
- workInProgress2.treeBaseDuration = current2.treeBaseDuration;
- workInProgress2._debugInfo = current2._debugInfo;
- workInProgress2._debugNeedsRemount = current2._debugNeedsRemount;
- switch (workInProgress2.tag) {
- case 0:
- case 15:
- workInProgress2.type = resolveFunctionForHotReloading(current2.type);
- break;
- case 1:
- workInProgress2.type = resolveFunctionForHotReloading(current2.type);
- break;
- case 11:
- workInProgress2.type = resolveForwardRefForHotReloading(current2.type);
- }
- return workInProgress2;
- }
- function resetWorkInProgress(workInProgress2, renderLanes2) {
- workInProgress2.flags &= 31457282;
- var current2 = workInProgress2.alternate;
- current2 === null ? (workInProgress2.childLanes = 0, workInProgress2.lanes = renderLanes2, workInProgress2.child = null, workInProgress2.subtreeFlags = 0, workInProgress2.memoizedProps = null, workInProgress2.memoizedState = null, workInProgress2.updateQueue = null, workInProgress2.dependencies = null, workInProgress2.stateNode = null, workInProgress2.selfBaseDuration = 0, workInProgress2.treeBaseDuration = 0) : (workInProgress2.childLanes = current2.childLanes, workInProgress2.lanes = current2.lanes, workInProgress2.child = current2.child, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.memoizedProps = current2.memoizedProps, workInProgress2.memoizedState = current2.memoizedState, workInProgress2.updateQueue = current2.updateQueue, workInProgress2.type = current2.type, renderLanes2 = current2.dependencies, workInProgress2.dependencies = renderLanes2 === null ? null : {
- lanes: renderLanes2.lanes,
- firstContext: renderLanes2.firstContext,
- _debugThenableState: renderLanes2._debugThenableState
- }, workInProgress2.selfBaseDuration = current2.selfBaseDuration, workInProgress2.treeBaseDuration = current2.treeBaseDuration);
- return workInProgress2;
- }
- function createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes) {
- var fiberTag = 0, resolvedType = type;
- if (typeof type === "function")
- shouldConstruct(type) && (fiberTag = 1), resolvedType = resolveFunctionForHotReloading(resolvedType);
- else if (typeof type === "string")
- supportsResources && supportsSingletons ? (fiberTag = getHostContext(), fiberTag = isHostHoistableType(type, pendingProps, fiberTag) ? 26 : isHostSingletonType(type) ? 27 : 5) : supportsResources ? (fiberTag = getHostContext(), fiberTag = isHostHoistableType(type, pendingProps, fiberTag) ? 26 : 5) : fiberTag = supportsSingletons ? isHostSingletonType(type) ? 27 : 5 : 5;
- else
- a:
- switch (type) {
- case REACT_FRAGMENT_TYPE:
- return createFiberFromFragment(pendingProps.children, mode, lanes, key);
- case REACT_STRICT_MODE_TYPE:
- fiberTag = 8;
- mode |= 24;
- break;
- case REACT_PROFILER_TYPE:
- return type = pendingProps, owner = mode, typeof type.id !== "string" && console.error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof type.id), key = createFiber(12, type, key, owner | 2), key.elementType = REACT_PROFILER_TYPE, key.lanes = lanes, key.stateNode = { effectDuration: 0, passiveEffectDuration: 0 }, key;
- case REACT_SUSPENSE_TYPE:
- return key = createFiber(13, pendingProps, key, mode), key.elementType = REACT_SUSPENSE_TYPE, key.lanes = lanes, key;
- case REACT_SUSPENSE_LIST_TYPE:
- return key = createFiber(19, pendingProps, key, mode), key.elementType = REACT_SUSPENSE_LIST_TYPE, key.lanes = lanes, key;
- case REACT_OFFSCREEN_TYPE:
- return createFiberFromOffscreen(pendingProps, mode, lanes, key);
- default:
- if (typeof type === "object" && type !== null)
- switch (type.$$typeof) {
- case REACT_PROVIDER_TYPE:
- case REACT_CONTEXT_TYPE:
- fiberTag = 10;
- break a;
- case REACT_CONSUMER_TYPE:
- fiberTag = 9;
- break a;
- case REACT_FORWARD_REF_TYPE:
- fiberTag = 11;
- resolvedType = resolveForwardRefForHotReloading(resolvedType);
- break a;
- case REACT_MEMO_TYPE:
- fiberTag = 14;
- break a;
- case REACT_LAZY_TYPE:
- fiberTag = 16;
- resolvedType = null;
- break a;
- }
- resolvedType = "";
- if (type === undefined || typeof type === "object" && type !== null && Object.keys(type).length === 0)
- resolvedType += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
- type === null ? pendingProps = "null" : isArrayImpl(type) ? pendingProps = "array" : type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE ? (pendingProps = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />", resolvedType = " Did you accidentally export a JSX literal instead of a component?") : pendingProps = typeof type;
- fiberTag = owner ? typeof owner.tag === "number" ? getComponentNameFromFiber(owner) : typeof owner.name === "string" ? owner.name : null : null;
- fiberTag && (resolvedType += `
-
-Check the render method of \`` + fiberTag + "`.");
- fiberTag = 29;
- pendingProps = Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + (pendingProps + "." + resolvedType));
- resolvedType = null;
- }
- key = createFiber(fiberTag, pendingProps, key, mode);
- key.elementType = type;
- key.type = resolvedType;
- key.lanes = lanes;
- key._debugOwner = owner;
- return key;
- }
- function createFiberFromElement(element, mode, lanes) {
- mode = createFiberFromTypeAndProps(element.type, element.key, element.props, element._owner, mode, lanes);
- mode._debugOwner = element._owner;
- return mode;
- }
- function createFiberFromFragment(elements2, mode, lanes, key) {
- elements2 = createFiber(7, elements2, key, mode);
- elements2.lanes = lanes;
- return elements2;
- }
- function createFiberFromOffscreen(pendingProps, mode, lanes, key) {
- pendingProps = createFiber(22, pendingProps, key, mode);
- pendingProps.elementType = REACT_OFFSCREEN_TYPE;
- pendingProps.lanes = lanes;
- var primaryChildInstance = {
- _visibility: 1,
- _pendingVisibility: 1,
- _pendingMarkers: null,
- _retryCache: null,
- _transitions: null,
- _current: null,
- detach: function() {
- var instance = primaryChildInstance, fiber = instance._current;
- if (fiber === null)
- throw Error("Calling Offscreen.detach before instance handle has been set.");
- if ((instance._pendingVisibility & 2) === 0) {
- var root2 = enqueueConcurrentRenderForLane(fiber, 2);
- root2 !== null && (instance._pendingVisibility |= 2, scheduleUpdateOnFiber(root2, fiber, 2));
- }
- },
- attach: function() {
- var instance = primaryChildInstance, fiber = instance._current;
- if (fiber === null)
- throw Error("Calling Offscreen.detach before instance handle has been set.");
- if ((instance._pendingVisibility & 2) !== 0) {
- var root2 = enqueueConcurrentRenderForLane(fiber, 2);
- root2 !== null && (instance._pendingVisibility &= -3, scheduleUpdateOnFiber(root2, fiber, 2));
- }
- }
- };
- pendingProps.stateNode = primaryChildInstance;
- return pendingProps;
- }
- function createFiberFromText(content, mode, lanes) {
- content = createFiber(6, content, null, mode);
- content.lanes = lanes;
- return content;
- }
- function createFiberFromPortal(portal, mode, lanes) {
- mode = createFiber(4, portal.children !== null ? portal.children : [], portal.key, mode);
- mode.lanes = lanes;
- mode.stateNode = {
- containerInfo: portal.containerInfo,
- pendingChildren: null,
- implementation: portal.implementation
- };
- return mode;
- }
- function FiberRootNode(containerInfo, tag2, hydrate, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, formState) {
- this.tag = 1;
- this.containerInfo = containerInfo;
- this.finishedWork = this.pingCache = this.current = this.pendingChildren = null;
- this.timeoutHandle = noTimeout;
- this.callbackNode = this.next = this.pendingContext = this.context = this.cancelPendingCommit = null;
- this.callbackPriority = 0;
- this.expirationTimes = createLaneMap(-1);
- this.entangledLanes = this.shellSuspendCounter = this.errorRecoveryDisabledLanes = this.finishedLanes = this.expiredLanes = this.warmLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
- this.entanglements = createLaneMap(0);
- this.hiddenUpdates = createLaneMap(null);
- this.identifierPrefix = identifierPrefix;
- this.onUncaughtError = onUncaughtError;
- this.onCaughtError = onCaughtError;
- this.onRecoverableError = onRecoverableError;
- this.pooledCache = null;
- this.pooledCacheLanes = 0;
- this.formState = formState;
- this.incompleteTransitions = new Map;
- this.passiveEffectDuration = this.effectDuration = -0;
- this.memoizedUpdaters = new Set;
- containerInfo = this.pendingUpdatersLaneMap = [];
- for (tag2 = 0;31 > tag2; tag2++)
- containerInfo.push(new Set);
- this._debugRootType = hydrate ? "hydrateRoot()" : "createRoot()";
- }
- function createFiberRoot(containerInfo, tag2, hydrate, initialChildren, hydrationCallbacks, isStrictMode, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks, formState) {
- containerInfo = new FiberRootNode(containerInfo, tag2, hydrate, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, formState);
- tag2 = 1;
- isStrictMode === true && (tag2 |= 24);
- isDevToolsPresent && (tag2 |= 2);
- isStrictMode = createFiber(3, null, null, tag2);
- containerInfo.current = isStrictMode;
- isStrictMode.stateNode = containerInfo;
- tag2 = createCache();
- retainCache(tag2);
- containerInfo.pooledCache = tag2;
- retainCache(tag2);
- isStrictMode.memoizedState = {
- element: initialChildren,
- isDehydrated: hydrate,
- cache: tag2
- };
- initializeUpdateQueue(isStrictMode);
- return containerInfo;
- }
- function testStringCoercion(value) {
- return "" + value;
- }
- function getContextForSubtree(parentComponent) {
- if (!parentComponent)
- return emptyContextObject;
- parentComponent = emptyContextObject;
- return parentComponent;
- }
- function updateContainerSync(element, container, parentComponent, callback) {
- container.tag === 0 && flushPassiveEffects();
- updateContainerImpl(container.current, 2, element, container, parentComponent, callback);
- return 2;
- }
- function updateContainerImpl(rootFiber, lane, element, container, parentComponent, callback) {
- if (injectedHook && typeof injectedHook.onScheduleFiberRoot === "function")
- try {
- injectedHook.onScheduleFiberRoot(rendererID, container, element);
- } catch (err) {
- hasLoggedError || (hasLoggedError = true, console.error("React instrumentation encountered an error: %s", err));
- }
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === "function" && injectedProfilingHooks.markRenderScheduled(lane);
- parentComponent = getContextForSubtree(parentComponent);
- container.context === null ? container.context = parentComponent : container.pendingContext = parentComponent;
- isRendering && current !== null && !didWarnAboutNestedUpdates && (didWarnAboutNestedUpdates = true, console.error(`Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.
-
-Check the render method of %s.`, getComponentNameFromFiber(current) || "Unknown"));
- container = createUpdate(lane);
- container.payload = { element };
- callback = callback === undefined ? null : callback;
- callback !== null && (typeof callback !== "function" && console.error("Expected the last optional `callback` argument to be a function. Instead received: %s.", callback), container.callback = callback);
- element = enqueueUpdate(rootFiber, container, lane);
- element !== null && (scheduleUpdateOnFiber(element, rootFiber, lane), entangleTransitions(element, rootFiber, lane));
- }
- function markRetryLaneImpl(fiber, retryLane) {
- fiber = fiber.memoizedState;
- if (fiber !== null && fiber.dehydrated !== null) {
- var a5 = fiber.retryLane;
- fiber.retryLane = a5 !== 0 && a5 < retryLane ? a5 : retryLane;
- }
- }
- function markRetryLaneIfNotHydrated(fiber, retryLane) {
- markRetryLaneImpl(fiber, retryLane);
- (fiber = fiber.alternate) && markRetryLaneImpl(fiber, retryLane);
- }
- function getCurrentFiberForDevTools() {
- return current;
- }
- function getLaneLabelMap() {
- for (var map7 = new Map, lane = 1, index2 = 0;31 > index2; index2++) {
- var label = getLabelForLane(lane);
- map7.set(lane, label);
- lane *= 2;
- }
- return map7;
- }
- var exports2 = {};
- var assign = Object.assign, REACT_LEGACY_ELEMENT_TYPE = Symbol.for("react.element"), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_PROVIDER_TYPE = Symbol.for("react.provider"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy");
- Symbol.for("react.scope");
- Symbol.for("react.debug_trace_mode");
- var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
- Symbol.for("react.legacy_hidden");
- Symbol.for("react.tracing_marker");
- var REACT_MEMO_CACHE_SENTINEL = Symbol.for("react.memo_cache_sentinel"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, disabledDepth = 0, prevLog, prevInfo, prevWarn, prevError, prevGroup, prevGroupCollapsed, prevGroupEnd;
- disabledLog.__reactDisabledLog = true;
- var prefix, suffix, reentry = false;
- var componentFrameCache = new (typeof WeakMap === "function" ? WeakMap : Map);
- var current = null, isRendering = false, isArrayImpl = Array.isArray, rendererVersion = $$$config.rendererVersion, rendererPackageName = $$$config.rendererPackageName, extraDevToolsConfig = $$$config.extraDevToolsConfig, getPublicInstance = $$$config.getPublicInstance, getRootHostContext = $$$config.getRootHostContext, getChildHostContext = $$$config.getChildHostContext, prepareForCommit = $$$config.prepareForCommit, resetAfterCommit = $$$config.resetAfterCommit, createInstance2 = $$$config.createInstance, appendInitialChild = $$$config.appendInitialChild, finalizeInitialChildren = $$$config.finalizeInitialChildren, shouldSetTextContent = $$$config.shouldSetTextContent, createTextInstance = $$$config.createTextInstance, scheduleTimeout = $$$config.scheduleTimeout, cancelTimeout = $$$config.cancelTimeout, noTimeout = $$$config.noTimeout, isPrimaryRenderer = $$$config.isPrimaryRenderer;
- $$$config.warnsIfNotActing;
- var { supportsMutation, supportsPersistence, supportsHydration, getInstanceFromNode } = $$$config;
- $$$config.beforeActiveInstanceBlur;
- $$$config.afterActiveInstanceBlur;
- var preparePortalMount = $$$config.preparePortalMount;
- $$$config.prepareScopeUpdate;
- $$$config.getInstanceFromScope;
- var { setCurrentUpdatePriority, getCurrentUpdatePriority, resolveUpdatePriority } = $$$config;
- $$$config.resolveEventType;
- $$$config.resolveEventTimeStamp;
- var { shouldAttemptEagerTransition, detachDeletedInstance } = $$$config;
- $$$config.requestPostPaintCallback;
- var { maySuspendCommit, preloadInstance, startSuspendingCommit, suspendInstance, waitForCommitToBeReady, NotPendingTransition, HostTransitionContext, resetFormInstance, bindToConsole, supportsMicrotasks, scheduleMicrotask, supportsTestSelectors, findFiberRoot, getBoundingRect, getTextContent, isHiddenSubtree, matchAccessibilityRole, setFocusIfFocusable, setupIntersectionObserver, appendChild, appendChildToContainer, commitTextUpdate, commitMount, commitUpdate, insertBefore, insertInContainerBefore, removeChild, removeChildFromContainer, resetTextContent, hideInstance, hideTextInstance, unhideInstance, unhideTextInstance, clearContainer, cloneInstance, createContainerChildSet, appendChildToContainerChildSet, finalizeContainerChildren, replaceContainerChildren, cloneHiddenInstance, cloneHiddenTextInstance, isSuspenseInstancePending, isSuspenseInstanceFallback, getSuspenseInstanceFallbackErrorDetails, registerSuspenseInstanceRetry, canHydrateFormStateMarker, isFormStateMarkerMatching, getNextHydratableSibling, getFirstHydratableChild, getFirstHydratableChildWithinContainer, getFirstHydratableChildWithinSuspenseInstance, canHydrateInstance, canHydrateTextInstance, canHydrateSuspenseInstance, hydrateInstance, hydrateTextInstance, hydrateSuspenseInstance, getNextHydratableInstanceAfterSuspenseInstance, commitHydratedContainer, commitHydratedSuspenseInstance, clearSuspenseBoundary, clearSuspenseBoundaryFromContainer, shouldDeleteUnhydratedTailInstances, diffHydratedPropsForDevWarnings, diffHydratedTextForDevWarnings, describeHydratableInstanceForDevWarnings, validateHydratableInstance, validateHydratableTextInstance, supportsResources, isHostHoistableType, getHoistableRoot, getResource, acquireResource, releaseResource, hydrateHoistable, mountHoistable, unmountHoistable, createHoistableInstance, prepareToCommitHoistables, mayResourceSuspendCommit, preloadResource, suspendResource, supportsSingletons, resolveSingletonInstance, clearSingleton, acquireSingletonInstance, releaseSingletonInstance, isHostSingletonType } = $$$config, valueStack = [];
- var fiberStack = [];
- var index$jscomp$0 = -1, emptyContextObject = {};
- Object.freeze(emptyContextObject);
- var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log$1 = Math.log, LN2 = Math.LN2, nextTransitionLane = 128, nextRetryLane = 4194304, scheduleCallback$3 = Scheduler.unstable_scheduleCallback, cancelCallback$1 = Scheduler.unstable_cancelCallback, shouldYield = Scheduler.unstable_shouldYield, requestPaint = Scheduler.unstable_requestPaint, now$1 = Scheduler.unstable_now, ImmediatePriority = Scheduler.unstable_ImmediatePriority, UserBlockingPriority = Scheduler.unstable_UserBlockingPriority, NormalPriority$1 = Scheduler.unstable_NormalPriority, IdlePriority = Scheduler.unstable_IdlePriority, log4 = Scheduler.log, unstable_setDisableYieldValue2 = Scheduler.unstable_setDisableYieldValue, rendererID = null, injectedHook = null, injectedProfilingHooks = null, hasLoggedError = false, isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined", objectIs = typeof Object.is === "function" ? Object.is : is, CapturedStacks = new WeakMap, forkStack = [], forkStackIndex = 0, treeForkProvider = null, treeForkCount = 0, idStack = [], idStackIndex = 0, treeContextProvider = null, treeContextId = 1, treeContextOverflow = "", contextStackCursor = createCursor(null), contextFiberStackCursor = createCursor(null), rootInstanceStackCursor = createCursor(null), hostTransitionProviderCursor = createCursor(null), needsEscaping = /["'&<>\n\t]|^\s|\s$/, hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = false, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, hydrationErrors = null, rootOrSingletonContext = false, HydrationMismatchException = Error("Hydration Mismatch Exception: This is not a real error, and should not leak into userspace. If you're seeing this, it's likely a bug in React."), NoMode = 0, concurrentQueues = [], concurrentQueuesIndex = 0, concurrentlyUpdatedLanes = 0, now2 = Scheduler.unstable_now, commitStartTime = -0, profilerStartTime = -1.1, profilerEffectDuration = -0, currentUpdateIsNested = false, nestedUpdateScheduled = false, firstScheduledRoot = null, lastScheduledRoot = null, didScheduleMicrotask = false, didScheduleMicrotask_act = false, mightHavePendingSyncWork = false, isFlushingWork = false, currentEventTransitionLane = 0, fakeActCallbackNode$1 = {}, currentEntangledListeners = null, currentEntangledPendingCount = 0, currentEntangledLane = 0, currentEntangledActionThenable = null, UpdateState = 0, ReplaceState = 1, ForceUpdate = 2, CaptureUpdate = 3, hasForceUpdate = false;
- var didWarnUpdateInsideUpdate = false;
- var currentlyProcessingQueue = null;
- var didReadFromEntangledAsyncAction = false, hasOwnProperty15 = Object.prototype.hasOwnProperty, ReactStrictModeWarnings = {
- recordUnsafeLifecycleWarnings: function() {},
- flushPendingUnsafeLifecycleWarnings: function() {},
- recordLegacyContextWarning: function() {},
- flushLegacyContextWarning: function() {},
- discardPendingWarnings: function() {}
- }, pendingComponentWillMountWarnings = [], pendingUNSAFE_ComponentWillMountWarnings = [], pendingComponentWillReceivePropsWarnings = [], pendingUNSAFE_ComponentWillReceivePropsWarnings = [], pendingComponentWillUpdateWarnings = [], pendingUNSAFE_ComponentWillUpdateWarnings = [], didWarnAboutUnsafeLifecycles = new Set;
- ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function(fiber, instance) {
- didWarnAboutUnsafeLifecycles.has(fiber.type) || (typeof instance.componentWillMount === "function" && instance.componentWillMount.__suppressDeprecationWarning !== true && pendingComponentWillMountWarnings.push(fiber), fiber.mode & 8 && typeof instance.UNSAFE_componentWillMount === "function" && pendingUNSAFE_ComponentWillMountWarnings.push(fiber), typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true && pendingComponentWillReceivePropsWarnings.push(fiber), fiber.mode & 8 && typeof instance.UNSAFE_componentWillReceiveProps === "function" && pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber), typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true && pendingComponentWillUpdateWarnings.push(fiber), fiber.mode & 8 && typeof instance.UNSAFE_componentWillUpdate === "function" && pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber));
- };
- ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() {
- var componentWillMountUniqueNames = new Set;
- 0 < pendingComponentWillMountWarnings.length && (pendingComponentWillMountWarnings.forEach(function(fiber) {
- componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
- didWarnAboutUnsafeLifecycles.add(fiber.type);
- }), pendingComponentWillMountWarnings = []);
- var UNSAFE_componentWillMountUniqueNames = new Set;
- 0 < pendingUNSAFE_ComponentWillMountWarnings.length && (pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) {
- UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
- didWarnAboutUnsafeLifecycles.add(fiber.type);
- }), pendingUNSAFE_ComponentWillMountWarnings = []);
- var componentWillReceivePropsUniqueNames = new Set;
- 0 < pendingComponentWillReceivePropsWarnings.length && (pendingComponentWillReceivePropsWarnings.forEach(function(fiber) {
- componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
- didWarnAboutUnsafeLifecycles.add(fiber.type);
- }), pendingComponentWillReceivePropsWarnings = []);
- var UNSAFE_componentWillReceivePropsUniqueNames = new Set;
- 0 < pendingUNSAFE_ComponentWillReceivePropsWarnings.length && (pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber) {
- UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
- didWarnAboutUnsafeLifecycles.add(fiber.type);
- }), pendingUNSAFE_ComponentWillReceivePropsWarnings = []);
- var componentWillUpdateUniqueNames = new Set;
- 0 < pendingComponentWillUpdateWarnings.length && (pendingComponentWillUpdateWarnings.forEach(function(fiber) {
- componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
- didWarnAboutUnsafeLifecycles.add(fiber.type);
- }), pendingComponentWillUpdateWarnings = []);
- var UNSAFE_componentWillUpdateUniqueNames = new Set;
- 0 < pendingUNSAFE_ComponentWillUpdateWarnings.length && (pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) {
- UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
- didWarnAboutUnsafeLifecycles.add(fiber.type);
- }), pendingUNSAFE_ComponentWillUpdateWarnings = []);
- if (0 < UNSAFE_componentWillMountUniqueNames.size) {
- var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
- console.error(`Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.
-
-* Move code with side effects to componentDidMount, and set initial state in the constructor.
-
-Please update the following components: %s`, sortedNames);
- }
- 0 < UNSAFE_componentWillReceivePropsUniqueNames.size && (sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames), console.error(`Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.
-
-* Move data fetching code or side effects to componentDidUpdate.
-* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state
-
-Please update the following components: %s`, sortedNames));
- 0 < UNSAFE_componentWillUpdateUniqueNames.size && (sortedNames = setToSortedString(UNSAFE_componentWillUpdateUniqueNames), console.error(`Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.
-
-* Move data fetching code or side effects to componentDidUpdate.
-
-Please update the following components: %s`, sortedNames));
- 0 < componentWillMountUniqueNames.size && (sortedNames = setToSortedString(componentWillMountUniqueNames), console.warn(`componentWillMount has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.
-
-* Move code with side effects to componentDidMount, and set initial state in the constructor.
-* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run \`npx react-codemod rename-unsafe-lifecycles\` in your project source folder.
-
-Please update the following components: %s`, sortedNames));
- 0 < componentWillReceivePropsUniqueNames.size && (sortedNames = setToSortedString(componentWillReceivePropsUniqueNames), console.warn(`componentWillReceiveProps has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.
-
-* Move data fetching code or side effects to componentDidUpdate.
-* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state
-* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run \`npx react-codemod rename-unsafe-lifecycles\` in your project source folder.
-
-Please update the following components: %s`, sortedNames));
- 0 < componentWillUpdateUniqueNames.size && (sortedNames = setToSortedString(componentWillUpdateUniqueNames), console.warn(`componentWillUpdate has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.
-
-* Move data fetching code or side effects to componentDidUpdate.
-* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run \`npx react-codemod rename-unsafe-lifecycles\` in your project source folder.
-
-Please update the following components: %s`, sortedNames));
- };
- var pendingLegacyContextWarning = new Map, didWarnAboutLegacyContext = new Set;
- ReactStrictModeWarnings.recordLegacyContextWarning = function(fiber, instance) {
- var strictRoot = null;
- for (var node = fiber;node !== null; )
- node.mode & 8 && (strictRoot = node), node = node.return;
- strictRoot === null ? console.error("Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue.") : !didWarnAboutLegacyContext.has(fiber.type) && (node = pendingLegacyContextWarning.get(strictRoot), fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === "function") && (node === undefined && (node = [], pendingLegacyContextWarning.set(strictRoot, node)), node.push(fiber));
- };
- ReactStrictModeWarnings.flushLegacyContextWarning = function() {
- pendingLegacyContextWarning.forEach(function(fiberArray) {
- if (fiberArray.length !== 0) {
- var firstFiber = fiberArray[0], uniqueNames = new Set;
- fiberArray.forEach(function(fiber) {
- uniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
- didWarnAboutLegacyContext.add(fiber.type);
- });
- var sortedNames = setToSortedString(uniqueNames);
- runWithFiberInDEV(firstFiber, function() {
- console.error(`Legacy context API has been detected within a strict-mode tree.
-
-The old API will be supported in all 16.x releases, but applications using it should migrate to the new version.
-
-Please update the following components: %s
-
-Learn more about this warning here: https://react.dev/link/legacy-context`, sortedNames);
- });
- }
- });
- };
- ReactStrictModeWarnings.discardPendingWarnings = function() {
- pendingComponentWillMountWarnings = [];
- pendingUNSAFE_ComponentWillMountWarnings = [];
- pendingComponentWillReceivePropsWarnings = [];
- pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
- pendingComponentWillUpdateWarnings = [];
- pendingUNSAFE_ComponentWillUpdateWarnings = [];
- pendingLegacyContextWarning = new Map;
- };
- var SuspenseException = Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`"), SuspenseyCommitException = Error("Suspense Exception: This is not a real error, and should not leak into userspace. If you're seeing this, it's likely a bug in React."), noopSuspenseyCommitThenable = {
- then: function() {
- console.error('Internal React error: A listener was unexpectedly attached to a "noop" thenable. This is a bug in React. Please file an issue.');
- }
- }, suspendedThenable = null, needsToResetSuspendedThenableDEV = false, callComponent = {
- "react-stack-bottom-frame": function(Component, props, secondArg) {
- var wasRendering = isRendering;
- isRendering = true;
- try {
- return Component(props, secondArg);
- } finally {
- isRendering = wasRendering;
- }
- }
- }, callComponentInDEV = callComponent["react-stack-bottom-frame"].bind(callComponent), callRender = {
- "react-stack-bottom-frame": function(instance) {
- var wasRendering = isRendering;
- isRendering = true;
- try {
- return instance.render();
- } finally {
- isRendering = wasRendering;
- }
- }
- }, callRenderInDEV = callRender["react-stack-bottom-frame"].bind(callRender), callComponentDidMount = {
- "react-stack-bottom-frame": function(finishedWork, instance) {
- try {
- instance.componentDidMount();
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- }, callComponentDidMountInDEV = callComponentDidMount["react-stack-bottom-frame"].bind(callComponentDidMount), callComponentDidUpdate = {
- "react-stack-bottom-frame": function(finishedWork, instance, prevProps, prevState, snapshot) {
- try {
- instance.componentDidUpdate(prevProps, prevState, snapshot);
- } catch (error46) {
- captureCommitPhaseError(finishedWork, finishedWork.return, error46);
- }
- }
- }, callComponentDidUpdateInDEV = callComponentDidUpdate["react-stack-bottom-frame"].bind(callComponentDidUpdate), callComponentDidCatch = {
- "react-stack-bottom-frame": function(instance, errorInfo) {
- var stack = errorInfo.stack;
- instance.componentDidCatch(errorInfo.value, {
- componentStack: stack !== null ? stack : ""
- });
- }
- }, callComponentDidCatchInDEV = callComponentDidCatch["react-stack-bottom-frame"].bind(callComponentDidCatch), callComponentWillUnmount = {
- "react-stack-bottom-frame": function(current2, nearestMountedAncestor, instance) {
- try {
- instance.componentWillUnmount();
- } catch (error46) {
- captureCommitPhaseError(current2, nearestMountedAncestor, error46);
- }
- }
- }, callComponentWillUnmountInDEV = callComponentWillUnmount["react-stack-bottom-frame"].bind(callComponentWillUnmount), callCreate = {
- "react-stack-bottom-frame": function(effect) {
- var create = effect.create;
- effect = effect.inst;
- create = create();
- return effect.destroy = create;
- }
- }, callCreateInDEV = callCreate["react-stack-bottom-frame"].bind(callCreate), callDestroy = {
- "react-stack-bottom-frame": function(current2, nearestMountedAncestor, destroy2) {
- try {
- destroy2();
- } catch (error46) {
- captureCommitPhaseError(current2, nearestMountedAncestor, error46);
- }
- }
- }, callDestroyInDEV = callDestroy["react-stack-bottom-frame"].bind(callDestroy), callLazyInit = {
- "react-stack-bottom-frame": function(lazy2) {
- var init = lazy2._init;
- return init(lazy2._payload);
- }
- }, callLazyInitInDEV = callLazyInit["react-stack-bottom-frame"].bind(callLazyInit), thenableState$1 = null, thenableIndexCounter$1 = 0, currentDebugInfo = null, didWarnAboutMaps;
- var didWarnAboutGenerators = didWarnAboutMaps = false;
- var ownerHasKeyUseWarning = {};
- var ownerHasFunctionTypeWarning = {};
- var ownerHasSymbolTypeWarning = {};
- warnForMissingKey = function(returnFiber, workInProgress2, child) {
- if (child !== null && typeof child === "object" && child._store && (!child._store.validated && child.key == null || child._store.validated === 2)) {
- if (typeof child._store !== "object")
- throw Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.");
- child._store.validated = 1;
- var componentName2 = getComponentNameFromFiber(returnFiber), componentKey = componentName2 || "null";
- if (!ownerHasKeyUseWarning[componentKey]) {
- ownerHasKeyUseWarning[componentKey] = true;
- child = child._owner;
- returnFiber = returnFiber._debugOwner;
- var currentComponentErrorInfo = "";
- returnFiber && typeof returnFiber.tag === "number" && (componentKey = getComponentNameFromFiber(returnFiber)) && (currentComponentErrorInfo = `
-
-Check the render method of \`` + componentKey + "`.");
- currentComponentErrorInfo || componentName2 && (currentComponentErrorInfo = `
-
-Check the top-level render call using <` + componentName2 + ">.");
- var childOwnerAppendix = "";
- child != null && returnFiber !== child && (componentName2 = null, typeof child.tag === "number" ? componentName2 = getComponentNameFromFiber(child) : typeof child.name === "string" && (componentName2 = child.name), componentName2 && (childOwnerAppendix = " It was passed a child from " + componentName2 + "."));
- runWithFiberInDEV(workInProgress2, function() {
- console.error('Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.', currentComponentErrorInfo, childOwnerAppendix);
- });
- }
- }
- };
- var reconcileChildFibers = createChildReconciler(true), mountChildFibers = createChildReconciler(false), currentTreeHiddenStackCursor = createCursor(null), prevEntangledRenderLanesCursor = createCursor(0), suspenseHandlerStackCursor = createCursor(null), shellBoundary = null, SubtreeSuspenseContextMask = 1, ForceSuspenseFallback = 2, suspenseStackCursor = createCursor(0), NoFlags = 0, HasEffect = 1, Insertion = 2, Layout = 4, Passive = 8, didWarnUncachedGetSnapshot;
- var didWarnAboutMismatchedHooksForComponent = new Set;
- var didWarnAboutUseWrappedInTryCatch = new Set;
- var didWarnAboutAsyncClientComponent = new Set;
- var didWarnAboutUseFormState = new Set;
- var renderLanes = 0, currentlyRenderingFiber$1 = null, currentHook = null, workInProgressHook = null, didScheduleRenderPhaseUpdate = false, didScheduleRenderPhaseUpdateDuringThisPass = false, shouldDoubleInvokeUserFnsInHooksDEV = false, localIdCounter = 0, thenableIndexCounter = 0, thenableState = null, globalClientIdCounter = 0, RE_RENDER_LIMIT = 25, currentHookNameInDev = null, hookTypesDev = null, hookTypesUpdateIndexDev = -1, ignorePreviousDependencies = false;
- var createFunctionComponentUpdateQueue = function() {
- return { lastEffect: null, events: null, stores: null, memoCache: null };
- };
- var ContextOnlyDispatcher = {
- readContext,
- use: use2,
- useCallback: throwInvalidHookError,
- useContext: throwInvalidHookError,
- useEffect: throwInvalidHookError,
- useImperativeHandle: throwInvalidHookError,
- useLayoutEffect: throwInvalidHookError,
- useInsertionEffect: throwInvalidHookError,
- useMemo: throwInvalidHookError,
- useReducer: throwInvalidHookError,
- useRef: throwInvalidHookError,
- useState: throwInvalidHookError,
- useDebugValue: throwInvalidHookError,
- useDeferredValue: throwInvalidHookError,
- useTransition: throwInvalidHookError,
- useSyncExternalStore: throwInvalidHookError,
- useId: throwInvalidHookError
- };
- ContextOnlyDispatcher.useCacheRefresh = throwInvalidHookError;
- ContextOnlyDispatcher.useMemoCache = throwInvalidHookError;
- ContextOnlyDispatcher.useHostTransitionStatus = throwInvalidHookError;
- ContextOnlyDispatcher.useFormState = throwInvalidHookError;
- ContextOnlyDispatcher.useActionState = throwInvalidHookError;
- ContextOnlyDispatcher.useOptimistic = throwInvalidHookError;
- var HooksDispatcherOnMountInDEV = null, HooksDispatcherOnMountWithHookTypesInDEV = null, HooksDispatcherOnUpdateInDEV = null, HooksDispatcherOnRerenderInDEV = null, InvalidNestedHooksDispatcherOnMountInDEV = null, InvalidNestedHooksDispatcherOnUpdateInDEV = null, InvalidNestedHooksDispatcherOnRerenderInDEV = null;
- HooksDispatcherOnMountInDEV = {
- readContext: function(context4) {
- return readContext(context4);
- },
- use: use2,
- useCallback: function(callback, deps) {
- currentHookNameInDev = "useCallback";
- mountHookTypesDev();
- checkDepsAreArrayDev(deps);
- return mountCallback(callback, deps);
- },
- useContext: function(context4) {
- currentHookNameInDev = "useContext";
- mountHookTypesDev();
- return readContext(context4);
- },
- useEffect: function(create, deps) {
- currentHookNameInDev = "useEffect";
- mountHookTypesDev();
- checkDepsAreArrayDev(deps);
- return mountEffect(create, deps);
- },
- useImperativeHandle: function(ref, create, deps) {
- currentHookNameInDev = "useImperativeHandle";
- mountHookTypesDev();
- checkDepsAreArrayDev(deps);
- return mountImperativeHandle(ref, create, deps);
- },
- useInsertionEffect: function(create, deps) {
- currentHookNameInDev = "useInsertionEffect";
- mountHookTypesDev();
- checkDepsAreArrayDev(deps);
- mountEffectImpl(4, Insertion, create, deps);
- },
- useLayoutEffect: function(create, deps) {
- currentHookNameInDev = "useLayoutEffect";
- mountHookTypesDev();
- checkDepsAreArrayDev(deps);
- return mountLayoutEffect(create, deps);
- },
- useMemo: function(create, deps) {
- currentHookNameInDev = "useMemo";
- mountHookTypesDev();
- checkDepsAreArrayDev(deps);
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
- try {
- return mountMemo(create, deps);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useReducer: function(reducer, initialArg, init) {
- currentHookNameInDev = "useReducer";
- mountHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
- try {
- return mountReducer(reducer, initialArg, init);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useRef: function(initialValue) {
- currentHookNameInDev = "useRef";
- mountHookTypesDev();
- return mountRef(initialValue);
- },
- useState: function(initialState) {
- currentHookNameInDev = "useState";
- mountHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
- try {
- return mountState(initialState);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useDebugValue: function() {
- currentHookNameInDev = "useDebugValue";
- mountHookTypesDev();
- },
- useDeferredValue: function(value, initialValue) {
- currentHookNameInDev = "useDeferredValue";
- mountHookTypesDev();
- return mountDeferredValue(value, initialValue);
- },
- useTransition: function() {
- currentHookNameInDev = "useTransition";
- mountHookTypesDev();
- return mountTransition();
- },
- useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
- currentHookNameInDev = "useSyncExternalStore";
- mountHookTypesDev();
- return mountSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot);
- },
- useId: function() {
- currentHookNameInDev = "useId";
- mountHookTypesDev();
- return mountId();
- },
- useCacheRefresh: function() {
- currentHookNameInDev = "useCacheRefresh";
- mountHookTypesDev();
- return mountRefresh();
- }
- };
- HooksDispatcherOnMountInDEV.useMemoCache = useMemoCache;
- HooksDispatcherOnMountInDEV.useHostTransitionStatus = useHostTransitionStatus;
- HooksDispatcherOnMountInDEV.useFormState = function(action, initialState) {
- currentHookNameInDev = "useFormState";
- mountHookTypesDev();
- warnOnUseFormStateInDev();
- return mountActionState(action, initialState);
- };
- HooksDispatcherOnMountInDEV.useActionState = function(action, initialState) {
- currentHookNameInDev = "useActionState";
- mountHookTypesDev();
- return mountActionState(action, initialState);
- };
- HooksDispatcherOnMountInDEV.useOptimistic = function(passthrough) {
- currentHookNameInDev = "useOptimistic";
- mountHookTypesDev();
- return mountOptimistic(passthrough);
- };
- HooksDispatcherOnMountWithHookTypesInDEV = {
- readContext: function(context4) {
- return readContext(context4);
- },
- use: use2,
- useCallback: function(callback, deps) {
- currentHookNameInDev = "useCallback";
- updateHookTypesDev();
- return mountCallback(callback, deps);
- },
- useContext: function(context4) {
- currentHookNameInDev = "useContext";
- updateHookTypesDev();
- return readContext(context4);
- },
- useEffect: function(create, deps) {
- currentHookNameInDev = "useEffect";
- updateHookTypesDev();
- return mountEffect(create, deps);
- },
- useImperativeHandle: function(ref, create, deps) {
- currentHookNameInDev = "useImperativeHandle";
- updateHookTypesDev();
- return mountImperativeHandle(ref, create, deps);
- },
- useInsertionEffect: function(create, deps) {
- currentHookNameInDev = "useInsertionEffect";
- updateHookTypesDev();
- mountEffectImpl(4, Insertion, create, deps);
- },
- useLayoutEffect: function(create, deps) {
- currentHookNameInDev = "useLayoutEffect";
- updateHookTypesDev();
- return mountLayoutEffect(create, deps);
- },
- useMemo: function(create, deps) {
- currentHookNameInDev = "useMemo";
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
- try {
- return mountMemo(create, deps);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useReducer: function(reducer, initialArg, init) {
- currentHookNameInDev = "useReducer";
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
- try {
- return mountReducer(reducer, initialArg, init);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useRef: function(initialValue) {
- currentHookNameInDev = "useRef";
- updateHookTypesDev();
- return mountRef(initialValue);
- },
- useState: function(initialState) {
- currentHookNameInDev = "useState";
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
- try {
- return mountState(initialState);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useDebugValue: function() {
- currentHookNameInDev = "useDebugValue";
- updateHookTypesDev();
- },
- useDeferredValue: function(value, initialValue) {
- currentHookNameInDev = "useDeferredValue";
- updateHookTypesDev();
- return mountDeferredValue(value, initialValue);
- },
- useTransition: function() {
- currentHookNameInDev = "useTransition";
- updateHookTypesDev();
- return mountTransition();
- },
- useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
- currentHookNameInDev = "useSyncExternalStore";
- updateHookTypesDev();
- return mountSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot);
- },
- useId: function() {
- currentHookNameInDev = "useId";
- updateHookTypesDev();
- return mountId();
- },
- useCacheRefresh: function() {
- currentHookNameInDev = "useCacheRefresh";
- updateHookTypesDev();
- return mountRefresh();
- }
- };
- HooksDispatcherOnMountWithHookTypesInDEV.useMemoCache = useMemoCache;
- HooksDispatcherOnMountWithHookTypesInDEV.useHostTransitionStatus = useHostTransitionStatus;
- HooksDispatcherOnMountWithHookTypesInDEV.useFormState = function(action, initialState) {
- currentHookNameInDev = "useFormState";
- updateHookTypesDev();
- warnOnUseFormStateInDev();
- return mountActionState(action, initialState);
- };
- HooksDispatcherOnMountWithHookTypesInDEV.useActionState = function(action, initialState) {
- currentHookNameInDev = "useActionState";
- updateHookTypesDev();
- return mountActionState(action, initialState);
- };
- HooksDispatcherOnMountWithHookTypesInDEV.useOptimistic = function(passthrough) {
- currentHookNameInDev = "useOptimistic";
- updateHookTypesDev();
- return mountOptimistic(passthrough);
- };
- HooksDispatcherOnUpdateInDEV = {
- readContext: function(context4) {
- return readContext(context4);
- },
- use: use2,
- useCallback: function(callback, deps) {
- currentHookNameInDev = "useCallback";
- updateHookTypesDev();
- return updateCallback(callback, deps);
- },
- useContext: function(context4) {
- currentHookNameInDev = "useContext";
- updateHookTypesDev();
- return readContext(context4);
- },
- useEffect: function(create, deps) {
- currentHookNameInDev = "useEffect";
- updateHookTypesDev();
- updateEffectImpl(2048, Passive, create, deps);
- },
- useImperativeHandle: function(ref, create, deps) {
- currentHookNameInDev = "useImperativeHandle";
- updateHookTypesDev();
- return updateImperativeHandle(ref, create, deps);
- },
- useInsertionEffect: function(create, deps) {
- currentHookNameInDev = "useInsertionEffect";
- updateHookTypesDev();
- return updateEffectImpl(4, Insertion, create, deps);
- },
- useLayoutEffect: function(create, deps) {
- currentHookNameInDev = "useLayoutEffect";
- updateHookTypesDev();
- return updateEffectImpl(4, Layout, create, deps);
- },
- useMemo: function(create, deps) {
- currentHookNameInDev = "useMemo";
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
- try {
- return updateMemo(create, deps);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useReducer: function(reducer, initialArg, init) {
- currentHookNameInDev = "useReducer";
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
- try {
- return updateReducer(reducer, initialArg, init);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useRef: function() {
- currentHookNameInDev = "useRef";
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- },
- useState: function() {
- currentHookNameInDev = "useState";
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
- try {
- return updateReducer(basicStateReducer);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useDebugValue: function() {
- currentHookNameInDev = "useDebugValue";
- updateHookTypesDev();
- },
- useDeferredValue: function(value, initialValue) {
- currentHookNameInDev = "useDeferredValue";
- updateHookTypesDev();
- return updateDeferredValue(value, initialValue);
- },
- useTransition: function() {
- currentHookNameInDev = "useTransition";
- updateHookTypesDev();
- return updateTransition();
- },
- useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
- currentHookNameInDev = "useSyncExternalStore";
- updateHookTypesDev();
- return updateSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot);
- },
- useId: function() {
- currentHookNameInDev = "useId";
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- },
- useCacheRefresh: function() {
- currentHookNameInDev = "useCacheRefresh";
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- }
- };
- HooksDispatcherOnUpdateInDEV.useMemoCache = useMemoCache;
- HooksDispatcherOnUpdateInDEV.useHostTransitionStatus = useHostTransitionStatus;
- HooksDispatcherOnUpdateInDEV.useFormState = function(action) {
- currentHookNameInDev = "useFormState";
- updateHookTypesDev();
- warnOnUseFormStateInDev();
- return updateActionState(action);
- };
- HooksDispatcherOnUpdateInDEV.useActionState = function(action) {
- currentHookNameInDev = "useActionState";
- updateHookTypesDev();
- return updateActionState(action);
- };
- HooksDispatcherOnUpdateInDEV.useOptimistic = function(passthrough, reducer) {
- currentHookNameInDev = "useOptimistic";
- updateHookTypesDev();
- return updateOptimistic(passthrough, reducer);
- };
- HooksDispatcherOnRerenderInDEV = {
- readContext: function(context4) {
- return readContext(context4);
- },
- use: use2,
- useCallback: function(callback, deps) {
- currentHookNameInDev = "useCallback";
- updateHookTypesDev();
- return updateCallback(callback, deps);
- },
- useContext: function(context4) {
- currentHookNameInDev = "useContext";
- updateHookTypesDev();
- return readContext(context4);
- },
- useEffect: function(create, deps) {
- currentHookNameInDev = "useEffect";
- updateHookTypesDev();
- updateEffectImpl(2048, Passive, create, deps);
- },
- useImperativeHandle: function(ref, create, deps) {
- currentHookNameInDev = "useImperativeHandle";
- updateHookTypesDev();
- return updateImperativeHandle(ref, create, deps);
- },
- useInsertionEffect: function(create, deps) {
- currentHookNameInDev = "useInsertionEffect";
- updateHookTypesDev();
- return updateEffectImpl(4, Insertion, create, deps);
- },
- useLayoutEffect: function(create, deps) {
- currentHookNameInDev = "useLayoutEffect";
- updateHookTypesDev();
- return updateEffectImpl(4, Layout, create, deps);
- },
- useMemo: function(create, deps) {
- currentHookNameInDev = "useMemo";
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
- try {
- return updateMemo(create, deps);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useReducer: function(reducer, initialArg, init) {
- currentHookNameInDev = "useReducer";
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
- try {
- return rerenderReducer(reducer, initialArg, init);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useRef: function() {
- currentHookNameInDev = "useRef";
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- },
- useState: function() {
- currentHookNameInDev = "useState";
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
- try {
- return rerenderReducer(basicStateReducer);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useDebugValue: function() {
- currentHookNameInDev = "useDebugValue";
- updateHookTypesDev();
- },
- useDeferredValue: function(value, initialValue) {
- currentHookNameInDev = "useDeferredValue";
- updateHookTypesDev();
- return rerenderDeferredValue(value, initialValue);
- },
- useTransition: function() {
- currentHookNameInDev = "useTransition";
- updateHookTypesDev();
- return rerenderTransition();
- },
- useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
- currentHookNameInDev = "useSyncExternalStore";
- updateHookTypesDev();
- return updateSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot);
- },
- useId: function() {
- currentHookNameInDev = "useId";
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- },
- useCacheRefresh: function() {
- currentHookNameInDev = "useCacheRefresh";
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- }
- };
- HooksDispatcherOnRerenderInDEV.useMemoCache = useMemoCache;
- HooksDispatcherOnRerenderInDEV.useHostTransitionStatus = useHostTransitionStatus;
- HooksDispatcherOnRerenderInDEV.useFormState = function(action) {
- currentHookNameInDev = "useFormState";
- updateHookTypesDev();
- warnOnUseFormStateInDev();
- return rerenderActionState(action);
- };
- HooksDispatcherOnRerenderInDEV.useActionState = function(action) {
- currentHookNameInDev = "useActionState";
- updateHookTypesDev();
- return rerenderActionState(action);
- };
- HooksDispatcherOnRerenderInDEV.useOptimistic = function(passthrough, reducer) {
- currentHookNameInDev = "useOptimistic";
- updateHookTypesDev();
- return rerenderOptimistic(passthrough, reducer);
- };
- InvalidNestedHooksDispatcherOnMountInDEV = {
- readContext: function(context4) {
- warnInvalidContextAccess();
- return readContext(context4);
- },
- use: function(usable) {
- warnInvalidHookAccess();
- return use2(usable);
- },
- useCallback: function(callback, deps) {
- currentHookNameInDev = "useCallback";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountCallback(callback, deps);
- },
- useContext: function(context4) {
- currentHookNameInDev = "useContext";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return readContext(context4);
- },
- useEffect: function(create, deps) {
- currentHookNameInDev = "useEffect";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountEffect(create, deps);
- },
- useImperativeHandle: function(ref, create, deps) {
- currentHookNameInDev = "useImperativeHandle";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountImperativeHandle(ref, create, deps);
- },
- useInsertionEffect: function(create, deps) {
- currentHookNameInDev = "useInsertionEffect";
- warnInvalidHookAccess();
- mountHookTypesDev();
- mountEffectImpl(4, Insertion, create, deps);
- },
- useLayoutEffect: function(create, deps) {
- currentHookNameInDev = "useLayoutEffect";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountLayoutEffect(create, deps);
- },
- useMemo: function(create, deps) {
- currentHookNameInDev = "useMemo";
- warnInvalidHookAccess();
- mountHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
- try {
- return mountMemo(create, deps);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useReducer: function(reducer, initialArg, init) {
- currentHookNameInDev = "useReducer";
- warnInvalidHookAccess();
- mountHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
- try {
- return mountReducer(reducer, initialArg, init);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useRef: function(initialValue) {
- currentHookNameInDev = "useRef";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountRef(initialValue);
- },
- useState: function(initialState) {
- currentHookNameInDev = "useState";
- warnInvalidHookAccess();
- mountHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
- try {
- return mountState(initialState);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useDebugValue: function() {
- currentHookNameInDev = "useDebugValue";
- warnInvalidHookAccess();
- mountHookTypesDev();
- },
- useDeferredValue: function(value, initialValue) {
- currentHookNameInDev = "useDeferredValue";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountDeferredValue(value, initialValue);
- },
- useTransition: function() {
- currentHookNameInDev = "useTransition";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountTransition();
- },
- useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
- currentHookNameInDev = "useSyncExternalStore";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot);
- },
- useId: function() {
- currentHookNameInDev = "useId";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountId();
- },
- useCacheRefresh: function() {
- currentHookNameInDev = "useCacheRefresh";
- mountHookTypesDev();
- return mountRefresh();
- },
- useMemoCache: function(size) {
- warnInvalidHookAccess();
- return useMemoCache(size);
- }
- };
- InvalidNestedHooksDispatcherOnMountInDEV.useHostTransitionStatus = useHostTransitionStatus;
- InvalidNestedHooksDispatcherOnMountInDEV.useFormState = function(action, initialState) {
- currentHookNameInDev = "useFormState";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountActionState(action, initialState);
- };
- InvalidNestedHooksDispatcherOnMountInDEV.useActionState = function(action, initialState) {
- currentHookNameInDev = "useActionState";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountActionState(action, initialState);
- };
- InvalidNestedHooksDispatcherOnMountInDEV.useOptimistic = function(passthrough) {
- currentHookNameInDev = "useOptimistic";
- warnInvalidHookAccess();
- mountHookTypesDev();
- return mountOptimistic(passthrough);
- };
- InvalidNestedHooksDispatcherOnUpdateInDEV = {
- readContext: function(context4) {
- warnInvalidContextAccess();
- return readContext(context4);
- },
- use: function(usable) {
- warnInvalidHookAccess();
- return use2(usable);
- },
- useCallback: function(callback, deps) {
- currentHookNameInDev = "useCallback";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateCallback(callback, deps);
- },
- useContext: function(context4) {
- currentHookNameInDev = "useContext";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return readContext(context4);
- },
- useEffect: function(create, deps) {
- currentHookNameInDev = "useEffect";
- warnInvalidHookAccess();
- updateHookTypesDev();
- updateEffectImpl(2048, Passive, create, deps);
- },
- useImperativeHandle: function(ref, create, deps) {
- currentHookNameInDev = "useImperativeHandle";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateImperativeHandle(ref, create, deps);
- },
- useInsertionEffect: function(create, deps) {
- currentHookNameInDev = "useInsertionEffect";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateEffectImpl(4, Insertion, create, deps);
- },
- useLayoutEffect: function(create, deps) {
- currentHookNameInDev = "useLayoutEffect";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateEffectImpl(4, Layout, create, deps);
- },
- useMemo: function(create, deps) {
- currentHookNameInDev = "useMemo";
- warnInvalidHookAccess();
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
- try {
- return updateMemo(create, deps);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useReducer: function(reducer, initialArg, init) {
- currentHookNameInDev = "useReducer";
- warnInvalidHookAccess();
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
- try {
- return updateReducer(reducer, initialArg, init);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useRef: function() {
- currentHookNameInDev = "useRef";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- },
- useState: function() {
- currentHookNameInDev = "useState";
- warnInvalidHookAccess();
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
- try {
- return updateReducer(basicStateReducer);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useDebugValue: function() {
- currentHookNameInDev = "useDebugValue";
- warnInvalidHookAccess();
- updateHookTypesDev();
- },
- useDeferredValue: function(value, initialValue) {
- currentHookNameInDev = "useDeferredValue";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateDeferredValue(value, initialValue);
- },
- useTransition: function() {
- currentHookNameInDev = "useTransition";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateTransition();
- },
- useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
- currentHookNameInDev = "useSyncExternalStore";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot);
- },
- useId: function() {
- currentHookNameInDev = "useId";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- },
- useCacheRefresh: function() {
- currentHookNameInDev = "useCacheRefresh";
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- },
- useMemoCache: function(size) {
- warnInvalidHookAccess();
- return useMemoCache(size);
- }
- };
- InvalidNestedHooksDispatcherOnUpdateInDEV.useHostTransitionStatus = useHostTransitionStatus;
- InvalidNestedHooksDispatcherOnUpdateInDEV.useFormState = function(action) {
- currentHookNameInDev = "useFormState";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateActionState(action);
- };
- InvalidNestedHooksDispatcherOnUpdateInDEV.useActionState = function(action) {
- currentHookNameInDev = "useActionState";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateActionState(action);
- };
- InvalidNestedHooksDispatcherOnUpdateInDEV.useOptimistic = function(passthrough, reducer) {
- currentHookNameInDev = "useOptimistic";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateOptimistic(passthrough, reducer);
- };
- InvalidNestedHooksDispatcherOnRerenderInDEV = {
- readContext: function(context4) {
- warnInvalidContextAccess();
- return readContext(context4);
- },
- use: function(usable) {
- warnInvalidHookAccess();
- return use2(usable);
- },
- useCallback: function(callback, deps) {
- currentHookNameInDev = "useCallback";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateCallback(callback, deps);
- },
- useContext: function(context4) {
- currentHookNameInDev = "useContext";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return readContext(context4);
- },
- useEffect: function(create, deps) {
- currentHookNameInDev = "useEffect";
- warnInvalidHookAccess();
- updateHookTypesDev();
- updateEffectImpl(2048, Passive, create, deps);
- },
- useImperativeHandle: function(ref, create, deps) {
- currentHookNameInDev = "useImperativeHandle";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateImperativeHandle(ref, create, deps);
- },
- useInsertionEffect: function(create, deps) {
- currentHookNameInDev = "useInsertionEffect";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateEffectImpl(4, Insertion, create, deps);
- },
- useLayoutEffect: function(create, deps) {
- currentHookNameInDev = "useLayoutEffect";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateEffectImpl(4, Layout, create, deps);
- },
- useMemo: function(create, deps) {
- currentHookNameInDev = "useMemo";
- warnInvalidHookAccess();
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
- try {
- return updateMemo(create, deps);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useReducer: function(reducer, initialArg, init) {
- currentHookNameInDev = "useReducer";
- warnInvalidHookAccess();
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
- try {
- return rerenderReducer(reducer, initialArg, init);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useRef: function() {
- currentHookNameInDev = "useRef";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- },
- useState: function() {
- currentHookNameInDev = "useState";
- warnInvalidHookAccess();
- updateHookTypesDev();
- var prevDispatcher = ReactSharedInternals.H;
- ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
- try {
- return rerenderReducer(basicStateReducer);
- } finally {
- ReactSharedInternals.H = prevDispatcher;
- }
- },
- useDebugValue: function() {
- currentHookNameInDev = "useDebugValue";
- warnInvalidHookAccess();
- updateHookTypesDev();
- },
- useDeferredValue: function(value, initialValue) {
- currentHookNameInDev = "useDeferredValue";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return rerenderDeferredValue(value, initialValue);
- },
- useTransition: function() {
- currentHookNameInDev = "useTransition";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return rerenderTransition();
- },
- useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
- currentHookNameInDev = "useSyncExternalStore";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot);
- },
- useId: function() {
- currentHookNameInDev = "useId";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- },
- useCacheRefresh: function() {
- currentHookNameInDev = "useCacheRefresh";
- updateHookTypesDev();
- return updateWorkInProgressHook().memoizedState;
- },
- useMemoCache: function(size) {
- warnInvalidHookAccess();
- return useMemoCache(size);
- }
- };
- InvalidNestedHooksDispatcherOnRerenderInDEV.useHostTransitionStatus = useHostTransitionStatus;
- InvalidNestedHooksDispatcherOnRerenderInDEV.useFormState = function(action) {
- currentHookNameInDev = "useFormState";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return rerenderActionState(action);
- };
- InvalidNestedHooksDispatcherOnRerenderInDEV.useActionState = function(action) {
- currentHookNameInDev = "useActionState";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return rerenderActionState(action);
- };
- InvalidNestedHooksDispatcherOnRerenderInDEV.useOptimistic = function(passthrough, reducer) {
- currentHookNameInDev = "useOptimistic";
- warnInvalidHookAccess();
- updateHookTypesDev();
- return rerenderOptimistic(passthrough, reducer);
- };
- var fakeInternalInstance = {};
- var didWarnAboutStateAssignmentForComponent = new Set;
- var didWarnAboutUninitializedState = new Set;
- var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set;
- var didWarnAboutLegacyLifecyclesAndDerivedState = new Set;
- var didWarnAboutDirectlyAssigningPropsToState = new Set;
- var didWarnAboutUndefinedDerivedState = new Set;
- var didWarnAboutContextTypes$1 = new Set;
- var didWarnAboutChildContextTypes = new Set;
- var didWarnAboutInvalidateContextType = new Set;
- var didWarnOnInvalidCallback = new Set;
- Object.freeze(fakeInternalInstance);
- var classComponentUpdater = {
- isMounted: function(component) {
- var owner = current;
- if (owner !== null && isRendering && owner.tag === 1) {
- var instance = owner.stateNode;
- instance._warnedAboutRefsInRender || console.error("%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.", getComponentNameFromFiber(owner) || "A component");
- instance._warnedAboutRefsInRender = true;
- }
- return (component = component._reactInternals) ? getNearestMountedFiber(component) === component : false;
- },
- enqueueSetState: function(inst, payload, callback) {
- inst = inst._reactInternals;
- var lane = requestUpdateLane(inst), update = createUpdate(lane);
- update.payload = payload;
- callback !== undefined && callback !== null && (warnOnInvalidCallback(callback), update.callback = callback);
- payload = enqueueUpdate(inst, update, lane);
- payload !== null && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
- markStateUpdateScheduled(inst, lane);
- },
- enqueueReplaceState: function(inst, payload, callback) {
- inst = inst._reactInternals;
- var lane = requestUpdateLane(inst), update = createUpdate(lane);
- update.tag = ReplaceState;
- update.payload = payload;
- callback !== undefined && callback !== null && (warnOnInvalidCallback(callback), update.callback = callback);
- payload = enqueueUpdate(inst, update, lane);
- payload !== null && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
- markStateUpdateScheduled(inst, lane);
- },
- enqueueForceUpdate: function(inst, callback) {
- inst = inst._reactInternals;
- var lane = requestUpdateLane(inst), update = createUpdate(lane);
- update.tag = ForceUpdate;
- callback !== undefined && callback !== null && (warnOnInvalidCallback(callback), update.callback = callback);
- callback = enqueueUpdate(inst, update, lane);
- callback !== null && (scheduleUpdateOnFiber(callback, inst, lane), entangleTransitions(callback, inst, lane));
- injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === "function" && injectedProfilingHooks.markForceUpdateScheduled(inst, lane);
- }
- }, reportGlobalError = typeof reportError === "function" ? reportError : function(error46) {
- if (typeof window === "object" && typeof window.ErrorEvent === "function") {
- var event = new window.ErrorEvent("error", {
- bubbles: true,
- cancelable: true,
- message: typeof error46 === "object" && error46 !== null && typeof error46.message === "string" ? String(error46.message) : String(error46),
- error: error46
- });
- if (!window.dispatchEvent(event))
- return;
- } else if (typeof process === "object" && typeof process.emit === "function") {
- process.emit("uncaughtException", error46);
- return;
- }
- console.error(error46);
- }, componentName = null, errorBoundaryName = null, SelectiveHydrationException = Error("This is not a real error. It's an implementation detail of React's selective hydration feature. If this leaks into userspace, it's a bug in React. Please file an issue."), didReceiveUpdate = false;
- var didWarnAboutBadClass = {};
- var didWarnAboutContextTypeOnFunctionComponent = {};
- var didWarnAboutContextTypes = {};
- var didWarnAboutGetDerivedStateOnFunctionComponent = {};
- var didWarnAboutReassigningProps = false;
- var didWarnAboutRevealOrder = {};
- var didWarnAboutTailOptions = {};
- var SUSPENDED_MARKER = {
- dehydrated: null,
- treeContext: null,
- retryLane: 0
- }, hasWarnedAboutUsingNoValuePropOnContextProvider = false, valueCursor = createCursor(null);
- var rendererCursorDEV = createCursor(null);
- var renderer2CursorDEV = createCursor(null);
- var rendererSigil = {};
- var currentlyRenderingFiber = null, lastContextDependency = null, isDisallowedContextReadInDEV = false, AbortControllerLocal = typeof AbortController !== "undefined" ? AbortController : function() {
- var listeners = [], signal = this.signal = {
- aborted: false,
- addEventListener: function(type, listener) {
- listeners.push(listener);
- }
- };
- this.abort = function() {
- signal.aborted = true;
- listeners.forEach(function(listener) {
- return listener();
- });
- };
- }, scheduleCallback$1 = Scheduler.unstable_scheduleCallback, NormalPriority = Scheduler.unstable_NormalPriority, CacheContext = {
- $$typeof: REACT_CONTEXT_TYPE,
- Consumer: null,
- Provider: null,
- _currentValue: null,
- _currentValue2: null,
- _threadCount: 0,
- _currentRenderer: null,
- _currentRenderer2: null
- }, prevOnStartTransitionFinish = ReactSharedInternals.S;
- ReactSharedInternals.S = function(transition, returnValue) {
- typeof returnValue === "object" && returnValue !== null && typeof returnValue.then === "function" && entangleAsyncAction(transition, returnValue);
- prevOnStartTransitionFinish !== null && prevOnStartTransitionFinish(transition, returnValue);
- };
- var resumedCache = createCursor(null), didWarnAboutUndefinedSnapshotBeforeUpdate = null;
- didWarnAboutUndefinedSnapshotBeforeUpdate = new Set;
- var offscreenSubtreeIsHidden = false, offscreenSubtreeWasHidden = false, needsFormReset = false, PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set, nextEffect = null, inProgressLanes = null, inProgressRoot = null, shouldFireAfterActiveInstanceBlur = false, hostParent = null, hostParentIsContainer = false, currentHoistableRoot = null, suspenseyCommitFlag = 8192, DefaultAsyncDispatcher = {
- getCacheForType: function(resourceType) {
- var cache5 = readContext(CacheContext), cacheForType = cache5.data.get(resourceType);
- cacheForType === undefined && (cacheForType = resourceType(), cache5.data.set(resourceType, cacheForType));
- return cacheForType;
- },
- getOwner: function() {
- return current;
- }
- }, COMPONENT_TYPE = 0, HAS_PSEUDO_CLASS_TYPE = 1, ROLE_TYPE = 2, TEST_NAME_TYPE = 3, TEXT_TYPE = 4;
- if (typeof Symbol === "function" && Symbol.for) {
- var symbolFor = Symbol.for;
- COMPONENT_TYPE = symbolFor("selector.component");
- HAS_PSEUDO_CLASS_TYPE = symbolFor("selector.has_pseudo_class");
- ROLE_TYPE = symbolFor("selector.role");
- TEST_NAME_TYPE = symbolFor("selector.test_id");
- TEXT_TYPE = symbolFor("selector.text");
- }
- var commitHooks = [], PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map, NoContext = 0, RenderContext = 2, CommitContext = 4, RootInProgress = 0, RootFatalErrored = 1, RootErrored = 2, RootSuspended = 3, RootSuspendedWithDelay = 4, RootCompleted = 5, RootDidNotComplete = 6, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, workInProgressRootRenderLanes = 0, NotSuspended = 0, SuspendedOnError = 1, SuspendedOnData = 2, SuspendedOnImmediate = 3, SuspendedOnInstance = 4, SuspendedOnInstanceAndReadyToContinue = 5, SuspendedOnDeprecatedThrowPromise = 6, SuspendedAndReadyToContinue = 7, SuspendedOnHydration = 8, workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, workInProgressRootDidSkipSuspendedSiblings = false, workInProgressRootIsPrerendering = false, workInProgressRootDidAttachPingListener = false, entangledRenderLanes = 0, workInProgressRootExitStatus = RootInProgress, workInProgressRootSkippedLanes = 0, workInProgressRootInterleavedUpdatedLanes = 0, workInProgressRootPingedLanes = 0, workInProgressDeferredLane = 0, workInProgressSuspendedRetryLanes = 0, workInProgressRootConcurrentErrors = null, workInProgressRootRecoverableErrors = null, workInProgressRootDidIncludeRecursiveRenderUpdate = false, globalMostRecentFallbackTime = 0, FALLBACK_THROTTLE_MS = 300, workInProgressRootRenderTargetTime = Infinity, RENDER_TIMEOUT_MS = 500, workInProgressTransitions = null, legacyErrorBoundariesThatAlreadyFailed = null, rootDoesHavePassiveEffects = false, rootWithPendingPassiveEffects = null, pendingPassiveEffectsLanes = 0, pendingPassiveEffectsRemainingLanes = 0, pendingPassiveTransitions = null, NESTED_UPDATE_LIMIT = 50, nestedUpdateCount = 0, rootWithNestedUpdates = null, isFlushingPassiveEffects = false, didScheduleUpdateDuringPassiveEffects = false, NESTED_PASSIVE_UPDATE_LIMIT = 50, nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null, isRunningInsertionEffect = false, IMMEDIATE_COMMIT = 0, SUSPENDED_COMMIT = 1, THROTTLED_COMMIT = 2, didWarnStateUpdateForNotYetMountedComponent = null, didWarnAboutUpdateInRender = false;
- var didWarnAboutUpdateInRenderForAnotherComponent = new Set;
- var fakeActCallbackNode = {}, resolveFamily2 = null, failedBoundaries = null;
- var hasBadMapPolyfill = false;
- try {
- var nonExtensibleObject = Object.preventExtensions({});
- new Map([[nonExtensibleObject, null]]);
- new Set([nonExtensibleObject]);
- } catch (e4) {
- hasBadMapPolyfill = true;
- }
- var didWarnAboutNestedUpdates = false;
- var didWarnAboutFindNodeInStrictMode = {};
- var overrideHookState = null, overrideHookStateDeletePath = null, overrideHookStateRenamePath = null, overrideProps = null, overridePropsDeletePath = null, overridePropsRenamePath = null, scheduleUpdate = null, setErrorHandler = null, setSuspenseHandler = null;
- overrideHookState = function(fiber, id, path15, value) {
- id = findHook(fiber, id);
- id !== null && (path15 = copyWithSetImpl(id.memoizedState, path15, 0, value), id.memoizedState = path15, id.baseState = path15, fiber.memoizedProps = assign({}, fiber.memoizedProps), path15 = enqueueConcurrentRenderForLane(fiber, 2), path15 !== null && scheduleUpdateOnFiber(path15, fiber, 2));
- };
- overrideHookStateDeletePath = function(fiber, id, path15) {
- id = findHook(fiber, id);
- id !== null && (path15 = copyWithDeleteImpl(id.memoizedState, path15, 0), id.memoizedState = path15, id.baseState = path15, fiber.memoizedProps = assign({}, fiber.memoizedProps), path15 = enqueueConcurrentRenderForLane(fiber, 2), path15 !== null && scheduleUpdateOnFiber(path15, fiber, 2));
- };
- overrideHookStateRenamePath = function(fiber, id, oldPath, newPath) {
- id = findHook(fiber, id);
- id !== null && (oldPath = copyWithRename(id.memoizedState, oldPath, newPath), id.memoizedState = oldPath, id.baseState = oldPath, fiber.memoizedProps = assign({}, fiber.memoizedProps), oldPath = enqueueConcurrentRenderForLane(fiber, 2), oldPath !== null && scheduleUpdateOnFiber(oldPath, fiber, 2));
- };
- overrideProps = function(fiber, path15, value) {
- fiber.pendingProps = copyWithSetImpl(fiber.memoizedProps, path15, 0, value);
- fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
- path15 = enqueueConcurrentRenderForLane(fiber, 2);
- path15 !== null && scheduleUpdateOnFiber(path15, fiber, 2);
- };
- overridePropsDeletePath = function(fiber, path15) {
- fiber.pendingProps = copyWithDeleteImpl(fiber.memoizedProps, path15, 0);
- fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
- path15 = enqueueConcurrentRenderForLane(fiber, 2);
- path15 !== null && scheduleUpdateOnFiber(path15, fiber, 2);
- };
- overridePropsRenamePath = function(fiber, oldPath, newPath) {
- fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath);
- fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
- oldPath = enqueueConcurrentRenderForLane(fiber, 2);
- oldPath !== null && scheduleUpdateOnFiber(oldPath, fiber, 2);
- };
- scheduleUpdate = function(fiber) {
- var root2 = enqueueConcurrentRenderForLane(fiber, 2);
- root2 !== null && scheduleUpdateOnFiber(root2, fiber, 2);
- };
- setErrorHandler = function(newShouldErrorImpl) {
- shouldErrorImpl = newShouldErrorImpl;
- };
- setSuspenseHandler = function(newShouldSuspendImpl) {
- shouldSuspendImpl = newShouldSuspendImpl;
- };
- exports2.attemptContinuousHydration = function(fiber) {
- if (fiber.tag === 13) {
- var root2 = enqueueConcurrentRenderForLane(fiber, 67108864);
- root2 !== null && scheduleUpdateOnFiber(root2, fiber, 67108864);
- markRetryLaneIfNotHydrated(fiber, 67108864);
- }
- };
- exports2.attemptHydrationAtCurrentPriority = function(fiber) {
- if (fiber.tag === 13) {
- var lane = requestUpdateLane(fiber), root2 = enqueueConcurrentRenderForLane(fiber, lane);
- root2 !== null && scheduleUpdateOnFiber(root2, fiber, lane);
- markRetryLaneIfNotHydrated(fiber, lane);
- }
- };
- exports2.attemptSynchronousHydration = function(fiber) {
- switch (fiber.tag) {
- case 3:
- fiber = fiber.stateNode;
- if (fiber.current.memoizedState.isDehydrated) {
- var lanes = getHighestPriorityLanes(fiber.pendingLanes);
- if (lanes !== 0) {
- fiber.pendingLanes |= 2;
- for (fiber.entangledLanes |= 2;lanes; ) {
- var lane = 1 << 31 - clz32(lanes);
- fiber.entanglements[1] |= lane;
- lanes &= ~lane;
- }
- ensureRootIsScheduled(fiber);
- (executionContext & (RenderContext | CommitContext)) === NoContext && (workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS, flushSyncWorkAcrossRoots_impl(0, false));
- }
- }
- break;
- case 13:
- lanes = enqueueConcurrentRenderForLane(fiber, 2), lanes !== null && scheduleUpdateOnFiber(lanes, fiber, 2), flushSyncWork(), markRetryLaneIfNotHydrated(fiber, 2);
- }
- };
- exports2.batchedUpdates = function(fn, a5) {
- return fn(a5);
- };
- exports2.createComponentSelector = function(component) {
- return { $$typeof: COMPONENT_TYPE, value: component };
- };
- exports2.createContainer = function(containerInfo, tag2, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks) {
- return createFiberRoot(containerInfo, tag2, false, null, hydrationCallbacks, isStrictMode, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks, null);
- };
- exports2.createHasPseudoClassSelector = function(selectors) {
- return { $$typeof: HAS_PSEUDO_CLASS_TYPE, value: selectors };
- };
- exports2.createHydrationContainer = function(initialChildren, callback, containerInfo, tag2, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks, formState) {
- initialChildren = createFiberRoot(containerInfo, tag2, true, initialChildren, hydrationCallbacks, isStrictMode, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks, formState);
- initialChildren.context = getContextForSubtree(null);
- containerInfo = initialChildren.current;
- tag2 = requestUpdateLane(containerInfo);
- hydrationCallbacks = createUpdate(tag2);
- hydrationCallbacks.callback = callback !== undefined && callback !== null ? callback : null;
- enqueueUpdate(containerInfo, hydrationCallbacks, tag2);
- initialChildren.current.lanes = tag2;
- markRootUpdated$1(initialChildren, tag2);
- ensureRootIsScheduled(initialChildren);
- return initialChildren;
- };
- exports2.createPortal = function(children, containerInfo, implementation) {
- var key = 3 < arguments.length && arguments[3] !== undefined ? arguments[3] : null;
- try {
- testStringCoercion(key);
- var JSCompiler_inline_result = false;
- } catch (e$6) {
- JSCompiler_inline_result = true;
- }
- JSCompiler_inline_result && (console.error("The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", typeof Symbol === "function" && Symbol.toStringTag && key[Symbol.toStringTag] || key.constructor.name || "Object"), testStringCoercion(key));
- return {
- $$typeof: REACT_PORTAL_TYPE,
- key: key == null ? null : "" + key,
- children,
- containerInfo,
- implementation
- };
- };
- exports2.createRoleSelector = function(role) {
- return { $$typeof: ROLE_TYPE, value: role };
- };
- exports2.createTestNameSelector = function(id) {
- return { $$typeof: TEST_NAME_TYPE, value: id };
- };
- exports2.createTextSelector = function(text) {
- return { $$typeof: TEXT_TYPE, value: text };
- };
- exports2.defaultOnCaughtError = function(error46, errorInfo) {
- var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component." : "The above error occurred in one of your React components.", recreateMessage = "React will try to recreate this component tree from scratch using the error boundary you provided, " + ((errorBoundaryName || "Anonymous") + "."), prevGetCurrentStack = ReactSharedInternals.getCurrentStack, componentStack = errorInfo.componentStack != null ? errorInfo.componentStack : "";
- ReactSharedInternals.getCurrentStack = function() {
- return componentStack;
- };
- try {
- typeof error46 === "object" && error46 !== null && typeof error46.environmentName === "string" ? bindToConsole("error", [
- `%o
-
-%s
-
-%s
-`,
- error46,
- componentNameMessage,
- recreateMessage
- ], error46.environmentName)() : console.error(`%o
-
-%s
-
-%s
-`, error46, componentNameMessage, recreateMessage);
- } finally {
- ReactSharedInternals.getCurrentStack = prevGetCurrentStack;
- }
- };
- exports2.defaultOnRecoverableError = function(error46) {
- reportGlobalError(error46);
- };
- exports2.defaultOnUncaughtError = function(error46, errorInfo) {
- reportGlobalError(error46);
- error46 = componentName ? "An error occurred in the <" + componentName + "> component." : "An error occurred in one of your React components.";
- var prevGetCurrentStack = ReactSharedInternals.getCurrentStack, componentStack = errorInfo.componentStack != null ? errorInfo.componentStack : "";
- ReactSharedInternals.getCurrentStack = function() {
- return componentStack;
- };
- try {
- console.warn(`%s
-
-%s
-`, error46, `Consider adding an error boundary to your tree to customize error handling behavior.
-Visit https://react.dev/link/error-boundaries to learn more about error boundaries.`);
- } finally {
- ReactSharedInternals.getCurrentStack = prevGetCurrentStack;
- }
- };
- exports2.deferredUpdates = function(fn) {
- var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
- try {
- return setCurrentUpdatePriority(32), ReactSharedInternals.T = null, fn();
- } finally {
- setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition;
- }
- };
- exports2.discreteUpdates = function(fn, a5, b4, c8, d4) {
- var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
- try {
- return setCurrentUpdatePriority(2), ReactSharedInternals.T = null, fn(a5, b4, c8, d4);
- } finally {
- setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition, executionContext === NoContext && (workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS);
- }
- };
- exports2.findAllNodes = findAllNodes;
- exports2.findBoundingRects = function(hostRoot, selectors) {
- if (!supportsTestSelectors)
- throw Error("Test selector API is not supported by this renderer.");
- selectors = findAllNodes(hostRoot, selectors);
- hostRoot = [];
- for (var i5 = 0;i5 < selectors.length; i5++)
- hostRoot.push(getBoundingRect(selectors[i5]));
- for (selectors = hostRoot.length - 1;0 < selectors; selectors--) {
- i5 = hostRoot[selectors];
- for (var targetLeft = i5.x, targetRight = targetLeft + i5.width, targetTop = i5.y, targetBottom = targetTop + i5.height, j4 = selectors - 1;0 <= j4; j4--)
- if (selectors !== j4) {
- var otherRect = hostRoot[j4], otherLeft = otherRect.x, otherRight = otherLeft + otherRect.width, otherTop = otherRect.y, otherBottom = otherTop + otherRect.height;
- if (targetLeft >= otherLeft && targetTop >= otherTop && targetRight <= otherRight && targetBottom <= otherBottom) {
- hostRoot.splice(selectors, 1);
- break;
- } else if (!(targetLeft !== otherLeft || i5.width !== otherRect.width || otherBottom < targetTop || otherTop > targetBottom)) {
- otherTop > targetTop && (otherRect.height += otherTop - targetTop, otherRect.y = targetTop);
- otherBottom < targetBottom && (otherRect.height = targetBottom - otherTop);
- hostRoot.splice(selectors, 1);
- break;
- } else if (!(targetTop !== otherTop || i5.height !== otherRect.height || otherRight < targetLeft || otherLeft > targetRight)) {
- otherLeft > targetLeft && (otherRect.width += otherLeft - targetLeft, otherRect.x = targetLeft);
- otherRight < targetRight && (otherRect.width = targetRight - otherLeft);
- hostRoot.splice(selectors, 1);
- break;
- }
- }
- }
- return hostRoot;
- };
- exports2.findHostInstance = function(component) {
- var fiber = component._reactInternals;
- if (fiber === undefined) {
- if (typeof component.render === "function")
- throw Error("Unable to find node on an unmounted component.");
- component = Object.keys(component).join(",");
- throw Error("Argument appears to not be a ReactComponent. Keys: " + component);
- }
- component = findCurrentHostFiber(fiber);
- return component === null ? null : getPublicInstance(component.stateNode);
- };
- exports2.findHostInstanceWithNoPortals = function(fiber) {
- fiber = findCurrentFiberUsingSlowPath(fiber);
- fiber = fiber !== null ? findCurrentHostFiberWithNoPortalsImpl(fiber) : null;
- return fiber === null ? null : getPublicInstance(fiber.stateNode);
- };
- exports2.findHostInstanceWithWarning = function(component, methodName) {
- var fiber = component._reactInternals;
- if (fiber === undefined) {
- if (typeof component.render === "function")
- throw Error("Unable to find node on an unmounted component.");
- component = Object.keys(component).join(",");
- throw Error("Argument appears to not be a ReactComponent. Keys: " + component);
- }
- component = findCurrentHostFiber(fiber);
- if (component === null)
- return null;
- if (component.mode & 8) {
- var componentName2 = getComponentNameFromFiber(fiber) || "Component";
- didWarnAboutFindNodeInStrictMode[componentName2] || (didWarnAboutFindNodeInStrictMode[componentName2] = true, runWithFiberInDEV(component, function() {
- fiber.mode & 8 ? console.error("%s is deprecated in StrictMode. %s was passed an instance of %s which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://react.dev/link/strict-mode-find-node", methodName, methodName, componentName2) : console.error("%s is deprecated in StrictMode. %s was passed an instance of %s which renders StrictMode children. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://react.dev/link/strict-mode-find-node", methodName, methodName, componentName2);
- }));
- }
- return getPublicInstance(component.stateNode);
- };
- exports2.flushPassiveEffects = flushPassiveEffects;
- exports2.flushSyncFromReconciler = function(fn) {
- var prevExecutionContext = executionContext;
- executionContext |= 1;
- var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
- try {
- if (setCurrentUpdatePriority(2), ReactSharedInternals.T = null, fn)
- return fn();
- } finally {
- setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition, executionContext = prevExecutionContext, (executionContext & (RenderContext | CommitContext)) === NoContext && flushSyncWorkAcrossRoots_impl(0, false);
- }
- };
- exports2.flushSyncWork = flushSyncWork;
- exports2.focusWithin = function(hostRoot, selectors) {
- if (!supportsTestSelectors)
- throw Error("Test selector API is not supported by this renderer.");
- hostRoot = findFiberRootForHostRoot(hostRoot);
- selectors = findPaths(hostRoot, selectors);
- selectors = Array.from(selectors);
- for (hostRoot = 0;hostRoot < selectors.length; ) {
- var fiber = selectors[hostRoot++], tag2 = fiber.tag;
- if (!isHiddenSubtree(fiber)) {
- if ((tag2 === 5 || tag2 === 26 || tag2 === 27) && setFocusIfFocusable(fiber.stateNode))
- return true;
- for (fiber = fiber.child;fiber !== null; )
- selectors.push(fiber), fiber = fiber.sibling;
- }
- }
- return false;
- };
- exports2.getFindAllNodesFailureDescription = function(hostRoot, selectors) {
- if (!supportsTestSelectors)
- throw Error("Test selector API is not supported by this renderer.");
- var maxSelectorIndex = 0, matchedNames = [];
- hostRoot = [findFiberRootForHostRoot(hostRoot), 0];
- for (var index2 = 0;index2 < hostRoot.length; ) {
- var fiber = hostRoot[index2++], tag2 = fiber.tag, selectorIndex = hostRoot[index2++], selector = selectors[selectorIndex];
- if (tag2 !== 5 && tag2 !== 26 && tag2 !== 27 || !isHiddenSubtree(fiber)) {
- if (matchSelector(fiber, selector) && (matchedNames.push(selectorToString(selector)), selectorIndex++, selectorIndex > maxSelectorIndex && (maxSelectorIndex = selectorIndex)), selectorIndex < selectors.length)
- for (fiber = fiber.child;fiber !== null; )
- hostRoot.push(fiber, selectorIndex), fiber = fiber.sibling;
- }
- }
- if (maxSelectorIndex < selectors.length) {
- for (hostRoot = [];maxSelectorIndex < selectors.length; maxSelectorIndex++)
- hostRoot.push(selectorToString(selectors[maxSelectorIndex]));
- return `findAllNodes was able to match part of the selector:
- ` + (matchedNames.join(" > ") + `
-
-No matching component was found for:
- `) + hostRoot.join(" > ");
- }
- return null;
- };
- exports2.getPublicRootInstance = function(container) {
- container = container.current;
- if (!container.child)
- return null;
- switch (container.child.tag) {
- case 27:
- case 5:
- return getPublicInstance(container.child.stateNode);
- default:
- return container.child.stateNode;
- }
- };
- exports2.injectIntoDevTools = function() {
- var internals = {
- bundleType: 1,
- version: rendererVersion,
- rendererPackageName,
- currentDispatcherRef: ReactSharedInternals,
- findFiberByHostInstance: getInstanceFromNode,
- reconcilerVersion: "19.0.0"
- };
- extraDevToolsConfig !== null && (internals.rendererConfig = extraDevToolsConfig);
- internals.overrideHookState = overrideHookState;
- internals.overrideHookStateDeletePath = overrideHookStateDeletePath;
- internals.overrideHookStateRenamePath = overrideHookStateRenamePath;
- internals.overrideProps = overrideProps;
- internals.overridePropsDeletePath = overridePropsDeletePath;
- internals.overridePropsRenamePath = overridePropsRenamePath;
- internals.scheduleUpdate = scheduleUpdate;
- internals.setErrorHandler = setErrorHandler;
- internals.setSuspenseHandler = setSuspenseHandler;
- internals.scheduleRefresh = scheduleRefresh;
- internals.scheduleRoot = scheduleRoot;
- internals.setRefreshHandler = setRefreshHandler;
- internals.getCurrentFiber = getCurrentFiberForDevTools;
- internals.getLaneLabelMap = getLaneLabelMap;
- internals.injectProfilingHooks = injectProfilingHooks;
- return injectInternals(internals);
- };
- exports2.isAlreadyRendering = function() {
- return (executionContext & (RenderContext | CommitContext)) !== NoContext;
- };
- exports2.observeVisibleRects = function(hostRoot, selectors, callback, options2) {
- function commitHook() {
- var nextInstanceRoots = findAllNodes(hostRoot, selectors);
- instanceRoots.forEach(function(target) {
- 0 > nextInstanceRoots.indexOf(target) && unobserve(target);
- });
- nextInstanceRoots.forEach(function(target) {
- 0 > instanceRoots.indexOf(target) && observe(target);
- });
- }
- if (!supportsTestSelectors)
- throw Error("Test selector API is not supported by this renderer.");
- var instanceRoots = findAllNodes(hostRoot, selectors);
- callback = setupIntersectionObserver(instanceRoots, callback, options2);
- var { disconnect: disconnect2, observe, unobserve } = callback;
- commitHooks.push(commitHook);
- return {
- disconnect: function() {
- var index2 = commitHooks.indexOf(commitHook);
- 0 <= index2 && commitHooks.splice(index2, 1);
- disconnect2();
- }
- };
- };
- exports2.shouldError = function(fiber) {
- return shouldErrorImpl(fiber);
- };
- exports2.shouldSuspend = function(fiber) {
- return shouldSuspendImpl(fiber);
- };
- exports2.startHostTransition = function(formFiber, pendingState, action, formData) {
- if (formFiber.tag !== 5)
- throw Error("Expected the form instance to be a HostComponent. This is a bug in React.");
- var queue = ensureFormComponentIsStateful(formFiber).queue;
- startTransition(formFiber, queue, pendingState, NotPendingTransition, action === null ? noop10 : function() {
- ReactSharedInternals.T === null && console.error("requestFormReset was called outside a transition or action. To fix, move to an action, or wrap with startTransition.");
- var resetStateQueue = ensureFormComponentIsStateful(formFiber).next.queue;
- dispatchSetStateInternal(formFiber, resetStateQueue, {}, requestUpdateLane(formFiber));
- return action(formData);
- });
- };
- exports2.updateContainer = function(element, container, parentComponent, callback) {
- var current2 = container.current, lane = requestUpdateLane(current2);
- updateContainerImpl(current2, lane, element, container, parentComponent, callback);
- return lane;
- };
- exports2.updateContainerSync = updateContainerSync;
- return exports2;
- }, module.exports.default = module.exports, Object.defineProperty(module.exports, "__esModule", { value: true });
-});
-
-// node_modules/react-reconciler/index.js
-var require_react_reconciler = __commonJS((exports, module) => {
- if (false) {} else {
- module.exports = require_react_reconciler_development();
- }
-});
-
-// src/ink/layout/node.ts
-var LayoutEdge, LayoutGutter, LayoutDisplay, LayoutFlexDirection, LayoutAlign, LayoutJustify, LayoutWrap, LayoutPositionType, LayoutOverflow, LayoutMeasureMode;
-var init_node5 = __esm(() => {
- LayoutEdge = {
- All: "all",
- Horizontal: "horizontal",
- Vertical: "vertical",
- Left: "left",
- Right: "right",
- Top: "top",
- Bottom: "bottom",
- Start: "start",
- End: "end"
- };
- LayoutGutter = {
- All: "all",
- Column: "column",
- Row: "row"
- };
- LayoutDisplay = {
- Flex: "flex",
- None: "none"
- };
- LayoutFlexDirection = {
- Row: "row",
- RowReverse: "row-reverse",
- Column: "column",
- ColumnReverse: "column-reverse"
- };
- LayoutAlign = {
- Auto: "auto",
- Stretch: "stretch",
- FlexStart: "flex-start",
- Center: "center",
- FlexEnd: "flex-end"
- };
- LayoutJustify = {
- FlexStart: "flex-start",
- Center: "center",
- FlexEnd: "flex-end",
- SpaceBetween: "space-between",
- SpaceAround: "space-around",
- SpaceEvenly: "space-evenly"
- };
- LayoutWrap = {
- NoWrap: "nowrap",
- Wrap: "wrap",
- WrapReverse: "wrap-reverse"
- };
- LayoutPositionType = {
- Relative: "relative",
- Absolute: "absolute"
- };
- LayoutOverflow = {
- Visible: "visible",
- Hidden: "hidden",
- Scroll: "scroll"
- };
- LayoutMeasureMode = {
- Undefined: "undefined",
- Exactly: "exactly",
- AtMost: "at-most"
- };
-});
-
-// src/ink/layout/yoga.ts
-class YogaLayoutNode {
- yoga;
- constructor(yoga) {
- this.yoga = yoga;
- }
- insertChild(child, index2) {
- this.yoga.insertChild(child.yoga, index2);
- }
- removeChild(child) {
- this.yoga.removeChild(child.yoga);
- }
- getChildCount() {
- return this.yoga.getChildCount();
- }
- getParent() {
- const p4 = this.yoga.getParent();
- return p4 ? new YogaLayoutNode(p4) : null;
- }
- calculateLayout(width, _height) {
- this.yoga.calculateLayout(width, undefined, Direction.LTR);
- }
- setMeasureFunc(fn) {
- this.yoga.setMeasureFunc((w2, wMode) => {
- const mode = wMode === MeasureMode.Exactly ? LayoutMeasureMode.Exactly : wMode === MeasureMode.AtMost ? LayoutMeasureMode.AtMost : LayoutMeasureMode.Undefined;
- return fn(w2, mode);
- });
- }
- unsetMeasureFunc() {
- this.yoga.unsetMeasureFunc();
- }
- markDirty() {
- this.yoga.markDirty();
- }
- getComputedLeft() {
- return this.yoga.getComputedLeft();
- }
- getComputedTop() {
- return this.yoga.getComputedTop();
- }
- getComputedWidth() {
- return this.yoga.getComputedWidth();
- }
- getComputedHeight() {
- return this.yoga.getComputedHeight();
- }
- getComputedBorder(edge) {
- return this.yoga.getComputedBorder(EDGE_MAP[edge]);
- }
- getComputedPadding(edge) {
- return this.yoga.getComputedPadding(EDGE_MAP[edge]);
- }
- setWidth(value) {
- this.yoga.setWidth(value);
- }
- setWidthPercent(value) {
- this.yoga.setWidthPercent(value);
- }
- setWidthAuto() {
- this.yoga.setWidthAuto();
- }
- setHeight(value) {
- this.yoga.setHeight(value);
- }
- setHeightPercent(value) {
- this.yoga.setHeightPercent(value);
- }
- setHeightAuto() {
- this.yoga.setHeightAuto();
- }
- setMinWidth(value) {
- this.yoga.setMinWidth(value);
- }
- setMinWidthPercent(value) {
- this.yoga.setMinWidthPercent(value);
- }
- setMinHeight(value) {
- this.yoga.setMinHeight(value);
- }
- setMinHeightPercent(value) {
- this.yoga.setMinHeightPercent(value);
- }
- setMaxWidth(value) {
- this.yoga.setMaxWidth(value);
- }
- setMaxWidthPercent(value) {
- this.yoga.setMaxWidthPercent(value);
- }
- setMaxHeight(value) {
- this.yoga.setMaxHeight(value);
- }
- setMaxHeightPercent(value) {
- this.yoga.setMaxHeightPercent(value);
- }
- setFlexDirection(dir) {
- const map7 = {
- row: FlexDirection.Row,
- "row-reverse": FlexDirection.RowReverse,
- column: FlexDirection.Column,
- "column-reverse": FlexDirection.ColumnReverse
- };
- this.yoga.setFlexDirection(map7[dir]);
- }
- setFlexGrow(value) {
- this.yoga.setFlexGrow(value);
- }
- setFlexShrink(value) {
- this.yoga.setFlexShrink(value);
- }
- setFlexBasis(value) {
- this.yoga.setFlexBasis(value);
- }
- setFlexBasisPercent(value) {
- this.yoga.setFlexBasisPercent(value);
- }
- setFlexWrap(wrap) {
- const map7 = {
- nowrap: Wrap.NoWrap,
- wrap: Wrap.Wrap,
- "wrap-reverse": Wrap.WrapReverse
- };
- this.yoga.setFlexWrap(map7[wrap]);
- }
- setAlignItems(align) {
- const map7 = {
- auto: Align.Auto,
- stretch: Align.Stretch,
- "flex-start": Align.FlexStart,
- center: Align.Center,
- "flex-end": Align.FlexEnd
- };
- this.yoga.setAlignItems(map7[align]);
- }
- setAlignSelf(align) {
- const map7 = {
- auto: Align.Auto,
- stretch: Align.Stretch,
- "flex-start": Align.FlexStart,
- center: Align.Center,
- "flex-end": Align.FlexEnd
- };
- this.yoga.setAlignSelf(map7[align]);
- }
- setJustifyContent(justify) {
- const map7 = {
- "flex-start": Justify.FlexStart,
- center: Justify.Center,
- "flex-end": Justify.FlexEnd,
- "space-between": Justify.SpaceBetween,
- "space-around": Justify.SpaceAround,
- "space-evenly": Justify.SpaceEvenly
- };
- this.yoga.setJustifyContent(map7[justify]);
- }
- setDisplay(display) {
- this.yoga.setDisplay(display === "flex" ? Display.Flex : Display.None);
- }
- getDisplay() {
- return this.yoga.getDisplay() === Display.None ? LayoutDisplay.None : LayoutDisplay.Flex;
- }
- setPositionType(type) {
- this.yoga.setPositionType(type === "absolute" ? PositionType.Absolute : PositionType.Relative);
- }
- setPosition(edge, value) {
- this.yoga.setPosition(EDGE_MAP[edge], value);
- }
- setPositionPercent(edge, value) {
- this.yoga.setPositionPercent(EDGE_MAP[edge], value);
- }
- setOverflow(overflow) {
- const map7 = {
- visible: Overflow.Visible,
- hidden: Overflow.Hidden,
- scroll: Overflow.Scroll
- };
- this.yoga.setOverflow(map7[overflow]);
- }
- setMargin(edge, value) {
- this.yoga.setMargin(EDGE_MAP[edge], value);
- }
- setPadding(edge, value) {
- this.yoga.setPadding(EDGE_MAP[edge], value);
- }
- setBorder(edge, value) {
- this.yoga.setBorder(EDGE_MAP[edge], value);
- }
- setGap(gutter, value) {
- this.yoga.setGap(GUTTER_MAP[gutter], value);
- }
- free() {
- this.yoga.free();
- }
- freeRecursive() {
- this.yoga.freeRecursive();
- }
-}
-function createYogaLayoutNode() {
- return new YogaLayoutNode(yoga_layout_default.Node.create());
-}
-var EDGE_MAP, GUTTER_MAP;
-var init_yoga = __esm(() => {
- init_yoga_layout();
- init_node5();
- EDGE_MAP = {
- all: Edge.All,
- horizontal: Edge.Horizontal,
- vertical: Edge.Vertical,
- left: Edge.Left,
- right: Edge.Right,
- top: Edge.Top,
- bottom: Edge.Bottom,
- start: Edge.Start,
- end: Edge.End
- };
- GUTTER_MAP = {
- all: Gutter.All,
- column: Gutter.Column,
- row: Gutter.Row
- };
-});
-
-// src/ink/layout/engine.ts
-function createLayoutNode() {
- return createYogaLayoutNode();
-}
-var init_engine = __esm(() => {
- init_yoga();
-});
-
-// src/ink/line-width-cache.ts
-function lineWidth(line) {
- const cached2 = cache5.get(line);
- if (cached2 !== undefined)
- return cached2;
- const width = stringWidth(line);
- if (cache5.size >= MAX_CACHE_SIZE2) {
- cache5.clear();
- }
- cache5.set(line, width);
- return width;
-}
-var cache5, MAX_CACHE_SIZE2 = 4096;
-var init_line_width_cache = __esm(() => {
- init_stringWidth();
- cache5 = new Map;
-});
-
-// src/ink/measure-text.ts
-function measureText(text, maxWidth) {
- if (text.length === 0) {
- return {
- width: 0,
- height: 0
- };
- }
- const noWrap = maxWidth <= 0 || !Number.isFinite(maxWidth);
- let height = 0;
- let width = 0;
- let start = 0;
- while (start <= text.length) {
- const end = text.indexOf(`
-`, start);
- const line = end === -1 ? text.substring(start) : text.substring(start, end);
- const w2 = lineWidth(line);
- width = Math.max(width, w2);
- if (noWrap) {
- height++;
- } else {
- height += w2 === 0 ? 1 : Math.ceil(w2 / maxWidth);
- }
- if (end === -1)
- break;
- start = end + 1;
- }
- return { width, height };
-}
-var measure_text_default;
-var init_measure_text = __esm(() => {
- init_line_width_cache();
- measure_text_default = measureText;
-});
-
-// src/ink/node-cache.ts
-function addPendingClear(parent, rect, isAbsolute5) {
- const existing = pendingClears.get(parent);
- if (existing) {
- existing.push(rect);
- } else {
- pendingClears.set(parent, [rect]);
- }
- if (isAbsolute5) {
- absoluteNodeRemoved = true;
- }
-}
-function consumeAbsoluteRemovedFlag() {
- const had = absoluteNodeRemoved;
- absoluteNodeRemoved = false;
- return had;
-}
-var nodeCache, pendingClears, absoluteNodeRemoved = false;
-var init_node_cache = __esm(() => {
- nodeCache = new WeakMap;
- pendingClears = new WeakMap;
-});
-
-// src/ink/squash-text-nodes.ts
-function squashTextNodesToSegments(node, inheritedStyles = {}, inheritedHyperlink, out = []) {
- const mergedStyles = node.textStyles ? { ...inheritedStyles, ...node.textStyles } : inheritedStyles;
- for (const childNode of node.childNodes) {
- if (childNode === undefined) {
- continue;
- }
- if (childNode.nodeName === "#text") {
- if (childNode.nodeValue.length > 0) {
- out.push({
- text: childNode.nodeValue,
- styles: mergedStyles,
- hyperlink: inheritedHyperlink
- });
- }
- } else if (childNode.nodeName === "ink-text" || childNode.nodeName === "ink-virtual-text") {
- squashTextNodesToSegments(childNode, mergedStyles, inheritedHyperlink, out);
- } else if (childNode.nodeName === "ink-link") {
- const href = childNode.attributes["href"];
- squashTextNodesToSegments(childNode, mergedStyles, href || inheritedHyperlink, out);
- }
- }
- return out;
-}
-function squashTextNodes(node) {
- let text = "";
- for (const childNode of node.childNodes) {
- if (childNode === undefined) {
- continue;
- }
- if (childNode.nodeName === "#text") {
- text += childNode.nodeValue;
- } else if (childNode.nodeName === "ink-text" || childNode.nodeName === "ink-virtual-text") {
- text += squashTextNodes(childNode);
- } else if (childNode.nodeName === "ink-link") {
- text += squashTextNodes(childNode);
- }
- }
- return text;
-}
-var squash_text_nodes_default;
-var init_squash_text_nodes = __esm(() => {
- squash_text_nodes_default = squashTextNodes;
-});
-
-// src/ink/tabstops.ts
-function expandTabs(text, interval = DEFAULT_TAB_INTERVAL) {
- if (!text.includes("\t")) {
- return text;
- }
- const tokenizer = createTokenizer();
- const tokens = tokenizer.feed(text);
- tokens.push(...tokenizer.flush());
- let result = "";
- let column = 0;
- for (const token of tokens) {
- if (token.type === "sequence") {
- result += token.value;
- } else {
- const parts = token.value.split(/(\t|\n)/);
- for (const part of parts) {
- if (part === "\t") {
- const spaces = interval - column % interval;
- result += " ".repeat(spaces);
- column += spaces;
- } else if (part === `
-`) {
- result += part;
- column = 0;
- } else {
- result += part;
- column += stringWidth(part);
- }
- }
- }
- }
- return result;
-}
-var DEFAULT_TAB_INTERVAL = 8;
-var init_tabstops = __esm(() => {
- init_stringWidth();
- init_tokenize();
-});
-
-// node_modules/ansi-styles/index.js
-function assembleStyles2() {
- const codes = new Map;
- for (const [groupName, group] of Object.entries(styles3)) {
- for (const [styleName, style] of Object.entries(group)) {
- styles3[styleName] = {
- open: `\x1B[${style[0]}m`,
- close: `\x1B[${style[1]}m`
- };
- group[styleName] = styles3[styleName];
- codes.set(style[0], style[1]);
- }
- Object.defineProperty(styles3, groupName, {
- value: group,
- enumerable: false
- });
- }
- Object.defineProperty(styles3, "codes", {
- value: codes,
- enumerable: false
- });
- styles3.color.close = "\x1B[39m";
- styles3.bgColor.close = "\x1B[49m";
- styles3.color.ansi = wrapAnsi162();
- styles3.color.ansi256 = wrapAnsi2562();
- styles3.color.ansi16m = wrapAnsi16m2();
- styles3.bgColor.ansi = wrapAnsi162(ANSI_BACKGROUND_OFFSET2);
- styles3.bgColor.ansi256 = wrapAnsi2562(ANSI_BACKGROUND_OFFSET2);
- styles3.bgColor.ansi16m = wrapAnsi16m2(ANSI_BACKGROUND_OFFSET2);
- Object.defineProperties(styles3, {
- rgbToAnsi256: {
- value(red2, green2, blue2) {
- if (red2 === green2 && green2 === blue2) {
- if (red2 < 8) {
- return 16;
- }
- if (red2 > 248) {
- return 231;
- }
- return Math.round((red2 - 8) / 247 * 24) + 232;
- }
- return 16 + 36 * Math.round(red2 / 255 * 5) + 6 * Math.round(green2 / 255 * 5) + Math.round(blue2 / 255 * 5);
- },
- enumerable: false
- },
- hexToRgb: {
- value(hex) {
- const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
- if (!matches) {
- return [0, 0, 0];
- }
- let [colorString] = matches;
- if (colorString.length === 3) {
- colorString = [...colorString].map((character) => character + character).join("");
- }
- const integer2 = Number.parseInt(colorString, 16);
- return [
- integer2 >> 16 & 255,
- integer2 >> 8 & 255,
- integer2 & 255
- ];
- },
- enumerable: false
- },
- hexToAnsi256: {
- value: (hex) => styles3.rgbToAnsi256(...styles3.hexToRgb(hex)),
- enumerable: false
- },
- ansi256ToAnsi: {
- value(code) {
- if (code < 8) {
- return 30 + code;
- }
- if (code < 16) {
- return 90 + (code - 8);
- }
- let red2;
- let green2;
- let blue2;
- if (code >= 232) {
- red2 = ((code - 232) * 10 + 8) / 255;
- green2 = red2;
- blue2 = red2;
- } else {
- code -= 16;
- const remainder = code % 36;
- red2 = Math.floor(code / 36) / 5;
- green2 = Math.floor(remainder / 6) / 5;
- blue2 = remainder % 6 / 5;
- }
- const value = Math.max(red2, green2, blue2) * 2;
- if (value === 0) {
- return 30;
- }
- let result = 30 + (Math.round(blue2) << 2 | Math.round(green2) << 1 | Math.round(red2));
- if (value === 2) {
- result += 60;
- }
- return result;
- },
- enumerable: false
- },
- rgbToAnsi: {
- value: (red2, green2, blue2) => styles3.ansi256ToAnsi(styles3.rgbToAnsi256(red2, green2, blue2)),
- enumerable: false
- },
- hexToAnsi: {
- value: (hex) => styles3.ansi256ToAnsi(styles3.hexToAnsi256(hex)),
- enumerable: false
- }
- });
- return styles3;
-}
-var ANSI_BACKGROUND_OFFSET2 = 10, wrapAnsi162 = (offset = 0) => (code) => `\x1B[${code + offset}m`, wrapAnsi2562 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, wrapAnsi16m2 = (offset = 0) => (red2, green2, blue2) => `\x1B[${38 + offset};2;${red2};${green2};${blue2}m`, styles3, modifierNames2, foregroundColorNames2, backgroundColorNames2, colorNames2, ansiStyles2, ansi_styles_default2;
-var init_ansi_styles2 = __esm(() => {
- styles3 = {
- modifier: {
- reset: [0, 0],
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- overline: [53, 55],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29]
- },
- color: {
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
- blackBright: [90, 39],
- gray: [90, 39],
- grey: [90, 39],
- redBright: [91, 39],
- greenBright: [92, 39],
- yellowBright: [93, 39],
- blueBright: [94, 39],
- magentaBright: [95, 39],
- cyanBright: [96, 39],
- whiteBright: [97, 39]
- },
- bgColor: {
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
- bgBlackBright: [100, 49],
- bgGray: [100, 49],
- bgGrey: [100, 49],
- bgRedBright: [101, 49],
- bgGreenBright: [102, 49],
- bgYellowBright: [103, 49],
- bgBlueBright: [104, 49],
- bgMagentaBright: [105, 49],
- bgCyanBright: [106, 49],
- bgWhiteBright: [107, 49]
- }
- };
- modifierNames2 = Object.keys(styles3.modifier);
- foregroundColorNames2 = Object.keys(styles3.color);
- backgroundColorNames2 = Object.keys(styles3.bgColor);
- colorNames2 = [...foregroundColorNames2, ...backgroundColorNames2];
- ansiStyles2 = assembleStyles2();
- ansi_styles_default2 = ansiStyles2;
-});
-
-// node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js
-function getEndCode(code) {
- if (endCodesSet.has(code))
- return code;
- if (endCodesMap.has(code))
- return endCodesMap.get(code);
- if (code.startsWith(linkStartCodePrefix))
- return linkEndCode;
- code = code.slice(2);
- if (code.includes(";")) {
- code = code[0] + "0";
- }
- const ret = ansi_styles_default2.codes.get(parseInt(code, 10));
- if (ret) {
- return ansi_styles_default2.color.ansi(ret);
- } else {
- return ansi_styles_default2.reset.open;
- }
-}
-function ansiCodesToString(codes) {
- return codes.map((code) => code.code).join("");
-}
-var ESCAPES, endCodesSet, endCodesMap, linkStartCodePrefix = "\x1B]8;;", linkStartCodePrefixCharCodes, linkCodeSuffix = "\x07", linkCodeSuffixCharCode, linkEndCode;
-var init_ansiCodes = __esm(() => {
- init_ansi_styles2();
- ESCAPES = new Set([27, 155]);
- endCodesSet = new Set;
- endCodesMap = new Map;
- for (const [start, end] of ansi_styles_default2.codes) {
- endCodesSet.add(ansi_styles_default2.color.ansi(end));
- endCodesMap.set(ansi_styles_default2.color.ansi(start), ansi_styles_default2.color.ansi(end));
- }
- linkStartCodePrefixCharCodes = linkStartCodePrefix.split("").map((char) => char.charCodeAt(0));
- linkCodeSuffixCharCode = linkCodeSuffix.charCodeAt(0);
- linkEndCode = `\x1B]8;;${linkCodeSuffix}`;
-});
-
-// node_modules/@alcalzone/ansi-tokenize/build/reduce.js
-function reduceAnsiCodes(codes) {
- return reduceAnsiCodesIncremental([], codes);
-}
-function reduceAnsiCodesIncremental(codes, newCodes) {
- let ret = [...codes];
- for (const code of newCodes) {
- if (code.code === ansi_styles_default2.reset.open) {
- ret = [];
- } else if (endCodesSet.has(code.code)) {
- ret = ret.filter((retCode) => retCode.endCode !== code.code);
- } else {
- ret = ret.filter((retCode) => retCode.endCode !== code.endCode);
- ret.push(code);
- }
- }
- return ret;
-}
-var init_reduce = __esm(() => {
- init_ansi_styles2();
- init_ansiCodes();
-});
-
-// node_modules/@alcalzone/ansi-tokenize/build/undo.js
-function undoAnsiCodes(codes) {
- return reduceAnsiCodes(codes).reverse().map((code) => ({
- ...code,
- code: code.endCode
- }));
-}
-var init_undo = __esm(() => {
- init_reduce();
-});
-
-// node_modules/@alcalzone/ansi-tokenize/build/diff.js
-function diffAnsiCodes(from, to) {
- const endCodesInTo = new Set(to.map((code) => code.endCode));
- const startCodesInFrom = new Set(from.map((code) => code.code));
- return [
- ...undoAnsiCodes(from.filter((code) => !endCodesInTo.has(code.endCode))),
- ...to.filter((code) => !startCodesInFrom.has(code.code))
- ];
-}
-var init_diff = __esm(() => {
- init_undo();
-});
-
-// node_modules/@alcalzone/ansi-tokenize/build/styledChars.js
-function styledCharsFromTokens(tokens) {
- let codes = [];
- const ret = [];
- for (const token of tokens) {
- if (token.type === "ansi") {
- codes = reduceAnsiCodesIncremental(codes, [token]);
- } else if (token.type === "char") {
- ret.push({
- ...token,
- styles: [...codes]
- });
- }
- }
- return ret;
-}
-var init_styledChars = __esm(() => {
- init_ansiCodes();
- init_diff();
- init_reduce();
-});
-
-// node_modules/is-fullwidth-code-point/index.js
-function isFullwidthCodePoint(codePoint) {
- if (!Number.isInteger(codePoint)) {
- return false;
- }
- return codePoint >= 4352 && (codePoint <= 4447 || codePoint === 9001 || codePoint === 9002 || 11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || 12880 <= codePoint && codePoint <= 19903 || 19968 <= codePoint && codePoint <= 42182 || 43360 <= codePoint && codePoint <= 43388 || 44032 <= codePoint && codePoint <= 55203 || 63744 <= codePoint && codePoint <= 64255 || 65040 <= codePoint && codePoint <= 65049 || 65072 <= codePoint && codePoint <= 65131 || 65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || 110592 <= codePoint && codePoint <= 110593 || 127488 <= codePoint && codePoint <= 127569 || 131072 <= codePoint && codePoint <= 262141);
-}
-
-// node_modules/@alcalzone/ansi-tokenize/build/tokenize.js
-function findNumberIndex(str) {
- for (let index2 = 0;index2 < str.length; index2++) {
- const charCode = str.charCodeAt(index2);
- if (charCode >= 48 && charCode <= 57) {
- return index2;
- }
- }
- return -1;
-}
-function parseLinkCode(string4, offset) {
- string4 = string4.slice(offset);
- for (let index2 = 1;index2 < linkStartCodePrefixCharCodes.length; index2++) {
- if (string4.charCodeAt(index2) !== linkStartCodePrefixCharCodes[index2]) {
- return;
- }
- }
- const endIndex = string4.indexOf("\x07", linkStartCodePrefix.length);
- if (endIndex === -1)
- return;
- return string4.slice(0, endIndex + 1);
-}
-function parseAnsiCode(string4, offset) {
- string4 = string4.slice(offset, offset + 19);
- const startIndex = findNumberIndex(string4);
- if (startIndex !== -1) {
- let endIndex = string4.indexOf("m", startIndex);
- if (endIndex === -1) {
- endIndex = string4.length;
- }
- return string4.slice(0, endIndex + 1);
- }
-}
-function tokenize6(str, endChar = Number.POSITIVE_INFINITY) {
- const ret = [];
- let index2 = 0;
- let visible = 0;
- while (index2 < str.length) {
- const codePoint = str.codePointAt(index2);
- if (ESCAPES.has(codePoint)) {
- const code = parseLinkCode(str, index2) || parseAnsiCode(str, index2);
- if (code) {
- ret.push({
- type: "ansi",
- code,
- endCode: getEndCode(code)
- });
- index2 += code.length;
- continue;
- }
- }
- const fullWidth = isFullwidthCodePoint(codePoint);
- const character = String.fromCodePoint(codePoint);
- ret.push({
- type: "char",
- value: character,
- fullWidth
- });
- index2 += character.length;
- visible += fullWidth ? 2 : character.length;
- if (visible >= endChar) {
- break;
- }
- }
- return ret;
-}
-var init_tokenize2 = __esm(() => {
- init_ansiCodes();
-});
-
-// node_modules/@alcalzone/ansi-tokenize/build/index.js
-var init_build = __esm(() => {
- init_ansiCodes();
- init_diff();
- init_reduce();
- init_undo();
- init_styledChars();
- init_tokenize2();
-});
-
-// src/utils/sliceAnsi.ts
-function isEndCode(code) {
- return code.code === code.endCode;
-}
-function filterStartCodes(codes) {
- return codes.filter((c8) => !isEndCode(c8));
-}
-function sliceAnsi(str, start, end) {
- const tokens = tokenize6(str);
- let activeCodes = [];
- let position2 = 0;
- let result = "";
- let include = false;
- for (const token of tokens) {
- const width = token.type === "ansi" ? 0 : token.fullWidth ? 2 : stringWidth(token.value);
- if (end !== undefined && position2 >= end) {
- if (token.type === "ansi" || width > 0 || !include)
- break;
- }
- if (token.type === "ansi") {
- activeCodes.push(token);
- if (include) {
- result += token.code;
- }
- } else {
- if (!include && position2 >= start) {
- if (start > 0 && width === 0)
- continue;
- include = true;
- activeCodes = filterStartCodes(reduceAnsiCodes(activeCodes));
- result = ansiCodesToString(activeCodes);
- }
- if (include) {
- result += token.value;
- }
- position2 += width;
- }
- }
- const activeStartCodes = filterStartCodes(reduceAnsiCodes(activeCodes));
- result += ansiCodesToString(undoAnsiCodes(activeStartCodes));
- return result;
-}
-var init_sliceAnsi = __esm(() => {
- init_build();
- init_stringWidth();
-});
-
-// node_modules/string-width/index.js
-function stringWidth2(string4, options2 = {}) {
- if (typeof string4 !== "string" || string4.length === 0) {
- return 0;
- }
- const {
- ambiguousIsNarrow = true,
- countAnsiEscapeCodes = false
- } = options2;
- if (!countAnsiEscapeCodes) {
- string4 = stripAnsi(string4);
- }
- if (string4.length === 0) {
- return 0;
- }
- let width = 0;
- const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
- for (const { segment: character } of segmenter.segment(string4)) {
- const codePoint = character.codePointAt(0);
- if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
- continue;
- }
- if (codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279) {
- continue;
- }
- if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
- continue;
- }
- if (codePoint >= 55296 && codePoint <= 57343) {
- continue;
- }
- if (codePoint >= 65024 && codePoint <= 65039) {
- continue;
- }
- if (defaultIgnorableCodePointRegex.test(character)) {
- continue;
- }
- if (emoji_regex_default().test(character)) {
- width += 2;
- continue;
- }
- width += eastAsianWidth(codePoint, eastAsianWidthOptions);
- }
- return width;
-}
-var segmenter, defaultIgnorableCodePointRegex;
-var init_string_width = __esm(() => {
- init_strip_ansi();
- init_get_east_asian_width();
- segmenter = new Intl.Segmenter;
- defaultIgnorableCodePointRegex = /^\p{Default_Ignorable_Code_Point}$/u;
-});
-
-// node_modules/wrap-ansi/index.js
-function wrapAnsi(string4, columns, options2) {
- return String(string4).normalize().replaceAll(`\r
-`, `
-`).split(`
-`).map((line) => exec3(line, columns, options2)).join(`
-`);
-}
-var ESCAPES2, END_CODE = 39, ANSI_ESCAPE_BELL = "\x07", ANSI_CSI = "[", ANSI_OSC = "]", ANSI_SGR_TERMINATOR = "m", ANSI_ESCAPE_LINK, wrapAnsiCode = (code) => `${ESCAPES2.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`, wrapAnsiHyperlink = (url3) => `${ESCAPES2.values().next().value}${ANSI_ESCAPE_LINK}${url3}${ANSI_ESCAPE_BELL}`, wordLengths = (string4) => string4.split(" ").map((character) => stringWidth2(character)), wrapWord = (rows, word, columns) => {
- const characters = [...word];
- let isInsideEscape = false;
- let isInsideLinkEscape = false;
- let visible = stringWidth2(stripAnsi(rows.at(-1)));
- for (const [index2, character] of characters.entries()) {
- const characterLength = stringWidth2(character);
- if (visible + characterLength <= columns) {
- rows[rows.length - 1] += character;
- } else {
- rows.push(character);
- visible = 0;
- }
- if (ESCAPES2.has(character)) {
- isInsideEscape = true;
- const ansiEscapeLinkCandidate = characters.slice(index2 + 1, index2 + 1 + ANSI_ESCAPE_LINK.length).join("");
- isInsideLinkEscape = ansiEscapeLinkCandidate === ANSI_ESCAPE_LINK;
- }
- if (isInsideEscape) {
- if (isInsideLinkEscape) {
- if (character === ANSI_ESCAPE_BELL) {
- isInsideEscape = false;
- isInsideLinkEscape = false;
- }
- } else if (character === ANSI_SGR_TERMINATOR) {
- isInsideEscape = false;
- }
- continue;
- }
- visible += characterLength;
- if (visible === columns && index2 < characters.length - 1) {
- rows.push("");
- visible = 0;
- }
- }
- if (!visible && rows.at(-1).length > 0 && rows.length > 1) {
- rows[rows.length - 2] += rows.pop();
- }
-}, stringVisibleTrimSpacesRight = (string4) => {
- const words = string4.split(" ");
- let last = words.length;
- while (last > 0) {
- if (stringWidth2(words[last - 1]) > 0) {
- break;
- }
- last--;
- }
- if (last === words.length) {
- return string4;
- }
- return words.slice(0, last).join(" ") + words.slice(last).join("");
-}, exec3 = (string4, columns, options2 = {}) => {
- if (options2.trim !== false && string4.trim() === "") {
- return "";
- }
- let returnValue = "";
- let escapeCode;
- let escapeUrl;
- const lengths = wordLengths(string4);
- let rows = [""];
- for (const [index2, word] of string4.split(" ").entries()) {
- if (options2.trim !== false) {
- rows[rows.length - 1] = rows.at(-1).trimStart();
- }
- let rowLength = stringWidth2(rows.at(-1));
- if (index2 !== 0) {
- if (rowLength >= columns && (options2.wordWrap === false || options2.trim === false)) {
- rows.push("");
- rowLength = 0;
- }
- if (rowLength > 0 || options2.trim === false) {
- rows[rows.length - 1] += " ";
- rowLength++;
- }
- }
- if (options2.hard && lengths[index2] > columns) {
- const remainingColumns = columns - rowLength;
- const breaksStartingThisLine = 1 + Math.floor((lengths[index2] - remainingColumns - 1) / columns);
- const breaksStartingNextLine = Math.floor((lengths[index2] - 1) / columns);
- if (breaksStartingNextLine < breaksStartingThisLine) {
- rows.push("");
- }
- wrapWord(rows, word, columns);
- continue;
- }
- if (rowLength + lengths[index2] > columns && rowLength > 0 && lengths[index2] > 0) {
- if (options2.wordWrap === false && rowLength < columns) {
- wrapWord(rows, word, columns);
- continue;
- }
- rows.push("");
- }
- if (rowLength + lengths[index2] > columns && options2.wordWrap === false) {
- wrapWord(rows, word, columns);
- continue;
- }
- rows[rows.length - 1] += word;
- }
- if (options2.trim !== false) {
- rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
- }
- const preString = rows.join(`
-`);
- const pre = [...preString];
- let preStringIndex = 0;
- for (const [index2, character] of pre.entries()) {
- returnValue += character;
- if (ESCAPES2.has(character)) {
- const { groups } = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(preString.slice(preStringIndex)) || { groups: {} };
- if (groups.code !== undefined) {
- const code2 = Number.parseFloat(groups.code);
- escapeCode = code2 === END_CODE ? undefined : code2;
- } else if (groups.uri !== undefined) {
- escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;
- }
- }
- const code = ansi_styles_default2.codes.get(Number(escapeCode));
- if (pre[index2 + 1] === `
-`) {
- if (escapeUrl) {
- returnValue += wrapAnsiHyperlink("");
- }
- if (escapeCode && code) {
- returnValue += wrapAnsiCode(code);
- }
- } else if (character === `
-`) {
- if (escapeCode && code) {
- returnValue += wrapAnsiCode(escapeCode);
- }
- if (escapeUrl) {
- returnValue += wrapAnsiHyperlink(escapeUrl);
- }
- }
- preStringIndex += character.length;
- }
- return returnValue;
-};
-var init_wrap_ansi = __esm(() => {
- init_string_width();
- init_strip_ansi();
- init_ansi_styles2();
- ESCAPES2 = new Set([
- "\x1B",
- "\x9B"
- ]);
- ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
-});
-
-// src/ink/wrapAnsi.ts
-var wrapAnsiBun, wrapAnsi2;
-var init_wrapAnsi = __esm(() => {
- init_wrap_ansi();
- wrapAnsiBun = typeof Bun !== "undefined" && typeof Bun.wrapAnsi === "function" ? Bun.wrapAnsi : null;
- wrapAnsi2 = wrapAnsiBun ?? wrapAnsi;
-});
-
-// src/ink/wrap-text.ts
-function sliceFit(text, start, end) {
- const s4 = sliceAnsi(text, start, end);
- return stringWidth(s4) > end - start ? sliceAnsi(text, start, end - 1) : s4;
-}
-function truncate2(text, columns, position2) {
- if (columns < 1)
- return "";
- if (columns === 1)
- return ELLIPSIS;
- const length = stringWidth(text);
- if (length <= columns)
- return text;
- if (position2 === "start") {
- return ELLIPSIS + sliceFit(text, length - columns + 1, length);
- }
- if (position2 === "middle") {
- const half = Math.floor(columns / 2);
- return sliceFit(text, 0, half) + ELLIPSIS + sliceFit(text, length - (columns - half) + 1, length);
- }
- return sliceFit(text, 0, columns - 1) + ELLIPSIS;
-}
-function wrapText2(text, maxWidth, wrapType) {
- if (wrapType === "wrap") {
- return wrapAnsi2(text, maxWidth, {
- trim: false,
- hard: true
- });
- }
- if (wrapType === "wrap-trim") {
- return wrapAnsi2(text, maxWidth, {
- trim: true,
- hard: true
- });
- }
- if (wrapType.startsWith("truncate")) {
- let position2 = "end";
- if (wrapType === "truncate-middle") {
- position2 = "middle";
- }
- if (wrapType === "truncate-start") {
- position2 = "start";
- }
- return truncate2(text, maxWidth, position2);
- }
- return text;
-}
-var ELLIPSIS = "\u2026";
-var init_wrap_text = __esm(() => {
- init_sliceAnsi();
- init_stringWidth();
- init_wrapAnsi();
-});
-
-// src/ink/dom.ts
-function collectRemovedRects(parent, removed, underAbsolute = false) {
- if (removed.nodeName === "#text")
- return;
- const elem = removed;
- const isAbsolute5 = underAbsolute || elem.style.position === "absolute";
- const cached2 = nodeCache.get(elem);
- if (cached2) {
- addPendingClear(parent, cached2, isAbsolute5);
- nodeCache.delete(elem);
- }
- for (const child of elem.childNodes) {
- collectRemovedRects(parent, child, isAbsolute5);
- }
-}
-function stylesEqual(a5, b4) {
- return shallowEqual(a5, b4);
-}
-function shallowEqual(a5, b4) {
- if (a5 === b4)
- return true;
- if (a5 === undefined || b4 === undefined)
- return false;
- const aKeys = Object.keys(a5);
- const bKeys = Object.keys(b4);
- if (aKeys.length !== bKeys.length)
- return false;
- for (const key of aKeys) {
- if (a5[key] !== b4[key])
- return false;
- }
- return true;
-}
-function isDOMElement(node) {
- return node.nodeName !== "#text";
-}
-function findOwnerChainAtRow(root2, y3) {
- let best = [];
- walk(root2, 0);
- return best;
- function walk(node, offsetY) {
- const yoga = node.yogaNode;
- if (!yoga || yoga.getDisplay() === LayoutDisplay.None)
- return;
- const top = offsetY + yoga.getComputedTop();
- const height = yoga.getComputedHeight();
- if (y3 < top || y3 >= top + height)
- return;
- if (node.debugOwnerChain)
- best = node.debugOwnerChain;
- for (const child of node.childNodes) {
- if (isDOMElement(child))
- walk(child, top);
- }
- }
-}
-var createNode = (nodeName) => {
- const needsYogaNode = nodeName !== "ink-virtual-text" && nodeName !== "ink-link" && nodeName !== "ink-progress";
- const node = {
- nodeName,
- style: {},
- attributes: {},
- childNodes: [],
- parentNode: undefined,
- yogaNode: needsYogaNode ? createLayoutNode() : undefined,
- dirty: false
- };
- if (nodeName === "ink-text") {
- node.yogaNode?.setMeasureFunc(measureTextNode.bind(null, node));
- } else if (nodeName === "ink-raw-ansi") {
- node.yogaNode?.setMeasureFunc(measureRawAnsiNode.bind(null, node));
- }
- return node;
-}, appendChildNode = (node, childNode) => {
- if (childNode.parentNode) {
- removeChildNode(childNode.parentNode, childNode);
- }
- childNode.parentNode = node;
- node.childNodes.push(childNode);
- if (childNode.yogaNode) {
- node.yogaNode?.insertChild(childNode.yogaNode, node.yogaNode.getChildCount());
- }
- markDirty(node);
-}, insertBeforeNode = (node, newChildNode, beforeChildNode) => {
- if (newChildNode.parentNode) {
- removeChildNode(newChildNode.parentNode, newChildNode);
- }
- newChildNode.parentNode = node;
- const index2 = node.childNodes.indexOf(beforeChildNode);
- if (index2 >= 0) {
- let yogaIndex = 0;
- if (newChildNode.yogaNode && node.yogaNode) {
- for (let i5 = 0;i5 < index2; i5++) {
- if (node.childNodes[i5]?.yogaNode) {
- yogaIndex++;
- }
- }
- }
- node.childNodes.splice(index2, 0, newChildNode);
- if (newChildNode.yogaNode && node.yogaNode) {
- node.yogaNode.insertChild(newChildNode.yogaNode, yogaIndex);
- }
- markDirty(node);
- return;
- }
- node.childNodes.push(newChildNode);
- if (newChildNode.yogaNode) {
- node.yogaNode?.insertChild(newChildNode.yogaNode, node.yogaNode.getChildCount());
- }
- markDirty(node);
-}, removeChildNode = (node, removeNode) => {
- if (removeNode.yogaNode) {
- removeNode.parentNode?.yogaNode?.removeChild(removeNode.yogaNode);
- }
- collectRemovedRects(node, removeNode);
- removeNode.parentNode = undefined;
- const index2 = node.childNodes.indexOf(removeNode);
- if (index2 >= 0) {
- node.childNodes.splice(index2, 1);
- }
- markDirty(node);
-}, setAttribute = (node, key, value) => {
- if (key === "children") {
- return;
- }
- if (node.attributes[key] === value) {
- return;
- }
- node.attributes[key] = value;
- markDirty(node);
-}, setStyle = (node, style) => {
- if (stylesEqual(node.style, style)) {
- return;
- }
- node.style = style;
- markDirty(node);
-}, setTextStyles = (node, textStyles) => {
- if (shallowEqual(node.textStyles, textStyles)) {
- return;
- }
- node.textStyles = textStyles;
- markDirty(node);
-}, createTextNode = (text) => {
- const node = {
- nodeName: "#text",
- nodeValue: text,
- yogaNode: undefined,
- parentNode: undefined,
- style: {}
- };
- setTextNodeValue(node, text);
- return node;
-}, measureTextNode = function(node, width, widthMode) {
- const rawText = node.nodeName === "#text" ? node.nodeValue : squash_text_nodes_default(node);
- const text = expandTabs(rawText);
- const dimensions = measure_text_default(text, width);
- if (dimensions.width <= width) {
- return dimensions;
- }
- if (dimensions.width >= 1 && width > 0 && width < 1) {
- return dimensions;
- }
- if (text.includes(`
-`) && widthMode === LayoutMeasureMode.Undefined) {
- const effectiveWidth = Math.max(width, dimensions.width);
- return measure_text_default(text, effectiveWidth);
- }
- const textWrap = node.style?.textWrap ?? "wrap";
- const wrappedText = wrapText2(text, width, textWrap);
- return measure_text_default(wrappedText, width);
-}, measureRawAnsiNode = function(node) {
- return {
- width: node.attributes["rawWidth"],
- height: node.attributes["rawHeight"]
- };
-}, markDirty = (node) => {
- let current = node;
- let markedYoga = false;
- while (current) {
- if (current.nodeName !== "#text") {
- current.dirty = true;
- if (!markedYoga && (current.nodeName === "ink-text" || current.nodeName === "ink-raw-ansi") && current.yogaNode) {
- current.yogaNode.markDirty();
- markedYoga = true;
- }
- }
- current = current.parentNode;
- }
-}, scheduleRenderFrom = (node) => {
- let cur = node;
- while (cur?.parentNode)
- cur = cur.parentNode;
- if (cur && cur.nodeName !== "#text")
- cur.onRender?.();
-}, setTextNodeValue = (node, text) => {
- if (typeof text !== "string") {
- text = String(text);
- }
- if (node.nodeValue === text) {
- return;
- }
- node.nodeValue = text;
- markDirty(node);
-}, clearYogaNodeReferences = (node) => {
- if ("childNodes" in node) {
- for (const child of node.childNodes) {
- clearYogaNodeReferences(child);
- }
- }
- node.yogaNode = undefined;
-};
-var init_dom = __esm(() => {
- init_engine();
- init_node5();
- init_measure_text();
- init_node_cache();
- init_squash_text_nodes();
- init_tabstops();
- init_wrap_text();
-});
-
-// src/ink/events/event-handlers.ts
-var HANDLER_FOR_EVENT, EVENT_HANDLER_PROPS;
-var init_event_handlers = __esm(() => {
- HANDLER_FOR_EVENT = {
- keydown: { bubble: "onKeyDown", capture: "onKeyDownCapture" },
- focus: { bubble: "onFocus", capture: "onFocusCapture" },
- blur: { bubble: "onBlur", capture: "onBlurCapture" },
- paste: { bubble: "onPaste", capture: "onPasteCapture" },
- resize: { bubble: "onResize" },
- click: { bubble: "onClick" }
- };
- EVENT_HANDLER_PROPS = new Set([
- "onKeyDown",
- "onKeyDownCapture",
- "onFocus",
- "onFocusCapture",
- "onBlur",
- "onBlurCapture",
- "onPaste",
- "onPasteCapture",
- "onResize",
- "onClick",
- "onMouseEnter",
- "onMouseLeave"
- ]);
-});
-
-// src/ink/events/dispatcher.ts
-function getHandler(node, eventType, capture) {
- const handlers = node._eventHandlers;
- if (!handlers)
- return;
- const mapping = HANDLER_FOR_EVENT[eventType];
- if (!mapping)
- return;
- const propName = capture ? mapping.capture : mapping.bubble;
- if (!propName)
- return;
- return handlers[propName];
-}
-function collectListeners(target, event) {
- const listeners = [];
- let node = target;
- while (node) {
- const isTarget = node === target;
- const captureHandler = getHandler(node, event.type, true);
- const bubbleHandler = getHandler(node, event.type, false);
- if (captureHandler) {
- listeners.unshift({
- node,
- handler: captureHandler,
- phase: isTarget ? "at_target" : "capturing"
- });
- }
- if (bubbleHandler && (event.bubbles || isTarget)) {
- listeners.push({
- node,
- handler: bubbleHandler,
- phase: isTarget ? "at_target" : "bubbling"
- });
- }
- node = node.parentNode;
- }
- return listeners;
-}
-function processDispatchQueue(listeners, event) {
- let previousNode;
- for (const { node, handler, phase } of listeners) {
- if (event._isImmediatePropagationStopped()) {
- break;
- }
- if (event._isPropagationStopped() && node !== previousNode) {
- break;
- }
- event._setEventPhase(phase);
- event._setCurrentTarget(node);
- event._prepareForTarget(node);
- try {
- handler(event);
- } catch (error46) {
- logError2(error46);
- }
- previousNode = node;
- }
-}
-function getEventPriority(eventType) {
- switch (eventType) {
- case "keydown":
- case "keyup":
- case "click":
- case "focus":
- case "blur":
- case "paste":
- return import_constants41.DiscreteEventPriority;
- case "resize":
- case "scroll":
- case "mousemove":
- return import_constants41.ContinuousEventPriority;
- default:
- return import_constants41.DefaultEventPriority;
- }
-}
-
-class Dispatcher {
- currentEvent = null;
- currentUpdatePriority = import_constants41.DefaultEventPriority;
- discreteUpdates = null;
- resolveEventPriority() {
- if (this.currentUpdatePriority !== import_constants41.NoEventPriority) {
- return this.currentUpdatePriority;
- }
- if (this.currentEvent) {
- return getEventPriority(this.currentEvent.type);
- }
- return import_constants41.DefaultEventPriority;
- }
- dispatch(target, event) {
- const previousEvent = this.currentEvent;
- this.currentEvent = event;
- try {
- event._setTarget(target);
- const listeners = collectListeners(target, event);
- processDispatchQueue(listeners, event);
- event._setEventPhase("none");
- event._setCurrentTarget(null);
- return !event.defaultPrevented;
- } finally {
- this.currentEvent = previousEvent;
- }
- }
- dispatchDiscrete(target, event) {
- if (!this.discreteUpdates) {
- return this.dispatch(target, event);
- }
- return this.discreteUpdates((t4, e4) => this.dispatch(t4, e4), target, event, undefined, undefined);
- }
- dispatchContinuous(target, event) {
- const previousPriority = this.currentUpdatePriority;
- try {
- this.currentUpdatePriority = import_constants41.ContinuousEventPriority;
- return this.dispatch(target, event);
- } finally {
- this.currentUpdatePriority = previousPriority;
- }
- }
-}
-var import_constants41;
-var init_dispatcher = __esm(() => {
- init_log2();
- init_event_handlers();
- import_constants41 = __toESM(require_constants5(), 1);
-});
-
-// src/ink/events/terminal-event.ts
-var TerminalEvent;
-var init_terminal_event = __esm(() => {
- TerminalEvent = class TerminalEvent extends Event2 {
- type;
- timeStamp;
- bubbles;
- cancelable;
- _target = null;
- _currentTarget = null;
- _eventPhase = "none";
- _propagationStopped = false;
- _defaultPrevented = false;
- constructor(type, init) {
- super();
- this.type = type;
- this.timeStamp = performance.now();
- this.bubbles = init?.bubbles ?? true;
- this.cancelable = init?.cancelable ?? true;
- }
- get target() {
- return this._target;
- }
- get currentTarget() {
- return this._currentTarget;
- }
- get eventPhase() {
- return this._eventPhase;
- }
- get defaultPrevented() {
- return this._defaultPrevented;
- }
- stopPropagation() {
- this._propagationStopped = true;
- }
- stopImmediatePropagation() {
- super.stopImmediatePropagation();
- this._propagationStopped = true;
- }
- preventDefault() {
- if (this.cancelable) {
- this._defaultPrevented = true;
- }
- }
- _setTarget(target) {
- this._target = target;
- }
- _setCurrentTarget(target) {
- this._currentTarget = target;
- }
- _setEventPhase(phase) {
- this._eventPhase = phase;
- }
- _isPropagationStopped() {
- return this._propagationStopped;
- }
- _isImmediatePropagationStopped() {
- return this.didStopImmediatePropagation();
- }
- _prepareForTarget(_target) {}
- };
-});
-
-// src/ink/events/focus-event.ts
-var FocusEvent;
-var init_focus_event = __esm(() => {
- init_terminal_event();
- FocusEvent = class FocusEvent extends TerminalEvent {
- relatedTarget;
- constructor(type, relatedTarget = null) {
- super(type, { bubbles: true, cancelable: false });
- this.relatedTarget = relatedTarget;
- }
- };
-});
-
-// src/ink/focus.ts
-class FocusManager {
- activeElement = null;
- dispatchFocusEvent;
- enabled = true;
- focusStack = [];
- constructor(dispatchFocusEvent) {
- this.dispatchFocusEvent = dispatchFocusEvent;
- }
- focus(node) {
- if (node === this.activeElement)
- return;
- if (!this.enabled)
- return;
- const previous = this.activeElement;
- if (previous) {
- const idx = this.focusStack.indexOf(previous);
- if (idx !== -1)
- this.focusStack.splice(idx, 1);
- this.focusStack.push(previous);
- if (this.focusStack.length > MAX_FOCUS_STACK)
- this.focusStack.shift();
- this.dispatchFocusEvent(previous, new FocusEvent("blur", node));
- }
- this.activeElement = node;
- this.dispatchFocusEvent(node, new FocusEvent("focus", previous));
- }
- blur() {
- if (!this.activeElement)
- return;
- const previous = this.activeElement;
- this.activeElement = null;
- this.dispatchFocusEvent(previous, new FocusEvent("blur", null));
- }
- handleNodeRemoved(node, root2) {
- this.focusStack = this.focusStack.filter((n5) => n5 !== node && isInTree(n5, root2));
- if (!this.activeElement)
- return;
- if (this.activeElement !== node && isInTree(this.activeElement, root2)) {
- return;
- }
- const removed = this.activeElement;
- this.activeElement = null;
- this.dispatchFocusEvent(removed, new FocusEvent("blur", null));
- while (this.focusStack.length > 0) {
- const candidate = this.focusStack.pop();
- if (isInTree(candidate, root2)) {
- this.activeElement = candidate;
- this.dispatchFocusEvent(candidate, new FocusEvent("focus", removed));
- return;
- }
- }
- }
- handleAutoFocus(node) {
- this.focus(node);
- }
- handleClickFocus(node) {
- const tabIndex = node.attributes["tabIndex"];
- if (typeof tabIndex !== "number")
- return;
- this.focus(node);
- }
- enable() {
- this.enabled = true;
- }
- disable() {
- this.enabled = false;
- }
- focusNext(root2) {
- this.moveFocus(1, root2);
- }
- focusPrevious(root2) {
- this.moveFocus(-1, root2);
- }
- moveFocus(direction, root2) {
- if (!this.enabled)
- return;
- const tabbable = collectTabbable(root2);
- if (tabbable.length === 0)
- return;
- const currentIndex = this.activeElement ? tabbable.indexOf(this.activeElement) : -1;
- const nextIndex = currentIndex === -1 ? direction === 1 ? 0 : tabbable.length - 1 : (currentIndex + direction + tabbable.length) % tabbable.length;
- const next = tabbable[nextIndex];
- if (next) {
- this.focus(next);
- }
- }
-}
-function collectTabbable(root2) {
- const result = [];
- walkTree(root2, result);
- return result;
-}
-function walkTree(node, result) {
- const tabIndex = node.attributes["tabIndex"];
- if (typeof tabIndex === "number" && tabIndex >= 0) {
- result.push(node);
- }
- for (const child of node.childNodes) {
- if (child.nodeName !== "#text") {
- walkTree(child, result);
- }
- }
-}
-function isInTree(node, root2) {
- let current = node;
- while (current) {
- if (current === root2)
- return true;
- current = current.parentNode;
- }
- return false;
-}
-function getRootNode(node) {
- let current = node;
- while (current) {
- if (current.focusManager)
- return current;
- current = current.parentNode;
- }
- throw new Error("Node is not in a tree with a FocusManager");
-}
-function getFocusManager(node) {
- return getRootNode(node).focusManager;
-}
-var MAX_FOCUS_STACK = 32;
-var init_focus = __esm(() => {
- init_focus_event();
-});
-
-// src/ink/styles.ts
-function applyPositionEdge(node, edge, v6) {
- if (typeof v6 === "string") {
- node.setPositionPercent(edge, Number.parseInt(v6, 10));
- } else if (typeof v6 === "number") {
- node.setPosition(edge, v6);
- } else {
- node.setPosition(edge, Number.NaN);
- }
-}
-var applyPositionStyles = (node, style) => {
- if ("position" in style) {
- node.setPositionType(style.position === "absolute" ? LayoutPositionType.Absolute : LayoutPositionType.Relative);
- }
- if ("top" in style)
- applyPositionEdge(node, "top", style.top);
- if ("bottom" in style)
- applyPositionEdge(node, "bottom", style.bottom);
- if ("left" in style)
- applyPositionEdge(node, "left", style.left);
- if ("right" in style)
- applyPositionEdge(node, "right", style.right);
-}, applyOverflowStyles = (node, style) => {
- const y3 = style.overflowY ?? style.overflow;
- const x3 = style.overflowX ?? style.overflow;
- if (y3 === "scroll" || x3 === "scroll") {
- node.setOverflow(LayoutOverflow.Scroll);
- } else if (y3 === "hidden" || x3 === "hidden") {
- node.setOverflow(LayoutOverflow.Hidden);
- } else if ("overflow" in style || "overflowX" in style || "overflowY" in style) {
- node.setOverflow(LayoutOverflow.Visible);
- }
-}, applyMarginStyles = (node, style) => {
- if ("margin" in style) {
- node.setMargin(LayoutEdge.All, style.margin ?? 0);
- }
- if ("marginX" in style) {
- node.setMargin(LayoutEdge.Horizontal, style.marginX ?? 0);
- }
- if ("marginY" in style) {
- node.setMargin(LayoutEdge.Vertical, style.marginY ?? 0);
- }
- if ("marginLeft" in style) {
- node.setMargin(LayoutEdge.Start, style.marginLeft || 0);
- }
- if ("marginRight" in style) {
- node.setMargin(LayoutEdge.End, style.marginRight || 0);
- }
- if ("marginTop" in style) {
- node.setMargin(LayoutEdge.Top, style.marginTop || 0);
- }
- if ("marginBottom" in style) {
- node.setMargin(LayoutEdge.Bottom, style.marginBottom || 0);
- }
-}, applyPaddingStyles = (node, style) => {
- if ("padding" in style) {
- node.setPadding(LayoutEdge.All, style.padding ?? 0);
- }
- if ("paddingX" in style) {
- node.setPadding(LayoutEdge.Horizontal, style.paddingX ?? 0);
- }
- if ("paddingY" in style) {
- node.setPadding(LayoutEdge.Vertical, style.paddingY ?? 0);
- }
- if ("paddingLeft" in style) {
- node.setPadding(LayoutEdge.Left, style.paddingLeft || 0);
- }
- if ("paddingRight" in style) {
- node.setPadding(LayoutEdge.Right, style.paddingRight || 0);
- }
- if ("paddingTop" in style) {
- node.setPadding(LayoutEdge.Top, style.paddingTop || 0);
- }
- if ("paddingBottom" in style) {
- node.setPadding(LayoutEdge.Bottom, style.paddingBottom || 0);
- }
-}, applyFlexStyles = (node, style) => {
- if ("flexGrow" in style) {
- node.setFlexGrow(style.flexGrow ?? 0);
- }
- if ("flexShrink" in style) {
- node.setFlexShrink(typeof style.flexShrink === "number" ? style.flexShrink : 1);
- }
- if ("flexWrap" in style) {
- if (style.flexWrap === "nowrap") {
- node.setFlexWrap(LayoutWrap.NoWrap);
- }
- if (style.flexWrap === "wrap") {
- node.setFlexWrap(LayoutWrap.Wrap);
- }
- if (style.flexWrap === "wrap-reverse") {
- node.setFlexWrap(LayoutWrap.WrapReverse);
- }
- }
- if ("flexDirection" in style) {
- if (style.flexDirection === "row") {
- node.setFlexDirection(LayoutFlexDirection.Row);
- }
- if (style.flexDirection === "row-reverse") {
- node.setFlexDirection(LayoutFlexDirection.RowReverse);
- }
- if (style.flexDirection === "column") {
- node.setFlexDirection(LayoutFlexDirection.Column);
- }
- if (style.flexDirection === "column-reverse") {
- node.setFlexDirection(LayoutFlexDirection.ColumnReverse);
- }
- }
- if ("flexBasis" in style) {
- if (typeof style.flexBasis === "number") {
- node.setFlexBasis(style.flexBasis);
- } else if (typeof style.flexBasis === "string") {
- node.setFlexBasisPercent(Number.parseInt(style.flexBasis, 10));
- } else {
- node.setFlexBasis(Number.NaN);
- }
- }
- if ("alignItems" in style) {
- if (style.alignItems === "stretch" || !style.alignItems) {
- node.setAlignItems(LayoutAlign.Stretch);
- }
- if (style.alignItems === "flex-start") {
- node.setAlignItems(LayoutAlign.FlexStart);
- }
- if (style.alignItems === "center") {
- node.setAlignItems(LayoutAlign.Center);
- }
- if (style.alignItems === "flex-end") {
- node.setAlignItems(LayoutAlign.FlexEnd);
- }
- }
- if ("alignSelf" in style) {
- if (style.alignSelf === "auto" || !style.alignSelf) {
- node.setAlignSelf(LayoutAlign.Auto);
- }
- if (style.alignSelf === "flex-start") {
- node.setAlignSelf(LayoutAlign.FlexStart);
- }
- if (style.alignSelf === "center") {
- node.setAlignSelf(LayoutAlign.Center);
- }
- if (style.alignSelf === "flex-end") {
- node.setAlignSelf(LayoutAlign.FlexEnd);
- }
- }
- if ("justifyContent" in style) {
- if (style.justifyContent === "flex-start" || !style.justifyContent) {
- node.setJustifyContent(LayoutJustify.FlexStart);
- }
- if (style.justifyContent === "center") {
- node.setJustifyContent(LayoutJustify.Center);
- }
- if (style.justifyContent === "flex-end") {
- node.setJustifyContent(LayoutJustify.FlexEnd);
- }
- if (style.justifyContent === "space-between") {
- node.setJustifyContent(LayoutJustify.SpaceBetween);
- }
- if (style.justifyContent === "space-around") {
- node.setJustifyContent(LayoutJustify.SpaceAround);
- }
- if (style.justifyContent === "space-evenly") {
- node.setJustifyContent(LayoutJustify.SpaceEvenly);
- }
- }
-}, applyDimensionStyles = (node, style) => {
- if ("width" in style) {
- if (typeof style.width === "number") {
- node.setWidth(style.width);
- } else if (typeof style.width === "string") {
- node.setWidthPercent(Number.parseInt(style.width, 10));
- } else {
- node.setWidthAuto();
- }
- }
- if ("height" in style) {
- if (typeof style.height === "number") {
- node.setHeight(style.height);
- } else if (typeof style.height === "string") {
- node.setHeightPercent(Number.parseInt(style.height, 10));
- } else {
- node.setHeightAuto();
- }
- }
- if ("minWidth" in style) {
- if (typeof style.minWidth === "string") {
- node.setMinWidthPercent(Number.parseInt(style.minWidth, 10));
- } else {
- node.setMinWidth(style.minWidth ?? 0);
- }
- }
- if ("minHeight" in style) {
- if (typeof style.minHeight === "string") {
- node.setMinHeightPercent(Number.parseInt(style.minHeight, 10));
- } else {
- node.setMinHeight(style.minHeight ?? 0);
- }
- }
- if ("maxWidth" in style) {
- if (typeof style.maxWidth === "string") {
- node.setMaxWidthPercent(Number.parseInt(style.maxWidth, 10));
- } else {
- node.setMaxWidth(style.maxWidth ?? 0);
- }
- }
- if ("maxHeight" in style) {
- if (typeof style.maxHeight === "string") {
- node.setMaxHeightPercent(Number.parseInt(style.maxHeight, 10));
- } else {
- node.setMaxHeight(style.maxHeight ?? 0);
- }
- }
-}, applyDisplayStyles = (node, style) => {
- if ("display" in style) {
- node.setDisplay(style.display === "flex" ? LayoutDisplay.Flex : LayoutDisplay.None);
- }
-}, applyBorderStyles = (node, style, resolvedStyle) => {
- const resolved = resolvedStyle ?? style;
- if ("borderStyle" in style) {
- const borderWidth = style.borderStyle ? 1 : 0;
- node.setBorder(LayoutEdge.Top, resolved.borderTop !== false ? borderWidth : 0);
- node.setBorder(LayoutEdge.Bottom, resolved.borderBottom !== false ? borderWidth : 0);
- node.setBorder(LayoutEdge.Left, resolved.borderLeft !== false ? borderWidth : 0);
- node.setBorder(LayoutEdge.Right, resolved.borderRight !== false ? borderWidth : 0);
- } else {
- if ("borderTop" in style && style.borderTop !== undefined) {
- node.setBorder(LayoutEdge.Top, style.borderTop === false ? 0 : 1);
- }
- if ("borderBottom" in style && style.borderBottom !== undefined) {
- node.setBorder(LayoutEdge.Bottom, style.borderBottom === false ? 0 : 1);
- }
- if ("borderLeft" in style && style.borderLeft !== undefined) {
- node.setBorder(LayoutEdge.Left, style.borderLeft === false ? 0 : 1);
- }
- if ("borderRight" in style && style.borderRight !== undefined) {
- node.setBorder(LayoutEdge.Right, style.borderRight === false ? 0 : 1);
- }
- }
-}, applyGapStyles = (node, style) => {
- if ("gap" in style) {
- node.setGap(LayoutGutter.All, style.gap ?? 0);
- }
- if ("columnGap" in style) {
- node.setGap(LayoutGutter.Column, style.columnGap ?? 0);
- }
- if ("rowGap" in style) {
- node.setGap(LayoutGutter.Row, style.rowGap ?? 0);
- }
-}, styles4 = (node, style = {}, resolvedStyle) => {
- applyPositionStyles(node, style);
- applyOverflowStyles(node, style);
- applyMarginStyles(node, style);
- applyPaddingStyles(node, style);
- applyFlexStyles(node, style);
- applyDimensionStyles(node, style);
- applyDisplayStyles(node, style);
- applyBorderStyles(node, style, resolvedStyle);
- applyGapStyles(node, style);
-}, styles_default;
-var init_styles = __esm(() => {
- init_node5();
- styles_default = styles4;
-});
-
-// src/ink/devtools.ts
-var exports_devtools = {};
-
-// src/ink/reconciler.ts
-import { appendFileSync as appendFileSync3 } from "fs";
-function setEventHandler(node, key, value) {
- if (!node._eventHandlers) {
- node._eventHandlers = {};
- }
- node._eventHandlers[key] = value;
-}
-function applyProp(node, key, value) {
- if (key === "children")
- return;
- if (key === "style") {
- setStyle(node, value);
- if (node.yogaNode) {
- styles_default(node.yogaNode, value);
- }
- return;
- }
- if (key === "textStyles") {
- node.textStyles = value;
- return;
- }
- if (EVENT_HANDLER_PROPS.has(key)) {
- setEventHandler(node, key, value);
- return;
- }
- setAttribute(node, key, value);
-}
-function getOwnerChain(fiber) {
- const chain4 = [];
- const seen = new Set;
- let cur = fiber;
- for (let i5 = 0;cur && i5 < 50; i5++) {
- if (seen.has(cur))
- break;
- seen.add(cur);
- const t4 = cur.elementType;
- const name3 = typeof t4 === "function" ? t4.displayName || t4.name : typeof t4 === "string" ? undefined : t4?.displayName || t4?.name;
- if (name3 && name3 !== chain4[chain4.length - 1])
- chain4.push(name3);
- cur = cur._debugOwner ?? cur.return;
- }
- return chain4;
-}
-function isDebugRepaintsEnabled() {
- if (debugRepaints === undefined) {
- debugRepaints = isEnvTruthy(process.env.CLAUDE_CODE_DEBUG_REPAINTS);
- }
- return debugRepaints;
-}
-function recordYogaMs(ms) {
- _lastYogaMs = ms;
-}
-function getLastYogaMs() {
- return _lastYogaMs;
-}
-function markCommitStart() {
- _commitStart = performance.now();
-}
-function getLastCommitMs() {
- return _lastCommitMs;
-}
-function resetProfileCounters() {
- _lastYogaMs = 0;
- _lastCommitMs = 0;
- _commitStart = 0;
-}
-var import_react_reconciler, diff = (before, after) => {
- if (before === after) {
- return;
- }
- if (!before) {
- return after;
- }
- const changed = {};
- let isChanged = false;
- for (const key of Object.keys(before)) {
- const isDeleted = after ? !Object.hasOwn(after, key) : true;
- if (isDeleted) {
- changed[key] = undefined;
- isChanged = true;
- }
- }
- if (after) {
- for (const key of Object.keys(after)) {
- if (after[key] !== before[key]) {
- changed[key] = after[key];
- isChanged = true;
- }
- }
- }
- return isChanged ? changed : undefined;
-}, cleanupYogaNode = (node) => {
- const yogaNode = node.yogaNode;
- if (yogaNode) {
- yogaNode.unsetMeasureFunc();
- clearYogaNodeReferences(node);
- yogaNode.freeRecursive();
- }
-}, debugRepaints, dispatcher, COMMIT_LOG, _commits = 0, _lastLog = 0, _lastCommitAt = 0, _maxGapMs = 0, _createCount = 0, _prepareAt = 0, _lastYogaMs = 0, _lastCommitMs = 0, _commitStart = 0, reconciler, reconciler_default;
-var init_reconciler = __esm(() => {
- init_yoga_layout();
- init_envUtils();
- init_dom();
- init_dispatcher();
- init_event_handlers();
- init_focus();
- init_node5();
- init_styles();
- import_react_reconciler = __toESM(require_react_reconciler(), 1);
- if (true) {
- try {
- Promise.resolve();
- } catch (error46) {
- if (error46.code === "ERR_MODULE_NOT_FOUND") {
- console.warn(`
-The environment variable DEV is set to true, so Ink tried to import \`react-devtools-core\`,
-but this failed as it was not installed. Debugging with React Devtools requires it.
-
-To install use this command:
-
-$ npm install --save-dev react-devtools-core
- `.trim() + `
-`);
- } else {
- throw error46;
- }
- }
- }
- dispatcher = new Dispatcher;
- COMMIT_LOG = process.env.CLAUDE_CODE_COMMIT_LOG;
- reconciler = import_react_reconciler.default({
- getRootHostContext: () => ({ isInsideText: false }),
- prepareForCommit: () => {
- if (COMMIT_LOG)
- _prepareAt = performance.now();
- return null;
- },
- preparePortalMount: () => null,
- clearContainer: () => false,
- resetAfterCommit(rootNode) {
- _lastCommitMs = _commitStart > 0 ? performance.now() - _commitStart : 0;
- _commitStart = 0;
- if (COMMIT_LOG) {
- const now2 = performance.now();
- _commits++;
- const gap = _lastCommitAt > 0 ? now2 - _lastCommitAt : 0;
- if (gap > _maxGapMs)
- _maxGapMs = gap;
- _lastCommitAt = now2;
- const reconcileMs = _prepareAt > 0 ? now2 - _prepareAt : 0;
- if (gap > 30 || reconcileMs > 20 || _createCount > 50) {
- appendFileSync3(COMMIT_LOG, `${now2.toFixed(1)} gap=${gap.toFixed(1)}ms reconcile=${reconcileMs.toFixed(1)}ms creates=${_createCount}
-`);
- }
- _createCount = 0;
- if (now2 - _lastLog > 1000) {
- appendFileSync3(COMMIT_LOG, `${now2.toFixed(1)} commits=${_commits}/s maxGap=${_maxGapMs.toFixed(1)}ms
-`);
- _commits = 0;
- _maxGapMs = 0;
- _lastLog = now2;
- }
- }
- const _t0 = COMMIT_LOG ? performance.now() : 0;
- if (typeof rootNode.onComputeLayout === "function") {
- rootNode.onComputeLayout();
- }
- if (COMMIT_LOG) {
- const layoutMs = performance.now() - _t0;
- if (layoutMs > 20) {
- const c8 = getYogaCounters();
- appendFileSync3(COMMIT_LOG, `${_t0.toFixed(1)} SLOW_YOGA ${layoutMs.toFixed(1)}ms visited=${c8.visited} measured=${c8.measured} hits=${c8.cacheHits} live=${c8.live}
-`);
- }
- }
- if (false) {}
- const _tr3 = COMMIT_LOG ? performance.now() : 0;
- rootNode.onRender?.();
- if (COMMIT_LOG) {
- const renderMs = performance.now() - _tr3;
- if (renderMs > 10) {
- appendFileSync3(COMMIT_LOG, `${_tr3.toFixed(1)} SLOW_PAINT ${renderMs.toFixed(1)}ms
-`);
- }
- }
- },
- getChildHostContext(parentHostContext, type) {
- const previousIsInsideText = parentHostContext.isInsideText;
- const isInsideText = type === "ink-text" || type === "ink-virtual-text" || type === "ink-link";
- if (previousIsInsideText === isInsideText) {
- return parentHostContext;
- }
- return { isInsideText };
- },
- shouldSetTextContent: () => false,
- createInstance(originalType, newProps, _root, hostContext, internalHandle) {
- if (hostContext.isInsideText && originalType === "ink-box") {
- throw new Error(` can't be nested inside component`);
- }
- const type = originalType === "ink-text" && hostContext.isInsideText ? "ink-virtual-text" : originalType;
- const node = createNode(type);
- if (COMMIT_LOG)
- _createCount++;
- for (const [key, value] of Object.entries(newProps)) {
- applyProp(node, key, value);
- }
- if (isDebugRepaintsEnabled()) {
- node.debugOwnerChain = getOwnerChain(internalHandle);
- }
- return node;
- },
- createTextInstance(text, _root, hostContext) {
- if (!hostContext.isInsideText) {
- throw new Error(`Text string "${text}" must be rendered inside component`);
- }
- return createTextNode(text);
- },
- resetTextContent() {},
- hideTextInstance(node) {
- setTextNodeValue(node, "");
- },
- unhideTextInstance(node, text) {
- setTextNodeValue(node, text);
- },
- getPublicInstance: (instance) => instance,
- hideInstance(node) {
- node.isHidden = true;
- node.yogaNode?.setDisplay(LayoutDisplay.None);
- markDirty(node);
- },
- unhideInstance(node) {
- node.isHidden = false;
- node.yogaNode?.setDisplay(LayoutDisplay.Flex);
- markDirty(node);
- },
- appendInitialChild: appendChildNode,
- appendChild: appendChildNode,
- insertBefore: insertBeforeNode,
- finalizeInitialChildren(_node, _type, props) {
- return props["autoFocus"] === true;
- },
- commitMount(node) {
- getFocusManager(node).handleAutoFocus(node);
- },
- isPrimaryRenderer: true,
- supportsMutation: true,
- supportsPersistence: false,
- supportsHydration: false,
- scheduleTimeout: setTimeout,
- cancelTimeout: clearTimeout,
- noTimeout: -1,
- getCurrentUpdatePriority: () => dispatcher.currentUpdatePriority,
- beforeActiveInstanceBlur() {},
- afterActiveInstanceBlur() {},
- detachDeletedInstance() {},
- getInstanceFromNode: () => null,
- prepareScopeUpdate() {},
- getInstanceFromScope: () => null,
- appendChildToContainer: appendChildNode,
- insertInContainerBefore: insertBeforeNode,
- removeChildFromContainer(node, removeNode) {
- removeChildNode(node, removeNode);
- cleanupYogaNode(removeNode);
- getFocusManager(node).handleNodeRemoved(removeNode, node);
- },
- commitUpdate(node, _type, oldProps, newProps) {
- const props = diff(oldProps, newProps);
- const style = diff(oldProps["style"], newProps["style"]);
- if (props) {
- for (const [key, value] of Object.entries(props)) {
- if (key === "style") {
- setStyle(node, value);
- continue;
- }
- if (key === "textStyles") {
- setTextStyles(node, value);
- continue;
- }
- if (EVENT_HANDLER_PROPS.has(key)) {
- setEventHandler(node, key, value);
- continue;
- }
- setAttribute(node, key, value);
- }
- }
- if (style && node.yogaNode) {
- styles_default(node.yogaNode, style, newProps["style"]);
- }
- },
- commitTextUpdate(node, _oldText, newText) {
- setTextNodeValue(node, newText);
- },
- removeChild(node, removeNode) {
- removeChildNode(node, removeNode);
- cleanupYogaNode(removeNode);
- if (removeNode.nodeName !== "#text") {
- const root2 = getRootNode(node);
- root2.focusManager.handleNodeRemoved(removeNode, root2);
- }
- },
- maySuspendCommit() {
- return false;
- },
- preloadInstance() {
- return true;
- },
- startSuspendingCommit() {},
- suspendInstance() {},
- waitForCommitToBeReady() {
- return null;
- },
- NotPendingTransition: null,
- HostTransitionContext: {
- $$typeof: Symbol.for("react.context"),
- _currentValue: null
- },
- setCurrentUpdatePriority(newPriority) {
- dispatcher.currentUpdatePriority = newPriority;
- },
- resolveUpdatePriority() {
- return dispatcher.resolveEventPriority();
- },
- resetFormInstance() {},
- requestPostPaintCallback() {},
- shouldAttemptEagerTransition() {
- return false;
- },
- trackSchedulerEvent() {},
- resolveEventType() {
- return dispatcher.currentEvent?.type ?? null;
- },
- resolveEventTimeStamp() {
- return dispatcher.currentEvent?.timeStamp ?? -1.1;
- }
- });
- dispatcher.discreteUpdates = reconciler.discreteUpdates.bind(reconciler);
- reconciler_default = reconciler;
-});
-
-// src/ink/layout/geometry.ts
-function unionRect(a5, b4) {
- const minX = Math.min(a5.x, b4.x);
- const minY = Math.min(a5.y, b4.y);
- const maxX = Math.max(a5.x + a5.width, b4.x + b4.width);
- const maxY = Math.max(a5.y + a5.height, b4.y + b4.height);
- return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
-}
-function clamp(value, min, max) {
- if (min !== undefined && value < min)
- return min;
- if (max !== undefined && value > max)
- return max;
- return value;
-}
-var init_geometry = () => {};
-
-// src/ink/warn.ts
-function ifNotInteger(value, name3) {
- if (value === undefined)
- return;
- if (Number.isInteger(value))
- return;
- logForDebugging(`${name3} should be an integer, got ${value}`, {
- level: "warn"
- });
-}
-var init_warn = __esm(() => {
- init_debug();
-});
-
-// src/ink/screen.ts
-class CharPool {
- strings = [" ", ""];
- stringMap = new Map([
- [" ", 0],
- ["", 1]
- ]);
- ascii = initCharAscii();
- intern(char) {
- if (char.length === 1) {
- const code = char.charCodeAt(0);
- if (code < 128) {
- const cached2 = this.ascii[code];
- if (cached2 !== -1)
- return cached2;
- const index3 = this.strings.length;
- this.strings.push(char);
- this.ascii[code] = index3;
- return index3;
- }
- }
- const existing = this.stringMap.get(char);
- if (existing !== undefined)
- return existing;
- const index2 = this.strings.length;
- this.strings.push(char);
- this.stringMap.set(char, index2);
- return index2;
- }
- get(index2) {
- return this.strings[index2] ?? " ";
- }
-}
-
-class HyperlinkPool {
- strings = [""];
- stringMap = new Map;
- intern(hyperlink) {
- if (!hyperlink)
- return 0;
- let id = this.stringMap.get(hyperlink);
- if (id === undefined) {
- id = this.strings.length;
- this.strings.push(hyperlink);
- this.stringMap.set(hyperlink, id);
- }
- return id;
- }
- get(id) {
- return id === 0 ? undefined : this.strings[id];
- }
-}
-
-class StylePool {
- ids = new Map;
- styles = [];
- transitionCache = new Map;
- none;
- constructor() {
- this.none = this.intern([]);
- }
- intern(styles5) {
- const key = styles5.length === 0 ? "" : styles5.map((s4) => s4.code).join("\x00");
- let id = this.ids.get(key);
- if (id === undefined) {
- const rawId = this.styles.length;
- this.styles.push(styles5.length === 0 ? [] : styles5);
- id = rawId << 1 | (styles5.length > 0 && hasVisibleSpaceEffect(styles5) ? 1 : 0);
- this.ids.set(key, id);
- }
- return id;
- }
- get(id) {
- return this.styles[id >>> 1] ?? [];
- }
- transition(fromId, toId) {
- if (fromId === toId)
- return "";
- const key = fromId * 1048576 + toId;
- let str = this.transitionCache.get(key);
- if (str === undefined) {
- str = ansiCodesToString(diffAnsiCodes(this.get(fromId), this.get(toId)));
- this.transitionCache.set(key, str);
- }
- return str;
- }
- inverseCache = new Map;
- withInverse(baseId) {
- let id = this.inverseCache.get(baseId);
- if (id === undefined) {
- const baseCodes = this.get(baseId);
- const hasInverse = baseCodes.some((c8) => c8.endCode === "\x1B[27m");
- id = hasInverse ? baseId : this.intern([...baseCodes, INVERSE_CODE]);
- this.inverseCache.set(baseId, id);
- }
- return id;
- }
- currentMatchCache = new Map;
- withCurrentMatch(baseId) {
- let id = this.currentMatchCache.get(baseId);
- if (id === undefined) {
- const baseCodes = this.get(baseId);
- const codes = baseCodes.filter((c8) => c8.endCode !== "\x1B[39m" && c8.endCode !== "\x1B[49m");
- codes.push(YELLOW_FG_CODE);
- if (!baseCodes.some((c8) => c8.endCode === "\x1B[27m"))
- codes.push(INVERSE_CODE);
- if (!baseCodes.some((c8) => c8.endCode === "\x1B[22m"))
- codes.push(BOLD_CODE);
- if (!baseCodes.some((c8) => c8.endCode === "\x1B[24m"))
- codes.push(UNDERLINE_CODE);
- id = this.intern(codes);
- this.currentMatchCache.set(baseId, id);
- }
- return id;
- }
- selectionBgCode = null;
- selectionBgCache = new Map;
- setSelectionBg(bg) {
- if (this.selectionBgCode?.code === bg?.code)
- return;
- this.selectionBgCode = bg;
- this.selectionBgCache.clear();
- }
- withSelectionBg(baseId) {
- const bg = this.selectionBgCode;
- if (bg === null)
- return this.withInverse(baseId);
- let id = this.selectionBgCache.get(baseId);
- if (id === undefined) {
- const kept = this.get(baseId).filter((c8) => c8.endCode !== "\x1B[49m" && c8.endCode !== "\x1B[27m");
- kept.push(bg);
- id = this.intern(kept);
- this.selectionBgCache.set(baseId, id);
- }
- return id;
- }
-}
-function hasVisibleSpaceEffect(styles5) {
- for (const style of styles5) {
- if (VISIBLE_ON_SPACE.has(style.endCode))
- return true;
- }
- return false;
-}
-function initCharAscii() {
- const table = new Int32Array(128);
- table.fill(-1);
- table[32] = EMPTY_CHAR_INDEX;
- return table;
-}
-function packWord1(styleId, hyperlinkId, width) {
- return styleId << STYLE_SHIFT | hyperlinkId << HYPERLINK_SHIFT | width;
-}
-function isEmptyCellByIndex(screen, index2) {
- const ci = index2 << 1;
- return screen.cells[ci] === 0 && screen.cells[ci | 1] === 0;
-}
-function isEmptyCellAt(screen, x3, y3) {
- if (x3 < 0 || y3 < 0 || x3 >= screen.width || y3 >= screen.height)
- return true;
- return isEmptyCellByIndex(screen, y3 * screen.width + x3);
-}
-function internHyperlink(screen, hyperlink) {
- return screen.hyperlinkPool.intern(hyperlink);
-}
-function createScreen(width, height, styles5, charPool, hyperlinkPool) {
- ifNotInteger(width, "createScreen width");
- ifNotInteger(height, "createScreen height");
- if (!Number.isInteger(width) || width < 0) {
- width = Math.max(0, Math.floor(width) || 0);
- }
- if (!Number.isInteger(height) || height < 0) {
- height = Math.max(0, Math.floor(height) || 0);
- }
- const size = width * height;
- const buf = new ArrayBuffer(size << 3);
- const cells = new Int32Array(buf);
- const cells64 = new BigInt64Array(buf);
- return {
- width,
- height,
- cells,
- cells64,
- charPool,
- hyperlinkPool,
- emptyStyleId: styles5.none,
- damage: undefined,
- noSelect: new Uint8Array(size),
- softWrap: new Int32Array(height)
- };
-}
-function resetScreen(screen, width, height) {
- ifNotInteger(width, "resetScreen width");
- ifNotInteger(height, "resetScreen height");
- if (!Number.isInteger(width) || width < 0) {
- width = Math.max(0, Math.floor(width) || 0);
- }
- if (!Number.isInteger(height) || height < 0) {
- height = Math.max(0, Math.floor(height) || 0);
- }
- const size = width * height;
- if (screen.cells64.length < size) {
- const buf = new ArrayBuffer(size << 3);
- screen.cells = new Int32Array(buf);
- screen.cells64 = new BigInt64Array(buf);
- screen.noSelect = new Uint8Array(size);
- }
- if (screen.softWrap.length < height) {
- screen.softWrap = new Int32Array(height);
- }
- screen.cells64.fill(EMPTY_CELL_VALUE, 0, size);
- screen.noSelect.fill(0, 0, size);
- screen.softWrap.fill(0, 0, height);
- screen.width = width;
- screen.height = height;
- screen.damage = undefined;
-}
-function migrateScreenPools(screen, charPool, hyperlinkPool) {
- const oldCharPool = screen.charPool;
- const oldHyperlinkPool = screen.hyperlinkPool;
- if (oldCharPool === charPool && oldHyperlinkPool === hyperlinkPool)
- return;
- const size = screen.width * screen.height;
- const cells = screen.cells;
- for (let ci = 0;ci < size << 1; ci += 2) {
- const oldCharId = cells[ci];
- cells[ci] = charPool.intern(oldCharPool.get(oldCharId));
- const word1 = cells[ci + 1];
- const oldHyperlinkId = word1 >>> HYPERLINK_SHIFT & HYPERLINK_MASK;
- if (oldHyperlinkId !== 0) {
- const oldStr = oldHyperlinkPool.get(oldHyperlinkId);
- const newHyperlinkId = hyperlinkPool.intern(oldStr);
- const styleId = word1 >>> STYLE_SHIFT;
- const width = word1 & WIDTH_MASK;
- cells[ci + 1] = packWord1(styleId, newHyperlinkId, width);
- }
- }
- screen.charPool = charPool;
- screen.hyperlinkPool = hyperlinkPool;
-}
-function cellAt(screen, x3, y3) {
- if (x3 < 0 || y3 < 0 || x3 >= screen.width || y3 >= screen.height)
- return;
- return cellAtIndex(screen, y3 * screen.width + x3);
-}
-function cellAtIndex(screen, index2) {
- const ci = index2 << 1;
- const word1 = screen.cells[ci + 1];
- const hid = word1 >>> HYPERLINK_SHIFT & HYPERLINK_MASK;
- return {
- char: screen.charPool.get(screen.cells[ci]),
- styleId: word1 >>> STYLE_SHIFT,
- width: word1 & WIDTH_MASK,
- hyperlink: hid === 0 ? undefined : screen.hyperlinkPool.get(hid)
- };
-}
-function visibleCellAtIndex(cells, charPool, hyperlinkPool, index2, lastRenderedStyleId) {
- const ci = index2 << 1;
- const charId = cells[ci];
- if (charId === 1)
- return;
- const word1 = cells[ci + 1];
- if (charId === 0 && (word1 & 262140) === 0) {
- const fgStyle = word1 >>> STYLE_SHIFT;
- if (fgStyle === 0 || fgStyle === lastRenderedStyleId)
- return;
- }
- const hid = word1 >>> HYPERLINK_SHIFT & HYPERLINK_MASK;
- return {
- char: charPool.get(charId),
- styleId: word1 >>> STYLE_SHIFT,
- width: word1 & WIDTH_MASK,
- hyperlink: hid === 0 ? undefined : hyperlinkPool.get(hid)
- };
-}
-function cellAtCI(screen, ci, out) {
- const w1 = ci | 1;
- const word1 = screen.cells[w1];
- out.char = screen.charPool.get(screen.cells[ci]);
- out.styleId = word1 >>> STYLE_SHIFT;
- out.width = word1 & WIDTH_MASK;
- const hid = word1 >>> HYPERLINK_SHIFT & HYPERLINK_MASK;
- out.hyperlink = hid === 0 ? undefined : screen.hyperlinkPool.get(hid);
-}
-function charInCellAt(screen, x3, y3) {
- if (x3 < 0 || y3 < 0 || x3 >= screen.width || y3 >= screen.height)
- return;
- const ci = y3 * screen.width + x3 << 1;
- return screen.charPool.get(screen.cells[ci]);
-}
-function setCellAt(screen, x3, y3, cell) {
- if (x3 < 0 || y3 < 0 || x3 >= screen.width || y3 >= screen.height)
- return;
- const ci = y3 * screen.width + x3 << 1;
- const cells = screen.cells;
- const prevWidth = cells[ci + 1] & WIDTH_MASK;
- if (prevWidth === 1 /* Wide */ && cell.width !== 1 /* Wide */) {
- const spacerX = x3 + 1;
- if (spacerX < screen.width) {
- const spacerCI = ci + 2;
- if ((cells[spacerCI + 1] & WIDTH_MASK) === 2 /* SpacerTail */) {
- cells[spacerCI] = EMPTY_CHAR_INDEX;
- cells[spacerCI + 1] = packWord1(screen.emptyStyleId, 0, 0 /* Narrow */);
- }
- }
- }
- let clearedWideX = -1;
- if (prevWidth === 2 /* SpacerTail */ && cell.width !== 2 /* SpacerTail */) {
- if (x3 > 0) {
- const wideCI = ci - 2;
- if ((cells[wideCI + 1] & WIDTH_MASK) === 1 /* Wide */) {
- cells[wideCI] = EMPTY_CHAR_INDEX;
- cells[wideCI + 1] = packWord1(screen.emptyStyleId, 0, 0 /* Narrow */);
- clearedWideX = x3 - 1;
- }
- }
- }
- cells[ci] = internCharString(screen, cell.char);
- cells[ci + 1] = packWord1(cell.styleId, internHyperlink(screen, cell.hyperlink), cell.width);
- const minX = clearedWideX >= 0 ? Math.min(x3, clearedWideX) : x3;
- const damage = screen.damage;
- if (damage) {
- const right = damage.x + damage.width;
- const bottom = damage.y + damage.height;
- if (minX < damage.x) {
- damage.width += damage.x - minX;
- damage.x = minX;
- } else if (x3 >= right) {
- damage.width = x3 - damage.x + 1;
- }
- if (y3 < damage.y) {
- damage.height += damage.y - y3;
- damage.y = y3;
- } else if (y3 >= bottom) {
- damage.height = y3 - damage.y + 1;
- }
- } else {
- screen.damage = { x: minX, y: y3, width: x3 - minX + 1, height: 1 };
- }
- if (cell.width === 1 /* Wide */) {
- const spacerX = x3 + 1;
- if (spacerX < screen.width) {
- const spacerCI = ci + 2;
- if ((cells[spacerCI + 1] & WIDTH_MASK) === 1 /* Wide */) {
- const orphanCI = spacerCI + 2;
- if (spacerX + 1 < screen.width && (cells[orphanCI + 1] & WIDTH_MASK) === 2 /* SpacerTail */) {
- cells[orphanCI] = EMPTY_CHAR_INDEX;
- cells[orphanCI + 1] = packWord1(screen.emptyStyleId, 0, 0 /* Narrow */);
- }
- }
- cells[spacerCI] = SPACER_CHAR_INDEX;
- cells[spacerCI + 1] = packWord1(screen.emptyStyleId, 0, 2 /* SpacerTail */);
- const d4 = screen.damage;
- if (d4 && spacerX >= d4.x + d4.width) {
- d4.width = spacerX - d4.x + 1;
- }
- }
- }
-}
-function setCellStyleId(screen, x3, y3, styleId) {
- if (x3 < 0 || y3 < 0 || x3 >= screen.width || y3 >= screen.height)
- return;
- const ci = y3 * screen.width + x3 << 1;
- const cells = screen.cells;
- const word1 = cells[ci + 1];
- const width = word1 & WIDTH_MASK;
- if (width === 2 /* SpacerTail */ || width === 3 /* SpacerHead */)
- return;
- const hid = word1 >>> HYPERLINK_SHIFT & HYPERLINK_MASK;
- cells[ci + 1] = packWord1(styleId, hid, width);
- const d4 = screen.damage;
- if (d4) {
- screen.damage = unionRect(d4, { x: x3, y: y3, width: 1, height: 1 });
- } else {
- screen.damage = { x: x3, y: y3, width: 1, height: 1 };
- }
-}
-function internCharString(screen, char) {
- return screen.charPool.intern(char);
-}
-function blitRegion(dst, src, regionX, regionY, maxX, maxY) {
- regionX = Math.max(0, regionX);
- regionY = Math.max(0, regionY);
- if (regionX >= maxX || regionY >= maxY)
- return;
- const rowLen = maxX - regionX;
- const srcStride = src.width << 1;
- const dstStride = dst.width << 1;
- const rowBytes = rowLen << 1;
- const srcCells = src.cells;
- const dstCells = dst.cells;
- const srcNoSel = src.noSelect;
- const dstNoSel = dst.noSelect;
- dst.softWrap.set(src.softWrap.subarray(regionY, maxY), regionY);
- if (regionX === 0 && maxX === src.width && src.width === dst.width) {
- const srcStart = regionY * srcStride;
- const totalBytes = (maxY - regionY) * srcStride;
- dstCells.set(srcCells.subarray(srcStart, srcStart + totalBytes), srcStart);
- const nsStart = regionY * src.width;
- const nsLen = (maxY - regionY) * src.width;
- dstNoSel.set(srcNoSel.subarray(nsStart, nsStart + nsLen), nsStart);
- } else {
- let srcRowCI = regionY * srcStride + (regionX << 1);
- let dstRowCI = regionY * dstStride + (regionX << 1);
- let srcRowNS = regionY * src.width + regionX;
- let dstRowNS = regionY * dst.width + regionX;
- for (let y3 = regionY;y3 < maxY; y3++) {
- dstCells.set(srcCells.subarray(srcRowCI, srcRowCI + rowBytes), dstRowCI);
- dstNoSel.set(srcNoSel.subarray(srcRowNS, srcRowNS + rowLen), dstRowNS);
- srcRowCI += srcStride;
- dstRowCI += dstStride;
- srcRowNS += src.width;
- dstRowNS += dst.width;
- }
- }
- const regionRect = {
- x: regionX,
- y: regionY,
- width: rowLen,
- height: maxY - regionY
- };
- if (dst.damage) {
- dst.damage = unionRect(dst.damage, regionRect);
- } else {
- dst.damage = regionRect;
- }
- if (maxX < dst.width) {
- let srcLastCI = regionY * src.width + (maxX - 1) << 1;
- let dstSpacerCI = regionY * dst.width + maxX << 1;
- let wroteSpacerOutsideRegion = false;
- for (let y3 = regionY;y3 < maxY; y3++) {
- if ((srcCells[srcLastCI + 1] & WIDTH_MASK) === 1 /* Wide */) {
- dstCells[dstSpacerCI] = SPACER_CHAR_INDEX;
- dstCells[dstSpacerCI + 1] = packWord1(dst.emptyStyleId, 0, 2 /* SpacerTail */);
- wroteSpacerOutsideRegion = true;
- }
- srcLastCI += srcStride;
- dstSpacerCI += dstStride;
- }
- if (wroteSpacerOutsideRegion && dst.damage) {
- const rightEdge = dst.damage.x + dst.damage.width;
- if (rightEdge === maxX) {
- dst.damage = { ...dst.damage, width: dst.damage.width + 1 };
- }
- }
- }
-}
-function shiftRows(screen, top, bottom, n5) {
- if (n5 === 0 || top < 0 || bottom >= screen.height || top > bottom)
- return;
- const w2 = screen.width;
- const cells64 = screen.cells64;
- const noSel = screen.noSelect;
- const sw = screen.softWrap;
- const absN = Math.abs(n5);
- if (absN > bottom - top) {
- cells64.fill(EMPTY_CELL_VALUE, top * w2, (bottom + 1) * w2);
- noSel.fill(0, top * w2, (bottom + 1) * w2);
- sw.fill(0, top, bottom + 1);
- return;
- }
- if (n5 > 0) {
- cells64.copyWithin(top * w2, (top + n5) * w2, (bottom + 1) * w2);
- noSel.copyWithin(top * w2, (top + n5) * w2, (bottom + 1) * w2);
- sw.copyWithin(top, top + n5, bottom + 1);
- cells64.fill(EMPTY_CELL_VALUE, (bottom - n5 + 1) * w2, (bottom + 1) * w2);
- noSel.fill(0, (bottom - n5 + 1) * w2, (bottom + 1) * w2);
- sw.fill(0, bottom - n5 + 1, bottom + 1);
- } else {
- cells64.copyWithin((top - n5) * w2, top * w2, (bottom + n5 + 1) * w2);
- noSel.copyWithin((top - n5) * w2, top * w2, (bottom + n5 + 1) * w2);
- sw.copyWithin(top - n5, top, bottom + n5 + 1);
- cells64.fill(EMPTY_CELL_VALUE, top * w2, (top - n5) * w2);
- noSel.fill(0, top * w2, (top - n5) * w2);
- sw.fill(0, top, top - n5);
- }
-}
-function extractHyperlinkFromStyles(styles5) {
- for (const style of styles5) {
- const code = style.code;
- if (code.length < 5 || !code.startsWith(OSC8_PREFIX))
- continue;
- const match = code.match(OSC8_REGEX);
- if (match) {
- return match[1] || null;
- }
- }
- return null;
-}
-function filterOutHyperlinkStyles(styles5) {
- return styles5.filter((style) => !style.code.startsWith(OSC8_PREFIX) || !OSC8_REGEX.test(style.code));
-}
-function diffEach(prev, next, cb) {
- const prevWidth = prev.width;
- const nextWidth = next.width;
- const prevHeight = prev.height;
- const nextHeight = next.height;
- let region;
- if (prevWidth === 0 && prevHeight === 0) {
- region = { x: 0, y: 0, width: nextWidth, height: nextHeight };
- } else if (next.damage) {
- region = next.damage;
- if (prev.damage) {
- region = unionRect(region, prev.damage);
- }
- } else if (prev.damage) {
- region = prev.damage;
- } else {
- region = { x: 0, y: 0, width: 0, height: 0 };
- }
- if (prevHeight > nextHeight) {
- region = unionRect(region, {
- x: 0,
- y: nextHeight,
- width: prevWidth,
- height: prevHeight - nextHeight
- });
- }
- if (prevWidth > nextWidth) {
- region = unionRect(region, {
- x: nextWidth,
- y: 0,
- width: prevWidth - nextWidth,
- height: prevHeight
- });
- }
- const maxHeight = Math.max(prevHeight, nextHeight);
- const maxWidth = Math.max(prevWidth, nextWidth);
- const endY = Math.min(region.y + region.height, maxHeight);
- const endX = Math.min(region.x + region.width, maxWidth);
- if (prevWidth === nextWidth) {
- return diffSameWidth(prev, next, region.x, endX, region.y, endY, cb);
- }
- return diffDifferentWidth(prev, next, region.x, endX, region.y, endY, cb);
-}
-function findNextDiff(a5, b4, w0, count3) {
- for (let i5 = 0;i5 < count3; i5++, w0 += 2) {
- const w1 = w0 | 1;
- if (a5[w0] !== b4[w0] || a5[w1] !== b4[w1])
- return i5;
- }
- return count3;
-}
-function diffRowBoth(prevCells, nextCells, prev, next, ci, y3, startX, endX, prevCell, nextCell, cb) {
- let x3 = startX;
- while (x3 < endX) {
- const skip = findNextDiff(prevCells, nextCells, ci, endX - x3);
- x3 += skip;
- ci += skip << 1;
- if (x3 >= endX)
- break;
- cellAtCI(prev, ci, prevCell);
- cellAtCI(next, ci, nextCell);
- if (cb(x3, y3, prevCell, nextCell))
- return true;
- x3++;
- ci += 2;
- }
- return false;
-}
-function diffRowRemoved(prev, ci, y3, startX, endX, prevCell, cb) {
- for (let x3 = startX;x3 < endX; x3++, ci += 2) {
- cellAtCI(prev, ci, prevCell);
- if (cb(x3, y3, prevCell, undefined))
- return true;
- }
- return false;
-}
-function diffRowAdded(nextCells, next, ci, y3, startX, endX, nextCell, cb) {
- for (let x3 = startX;x3 < endX; x3++, ci += 2) {
- if (nextCells[ci] === 0 && nextCells[ci | 1] === 0)
- continue;
- cellAtCI(next, ci, nextCell);
- if (cb(x3, y3, undefined, nextCell))
- return true;
- }
- return false;
-}
-function diffSameWidth(prev, next, startX, endX, startY, endY, cb) {
- const prevCells = prev.cells;
- const nextCells = next.cells;
- const width = prev.width;
- const prevHeight = prev.height;
- const nextHeight = next.height;
- const stride = width << 1;
- const prevCell = {
- char: " ",
- styleId: 0,
- width: 0 /* Narrow */,
- hyperlink: undefined
- };
- const nextCell = {
- char: " ",
- styleId: 0,
- width: 0 /* Narrow */,
- hyperlink: undefined
- };
- const rowEndX = Math.min(endX, width);
- let rowCI = startY * width + startX << 1;
- for (let y3 = startY;y3 < endY; y3++) {
- const prevIn = y3 < prevHeight;
- const nextIn = y3 < nextHeight;
- if (prevIn && nextIn) {
- if (diffRowBoth(prevCells, nextCells, prev, next, rowCI, y3, startX, rowEndX, prevCell, nextCell, cb))
- return true;
- } else if (prevIn) {
- if (diffRowRemoved(prev, rowCI, y3, startX, rowEndX, prevCell, cb))
- return true;
- } else if (nextIn) {
- if (diffRowAdded(nextCells, next, rowCI, y3, startX, rowEndX, nextCell, cb))
- return true;
- }
- rowCI += stride;
- }
- return false;
-}
-function diffDifferentWidth(prev, next, startX, endX, startY, endY, cb) {
- const prevWidth = prev.width;
- const nextWidth = next.width;
- const prevCells = prev.cells;
- const nextCells = next.cells;
- const prevCell = {
- char: " ",
- styleId: 0,
- width: 0 /* Narrow */,
- hyperlink: undefined
- };
- const nextCell = {
- char: " ",
- styleId: 0,
- width: 0 /* Narrow */,
- hyperlink: undefined
- };
- const prevStride = prevWidth << 1;
- const nextStride = nextWidth << 1;
- let prevRowCI = startY * prevWidth + startX << 1;
- let nextRowCI = startY * nextWidth + startX << 1;
- for (let y3 = startY;y3 < endY; y3++) {
- const prevIn = y3 < prev.height;
- const nextIn = y3 < next.height;
- const prevEndX = prevIn ? Math.min(endX, prevWidth) : startX;
- const nextEndX = nextIn ? Math.min(endX, nextWidth) : startX;
- const bothEndX = Math.min(prevEndX, nextEndX);
- let prevCI = prevRowCI;
- let nextCI = nextRowCI;
- for (let x3 = startX;x3 < bothEndX; x3++) {
- if (prevCells[prevCI] === nextCells[nextCI] && prevCells[prevCI + 1] === nextCells[nextCI + 1]) {
- prevCI += 2;
- nextCI += 2;
- continue;
- }
- cellAtCI(prev, prevCI, prevCell);
- cellAtCI(next, nextCI, nextCell);
- prevCI += 2;
- nextCI += 2;
- if (cb(x3, y3, prevCell, nextCell))
- return true;
- }
- if (prevEndX > bothEndX) {
- prevCI = prevRowCI + (bothEndX - startX << 1);
- for (let x3 = bothEndX;x3 < prevEndX; x3++) {
- cellAtCI(prev, prevCI, prevCell);
- prevCI += 2;
- if (cb(x3, y3, prevCell, undefined))
- return true;
- }
- }
- if (nextEndX > bothEndX) {
- nextCI = nextRowCI + (bothEndX - startX << 1);
- for (let x3 = bothEndX;x3 < nextEndX; x3++) {
- if (nextCells[nextCI] === 0 && nextCells[nextCI | 1] === 0) {
- nextCI += 2;
- continue;
- }
- cellAtCI(next, nextCI, nextCell);
- nextCI += 2;
- if (cb(x3, y3, undefined, nextCell))
- return true;
- }
- }
- prevRowCI += prevStride;
- nextRowCI += nextStride;
- }
- return false;
-}
-function markNoSelectRegion(screen, x3, y3, width, height) {
- const maxX = Math.min(x3 + width, screen.width);
- const maxY = Math.min(y3 + height, screen.height);
- const noSel = screen.noSelect;
- const stride = screen.width;
- for (let row = Math.max(0, y3);row < maxY; row++) {
- const rowStart = row * stride;
- noSel.fill(1, rowStart + Math.max(0, x3), rowStart + maxX);
- }
-}
-var INVERSE_CODE, BOLD_CODE, UNDERLINE_CODE, YELLOW_FG_CODE, VISIBLE_ON_SPACE, EMPTY_CHAR_INDEX = 0, SPACER_CHAR_INDEX = 1, STYLE_SHIFT = 17, HYPERLINK_SHIFT = 2, HYPERLINK_MASK = 32767, WIDTH_MASK = 3, EMPTY_CELL_VALUE = 0n, OSC8_REGEX, OSC8_PREFIX;
-var init_screen = __esm(() => {
- init_build();
- init_geometry();
- init_ansi();
- init_warn();
- INVERSE_CODE = {
- type: "ansi",
- code: "\x1B[7m",
- endCode: "\x1B[27m"
- };
- BOLD_CODE = {
- type: "ansi",
- code: "\x1B[1m",
- endCode: "\x1B[22m"
- };
- UNDERLINE_CODE = {
- type: "ansi",
- code: "\x1B[4m",
- endCode: "\x1B[24m"
- };
- YELLOW_FG_CODE = {
- type: "ansi",
- code: "\x1B[33m",
- endCode: "\x1B[39m"
- };
- VISIBLE_ON_SPACE = new Set([
- "\x1B[49m",
- "\x1B[27m",
- "\x1B[24m",
- "\x1B[29m",
- "\x1B[55m"
- ]);
- OSC8_REGEX = new RegExp(`^${ESC}\\]8${SEP}${SEP}([^${BEL}]*)${BEL}$`);
- OSC8_PREFIX = `${ESC}]8${SEP}`;
-});
-
-// src/ink/selection.ts
-function createSelectionState() {
- return {
- anchor: null,
- focus: null,
- isDragging: false,
- anchorSpan: null,
- scrolledOffAbove: [],
- scrolledOffBelow: [],
- scrolledOffAboveSW: [],
- scrolledOffBelowSW: [],
- lastPressHadAlt: false
- };
-}
-function startSelection(s4, col, row) {
- s4.anchor = { col, row };
- s4.focus = null;
- s4.isDragging = true;
- s4.anchorSpan = null;
- s4.scrolledOffAbove = [];
- s4.scrolledOffBelow = [];
- s4.scrolledOffAboveSW = [];
- s4.scrolledOffBelowSW = [];
- s4.virtualAnchorRow = undefined;
- s4.virtualFocusRow = undefined;
- s4.lastPressHadAlt = false;
-}
-function updateSelection(s4, col, row) {
- if (!s4.isDragging)
- return;
- if (!s4.focus && s4.anchor && s4.anchor.col === col && s4.anchor.row === row)
- return;
- s4.focus = { col, row };
-}
-function finishSelection(s4) {
- s4.isDragging = false;
-}
-function clearSelection(s4) {
- s4.anchor = null;
- s4.focus = null;
- s4.isDragging = false;
- s4.anchorSpan = null;
- s4.scrolledOffAbove = [];
- s4.scrolledOffBelow = [];
- s4.scrolledOffAboveSW = [];
- s4.scrolledOffBelowSW = [];
- s4.virtualAnchorRow = undefined;
- s4.virtualFocusRow = undefined;
- s4.lastPressHadAlt = false;
-}
-function charClass(c8) {
- if (c8 === " " || c8 === "")
- return 0;
- if (WORD_CHAR.test(c8))
- return 1;
- return 2;
-}
-function wordBoundsAt(screen, col, row) {
- if (row < 0 || row >= screen.height)
- return null;
- const width = screen.width;
- const noSelect = screen.noSelect;
- const rowOff = row * width;
- let c8 = col;
- if (c8 > 0) {
- const cell = cellAt(screen, c8, row);
- if (cell && cell.width === 2 /* SpacerTail */)
- c8 -= 1;
- }
- if (c8 < 0 || c8 >= width || noSelect[rowOff + c8] === 1)
- return null;
- const startCell = cellAt(screen, c8, row);
- if (!startCell)
- return null;
- const cls = charClass(startCell.char);
- let lo = c8;
- while (lo > 0) {
- const prev = lo - 1;
- if (noSelect[rowOff + prev] === 1)
- break;
- const pc = cellAt(screen, prev, row);
- if (!pc)
- break;
- if (pc.width === 2 /* SpacerTail */) {
- if (prev === 0 || noSelect[rowOff + prev - 1] === 1)
- break;
- const head = cellAt(screen, prev - 1, row);
- if (!head || charClass(head.char) !== cls)
- break;
- lo = prev - 1;
- continue;
- }
- if (charClass(pc.char) !== cls)
- break;
- lo = prev;
- }
- let hi = c8;
- while (hi < width - 1) {
- const next = hi + 1;
- if (noSelect[rowOff + next] === 1)
- break;
- const nc = cellAt(screen, next, row);
- if (!nc)
- break;
- if (nc.width === 2 /* SpacerTail */) {
- hi = next;
- continue;
- }
- if (charClass(nc.char) !== cls)
- break;
- hi = next;
- }
- return { lo, hi };
-}
-function comparePoints(a5, b4) {
- if (a5.row !== b4.row)
- return a5.row < b4.row ? -1 : 1;
- if (a5.col !== b4.col)
- return a5.col < b4.col ? -1 : 1;
- return 0;
-}
-function selectWordAt(s4, screen, col, row) {
- const b4 = wordBoundsAt(screen, col, row);
- if (!b4)
- return;
- const lo = { col: b4.lo, row };
- const hi = { col: b4.hi, row };
- s4.anchor = lo;
- s4.focus = hi;
- s4.isDragging = true;
- s4.anchorSpan = { lo, hi, kind: "word" };
-}
-function isUrlChar(c8) {
- if (c8.length !== 1)
- return false;
- const code = c8.charCodeAt(0);
- return code >= 33 && code <= 126 && !URL_BOUNDARY.has(c8);
-}
-function findPlainTextUrlAt(screen, col, row) {
- if (row < 0 || row >= screen.height)
- return;
- const width = screen.width;
- const noSelect = screen.noSelect;
- const rowOff = row * width;
- let c8 = col;
- if (c8 > 0) {
- const cell = cellAt(screen, c8, row);
- if (cell && cell.width === 2 /* SpacerTail */)
- c8 -= 1;
- }
- if (c8 < 0 || c8 >= width || noSelect[rowOff + c8] === 1)
- return;
- const startCell = cellAt(screen, c8, row);
- if (!startCell || !isUrlChar(startCell.char))
- return;
- let lo = c8;
- while (lo > 0) {
- const prev = lo - 1;
- if (noSelect[rowOff + prev] === 1)
- break;
- const pc = cellAt(screen, prev, row);
- if (!pc || pc.width !== 0 /* Narrow */ || !isUrlChar(pc.char))
- break;
- lo = prev;
- }
- let hi = c8;
- while (hi < width - 1) {
- const next = hi + 1;
- if (noSelect[rowOff + next] === 1)
- break;
- const nc = cellAt(screen, next, row);
- if (!nc || nc.width !== 0 /* Narrow */ || !isUrlChar(nc.char))
- break;
- hi = next;
- }
- let token = "";
- for (let i5 = lo;i5 <= hi; i5++)
- token += cellAt(screen, i5, row).char;
- const clickIdx = c8 - lo;
- const schemeRe = /(?:https?|file):\/\//g;
- let urlStart = -1;
- let urlEnd = token.length;
- for (let m4;m4 = schemeRe.exec(token); ) {
- if (m4.index > clickIdx) {
- urlEnd = m4.index;
- break;
- }
- urlStart = m4.index;
- }
- if (urlStart < 0)
- return;
- let url3 = token.slice(urlStart, urlEnd);
- const OPENER = { ")": "(", "]": "[", "}": "{" };
- while (url3.length > 0) {
- const last = url3.at(-1);
- if (".,;:!?".includes(last)) {
- url3 = url3.slice(0, -1);
- continue;
- }
- const opener = OPENER[last];
- if (!opener)
- break;
- let opens = 0;
- let closes = 0;
- for (let i5 = 0;i5 < url3.length; i5++) {
- const ch = url3.charAt(i5);
- if (ch === opener)
- opens++;
- else if (ch === last)
- closes++;
- }
- if (closes > opens)
- url3 = url3.slice(0, -1);
- else
- break;
- }
- if (clickIdx >= urlStart + url3.length)
- return;
- return url3;
-}
-function selectLineAt(s4, screen, row) {
- if (row < 0 || row >= screen.height)
- return;
- const lo = { col: 0, row };
- const hi = { col: screen.width - 1, row };
- s4.anchor = lo;
- s4.focus = hi;
- s4.isDragging = true;
- s4.anchorSpan = { lo, hi, kind: "line" };
-}
-function extendSelection(s4, screen, col, row) {
- if (!s4.isDragging || !s4.anchorSpan)
- return;
- const span = s4.anchorSpan;
- let mLo;
- let mHi;
- if (span.kind === "word") {
- const b4 = wordBoundsAt(screen, col, row);
- mLo = { col: b4 ? b4.lo : col, row };
- mHi = { col: b4 ? b4.hi : col, row };
- } else {
- const r4 = clamp(row, 0, screen.height - 1);
- mLo = { col: 0, row: r4 };
- mHi = { col: screen.width - 1, row: r4 };
- }
- if (comparePoints(mHi, span.lo) < 0) {
- s4.anchor = span.hi;
- s4.focus = mLo;
- } else if (comparePoints(mLo, span.hi) > 0) {
- s4.anchor = span.lo;
- s4.focus = mHi;
- } else {
- s4.anchor = span.lo;
- s4.focus = span.hi;
- }
-}
-function moveFocus(s4, col, row) {
- if (!s4.focus)
- return;
- s4.anchorSpan = null;
- s4.focus = { col, row };
- s4.virtualFocusRow = undefined;
-}
-function shiftSelection(s4, dRow, minRow, maxRow, width) {
- if (!s4.anchor || !s4.focus)
- return;
- const vAnchor = (s4.virtualAnchorRow ?? s4.anchor.row) + dRow;
- const vFocus = (s4.virtualFocusRow ?? s4.focus.row) + dRow;
- if (vAnchor < minRow && vFocus < minRow || vAnchor > maxRow && vFocus > maxRow) {
- clearSelection(s4);
- return;
- }
- const oldMin = Math.min(s4.virtualAnchorRow ?? s4.anchor.row, s4.virtualFocusRow ?? s4.focus.row);
- const oldMax = Math.max(s4.virtualAnchorRow ?? s4.anchor.row, s4.virtualFocusRow ?? s4.focus.row);
- const oldAboveDebt = Math.max(0, minRow - oldMin);
- const oldBelowDebt = Math.max(0, oldMax - maxRow);
- const newAboveDebt = Math.max(0, minRow - Math.min(vAnchor, vFocus));
- const newBelowDebt = Math.max(0, Math.max(vAnchor, vFocus) - maxRow);
- if (newAboveDebt < oldAboveDebt) {
- const drop = oldAboveDebt - newAboveDebt;
- s4.scrolledOffAbove.length -= drop;
- s4.scrolledOffAboveSW.length = s4.scrolledOffAbove.length;
- }
- if (newBelowDebt < oldBelowDebt) {
- const drop = oldBelowDebt - newBelowDebt;
- s4.scrolledOffBelow.splice(0, drop);
- s4.scrolledOffBelowSW.splice(0, drop);
- }
- if (s4.scrolledOffAbove.length > newAboveDebt) {
- s4.scrolledOffAbove = newAboveDebt > 0 ? s4.scrolledOffAbove.slice(-newAboveDebt) : [];
- s4.scrolledOffAboveSW = newAboveDebt > 0 ? s4.scrolledOffAboveSW.slice(-newAboveDebt) : [];
- }
- if (s4.scrolledOffBelow.length > newBelowDebt) {
- s4.scrolledOffBelow = s4.scrolledOffBelow.slice(0, newBelowDebt);
- s4.scrolledOffBelowSW = s4.scrolledOffBelowSW.slice(0, newBelowDebt);
- }
- const shift = (p4, vRow) => {
- if (vRow < minRow)
- return { col: 0, row: minRow };
- if (vRow > maxRow)
- return { col: width - 1, row: maxRow };
- return { col: p4.col, row: vRow };
- };
- s4.anchor = shift(s4.anchor, vAnchor);
- s4.focus = shift(s4.focus, vFocus);
- s4.virtualAnchorRow = vAnchor < minRow || vAnchor > maxRow ? vAnchor : undefined;
- s4.virtualFocusRow = vFocus < minRow || vFocus > maxRow ? vFocus : undefined;
- if (s4.anchorSpan) {
- const sp = (p4) => {
- const r4 = p4.row + dRow;
- if (r4 < minRow)
- return { col: 0, row: minRow };
- if (r4 > maxRow)
- return { col: width - 1, row: maxRow };
- return { col: p4.col, row: r4 };
- };
- s4.anchorSpan = {
- lo: sp(s4.anchorSpan.lo),
- hi: sp(s4.anchorSpan.hi),
- kind: s4.anchorSpan.kind
- };
- }
-}
-function shiftAnchor(s4, dRow, minRow, maxRow) {
- if (!s4.anchor)
- return;
- const raw = (s4.virtualAnchorRow ?? s4.anchor.row) + dRow;
- s4.anchor = { col: s4.anchor.col, row: clamp(raw, minRow, maxRow) };
- s4.virtualAnchorRow = raw < minRow || raw > maxRow ? raw : undefined;
- if (s4.anchorSpan) {
- const shift = (p4) => ({
- col: p4.col,
- row: clamp(p4.row + dRow, minRow, maxRow)
- });
- s4.anchorSpan = {
- lo: shift(s4.anchorSpan.lo),
- hi: shift(s4.anchorSpan.hi),
- kind: s4.anchorSpan.kind
- };
- }
-}
-function shiftSelectionForFollow(s4, dRow, minRow, maxRow) {
- if (!s4.anchor)
- return false;
- const rawAnchor = (s4.virtualAnchorRow ?? s4.anchor.row) + dRow;
- const rawFocus = s4.focus ? (s4.virtualFocusRow ?? s4.focus.row) + dRow : undefined;
- if (rawAnchor < minRow && rawFocus !== undefined && rawFocus < minRow) {
- clearSelection(s4);
- return true;
- }
- s4.anchor = { col: s4.anchor.col, row: clamp(rawAnchor, minRow, maxRow) };
- if (s4.focus && rawFocus !== undefined) {
- s4.focus = { col: s4.focus.col, row: clamp(rawFocus, minRow, maxRow) };
- }
- s4.virtualAnchorRow = rawAnchor < minRow || rawAnchor > maxRow ? rawAnchor : undefined;
- s4.virtualFocusRow = rawFocus !== undefined && (rawFocus < minRow || rawFocus > maxRow) ? rawFocus : undefined;
- if (s4.anchorSpan) {
- const shift = (p4) => ({
- col: p4.col,
- row: clamp(p4.row + dRow, minRow, maxRow)
- });
- s4.anchorSpan = {
- lo: shift(s4.anchorSpan.lo),
- hi: shift(s4.anchorSpan.hi),
- kind: s4.anchorSpan.kind
- };
- }
- return false;
-}
-function hasSelection(s4) {
- return s4.anchor !== null && s4.focus !== null;
-}
-function selectionBounds(s4) {
- if (!s4.anchor || !s4.focus)
- return null;
- return comparePoints(s4.anchor, s4.focus) <= 0 ? { start: s4.anchor, end: s4.focus } : { start: s4.focus, end: s4.anchor };
-}
-function extractRowText(screen, row, colStart, colEnd) {
- const noSelect = screen.noSelect;
- const rowOff = row * screen.width;
- const contentEnd = row + 1 < screen.height ? screen.softWrap[row + 1] : 0;
- const lastCol = contentEnd > 0 ? Math.min(colEnd, contentEnd - 1) : colEnd;
- let line = "";
- for (let col = colStart;col <= lastCol; col++) {
- if (noSelect[rowOff + col] === 1)
- continue;
- const cell = cellAt(screen, col, row);
- if (!cell)
- continue;
- if (cell.width === 2 /* SpacerTail */ || cell.width === 3 /* SpacerHead */) {
- continue;
- }
- line += cell.char;
- }
- return contentEnd > 0 ? line : line.replace(/\s+$/, "");
-}
-function joinRows(lines, text, sw) {
- if (sw && lines.length > 0) {
- lines[lines.length - 1] += text;
- } else {
- lines.push(text);
- }
-}
-function getSelectedText(s4, screen) {
- const b4 = selectionBounds(s4);
- if (!b4)
- return "";
- const { start, end } = b4;
- const sw = screen.softWrap;
- const lines = [];
- for (let i5 = 0;i5 < s4.scrolledOffAbove.length; i5++) {
- joinRows(lines, s4.scrolledOffAbove[i5], s4.scrolledOffAboveSW[i5]);
- }
- for (let row = start.row;row <= end.row; row++) {
- const rowStart = row === start.row ? start.col : 0;
- const rowEnd = row === end.row ? end.col : screen.width - 1;
- joinRows(lines, extractRowText(screen, row, rowStart, rowEnd), sw[row] > 0);
- }
- for (let i5 = 0;i5 < s4.scrolledOffBelow.length; i5++) {
- joinRows(lines, s4.scrolledOffBelow[i5], s4.scrolledOffBelowSW[i5]);
- }
- return lines.join(`
-`);
-}
-function captureScrolledRows(s4, screen, firstRow, lastRow, side) {
- const b4 = selectionBounds(s4);
- if (!b4 || firstRow > lastRow)
- return;
- const { start, end } = b4;
- const lo = Math.max(firstRow, start.row);
- const hi = Math.min(lastRow, end.row);
- if (lo > hi)
- return;
- const width = screen.width;
- const sw = screen.softWrap;
- const captured = [];
- const capturedSW = [];
- for (let row = lo;row <= hi; row++) {
- const colStart = row === start.row ? start.col : 0;
- const colEnd = row === end.row ? end.col : width - 1;
- captured.push(extractRowText(screen, row, colStart, colEnd));
- capturedSW.push(sw[row] > 0);
- }
- if (side === "above") {
- s4.scrolledOffAbove.push(...captured);
- s4.scrolledOffAboveSW.push(...capturedSW);
- if (s4.anchor && s4.anchor.row === start.row && lo === start.row) {
- s4.anchor = { col: 0, row: s4.anchor.row };
- if (s4.anchorSpan) {
- s4.anchorSpan = {
- kind: s4.anchorSpan.kind,
- lo: { col: 0, row: s4.anchorSpan.lo.row },
- hi: { col: width - 1, row: s4.anchorSpan.hi.row }
- };
- }
- }
- } else {
- s4.scrolledOffBelow.unshift(...captured);
- s4.scrolledOffBelowSW.unshift(...capturedSW);
- if (s4.anchor && s4.anchor.row === end.row && hi === end.row) {
- s4.anchor = { col: width - 1, row: s4.anchor.row };
- if (s4.anchorSpan) {
- s4.anchorSpan = {
- kind: s4.anchorSpan.kind,
- lo: { col: 0, row: s4.anchorSpan.lo.row },
- hi: { col: width - 1, row: s4.anchorSpan.hi.row }
- };
- }
- }
- }
-}
-function applySelectionOverlay(screen, selection, stylePool) {
- const b4 = selectionBounds(selection);
- if (!b4)
- return;
- const { start, end } = b4;
- const width = screen.width;
- const noSelect = screen.noSelect;
- for (let row = start.row;row <= end.row && row < screen.height; row++) {
- const colStart = row === start.row ? start.col : 0;
- const colEnd = row === end.row ? Math.min(end.col, width - 1) : width - 1;
- const rowOff = row * width;
- for (let col = colStart;col <= colEnd; col++) {
- const idx = rowOff + col;
- if (noSelect[idx] === 1)
- continue;
- const cell = cellAtIndex(screen, idx);
- setCellStyleId(screen, col, row, stylePool.withSelectionBg(cell.styleId));
- }
- }
-}
-var WORD_CHAR, URL_BOUNDARY;
-var init_selection = __esm(() => {
- init_geometry();
- init_screen();
- WORD_CHAR = /[\p{L}\p{N}_/.\-+~\\]/u;
- URL_BOUNDARY = new Set([..."<>\"'` "]);
-});
-
-// src/utils/semver.ts
-function getNpmSemver() {
- if (!_npmSemver) {
- _npmSemver = require_semver2();
- }
- return _npmSemver;
-}
-function gt(a5, b4) {
- if (typeof Bun !== "undefined") {
- return Bun.semver.order(a5, b4) === 1;
- }
- return getNpmSemver().gt(a5, b4, { loose: true });
-}
-function gte(a5, b4) {
- if (typeof Bun !== "undefined") {
- return Bun.semver.order(a5, b4) >= 0;
- }
- return getNpmSemver().gte(a5, b4, { loose: true });
-}
-function lt(a5, b4) {
- if (typeof Bun !== "undefined") {
- return Bun.semver.order(a5, b4) === -1;
- }
- return getNpmSemver().lt(a5, b4, { loose: true });
-}
-function satisfies(version6, range) {
- if (typeof Bun !== "undefined") {
- return Bun.semver.satisfies(version6, range);
- }
- return getNpmSemver().satisfies(version6, range, { loose: true });
-}
-var _npmSemver;
-
-// src/ink/clearTerminal.ts
-function isWindowsTerminal() {
- return process.platform === "win32" && !!process.env.WT_SESSION;
-}
-function isMintty() {
- if (process.env.TERM_PROGRAM === "mintty") {
- return true;
- }
- if (process.platform === "win32" && process.env.MSYSTEM) {
- return true;
- }
- return false;
-}
-function isModernWindowsTerminal() {
- if (isWindowsTerminal()) {
- return true;
- }
- if (process.platform === "win32" && process.env.TERM_PROGRAM === "vscode" && process.env.TERM_PROGRAM_VERSION) {
- return true;
- }
- if (isMintty()) {
- return true;
- }
- return false;
-}
-function getClearTerminalSequence() {
- if (process.platform === "win32") {
- if (isModernWindowsTerminal()) {
- return ERASE_SCREEN + ERASE_SCROLLBACK + CURSOR_HOME;
- } else {
- return ERASE_SCREEN + CURSOR_HOME_WINDOWS;
- }
- }
- return ERASE_SCREEN + ERASE_SCROLLBACK + CURSOR_HOME;
-}
-var CURSOR_HOME_WINDOWS, clearTerminal;
-var init_clearTerminal = __esm(() => {
- init_csi();
- CURSOR_HOME_WINDOWS = csi(0, "f");
- clearTerminal = getClearTerminalSequence();
-});
-
-// src/ink/termio/dec.ts
-function decset(mode) {
- return csi(`?${mode}h`);
-}
-function decreset(mode) {
- return csi(`?${mode}l`);
-}
-var DEC, BSU, ESU, EBP, DBP, EFE, DFE, SHOW_CURSOR, HIDE_CURSOR, ENTER_ALT_SCREEN, EXIT_ALT_SCREEN, ENABLE_MOUSE_TRACKING, DISABLE_MOUSE_TRACKING;
-var init_dec = __esm(() => {
- init_csi();
- DEC = {
- CURSOR_VISIBLE: 25,
- ALT_SCREEN: 47,
- ALT_SCREEN_CLEAR: 1049,
- MOUSE_NORMAL: 1000,
- MOUSE_BUTTON: 1002,
- MOUSE_ANY: 1003,
- MOUSE_SGR: 1006,
- FOCUS_EVENTS: 1004,
- BRACKETED_PASTE: 2004,
- SYNCHRONIZED_UPDATE: 2026
- };
- BSU = decset(DEC.SYNCHRONIZED_UPDATE);
- ESU = decreset(DEC.SYNCHRONIZED_UPDATE);
- EBP = decset(DEC.BRACKETED_PASTE);
- DBP = decreset(DEC.BRACKETED_PASTE);
- EFE = decset(DEC.FOCUS_EVENTS);
- DFE = decreset(DEC.FOCUS_EVENTS);
- SHOW_CURSOR = decset(DEC.CURSOR_VISIBLE);
- HIDE_CURSOR = decreset(DEC.CURSOR_VISIBLE);
- ENTER_ALT_SCREEN = decset(DEC.ALT_SCREEN_CLEAR);
- EXIT_ALT_SCREEN = decreset(DEC.ALT_SCREEN_CLEAR);
- ENABLE_MOUSE_TRACKING = decset(DEC.MOUSE_NORMAL) + decset(DEC.MOUSE_BUTTON) + decset(DEC.MOUSE_ANY) + decset(DEC.MOUSE_SGR);
- DISABLE_MOUSE_TRACKING = decreset(DEC.MOUSE_SGR) + decreset(DEC.MOUSE_ANY) + decreset(DEC.MOUSE_BUTTON) + decreset(DEC.MOUSE_NORMAL);
-});
-
-// src/ink/termio/osc.ts
-import { Buffer as Buffer15 } from "buffer";
-function osc(...parts) {
- const terminator = env2.terminal === "kitty" ? ST : BEL;
- return `${OSC_PREFIX}${parts.join(SEP)}${terminator}`;
-}
-function wrapForMultiplexer(sequence) {
- if (process.env["TMUX"]) {
- const escaped = sequence.replaceAll("\x1B", "\x1B\x1B");
- return `\x1BPtmux;${escaped}\x1B\\`;
- }
- if (process.env["STY"]) {
- return `\x1BP${sequence}\x1B\\`;
- }
- return sequence;
-}
-function getClipboardPath() {
- const nativeAvailable = process.platform === "darwin" && !process.env["SSH_CONNECTION"];
- if (nativeAvailable)
- return "native";
- if (process.env["TMUX"])
- return "tmux-buffer";
- return "osc52";
-}
-function tmuxPassthrough(payload) {
- return `${ESC}Ptmux;${payload.replaceAll(ESC, ESC + ESC)}${ST}`;
-}
-async function tmuxLoadBuffer(text) {
- if (!process.env["TMUX"])
- return false;
- const args = process.env["LC_TERMINAL"] === "iTerm2" ? ["load-buffer", "-"] : ["load-buffer", "-w", "-"];
- const { code } = await execFileNoThrow("tmux", args, {
- input: text,
- useCwd: false,
- timeout: 2000
- });
- return code === 0;
-}
-async function setClipboard(text) {
- const b64 = Buffer15.from(text, "utf8").toString("base64");
- const raw = osc(OSC.CLIPBOARD, "c", b64);
- if (!process.env["SSH_CONNECTION"])
- copyNative(text);
- const tmuxBufferLoaded = await tmuxLoadBuffer(text);
- if (tmuxBufferLoaded)
- return tmuxPassthrough(`${ESC}]52;c;${b64}${BEL}`);
- return raw;
-}
-function copyNative(text) {
- const opts = { input: text, useCwd: false, timeout: 2000 };
- switch (process.platform) {
- case "darwin":
- execFileNoThrow("pbcopy", [], opts);
- return;
- case "linux": {
- if (linuxCopy === null)
- return;
- if (linuxCopy === "wl-copy") {
- execFileNoThrow("wl-copy", [], opts);
- return;
- }
- if (linuxCopy === "xclip") {
- execFileNoThrow("xclip", ["-selection", "clipboard"], opts);
- return;
- }
- if (linuxCopy === "xsel") {
- execFileNoThrow("xsel", ["--clipboard", "--input"], opts);
- return;
- }
- execFileNoThrow("wl-copy", [], opts).then((r4) => {
- if (r4.code === 0) {
- linuxCopy = "wl-copy";
- return;
- }
- execFileNoThrow("xclip", ["-selection", "clipboard"], opts).then((r22) => {
- if (r22.code === 0) {
- linuxCopy = "xclip";
- return;
- }
- execFileNoThrow("xsel", ["--clipboard", "--input"], opts).then((r32) => {
- linuxCopy = r32.code === 0 ? "xsel" : null;
- });
- });
- });
- return;
- }
- case "win32":
- execFileNoThrow("clip", [], opts);
- return;
- }
-}
-function parseOSC(content) {
- const semicolonIdx = content.indexOf(";");
- const command12 = semicolonIdx >= 0 ? content.slice(0, semicolonIdx) : content;
- const data = semicolonIdx >= 0 ? content.slice(semicolonIdx + 1) : "";
- const commandNum = parseInt(command12, 10);
- if (commandNum === OSC.SET_TITLE_AND_ICON) {
- return { type: "title", action: { type: "both", title: data } };
- }
- if (commandNum === OSC.SET_ICON) {
- return { type: "title", action: { type: "iconName", name: data } };
- }
- if (commandNum === OSC.SET_TITLE) {
- return { type: "title", action: { type: "windowTitle", title: data } };
- }
- if (commandNum === OSC.HYPERLINK) {
- const parts = data.split(";");
- const paramsStr = parts[0] ?? "";
- const url3 = parts.slice(1).join(";");
- if (url3 === "") {
- return { type: "link", action: { type: "end" } };
- }
- const params = {};
- if (paramsStr) {
- for (const pair of paramsStr.split(":")) {
- const eqIdx = pair.indexOf("=");
- if (eqIdx >= 0) {
- params[pair.slice(0, eqIdx)] = pair.slice(eqIdx + 1);
- }
- }
- }
- return {
- type: "link",
- action: {
- type: "start",
- url: url3,
- params: Object.keys(params).length > 0 ? params : undefined
- }
- };
- }
- if (commandNum === OSC.TAB_STATUS) {
- return { type: "tabStatus", action: parseTabStatus(data) };
- }
- return { type: "unknown", sequence: `\x1B]${content}` };
-}
-function parseOscColor(spec) {
- const hex = spec.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex) {
- return {
- type: "rgb",
- r: parseInt(hex[1], 16),
- g: parseInt(hex[2], 16),
- b: parseInt(hex[3], 16)
- };
- }
- const rgb = spec.match(/^rgb:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})$/i);
- if (rgb) {
- const scale = (s4) => Math.round(parseInt(s4, 16) / (16 ** s4.length - 1) * 255);
- return {
- type: "rgb",
- r: scale(rgb[1]),
- g: scale(rgb[2]),
- b: scale(rgb[3])
- };
- }
- return null;
-}
-function parseTabStatus(data) {
- const action = {};
- for (const [key, value] of splitTabStatusPairs(data)) {
- switch (key) {
- case "indicator":
- action.indicator = value === "" ? null : parseOscColor(value);
- break;
- case "status":
- action.status = value === "" ? null : value;
- break;
- case "status-color":
- action.statusColor = value === "" ? null : parseOscColor(value);
- break;
- }
- }
- return action;
-}
-function* splitTabStatusPairs(data) {
- let key = "";
- let val = "";
- let inVal = false;
- let esc2 = false;
- for (const c8 of data) {
- if (esc2) {
- if (inVal)
- val += c8;
- else
- key += c8;
- esc2 = false;
- } else if (c8 === "\\") {
- esc2 = true;
- } else if (c8 === ";") {
- yield [key, val];
- key = "";
- val = "";
- inVal = false;
- } else if (c8 === "=" && !inVal) {
- inVal = true;
- } else if (inVal) {
- val += c8;
- } else {
- key += c8;
- }
- }
- if (key || inVal)
- yield [key, val];
-}
-function link2(url3, params) {
- if (!url3)
- return LINK_END;
- const p4 = { id: osc8Id(url3), ...params };
- const paramStr = Object.entries(p4).map(([k4, v6]) => `${k4}=${v6}`).join(":");
- return osc(OSC.HYPERLINK, paramStr, url3);
-}
-function osc8Id(url3) {
- let h5 = 0;
- for (let i5 = 0;i5 < url3.length; i5++)
- h5 = (h5 << 5) - h5 + url3.charCodeAt(i5) | 0;
- return (h5 >>> 0).toString(36);
-}
-function supportsTabStatus() {
- return process.env.USER_TYPE === "ant";
-}
-function tabStatus(fields) {
- const parts = [];
- const rgb = (c8) => c8.type === "rgb" ? `#${[c8.r, c8.g, c8.b].map((n5) => n5.toString(16).padStart(2, "0")).join("")}` : "";
- if ("indicator" in fields)
- parts.push(`indicator=${fields.indicator ? rgb(fields.indicator) : ""}`);
- if ("status" in fields)
- parts.push(`status=${fields.status?.replaceAll("\\", "\\\\").replaceAll(";", "\\;") ?? ""}`);
- if ("statusColor" in fields)
- parts.push(`status-color=${fields.statusColor ? rgb(fields.statusColor) : ""}`);
- return osc(OSC.TAB_STATUS, parts.join(";"));
-}
-var OSC_PREFIX, ST, linuxCopy, OSC, LINK_END, ITERM2, PROGRESS, CLEAR_ITERM2_PROGRESS, CLEAR_TERMINAL_TITLE, CLEAR_TAB_STATUS;
-var init_osc = __esm(() => {
- init_env();
- init_execFileNoThrow();
- init_ansi();
- OSC_PREFIX = ESC + String.fromCharCode(ESC_TYPE.OSC);
- ST = ESC + "\\";
- OSC = {
- SET_TITLE_AND_ICON: 0,
- SET_ICON: 1,
- SET_TITLE: 2,
- SET_COLOR: 4,
- SET_CWD: 7,
- HYPERLINK: 8,
- ITERM2: 9,
- SET_FG_COLOR: 10,
- SET_BG_COLOR: 11,
- SET_CURSOR_COLOR: 12,
- CLIPBOARD: 52,
- KITTY: 99,
- RESET_COLOR: 104,
- RESET_FG_COLOR: 110,
- RESET_BG_COLOR: 111,
- RESET_CURSOR_COLOR: 112,
- SEMANTIC_PROMPT: 133,
- GHOSTTY: 777,
- TAB_STATUS: 21337
- };
- LINK_END = osc(OSC.HYPERLINK, "", "");
- ITERM2 = {
- NOTIFY: 0,
- BADGE: 2,
- PROGRESS: 4
- };
- PROGRESS = {
- CLEAR: 0,
- SET: 1,
- ERROR: 2,
- INDETERMINATE: 3
- };
- CLEAR_ITERM2_PROGRESS = `${OSC_PREFIX}${OSC.ITERM2};${ITERM2.PROGRESS};${PROGRESS.CLEAR};${BEL}`;
- CLEAR_TERMINAL_TITLE = `${OSC_PREFIX}${OSC.SET_TITLE_AND_ICON};${BEL}`;
- CLEAR_TAB_STATUS = osc(OSC.TAB_STATUS, "indicator=;status=;status-color=");
-});
-
-// src/ink/terminal.ts
-function isProgressReportingAvailable() {
- if (!process.stdout.isTTY) {
- return false;
- }
- if (process.env.WT_SESSION) {
- return false;
- }
- if (process.env.ConEmuANSI || process.env.ConEmuPID || process.env.ConEmuTask) {
- return true;
- }
- const version6 = import_semver.coerce(process.env.TERM_PROGRAM_VERSION);
- if (!version6) {
- return false;
- }
- if (process.env.TERM_PROGRAM === "ghostty") {
- return gte(version6.version, "1.2.0");
- }
- if (process.env.TERM_PROGRAM === "iTerm.app") {
- return gte(version6.version, "3.6.6");
- }
- return false;
-}
-function isSynchronizedOutputSupported() {
- if (process.env.TMUX)
- return false;
- const termProgram = process.env.TERM_PROGRAM;
- const term = process.env.TERM;
- if (termProgram === "iTerm.app" || termProgram === "WezTerm" || termProgram === "WarpTerminal" || termProgram === "ghostty" || termProgram === "contour" || termProgram === "vscode" || termProgram === "alacritty") {
- return true;
- }
- if (term?.includes("kitty") || process.env.KITTY_WINDOW_ID)
- return true;
- if (term === "xterm-ghostty")
- return true;
- if (term?.startsWith("foot"))
- return true;
- if (term?.includes("alacritty"))
- return true;
- if (process.env.ZED_TERM)
- return true;
- if (process.env.WT_SESSION)
- return true;
- const vteVersion = process.env.VTE_VERSION;
- if (vteVersion) {
- const version6 = parseInt(vteVersion, 10);
- if (version6 >= 6800)
- return true;
- }
- return false;
-}
-function setXtversionName(name3) {
- if (xtversionName === undefined)
- xtversionName = name3;
-}
-function isXtermJs() {
- if (process.env.TERM_PROGRAM === "vscode")
- return true;
- return xtversionName?.startsWith("xterm.js") ?? false;
-}
-function supportsExtendedKeys() {
- return EXTENDED_KEYS_TERMINALS.includes(env2.terminal ?? "");
-}
-function hasCursorUpViewportYankBug() {
- return process.platform === "win32" || !!process.env.WT_SESSION;
-}
-function writeDiffToTerminal(terminal, diff2, skipSyncMarkers = false) {
- if (diff2.length === 0) {
- return;
- }
- const useSync = !skipSyncMarkers;
- let buffer = useSync ? BSU : "";
- for (const patch of diff2) {
- switch (patch.type) {
- case "stdout":
- buffer += patch.content;
- break;
- case "clear":
- if (patch.count > 0) {
- buffer += eraseLines(patch.count);
- }
- break;
- case "clearTerminal":
- buffer += getClearTerminalSequence();
- break;
- case "cursorHide":
- buffer += HIDE_CURSOR;
- break;
- case "cursorShow":
- buffer += SHOW_CURSOR;
- break;
- case "cursorMove":
- buffer += cursorMove(patch.x, patch.y);
- break;
- case "cursorTo":
- buffer += cursorTo(patch.col);
- break;
- case "carriageReturn":
- buffer += "\r";
- break;
- case "hyperlink":
- buffer += link2(patch.uri);
- break;
- case "styleStr":
- buffer += patch.str;
- break;
- }
- }
- if (useSync)
- buffer += ESU;
- terminal.stdout.write(buffer);
-}
-var import_semver, xtversionName, EXTENDED_KEYS_TERMINALS, SYNC_OUTPUT_SUPPORTED;
-var init_terminal = __esm(() => {
- init_env();
- init_clearTerminal();
- init_csi();
- init_dec();
- init_osc();
- import_semver = __toESM(require_semver2(), 1);
- EXTENDED_KEYS_TERMINALS = [
- "iTerm.app",
- "kitty",
- "WezTerm",
- "ghostty",
- "tmux",
- "windows-terminal"
- ];
- SYNC_OUTPUT_SUPPORTED = isSynchronizedOutputSupported();
-});
-
-// src/ink/terminal-focus-state.ts
-function setTerminalFocused(v6) {
- focusState = v6 ? "focused" : "blurred";
- for (const cb of subscribers) {
- cb();
- }
- if (!v6) {
- for (const resolve9 of resolvers) {
- resolve9();
- }
- resolvers.clear();
- }
-}
-function getTerminalFocused() {
- return focusState !== "blurred";
-}
-function getTerminalFocusState() {
- return focusState;
-}
-function subscribeTerminalFocus(cb) {
- subscribers.add(cb);
- return () => {
- subscribers.delete(cb);
- };
-}
-var focusState = "unknown", resolvers, subscribers;
-var init_terminal_focus_state = __esm(() => {
- resolvers = new Set;
- subscribers = new Set;
-});
-
-// src/ink/terminal-querier.ts
-function xtversion() {
- return {
- request: csi(">0q"),
- match: (r4) => r4.type === "xtversion"
- };
-}
-
-class TerminalQuerier {
- stdout;
- queue = [];
- constructor(stdout) {
- this.stdout = stdout;
- }
- send(query) {
- return new Promise((resolve9) => {
- this.queue.push({
- kind: "query",
- match: query.match,
- resolve: (r4) => resolve9(r4)
- });
- this.stdout.write(query.request);
- });
- }
- flush() {
- return new Promise((resolve9) => {
- this.queue.push({ kind: "sentinel", resolve: resolve9 });
- this.stdout.write(SENTINEL);
- });
- }
- onResponse(r4) {
- const idx = this.queue.findIndex((p4) => p4.kind === "query" && p4.match(r4));
- if (idx !== -1) {
- const [q4] = this.queue.splice(idx, 1);
- if (q4?.kind === "query")
- q4.resolve(r4);
- return;
- }
- if (r4.type === "da1") {
- const s4 = this.queue.findIndex((p4) => p4.kind === "sentinel");
- if (s4 === -1)
- return;
- for (const p4 of this.queue.splice(0, s4 + 1)) {
- if (p4.kind === "query")
- p4.resolve(undefined);
- else
- p4.resolve();
- }
- }
- }
-}
-var SENTINEL;
-var init_terminal_querier = __esm(() => {
- init_csi();
- init_osc();
- SENTINEL = csi("c");
-});
-
-// src/ink/components/AppContext.ts
-var import_react4, AppContext, AppContext_default;
-var init_AppContext = __esm(() => {
- import_react4 = __toESM(require_react(), 1);
- AppContext = import_react4.createContext({
- exit() {}
- });
- AppContext.displayName = "InternalAppContext";
- AppContext_default = AppContext;
-});
-
-// src/ink/constants.ts
-var FRAME_INTERVAL_MS = 16;
-
-// src/ink/components/TerminalFocusContext.tsx
-function TerminalFocusProvider(t0) {
- const $2 = import_compiler_runtime2.c(6);
- const {
- children
- } = t0;
- const isTerminalFocused = import_react5.useSyncExternalStore(subscribeTerminalFocus, getTerminalFocused);
- const terminalFocusState = import_react5.useSyncExternalStore(subscribeTerminalFocus, getTerminalFocusState);
- let t1;
- if ($2[0] !== isTerminalFocused || $2[1] !== terminalFocusState) {
- t1 = {
- isTerminalFocused,
- terminalFocusState
- };
- $2[0] = isTerminalFocused;
- $2[1] = terminalFocusState;
- $2[2] = t1;
- } else {
- t1 = $2[2];
- }
- const value = t1;
- let t22;
- if ($2[3] !== children || $2[4] !== value) {
- t22 = /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(TerminalFocusContext.Provider, {
- value,
- children
- }, undefined, false, undefined, this);
- $2[3] = children;
- $2[4] = value;
- $2[5] = t22;
- } else {
- t22 = $2[5];
- }
- return t22;
-}
-var import_compiler_runtime2, import_react5, jsx_dev_runtime2, TerminalFocusContext, TerminalFocusContext_default;
-var init_TerminalFocusContext = __esm(() => {
- init_terminal_focus_state();
- import_compiler_runtime2 = __toESM(require_compiler_runtime(), 1);
- import_react5 = __toESM(require_react(), 1);
- jsx_dev_runtime2 = __toESM(require_jsx_dev_runtime(), 1);
- TerminalFocusContext = import_react5.createContext({
- isTerminalFocused: true,
- terminalFocusState: "unknown"
- });
- TerminalFocusContext.displayName = "TerminalFocusContext";
- TerminalFocusContext_default = TerminalFocusContext;
-});
-
-// src/ink/hooks/use-terminal-focus.ts
-function useTerminalFocus() {
- const { isTerminalFocused } = import_react6.useContext(TerminalFocusContext_default);
- return isTerminalFocused;
-}
-var import_react6;
-var init_use_terminal_focus = __esm(() => {
- init_TerminalFocusContext();
- import_react6 = __toESM(require_react(), 1);
-});
-
-// src/ink/components/ClockContext.tsx
-function createClock(tickIntervalMs) {
- const subscribers2 = new Map;
- let interval = null;
- let currentTickIntervalMs = tickIntervalMs;
- let startTime = 0;
- let tickTime = 0;
- function tick() {
- tickTime = Date.now() - startTime;
- for (const onChange of subscribers2.keys()) {
- onChange();
- }
- }
- function updateInterval() {
- const anyKeepAlive = [...subscribers2.values()].some(Boolean);
- if (anyKeepAlive) {
- if (interval) {
- clearInterval(interval);
- interval = null;
- }
- if (startTime === 0) {
- startTime = Date.now();
- }
- interval = setInterval(tick, currentTickIntervalMs);
- } else if (interval) {
- clearInterval(interval);
- interval = null;
- }
- }
- return {
- subscribe(onChange, keepAlive) {
- subscribers2.set(onChange, keepAlive);
- updateInterval();
- return () => {
- subscribers2.delete(onChange);
- updateInterval();
- };
- },
- now() {
- if (startTime === 0) {
- startTime = Date.now();
- }
- if (interval && tickTime) {
- return tickTime;
- }
- return Date.now() - startTime;
- },
- setTickInterval(ms) {
- if (ms === currentTickIntervalMs)
- return;
- currentTickIntervalMs = ms;
- updateInterval();
- }
- };
-}
-function ClockProvider(t0) {
- const $2 = import_compiler_runtime3.c(7);
- const {
- children
- } = t0;
- const [clock] = import_react7.useState(_temp);
- const focused = useTerminalFocus();
- let t1;
- let t22;
- if ($2[0] !== clock || $2[1] !== focused) {
- t1 = () => {
- clock.setTickInterval(focused ? FRAME_INTERVAL_MS : BLURRED_TICK_INTERVAL_MS);
- };
- t22 = [clock, focused];
- $2[0] = clock;
- $2[1] = focused;
- $2[2] = t1;
- $2[3] = t22;
- } else {
- t1 = $2[2];
- t22 = $2[3];
- }
- import_react7.useEffect(t1, t22);
- let t32;
- if ($2[4] !== children || $2[5] !== clock) {
- t32 = /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ClockContext.Provider, {
- value: clock,
- children
- }, undefined, false, undefined, this);
- $2[4] = children;
- $2[5] = clock;
- $2[6] = t32;
- } else {
- t32 = $2[6];
- }
- return t32;
-}
-function _temp() {
- return createClock(FRAME_INTERVAL_MS);
-}
-var import_compiler_runtime3, import_react7, jsx_dev_runtime3, ClockContext, BLURRED_TICK_INTERVAL_MS;
-var init_ClockContext = __esm(() => {
- init_use_terminal_focus();
- import_compiler_runtime3 = __toESM(require_compiler_runtime(), 1);
- import_react7 = __toESM(require_react(), 1);
- jsx_dev_runtime3 = __toESM(require_jsx_dev_runtime(), 1);
- ClockContext = import_react7.createContext(null);
- BLURRED_TICK_INTERVAL_MS = FRAME_INTERVAL_MS * 2;
-});
-
-// src/ink/components/CursorDeclarationContext.ts
-var import_react8, CursorDeclarationContext, CursorDeclarationContext_default;
-var init_CursorDeclarationContext = __esm(() => {
- import_react8 = __toESM(require_react(), 1);
- CursorDeclarationContext = import_react8.createContext(() => {});
- CursorDeclarationContext_default = CursorDeclarationContext;
-});
-
-// node_modules/convert-to-spaces/dist/index.js
-var convertToSpaces = (input, spaces = 2) => {
- return input.replace(/^\t+/gm, ($1) => " ".repeat($1.length * spaces));
-}, dist_default;
-var init_dist2 = __esm(() => {
- dist_default = convertToSpaces;
-});
-
-// node_modules/code-excerpt/dist/index.js
-var generateLineNumbers = (line, around) => {
- const lineNumbers = [];
- const min = line - around;
- const max = line + around;
- for (let lineNumber = min;lineNumber <= max; lineNumber++) {
- lineNumbers.push(lineNumber);
- }
- return lineNumbers;
-}, codeExcerpt = (source, line, options2 = {}) => {
- var _a8;
- if (typeof source !== "string") {
- throw new TypeError("Source code is missing.");
- }
- if (!line || line < 1) {
- throw new TypeError("Line number must start from `1`.");
- }
- const lines = dist_default(source).split(/\r?\n/);
- if (line > lines.length) {
- return;
- }
- return generateLineNumbers(line, (_a8 = options2.around) !== null && _a8 !== undefined ? _a8 : 3).filter((line2) => lines[line2 - 1] !== undefined).map((line2) => ({ line: line2, value: lines[line2 - 1] }));
-}, dist_default2;
-var init_dist3 = __esm(() => {
- init_dist2();
- dist_default2 = codeExcerpt;
-});
-
-// node_modules/escape-string-regexp/index.js
-var require_escape_string_regexp = __commonJS((exports, module) => {
- var matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
- module.exports = (string4) => {
- if (typeof string4 !== "string") {
- throw new TypeError("Expected a string");
- }
- return string4.replace(matchOperatorsRegex, "\\$&");
- };
-});
-
-// node_modules/stack-utils/index.js
-var require_stack_utils = __commonJS((exports, module) => {
- var escapeStringRegexp = require_escape_string_regexp();
- var cwd2 = typeof process === "object" && process && typeof process.cwd === "function" ? process.cwd() : ".";
- var natives = [].concat(__require("module").builtinModules, "bootstrap_node", "node").map((n5) => new RegExp(`(?:\\((?:node:)?${n5}(?:\\.js)?:\\d+:\\d+\\)$|^\\s*at (?:node:)?${n5}(?:\\.js)?:\\d+:\\d+$)`));
- natives.push(/\((?:node:)?internal\/[^:]+:\d+:\d+\)$/, /\s*at (?:node:)?internal\/[^:]+:\d+:\d+$/, /\/\.node-spawn-wrap-\w+-\w+\/node:\d+:\d+\)?$/);
-
- class StackUtils {
- constructor(opts) {
- opts = {
- ignoredPackages: [],
- ...opts
- };
- if ("internals" in opts === false) {
- opts.internals = StackUtils.nodeInternals();
- }
- if ("cwd" in opts === false) {
- opts.cwd = cwd2;
- }
- this._cwd = opts.cwd.replace(/\\/g, "/");
- this._internals = [].concat(opts.internals, ignoredPackagesRegExp(opts.ignoredPackages));
- this._wrapCallSite = opts.wrapCallSite || false;
- }
- static nodeInternals() {
- return [...natives];
- }
- clean(stack, indent = 0) {
- indent = " ".repeat(indent);
- if (!Array.isArray(stack)) {
- stack = stack.split(`
-`);
- }
- if (!/^\s*at /.test(stack[0]) && /^\s*at /.test(stack[1])) {
- stack = stack.slice(1);
- }
- let outdent = false;
- let lastNonAtLine = null;
- const result = [];
- stack.forEach((st) => {
- st = st.replace(/\\/g, "/");
- if (this._internals.some((internal2) => internal2.test(st))) {
- return;
- }
- const isAtLine = /^\s*at /.test(st);
- if (outdent) {
- st = st.trimEnd().replace(/^(\s+)at /, "$1");
- } else {
- st = st.trim();
- if (isAtLine) {
- st = st.slice(3);
- }
- }
- st = st.replace(`${this._cwd}/`, "");
- if (st) {
- if (isAtLine) {
- if (lastNonAtLine) {
- result.push(lastNonAtLine);
- lastNonAtLine = null;
- }
- result.push(st);
- } else {
- outdent = true;
- lastNonAtLine = st;
- }
- }
- });
- return result.map((line) => `${indent}${line}
-`).join("");
- }
- captureString(limit, fn = this.captureString) {
- if (typeof limit === "function") {
- fn = limit;
- limit = Infinity;
- }
- const { stackTraceLimit } = Error;
- if (limit) {
- Error.stackTraceLimit = limit;
- }
- const obj = {};
- Error.captureStackTrace(obj, fn);
- const { stack } = obj;
- Error.stackTraceLimit = stackTraceLimit;
- return this.clean(stack);
- }
- capture(limit, fn = this.capture) {
- if (typeof limit === "function") {
- fn = limit;
- limit = Infinity;
- }
- const { prepareStackTrace, stackTraceLimit } = Error;
- Error.prepareStackTrace = (obj2, site) => {
- if (this._wrapCallSite) {
- return site.map(this._wrapCallSite);
- }
- return site;
- };
- if (limit) {
- Error.stackTraceLimit = limit;
- }
- const obj = {};
- Error.captureStackTrace(obj, fn);
- const { stack } = obj;
- Object.assign(Error, { prepareStackTrace, stackTraceLimit });
- return stack;
- }
- at(fn = this.at) {
- const [site] = this.capture(1, fn);
- if (!site) {
- return {};
- }
- const res = {
- line: site.getLineNumber(),
- column: site.getColumnNumber()
- };
- setFile(res, site.getFileName(), this._cwd);
- if (site.isConstructor()) {
- Object.defineProperty(res, "constructor", {
- value: true,
- configurable: true
- });
- }
- if (site.isEval()) {
- res.evalOrigin = site.getEvalOrigin();
- }
- if (site.isNative()) {
- res.native = true;
- }
- let typename;
- try {
- typename = site.getTypeName();
- } catch (_) {}
- if (typename && typename !== "Object" && typename !== "[object Object]") {
- res.type = typename;
- }
- const fname = site.getFunctionName();
- if (fname) {
- res.function = fname;
- }
- const meth = site.getMethodName();
- if (meth && fname !== meth) {
- res.method = meth;
- }
- return res;
- }
- parseLine(line) {
- const match = line && line.match(re);
- if (!match) {
- return null;
- }
- const ctor = match[1] === "new";
- let fname = match[2];
- const evalOrigin = match[3];
- const evalFile = match[4];
- const evalLine = Number(match[5]);
- const evalCol = Number(match[6]);
- let file2 = match[7];
- const lnum = match[8];
- const col = match[9];
- const native = match[10] === "native";
- const closeParen = match[11] === ")";
- let method;
- const res = {};
- if (lnum) {
- res.line = Number(lnum);
- }
- if (col) {
- res.column = Number(col);
- }
- if (closeParen && file2) {
- let closes = 0;
- for (let i5 = file2.length - 1;i5 > 0; i5--) {
- if (file2.charAt(i5) === ")") {
- closes++;
- } else if (file2.charAt(i5) === "(" && file2.charAt(i5 - 1) === " ") {
- closes--;
- if (closes === -1 && file2.charAt(i5 - 1) === " ") {
- const before = file2.slice(0, i5 - 1);
- const after = file2.slice(i5 + 1);
- file2 = after;
- fname += ` (${before}`;
- break;
- }
- }
- }
- }
- if (fname) {
- const methodMatch = fname.match(methodRe);
- if (methodMatch) {
- fname = methodMatch[1];
- method = methodMatch[2];
- }
- }
- setFile(res, file2, this._cwd);
- if (ctor) {
- Object.defineProperty(res, "constructor", {
- value: true,
- configurable: true
- });
- }
- if (evalOrigin) {
- res.evalOrigin = evalOrigin;
- res.evalLine = evalLine;
- res.evalColumn = evalCol;
- res.evalFile = evalFile && evalFile.replace(/\\/g, "/");
- }
- if (native) {
- res.native = true;
- }
- if (fname) {
- res.function = fname;
- }
- if (method && fname !== method) {
- res.method = method;
- }
- return res;
- }
- }
- function setFile(result, filename, cwd3) {
- if (filename) {
- filename = filename.replace(/\\/g, "/");
- if (filename.startsWith(`${cwd3}/`)) {
- filename = filename.slice(cwd3.length + 1);
- }
- result.file = filename;
- }
- }
- function ignoredPackagesRegExp(ignoredPackages) {
- if (ignoredPackages.length === 0) {
- return [];
- }
- const packages = ignoredPackages.map((mod2) => escapeStringRegexp(mod2));
- return new RegExp(`[/\\\\]node_modules[/\\\\](?:${packages.join("|")})[/\\\\][^:]+:\\d+:\\d+`);
- }
- var re = new RegExp("^" + "(?:\\s*at )?" + "(?:(new) )?" + "(?:(.*?) \\()?" + "(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?" + "(?:(.+?):(\\d+):(\\d+)|(native))" + "(\\)?)$");
- var methodRe = /^(.*?) \[as (.*?)\]$/;
- module.exports = StackUtils;
-});
-// src/ink/components/Box.tsx
-function Box(t0) {
- const $2 = import_compiler_runtime4.c(42);
- let autoFocus;
- let children;
- let flexDirection;
- let flexGrow;
- let flexShrink;
- let flexWrap;
- let onBlur;
- let onBlurCapture;
- let onClick;
- let onFocus;
- let onFocusCapture;
- let onKeyDown;
- let onKeyDownCapture;
- let onMouseEnter;
- let onMouseLeave;
- let ref;
- let style;
- let tabIndex;
- if ($2[0] !== t0) {
- const {
- children: t12,
- flexWrap: t23,
- flexDirection: t33,
- flexGrow: t42,
- flexShrink: t5,
- ref: t6,
- tabIndex: t7,
- autoFocus: t8,
- onClick: t9,
- onFocus: t10,
- onFocusCapture: t11,
- onBlur: t122,
- onBlurCapture: t13,
- onMouseEnter: t14,
- onMouseLeave: t15,
- onKeyDown: t16,
- onKeyDownCapture: t17,
- ...t18
- } = t0;
- children = t12;
- ref = t6;
- tabIndex = t7;
- autoFocus = t8;
- onClick = t9;
- onFocus = t10;
- onFocusCapture = t11;
- onBlur = t122;
- onBlurCapture = t13;
- onMouseEnter = t14;
- onMouseLeave = t15;
- onKeyDown = t16;
- onKeyDownCapture = t17;
- style = t18;
- flexWrap = t23 === undefined ? "nowrap" : t23;
- flexDirection = t33 === undefined ? "row" : t33;
- flexGrow = t42 === undefined ? 0 : t42;
- flexShrink = t5 === undefined ? 1 : t5;
- ifNotInteger(style.margin, "margin");
- ifNotInteger(style.marginX, "marginX");
- ifNotInteger(style.marginY, "marginY");
- ifNotInteger(style.marginTop, "marginTop");
- ifNotInteger(style.marginBottom, "marginBottom");
- ifNotInteger(style.marginLeft, "marginLeft");
- ifNotInteger(style.marginRight, "marginRight");
- ifNotInteger(style.padding, "padding");
- ifNotInteger(style.paddingX, "paddingX");
- ifNotInteger(style.paddingY, "paddingY");
- ifNotInteger(style.paddingTop, "paddingTop");
- ifNotInteger(style.paddingBottom, "paddingBottom");
- ifNotInteger(style.paddingLeft, "paddingLeft");
- ifNotInteger(style.paddingRight, "paddingRight");
- ifNotInteger(style.gap, "gap");
- ifNotInteger(style.columnGap, "columnGap");
- ifNotInteger(style.rowGap, "rowGap");
- $2[0] = t0;
- $2[1] = autoFocus;
- $2[2] = children;
- $2[3] = flexDirection;
- $2[4] = flexGrow;
- $2[5] = flexShrink;
- $2[6] = flexWrap;
- $2[7] = onBlur;
- $2[8] = onBlurCapture;
- $2[9] = onClick;
- $2[10] = onFocus;
- $2[11] = onFocusCapture;
- $2[12] = onKeyDown;
- $2[13] = onKeyDownCapture;
- $2[14] = onMouseEnter;
- $2[15] = onMouseLeave;
- $2[16] = ref;
- $2[17] = style;
- $2[18] = tabIndex;
- } else {
- autoFocus = $2[1];
- children = $2[2];
- flexDirection = $2[3];
- flexGrow = $2[4];
- flexShrink = $2[5];
- flexWrap = $2[6];
- onBlur = $2[7];
- onBlurCapture = $2[8];
- onClick = $2[9];
- onFocus = $2[10];
- onFocusCapture = $2[11];
- onKeyDown = $2[12];
- onKeyDownCapture = $2[13];
- onMouseEnter = $2[14];
- onMouseLeave = $2[15];
- ref = $2[16];
- style = $2[17];
- tabIndex = $2[18];
- }
- const t1 = style.overflowX ?? style.overflow ?? "visible";
- const t22 = style.overflowY ?? style.overflow ?? "visible";
- let t32;
- if ($2[19] !== flexDirection || $2[20] !== flexGrow || $2[21] !== flexShrink || $2[22] !== flexWrap || $2[23] !== style || $2[24] !== t1 || $2[25] !== t22) {
- t32 = {
- flexWrap,
- flexDirection,
- flexGrow,
- flexShrink,
- ...style,
- overflowX: t1,
- overflowY: t22
- };
- $2[19] = flexDirection;
- $2[20] = flexGrow;
- $2[21] = flexShrink;
- $2[22] = flexWrap;
- $2[23] = style;
- $2[24] = t1;
- $2[25] = t22;
- $2[26] = t32;
- } else {
- t32 = $2[26];
- }
- let t4;
- if ($2[27] !== autoFocus || $2[28] !== children || $2[29] !== onBlur || $2[30] !== onBlurCapture || $2[31] !== onClick || $2[32] !== onFocus || $2[33] !== onFocusCapture || $2[34] !== onKeyDown || $2[35] !== onKeyDownCapture || $2[36] !== onMouseEnter || $2[37] !== onMouseLeave || $2[38] !== ref || $2[39] !== t32 || $2[40] !== tabIndex) {
- t4 = /* @__PURE__ */ jsx_dev_runtime4.jsxDEV("ink-box", {
- ref,
- tabIndex,
- autoFocus,
- onClick,
- onFocus,
- onFocusCapture,
- onBlur,
- onBlurCapture,
- onMouseEnter,
- onMouseLeave,
- onKeyDown,
- onKeyDownCapture,
- style: t32,
- children
- }, undefined, false, undefined, this);
- $2[27] = autoFocus;
- $2[28] = children;
- $2[29] = onBlur;
- $2[30] = onBlurCapture;
- $2[31] = onClick;
- $2[32] = onFocus;
- $2[33] = onFocusCapture;
- $2[34] = onKeyDown;
- $2[35] = onKeyDownCapture;
- $2[36] = onMouseEnter;
- $2[37] = onMouseLeave;
- $2[38] = ref;
- $2[39] = t32;
- $2[40] = tabIndex;
- $2[41] = t4;
- } else {
- t4 = $2[41];
- }
- return t4;
-}
-var import_compiler_runtime4, jsx_dev_runtime4, Box_default;
-var init_Box = __esm(() => {
- init_warn();
- import_compiler_runtime4 = __toESM(require_compiler_runtime(), 1);
- jsx_dev_runtime4 = __toESM(require_jsx_dev_runtime(), 1);
- Box_default = Box;
-});
-
-// src/ink/components/Text.tsx
-function Text(t0) {
- const $2 = import_compiler_runtime5.c(29);
- const {
- color,
- backgroundColor,
- bold: bold2,
- dim: dim2,
- italic: t1,
- underline: t22,
- strikethrough: t32,
- inverse: t4,
- wrap: t5,
- children
- } = t0;
- const italic2 = t1 === undefined ? false : t1;
- const underline2 = t22 === undefined ? false : t22;
- const strikethrough2 = t32 === undefined ? false : t32;
- const inverse2 = t4 === undefined ? false : t4;
- const wrap = t5 === undefined ? "wrap" : t5;
- if (children === undefined || children === null) {
- return null;
- }
- let t6;
- if ($2[0] !== color) {
- t6 = color && {
- color
- };
- $2[0] = color;
- $2[1] = t6;
- } else {
- t6 = $2[1];
- }
- let t7;
- if ($2[2] !== backgroundColor) {
- t7 = backgroundColor && {
- backgroundColor
- };
- $2[2] = backgroundColor;
- $2[3] = t7;
- } else {
- t7 = $2[3];
- }
- let t8;
- if ($2[4] !== dim2) {
- t8 = dim2 && {
- dim: dim2
- };
- $2[4] = dim2;
- $2[5] = t8;
- } else {
- t8 = $2[5];
- }
- let t9;
- if ($2[6] !== bold2) {
- t9 = bold2 && {
- bold: bold2
- };
- $2[6] = bold2;
- $2[7] = t9;
- } else {
- t9 = $2[7];
- }
- let t10;
- if ($2[8] !== italic2) {
- t10 = italic2 && {
- italic: italic2
- };
- $2[8] = italic2;
- $2[9] = t10;
- } else {
- t10 = $2[9];
- }
- let t11;
- if ($2[10] !== underline2) {
- t11 = underline2 && {
- underline: underline2
- };
- $2[10] = underline2;
- $2[11] = t11;
- } else {
- t11 = $2[11];
- }
- let t12;
- if ($2[12] !== strikethrough2) {
- t12 = strikethrough2 && {
- strikethrough: strikethrough2
- };
- $2[12] = strikethrough2;
- $2[13] = t12;
- } else {
- t12 = $2[13];
- }
- let t13;
- if ($2[14] !== inverse2) {
- t13 = inverse2 && {
- inverse: inverse2
- };
- $2[14] = inverse2;
- $2[15] = t13;
- } else {
- t13 = $2[15];
- }
- let t14;
- if ($2[16] !== t10 || $2[17] !== t11 || $2[18] !== t12 || $2[19] !== t13 || $2[20] !== t6 || $2[21] !== t7 || $2[22] !== t8 || $2[23] !== t9) {
- t14 = {
- ...t6,
- ...t7,
- ...t8,
- ...t9,
- ...t10,
- ...t11,
- ...t12,
- ...t13
- };
- $2[16] = t10;
- $2[17] = t11;
- $2[18] = t12;
- $2[19] = t13;
- $2[20] = t6;
- $2[21] = t7;
- $2[22] = t8;
- $2[23] = t9;
- $2[24] = t14;
- } else {
- t14 = $2[24];
- }
- const textStyles = t14;
- const t15 = memoizedStylesForWrap[wrap];
- let t16;
- if ($2[25] !== children || $2[26] !== t15 || $2[27] !== textStyles) {
- t16 = /* @__PURE__ */ jsx_dev_runtime5.jsxDEV("ink-text", {
- style: t15,
- textStyles,
- children
- }, undefined, false, undefined, this);
- $2[25] = children;
- $2[26] = t15;
- $2[27] = textStyles;
- $2[28] = t16;
- } else {
- t16 = $2[28];
- }
- return t16;
-}
-var import_compiler_runtime5, jsx_dev_runtime5, memoizedStylesForWrap;
-var init_Text = __esm(() => {
- import_compiler_runtime5 = __toESM(require_compiler_runtime(), 1);
- jsx_dev_runtime5 = __toESM(require_jsx_dev_runtime(), 1);
- memoizedStylesForWrap = {
- wrap: {
- flexGrow: 0,
- flexShrink: 1,
- flexDirection: "row",
- textWrap: "wrap"
- },
- "wrap-trim": {
- flexGrow: 0,
- flexShrink: 1,
- flexDirection: "row",
- textWrap: "wrap-trim"
- },
- end: {
- flexGrow: 0,
- flexShrink: 1,
- flexDirection: "row",
- textWrap: "end"
- },
- middle: {
- flexGrow: 0,
- flexShrink: 1,
- flexDirection: "row",
- textWrap: "middle"
- },
- "truncate-end": {
- flexGrow: 0,
- flexShrink: 1,
- flexDirection: "row",
- textWrap: "truncate-end"
- },
- truncate: {
- flexGrow: 0,
- flexShrink: 1,
- flexDirection: "row",
- textWrap: "truncate"
- },
- "truncate-middle": {
- flexGrow: 0,
- flexShrink: 1,
- flexDirection: "row",
- textWrap: "truncate-middle"
- },
- "truncate-start": {
- flexGrow: 0,
- flexShrink: 1,
- flexDirection: "row",
- textWrap: "truncate-start"
- }
- };
-});
-
-// src/ink/components/ErrorOverview.tsx
-import { readFileSync as readFileSync9 } from "fs";
-function getStackUtils() {
- return stackUtils ??= new import_stack_utils.default({
- cwd: process.cwd(),
- internals: import_stack_utils.default.nodeInternals()
- });
-}
-function ErrorOverview({
- error: error46
-}) {
- const stack = error46.stack ? error46.stack.split(`
-`).slice(1) : undefined;
- const origin2 = stack ? getStackUtils().parseLine(stack[0]) : undefined;
- const filePath = cleanupPath(origin2?.file);
- let excerpt;
- let lineWidth2 = 0;
- if (filePath && origin2?.line) {
- try {
- const sourceCode = readFileSync9(filePath, "utf8");
- excerpt = dist_default2(sourceCode, origin2.line);
- if (excerpt) {
- for (const {
- line
- } of excerpt) {
- lineWidth2 = Math.max(lineWidth2, String(line).length);
- }
- }
- } catch {}
- }
- return /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
- flexDirection: "column",
- padding: 1,
- children: [
- /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
- children: [
- /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
- backgroundColor: "ansi:red",
- color: "ansi:white",
- children: [
- " ",
- "ERROR",
- " "
- ]
- }, undefined, true, undefined, this),
- /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
- children: [
- " ",
- error46.message
- ]
- }, undefined, true, undefined, this)
- ]
- }, undefined, true, undefined, this),
- origin2 && filePath && /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
- marginTop: 1,
- children: /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
- dim: true,
- children: [
- filePath,
- ":",
- origin2.line,
- ":",
- origin2.column
- ]
- }, undefined, true, undefined, this)
- }, undefined, false, undefined, this),
- origin2 && excerpt && /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
- marginTop: 1,
- flexDirection: "column",
- children: excerpt.map(({
- line: line_0,
- value
- }) => /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
- children: [
- /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
- width: lineWidth2 + 1,
- children: /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
- dim: line_0 !== origin2.line,
- backgroundColor: line_0 === origin2.line ? "ansi:red" : undefined,
- color: line_0 === origin2.line ? "ansi:white" : undefined,
- children: [
- String(line_0).padStart(lineWidth2, " "),
- ":"
- ]
- }, undefined, true, undefined, this)
- }, undefined, false, undefined, this),
- /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
- backgroundColor: line_0 === origin2.line ? "ansi:red" : undefined,
- color: line_0 === origin2.line ? "ansi:white" : undefined,
- children: " " + value
- }, line_0, false, undefined, this)
- ]
- }, line_0, true, undefined, this))
- }, undefined, false, undefined, this),
- error46.stack && /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
- marginTop: 1,
- flexDirection: "column",
- children: error46.stack.split(`
-`).slice(1).map((line_1) => {
- const parsedLine = getStackUtils().parseLine(line_1);
- if (!parsedLine) {
- return /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
- children: [
- /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
- dim: true,
- children: "- "
- }, undefined, false, undefined, this),
- /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
- bold: true,
- children: line_1
- }, undefined, false, undefined, this)
- ]
- }, line_1, true, undefined, this);
- }
- return /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Box_default, {
- children: [
- /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
- dim: true,
- children: "- "
- }, undefined, false, undefined, this),
- /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
- bold: true,
- children: parsedLine.function
- }, undefined, false, undefined, this),
- /* @__PURE__ */ jsx_dev_runtime6.jsxDEV(Text, {
- dim: true,
- children: [
- " ",
- "(",
- cleanupPath(parsedLine.file) ?? "",
- ":",
- parsedLine.line,
- ":",
- parsedLine.column,
- ")"
- ]
- }, undefined, true, undefined, this)
- ]
- }, line_1, true, undefined, this);
- })
- }, undefined, false, undefined, this)
- ]
- }, undefined, true, undefined, this);
-}
-var import_stack_utils, jsx_dev_runtime6, cleanupPath = (path15) => {
- return path15?.replace(`file://${process.cwd()}/`, "");
-}, stackUtils;
-var init_ErrorOverview = __esm(() => {
- init_dist3();
- init_Box();
- init_Text();
- import_stack_utils = __toESM(require_stack_utils(), 1);
- jsx_dev_runtime6 = __toESM(require_jsx_dev_runtime(), 1);
-});
-
-// src/ink/components/TerminalSizeContext.tsx
-var import_react9, TerminalSizeContext;
-var init_TerminalSizeContext = __esm(() => {
- import_react9 = __toESM(require_react(), 1);
- TerminalSizeContext = import_react9.createContext(null);
-});
-
-// src/ink/components/App.tsx
-function processKeysInBatch(app, items, _unused1, _unused2) {
- if (items.some((i5) => i5.kind === "key" || i5.kind === "mouse" && !((i5.button & 32) !== 0 && (i5.button & 3) === 3))) {
- updateLastInteractionTime();
- }
- for (const item of items) {
- if (item.kind === "response") {
- app.querier.onResponse(item.response);
- continue;
- }
- if (item.kind === "mouse") {
- handleMouseEvent(app, item);
- continue;
- }
- const sequence = item.sequence;
- if (sequence === FOCUS_IN) {
- app.handleTerminalFocus(true);
- const event2 = new TerminalFocusEvent("terminalfocus");
- app.internal_eventEmitter.emit("terminalfocus", event2);
- continue;
- }
- if (sequence === FOCUS_OUT) {
- app.handleTerminalFocus(false);
- if (app.props.selection.isDragging) {
- finishSelection(app.props.selection);
- app.props.onSelectionChange();
- }
- const event2 = new TerminalFocusEvent("terminalblur");
- app.internal_eventEmitter.emit("terminalblur", event2);
- continue;
- }
- if (!getTerminalFocused()) {
- setTerminalFocused(true);
- }
- if (item.name === "z" && item.ctrl && SUPPORTS_SUSPEND) {
- app.handleSuspend();
- continue;
- }
- app.handleInput(sequence);
- const event = new InputEvent(item);
- app.internal_eventEmitter.emit("input", event);
- app.props.dispatchKeyboardEvent(item);
- }
-}
-function handleMouseEvent(app, m4) {
- if (isMouseClicksDisabled())
- return;
- const sel = app.props.selection;
- const col = m4.col - 1;
- const row = m4.row - 1;
- const baseButton = m4.button & 3;
- if (m4.action === "press") {
- if ((m4.button & 32) !== 0 && baseButton === 3) {
- if (sel.isDragging) {
- finishSelection(sel);
- app.props.onSelectionChange();
- }
- if (col === app.lastHoverCol && row === app.lastHoverRow)
- return;
- app.lastHoverCol = col;
- app.lastHoverRow = row;
- app.props.onHoverAt(col, row);
- return;
- }
- if (baseButton !== 0) {
- app.clickCount = 0;
- return;
- }
- if ((m4.button & 32) !== 0) {
- app.props.onSelectionDrag(col, row);
- return;
- }
- if (sel.isDragging) {
- finishSelection(sel);
- app.props.onSelectionChange();
- }
- const now2 = Date.now();
- const nearLast = now2 - app.lastClickTime < MULTI_CLICK_TIMEOUT_MS && Math.abs(col - app.lastClickCol) <= MULTI_CLICK_DISTANCE && Math.abs(row - app.lastClickRow) <= MULTI_CLICK_DISTANCE;
- app.clickCount = nearLast ? app.clickCount + 1 : 1;
- app.lastClickTime = now2;
- app.lastClickCol = col;
- app.lastClickRow = row;
- if (app.clickCount >= 2) {
- if (app.pendingHyperlinkTimer) {
- clearTimeout(app.pendingHyperlinkTimer);
- app.pendingHyperlinkTimer = null;
- }
- const count3 = app.clickCount === 2 ? 2 : 3;
- app.props.onMultiClick(col, row, count3);
- return;
- }
- startSelection(sel, col, row);
- sel.lastPressHadAlt = (m4.button & 8) !== 0;
- app.props.onSelectionChange();
- return;
- }
- if (baseButton !== 0) {
- if (!sel.isDragging)
- return;
- finishSelection(sel);
- app.props.onSelectionChange();
- return;
- }
- finishSelection(sel);
- if (!hasSelection(sel) && sel.anchor) {
- if (!app.props.onClickAt(col, row)) {
- const url3 = app.props.getHyperlinkAt(col, row);
- if (url3 && process.env.TERM_PROGRAM !== "vscode" && !isXtermJs()) {
- if (app.pendingHyperlinkTimer) {
- clearTimeout(app.pendingHyperlinkTimer);
- }
- app.pendingHyperlinkTimer = setTimeout((app2, url4) => {
- app2.pendingHyperlinkTimer = null;
- app2.props.onOpenHyperlink(url4);
- }, MULTI_CLICK_TIMEOUT_MS, app, url3);
- }
- }
- }
- app.props.onSelectionChange();
-}
-var import_react10, jsx_dev_runtime7, SUPPORTS_SUSPEND, STDIN_RESUME_GAP_MS = 5000, MULTI_CLICK_TIMEOUT_MS = 500, MULTI_CLICK_DISTANCE = 1, App;
-var init_App = __esm(() => {
- init_state();
- init_debug();
- init_earlyInput();
- init_envUtils();
- init_fullscreen();
- init_log2();
- init_emitter();
- init_input_event();
- init_terminal_focus_event();
- init_parse_keypress();
- init_reconciler();
- init_selection();
- init_terminal();
- init_terminal_focus_state();
- init_terminal_querier();
- init_csi();
- init_dec();
- init_AppContext();
- init_ClockContext();
- init_CursorDeclarationContext();
- init_ErrorOverview();
- init_StdinContext();
- init_TerminalFocusContext();
- init_TerminalSizeContext();
- import_react10 = __toESM(require_react(), 1);
- jsx_dev_runtime7 = __toESM(require_jsx_dev_runtime(), 1);
- SUPPORTS_SUSPEND = process.platform !== "win32";
- App = class App extends import_react10.PureComponent {
- static displayName = "InternalApp";
- static getDerivedStateFromError(error46) {
- return {
- error: error46
- };
- }
- state = {
- error: undefined
- };
- rawModeEnabledCount = 0;
- internal_eventEmitter = new EventEmitter3;
- keyParseState = INITIAL_STATE;
- incompleteEscapeTimer = null;
- NORMAL_TIMEOUT = 50;
- PASTE_TIMEOUT = 500;
- querier = new TerminalQuerier(this.props.stdout);
- lastClickTime = 0;
- lastClickCol = -1;
- lastClickRow = -1;
- clickCount = 0;
- pendingHyperlinkTimer = null;
- lastHoverCol = -1;
- lastHoverRow = -1;
- lastStdinTime = Date.now();
- isRawModeSupported() {
- return this.props.stdin.isTTY;
- }
- render() {
- return /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(TerminalSizeContext.Provider, {
- value: {
- columns: this.props.terminalColumns,
- rows: this.props.terminalRows
- },
- children: /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(AppContext_default.Provider, {
- value: {
- exit: this.handleExit
- },
- children: /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(StdinContext_default.Provider, {
- value: {
- stdin: this.props.stdin,
- setRawMode: this.handleSetRawMode,
- isRawModeSupported: this.isRawModeSupported(),
- internal_exitOnCtrlC: this.props.exitOnCtrlC,
- internal_eventEmitter: this.internal_eventEmitter,
- internal_querier: this.querier
- },
- children: /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(TerminalFocusProvider, {
- children: /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(ClockProvider, {
- children: /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(CursorDeclarationContext_default.Provider, {
- value: this.props.onCursorDeclaration ?? (() => {}),
- children: this.state.error ? /* @__PURE__ */ jsx_dev_runtime7.jsxDEV(ErrorOverview, {
- error: this.state.error
- }, undefined, false, undefined, this) : this.props.children
- }, undefined, false, undefined, this)
- }, undefined, false, undefined, this)
- }, undefined, false, undefined, this)
- }, undefined, false, undefined, this)
- }, undefined, false, undefined, this)
- }, undefined, false, undefined, this);
- }
- componentDidMount() {
- if (this.props.stdout.isTTY && !isEnvTruthy(process.env.CLAUDE_CODE_ACCESSIBILITY)) {
- this.props.stdout.write(HIDE_CURSOR);
- }
- }
- componentWillUnmount() {
- if (this.props.stdout.isTTY) {
- this.props.stdout.write(SHOW_CURSOR);
- }
- if (this.incompleteEscapeTimer) {
- clearTimeout(this.incompleteEscapeTimer);
- this.incompleteEscapeTimer = null;
- }
- if (this.pendingHyperlinkTimer) {
- clearTimeout(this.pendingHyperlinkTimer);
- this.pendingHyperlinkTimer = null;
- }
- if (this.isRawModeSupported()) {
- this.handleSetRawMode(false);
- }
- }
- componentDidCatch(error46) {
- this.handleExit(error46);
- }
- handleSetRawMode = (isEnabled) => {
- const {
- stdin
- } = this.props;
- if (!this.isRawModeSupported()) {
- if (stdin === process.stdin) {
- throw new Error(`Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.
-Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);
- } else {
- throw new Error(`Raw mode is not supported on the stdin provided to Ink.
-Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);
- }
- }
- stdin.setEncoding("utf8");
- if (isEnabled) {
- if (this.rawModeEnabledCount === 0) {
- stopCapturingEarlyInput();
- stdin.ref();
- stdin.setRawMode(true);
- stdin.addListener("readable", this.handleReadable);
- this.props.stdout.write(EBP);
- this.props.stdout.write(EFE);
- if (supportsExtendedKeys()) {
- this.props.stdout.write(ENABLE_KITTY_KEYBOARD);
- this.props.stdout.write(ENABLE_MODIFY_OTHER_KEYS);
- }
- setImmediate(() => {
- Promise.all([this.querier.send(xtversion()), this.querier.flush()]).then(([r4]) => {
- if (r4) {
- setXtversionName(r4.name);
- logForDebugging(`XTVERSION: terminal identified as "${r4.name}"`);
- } else {
- logForDebugging("XTVERSION: no reply (terminal ignored query)");
- }
- });
- });
- }
- this.rawModeEnabledCount++;
- return;
- }
- if (--this.rawModeEnabledCount === 0) {
- this.props.stdout.write(DISABLE_MODIFY_OTHER_KEYS);
- this.props.stdout.write(DISABLE_KITTY_KEYBOARD);
- this.props.stdout.write(DFE);
- this.props.stdout.write(DBP);
- stdin.setRawMode(false);
- stdin.removeListener("readable", this.handleReadable);
- stdin.unref();
- }
- };
- flushIncomplete = () => {
- this.incompleteEscapeTimer = null;
- if (!this.keyParseState.incomplete)
- return;
- if (this.props.stdin.readableLength > 0) {
- this.incompleteEscapeTimer = setTimeout(this.flushIncomplete, this.NORMAL_TIMEOUT);
- return;
- }
- this.processInput(null);
- };
- processInput = (input) => {
- const [keys2, newState] = parseMultipleKeypresses(this.keyParseState, input);
- this.keyParseState = newState;
- if (keys2.length > 0) {
- reconciler_default.discreteUpdates(processKeysInBatch, this, keys2, undefined, undefined);
- }
- if (this.keyParseState.incomplete) {
- if (this.incompleteEscapeTimer) {
- clearTimeout(this.incompleteEscapeTimer);
- }
- this.incompleteEscapeTimer = setTimeout(this.flushIncomplete, this.keyParseState.mode === "IN_PASTE" ? this.PASTE_TIMEOUT : this.NORMAL_TIMEOUT);
- }
- };
- handleReadable = () => {
- const now2 = Date.now();
- if (now2 - this.lastStdinTime > STDIN_RESUME_GAP_MS) {
- this.props.onStdinResume?.();
- }
- this.lastStdinTime = now2;
- try {
- let chunk;
- while ((chunk = this.props.stdin.read()) !== null) {
- this.processInput(chunk);
- }
- } catch (error46) {
- logError2(error46);
- const {
- stdin
- } = this.props;
- if (this.rawModeEnabledCount > 0 && !stdin.listeners("readable").includes(this.handleReadable)) {
- logForDebugging("handleReadable: re-attaching stdin readable listener after error recovery", {
- level: "warn"
- });
- stdin.addListener("readable", this.handleReadable);
- }
- }
- };
- handleInput = (input) => {
- if (input === "\x03" && this.props.exitOnCtrlC) {
- this.handleExit();
- }
- };
- handleExit = (error46) => {
- if (this.isRawModeSupported()) {
- this.handleSetRawMode(false);
- }
- this.props.onExit(error46);
- };
- handleTerminalFocus = (isFocused) => {
- setTerminalFocused(isFocused);
- };
- handleSuspend = () => {
- if (!this.isRawModeSupported()) {
- return;
- }
- const rawModeCountBeforeSuspend = this.rawModeEnabledCount;
- while (this.rawModeEnabledCount > 0) {
- this.handleSetRawMode(false);
- }
- if (this.props.stdout.isTTY) {
- this.props.stdout.write(SHOW_CURSOR + DFE + DISABLE_MOUSE_TRACKING);
- }
- this.internal_eventEmitter.emit("suspend");
- const resumeHandler = () => {
- for (let i5 = 0;i5 < rawModeCountBeforeSuspend; i5++) {
- if (this.isRawModeSupported()) {
- this.handleSetRawMode(true);
- }
- }
- if (this.props.stdout.isTTY) {
- if (!isEnvTruthy(process.env.CLAUDE_CODE_ACCESSIBILITY)) {
- this.props.stdout.write(HIDE_CURSOR);
- }
- this.props.stdout.write(EFE);
- }
- this.internal_eventEmitter.emit("resume");
- process.removeListener("SIGCONT", resumeHandler);
- };
- process.on("SIGCONT", resumeHandler);
- process.kill(process.pid, "SIGSTOP");
- };
- };
-});
-
-// src/ink/events/keyboard-event.ts
-function keyFromParsed(parsed) {
- const seq = parsed.sequence ?? "";
- const name3 = parsed.name ?? "";
- if (parsed.ctrl)
- return name3;
- if (seq.length === 1) {
- const code = seq.charCodeAt(0);
- if (code >= 32 && code !== 127)
- return seq;
- }
- return name3 || seq;
-}
-var KeyboardEvent;
-var init_keyboard_event = __esm(() => {
- init_terminal_event();
- KeyboardEvent = class KeyboardEvent extends TerminalEvent {
- key;
- ctrl;
- shift;
- meta;
- superKey;
- fn;
- constructor(parsedKey) {
- super("keydown", { bubbles: true, cancelable: true });
- this.key = keyFromParsed(parsedKey);
- this.ctrl = parsedKey.ctrl;
- this.shift = parsedKey.shift;
- this.meta = parsedKey.meta || parsedKey.option;
- this.superKey = parsedKey.super;
- this.fn = parsedKey.fn;
- }
- };
-});
-
-// src/ink/frame.ts
-function emptyFrame(rows, columns, stylePool, charPool, hyperlinkPool) {
- return {
- screen: createScreen(0, 0, stylePool, charPool, hyperlinkPool),
- viewport: { width: columns, height: rows },
- cursor: { x: 0, y: 0, visible: true }
- };
-}
-var init_frame = __esm(() => {
- init_screen();
-});
-
-// src/ink/events/click-event.ts
-var ClickEvent;
-var init_click_event = __esm(() => {
- ClickEvent = class ClickEvent extends Event2 {
- col;
- row;
- localCol = 0;
- localRow = 0;
- cellIsBlank;
- constructor(col, row, cellIsBlank) {
- super();
- this.col = col;
- this.row = row;
- this.cellIsBlank = cellIsBlank;
- }
- };
-});
-
-// src/ink/hit-test.ts
-function hitTest(node, col, row) {
- const rect = nodeCache.get(node);
- if (!rect)
- return null;
- if (col < rect.x || col >= rect.x + rect.width || row < rect.y || row >= rect.y + rect.height) {
- return null;
- }
- for (let i5 = node.childNodes.length - 1;i5 >= 0; i5--) {
- const child = node.childNodes[i5];
- if (child.nodeName === "#text")
- continue;
- const hit = hitTest(child, col, row);
- if (hit)
- return hit;
- }
- return node;
-}
-function dispatchClick(root2, col, row, cellIsBlank = false) {
- let target = hitTest(root2, col, row) ?? undefined;
- if (!target)
- return false;
- if (root2.focusManager) {
- let focusTarget = target;
- while (focusTarget) {
- if (typeof focusTarget.attributes["tabIndex"] === "number") {
- root2.focusManager.handleClickFocus(focusTarget);
- break;
- }
- focusTarget = focusTarget.parentNode;
- }
- }
- const event = new ClickEvent(col, row, cellIsBlank);
- let handled = false;
- while (target) {
- const handler = target._eventHandlers?.onClick;
- if (handler) {
- handled = true;
- const rect = nodeCache.get(target);
- if (rect) {
- event.localCol = col - rect.x;
- event.localRow = row - rect.y;
- }
- handler(event);
- if (event.didStopImmediatePropagation())
- return true;
- }
- target = target.parentNode;
- }
- return handled;
-}
-function dispatchHover(root2, col, row, hovered) {
- const next = new Set;
- let node = hitTest(root2, col, row) ?? undefined;
- while (node) {
- const h5 = node._eventHandlers;
- if (h5?.onMouseEnter || h5?.onMouseLeave)
- next.add(node);
- node = node.parentNode;
- }
- for (const old of hovered) {
- if (!next.has(old)) {
- hovered.delete(old);
- if (old.parentNode) {
- old._eventHandlers?.onMouseLeave?.();
- }
- }
- }
- for (const n5 of next) {
- if (!hovered.has(n5)) {
- hovered.add(n5);
- n5._eventHandlers?.onMouseEnter?.();
- }
- }
-}
-var init_hit_test = __esm(() => {
- init_click_event();
- init_node_cache();
-});
-
-// src/ink/instances.ts
-var instances, instances_default;
-var init_instances = __esm(() => {
- instances = new Map;
- instances_default = instances;
-});
-
-// src/ink/log-update.ts
-class LogUpdate {
- options;
- state;
- constructor(options2) {
- this.options = options2;
- this.state = {
- previousOutput: ""
- };
- }
- renderPreviousOutput_DEPRECATED(prevFrame) {
- if (!this.options.isTTY) {
- return [NEWLINE];
- }
- return this.getRenderOpsForDone(prevFrame);
- }
- reset() {
- this.state.previousOutput = "";
- }
- renderFullFrame(frame) {
- const { screen } = frame;
- const lines = [];
- let currentStyles = [];
- let currentHyperlink = undefined;
- for (let y3 = 0;y3 < screen.height; y3++) {
- let line = "";
- for (let x3 = 0;x3 < screen.width; x3++) {
- const cell = cellAt(screen, x3, y3);
- if (cell && cell.width !== 2 /* SpacerTail */) {
- if (cell.hyperlink !== currentHyperlink) {
- if (currentHyperlink !== undefined) {
- line += LINK_END;
- }
- if (cell.hyperlink !== undefined) {
- line += link2(cell.hyperlink);
- }
- currentHyperlink = cell.hyperlink;
- }
- const cellStyles = this.options.stylePool.get(cell.styleId);
- const styleDiff = diffAnsiCodes(currentStyles, cellStyles);
- if (styleDiff.length > 0) {
- line += ansiCodesToString(styleDiff);
- currentStyles = cellStyles;
- }
- line += cell.char;
- }
- }
- if (currentHyperlink !== undefined) {
- line += LINK_END;
- currentHyperlink = undefined;
- }
- const resetCodes = diffAnsiCodes(currentStyles, []);
- if (resetCodes.length > 0) {
- line += ansiCodesToString(resetCodes);
- currentStyles = [];
- }
- lines.push(line.trimEnd());
- }
- if (lines.length === 0) {
- return [];
- }
- return [{ type: "stdout", content: lines.join(`
-`) }];
- }
- getRenderOpsForDone(prev) {
- this.state.previousOutput = "";
- if (!prev.cursor.visible) {
- return [{ type: "cursorShow" }];
- }
- return [];
- }
- render(prev, next, altScreen = false, decstbmSafe = true) {
- if (!this.options.isTTY) {
- return this.renderFullFrame(next);
- }
- const startTime = performance.now();
- const stylePool = this.options.stylePool;
- if (next.viewport.height < prev.viewport.height || prev.viewport.width !== 0 && next.viewport.width !== prev.viewport.width) {
- return fullResetSequence_CAUSES_FLICKER(next, "resize", stylePool);
- }
- let scrollPatch = [];
- if (altScreen && next.scrollHint && decstbmSafe) {
- const { top, bottom, delta } = next.scrollHint;
- if (top >= 0 && bottom < prev.screen.height && bottom < next.screen.height) {
- shiftRows(prev.screen, top, bottom, delta);
- scrollPatch = [
- {
- type: "stdout",
- content: setScrollRegion(top + 1, bottom + 1) + (delta > 0 ? scrollUp(delta) : scrollDown(-delta)) + RESET_SCROLL_REGION + CURSOR_HOME
- }
- ];
- }
- }
- const cursorAtBottom = prev.cursor.y >= prev.screen.height;
- const isGrowing = next.screen.height > prev.screen.height;
- const prevHadScrollback = cursorAtBottom && prev.screen.height >= prev.viewport.height;
- const isShrinking = next.screen.height < prev.screen.height;
- const nextFitsViewport = next.screen.height <= prev.viewport.height;
- if (prevHadScrollback && nextFitsViewport && isShrinking) {
- logForDebugging(`Full reset (shrink->below): prevHeight=${prev.screen.height}, nextHeight=${next.screen.height}, viewport=${prev.viewport.height}`);
- return fullResetSequence_CAUSES_FLICKER(next, "offscreen", stylePool);
- }
- if (prev.screen.height >= prev.viewport.height && prev.screen.height > 0 && cursorAtBottom && !isGrowing) {
- const viewportY2 = prev.screen.height - prev.viewport.height;
- const scrollbackRows = viewportY2 + 1;
- let scrollbackChangeY = -1;
- diffEach(prev.screen, next.screen, (_x, y3) => {
- if (y3 < scrollbackRows) {
- scrollbackChangeY = y3;
- return true;
- }
- });
- if (scrollbackChangeY >= 0) {
- const prevLine = readLine(prev.screen, scrollbackChangeY);
- const nextLine = readLine(next.screen, scrollbackChangeY);
- return fullResetSequence_CAUSES_FLICKER(next, "offscreen", stylePool, {
- triggerY: scrollbackChangeY,
- prevLine,
- nextLine
- });
- }
- }
- const screen = new VirtualScreen(prev.cursor, next.viewport.width);
- const heightDelta = Math.max(next.screen.height, 1) - Math.max(prev.screen.height, 1);
- const shrinking = heightDelta < 0;
- const growing = heightDelta > 0;
- if (shrinking) {
- const linesToClear = prev.screen.height - next.screen.height;
- if (linesToClear > prev.viewport.height) {
- return fullResetSequence_CAUSES_FLICKER(next, "offscreen", this.options.stylePool);
- }
- screen.txn((prev2) => [
- [
- { type: "clear", count: linesToClear },
- { type: "cursorMove", x: 0, y: -1 }
- ],
- { dx: -prev2.x, dy: -linesToClear }
- ]);
- }
- const cursorRestoreScroll = prevHadScrollback ? 1 : 0;
- const viewportY = growing ? Math.max(0, prev.screen.height - prev.viewport.height + cursorRestoreScroll) : Math.max(prev.screen.height, next.screen.height) - next.viewport.height + cursorRestoreScroll;
- let currentStyleId = stylePool.none;
- let currentHyperlink = undefined;
- let needsFullReset = false;
- let resetTriggerY = -1;
- diffEach(prev.screen, next.screen, (x3, y3, removed, added) => {
- if (growing && y3 >= prev.screen.height) {
- return;
- }
- if (added && (added.width === 2 /* SpacerTail */ || added.width === 3 /* SpacerHead */)) {
- return;
- }
- if (removed && (removed.width === 2 /* SpacerTail */ || removed.width === 3 /* SpacerHead */) && !added) {
- return;
- }
- if (added && isEmptyCellAt(next.screen, x3, y3) && !removed) {
- return;
- }
- if (y3 < viewportY) {
- needsFullReset = true;
- resetTriggerY = y3;
- return true;
- }
- moveCursorTo(screen, x3, y3);
- if (added) {
- const targetHyperlink = added.hyperlink;
- currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, targetHyperlink);
- const styleStr = stylePool.transition(currentStyleId, added.styleId);
- if (writeCellWithStyleStr(screen, added, styleStr)) {
- currentStyleId = added.styleId;
- }
- } else if (removed) {
- const styleIdToReset = currentStyleId;
- const hyperlinkToReset = currentHyperlink;
- currentStyleId = stylePool.none;
- currentHyperlink = undefined;
- screen.txn(() => {
- const patches = [];
- transitionStyle(patches, stylePool, styleIdToReset, stylePool.none);
- transitionHyperlink(patches, hyperlinkToReset, undefined);
- patches.push({ type: "stdout", content: " " });
- return [patches, { dx: 1, dy: 0 }];
- });
- }
- });
- if (needsFullReset) {
- return fullResetSequence_CAUSES_FLICKER(next, "offscreen", stylePool, {
- triggerY: resetTriggerY,
- prevLine: readLine(prev.screen, resetTriggerY),
- nextLine: readLine(next.screen, resetTriggerY)
- });
- }
- currentStyleId = transitionStyle(screen.diff, stylePool, currentStyleId, stylePool.none);
- currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, undefined);
- if (growing) {
- renderFrameSlice(screen, next, prev.screen.height, next.screen.height, stylePool);
- }
- if (altScreen) {} else if (next.cursor.y >= next.screen.height) {
- screen.txn((prev2) => {
- const rowsToCreate = next.cursor.y - prev2.y;
- if (rowsToCreate > 0) {
- const patches = new Array(1 + rowsToCreate);
- patches[0] = CARRIAGE_RETURN;
- for (let i5 = 0;i5 < rowsToCreate; i5++) {
- patches[1 + i5] = NEWLINE;
- }
- return [patches, { dx: -prev2.x, dy: rowsToCreate }];
- }
- const dy = next.cursor.y - prev2.y;
- if (dy !== 0 || prev2.x !== next.cursor.x) {
- const patches = [CARRIAGE_RETURN];
- patches.push({ type: "cursorMove", x: next.cursor.x, y: dy });
- return [patches, { dx: next.cursor.x - prev2.x, dy }];
- }
- return [[], { dx: 0, dy: 0 }];
- });
- } else {
- moveCursorTo(screen, next.cursor.x, next.cursor.y);
- }
- const elapsed = performance.now() - startTime;
- if (elapsed > 50) {
- const damage = next.screen.damage;
- const damageInfo = damage ? `${damage.width}x${damage.height} at (${damage.x},${damage.y})` : "none";
- logForDebugging(`Slow render: ${elapsed.toFixed(1)}ms, screen: ${next.screen.height}x${next.screen.width}, damage: ${damageInfo}, changes: ${screen.diff.length}`);
- }
- return scrollPatch.length > 0 ? [...scrollPatch, ...screen.diff] : screen.diff;
- }
-}
-function transitionHyperlink(diff2, current, target) {
- if (current !== target) {
- diff2.push({ type: "hyperlink", uri: target ?? "" });
- return target;
- }
- return current;
-}
-function transitionStyle(diff2, stylePool, currentId, targetId) {
- const str = stylePool.transition(currentId, targetId);
- if (str.length > 0) {
- diff2.push({ type: "styleStr", str });
- }
- return targetId;
-}
-function readLine(screen, y3) {
- let line = "";
- for (let x3 = 0;x3 < screen.width; x3++) {
- line += charInCellAt(screen, x3, y3) ?? " ";
- }
- return line.trimEnd();
-}
-function fullResetSequence_CAUSES_FLICKER(frame, reason, stylePool, debug2) {
- const screen = new VirtualScreen({ x: 0, y: 0 }, frame.viewport.width);
- renderFrame(screen, frame, stylePool);
- return [{ type: "clearTerminal", reason, debug: debug2 }, ...screen.diff];
-}
-function renderFrame(screen, frame, stylePool) {
- renderFrameSlice(screen, frame, 0, frame.screen.height, stylePool);
-}
-function renderFrameSlice(screen, frame, startY, endY, stylePool) {
- let currentStyleId = stylePool.none;
- let currentHyperlink = undefined;
- let lastRenderedStyleId = -1;
- const { width: screenWidth, cells, charPool, hyperlinkPool } = frame.screen;
- let index2 = startY * screenWidth;
- for (let y3 = startY;y3 < endY; y3 += 1) {
- if (screen.cursor.y < y3) {
- const rowsToAdvance = y3 - screen.cursor.y;
- screen.txn((prev) => {
- const patches = new Array(1 + rowsToAdvance);
- patches[0] = CARRIAGE_RETURN;
- for (let i5 = 0;i5 < rowsToAdvance; i5++) {
- patches[1 + i5] = NEWLINE;
- }
- return [patches, { dx: -prev.x, dy: rowsToAdvance }];
- });
- }
- lastRenderedStyleId = -1;
- for (let x3 = 0;x3 < screenWidth; x3 += 1, index2 += 1) {
- const cell = visibleCellAtIndex(cells, charPool, hyperlinkPool, index2, lastRenderedStyleId);
- if (!cell) {
- continue;
- }
- moveCursorTo(screen, x3, y3);
- const targetHyperlink = cell.hyperlink;
- currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, targetHyperlink);
- const styleStr = stylePool.transition(currentStyleId, cell.styleId);
- if (writeCellWithStyleStr(screen, cell, styleStr)) {
- currentStyleId = cell.styleId;
- lastRenderedStyleId = cell.styleId;
- }
- }
- currentStyleId = transitionStyle(screen.diff, stylePool, currentStyleId, stylePool.none);
- currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, undefined);
- screen.txn((prev) => [[CARRIAGE_RETURN, NEWLINE], { dx: -prev.x, dy: 1 }]);
- }
- transitionStyle(screen.diff, stylePool, currentStyleId, stylePool.none);
- transitionHyperlink(screen.diff, currentHyperlink, undefined);
- return screen;
-}
-function writeCellWithStyleStr(screen, cell, styleStr) {
- const cellWidth = cell.width === 1 /* Wide */ ? 2 : 1;
- const px = screen.cursor.x;
- const vw = screen.viewportWidth;
- if (cellWidth === 2 && px < vw) {
- const threshold = cell.char.length > 2 ? vw : vw + 1;
- if (px + 2 >= threshold) {
- return false;
- }
- }
- const diff2 = screen.diff;
- if (styleStr.length > 0) {
- diff2.push({ type: "styleStr", str: styleStr });
- }
- const needsCompensation = cellWidth === 2 && needsWidthCompensation(cell.char);
- if (needsCompensation && px + 1 < vw) {
- diff2.push({ type: "cursorTo", col: px + 2 });
- diff2.push({ type: "stdout", content: " " });
- diff2.push({ type: "cursorTo", col: px + 1 });
- }
- diff2.push({ type: "stdout", content: cell.char });
- if (needsCompensation) {
- diff2.push({ type: "cursorTo", col: px + cellWidth + 1 });
- }
- if (px >= vw) {
- screen.cursor.x = cellWidth;
- screen.cursor.y++;
- } else {
- screen.cursor.x = px + cellWidth;
- }
- return true;
-}
-function moveCursorTo(screen, targetX, targetY) {
- screen.txn((prev) => {
- const dx = targetX - prev.x;
- const dy = targetY - prev.y;
- const inPendingWrap = prev.x >= screen.viewportWidth;
- if (inPendingWrap) {
- return [
- [CARRIAGE_RETURN, { type: "cursorMove", x: targetX, y: dy }],
- { dx, dy }
- ];
- }
- if (dy !== 0) {
- return [
- [CARRIAGE_RETURN, { type: "cursorMove", x: targetX, y: dy }],
- { dx, dy }
- ];
- }
- return [[{ type: "cursorMove", x: dx, y: dy }], { dx, dy }];
- });
-}
-function needsWidthCompensation(char) {
- const cp = char.codePointAt(0);
- if (cp === undefined)
- return false;
- if (cp >= 129648 && cp <= 129791 || cp >= 129792 && cp <= 130047) {
- return true;
- }
- if (char.length >= 2) {
- for (let i5 = 0;i5 < char.length; i5++) {
- if (char.charCodeAt(i5) === 65039)
- return true;
- }
- }
- return false;
-}
-
-class VirtualScreen {
- viewportWidth;
- cursor;
- diff = [];
- constructor(origin2, viewportWidth) {
- this.viewportWidth = viewportWidth;
- this.cursor = { ...origin2 };
- }
- txn(fn) {
- const [patches, next] = fn(this.cursor);
- for (const patch of patches) {
- this.diff.push(patch);
- }
- this.cursor.x += next.dx;
- this.cursor.y += next.dy;
- }
-}
-var CARRIAGE_RETURN, NEWLINE;
-var init_log_update = __esm(() => {
- init_build();
- init_debug();
- init_screen();
- init_csi();
- init_osc();
- CARRIAGE_RETURN = { type: "carriageReturn" };
- NEWLINE = { type: "stdout", content: `
-` };
-});
-
-// src/ink/optimizer.ts
-function optimize(diff2) {
- if (diff2.length <= 1) {
- return diff2;
- }
- const result = [];
- let len = 0;
- for (const patch of diff2) {
- const type = patch.type;
- if (type === "stdout") {
- if (patch.content === "")
- continue;
- } else if (type === "cursorMove") {
- if (patch.x === 0 && patch.y === 0)
- continue;
- } else if (type === "clear") {
- if (patch.count === 0)
- continue;
- }
- if (len > 0) {
- const lastIdx = len - 1;
- const last = result[lastIdx];
- const lastType = last.type;
- if (type === "cursorMove" && lastType === "cursorMove") {
- result[lastIdx] = {
- type: "cursorMove",
- x: last.x + patch.x,
- y: last.y + patch.y
- };
- continue;
- }
- if (type === "cursorTo" && lastType === "cursorTo") {
- result[lastIdx] = patch;
- continue;
- }
- if (type === "styleStr" && lastType === "styleStr") {
- result[lastIdx] = { type: "styleStr", str: last.str + patch.str };
- continue;
- }
- if (type === "hyperlink" && lastType === "hyperlink" && patch.uri === last.uri) {
- continue;
- }
- if (type === "cursorShow" && lastType === "cursorHide" || type === "cursorHide" && lastType === "cursorShow") {
- result.pop();
- len--;
- continue;
- }
- }
- result.push(patch);
- len++;
- }
- return result;
-}
-
-// node_modules/bidi-js/dist/bidi.mjs
-function bidiFactory() {
- var bidi = function(exports) {
- var DATA = {
- R: "13k,1a,2,3,3,2+1j,ch+16,a+1,5+2,2+n,5,a,4,6+16,4+3,h+1b,4mo,179q,2+9,2+11,2i9+7y,2+68,4,3+4,5+13,4+3,2+4k,3+29,8+cf,1t+7z,w+17,3+3m,1t+3z,16o1+5r,8+30,8+mc,29+1r,29+4v,75+73",
- EN: "1c+9,3d+1,6,187+9,513,4+5,7+9,sf+j,175h+9,qw+q,161f+1d,4xt+a,25i+9",
- ES: "17,2,6dp+1,f+1,av,16vr,mx+1,4o,2",
- ET: "z+2,3h+3,b+1,ym,3e+1,2o,p4+1,8,6u,7c,g6,1wc,1n9+4,30+1b,2n,6d,qhx+1,h0m,a+1,49+2,63+1,4+1,6bb+3,12jj",
- AN: "16o+5,2j+9,2+1,35,ed,1ff2+9,87+u",
- CS: "18,2+1,b,2u,12k,55v,l,17v0,2,3,53,2+1,b",
- B: "a,3,f+2,2v,690",
- S: "9,2,k",
- WS: "c,k,4f4,1vk+a,u,1j,335",
- ON: "x+1,4+4,h+5,r+5,r+3,z,5+3,2+1,2+1,5,2+2,3+4,o,w,ci+1,8+d,3+d,6+8,2+g,39+1,9,6+1,2,33,b8,3+1,3c+1,7+1,5r,b,7h+3,sa+5,2,3i+6,jg+3,ur+9,2v,ij+1,9g+9,7+a,8m,4+1,49+x,14u,2+2,c+2,e+2,e+2,e+1,i+n,e+e,2+p,u+2,e+2,36+1,2+3,2+1,b,2+2,6+5,2,2,2,h+1,5+4,6+3,3+f,16+2,5+3l,3+81,1y+p,2+40,q+a,m+13,2r+ch,2+9e,75+hf,3+v,2+2w,6e+5,f+6,75+2a,1a+p,2+2g,d+5x,r+b,6+3,4+o,g,6+1,6+2,2k+1,4,2j,5h+z,1m+1,1e+f,t+2,1f+e,d+3,4o+3,2s+1,w,535+1r,h3l+1i,93+2,2s,b+1,3l+x,2v,4g+3,21+3,kz+1,g5v+1,5a,j+9,n+v,2,3,2+8,2+1,3+2,2,3,46+1,4+4,h+5,r+5,r+a,3h+2,4+6,b+4,78,1r+24,4+c,4,1hb,ey+6,103+j,16j+c,1ux+7,5+g,fsh,jdq+1t,4,57+2e,p1,1m,1m,1m,1m,4kt+1,7j+17,5+2r,d+e,3+e,2+e,2+10,m+4,w,1n+5,1q,4z+5,4b+rb,9+c,4+c,4+37,d+2g,8+b,l+b,5+1j,9+9,7+13,9+t,3+1,27+3c,2+29,2+3q,d+d,3+4,4+2,6+6,a+o,8+6,a+2,e+6,16+42,2+1i",
- BN: "0+8,6+d,2s+5,2+p,e,4m9,1kt+2,2b+5,5+5,17q9+v,7k,6p+8,6+1,119d+3,440+7,96s+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+75,6p+2rz,1ben+1,1ekf+1,1ekf+1",
- NSM: "lc+33,7o+6,7c+18,2,2+1,2+1,2,21+a,1d+k,h,2u+6,3+5,3+1,2+3,10,v+q,2k+a,1n+8,a,p+3,2+8,2+2,2+4,18+2,3c+e,2+v,1k,2,5+7,5,4+6,b+1,u,1n,5+3,9,l+1,r,3+1,1m,5+1,5+1,3+2,4,v+1,4,c+1,1m,5+4,2+1,5,l+1,n+5,2,1n,3,2+3,9,8+1,c+1,v,1q,d,1f,4,1m+2,6+2,2+3,8+1,c+1,u,1n,g+1,l+1,t+1,1m+1,5+3,9,l+1,u,21,8+2,2,2j,3+6,d+7,2r,3+8,c+5,23+1,s,2,2,1k+d,2+4,2+1,6+a,2+z,a,2v+3,2+5,2+1,3+1,q+1,5+2,h+3,e,3+1,7,g,jk+2,qb+2,u+2,u+1,v+1,1t+1,2+6,9,3+a,a,1a+2,3c+1,z,3b+2,5+1,a,7+2,64+1,3,1n,2+6,2,2,3+7,7+9,3,1d+g,1s+3,1d,2+4,2,6,15+8,d+1,x+3,3+1,2+2,1l,2+1,4,2+2,1n+7,3+1,49+2,2+c,2+6,5,7,4+1,5j+1l,2+4,k1+w,2db+2,3y,2p+v,ff+3,30+1,n9x+3,2+9,x+1,29+1,7l,4,5,q+1,6,48+1,r+h,e,13+7,q+a,1b+2,1d,3+3,3+1,14,1w+5,3+1,3+1,d,9,1c,1g,2+2,3+1,6+1,2,17+1,9,6n,3,5,fn5,ki+f,h+f,r2,6b,46+4,1af+2,2+1,6+3,15+2,5,4m+1,fy+3,as+1,4a+a,4x,1j+e,1l+2,1e+3,3+1,1y+2,11+4,2+7,1r,d+1,1h+8,b+3,3,2o+2,3,2+1,7,4h,4+7,m+1,1m+1,4,12+6,4+4,5g+7,3+2,2,o,2d+5,2,5+1,2+1,6n+3,7+1,2+1,s+1,2e+7,3,2+1,2z,2,3+5,2,2u+2,3+3,2+4,78+8,2+1,75+1,2,5,41+3,3+1,5,x+5,3+1,15+5,3+3,9,a+5,3+2,1b+c,2+1,bb+6,2+5,2d+l,3+6,2+1,2+1,3f+5,4,2+1,2+6,2,21+1,4,2,9o+1,f0c+4,1o+6,t5,1s+3,2a,f5l+1,43t+2,i+7,3+6,v+3,45+2,1j0+1i,5+1d,9,f,n+4,2+e,11t+6,2+g,3+6,2+1,2+4,7a+6,c6+3,15t+6,32+6,gzhy+6n",
- AL: "16w,3,2,e+1b,z+2,2+2s,g+1,8+1,b+m,2+t,s+2i,c+e,4h+f,1d+1e,1bwe+dp,3+3z,x+c,2+1,35+3y,2rm+z,5+7,b+5,dt+l,c+u,17nl+27,1t+27,4x+6n,3+d",
- LRO: "6ct",
- RLO: "6cu",
- LRE: "6cq",
- RLE: "6cr",
- PDF: "6cs",
- LRI: "6ee",
- RLI: "6ef",
- FSI: "6eg",
- PDI: "6eh"
- };
- var TYPES = {};
- var TYPES_TO_NAMES = {};
- TYPES.L = 1;
- TYPES_TO_NAMES[1] = "L";
- Object.keys(DATA).forEach(function(type, i5) {
- TYPES[type] = 1 << i5 + 1;
- TYPES_TO_NAMES[TYPES[type]] = type;
- });
- Object.freeze(TYPES);
- var ISOLATE_INIT_TYPES = TYPES.LRI | TYPES.RLI | TYPES.FSI;
- var STRONG_TYPES = TYPES.L | TYPES.R | TYPES.AL;
- var NEUTRAL_ISOLATE_TYPES = TYPES.B | TYPES.S | TYPES.WS | TYPES.ON | TYPES.FSI | TYPES.LRI | TYPES.RLI | TYPES.PDI;
- var BN_LIKE_TYPES = TYPES.BN | TYPES.RLE | TYPES.LRE | TYPES.RLO | TYPES.LRO | TYPES.PDF;
- var TRAILING_TYPES = TYPES.S | TYPES.WS | TYPES.B | ISOLATE_INIT_TYPES | TYPES.PDI | BN_LIKE_TYPES;
- var map7 = null;
- function parseData() {
- if (!map7) {
- map7 = new Map;
- var loop = function(type2) {
- if (DATA.hasOwnProperty(type2)) {
- var lastCode = 0;
- DATA[type2].split(",").forEach(function(range) {
- var ref = range.split("+");
- var skip = ref[0];
- var step = ref[1];
- skip = parseInt(skip, 36);
- step = step ? parseInt(step, 36) : 0;
- map7.set(lastCode += skip, TYPES[type2]);
- for (var i5 = 0;i5 < step; i5++) {
- map7.set(++lastCode, TYPES[type2]);
- }
- });
- }
- };
- for (var type in DATA)
- loop(type);
- }
- }
- function getBidiCharType(char) {
- parseData();
- return map7.get(char.codePointAt(0)) || TYPES.L;
- }
- function getBidiCharTypeName(char) {
- return TYPES_TO_NAMES[getBidiCharType(char)];
- }
- var data$1 = {
- pairs: "14>1,1e>2,u>2,2wt>1,1>1,1ge>1,1wp>1,1j>1,f>1,hm>1,1>1,u>1,u6>1,1>1,+5,28>1,w>1,1>1,+3,b8>1,1>1,+3,1>3,-1>-1,3>1,1>1,+2,1s>1,1>1,x>1,th>1,1>1,+2,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,4q>1,1e>2,u>2,2>1,+1",
- canonical: "6f1>-6dx,6dy>-6dx,6ec>-6ed,6ee>-6ed,6ww>2jj,-2ji>2jj,14r4>-1e7l,1e7m>-1e7l,1e7m>-1e5c,1e5d>-1e5b,1e5c>-14qx,14qy>-14qx,14vn>-1ecg,1ech>-1ecg,1edu>-1ecg,1eci>-1ecg,1eda>-1ecg,1eci>-1ecg,1eci>-168q,168r>-168q,168s>-14ye,14yf>-14ye"
- };
- function parseCharacterMap(encodedString, includeReverse) {
- var radix = 36;
- var lastCode = 0;
- var map8 = new Map;
- var reverseMap = includeReverse && new Map;
- var prevPair;
- encodedString.split(",").forEach(function visit2(entry) {
- if (entry.indexOf("+") !== -1) {
- for (var i5 = +entry;i5--; ) {
- visit2(prevPair);
- }
- } else {
- prevPair = entry;
- var ref = entry.split(">");
- var a5 = ref[0];
- var b4 = ref[1];
- a5 = String.fromCodePoint(lastCode += parseInt(a5, radix));
- b4 = String.fromCodePoint(lastCode += parseInt(b4, radix));
- map8.set(a5, b4);
- includeReverse && reverseMap.set(b4, a5);
- }
- });
- return { map: map8, reverseMap };
- }
- var openToClose, closeToOpen, canonical;
- function parse$1() {
- if (!openToClose) {
- var ref = parseCharacterMap(data$1.pairs, true);
- var map8 = ref.map;
- var reverseMap = ref.reverseMap;
- openToClose = map8;
- closeToOpen = reverseMap;
- canonical = parseCharacterMap(data$1.canonical, false).map;
- }
- }
- function openingToClosingBracket(char) {
- parse$1();
- return openToClose.get(char) || null;
- }
- function closingToOpeningBracket(char) {
- parse$1();
- return closeToOpen.get(char) || null;
- }
- function getCanonicalBracket(char) {
- parse$1();
- return canonical.get(char) || null;
- }
- var TYPE_L = TYPES.L;
- var TYPE_R = TYPES.R;
- var TYPE_EN = TYPES.EN;
- var TYPE_ES = TYPES.ES;
- var TYPE_ET = TYPES.ET;
- var TYPE_AN = TYPES.AN;
- var TYPE_CS = TYPES.CS;
- var TYPE_B = TYPES.B;
- var TYPE_S = TYPES.S;
- var TYPE_ON = TYPES.ON;
- var TYPE_BN = TYPES.BN;
- var TYPE_NSM = TYPES.NSM;
- var TYPE_AL = TYPES.AL;
- var TYPE_LRO = TYPES.LRO;
- var TYPE_RLO = TYPES.RLO;
- var TYPE_LRE = TYPES.LRE;
- var TYPE_RLE = TYPES.RLE;
- var TYPE_PDF = TYPES.PDF;
- var TYPE_LRI = TYPES.LRI;
- var TYPE_RLI = TYPES.RLI;
- var TYPE_FSI = TYPES.FSI;
- var TYPE_PDI = TYPES.PDI;
- function getEmbeddingLevels(string4, baseDirection) {
- var MAX_DEPTH = 125;
- var charTypes = new Uint32Array(string4.length);
- for (var i5 = 0;i5 < string4.length; i5++) {
- charTypes[i5] = getBidiCharType(string4[i5]);
- }
- var charTypeCounts = new Map;
- function changeCharType(i6, type2) {
- var oldType = charTypes[i6];
- charTypes[i6] = type2;
- charTypeCounts.set(oldType, charTypeCounts.get(oldType) - 1);
- if (oldType & NEUTRAL_ISOLATE_TYPES) {
- charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) - 1);
- }
- charTypeCounts.set(type2, (charTypeCounts.get(type2) || 0) + 1);
- if (type2 & NEUTRAL_ISOLATE_TYPES) {
- charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) || 0) + 1);
- }
- }
- var embedLevels = new Uint8Array(string4.length);
- var isolationPairs = new Map;
- var paragraphs = [];
- var paragraph2 = null;
- for (var i$1 = 0;i$1 < string4.length; i$1++) {
- if (!paragraph2) {
- paragraphs.push(paragraph2 = {
- start: i$1,
- end: string4.length - 1,
- level: baseDirection === "rtl" ? 1 : baseDirection === "ltr" ? 0 : determineAutoEmbedLevel(i$1, false)
- });
- }
- if (charTypes[i$1] & TYPE_B) {
- paragraph2.end = i$1;
- paragraph2 = null;
- }
- }
- var FORMATTING_TYPES = TYPE_RLE | TYPE_LRE | TYPE_RLO | TYPE_LRO | ISOLATE_INIT_TYPES | TYPE_PDI | TYPE_PDF | TYPE_B;
- var nextEven = function(n5) {
- return n5 + (n5 & 1 ? 1 : 2);
- };
- var nextOdd = function(n5) {
- return n5 + (n5 & 1 ? 2 : 1);
- };
- for (var paraIdx = 0;paraIdx < paragraphs.length; paraIdx++) {
- paragraph2 = paragraphs[paraIdx];
- var statusStack = [{
- _level: paragraph2.level,
- _override: 0,
- _isolate: 0
- }];
- var stackTop = undefined;
- var overflowIsolateCount = 0;
- var overflowEmbeddingCount = 0;
- var validIsolateCount = 0;
- charTypeCounts.clear();
- for (var i$2 = paragraph2.start;i$2 <= paragraph2.end; i$2++) {
- var charType = charTypes[i$2];
- stackTop = statusStack[statusStack.length - 1];
- charTypeCounts.set(charType, (charTypeCounts.get(charType) || 0) + 1);
- if (charType & NEUTRAL_ISOLATE_TYPES) {
- charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) || 0) + 1);
- }
- if (charType & FORMATTING_TYPES) {
- if (charType & (TYPE_RLE | TYPE_LRE)) {
- embedLevels[i$2] = stackTop._level;
- var level = (charType === TYPE_RLE ? nextOdd : nextEven)(stackTop._level);
- if (level <= MAX_DEPTH && !overflowIsolateCount && !overflowEmbeddingCount) {
- statusStack.push({
- _level: level,
- _override: 0,
- _isolate: 0
- });
- } else if (!overflowIsolateCount) {
- overflowEmbeddingCount++;
- }
- } else if (charType & (TYPE_RLO | TYPE_LRO)) {
- embedLevels[i$2] = stackTop._level;
- var level$1 = (charType === TYPE_RLO ? nextOdd : nextEven)(stackTop._level);
- if (level$1 <= MAX_DEPTH && !overflowIsolateCount && !overflowEmbeddingCount) {
- statusStack.push({
- _level: level$1,
- _override: charType & TYPE_RLO ? TYPE_R : TYPE_L,
- _isolate: 0
- });
- } else if (!overflowIsolateCount) {
- overflowEmbeddingCount++;
- }
- } else if (charType & ISOLATE_INIT_TYPES) {
- if (charType & TYPE_FSI) {
- charType = determineAutoEmbedLevel(i$2 + 1, true) === 1 ? TYPE_RLI : TYPE_LRI;
- }
- embedLevels[i$2] = stackTop._level;
- if (stackTop._override) {
- changeCharType(i$2, stackTop._override);
- }
- var level$2 = (charType === TYPE_RLI ? nextOdd : nextEven)(stackTop._level);
- if (level$2 <= MAX_DEPTH && overflowIsolateCount === 0 && overflowEmbeddingCount === 0) {
- validIsolateCount++;
- statusStack.push({
- _level: level$2,
- _override: 0,
- _isolate: 1,
- _isolInitIndex: i$2
- });
- } else {
- overflowIsolateCount++;
- }
- } else if (charType & TYPE_PDI) {
- if (overflowIsolateCount > 0) {
- overflowIsolateCount--;
- } else if (validIsolateCount > 0) {
- overflowEmbeddingCount = 0;
- while (!statusStack[statusStack.length - 1]._isolate) {
- statusStack.pop();
- }
- var isolInitIndex = statusStack[statusStack.length - 1]._isolInitIndex;
- if (isolInitIndex != null) {
- isolationPairs.set(isolInitIndex, i$2);
- isolationPairs.set(i$2, isolInitIndex);
- }
- statusStack.pop();
- validIsolateCount--;
- }
- stackTop = statusStack[statusStack.length - 1];
- embedLevels[i$2] = stackTop._level;
- if (stackTop._override) {
- changeCharType(i$2, stackTop._override);
- }
- } else if (charType & TYPE_PDF) {
- if (overflowIsolateCount === 0) {
- if (overflowEmbeddingCount > 0) {
- overflowEmbeddingCount--;
- } else if (!stackTop._isolate && statusStack.length > 1) {
- statusStack.pop();
- stackTop = statusStack[statusStack.length - 1];
- }
- }
- embedLevels[i$2] = stackTop._level;
- } else if (charType & TYPE_B) {
- embedLevels[i$2] = paragraph2.level;
- }
- } else {
- embedLevels[i$2] = stackTop._level;
- if (stackTop._override && charType !== TYPE_BN) {
- changeCharType(i$2, stackTop._override);
- }
- }
- }
- var levelRuns = [];
- var currentRun = null;
- for (var i$3 = paragraph2.start;i$3 <= paragraph2.end; i$3++) {
- var charType$1 = charTypes[i$3];
- if (!(charType$1 & BN_LIKE_TYPES)) {
- var lvl = embedLevels[i$3];
- var isIsolInit = charType$1 & ISOLATE_INIT_TYPES;
- var isPDI = charType$1 === TYPE_PDI;
- if (currentRun && lvl === currentRun._level) {
- currentRun._end = i$3;
- currentRun._endsWithIsolInit = isIsolInit;
- } else {
- levelRuns.push(currentRun = {
- _start: i$3,
- _end: i$3,
- _level: lvl,
- _startsWithPDI: isPDI,
- _endsWithIsolInit: isIsolInit
- });
- }
- }
- }
- var isolatingRunSeqs = [];
- for (var runIdx = 0;runIdx < levelRuns.length; runIdx++) {
- var run = levelRuns[runIdx];
- if (!run._startsWithPDI || run._startsWithPDI && !isolationPairs.has(run._start)) {
- var seqRuns = [currentRun = run];
- for (var pdiIndex = undefined;currentRun && currentRun._endsWithIsolInit && (pdiIndex = isolationPairs.get(currentRun._end)) != null; ) {
- for (var i$4 = runIdx + 1;i$4 < levelRuns.length; i$4++) {
- if (levelRuns[i$4]._start === pdiIndex) {
- seqRuns.push(currentRun = levelRuns[i$4]);
- break;
- }
- }
- }
- var seqIndices = [];
- for (var i$5 = 0;i$5 < seqRuns.length; i$5++) {
- var run$1 = seqRuns[i$5];
- for (var j4 = run$1._start;j4 <= run$1._end; j4++) {
- seqIndices.push(j4);
- }
- }
- var firstLevel = embedLevels[seqIndices[0]];
- var prevLevel = paragraph2.level;
- for (var i$6 = seqIndices[0] - 1;i$6 >= 0; i$6--) {
- if (!(charTypes[i$6] & BN_LIKE_TYPES)) {
- prevLevel = embedLevels[i$6];
- break;
- }
- }
- var lastIndex = seqIndices[seqIndices.length - 1];
- var lastLevel = embedLevels[lastIndex];
- var nextLevel = paragraph2.level;
- if (!(charTypes[lastIndex] & ISOLATE_INIT_TYPES)) {
- for (var i$7 = lastIndex + 1;i$7 <= paragraph2.end; i$7++) {
- if (!(charTypes[i$7] & BN_LIKE_TYPES)) {
- nextLevel = embedLevels[i$7];
- break;
- }
- }
- }
- isolatingRunSeqs.push({
- _seqIndices: seqIndices,
- _sosType: Math.max(prevLevel, firstLevel) % 2 ? TYPE_R : TYPE_L,
- _eosType: Math.max(nextLevel, lastLevel) % 2 ? TYPE_R : TYPE_L
- });
- }
- }
- for (var seqIdx = 0;seqIdx < isolatingRunSeqs.length; seqIdx++) {
- var ref = isolatingRunSeqs[seqIdx];
- var seqIndices$1 = ref._seqIndices;
- var sosType = ref._sosType;
- var eosType = ref._eosType;
- var embedDirection = embedLevels[seqIndices$1[0]] & 1 ? TYPE_R : TYPE_L;
- if (charTypeCounts.get(TYPE_NSM)) {
- for (var si = 0;si < seqIndices$1.length; si++) {
- var i$8 = seqIndices$1[si];
- if (charTypes[i$8] & TYPE_NSM) {
- var prevType = sosType;
- for (var sj = si - 1;sj >= 0; sj--) {
- if (!(charTypes[seqIndices$1[sj]] & BN_LIKE_TYPES)) {
- prevType = charTypes[seqIndices$1[sj]];
- break;
- }
- }
- changeCharType(i$8, prevType & (ISOLATE_INIT_TYPES | TYPE_PDI) ? TYPE_ON : prevType);
- }
- }
- }
- if (charTypeCounts.get(TYPE_EN)) {
- for (var si$1 = 0;si$1 < seqIndices$1.length; si$1++) {
- var i$9 = seqIndices$1[si$1];
- if (charTypes[i$9] & TYPE_EN) {
- for (var sj$1 = si$1 - 1;sj$1 >= -1; sj$1--) {
- var prevCharType = sj$1 === -1 ? sosType : charTypes[seqIndices$1[sj$1]];
- if (prevCharType & STRONG_TYPES) {
- if (prevCharType === TYPE_AL) {
- changeCharType(i$9, TYPE_AN);
- }
- break;
- }
- }
- }
- }
- }
- if (charTypeCounts.get(TYPE_AL)) {
- for (var si$2 = 0;si$2 < seqIndices$1.length; si$2++) {
- var i$10 = seqIndices$1[si$2];
- if (charTypes[i$10] & TYPE_AL) {
- changeCharType(i$10, TYPE_R);
- }
- }
- }
- if (charTypeCounts.get(TYPE_ES) || charTypeCounts.get(TYPE_CS)) {
- for (var si$3 = 1;si$3 < seqIndices$1.length - 1; si$3++) {
- var i$11 = seqIndices$1[si$3];
- if (charTypes[i$11] & (TYPE_ES | TYPE_CS)) {
- var prevType$1 = 0, nextType = 0;
- for (var sj$2 = si$3 - 1;sj$2 >= 0; sj$2--) {
- prevType$1 = charTypes[seqIndices$1[sj$2]];
- if (!(prevType$1 & BN_LIKE_TYPES)) {
- break;
- }
- }
- for (var sj$3 = si$3 + 1;sj$3 < seqIndices$1.length; sj$3++) {
- nextType = charTypes[seqIndices$1[sj$3]];
- if (!(nextType & BN_LIKE_TYPES)) {
- break;
- }
- }
- if (prevType$1 === nextType && (charTypes[i$11] === TYPE_ES ? prevType$1 === TYPE_EN : prevType$1 & (TYPE_EN | TYPE_AN))) {
- changeCharType(i$11, prevType$1);
- }
- }
- }
- }
- if (charTypeCounts.get(TYPE_EN)) {
- for (var si$4 = 0;si$4 < seqIndices$1.length; si$4++) {
- var i$12 = seqIndices$1[si$4];
- if (charTypes[i$12] & TYPE_EN) {
- for (var sj$4 = si$4 - 1;sj$4 >= 0 && charTypes[seqIndices$1[sj$4]] & (TYPE_ET | BN_LIKE_TYPES); sj$4--) {
- changeCharType(seqIndices$1[sj$4], TYPE_EN);
- }
- for (si$4++;si$4 < seqIndices$1.length && charTypes[seqIndices$1[si$4]] & (TYPE_ET | BN_LIKE_TYPES | TYPE_EN); si$4++) {
- if (charTypes[seqIndices$1[si$4]] !== TYPE_EN) {
- changeCharType(seqIndices$1[si$4], TYPE_EN);
- }
- }
- }
- }
- }
- if (charTypeCounts.get(TYPE_ET) || charTypeCounts.get(TYPE_ES) || charTypeCounts.get(TYPE_CS)) {
- for (var si$5 = 0;si$5 < seqIndices$1.length; si$5++) {
- var i$13 = seqIndices$1[si$5];
- if (charTypes[i$13] & (TYPE_ET | TYPE_ES | TYPE_CS)) {
- changeCharType(i$13, TYPE_ON);
- for (var sj$5 = si$5 - 1;sj$5 >= 0 && charTypes[seqIndices$1[sj$5]] & BN_LIKE_TYPES; sj$5--) {
- changeCharType(seqIndices$1[sj$5], TYPE_ON);
- }
- for (var sj$6 = si$5 + 1;sj$6 < seqIndices$1.length && charTypes[seqIndices$1[sj$6]] & BN_LIKE_TYPES; sj$6++) {
- changeCharType(seqIndices$1[sj$6], TYPE_ON);
- }
- }
- }
- }
- if (charTypeCounts.get(TYPE_EN)) {
- for (var si$6 = 0, prevStrongType = sosType;si$6 < seqIndices$1.length; si$6++) {
- var i$14 = seqIndices$1[si$6];
- var type = charTypes[i$14];
- if (type & TYPE_EN) {
- if (prevStrongType === TYPE_L) {
- changeCharType(i$14, TYPE_L);
- }
- } else if (type & STRONG_TYPES) {
- prevStrongType = type;
- }
- }
- }
- if (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES)) {
- var R_TYPES_FOR_N_STEPS = TYPE_R | TYPE_EN | TYPE_AN;
- var STRONG_TYPES_FOR_N_STEPS = R_TYPES_FOR_N_STEPS | TYPE_L;
- var bracketPairs = [];
- {
- var openerStack = [];
- for (var si$7 = 0;si$7 < seqIndices$1.length; si$7++) {
- if (charTypes[seqIndices$1[si$7]] & NEUTRAL_ISOLATE_TYPES) {
- var char = string4[seqIndices$1[si$7]];
- var oppositeBracket = undefined;
- if (openingToClosingBracket(char) !== null) {
- if (openerStack.length < 63) {
- openerStack.push({ char, seqIndex: si$7 });
- } else {
- break;
- }
- } else if ((oppositeBracket = closingToOpeningBracket(char)) !== null) {
- for (var stackIdx = openerStack.length - 1;stackIdx >= 0; stackIdx--) {
- var stackChar = openerStack[stackIdx].char;
- if (stackChar === oppositeBracket || stackChar === closingToOpeningBracket(getCanonicalBracket(char)) || openingToClosingBracket(getCanonicalBracket(stackChar)) === char) {
- bracketPairs.push([openerStack[stackIdx].seqIndex, si$7]);
- openerStack.length = stackIdx;
- break;
- }
- }
- }
- }
- }
- bracketPairs.sort(function(a5, b4) {
- return a5[0] - b4[0];
- });
- }
- for (var pairIdx = 0;pairIdx < bracketPairs.length; pairIdx++) {
- var ref$1 = bracketPairs[pairIdx];
- var openSeqIdx = ref$1[0];
- var closeSeqIdx = ref$1[1];
- var foundStrongType = false;
- var useStrongType = 0;
- for (var si$8 = openSeqIdx + 1;si$8 < closeSeqIdx; si$8++) {
- var i$15 = seqIndices$1[si$8];
- if (charTypes[i$15] & STRONG_TYPES_FOR_N_STEPS) {
- foundStrongType = true;
- var lr = charTypes[i$15] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L;
- if (lr === embedDirection) {
- useStrongType = lr;
- break;
- }
- }
- }
- if (foundStrongType && !useStrongType) {
- useStrongType = sosType;
- for (var si$9 = openSeqIdx - 1;si$9 >= 0; si$9--) {
- var i$16 = seqIndices$1[si$9];
- if (charTypes[i$16] & STRONG_TYPES_FOR_N_STEPS) {
- var lr$1 = charTypes[i$16] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L;
- if (lr$1 !== embedDirection) {
- useStrongType = lr$1;
- } else {
- useStrongType = embedDirection;
- }
- break;
- }
- }
- }
- if (useStrongType) {
- charTypes[seqIndices$1[openSeqIdx]] = charTypes[seqIndices$1[closeSeqIdx]] = useStrongType;
- if (useStrongType !== embedDirection) {
- for (var si$10 = openSeqIdx + 1;si$10 < seqIndices$1.length; si$10++) {
- if (!(charTypes[seqIndices$1[si$10]] & BN_LIKE_TYPES)) {
- if (getBidiCharType(string4[seqIndices$1[si$10]]) & TYPE_NSM) {
- charTypes[seqIndices$1[si$10]] = useStrongType;
- }
- break;
- }
- }
- }
- if (useStrongType !== embedDirection) {
- for (var si$11 = closeSeqIdx + 1;si$11 < seqIndices$1.length; si$11++) {
- if (!(charTypes[seqIndices$1[si$11]] & BN_LIKE_TYPES)) {
- if (getBidiCharType(string4[seqIndices$1[si$11]]) & TYPE_NSM) {
- charTypes[seqIndices$1[si$11]] = useStrongType;
- }
- break;
- }
- }
- }
- }
- }
- for (var si$12 = 0;si$12 < seqIndices$1.length; si$12++) {
- if (charTypes[seqIndices$1[si$12]] & NEUTRAL_ISOLATE_TYPES) {
- var niRunStart = si$12, niRunEnd = si$12;
- var prevType$2 = sosType;
- for (var si2 = si$12 - 1;si2 >= 0; si2--) {
- if (charTypes[seqIndices$1[si2]] & BN_LIKE_TYPES) {
- niRunStart = si2;
- } else {
- prevType$2 = charTypes[seqIndices$1[si2]] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L;
- break;
- }
- }
- var nextType$1 = eosType;
- for (var si2$1 = si$12 + 1;si2$1 < seqIndices$1.length; si2$1++) {
- if (charTypes[seqIndices$1[si2$1]] & (NEUTRAL_ISOLATE_TYPES | BN_LIKE_TYPES)) {
- niRunEnd = si2$1;
- } else {
- nextType$1 = charTypes[seqIndices$1[si2$1]] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L;
- break;
- }
- }
- for (var sj$7 = niRunStart;sj$7 <= niRunEnd; sj$7++) {
- charTypes[seqIndices$1[sj$7]] = prevType$2 === nextType$1 ? prevType$2 : embedDirection;
- }
- si$12 = niRunEnd;
- }
- }
- }
- }
- for (var i$17 = paragraph2.start;i$17 <= paragraph2.end; i$17++) {
- var level$3 = embedLevels[i$17];
- var type$1 = charTypes[i$17];
- if (level$3 & 1) {
- if (type$1 & (TYPE_L | TYPE_EN | TYPE_AN)) {
- embedLevels[i$17]++;
- }
- } else {
- if (type$1 & TYPE_R) {
- embedLevels[i$17]++;
- } else if (type$1 & (TYPE_AN | TYPE_EN)) {
- embedLevels[i$17] += 2;
- }
- }
- if (type$1 & BN_LIKE_TYPES) {
- embedLevels[i$17] = i$17 === 0 ? paragraph2.level : embedLevels[i$17 - 1];
- }
- if (i$17 === paragraph2.end || getBidiCharType(string4[i$17]) & (TYPE_S | TYPE_B)) {
- for (var j$1 = i$17;j$1 >= 0 && getBidiCharType(string4[j$1]) & TRAILING_TYPES; j$1--) {
- embedLevels[j$1] = paragraph2.level;
- }
- }
- }
- }
- return {
- levels: embedLevels,
- paragraphs
- };
- function determineAutoEmbedLevel(start, isFSI) {
- for (var i6 = start;i6 < string4.length; i6++) {
- var charType2 = charTypes[i6];
- if (charType2 & (TYPE_R | TYPE_AL)) {
- return 1;
- }
- if (charType2 & (TYPE_B | TYPE_L) || isFSI && charType2 === TYPE_PDI) {
- return 0;
- }
- if (charType2 & ISOLATE_INIT_TYPES) {
- var pdi = indexOfMatchingPDI(i6);
- i6 = pdi === -1 ? string4.length : pdi;
- }
- }
- return 0;
- }
- function indexOfMatchingPDI(isolateStart) {
- var isolationLevel = 1;
- for (var i6 = isolateStart + 1;i6 < string4.length; i6++) {
- var charType2 = charTypes[i6];
- if (charType2 & TYPE_B) {
- break;
- }
- if (charType2 & TYPE_PDI) {
- if (--isolationLevel === 0) {
- return i6;
- }
- } else if (charType2 & ISOLATE_INIT_TYPES) {
- isolationLevel++;
- }
- }
- return -1;
- }
- }
- var data = "14>1,j>2,t>2,u>2,1a>g,2v3>1,1>1,1ge>1,1wd>1,b>1,1j>1,f>1,ai>3,-2>3,+1,8>1k0,-1jq>1y7,-1y6>1hf,-1he>1h6,-1h5>1ha,-1h8>1qi,-1pu>1,6>3u,-3s>7,6>1,1>1,f>1,1>1,+2,3>1,1>1,+13,4>1,1>1,6>1eo,-1ee>1,3>1mg,-1me>1mk,-1mj>1mi,-1mg>1mi,-1md>1,1>1,+2,1>10k,-103>1,1>1,4>1,5>1,1>1,+10,3>1,1>8,-7>8,+1,-6>7,+1,a>1,1>1,u>1,u6>1,1>1,+5,26>1,1>1,2>1,2>2,8>1,7>1,4>1,1>1,+5,b8>1,1>1,+3,1>3,-2>1,2>1,1>1,+2,c>1,3>1,1>1,+2,h>1,3>1,a>1,1>1,2>1,3>1,1>1,d>1,f>1,3>1,1a>1,1>1,6>1,7>1,13>1,k>1,1>1,+19,4>1,1>1,+2,2>1,1>1,+18,m>1,a>1,1>1,lk>1,1>1,4>1,2>1,f>1,3>1,1>1,+3,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,6>1,4j>1,j>2,t>2,u>2,2>1,+1";
- var mirrorMap;
- function parse10() {
- if (!mirrorMap) {
- var ref = parseCharacterMap(data, true);
- var map8 = ref.map;
- var reverseMap = ref.reverseMap;
- reverseMap.forEach(function(value, key) {
- map8.set(key, value);
- });
- mirrorMap = map8;
- }
- }
- function getMirroredCharacter(char) {
- parse10();
- return mirrorMap.get(char) || null;
- }
- function getMirroredCharactersMap(string4, embeddingLevels, start, end) {
- var strLen = string4.length;
- start = Math.max(0, start == null ? 0 : +start);
- end = Math.min(strLen - 1, end == null ? strLen - 1 : +end);
- var map8 = new Map;
- for (var i5 = start;i5 <= end; i5++) {
- if (embeddingLevels[i5] & 1) {
- var mirror = getMirroredCharacter(string4[i5]);
- if (mirror !== null) {
- map8.set(i5, mirror);
- }
- }
- }
- return map8;
- }
- function getReorderSegments(string4, embeddingLevelsResult, start, end) {
- var strLen = string4.length;
- start = Math.max(0, start == null ? 0 : +start);
- end = Math.min(strLen - 1, end == null ? strLen - 1 : +end);
- var segments = [];
- embeddingLevelsResult.paragraphs.forEach(function(paragraph2) {
- var lineStart = Math.max(start, paragraph2.start);
- var lineEnd = Math.min(end, paragraph2.end);
- if (lineStart < lineEnd) {
- var lineLevels = embeddingLevelsResult.levels.slice(lineStart, lineEnd + 1);
- for (var i5 = lineEnd;i5 >= lineStart && getBidiCharType(string4[i5]) & TRAILING_TYPES; i5--) {
- lineLevels[i5] = paragraph2.level;
- }
- var maxLevel = paragraph2.level;
- var minOddLevel = Infinity;
- for (var i$1 = 0;i$1 < lineLevels.length; i$1++) {
- var level = lineLevels[i$1];
- if (level > maxLevel) {
- maxLevel = level;
- }
- if (level < minOddLevel) {
- minOddLevel = level | 1;
- }
- }
- for (var lvl = maxLevel;lvl >= minOddLevel; lvl--) {
- for (var i$2 = 0;i$2 < lineLevels.length; i$2++) {
- if (lineLevels[i$2] >= lvl) {
- var segStart = i$2;
- while (i$2 + 1 < lineLevels.length && lineLevels[i$2 + 1] >= lvl) {
- i$2++;
- }
- if (i$2 > segStart) {
- segments.push([segStart + lineStart, i$2 + lineStart]);
- }
- }
- }
- }
- }
- });
- return segments;
- }
- function getReorderedString(string4, embedLevelsResult, start, end) {
- var indices = getReorderedIndices(string4, embedLevelsResult, start, end);
- var chars = [].concat(string4);
- indices.forEach(function(charIndex, i5) {
- chars[i5] = (embedLevelsResult.levels[charIndex] & 1 ? getMirroredCharacter(string4[charIndex]) : null) || string4[charIndex];
- });
- return chars.join("");
- }
- function getReorderedIndices(string4, embedLevelsResult, start, end) {
- var segments = getReorderSegments(string4, embedLevelsResult, start, end);
- var indices = [];
- for (var i5 = 0;i5 < string4.length; i5++) {
- indices[i5] = i5;
- }
- segments.forEach(function(ref) {
- var start2 = ref[0];
- var end2 = ref[1];
- var slice = indices.slice(start2, end2 + 1);
- for (var i6 = slice.length;i6--; ) {
- indices[end2 - i6] = slice[i6];
- }
- });
- return indices;
- }
- exports.closingToOpeningBracket = closingToOpeningBracket;
- exports.getBidiCharType = getBidiCharType;
- exports.getBidiCharTypeName = getBidiCharTypeName;
- exports.getCanonicalBracket = getCanonicalBracket;
- exports.getEmbeddingLevels = getEmbeddingLevels;
- exports.getMirroredCharacter = getMirroredCharacter;
- exports.getMirroredCharactersMap = getMirroredCharactersMap;
- exports.getReorderSegments = getReorderSegments;
- exports.getReorderedIndices = getReorderedIndices;
- exports.getReorderedString = getReorderedString;
- exports.openingToClosingBracket = openingToClosingBracket;
- Object.defineProperty(exports, "__esModule", { value: true });
- return exports;
- }({});
- return bidi;
-}
-var bidi_default;
-var init_bidi = __esm(() => {
- bidi_default = bidiFactory;
-});
-
-// src/ink/bidi.ts
-function needsBidi() {
- if (needsSoftwareBidi === undefined) {
- needsSoftwareBidi = process.platform === "win32" || typeof process.env["WT_SESSION"] === "string" || process.env["TERM_PROGRAM"] === "vscode";
- }
- return needsSoftwareBidi;
-}
-function getBidi() {
- if (!bidiInstance) {
- bidiInstance = bidi_default();
- }
- return bidiInstance;
-}
-function reorderBidi(characters) {
- if (!needsBidi() || characters.length === 0) {
- return characters;
- }
- const plainText = characters.map((c8) => c8.value).join("");
- if (!hasRTLCharacters(plainText)) {
- return characters;
- }
- const bidi = getBidi();
- const { levels } = bidi.getEmbeddingLevels(plainText, "auto");
- const charLevels = [];
- let offset = 0;
- for (let i5 = 0;i5 < characters.length; i5++) {
- charLevels.push(levels[offset]);
- offset += characters[i5].value.length;
- }
- const reordered = [...characters];
- const maxLevel = Math.max(...charLevels);
- for (let level = maxLevel;level >= 1; level--) {
- let i5 = 0;
- while (i5 < reordered.length) {
- if (charLevels[i5] >= level) {
- let j4 = i5 + 1;
- while (j4 < reordered.length && charLevels[j4] >= level) {
- j4++;
- }
- reverseRange(reordered, i5, j4 - 1);
- reverseRangeNumbers(charLevels, i5, j4 - 1);
- i5 = j4;
- } else {
- i5++;
- }
- }
- }
- return reordered;
-}
-function reverseRange(arr, start, end) {
- while (start < end) {
- const temp = arr[start];
- arr[start] = arr[end];
- arr[end] = temp;
- start++;
- end--;
- }
-}
-function reverseRangeNumbers(arr, start, end) {
- while (start < end) {
- const temp = arr[start];
- arr[start] = arr[end];
- arr[end] = temp;
- start++;
- end--;
- }
-}
-function hasRTLCharacters(text) {
- return /[\u0590-\u05FF\uFB1D-\uFB4F\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF\u0780-\u07BF\u0700-\u074F]/u.test(text);
-}
-var bidiInstance, needsSoftwareBidi;
-var init_bidi2 = __esm(() => {
- init_bidi();
-});
-
-// src/ink/widest-line.ts
-function widestLine(string4) {
- let maxWidth = 0;
- let start = 0;
- while (start <= string4.length) {
- const end = string4.indexOf(`
-`, start);
- const line = end === -1 ? string4.substring(start) : string4.substring(start, end);
- maxWidth = Math.max(maxWidth, lineWidth(line));
- if (end === -1)
- break;
- start = end + 1;
- }
- return maxWidth;
-}
-var init_widest_line = __esm(() => {
- init_line_width_cache();
-});
-
-// src/ink/output.ts
-function intersectClip(parent, child) {
- if (!parent)
- return child;
- return {
- x1: maxDefined(parent.x1, child.x1),
- x2: minDefined(parent.x2, child.x2),
- y1: maxDefined(parent.y1, child.y1),
- y2: minDefined(parent.y2, child.y2)
- };
-}
-function maxDefined(a5, b4) {
- if (a5 === undefined)
- return b4;
- if (b4 === undefined)
- return a5;
- return Math.max(a5, b4);
-}
-function minDefined(a5, b4) {
- if (a5 === undefined)
- return b4;
- if (b4 === undefined)
- return a5;
- return Math.min(a5, b4);
-}
-
-class Output {
- width;
- height;
- stylePool;
- screen;
- operations = [];
- charCache = new Map;
- constructor(options2) {
- const { width, height, stylePool, screen } = options2;
- this.width = width;
- this.height = height;
- this.stylePool = stylePool;
- this.screen = screen;
- resetScreen(screen, width, height);
- }
- reset(width, height, screen) {
- this.width = width;
- this.height = height;
- this.screen = screen;
- this.operations.length = 0;
- resetScreen(screen, width, height);
- if (this.charCache.size > 16384)
- this.charCache.clear();
- }
- blit(src, x3, y3, width, height) {
- this.operations.push({ type: "blit", src, x: x3, y: y3, width, height });
- }
- shift(top, bottom, n5) {
- this.operations.push({ type: "shift", top, bottom, n: n5 });
- }
- clear(region, fromAbsolute) {
- this.operations.push({ type: "clear", region, fromAbsolute });
- }
- noSelect(region) {
- this.operations.push({ type: "noSelect", region });
- }
- write(x3, y3, text, softWrap) {
- if (!text) {
- return;
- }
- this.operations.push({
- type: "write",
- x: x3,
- y: y3,
- text,
- softWrap
- });
- }
- clip(clip) {
- this.operations.push({
- type: "clip",
- clip
- });
- }
- unclip() {
- this.operations.push({
- type: "unclip"
- });
- }
- get() {
- const screen = this.screen;
- const screenWidth = this.width;
- const screenHeight = this.height;
- let blitCells = 0;
- let writeCells = 0;
- const absoluteClears = [];
- for (const operation of this.operations) {
- if (operation.type !== "clear")
- continue;
- const { x: x3, y: y3, width, height } = operation.region;
- const startX = Math.max(0, x3);
- const startY = Math.max(0, y3);
- const maxX = Math.min(x3 + width, screenWidth);
- const maxY = Math.min(y3 + height, screenHeight);
- if (startX >= maxX || startY >= maxY)
- continue;
- const rect = {
- x: startX,
- y: startY,
- width: maxX - startX,
- height: maxY - startY
- };
- screen.damage = screen.damage ? unionRect(screen.damage, rect) : rect;
- if (operation.fromAbsolute)
- absoluteClears.push(rect);
- }
- const clips = [];
- for (const operation of this.operations) {
- switch (operation.type) {
- case "clear":
- continue;
- case "clip":
- clips.push(intersectClip(clips.at(-1), operation.clip));
- continue;
- case "unclip":
- clips.pop();
- continue;
- case "blit": {
- const {
- src,
- x: regionX,
- y: regionY,
- width: regionWidth,
- height: regionHeight
- } = operation;
- const clip = clips.at(-1);
- const startX = Math.max(regionX, clip?.x1 ?? 0);
- const startY = Math.max(regionY, clip?.y1 ?? 0);
- const maxY = Math.min(regionY + regionHeight, screenHeight, src.height, clip?.y2 ?? Infinity);
- const maxX = Math.min(regionX + regionWidth, screenWidth, src.width, clip?.x2 ?? Infinity);
- if (startX >= maxX || startY >= maxY)
- continue;
- if (absoluteClears.length === 0) {
- blitRegion(screen, src, startX, startY, maxX, maxY);
- blitCells += (maxY - startY) * (maxX - startX);
- continue;
- }
- let rowStart = startY;
- for (let row = startY;row <= maxY; row++) {
- const excluded = row < maxY && absoluteClears.some((r4) => row >= r4.y && row < r4.y + r4.height && startX >= r4.x && maxX <= r4.x + r4.width);
- if (excluded || row === maxY) {
- if (row > rowStart) {
- blitRegion(screen, src, startX, rowStart, maxX, row);
- blitCells += (row - rowStart) * (maxX - startX);
- }
- rowStart = row + 1;
- }
- }
- continue;
- }
- case "shift": {
- shiftRows(screen, operation.top, operation.bottom, operation.n);
- continue;
- }
- case "write": {
- const { text, softWrap } = operation;
- let { x: x3, y: y3 } = operation;
- let lines = text.split(`
-`);
- let swFrom = 0;
- let prevContentEnd = 0;
- const clip = clips.at(-1);
- if (clip) {
- const clipHorizontally = typeof clip?.x1 === "number" && typeof clip?.x2 === "number";
- const clipVertically = typeof clip?.y1 === "number" && typeof clip?.y2 === "number";
- if (clipHorizontally) {
- const width = widestLine(text);
- if (x3 + width <= clip.x1 || x3 >= clip.x2) {
- continue;
- }
- }
- if (clipVertically) {
- const height = lines.length;
- if (y3 + height <= clip.y1 || y3 >= clip.y2) {
- continue;
- }
- }
- if (clipHorizontally) {
- lines = lines.map((line) => {
- const from = x3 < clip.x1 ? clip.x1 - x3 : 0;
- const width = stringWidth(line);
- const to = x3 + width > clip.x2 ? clip.x2 - x3 : width;
- let sliced = sliceAnsi(line, from, to);
- if (stringWidth(sliced) > to - from) {
- sliced = sliceAnsi(line, from, to - 1);
- }
- return sliced;
- });
- if (x3 < clip.x1) {
- x3 = clip.x1;
- }
- }
- if (clipVertically) {
- const from = y3 < clip.y1 ? clip.y1 - y3 : 0;
- const height = lines.length;
- const to = y3 + height > clip.y2 ? clip.y2 - y3 : height;
- if (softWrap && from > 0 && softWrap[from] === true) {
- prevContentEnd = x3 + stringWidth(lines[from - 1]);
- }
- lines = lines.slice(from, to);
- swFrom = from;
- if (y3 < clip.y1) {
- y3 = clip.y1;
- }
- }
- }
- const swBits = screen.softWrap;
- let offsetY = 0;
- for (const line of lines) {
- const lineY = y3 + offsetY;
- if (lineY >= screenHeight) {
- break;
- }
- const contentEnd = writeLineToScreen(screen, line, x3, lineY, screenWidth, this.stylePool, this.charCache);
- writeCells += contentEnd - x3;
- if (softWrap) {
- const isSW = softWrap[swFrom + offsetY] === true;
- swBits[lineY] = isSW ? prevContentEnd : 0;
- prevContentEnd = contentEnd;
- }
- offsetY++;
- }
- continue;
- }
- }
- }
- for (const operation of this.operations) {
- if (operation.type === "noSelect") {
- const { x: x3, y: y3, width, height } = operation.region;
- markNoSelectRegion(screen, x3, y3, width, height);
- }
- }
- const totalCells = blitCells + writeCells;
- if (totalCells > 1000 && writeCells > blitCells) {
- logForDebugging(`High write ratio: blit=${blitCells}, write=${writeCells} (${(writeCells / totalCells * 100).toFixed(1)}% writes), screen=${screenHeight}x${screenWidth}`);
- }
- return screen;
- }
-}
-function stylesEqual2(a5, b4) {
- if (a5 === b4)
- return true;
- const len = a5.length;
- if (len !== b4.length)
- return false;
- if (len === 0)
- return true;
- for (let i5 = 0;i5 < len; i5++) {
- if (a5[i5].code !== b4[i5].code)
- return false;
- }
- return true;
-}
-function styledCharsWithGraphemeClustering(chars, stylePool) {
- const charCount = chars.length;
- if (charCount === 0)
- return [];
- const result = [];
- const bufferChars = [];
- let bufferStyles = chars[0].styles;
- for (let i5 = 0;i5 < charCount; i5++) {
- const char = chars[i5];
- const styles5 = char.styles;
- if (bufferChars.length > 0 && !stylesEqual2(styles5, bufferStyles)) {
- flushBuffer(bufferChars.join(""), bufferStyles, stylePool, result);
- bufferChars.length = 0;
- }
- bufferChars.push(char.value);
- bufferStyles = styles5;
- }
- if (bufferChars.length > 0) {
- flushBuffer(bufferChars.join(""), bufferStyles, stylePool, result);
- }
- return result;
-}
-function flushBuffer(buffer, styles5, stylePool, out) {
- const hyperlink = extractHyperlinkFromStyles(styles5) ?? undefined;
- const hasOsc8Styles = hyperlink !== undefined || styles5.some((s4) => s4.code.length >= OSC8_PREFIX.length && s4.code.startsWith(OSC8_PREFIX));
- const filteredStyles = hasOsc8Styles ? filterOutHyperlinkStyles(styles5) : styles5;
- const styleId = stylePool.intern(filteredStyles);
- for (const { segment: grapheme } of getGraphemeSegmenter().segment(buffer)) {
- out.push({
- value: grapheme,
- width: stringWidth(grapheme),
- styleId,
- hyperlink
- });
- }
-}
-function writeLineToScreen(screen, line, x3, y3, screenWidth, stylePool, charCache) {
- let characters = charCache.get(line);
- if (!characters) {
- characters = reorderBidi(styledCharsWithGraphemeClustering(styledCharsFromTokens(tokenize6(line)), stylePool));
- charCache.set(line, characters);
- }
- let offsetX = x3;
- for (let charIdx = 0;charIdx < characters.length; charIdx++) {
- const character = characters[charIdx];
- const codePoint = character.value.codePointAt(0);
- if (codePoint !== undefined && codePoint <= 31) {
- if (codePoint === 9) {
- const tabWidth = 8;
- const spacesToNextStop = tabWidth - offsetX % tabWidth;
- for (let i5 = 0;i5 < spacesToNextStop && offsetX < screenWidth; i5++) {
- setCellAt(screen, offsetX, y3, {
- char: " ",
- styleId: stylePool.none,
- width: 0 /* Narrow */,
- hyperlink: undefined
- });
- offsetX++;
- }
- } else if (codePoint === 27) {
- const nextChar = characters[charIdx + 1]?.value;
- const nextCode = nextChar?.codePointAt(0);
- if (nextChar === "(" || nextChar === ")" || nextChar === "*" || nextChar === "+") {
- charIdx += 2;
- } else if (nextChar === "[") {
- charIdx++;
- while (charIdx < characters.length - 1) {
- charIdx++;
- const c8 = characters[charIdx]?.value.codePointAt(0);
- if (c8 !== undefined && c8 >= 64 && c8 <= 126) {
- break;
- }
- }
- } else if (nextChar === "]" || nextChar === "P" || nextChar === "_" || nextChar === "^" || nextChar === "X") {
- charIdx++;
- while (charIdx < characters.length - 1) {
- charIdx++;
- const c8 = characters[charIdx]?.value;
- if (c8 === "\x07") {
- break;
- }
- if (c8 === "\x1B") {
- const nextC = characters[charIdx + 1]?.value;
- if (nextC === "\\") {
- charIdx++;
- break;
- }
- }
- }
- } else if (nextCode !== undefined && nextCode >= 48 && nextCode <= 126) {
- charIdx++;
- }
- }
- continue;
- }
- const charWidth = character.width;
- if (charWidth === 0) {
- continue;
- }
- const isWideCharacter = charWidth >= 2;
- if (isWideCharacter && offsetX + 2 > screenWidth) {
- setCellAt(screen, offsetX, y3, {
- char: " ",
- styleId: stylePool.none,
- width: 3 /* SpacerHead */,
- hyperlink: undefined
- });
- offsetX++;
- continue;
- }
- setCellAt(screen, offsetX, y3, {
- char: character.value,
- styleId: character.styleId,
- width: isWideCharacter ? 1 /* Wide */ : 0 /* Narrow */,
- hyperlink: character.hyperlink
- });
- offsetX += isWideCharacter ? 2 : 1;
- }
- return offsetX;
-}
-var init_output2 = __esm(() => {
- init_build();
- init_debug();
- init_intl();
- init_sliceAnsi();
- init_bidi2();
- init_geometry();
- init_screen();
- init_stringWidth();
- init_widest_line();
-});
-
-// node_modules/indent-string/index.js
-function indentString(string4, count3 = 1, options2 = {}) {
- const {
- indent = " ",
- includeEmptyLines = false
- } = options2;
- if (typeof string4 !== "string") {
- throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string4}\``);
- }
- if (typeof count3 !== "number") {
- throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count3}\``);
- }
- if (count3 < 0) {
- throw new RangeError(`Expected \`count\` to be at least 0, got \`${count3}\``);
- }
- if (typeof indent !== "string") {
- throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``);
- }
- if (count3 === 0) {
- return string4;
- }
- const regex2 = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
- return string4.replace(regex2, indent.repeat(count3));
-}
-
-// src/ink/get-max-width.ts
-var getMaxWidth = (yogaNode) => {
- return yogaNode.getComputedWidth() - yogaNode.getComputedPadding(LayoutEdge.Left) - yogaNode.getComputedPadding(LayoutEdge.Right) - yogaNode.getComputedBorder(LayoutEdge.Left) - yogaNode.getComputedBorder(LayoutEdge.Right);
-}, get_max_width_default;
-var init_get_max_width = __esm(() => {
- init_node5();
- get_max_width_default = getMaxWidth;
-});
-
-// node_modules/cli-boxes/boxes.json
-var require_boxes = __commonJS((exports, module) => {
- module.exports = {
- single: {
- topLeft: "\u250C",
- top: "\u2500",
- topRight: "\u2510",
- right: "\u2502",
- bottomRight: "\u2518",
- bottom: "\u2500",
- bottomLeft: "\u2514",
- left: "\u2502"
- },
- double: {
- topLeft: "\u2554",
- top: "\u2550",
- topRight: "\u2557",
- right: "\u2551",
- bottomRight: "\u255D",
- bottom: "\u2550",
- bottomLeft: "\u255A",
- left: "\u2551"
- },
- round: {
- topLeft: "\u256D",
- top: "\u2500",
- topRight: "\u256E",
- right: "\u2502",
- bottomRight: "\u256F",
- bottom: "\u2500",
- bottomLeft: "\u2570",
- left: "\u2502"
- },
- bold: {
- topLeft: "\u250F",
- top: "\u2501",
- topRight: "\u2513",
- right: "\u2503",
- bottomRight: "\u251B",
- bottom: "\u2501",
- bottomLeft: "\u2517",
- left: "\u2503"
- },
- singleDouble: {
- topLeft: "\u2553",
- top: "\u2500",
- topRight: "\u2556",
- right: "\u2551",
- bottomRight: "\u255C",
- bottom: "\u2500",
- bottomLeft: "\u2559",
- left: "\u2551"
- },
- doubleSingle: {
- topLeft: "\u2552",
- top: "\u2550",
- topRight: "\u2555",
- right: "\u2502",
- bottomRight: "\u255B",
- bottom: "\u2550",
- bottomLeft: "\u2558",
- left: "\u2502"
- },
- classic: {
- topLeft: "+",
- top: "-",
- topRight: "+",
- right: "|",
- bottomRight: "+",
- bottom: "-",
- bottomLeft: "+",
- left: "|"
- },
- arrow: {
- topLeft: "\u2198",
- top: "\u2193",
- topRight: "\u2199",
- right: "\u2190",
- bottomRight: "\u2196",
- bottom: "\u2191",
- bottomLeft: "\u2197",
- left: "\u2192"
- }
- };
-});
-
-// node_modules/cli-boxes/index.js
-var require_cli_boxes = __commonJS((exports, module) => {
- var cliBoxes = require_boxes();
- module.exports = cliBoxes;
- module.exports.default = cliBoxes;
-});
-
-// src/ink/render-border.ts
-function embedTextInBorder(borderLine, text, align, offset = 0, borderChar) {
- const textLength = stringWidth(text);
- const borderLength = borderLine.length;
- if (textLength >= borderLength - 2) {
- return ["", text.substring(0, borderLength), ""];
- }
- let position2;
- if (align === "center") {
- position2 = Math.floor((borderLength - textLength) / 2);
- } else if (align === "start") {
- position2 = offset + 1;
- } else {
- position2 = borderLength - textLength - offset - 1;
- }
- position2 = Math.max(1, Math.min(position2, borderLength - textLength - 1));
- const before = borderLine.substring(0, 1) + borderChar.repeat(position2 - 1);
- const after = borderChar.repeat(borderLength - position2 - textLength - 1) + borderLine.substring(borderLength - 1);
- return [before, text, after];
-}
-function styleBorderLine(line, color, dim2) {
- let styled = applyColor(line, color);
- if (dim2) {
- styled = source_default.dim(styled);
- }
- return styled;
-}
-var import_cli_boxes, CUSTOM_BORDER_STYLES, renderBorder = (x3, y3, node, output) => {
- if (node.style.borderStyle) {
- const width = Math.floor(node.yogaNode.getComputedWidth());
- const height = Math.floor(node.yogaNode.getComputedHeight());
- const box = typeof node.style.borderStyle === "string" ? CUSTOM_BORDER_STYLES[node.style.borderStyle] ?? import_cli_boxes.default[node.style.borderStyle] : node.style.borderStyle;
- const topBorderColor = node.style.borderTopColor ?? node.style.borderColor;
- const bottomBorderColor = node.style.borderBottomColor ?? node.style.borderColor;
- const leftBorderColor = node.style.borderLeftColor ?? node.style.borderColor;
- const rightBorderColor = node.style.borderRightColor ?? node.style.borderColor;
- const dimTopBorderColor = node.style.borderTopDimColor ?? node.style.borderDimColor;
- const dimBottomBorderColor = node.style.borderBottomDimColor ?? node.style.borderDimColor;
- const dimLeftBorderColor = node.style.borderLeftDimColor ?? node.style.borderDimColor;
- const dimRightBorderColor = node.style.borderRightDimColor ?? node.style.borderDimColor;
- const showTopBorder = node.style.borderTop !== false;
- const showBottomBorder = node.style.borderBottom !== false;
- const showLeftBorder = node.style.borderLeft !== false;
- const showRightBorder = node.style.borderRight !== false;
- const contentWidth = Math.max(0, width - (showLeftBorder ? 1 : 0) - (showRightBorder ? 1 : 0));
- const topBorderLine = showTopBorder ? (showLeftBorder ? box.topLeft : "") + box.top.repeat(contentWidth) + (showRightBorder ? box.topRight : "") : "";
- let topBorder;
- if (showTopBorder && node.style.borderText?.position === "top") {
- const [before, text, after] = embedTextInBorder(topBorderLine, node.style.borderText.content, node.style.borderText.align, node.style.borderText.offset, box.top);
- topBorder = styleBorderLine(before, topBorderColor, dimTopBorderColor) + text + styleBorderLine(after, topBorderColor, dimTopBorderColor);
- } else if (showTopBorder) {
- topBorder = styleBorderLine(topBorderLine, topBorderColor, dimTopBorderColor);
- }
- let verticalBorderHeight = height;
- if (showTopBorder) {
- verticalBorderHeight -= 1;
- }
- if (showBottomBorder) {
- verticalBorderHeight -= 1;
- }
- verticalBorderHeight = Math.max(0, verticalBorderHeight);
- let leftBorder = (applyColor(box.left, leftBorderColor) + `
-`).repeat(verticalBorderHeight);
- if (dimLeftBorderColor) {
- leftBorder = source_default.dim(leftBorder);
- }
- let rightBorder = (applyColor(box.right, rightBorderColor) + `
-`).repeat(verticalBorderHeight);
- if (dimRightBorderColor) {
- rightBorder = source_default.dim(rightBorder);
- }
- const bottomBorderLine = showBottomBorder ? (showLeftBorder ? box.bottomLeft : "") + box.bottom.repeat(contentWidth) + (showRightBorder ? box.bottomRight : "") : "";
- let bottomBorder;
- if (showBottomBorder && node.style.borderText?.position === "bottom") {
- const [before, text, after] = embedTextInBorder(bottomBorderLine, node.style.borderText.content, node.style.borderText.align, node.style.borderText.offset, box.bottom);
- bottomBorder = styleBorderLine(before, bottomBorderColor, dimBottomBorderColor) + text + styleBorderLine(after, bottomBorderColor, dimBottomBorderColor);
- } else if (showBottomBorder) {
- bottomBorder = styleBorderLine(bottomBorderLine, bottomBorderColor, dimBottomBorderColor);
- }
- const offsetY = showTopBorder ? 1 : 0;
- if (topBorder) {
- output.write(x3, y3, topBorder);
- }
- if (showLeftBorder) {
- output.write(x3, y3 + offsetY, leftBorder);
- }
- if (showRightBorder) {
- output.write(x3 + width - 1, y3 + offsetY, rightBorder);
- }
- if (bottomBorder) {
- output.write(x3, y3 + height - 1, bottomBorder);
- }
- }
-}, render_border_default;
-var init_render_border = __esm(() => {
- init_source();
- init_colorize();
- init_stringWidth();
- import_cli_boxes = __toESM(require_cli_boxes(), 1);
- CUSTOM_BORDER_STYLES = {
- dashed: {
- top: "\u254C",
- left: "\u254E",
- right: "\u254E",
- bottom: "\u254C",
- topLeft: " ",
- topRight: " ",
- bottomLeft: " ",
- bottomRight: " "
- }
- };
- render_border_default = renderBorder;
-});
-
-// src/ink/render-node-to-output.ts
-function isXtermJsHost() {
- return process.env.TERM_PROGRAM === "vscode" || isXtermJs();
-}
-function resetLayoutShifted() {
- layoutShifted = false;
-}
-function didLayoutShift() {
- return layoutShifted;
-}
-function resetScrollHint() {
- scrollHint = null;
- absoluteRectsPrev = absoluteRectsCur;
- absoluteRectsCur = [];
-}
-function getScrollHint() {
- return scrollHint;
-}
-function resetScrollDrainNode() {
- scrollDrainNode = null;
-}
-function getScrollDrainNode() {
- return scrollDrainNode;
-}
-function consumeFollowScroll() {
- const f4 = followScroll;
- followScroll = null;
- return f4;
-}
-function drainAdaptive(node, pending, innerHeight) {
- const sign2 = pending > 0 ? 1 : -1;
- let abs = Math.abs(pending);
- let applied = 0;
- if (abs > SCROLL_MAX_PENDING) {
- applied += sign2 * (abs - SCROLL_MAX_PENDING);
- abs = SCROLL_MAX_PENDING;
- }
- const step = abs <= SCROLL_INSTANT_THRESHOLD ? abs : abs < SCROLL_HIGH_PENDING ? SCROLL_STEP_MED : SCROLL_STEP_HIGH;
- applied += sign2 * step;
- const rem = abs - step;
- const cap = Math.max(1, innerHeight - 1);
- const totalAbs = Math.abs(applied);
- if (totalAbs > cap) {
- const excess = totalAbs - cap;
- node.pendingScrollDelta = sign2 * (rem + excess);
- return sign2 * cap;
- }
- node.pendingScrollDelta = rem > 0 ? sign2 * rem : undefined;
- return applied;
-}
-function drainProportional(node, pending, innerHeight) {
- const abs = Math.abs(pending);
- const cap = Math.max(1, innerHeight - 1);
- const step = Math.min(cap, Math.max(SCROLL_MIN_PER_FRAME, abs * 3 >> 2));
- if (abs <= step) {
- node.pendingScrollDelta = undefined;
- return pending;
- }
- const applied = pending > 0 ? step : -step;
- node.pendingScrollDelta = pending - applied;
- return applied;
-}
-function wrapWithOsc8Link(text, url3) {
- return `${OSC2}8;;${url3}${BEL2}${text}${OSC2}8;;${BEL2}`;
-}
-function buildCharToSegmentMap(segments) {
- const map7 = [];
- for (let i5 = 0;i5 < segments.length; i5++) {
- const len = segments[i5].text.length;
- for (let j4 = 0;j4 < len; j4++) {
- map7.push(i5);
- }
- }
- return map7;
-}
-function applyStylesToWrappedText(wrappedPlain, segments, charToSegment, originalPlain, trimEnabled = false) {
- const lines = wrappedPlain.split(`
-`);
- const resultLines = [];
- let charIndex = 0;
- for (let lineIdx = 0;lineIdx < lines.length; lineIdx++) {
- const line = lines[lineIdx];
- if (trimEnabled && line.length > 0) {
- const lineStartsWithWhitespace = /\s/.test(line[0]);
- const originalHasWhitespace = charIndex < originalPlain.length && /\s/.test(originalPlain[charIndex]);
- if (originalHasWhitespace && !lineStartsWithWhitespace) {
- while (charIndex < originalPlain.length && /\s/.test(originalPlain[charIndex])) {
- charIndex++;
- }
- }
- }
- let styledLine = "";
- let runStart = 0;
- let runSegmentIndex = charToSegment[charIndex] ?? 0;
- for (let i5 = 0;i5 < line.length; i5++) {
- const currentSegmentIndex = charToSegment[charIndex] ?? runSegmentIndex;
- if (currentSegmentIndex !== runSegmentIndex) {
- const runText2 = line.slice(runStart, i5);
- const segment2 = segments[runSegmentIndex];
- if (segment2) {
- let styled = applyTextStyles(runText2, segment2.styles);
- if (segment2.hyperlink) {
- styled = wrapWithOsc8Link(styled, segment2.hyperlink);
- }
- styledLine += styled;
- } else {
- styledLine += runText2;
- }
- runStart = i5;
- runSegmentIndex = currentSegmentIndex;
- }
- charIndex++;
- }
- const runText = line.slice(runStart);
- const segment = segments[runSegmentIndex];
- if (segment) {
- let styled = applyTextStyles(runText, segment.styles);
- if (segment.hyperlink) {
- styled = wrapWithOsc8Link(styled, segment.hyperlink);
- }
- styledLine += styled;
- } else {
- styledLine += runText;
- }
- resultLines.push(styledLine);
- if (charIndex < originalPlain.length && originalPlain[charIndex] === `
-`) {
- charIndex++;
- }
- if (trimEnabled && lineIdx < lines.length - 1) {
- const nextLine = lines[lineIdx + 1];
- const nextLineFirstChar = nextLine.length > 0 ? nextLine[0] : null;
- while (charIndex < originalPlain.length && /\s/.test(originalPlain[charIndex])) {
- if (nextLineFirstChar !== null && originalPlain[charIndex] === nextLineFirstChar) {
- break;
- }
- charIndex++;
- }
- }
- }
- return resultLines.join(`
-`);
-}
-function wrapWithSoftWrap(plainText, maxWidth, textWrap) {
- if (textWrap !== "wrap" && textWrap !== "wrap-trim") {
- return {
- wrapped: wrapText2(plainText, maxWidth, textWrap),
- softWrap: undefined
- };
- }
- const origLines = plainText.split(`
-`);
- const outLines = [];
- const softWrap = [];
- for (const orig of origLines) {
- const pieces = wrapText2(orig, maxWidth, textWrap).split(`
-`);
- for (let i5 = 0;i5 < pieces.length; i5++) {
- outLines.push(pieces[i5]);
- softWrap.push(i5 > 0);
- }
- }
- return { wrapped: outLines.join(`
-`), softWrap };
-}
-function applyPaddingToText(node, text, softWrap) {
- const yogaNode = node.childNodes[0]?.yogaNode;
- if (yogaNode) {
- const offsetX = yogaNode.getComputedLeft();
- const offsetY = yogaNode.getComputedTop();
- text = `
-`.repeat(offsetY) + indentString(text, offsetX);
- if (softWrap && offsetY > 0) {
- softWrap.unshift(...Array(offsetY).fill(false));
- }
- }
- return text;
-}
-function renderNodeToOutput(node, output, {
- offsetX = 0,
- offsetY = 0,
- prevScreen,
- skipSelfBlit = false,
- inheritedBackgroundColor
-}) {
- const { yogaNode } = node;
- if (yogaNode) {
- if (yogaNode.getDisplay() === LayoutDisplay.None) {
- if (node.dirty) {
- const cached3 = nodeCache.get(node);
- if (cached3) {
- output.clear({
- x: Math.floor(cached3.x),
- y: Math.floor(cached3.y),
- width: Math.floor(cached3.width),
- height: Math.floor(cached3.height)
- });
- dropSubtreeCache(node);
- layoutShifted = true;
- }
- }
- return;
- }
- const x3 = offsetX + yogaNode.getComputedLeft();
- const yogaTop = yogaNode.getComputedTop();
- let y3 = offsetY + yogaTop;
- const width = yogaNode.getComputedWidth();
- const height = yogaNode.getComputedHeight();
- if (y3 < 0 && node.style.position === "absolute") {
- y3 = 0;
- }
- const cached2 = nodeCache.get(node);
- if (!node.dirty && !skipSelfBlit && node.pendingScrollDelta === undefined && cached2 && cached2.x === x3 && cached2.y === y3 && cached2.width === width && cached2.height === height && prevScreen) {
- const fx = Math.floor(x3);
- const fy = Math.floor(y3);
- const fw = Math.floor(width);
- const fh = Math.floor(height);
- output.blit(prevScreen, fx, fy, fw, fh);
- if (node.style.position === "absolute") {
- absoluteRectsCur.push(cached2);
- }
- blitEscapingAbsoluteDescendants(node, output, prevScreen, fx, fy, fw, fh);
- return;
- }
- const positionChanged = cached2 !== undefined && (cached2.x !== x3 || cached2.y !== y3 || cached2.width !== width || cached2.height !== height);
- if (positionChanged) {
- layoutShifted = true;
- }
- if (cached2 && (node.dirty || positionChanged)) {
- output.clear({
- x: Math.floor(cached2.x),
- y: Math.floor(cached2.y),
- width: Math.floor(cached2.width),
- height: Math.floor(cached2.height)
- }, node.style.position === "absolute");
- }
- const clears = pendingClears.get(node);
- const hasRemovedChild = clears !== undefined;
- if (hasRemovedChild) {
- layoutShifted = true;
- for (const rect2 of clears) {
- output.clear({
- x: Math.floor(rect2.x),
- y: Math.floor(rect2.y),
- width: Math.floor(rect2.width),
- height: Math.floor(rect2.height)
- });
- }
- pendingClears.delete(node);
- }
- if (height === 0 && siblingSharesY(node, yogaNode)) {
- nodeCache.set(node, { x: x3, y: y3, width, height, top: yogaTop });
- node.dirty = false;
- return;
- }
- if (node.nodeName === "ink-raw-ansi") {
- const text = node.attributes["rawText"];
- if (text) {
- output.write(x3, y3, text);
- }
- } else if (node.nodeName === "ink-text") {
- const segments = squashTextNodesToSegments(node, inheritedBackgroundColor ? { backgroundColor: inheritedBackgroundColor } : undefined);
- const plainText = segments.map((s4) => s4.text).join("");
- if (plainText.length > 0) {
- const maxWidth = Math.min(get_max_width_default(yogaNode), output.width - x3);
- const textWrap = node.style.textWrap ?? "wrap";
- const needsWrapping = widestLine(plainText) > maxWidth;
- let text;
- let softWrap;
- if (needsWrapping && segments.length === 1) {
- const segment = segments[0];
- const w2 = wrapWithSoftWrap(plainText, maxWidth, textWrap);
- softWrap = w2.softWrap;
- text = w2.wrapped.split(`
-`).map((line) => {
- let styled = applyTextStyles(line, segment.styles);
- if (segment.hyperlink) {
- styled = wrapWithOsc8Link(styled, segment.hyperlink);
- }
- return styled;
- }).join(`
-`);
- } else if (needsWrapping) {
- const w2 = wrapWithSoftWrap(plainText, maxWidth, textWrap);
- softWrap = w2.softWrap;
- const charToSegment = buildCharToSegmentMap(segments);
- text = applyStylesToWrappedText(w2.wrapped, segments, charToSegment, plainText, textWrap === "wrap-trim");
- } else {
- text = segments.map((segment) => {
- let styledText = applyTextStyles(segment.text, segment.styles);
- if (segment.hyperlink) {
- styledText = wrapWithOsc8Link(styledText, segment.hyperlink);
- }
- return styledText;
- }).join("");
- }
- text = applyPaddingToText(node, text, softWrap);
- output.write(x3, y3, text, softWrap);
- }
- } else if (node.nodeName === "ink-box") {
- const boxBackgroundColor = node.style.backgroundColor ?? inheritedBackgroundColor;
- if (node.style.noSelect) {
- const boxX = Math.floor(x3);
- const fromEdge = node.style.noSelect === "from-left-edge";
- output.noSelect({
- x: fromEdge ? 0 : boxX,
- y: Math.floor(y3),
- width: fromEdge ? boxX + Math.floor(width) : Math.floor(width),
- height: Math.floor(height)
- });
- }
- const overflowX = node.style.overflowX ?? node.style.overflow;
- const overflowY = node.style.overflowY ?? node.style.overflow;
- const clipHorizontally = overflowX === "hidden" || overflowX === "scroll";
- const clipVertically = overflowY === "hidden" || overflowY === "scroll";
- const isScrollY = overflowY === "scroll";
- const needsClip = clipHorizontally || clipVertically;
- let y1;
- let y22;
- if (needsClip) {
- const x1 = clipHorizontally ? x3 + yogaNode.getComputedBorder(LayoutEdge.Left) : undefined;
- const x22 = clipHorizontally ? x3 + yogaNode.getComputedWidth() - yogaNode.getComputedBorder(LayoutEdge.Right) : undefined;
- y1 = clipVertically ? y3 + yogaNode.getComputedBorder(LayoutEdge.Top) : undefined;
- y22 = clipVertically ? y3 + yogaNode.getComputedHeight() - yogaNode.getComputedBorder(LayoutEdge.Bottom) : undefined;
- output.clip({ x1, x2: x22, y1, y2: y22 });
- }
- if (isScrollY) {
- const padTop = yogaNode.getComputedPadding(LayoutEdge.Top);
- const innerHeight = Math.max(0, (y22 ?? y3 + height) - (y1 ?? y3) - padTop - yogaNode.getComputedPadding(LayoutEdge.Bottom));
- const content = node.childNodes.find((c8) => c8.yogaNode);
- const contentYoga = content?.yogaNode;
- const scrollHeight = contentYoga?.getComputedHeight() ?? 0;
- const prevScrollHeight = node.scrollHeight ?? scrollHeight;
- const prevInnerHeight = node.scrollViewportHeight ?? innerHeight;
- node.scrollHeight = scrollHeight;
- node.scrollViewportHeight = innerHeight;
- node.scrollViewportTop = (y1 ?? y3) + padTop;
- const maxScroll = Math.max(0, scrollHeight - innerHeight);
- if (node.scrollAnchor) {
- const anchorTop = node.scrollAnchor.el.yogaNode?.getComputedTop();
- if (anchorTop != null) {
- node.scrollTop = anchorTop + node.scrollAnchor.offset;
- node.pendingScrollDelta = undefined;
- }
- node.scrollAnchor = undefined;
- }
- const scrollTopBeforeFollow = node.scrollTop ?? 0;
- const sticky = node.stickyScroll ?? Boolean(node.attributes["stickyScroll"]);
- const prevMaxScroll = Math.max(0, prevScrollHeight - prevInnerHeight);
- const grew = scrollHeight >= prevScrollHeight;
- const atBottom = sticky || grew && scrollTopBeforeFollow >= prevMaxScroll;
- if (atBottom && (node.pendingScrollDelta ?? 0) >= 0) {
- node.scrollTop = maxScroll;
- node.pendingScrollDelta = undefined;
- if (node.stickyScroll === false && scrollTopBeforeFollow >= prevMaxScroll) {
- node.stickyScroll = true;
- }
- }
- const followDelta = (node.scrollTop ?? 0) - scrollTopBeforeFollow;
- if (followDelta > 0) {
- const vpTop = node.scrollViewportTop ?? 0;
- followScroll = {
- delta: followDelta,
- viewportTop: vpTop,
- viewportBottom: vpTop + innerHeight - 1
- };
- }
- let cur = node.scrollTop ?? 0;
- const pending = node.pendingScrollDelta;
- const cMin = node.scrollClampMin;
- const cMax = node.scrollClampMax;
- const haveClamp = cMin !== undefined && cMax !== undefined;
- if (pending !== undefined && pending !== 0) {
- const pastClamp = haveClamp && (pending < 0 && cur < cMin || pending > 0 && cur > cMax);
- const eff = pastClamp ? Math.min(4, innerHeight >> 3) : innerHeight;
- cur += isXtermJsHost() ? drainAdaptive(node, pending, eff) : drainProportional(node, pending, eff);
- } else if (pending === 0) {
- node.pendingScrollDelta = undefined;
- }
- let scrollTop = Math.max(0, Math.min(cur, maxScroll));
- const clamped = haveClamp ? Math.max(cMin, Math.min(scrollTop, cMax)) : scrollTop;
- node.scrollTop = scrollTop;
- if (scrollTop !== cur)
- node.pendingScrollDelta = undefined;
- if (node.pendingScrollDelta !== undefined)
- scrollDrainNode = node;
- scrollTop = clamped;
- if (content && contentYoga) {
- const contentX = x3 + contentYoga.getComputedLeft();
- const contentY = y3 + contentYoga.getComputedTop() - scrollTop;
- const contentCached = nodeCache.get(content);
- let hint = null;
- if (contentCached && contentCached.y !== contentY) {
- const delta = contentCached.y - contentY;
- const regionTop = Math.floor(y3 + contentYoga.getComputedTop());
- const regionBottom = regionTop + innerHeight - 1;
- if (cached2?.y === y3 && cached2.height === height && innerHeight > 0 && Math.abs(delta) < innerHeight) {
- hint = { top: regionTop, bottom: regionBottom, delta };
- scrollHint = hint;
- } else {
- layoutShifted = true;
- }
- }
- const scrollHeight2 = contentYoga.getComputedHeight();
- const prevHeight = contentCached?.height ?? scrollHeight2;
- const heightDelta = scrollHeight2 - prevHeight;
- const safeForFastPath = !hint || heightDelta === 0 || hint.delta > 0 && heightDelta === hint.delta;
- if (!safeForFastPath)
- scrollHint = null;
- if (hint && prevScreen && safeForFastPath) {
- const { top, bottom, delta } = hint;
- const w2 = Math.floor(width);
- output.blit(prevScreen, Math.floor(x3), top, w2, bottom - top + 1);
- output.shift(top, bottom, delta);
- const edgeTop = delta > 0 ? bottom - delta + 1 : top;
- const edgeBottom = delta > 0 ? bottom : top - delta - 1;
- output.clear({
- x: Math.floor(x3),
- y: edgeTop,
- width: w2,
- height: edgeBottom - edgeTop + 1
- });
- output.clip({
- x1: undefined,
- x2: undefined,
- y1: edgeTop,
- y2: edgeBottom + 1
- });
- const dirtyChildren = content.dirty ? new Set(content.childNodes.filter((c8) => c8.dirty)) : null;
- renderScrolledChildren(content, output, contentX, contentY, hasRemovedChild, undefined, edgeTop - contentY, edgeBottom + 1 - contentY, boxBackgroundColor, true);
- output.unclip();
- if (dirtyChildren) {
- const edgeTopLocal = edgeTop - contentY;
- const edgeBottomLocal = edgeBottom + 1 - contentY;
- const spaces2 = " ".repeat(w2);
- let cumHeightShift = 0;
- for (const childNode of content.childNodes) {
- const childElem = childNode;
- const isDirty = dirtyChildren.has(childNode);
- if (!isDirty && cumHeightShift === 0) {
- if (nodeCache.has(childElem))
- continue;
- }
- const cy = childElem.yogaNode;
- if (!cy)
- continue;
- const childTop = cy.getComputedTop();
- const childH = cy.getComputedHeight();
- const childBottom = childTop + childH;
- if (isDirty) {
- const prev = nodeCache.get(childElem);
- cumHeightShift += childH - (prev ? prev.height : 0);
- }
- if (childBottom <= scrollTop || childTop >= scrollTop + innerHeight)
- continue;
- if (childTop >= edgeTopLocal && childBottom <= edgeBottomLocal)
- continue;
- const screenY = Math.floor(contentY + childTop);
- if (!isDirty) {
- const childCached = nodeCache.get(childElem);
- if (childCached && Math.floor(childCached.y) - delta === screenY) {
- continue;
- }
- }
- const screenBottom = Math.min(Math.floor(contentY + childBottom), Math.floor((y1 ?? y3) + padTop + innerHeight));
- if (screenY < screenBottom) {
- const fill = Array(screenBottom - screenY).fill(spaces2).join(`
-`);
- output.write(Math.floor(x3), screenY, fill);
- output.clip({
- x1: undefined,
- x2: undefined,
- y1: screenY,
- y2: screenBottom
- });
- renderNodeToOutput(childElem, output, {
- offsetX: contentX,
- offsetY: contentY,
- prevScreen: undefined,
- inheritedBackgroundColor: boxBackgroundColor
- });
- output.unclip();
- }
- }
- }
- const spaces = absoluteRectsPrev.length ? " ".repeat(w2) : "";
- for (const r4 of absoluteRectsPrev) {
- if (r4.y >= bottom + 1 || r4.y + r4.height <= top)
- continue;
- const shiftedTop = Math.max(top, Math.floor(r4.y) - delta);
- const shiftedBottom = Math.min(bottom + 1, Math.floor(r4.y + r4.height) - delta);
- if (shiftedTop >= edgeTop && shiftedBottom <= edgeBottom + 1)
- continue;
- if (shiftedTop >= shiftedBottom)
- continue;
- const fill = Array(shiftedBottom - shiftedTop).fill(spaces).join(`
-`);
- output.write(Math.floor(x3), shiftedTop, fill);
- output.clip({
- x1: undefined,
- x2: undefined,
- y1: shiftedTop,
- y2: shiftedBottom
- });
- renderScrolledChildren(content, output, contentX, contentY, hasRemovedChild, undefined, shiftedTop - contentY, shiftedBottom - contentY, boxBackgroundColor, true);
- output.unclip();
- }
- } else {
- const scrolled = contentCached && contentCached.y !== contentY;
- if (scrolled && y1 !== undefined && y22 !== undefined) {
- output.clear({
- x: Math.floor(x3),
- y: Math.floor(y1),
- width: Math.floor(width),
- height: Math.floor(y22 - y1)
- });
- }
- renderScrolledChildren(content, output, contentX, contentY, hasRemovedChild, scrolled || positionChanged ? undefined : prevScreen, scrollTop, scrollTop + innerHeight, boxBackgroundColor);
- }
- nodeCache.set(content, {
- x: contentX,
- y: contentY,
- width: contentYoga.getComputedWidth(),
- height: contentYoga.getComputedHeight()
- });
- content.dirty = false;
- }
- } else {
- const ownBackgroundColor = node.style.backgroundColor;
- if (ownBackgroundColor || node.style.opaque) {
- const borderLeft = yogaNode.getComputedBorder(LayoutEdge.Left);
- const borderRight = yogaNode.getComputedBorder(LayoutEdge.Right);
- const borderTop = yogaNode.getComputedBorder(LayoutEdge.Top);
- const borderBottom = yogaNode.getComputedBorder(LayoutEdge.Bottom);
- const innerWidth = Math.floor(width) - borderLeft - borderRight;
- const innerHeight = Math.floor(height) - borderTop - borderBottom;
- if (innerWidth > 0 && innerHeight > 0) {
- const spaces = " ".repeat(innerWidth);
- const fillLine = ownBackgroundColor ? applyTextStyles(spaces, { backgroundColor: ownBackgroundColor }) : spaces;
- const fill = Array(innerHeight).fill(fillLine).join(`
-`);
- output.write(x3 + borderLeft, y3 + borderTop, fill);
- }
- }
- renderChildren(node, output, x3, y3, hasRemovedChild, ownBackgroundColor || node.style.opaque ? undefined : prevScreen, boxBackgroundColor);
- }
- if (needsClip) {
- output.unclip();
- }
- render_border_default(x3, y3, node, output);
- } else if (node.nodeName === "ink-root") {
- renderChildren(node, output, x3, y3, hasRemovedChild, prevScreen, inheritedBackgroundColor);
- }
- const rect = { x: x3, y: y3, width, height, top: yogaTop };
- nodeCache.set(node, rect);
- if (node.style.position === "absolute") {
- absoluteRectsCur.push(rect);
- }
- node.dirty = false;
- }
-}
-function renderChildren(node, output, offsetX, offsetY, hasRemovedChild, prevScreen, inheritedBackgroundColor) {
- let seenDirtyChild = false;
- let seenDirtyClipped = false;
- for (const childNode of node.childNodes) {
- const childElem = childNode;
- const wasDirty = childElem.dirty;
- const isAbsolute5 = childElem.style.position === "absolute";
- renderNodeToOutput(childElem, output, {
- offsetX,
- offsetY,
- prevScreen: hasRemovedChild || seenDirtyChild ? undefined : prevScreen,
- skipSelfBlit: seenDirtyClipped && isAbsolute5 && !childElem.style.opaque && childElem.style.backgroundColor === undefined,
- inheritedBackgroundColor
- });
- if (wasDirty && !seenDirtyChild) {
- if (!clipsBothAxes(childElem) || isAbsolute5) {
- seenDirtyChild = true;
- } else {
- seenDirtyClipped = true;
- }
- }
- }
-}
-function clipsBothAxes(node) {
- const ox = node.style.overflowX ?? node.style.overflow;
- const oy = node.style.overflowY ?? node.style.overflow;
- return (ox === "hidden" || ox === "scroll") && (oy === "hidden" || oy === "scroll");
-}
-function siblingSharesY(node, yogaNode) {
- const parent = node.parentNode;
- if (!parent)
- return false;
- const myTop = yogaNode.getComputedTop();
- const siblings = parent.childNodes;
- const idx = siblings.indexOf(node);
- for (let i5 = idx + 1;i5 < siblings.length; i5++) {
- const sib = siblings[i5].yogaNode;
- if (!sib)
- continue;
- return sib.getComputedTop() === myTop;
- }
- for (let i5 = idx - 1;i5 >= 0; i5--) {
- const sib = siblings[i5].yogaNode;
- if (!sib)
- continue;
- return sib.getComputedTop() === myTop;
- }
- return false;
-}
-function blitEscapingAbsoluteDescendants(node, output, prevScreen, px, py, pw, ph) {
- const pr = px + pw;
- const pb = py + ph;
- for (const child of node.childNodes) {
- if (child.nodeName === "#text")
- continue;
- const elem = child;
- if (elem.style.position === "absolute") {
- const cached2 = nodeCache.get(elem);
- if (cached2) {
- absoluteRectsCur.push(cached2);
- const cx = Math.floor(cached2.x);
- const cy = Math.floor(cached2.y);
- const cw = Math.floor(cached2.width);
- const ch = Math.floor(cached2.height);
- if (cx < px || cy < py || cx + cw > pr || cy + ch > pb) {
- output.blit(prevScreen, cx, cy, cw, ch);
- }
- }
- }
- blitEscapingAbsoluteDescendants(elem, output, prevScreen, px, py, pw, ph);
- }
-}
-function renderScrolledChildren(node, output, offsetX, offsetY, hasRemovedChild, prevScreen, scrollTopY, scrollBottomY, inheritedBackgroundColor, preserveCulledCache = false) {
- let seenDirtyChild = false;
- let cumHeightShift = 0;
- for (const childNode of node.childNodes) {
- const childElem = childNode;
- const cy = childElem.yogaNode;
- if (cy) {
- const cached2 = nodeCache.get(childElem);
- let top;
- let height;
- if (cached2?.top !== undefined && !childElem.dirty && cumHeightShift === 0) {
- top = cached2.top;
- height = cached2.height;
- } else {
- top = cy.getComputedTop();
- height = cy.getComputedHeight();
- if (childElem.dirty) {
- cumHeightShift += height - (cached2 ? cached2.height : 0);
- }
- if (cached2)
- cached2.top = top;
- }
- const bottom = top + height;
- if (bottom <= scrollTopY || top >= scrollBottomY) {
- if (!preserveCulledCache)
- dropSubtreeCache(childElem);
- continue;
- }
- }
- const wasDirty = childElem.dirty;
- renderNodeToOutput(childElem, output, {
- offsetX,
- offsetY,
- prevScreen: hasRemovedChild || seenDirtyChild ? undefined : prevScreen,
- inheritedBackgroundColor
- });
- if (wasDirty) {
- seenDirtyChild = true;
- }
- }
-}
-function dropSubtreeCache(node) {
- nodeCache.delete(node);
- for (const child of node.childNodes) {
- if (child.nodeName !== "#text") {
- dropSubtreeCache(child);
- }
- }
-}
-var layoutShifted = false, scrollHint = null, absoluteRectsPrev, absoluteRectsCur, scrollDrainNode = null, followScroll = null, SCROLL_MIN_PER_FRAME = 4, SCROLL_INSTANT_THRESHOLD = 5, SCROLL_HIGH_PENDING = 12, SCROLL_STEP_MED = 2, SCROLL_STEP_HIGH = 3, SCROLL_MAX_PENDING = 30, OSC2 = "\x1B]", BEL2 = "\x07", render_node_to_output_default;
-var init_render_node_to_output = __esm(() => {
- init_colorize();
- init_get_max_width();
- init_node5();
- init_node_cache();
- init_render_border();
- init_squash_text_nodes();
- init_terminal();
- init_widest_line();
- init_wrap_text();
- absoluteRectsPrev = [];
- absoluteRectsCur = [];
- render_node_to_output_default = renderNodeToOutput;
-});
-
-// src/ink/render-to-screen.ts
-function scanPositions(screen, query) {
- const lq = query.toLowerCase();
- if (!lq)
- return [];
- const qlen = lq.length;
- const w2 = screen.width;
- const h5 = screen.height;
- const noSelect = screen.noSelect;
- const positions = [];
- const t0 = performance.now();
- for (let row = 0;row < h5; row++) {
- const rowOff = row * w2;
- let text = "";
- const colOf = [];
- const codeUnitToCell = [];
- for (let col = 0;col < w2; col++) {
- const idx = rowOff + col;
- const cell = cellAtIndex(screen, idx);
- if (cell.width === 2 /* SpacerTail */ || cell.width === 3 /* SpacerHead */ || noSelect[idx] === 1) {
- continue;
- }
- const lc = cell.char.toLowerCase();
- const cellIdx = colOf.length;
- for (let i5 = 0;i5 < lc.length; i5++) {
- codeUnitToCell.push(cellIdx);
- }
- text += lc;
- colOf.push(col);
- }
- let pos = text.indexOf(lq);
- while (pos >= 0) {
- const startCi = codeUnitToCell[pos];
- const endCi = codeUnitToCell[pos + qlen - 1];
- const col = colOf[startCi];
- const endCol = colOf[endCi] + 1;
- positions.push({ row, col, len: endCol - col });
- pos = text.indexOf(lq, pos + qlen);
- }
- }
- timing.scan += performance.now() - t0;
- return positions;
-}
-function applyPositionedHighlight(screen, stylePool, positions, rowOffset, currentIdx) {
- if (currentIdx < 0 || currentIdx >= positions.length)
- return false;
- const p4 = positions[currentIdx];
- const row = p4.row + rowOffset;
- if (row < 0 || row >= screen.height)
- return false;
- const transform2 = (id) => stylePool.withCurrentMatch(id);
- const rowOff = row * screen.width;
- for (let col = p4.col;col < p4.col + p4.len; col++) {
- if (col < 0 || col >= screen.width)
- continue;
- const cell = cellAtIndex(screen, rowOff + col);
- setCellStyleId(screen, col, row, transform2(cell.styleId));
- }
- return true;
-}
-var import_constants43, timing;
-var init_render_to_screen = __esm(() => {
- init_debug();
- init_dom();
- init_focus();
- init_output2();
- init_reconciler();
- init_render_node_to_output();
- init_screen();
- import_constants43 = __toESM(require_constants5(), 1);
- timing = { reconcile: 0, yoga: 0, paint: 0, scan: 0, calls: 0 };
-});
-
-// src/ink/renderer.ts
-function createRenderer(node, stylePool) {
- let output;
- return (options2) => {
- const { frontFrame, backFrame, isTTY, terminalWidth, terminalRows } = options2;
- const prevScreen = frontFrame.screen;
- const backScreen = backFrame.screen;
- const charPool = backScreen.charPool;
- const hyperlinkPool = backScreen.hyperlinkPool;
- const computedHeight = node.yogaNode?.getComputedHeight();
- const computedWidth = node.yogaNode?.getComputedWidth();
- const hasInvalidHeight = computedHeight === undefined || !Number.isFinite(computedHeight) || computedHeight < 0;
- const hasInvalidWidth = computedWidth === undefined || !Number.isFinite(computedWidth) || computedWidth < 0;
- if (!node.yogaNode || hasInvalidHeight || hasInvalidWidth) {
- if (node.yogaNode && (hasInvalidHeight || hasInvalidWidth)) {
- logForDebugging(`Invalid yoga dimensions: width=${computedWidth}, height=${computedHeight}, ` + `childNodes=${node.childNodes.length}, terminalWidth=${terminalWidth}, terminalRows=${terminalRows}`);
- }
- return {
- screen: createScreen(terminalWidth, 0, stylePool, charPool, hyperlinkPool),
- viewport: { width: terminalWidth, height: terminalRows },
- cursor: { x: 0, y: 0, visible: true }
- };
- }
- const width = Math.floor(node.yogaNode.getComputedWidth());
- const yogaHeight = Math.floor(node.yogaNode.getComputedHeight());
- const height = options2.altScreen ? terminalRows : yogaHeight;
- if (options2.altScreen && yogaHeight > terminalRows) {
- logForDebugging(`alt-screen: yoga height ${yogaHeight} > terminalRows ${terminalRows} \u2014 ` + `something is rendering outside . Overflow clipped.`, { level: "warn" });
- }
- const screen = backScreen ?? createScreen(width, height, stylePool, charPool, hyperlinkPool);
- if (output) {
- output.reset(width, height, screen);
- } else {
- output = new Output({ width, height, stylePool, screen });
- }
- resetLayoutShifted();
- resetScrollHint();
- resetScrollDrainNode();
- const absoluteRemoved = consumeAbsoluteRemovedFlag();
- render_node_to_output_default(node, output, {
- prevScreen: absoluteRemoved || options2.prevFrameContaminated ? undefined : prevScreen
- });
- const renderedScreen = output.get();
- const drainNode = getScrollDrainNode();
- if (drainNode)
- markDirty(drainNode);
- return {
- scrollHint: options2.altScreen ? getScrollHint() : null,
- scrollDrainPending: drainNode !== null,
- screen: renderedScreen,
- viewport: {
- width: terminalWidth,
- height: options2.altScreen ? terminalRows + 1 : terminalRows
- },
- cursor: {
- x: 0,
- y: options2.altScreen ? Math.max(0, Math.min(screen.height, terminalRows) - 1) : screen.height,
- visible: !isTTY || screen.height === 0
- }
- };
- };
-}
-var init_renderer = __esm(() => {
- init_debug();
- init_dom();
- init_node_cache();
- init_output2();
- init_render_node_to_output();
- init_screen();
-});
-
-// src/ink/searchHighlight.ts
-function applySearchHighlight(screen, query, stylePool) {
- if (!query)
- return false;
- const lq = query.toLowerCase();
- const qlen = lq.length;
- const w2 = screen.width;
- const noSelect = screen.noSelect;
- const height = screen.height;
- let applied = false;
- for (let row = 0;row < height; row++) {
- const rowOff = row * w2;
- let text = "";
- const colOf = [];
- const codeUnitToCell = [];
- for (let col = 0;col < w2; col++) {
- const idx = rowOff + col;
- const cell = cellAtIndex(screen, idx);
- if (cell.width === 2 /* SpacerTail */ || cell.width === 3 /* SpacerHead */ || noSelect[idx] === 1) {
- continue;
- }
- const lc = cell.char.toLowerCase();
- const cellIdx = colOf.length;
- for (let i5 = 0;i5 < lc.length; i5++) {
- codeUnitToCell.push(cellIdx);
- }
- text += lc;
- colOf.push(col);
- }
- let pos = text.indexOf(lq);
- while (pos >= 0) {
- applied = true;
- const startCi = codeUnitToCell[pos];
- const endCi = codeUnitToCell[pos + qlen - 1];
- for (let ci = startCi;ci <= endCi; ci++) {
- const col = colOf[ci];
- const cell = cellAtIndex(screen, rowOff + col);
- setCellStyleId(screen, col, row, stylePool.withInverse(cell.styleId));
- }
- pos = text.indexOf(lq, pos + qlen);
- }
- }
- return applied;
-}
-var init_searchHighlight = __esm(() => {
- init_screen();
-});
-
-// src/ink/useTerminalNotification.ts
-function useTerminalNotification() {
- const writeRaw = import_react11.useContext(TerminalWriteContext);
- if (!writeRaw) {
- throw new Error("useTerminalNotification must be used within TerminalWriteProvider");
- }
- const notifyITerm2 = import_react11.useCallback(({ message, title }) => {
- const displayString = title ? `${title}:
-${message}` : message;
- writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, `
-
-${displayString}`)));
- }, [writeRaw]);
- const notifyKitty = import_react11.useCallback(({
- message,
- title,
- id
- }) => {
- writeRaw(wrapForMultiplexer(osc(OSC.KITTY, `i=${id}:d=0:p=title`, title)));
- writeRaw(wrapForMultiplexer(osc(OSC.KITTY, `i=${id}:p=body`, message)));
- writeRaw(wrapForMultiplexer(osc(OSC.KITTY, `i=${id}:d=1:a=focus`, "")));
- }, [writeRaw]);
- const notifyGhostty = import_react11.useCallback(({ message, title }) => {
- writeRaw(wrapForMultiplexer(osc(OSC.GHOSTTY, "notify", title, message)));
- }, [writeRaw]);
- const notifyBell = import_react11.useCallback(() => {
- writeRaw(BEL);
- }, [writeRaw]);
- const progress = import_react11.useCallback((state3, percentage) => {
- if (!isProgressReportingAvailable()) {
- return;
- }
- if (!state3) {
- writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, ITERM2.PROGRESS, PROGRESS.CLEAR, "")));
- return;
- }
- const pct = Math.max(0, Math.min(100, Math.round(percentage ?? 0)));
- switch (state3) {
- case "completed":
- writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, ITERM2.PROGRESS, PROGRESS.CLEAR, "")));
- break;
- case "error":
- writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, ITERM2.PROGRESS, PROGRESS.ERROR, pct)));
- break;
- case "indeterminate":
- writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, ITERM2.PROGRESS, PROGRESS.INDETERMINATE, "")));
- break;
- case "running":
- writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, ITERM2.PROGRESS, PROGRESS.SET, pct)));
- break;
- case null:
- break;
- }
- }, [writeRaw]);
- return import_react11.useMemo(() => ({ notifyITerm2, notifyKitty, notifyGhostty, notifyBell, progress }), [notifyITerm2, notifyKitty, notifyGhostty, notifyBell, progress]);
-}
-var import_react11, TerminalWriteContext, TerminalWriteProvider;
-var init_useTerminalNotification = __esm(() => {
- init_terminal();
- init_ansi();
- init_osc();
- import_react11 = __toESM(require_react(), 1);
- TerminalWriteContext = import_react11.createContext(null);
- TerminalWriteProvider = TerminalWriteContext.Provider;
-});
-
-// src/ink/ink.tsx
-import { closeSync as closeSync3, constants as fsConstants3, openSync as openSync3, readSync as readSync2, writeSync } from "fs";
-import { format as format3 } from "util";
-function makeAltScreenParkPatch(terminalRows) {
- return Object.freeze({
- type: "stdout",
- content: cursorPosition(terminalRows, 1)
- });
-}
-
-class Ink {
- options;
- log;
- terminal;
- scheduleRender;
- isUnmounted = false;
- isPaused = false;
- container;
- rootNode;
- focusManager;
- renderer;
- stylePool;
- charPool;
- hyperlinkPool;
- exitPromise;
- restoreConsole;
- restoreStderr;
- unsubscribeTTYHandlers;
- terminalColumns;
- terminalRows;
- currentNode = null;
- frontFrame;
- backFrame;
- lastPoolResetTime = performance.now();
- drainTimer = null;
- lastYogaCounters = {
- ms: 0,
- visited: 0,
- measured: 0,
- cacheHits: 0,
- live: 0
- };
- altScreenParkPatch;
- selection = createSelectionState();
- searchHighlightQuery = "";
- searchPositions = null;
- selectionListeners = new Set;
- hoveredNodes = new Set;
- altScreenActive = false;
- altScreenMouseTracking = false;
- prevFrameContaminated = false;
- needsEraseBeforePaint = false;
- cursorDeclaration = null;
- displayCursor = null;
- constructor(options2) {
- this.options = options2;
- autoBind(this);
- if (this.options.patchConsole) {
- this.restoreConsole = this.patchConsole();
- this.restoreStderr = this.patchStderr();
- }
- this.terminal = {
- stdout: options2.stdout,
- stderr: options2.stderr
- };
- this.terminalColumns = options2.stdout.columns || 80;
- this.terminalRows = options2.stdout.rows || 24;
- this.altScreenParkPatch = makeAltScreenParkPatch(this.terminalRows);
- this.stylePool = new StylePool;
- this.charPool = new CharPool;
- this.hyperlinkPool = new HyperlinkPool;
- this.frontFrame = emptyFrame(this.terminalRows, this.terminalColumns, this.stylePool, this.charPool, this.hyperlinkPool);
- this.backFrame = emptyFrame(this.terminalRows, this.terminalColumns, this.stylePool, this.charPool, this.hyperlinkPool);
- this.log = new LogUpdate({
- isTTY: options2.stdout.isTTY || false,
- stylePool: this.stylePool
- });
- const deferredRender = () => queueMicrotask(this.onRender);
- this.scheduleRender = throttle_default2(deferredRender, FRAME_INTERVAL_MS, {
- leading: true,
- trailing: true
- });
- this.isUnmounted = false;
- this.unsubscribeExit = onExit(this.unmount, {
- alwaysLast: false
- });
- if (options2.stdout.isTTY) {
- options2.stdout.on("resize", this.handleResize);
- process.on("SIGCONT", this.handleResume);
- this.unsubscribeTTYHandlers = () => {
- options2.stdout.off("resize", this.handleResize);
- process.off("SIGCONT", this.handleResume);
- };
- }
- this.rootNode = createNode("ink-root");
- this.focusManager = new FocusManager((target, event) => dispatcher.dispatchDiscrete(target, event));
- this.rootNode.focusManager = this.focusManager;
- this.renderer = createRenderer(this.rootNode, this.stylePool);
- this.rootNode.onRender = this.scheduleRender;
- this.rootNode.onImmediateRender = this.onRender;
- this.rootNode.onComputeLayout = () => {
- if (this.isUnmounted) {
- return;
- }
- if (this.rootNode.yogaNode) {
- const t0 = performance.now();
- this.rootNode.yogaNode.setWidth(this.terminalColumns);
- this.rootNode.yogaNode.calculateLayout(this.terminalColumns);
- const ms = performance.now() - t0;
- recordYogaMs(ms);
- const c8 = getYogaCounters();
- this.lastYogaCounters = {
- ms,
- ...c8
- };
- }
- };
- this.container = reconciler_default.createContainer(this.rootNode, import_constants44.ConcurrentRoot, null, false, null, "id", noop_default, noop_default, noop_default, noop_default);
- if (false) {}
- }
- handleResume = () => {
- if (!this.options.stdout.isTTY) {
- return;
- }
- if (this.altScreenActive) {
- this.reenterAltScreen();
- return;
- }
- this.frontFrame = emptyFrame(this.frontFrame.viewport.height, this.frontFrame.viewport.width, this.stylePool, this.charPool, this.hyperlinkPool);
- this.backFrame = emptyFrame(this.backFrame.viewport.height, this.backFrame.viewport.width, this.stylePool, this.charPool, this.hyperlinkPool);
- this.log.reset();
- this.displayCursor = null;
- };
- handleResize = () => {
- const cols = this.options.stdout.columns || 80;
- const rows = this.options.stdout.rows || 24;
- if (cols === this.terminalColumns && rows === this.terminalRows)
- return;
- this.terminalColumns = cols;
- this.terminalRows = rows;
- this.altScreenParkPatch = makeAltScreenParkPatch(this.terminalRows);
- if (this.altScreenActive && !this.isPaused && this.options.stdout.isTTY) {
- if (this.altScreenMouseTracking) {
- this.options.stdout.write(ENABLE_MOUSE_TRACKING);
- }
- this.resetFramesForAltScreen();
- this.needsEraseBeforePaint = true;
- }
- if (this.currentNode !== null) {
- this.render(this.currentNode);
- }
- };
- resolveExitPromise = () => {};
- rejectExitPromise = () => {};
- unsubscribeExit = () => {};
- enterAlternateScreen() {
- this.pause();
- this.suspendStdin();
- this.options.stdout.write(DISABLE_KITTY_KEYBOARD + DISABLE_MODIFY_OTHER_KEYS + (this.altScreenMouseTracking ? DISABLE_MOUSE_TRACKING : "") + (this.altScreenActive ? "" : "\x1B[?1049h") + "\x1B[?1004l" + "\x1B[0m" + "\x1B[?25h" + "\x1B[2J" + "\x1B[H");
- }
- exitAlternateScreen() {
- this.options.stdout.write((this.altScreenActive ? ENTER_ALT_SCREEN : "") + "\x1B[2J" + "\x1B[H" + (this.altScreenMouseTracking ? ENABLE_MOUSE_TRACKING : "") + (this.altScreenActive ? "" : "\x1B[?1049l") + "\x1B[?25l");
- this.resumeStdin();
- if (this.altScreenActive) {
- this.resetFramesForAltScreen();
- } else {
- this.repaint();
- }
- this.resume();
- this.options.stdout.write("\x1B[?1004h" + (supportsExtendedKeys() ? DISABLE_KITTY_KEYBOARD + ENABLE_KITTY_KEYBOARD + ENABLE_MODIFY_OTHER_KEYS : ""));
- }
- onRender() {
- if (this.isUnmounted || this.isPaused) {
- return;
- }
- if (this.drainTimer !== null) {
- clearTimeout(this.drainTimer);
- this.drainTimer = null;
- }
- flushInteractionTime();
- const renderStart = performance.now();
- const terminalWidth = this.options.stdout.columns || 80;
- const terminalRows = this.options.stdout.rows || 24;
- const frame = this.renderer({
- frontFrame: this.frontFrame,
- backFrame: this.backFrame,
- isTTY: this.options.stdout.isTTY,
- terminalWidth,
- terminalRows,
- altScreen: this.altScreenActive,
- prevFrameContaminated: this.prevFrameContaminated
- });
- const rendererMs = performance.now() - renderStart;
- const follow = consumeFollowScroll();
- if (follow && this.selection.anchor && this.selection.anchor.row >= follow.viewportTop && this.selection.anchor.row <= follow.viewportBottom) {
- const {
- delta,
- viewportTop,
- viewportBottom
- } = follow;
- if (this.selection.isDragging) {
- if (hasSelection(this.selection)) {
- captureScrolledRows(this.selection, this.frontFrame.screen, viewportTop, viewportTop + delta - 1, "above");
- }
- shiftAnchor(this.selection, -delta, viewportTop, viewportBottom);
- } else if (!this.selection.focus || this.selection.focus.row >= viewportTop && this.selection.focus.row <= viewportBottom) {
- if (hasSelection(this.selection)) {
- captureScrolledRows(this.selection, this.frontFrame.screen, viewportTop, viewportTop + delta - 1, "above");
- }
- const cleared = shiftSelectionForFollow(this.selection, -delta, viewportTop, viewportBottom);
- if (cleared)
- for (const cb of this.selectionListeners)
- cb();
- }
- }
- let selActive = false;
- let hlActive = false;
- if (this.altScreenActive) {
- selActive = hasSelection(this.selection);
- if (selActive) {
- applySelectionOverlay(frame.screen, this.selection, this.stylePool);
- }
- hlActive = applySearchHighlight(frame.screen, this.searchHighlightQuery, this.stylePool);
- if (this.searchPositions) {
- const sp = this.searchPositions;
- const posApplied = applyPositionedHighlight(frame.screen, this.stylePool, sp.positions, sp.rowOffset, sp.currentIdx);
- hlActive = hlActive || posApplied;
- }
- }
- if (didLayoutShift() || selActive || hlActive || this.prevFrameContaminated) {
- frame.screen.damage = {
- x: 0,
- y: 0,
- width: frame.screen.width,
- height: frame.screen.height
- };
- }
- let prevFrame = this.frontFrame;
- if (this.altScreenActive) {
- prevFrame = {
- ...this.frontFrame,
- cursor: ALT_SCREEN_ANCHOR_CURSOR
- };
- }
- const tDiff = performance.now();
- const diff2 = this.log.render(prevFrame, frame, this.altScreenActive, SYNC_OUTPUT_SUPPORTED);
- const diffMs = performance.now() - tDiff;
- this.backFrame = this.frontFrame;
- this.frontFrame = frame;
- if (renderStart - this.lastPoolResetTime > 5 * 60 * 1000) {
- this.resetPools();
- this.lastPoolResetTime = renderStart;
- }
- const flickers = [];
- for (const patch of diff2) {
- if (patch.type === "clearTerminal") {
- flickers.push({
- desiredHeight: frame.screen.height,
- availableHeight: frame.viewport.height,
- reason: patch.reason
- });
- if (isDebugRepaintsEnabled() && patch.debug) {
- const chain4 = findOwnerChainAtRow(this.rootNode, patch.debug.triggerY);
- logForDebugging(`[REPAINT] full reset \xB7 ${patch.reason} \xB7 row ${patch.debug.triggerY}
-` + ` prev: "${patch.debug.prevLine}"
-` + ` next: "${patch.debug.nextLine}"
-` + ` culprit: ${chain4.length ? chain4.join(" < ") : "(no owner chain captured)"}`, {
- level: "warn"
- });
- }
- }
- }
- const tOptimize = performance.now();
- const optimized = optimize(diff2);
- const optimizeMs = performance.now() - tOptimize;
- const hasDiff = optimized.length > 0;
- if (this.altScreenActive && hasDiff) {
- if (this.needsEraseBeforePaint) {
- this.needsEraseBeforePaint = false;
- optimized.unshift(ERASE_THEN_HOME_PATCH);
- } else {
- optimized.unshift(CURSOR_HOME_PATCH);
- }
- optimized.push(this.altScreenParkPatch);
- }
- const decl = this.cursorDeclaration;
- const rect = decl !== null ? nodeCache.get(decl.node) : undefined;
- const target = decl !== null && rect !== undefined ? {
- x: rect.x + decl.relativeX,
- y: rect.y + decl.relativeY
- } : null;
- const parked = this.displayCursor;
- const targetMoved = target !== null && (parked === null || parked.x !== target.x || parked.y !== target.y);
- if (hasDiff || targetMoved || target === null && parked !== null) {
- if (parked !== null && !this.altScreenActive && hasDiff) {
- const pdx = prevFrame.cursor.x - parked.x;
- const pdy = prevFrame.cursor.y - parked.y;
- if (pdx !== 0 || pdy !== 0) {
- optimized.unshift({
- type: "stdout",
- content: cursorMove(pdx, pdy)
- });
- }
- }
- if (target !== null) {
- if (this.altScreenActive) {
- const row = Math.min(Math.max(target.y + 1, 1), terminalRows);
- const col = Math.min(Math.max(target.x + 1, 1), terminalWidth);
- optimized.push({
- type: "stdout",
- content: cursorPosition(row, col)
- });
- } else {
- const from = !hasDiff && parked !== null ? parked : {
- x: frame.cursor.x,
- y: frame.cursor.y
- };
- const dx = target.x - from.x;
- const dy = target.y - from.y;
- if (dx !== 0 || dy !== 0) {
- optimized.push({
- type: "stdout",
- content: cursorMove(dx, dy)
- });
- }
- }
- this.displayCursor = target;
- } else {
- if (parked !== null && !this.altScreenActive && !hasDiff) {
- const rdx = frame.cursor.x - parked.x;
- const rdy = frame.cursor.y - parked.y;
- if (rdx !== 0 || rdy !== 0) {
- optimized.push({
- type: "stdout",
- content: cursorMove(rdx, rdy)
- });
- }
- }
- this.displayCursor = null;
- }
- }
- const tWrite = performance.now();
- writeDiffToTerminal(this.terminal, optimized, this.altScreenActive && !SYNC_OUTPUT_SUPPORTED);
- const writeMs = performance.now() - tWrite;
- this.prevFrameContaminated = selActive || hlActive;
- if (frame.scrollDrainPending) {
- this.drainTimer = setTimeout(() => this.onRender(), FRAME_INTERVAL_MS >> 2);
- }
- const yogaMs = getLastYogaMs();
- const commitMs = getLastCommitMs();
- const yc = this.lastYogaCounters;
- resetProfileCounters();
- this.lastYogaCounters = {
- ms: 0,
- visited: 0,
- measured: 0,
- cacheHits: 0,
- live: 0
- };
- this.options.onFrame?.({
- durationMs: performance.now() - renderStart,
- phases: {
- renderer: rendererMs,
- diff: diffMs,
- optimize: optimizeMs,
- write: writeMs,
- patches: diff2.length,
- yoga: yogaMs,
- commit: commitMs,
- yogaVisited: yc.visited,
- yogaMeasured: yc.measured,
- yogaCacheHits: yc.cacheHits,
- yogaLive: yc.live
- },
- flickers
- });
- }
- pause() {
- reconciler_default.flushSyncFromReconciler();
- this.onRender();
- this.isPaused = true;
- }
- resume() {
- this.isPaused = false;
- this.onRender();
- }
- repaint() {
- this.frontFrame = emptyFrame(this.frontFrame.viewport.height, this.frontFrame.viewport.width, this.stylePool, this.charPool, this.hyperlinkPool);
- this.backFrame = emptyFrame(this.backFrame.viewport.height, this.backFrame.viewport.width, this.stylePool, this.charPool, this.hyperlinkPool);
- this.log.reset();
- this.displayCursor = null;
- }
- forceRedraw() {
- if (!this.options.stdout.isTTY || this.isUnmounted || this.isPaused)
- return;
- this.options.stdout.write(ERASE_SCREEN + CURSOR_HOME);
- if (this.altScreenActive) {
- this.resetFramesForAltScreen();
- } else {
- this.repaint();
- this.prevFrameContaminated = true;
- }
- this.onRender();
- }
- invalidatePrevFrame() {
- this.prevFrameContaminated = true;
- }
- setAltScreenActive(active, mouseTracking = false) {
- if (this.altScreenActive === active)
- return;
- this.altScreenActive = active;
- this.altScreenMouseTracking = active && mouseTracking;
- if (active) {
- this.resetFramesForAltScreen();
- } else {
- this.repaint();
- }
- }
- get isAltScreenActive() {
- return this.altScreenActive;
- }
- reassertTerminalModes = (includeAltScreen = false) => {
- if (!this.options.stdout.isTTY)
- return;
- if (this.isPaused)
- return;
- if (supportsExtendedKeys()) {
- this.options.stdout.write(DISABLE_KITTY_KEYBOARD + ENABLE_KITTY_KEYBOARD + ENABLE_MODIFY_OTHER_KEYS);
- }
- if (!this.altScreenActive)
- return;
- if (this.altScreenMouseTracking) {
- this.options.stdout.write(ENABLE_MOUSE_TRACKING);
- }
- if (includeAltScreen) {
- this.reenterAltScreen();
- }
- };
- detachForShutdown() {
- this.isUnmounted = true;
- this.scheduleRender.cancel?.();
- const stdin = this.options.stdin;
- this.drainStdin();
- if (stdin.isTTY && stdin.isRaw && stdin.setRawMode) {
- stdin.setRawMode(false);
- }
- }
- drainStdin() {
- drainStdin(this.options.stdin);
- }
- reenterAltScreen() {
- this.options.stdout.write(ENTER_ALT_SCREEN + ERASE_SCREEN + CURSOR_HOME + (this.altScreenMouseTracking ? ENABLE_MOUSE_TRACKING : ""));
- this.resetFramesForAltScreen();
- }
- resetFramesForAltScreen() {
- const rows = this.terminalRows;
- const cols = this.terminalColumns;
- const blank = () => ({
- screen: createScreen(cols, rows, this.stylePool, this.charPool, this.hyperlinkPool),
- viewport: {
- width: cols,
- height: rows + 1
- },
- cursor: {
- x: 0,
- y: 0,
- visible: true
- }
- });
- this.frontFrame = blank();
- this.backFrame = blank();
- this.log.reset();
- this.displayCursor = null;
- this.prevFrameContaminated = true;
- }
- copySelectionNoClear() {
- if (!hasSelection(this.selection))
- return "";
- const text = getSelectedText(this.selection, this.frontFrame.screen);
- if (text) {
- setClipboard(text).then((raw) => {
- if (raw)
- this.options.stdout.write(raw);
- });
- }
- return text;
- }
- copySelection() {
- if (!hasSelection(this.selection))
- return "";
- const text = this.copySelectionNoClear();
- clearSelection(this.selection);
- this.notifySelectionChange();
- return text;
- }
- clearTextSelection() {
- if (!hasSelection(this.selection))
- return;
- clearSelection(this.selection);
- this.notifySelectionChange();
- }
- setSearchHighlight(query) {
- if (this.searchHighlightQuery === query)
- return;
- this.searchHighlightQuery = query;
- this.scheduleRender();
- }
- scanElementSubtree(el) {
- if (!this.searchHighlightQuery || !el.yogaNode)
- return [];
- const width = Math.ceil(el.yogaNode.getComputedWidth());
- const height = Math.ceil(el.yogaNode.getComputedHeight());
- if (width <= 0 || height <= 0)
- return [];
- const elLeft = el.yogaNode.getComputedLeft();
- const elTop = el.yogaNode.getComputedTop();
- const screen = createScreen(width, height, this.stylePool, this.charPool, this.hyperlinkPool);
- const output = new Output({
- width,
- height,
- stylePool: this.stylePool,
- screen
- });
- render_node_to_output_default(el, output, {
- offsetX: -elLeft,
- offsetY: -elTop,
- prevScreen: undefined
- });
- const rendered = output.get();
- markDirty(el);
- const positions = scanPositions(rendered, this.searchHighlightQuery);
- logForDebugging(`scanElementSubtree: q='${this.searchHighlightQuery}' ` + `el=${width}x${height}@(${elLeft},${elTop}) n=${positions.length} ` + `[${positions.slice(0, 10).map((p4) => `${p4.row}:${p4.col}`).join(",")}` + `${positions.length > 10 ? ",\u2026" : ""}]`);
- return positions;
- }
- setSearchPositions(state3) {
- this.searchPositions = state3;
- this.scheduleRender();
- }
- setSelectionBgColor(color) {
- const wrapped = colorize("\x00", color, "background");
- const nul = wrapped.indexOf("\x00");
- if (nul <= 0 || nul === wrapped.length - 1) {
- this.stylePool.setSelectionBg(null);
- return;
- }
- this.stylePool.setSelectionBg({
- type: "ansi",
- code: wrapped.slice(0, nul),
- endCode: wrapped.slice(nul + 1)
- });
- }
- captureScrolledRows(firstRow, lastRow, side) {
- captureScrolledRows(this.selection, this.frontFrame.screen, firstRow, lastRow, side);
- }
- shiftSelectionForScroll(dRow, minRow, maxRow) {
- const hadSel = hasSelection(this.selection);
- shiftSelection(this.selection, dRow, minRow, maxRow, this.frontFrame.screen.width);
- if (hadSel && !hasSelection(this.selection)) {
- this.notifySelectionChange();
- }
- }
- moveSelectionFocus(move) {
- if (!this.altScreenActive)
- return;
- const {
- focus
- } = this.selection;
- if (!focus)
- return;
- const {
- width,
- height
- } = this.frontFrame.screen;
- const maxCol = width - 1;
- const maxRow = height - 1;
- let {
- col,
- row
- } = focus;
- switch (move) {
- case "left":
- if (col > 0)
- col--;
- else if (row > 0) {
- col = maxCol;
- row--;
- }
- break;
- case "right":
- if (col < maxCol)
- col++;
- else if (row < maxRow) {
- col = 0;
- row++;
- }
- break;
- case "up":
- if (row > 0)
- row--;
- break;
- case "down":
- if (row < maxRow)
- row++;
- break;
- case "lineStart":
- col = 0;
- break;
- case "lineEnd":
- col = maxCol;
- break;
- }
- if (col === focus.col && row === focus.row)
- return;
- moveFocus(this.selection, col, row);
- this.notifySelectionChange();
- }
- hasTextSelection() {
- return hasSelection(this.selection);
- }
- subscribeToSelectionChange(cb) {
- this.selectionListeners.add(cb);
- return () => this.selectionListeners.delete(cb);
- }
- notifySelectionChange() {
- this.onRender();
- for (const cb of this.selectionListeners)
- cb();
- }
- dispatchClick(col, row) {
- if (!this.altScreenActive)
- return false;
- const blank = isEmptyCellAt(this.frontFrame.screen, col, row);
- return dispatchClick(this.rootNode, col, row, blank);
- }
- dispatchHover(col, row) {
- if (!this.altScreenActive)
- return;
- dispatchHover(this.rootNode, col, row, this.hoveredNodes);
- }
- dispatchKeyboardEvent(parsedKey) {
- const target = this.focusManager.activeElement ?? this.rootNode;
- const event = new KeyboardEvent(parsedKey);
- dispatcher.dispatchDiscrete(target, event);
- if (!event.defaultPrevented && parsedKey.name === "tab" && !parsedKey.ctrl && !parsedKey.meta) {
- if (parsedKey.shift) {
- this.focusManager.focusPrevious(this.rootNode);
- } else {
- this.focusManager.focusNext(this.rootNode);
- }
- }
- }
- getHyperlinkAt(col, row) {
- if (!this.altScreenActive)
- return;
- const screen = this.frontFrame.screen;
- const cell = cellAt(screen, col, row);
- let url3 = cell?.hyperlink;
- if (!url3 && cell?.width === 2 /* SpacerTail */ && col > 0) {
- url3 = cellAt(screen, col - 1, row)?.hyperlink;
- }
- return url3 ?? findPlainTextUrlAt(screen, col, row);
- }
- onHyperlinkClick;
- openHyperlink(url3) {
- this.onHyperlinkClick?.(url3);
- }
- handleMultiClick(col, row, count3) {
- if (!this.altScreenActive)
- return;
- const screen = this.frontFrame.screen;
- startSelection(this.selection, col, row);
- if (count3 === 2)
- selectWordAt(this.selection, screen, col, row);
- else
- selectLineAt(this.selection, screen, row);
- if (!this.selection.focus)
- this.selection.focus = this.selection.anchor;
- this.notifySelectionChange();
- }
- handleSelectionDrag(col, row) {
- if (!this.altScreenActive)
- return;
- const sel = this.selection;
- if (sel.anchorSpan) {
- extendSelection(sel, this.frontFrame.screen, col, row);
- } else {
- updateSelection(sel, col, row);
- }
- this.notifySelectionChange();
- }
- stdinListeners = [];
- wasRawMode = false;
- suspendStdin() {
- const stdin = this.options.stdin;
- if (!stdin.isTTY) {
- return;
- }
- const readableListeners = stdin.listeners("readable");
- logForDebugging(`[stdin] suspendStdin: removing ${readableListeners.length} readable listener(s), wasRawMode=${stdin.isRaw ?? false}`);
- readableListeners.forEach((listener) => {
- this.stdinListeners.push({
- event: "readable",
- listener
- });
- stdin.removeListener("readable", listener);
- });
- const stdinWithRaw = stdin;
- if (stdinWithRaw.isRaw && stdinWithRaw.setRawMode) {
- stdinWithRaw.setRawMode(false);
- this.wasRawMode = true;
- }
- }
- resumeStdin() {
- const stdin = this.options.stdin;
- if (!stdin.isTTY) {
- return;
- }
- if (this.stdinListeners.length === 0 && !this.wasRawMode) {
- logForDebugging("[stdin] resumeStdin: called with no stored listeners and wasRawMode=false (possible desync)", {
- level: "warn"
- });
- }
- logForDebugging(`[stdin] resumeStdin: re-attaching ${this.stdinListeners.length} listener(s), wasRawMode=${this.wasRawMode}`);
- this.stdinListeners.forEach(({
- event,
- listener
- }) => {
- stdin.addListener(event, listener);
- });
- this.stdinListeners = [];
- if (this.wasRawMode) {
- const stdinWithRaw = stdin;
- if (stdinWithRaw.setRawMode) {
- stdinWithRaw.setRawMode(true);
- }
- this.wasRawMode = false;
- }
- }
- writeRaw(data) {
- this.options.stdout.write(data);
- }
- setCursorDeclaration = (decl, clearIfNode) => {
- if (decl === null && clearIfNode !== undefined && this.cursorDeclaration?.node !== clearIfNode) {
- return;
- }
- this.cursorDeclaration = decl;
- };
- render(node) {
- this.currentNode = node;
- const tree = /* @__PURE__ */ jsx_dev_runtime8.jsxDEV(App, {
- stdin: this.options.stdin,
- stdout: this.options.stdout,
- stderr: this.options.stderr,
- exitOnCtrlC: this.options.exitOnCtrlC,
- onExit: this.unmount,
- terminalColumns: this.terminalColumns,
- terminalRows: this.terminalRows,
- selection: this.selection,
- onSelectionChange: this.notifySelectionChange,
- onClickAt: this.dispatchClick,
- onHoverAt: this.dispatchHover,
- getHyperlinkAt: this.getHyperlinkAt,
- onOpenHyperlink: this.openHyperlink,
- onMultiClick: this.handleMultiClick,
- onSelectionDrag: this.handleSelectionDrag,
- onStdinResume: this.reassertTerminalModes,
- onCursorDeclaration: this.setCursorDeclaration,
- dispatchKeyboardEvent: this.dispatchKeyboardEvent,
- children: /* @__PURE__ */ jsx_dev_runtime8.jsxDEV(TerminalWriteProvider, {
- value: this.writeRaw,
- children: node
- }, undefined, false, undefined, this)
- }, undefined, false, undefined, this);
- reconciler_default.updateContainerSync(tree, this.container, null, noop_default);
- reconciler_default.flushSyncWork();
- }
- unmount(error46) {
- if (this.isUnmounted) {
- return;
- }
- this.onRender();
- this.unsubscribeExit();
- if (typeof this.restoreConsole === "function") {
- this.restoreConsole();
- }
- this.restoreStderr?.();
- this.unsubscribeTTYHandlers?.();
- const diff2 = this.log.renderPreviousOutput_DEPRECATED(this.frontFrame);
- writeDiffToTerminal(this.terminal, optimize(diff2));
- if (this.options.stdout.isTTY) {
- if (this.altScreenActive) {
- writeSync(1, EXIT_ALT_SCREEN);
- }
- writeSync(1, DISABLE_MOUSE_TRACKING);
- this.drainStdin();
- writeSync(1, DISABLE_MODIFY_OTHER_KEYS);
- writeSync(1, DISABLE_KITTY_KEYBOARD);
- writeSync(1, DFE);
- writeSync(1, DBP);
- writeSync(1, SHOW_CURSOR);
- writeSync(1, CLEAR_ITERM2_PROGRESS);
- if (supportsTabStatus())
- writeSync(1, wrapForMultiplexer(CLEAR_TAB_STATUS));
- }
- this.isUnmounted = true;
- this.scheduleRender.cancel?.();
- if (this.drainTimer !== null) {
- clearTimeout(this.drainTimer);
- this.drainTimer = null;
- }
- reconciler_default.updateContainerSync(null, this.container, null, noop_default);
- reconciler_default.flushSyncWork();
- instances_default.delete(this.options.stdout);
- this.rootNode.yogaNode?.free();
- this.rootNode.yogaNode = undefined;
- if (error46 instanceof Error) {
- this.rejectExitPromise(error46);
- } else {
- this.resolveExitPromise();
- }
- }
- async waitUntilExit() {
- this.exitPromise ||= new Promise((resolve9, reject) => {
- this.resolveExitPromise = resolve9;
- this.rejectExitPromise = reject;
- });
- return this.exitPromise;
- }
- resetLineCount() {
- if (this.options.stdout.isTTY) {
- this.backFrame = this.frontFrame;
- this.frontFrame = emptyFrame(this.frontFrame.viewport.height, this.frontFrame.viewport.width, this.stylePool, this.charPool, this.hyperlinkPool);
- this.log.reset();
- this.displayCursor = null;
- }
- }
- resetPools() {
- this.charPool = new CharPool;
- this.hyperlinkPool = new HyperlinkPool;
- migrateScreenPools(this.frontFrame.screen, this.charPool, this.hyperlinkPool);
- this.backFrame.screen.charPool = this.charPool;
- this.backFrame.screen.hyperlinkPool = this.hyperlinkPool;
- }
- patchConsole() {
- const con = console;
- const originals = {};
- const toDebug = (...args) => logForDebugging(`console.log: ${format3(...args)}`);
- const toError2 = (...args) => logError2(new Error(`console.error: ${format3(...args)}`));
- for (const m4 of CONSOLE_STDOUT_METHODS) {
- originals[m4] = con[m4];
- con[m4] = toDebug;
- }
- for (const m4 of CONSOLE_STDERR_METHODS) {
- originals[m4] = con[m4];
- con[m4] = toError2;
- }
- originals.assert = con.assert;
- con.assert = (condition, ...args) => {
- if (!condition)
- toError2(...args);
- };
- return () => Object.assign(con, originals);
- }
- patchStderr() {
- const stderr = process.stderr;
- const originalWrite = stderr.write;
- let reentered = false;
- const intercept = (chunk, encodingOrCb, cb) => {
- const callback = typeof encodingOrCb === "function" ? encodingOrCb : cb;
- if (reentered) {
- const encoding = typeof encodingOrCb === "string" ? encodingOrCb : undefined;
- return originalWrite.call(stderr, chunk, encoding, callback);
- }
- reentered = true;
- try {
- const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
- logForDebugging(`[stderr] ${text}`, {
- level: "warn"
- });
- if (this.altScreenActive && !this.isUnmounted && !this.isPaused) {
- this.prevFrameContaminated = true;
- this.scheduleRender();
- }
- } finally {
- reentered = false;
- callback?.();
- }
- return true;
- };
- stderr.write = intercept;
- return () => {
- if (stderr.write === intercept) {
- stderr.write = originalWrite;
- }
- };
- }
-}
-function drainStdin(stdin = process.stdin) {
- if (!stdin.isTTY)
- return;
- try {
- while (stdin.read() !== null) {}
- } catch {}
- if (process.platform === "win32")
- return;
- const tty4 = stdin;
- const wasRaw = tty4.isRaw === true;
- let fd = -1;
- try {
- if (!wasRaw)
- tty4.setRawMode?.(true);
- fd = openSync3("/dev/tty", fsConstants3.O_RDONLY | fsConstants3.O_NONBLOCK);
- const buf = Buffer.alloc(1024);
- for (let i5 = 0;i5 < 64; i5++) {
- if (readSync2(fd, buf, 0, buf.length, null) <= 0)
- break;
- }
- } catch {} finally {
- if (fd >= 0) {
- try {
- closeSync3(fd);
- } catch {}
- }
- if (!wasRaw) {
- try {
- tty4.setRawMode?.(false);
- } catch {}
- }
- }
-}
-var import_constants44, jsx_dev_runtime8, ALT_SCREEN_ANCHOR_CURSOR, CURSOR_HOME_PATCH, ERASE_THEN_HOME_PATCH, CONSOLE_STDOUT_METHODS, CONSOLE_STDERR_METHODS;
-var init_ink = __esm(() => {
- init_noop();
- init_throttle2();
- init_mjs();
- init_state();
- init_yoga_layout();
- init_debug();
- init_log2();
- init_colorize();
- init_App();
- init_dom();
- init_keyboard_event();
- init_focus();
- init_frame();
- init_hit_test();
- init_instances();
- init_log_update();
- init_node_cache();
- init_output2();
- init_reconciler();
- init_render_node_to_output();
- init_render_to_screen();
- init_renderer();
- init_screen();
- init_searchHighlight();
- init_selection();
- init_terminal();
- init_csi();
- init_dec();
- init_osc();
- init_useTerminalNotification();
- import_constants44 = __toESM(require_constants5(), 1);
- jsx_dev_runtime8 = __toESM(require_jsx_dev_runtime(), 1);
- ALT_SCREEN_ANCHOR_CURSOR = Object.freeze({
- x: 0,
- y: 0,
- visible: false
- });
- CURSOR_HOME_PATCH = Object.freeze({
- type: "stdout",
- content: CURSOR_HOME
- });
- ERASE_THEN_HOME_PATCH = Object.freeze({
- type: "stdout",
- content: ERASE_SCREEN + CURSOR_HOME
- });
- CONSOLE_STDOUT_METHODS = ["log", "info", "debug", "dir", "dirxml", "count", "countReset", "group", "groupCollapsed", "groupEnd", "table", "time", "timeEnd", "timeLog"];
- CONSOLE_STDERR_METHODS = ["warn", "error", "trace"];
-});
-
-// src/ink/root.ts
-import { Stream as Stream6 } from "stream";
-async function createRoot({
- stdout = process.stdout,
- stdin = process.stdin,
- stderr = process.stderr,
- exitOnCtrlC = true,
- patchConsole = true,
- onFrame
-} = {}) {
- await Promise.resolve();
- const instance = new Ink({
- stdout,
- stdin,
- stderr,
- exitOnCtrlC,
- patchConsole,
- onFrame
- });
- instances_default.set(stdout, instance);
- return {
- render: (node) => instance.render(node),
- unmount: () => instance.unmount(),
- waitUntilExit: () => instance.waitUntilExit()
- };
-}
-var renderSync = (node, options2) => {
- const opts = getOptions(options2);
- const inkOptions = {
- stdout: process.stdout,
- stdin: process.stdin,
- stderr: process.stderr,
- exitOnCtrlC: true,
- patchConsole: true,
- ...opts
- };
- const instance = getInstance(inkOptions.stdout, () => new Ink(inkOptions));
- instance.render(node);
- return {
- rerender: instance.render,
- unmount() {
- instance.unmount();
- },
- waitUntilExit: instance.waitUntilExit,
- cleanup: () => instances_default.delete(inkOptions.stdout)
- };
-}, wrappedRender = async (node, options2) => {
- await Promise.resolve();
- const instance = renderSync(node, options2);
- logForDebugging(`[render] first ink render: ${Math.round(process.uptime() * 1000)}ms since process start`);
- return instance;
-}, root_default, getOptions = (stdout = {}) => {
- if (stdout instanceof Stream6) {
- return {
- stdout,
- stdin: process.stdin
- };
- }
- return stdout;
-}, getInstance = (stdout, createInstance2) => {
- let instance = instances_default.get(stdout);
- if (!instance) {
- instance = createInstance2();
- instances_default.set(stdout, instance);
- }
- return instance;
-};
-var init_root = __esm(() => {
- init_debug();
- init_ink();
- init_instances();
- root_default = wrappedRender;
-});
-
-// src/utils/theme.ts
-function getTheme(themeName) {
- switch (themeName) {
- case "light":
- return lightTheme;
- case "light-ansi":
- return lightAnsiTheme;
- case "dark-ansi":
- return darkAnsiTheme;
- case "light-daltonized":
- return lightDaltonizedTheme;
- case "dark-daltonized":
- return darkDaltonizedTheme;
- default:
- return darkTheme;
- }
-}
-function themeColorToAnsi(themeColor) {
- const rgbMatch = themeColor.match(/rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)/);
- if (rgbMatch) {
- const r4 = parseInt(rgbMatch[1], 10);
- const g4 = parseInt(rgbMatch[2], 10);
- const b4 = parseInt(rgbMatch[3], 10);
- const colored = chalkForChart.rgb(r4, g4, b4)("X");
- return colored.slice(0, colored.indexOf("X"));
- }
- return "\x1B[35m";
-}
-var THEME_NAMES, THEME_SETTINGS, lightTheme, lightAnsiTheme, darkAnsiTheme, lightDaltonizedTheme, darkTheme, darkDaltonizedTheme, chalkForChart;
-var init_theme = __esm(() => {
- init_source();
- init_env();
- THEME_NAMES = [
- "dark",
- "light",
- "light-daltonized",
- "dark-daltonized",
- "light-ansi",
- "dark-ansi"
- ];
- THEME_SETTINGS = ["auto", ...THEME_NAMES];
- lightTheme = {
- autoAccept: "rgb(135,0,255)",
- bashBorder: "rgb(255,0,135)",
- claude: "rgb(215,119,87)",
- claudeShimmer: "rgb(245,149,117)",
- claudeBlue_FOR_SYSTEM_SPINNER: "rgb(87,105,247)",
- claudeBlueShimmer_FOR_SYSTEM_SPINNER: "rgb(117,135,255)",
- permission: "rgb(87,105,247)",
- permissionShimmer: "rgb(137,155,255)",
- planMode: "rgb(0,102,102)",
- ide: "rgb(71,130,200)",
- promptBorder: "rgb(153,153,153)",
- promptBorderShimmer: "rgb(183,183,183)",
- text: "rgb(0,0,0)",
- inverseText: "rgb(255,255,255)",
- inactive: "rgb(102,102,102)",
- inactiveShimmer: "rgb(142,142,142)",
- subtle: "rgb(175,175,175)",
- suggestion: "rgb(87,105,247)",
- remember: "rgb(0,0,255)",
- background: "rgb(0,153,153)",
- success: "rgb(44,122,57)",
- error: "rgb(171,43,63)",
- warning: "rgb(150,108,30)",
- merged: "rgb(135,0,255)",
- warningShimmer: "rgb(200,158,80)",
- diffAdded: "rgb(105,219,124)",
- diffRemoved: "rgb(255,168,180)",
- diffAddedDimmed: "rgb(199,225,203)",
- diffRemovedDimmed: "rgb(253,210,216)",
- diffAddedWord: "rgb(47,157,68)",
- diffRemovedWord: "rgb(209,69,75)",
- red_FOR_SUBAGENTS_ONLY: "rgb(220,38,38)",
- blue_FOR_SUBAGENTS_ONLY: "rgb(37,99,235)",
- green_FOR_SUBAGENTS_ONLY: "rgb(22,163,74)",
- yellow_FOR_SUBAGENTS_ONLY: "rgb(202,138,4)",
- purple_FOR_SUBAGENTS_ONLY: "rgb(147,51,234)",
- orange_FOR_SUBAGENTS_ONLY: "rgb(234,88,12)",
- pink_FOR_SUBAGENTS_ONLY: "rgb(219,39,119)",
- cyan_FOR_SUBAGENTS_ONLY: "rgb(8,145,178)",
- professionalBlue: "rgb(106,155,204)",
- chromeYellow: "rgb(251,188,4)",
- clawd_body: "rgb(215,119,87)",
- clawd_background: "rgb(0,0,0)",
- userMessageBackground: "rgb(240, 240, 240)",
- userMessageBackgroundHover: "rgb(252, 252, 252)",
- messageActionsBackground: "rgb(232, 236, 244)",
- selectionBg: "rgb(180, 213, 255)",
- bashMessageBackgroundColor: "rgb(250, 245, 250)",
- memoryBackgroundColor: "rgb(230, 245, 250)",
- rate_limit_fill: "rgb(87,105,247)",
- rate_limit_empty: "rgb(39,47,111)",
- fastMode: "rgb(255,106,0)",
- fastModeShimmer: "rgb(255,150,50)",
- briefLabelYou: "rgb(37,99,235)",
- briefLabelClaude: "rgb(215,119,87)",
- rainbow_red: "rgb(235,95,87)",
- rainbow_orange: "rgb(245,139,87)",
- rainbow_yellow: "rgb(250,195,95)",
- rainbow_green: "rgb(145,200,130)",
- rainbow_blue: "rgb(130,170,220)",
- rainbow_indigo: "rgb(155,130,200)",
- rainbow_violet: "rgb(200,130,180)",
- rainbow_red_shimmer: "rgb(250,155,147)",
- rainbow_orange_shimmer: "rgb(255,185,137)",
- rainbow_yellow_shimmer: "rgb(255,225,155)",
- rainbow_green_shimmer: "rgb(185,230,180)",
- rainbow_blue_shimmer: "rgb(180,205,240)",
- rainbow_indigo_shimmer: "rgb(195,180,230)",
- rainbow_violet_shimmer: "rgb(230,180,210)"
- };
- lightAnsiTheme = {
- autoAccept: "ansi:magenta",
- bashBorder: "ansi:magenta",
- claude: "ansi:redBright",
- claudeShimmer: "ansi:yellowBright",
- claudeBlue_FOR_SYSTEM_SPINNER: "ansi:blue",
- claudeBlueShimmer_FOR_SYSTEM_SPINNER: "ansi:blueBright",
- permission: "ansi:blue",
- permissionShimmer: "ansi:blueBright",
- planMode: "ansi:cyan",
- ide: "ansi:blueBright",
- promptBorder: "ansi:white",
- promptBorderShimmer: "ansi:whiteBright",
- text: "ansi:black",
- inverseText: "ansi:white",
- inactive: "ansi:blackBright",
- inactiveShimmer: "ansi:white",
- subtle: "ansi:blackBright",
- suggestion: "ansi:blue",
- remember: "ansi:blue",
- background: "ansi:cyan",
- success: "ansi:green",
- error: "ansi:red",
- warning: "ansi:yellow",
- merged: "ansi:magenta",
- warningShimmer: "ansi:yellowBright",
- diffAdded: "ansi:green",
- diffRemoved: "ansi:red",
- diffAddedDimmed: "ansi:green",
- diffRemovedDimmed: "ansi:red",
- diffAddedWord: "ansi:greenBright",
- diffRemovedWord: "ansi:redBright",
- red_FOR_SUBAGENTS_ONLY: "ansi:red",
- blue_FOR_SUBAGENTS_ONLY: "ansi:blue",
- green_FOR_SUBAGENTS_ONLY: "ansi:green",
- yellow_FOR_SUBAGENTS_ONLY: "ansi:yellow",
- purple_FOR_SUBAGENTS_ONLY: "ansi:magenta",
- orange_FOR_SUBAGENTS_ONLY: "ansi:redBright",
- pink_FOR_SUBAGENTS_ONLY: "ansi:magentaBright",
- cyan_FOR_SUBAGENTS_ONLY: "ansi:cyan",
- professionalBlue: "ansi:blueBright",
- chromeYellow: "ansi:yellow",
- clawd_body: "ansi:redBright",
- clawd_background: "ansi:black",
- userMessageBackground: "ansi:white",
- userMessageBackgroundHover: "ansi:whiteBright",
- messageActionsBackground: "ansi:white",
- selectionBg: "ansi:cyan",
- bashMessageBackgroundColor: "ansi:whiteBright",
- memoryBackgroundColor: "ansi:white",
- rate_limit_fill: "ansi:yellow",
- rate_limit_empty: "ansi:black",
- fastMode: "ansi:red",
- fastModeShimmer: "ansi:redBright",
- briefLabelYou: "ansi:blue",
- briefLabelClaude: "ansi:redBright",
- rainbow_red: "ansi:red",
- rainbow_orange: "ansi:redBright",
- rainbow_yellow: "ansi:yellow",
- rainbow_green: "ansi:green",
- rainbow_blue: "ansi:cyan",
- rainbow_indigo: "ansi:blue",
- rainbow_violet: "ansi:magenta",
- rainbow_red_shimmer: "ansi:redBright",
- rainbow_orange_shimmer: "ansi:yellow",
- rainbow_yellow_shimmer: "ansi:yellowBright",
- rainbow_green_shimmer: "ansi:greenBright",
- rainbow_blue_shimmer: "ansi:cyanBright",
- rainbow_indigo_shimmer: "ansi:blueBright",
- rainbow_violet_shimmer: "ansi:magentaBright"
- };
- darkAnsiTheme = {
- autoAccept: "ansi:magentaBright",
- bashBorder: "ansi:magentaBright",
- claude: "ansi:redBright",
- claudeShimmer: "ansi:yellowBright",
- claudeBlue_FOR_SYSTEM_SPINNER: "ansi:blueBright",
- claudeBlueShimmer_FOR_SYSTEM_SPINNER: "ansi:blueBright",
- permission: "ansi:blueBright",
- permissionShimmer: "ansi:blueBright",
- planMode: "ansi:cyanBright",
- ide: "ansi:blue",
- promptBorder: "ansi:white",
- promptBorderShimmer: "ansi:whiteBright",
- text: "ansi:whiteBright",
- inverseText: "ansi:black",
- inactive: "ansi:white",
- inactiveShimmer: "ansi:whiteBright",
- subtle: "ansi:white",
- suggestion: "ansi:blueBright",
- remember: "ansi:blueBright",
- background: "ansi:cyanBright",
- success: "ansi:greenBright",
- error: "ansi:redBright",
- warning: "ansi:yellowBright",
- merged: "ansi:magentaBright",
- warningShimmer: "ansi:yellowBright",
- diffAdded: "ansi:green",
- diffRemoved: "ansi:red",
- diffAddedDimmed: "ansi:green",
- diffRemovedDimmed: "ansi:red",
- diffAddedWord: "ansi:greenBright",
- diffRemovedWord: "ansi:redBright",
- red_FOR_SUBAGENTS_ONLY: "ansi:redBright",
- blue_FOR_SUBAGENTS_ONLY: "ansi:blueBright",
- green_FOR_SUBAGENTS_ONLY: "ansi:greenBright",
- yellow_FOR_SUBAGENTS_ONLY: "ansi:yellowBright",
- purple_FOR_SUBAGENTS_ONLY: "ansi:magentaBright",
- orange_FOR_SUBAGENTS_ONLY: "ansi:redBright",
- pink_FOR_SUBAGENTS_ONLY: "ansi:magentaBright",
- cyan_FOR_SUBAGENTS_ONLY: "ansi:cyanBright",
- professionalBlue: "rgb(106,155,204)",
- chromeYellow: "ansi:yellowBright",
- clawd_body: "ansi:redBright",
- clawd_background: "ansi:black",
- userMessageBackground: "ansi:blackBright",
- userMessageBackgroundHover: "ansi:white",
- messageActionsBackground: "ansi:blackBright",
- selectionBg: "ansi:blue",
- bashMessageBackgroundColor: "ansi:black",
- memoryBackgroundColor: "ansi:blackBright",
- rate_limit_fill: "ansi:yellow",
- rate_limit_empty: "ansi:white",
- fastMode: "ansi:redBright",
- fastModeShimmer: "ansi:redBright",
- briefLabelYou: "ansi:blueBright",
- briefLabelClaude: "ansi:redBright",
- rainbow_red: "ansi:red",
- rainbow_orange: "ansi:redBright",
- rainbow_yellow: "ansi:yellow",
- rainbow_green: "ansi:green",
- rainbow_blue: "ansi:cyan",
- rainbow_indigo: "ansi:blue",
- rainbow_violet: "ansi:magenta",
- rainbow_red_shimmer: "ansi:redBright",
- rainbow_orange_shimmer: "ansi:yellow",
- rainbow_yellow_shimmer: "ansi:yellowBright",
- rainbow_green_shimmer: "ansi:greenBright",
- rainbow_blue_shimmer: "ansi:cyanBright",
- rainbow_indigo_shimmer: "ansi:blueBright",
- rainbow_violet_shimmer: "ansi:magentaBright"
- };
- lightDaltonizedTheme = {
- autoAccept: "rgb(135,0,255)",
- bashBorder: "rgb(0,102,204)",
- claude: "rgb(255,153,51)",
- claudeShimmer: "rgb(255,183,101)",
- claudeBlue_FOR_SYSTEM_SPINNER: "rgb(51,102,255)",
- claudeBlueShimmer_FOR_SYSTEM_SPINNER: "rgb(101,152,255)",
- permission: "rgb(51,102,255)",
- permissionShimmer: "rgb(101,152,255)",
- planMode: "rgb(51,102,102)",
- ide: "rgb(71,130,200)",
- promptBorder: "rgb(153,153,153)",
- promptBorderShimmer: "rgb(183,183,183)",
- text: "rgb(0,0,0)",
- inverseText: "rgb(255,255,255)",
- inactive: "rgb(102,102,102)",
- inactiveShimmer: "rgb(142,142,142)",
- subtle: "rgb(175,175,175)",
- suggestion: "rgb(51,102,255)",
- remember: "rgb(51,102,255)",
- background: "rgb(0,153,153)",
- success: "rgb(0,102,153)",
- error: "rgb(204,0,0)",
- warning: "rgb(255,153,0)",
- merged: "rgb(135,0,255)",
- warningShimmer: "rgb(255,183,50)",
- diffAdded: "rgb(153,204,255)",
- diffRemoved: "rgb(255,204,204)",
- diffAddedDimmed: "rgb(209,231,253)",
- diffRemovedDimmed: "rgb(255,233,233)",
- diffAddedWord: "rgb(51,102,204)",
- diffRemovedWord: "rgb(153,51,51)",
- red_FOR_SUBAGENTS_ONLY: "rgb(204,0,0)",
- blue_FOR_SUBAGENTS_ONLY: "rgb(0,102,204)",
- green_FOR_SUBAGENTS_ONLY: "rgb(0,204,0)",
- yellow_FOR_SUBAGENTS_ONLY: "rgb(255,204,0)",
- purple_FOR_SUBAGENTS_ONLY: "rgb(128,0,128)",
- orange_FOR_SUBAGENTS_ONLY: "rgb(255,128,0)",
- pink_FOR_SUBAGENTS_ONLY: "rgb(255,102,178)",
- cyan_FOR_SUBAGENTS_ONLY: "rgb(0,178,178)",
- professionalBlue: "rgb(106,155,204)",
- chromeYellow: "rgb(251,188,4)",
- clawd_body: "rgb(215,119,87)",
- clawd_background: "rgb(0,0,0)",
- userMessageBackground: "rgb(220, 220, 220)",
- userMessageBackgroundHover: "rgb(232, 232, 232)",
- messageActionsBackground: "rgb(210, 216, 226)",
- selectionBg: "rgb(180, 213, 255)",
- bashMessageBackgroundColor: "rgb(250, 245, 250)",
- memoryBackgroundColor: "rgb(230, 245, 250)",
- rate_limit_fill: "rgb(51,102,255)",
- rate_limit_empty: "rgb(23,46,114)",
- fastMode: "rgb(255,106,0)",
- fastModeShimmer: "rgb(255,150,50)",
- briefLabelYou: "rgb(37,99,235)",
- briefLabelClaude: "rgb(255,153,51)",
- rainbow_red: "rgb(235,95,87)",
- rainbow_orange: "rgb(245,139,87)",
- rainbow_yellow: "rgb(250,195,95)",
- rainbow_green: "rgb(145,200,130)",
- rainbow_blue: "rgb(130,170,220)",
- rainbow_indigo: "rgb(155,130,200)",
- rainbow_violet: "rgb(200,130,180)",
- rainbow_red_shimmer: "rgb(250,155,147)",
- rainbow_orange_shimmer: "rgb(255,185,137)",
- rainbow_yellow_shimmer: "rgb(255,225,155)",
- rainbow_green_shimmer: "rgb(185,230,180)",
- rainbow_blue_shimmer: "rgb(180,205,240)",
- rainbow_indigo_shimmer: "rgb(195,180,230)",
- rainbow_violet_shimmer: "rgb(230,180,210)"
- };
- darkTheme = {
- autoAccept: "rgb(175,135,255)",
- bashBorder: "rgb(253,93,177)",
- claude: "rgb(215,119,87)",
- claudeShimmer: "rgb(235,159,127)",
- claudeBlue_FOR_SYSTEM_SPINNER: "rgb(147,165,255)",
- claudeBlueShimmer_FOR_SYSTEM_SPINNER: "rgb(177,195,255)",
- permission: "rgb(177,185,249)",
- permissionShimmer: "rgb(207,215,255)",
- planMode: "rgb(72,150,140)",
- ide: "rgb(71,130,200)",
- promptBorder: "rgb(136,136,136)",
- promptBorderShimmer: "rgb(166,166,166)",
- text: "rgb(255,255,255)",
- inverseText: "rgb(0,0,0)",
- inactive: "rgb(153,153,153)",
- inactiveShimmer: "rgb(193,193,193)",
- subtle: "rgb(80,80,80)",
- suggestion: "rgb(177,185,249)",
- remember: "rgb(177,185,249)",
- background: "rgb(0,204,204)",
- success: "rgb(78,186,101)",
- error: "rgb(255,107,128)",
- warning: "rgb(255,193,7)",
- merged: "rgb(175,135,255)",
- warningShimmer: "rgb(255,223,57)",
- diffAdded: "rgb(34,92,43)",
- diffRemoved: "rgb(122,41,54)",
- diffAddedDimmed: "rgb(71,88,74)",
- diffRemovedDimmed: "rgb(105,72,77)",
- diffAddedWord: "rgb(56,166,96)",
- diffRemovedWord: "rgb(179,89,107)",
- red_FOR_SUBAGENTS_ONLY: "rgb(220,38,38)",
- blue_FOR_SUBAGENTS_ONLY: "rgb(37,99,235)",
- green_FOR_SUBAGENTS_ONLY: "rgb(22,163,74)",
- yellow_FOR_SUBAGENTS_ONLY: "rgb(202,138,4)",
- purple_FOR_SUBAGENTS_ONLY: "rgb(147,51,234)",
- orange_FOR_SUBAGENTS_ONLY: "rgb(234,88,12)",
- pink_FOR_SUBAGENTS_ONLY: "rgb(219,39,119)",
- cyan_FOR_SUBAGENTS_ONLY: "rgb(8,145,178)",
- professionalBlue: "rgb(106,155,204)",
- chromeYellow: "rgb(251,188,4)",
- clawd_body: "rgb(215,119,87)",
- clawd_background: "rgb(0,0,0)",
- userMessageBackground: "rgb(55, 55, 55)",
- userMessageBackgroundHover: "rgb(70, 70, 70)",
- messageActionsBackground: "rgb(44, 50, 62)",
- selectionBg: "rgb(38, 79, 120)",
- bashMessageBackgroundColor: "rgb(65, 60, 65)",
- memoryBackgroundColor: "rgb(55, 65, 70)",
- rate_limit_fill: "rgb(177,185,249)",
- rate_limit_empty: "rgb(80,83,112)",
- fastMode: "rgb(255,120,20)",
- fastModeShimmer: "rgb(255,165,70)",
- briefLabelYou: "rgb(122,180,232)",
- briefLabelClaude: "rgb(215,119,87)",
- rainbow_red: "rgb(235,95,87)",
- rainbow_orange: "rgb(245,139,87)",
- rainbow_yellow: "rgb(250,195,95)",
- rainbow_green: "rgb(145,200,130)",
- rainbow_blue: "rgb(130,170,220)",
- rainbow_indigo: "rgb(155,130,200)",
- rainbow_violet: "rgb(200,130,180)",
- rainbow_red_shimmer: "rgb(250,155,147)",
- rainbow_orange_shimmer: "rgb(255,185,137)",
- rainbow_yellow_shimmer: "rgb(255,225,155)",
- rainbow_green_shimmer: "rgb(185,230,180)",
- rainbow_blue_shimmer: "rgb(180,205,240)",
- rainbow_indigo_shimmer: "rgb(195,180,230)",
- rainbow_violet_shimmer: "rgb(230,180,210)"
- };
- darkDaltonizedTheme = {
- autoAccept: "rgb(175,135,255)",
- bashBorder: "rgb(51,153,255)",
- claude: "rgb(255,153,51)",
- claudeShimmer: "rgb(255,183,101)",
- claudeBlue_FOR_SYSTEM_SPINNER: "rgb(153,204,255)",
- claudeBlueShimmer_FOR_SYSTEM_SPINNER: "rgb(183,224,255)",
- permission: "rgb(153,204,255)",
- permissionShimmer: "rgb(183,224,255)",
- planMode: "rgb(102,153,153)",
- ide: "rgb(71,130,200)",
- promptBorder: "rgb(136,136,136)",
- promptBorderShimmer: "rgb(166,166,166)",
- text: "rgb(255,255,255)",
- inverseText: "rgb(0,0,0)",
- inactive: "rgb(153,153,153)",
- inactiveShimmer: "rgb(193,193,193)",
- subtle: "rgb(80,80,80)",
- suggestion: "rgb(153,204,255)",
- remember: "rgb(153,204,255)",
- background: "rgb(0,204,204)",
- success: "rgb(51,153,255)",
- error: "rgb(255,102,102)",
- warning: "rgb(255,204,0)",
- merged: "rgb(175,135,255)",
- warningShimmer: "rgb(255,234,50)",
- diffAdded: "rgb(0,68,102)",
- diffRemoved: "rgb(102,0,0)",
- diffAddedDimmed: "rgb(62,81,91)",
- diffRemovedDimmed: "rgb(62,44,44)",
- diffAddedWord: "rgb(0,119,179)",
- diffRemovedWord: "rgb(179,0,0)",
- red_FOR_SUBAGENTS_ONLY: "rgb(255,102,102)",
- blue_FOR_SUBAGENTS_ONLY: "rgb(102,178,255)",
- green_FOR_SUBAGENTS_ONLY: "rgb(102,255,102)",
- yellow_FOR_SUBAGENTS_ONLY: "rgb(255,255,102)",
- purple_FOR_SUBAGENTS_ONLY: "rgb(178,102,255)",
- orange_FOR_SUBAGENTS_ONLY: "rgb(255,178,102)",
- pink_FOR_SUBAGENTS_ONLY: "rgb(255,153,204)",
- cyan_FOR_SUBAGENTS_ONLY: "rgb(102,204,204)",
- professionalBlue: "rgb(106,155,204)",
- chromeYellow: "rgb(251,188,4)",
- clawd_body: "rgb(215,119,87)",
- clawd_background: "rgb(0,0,0)",
- userMessageBackground: "rgb(55, 55, 55)",
- userMessageBackgroundHover: "rgb(70, 70, 70)",
- messageActionsBackground: "rgb(44, 50, 62)",
- selectionBg: "rgb(38, 79, 120)",
- bashMessageBackgroundColor: "rgb(65, 60, 65)",
- memoryBackgroundColor: "rgb(55, 65, 70)",
- rate_limit_fill: "rgb(153,204,255)",
- rate_limit_empty: "rgb(69,92,115)",
- fastMode: "rgb(255,120,20)",
- fastModeShimmer: "rgb(255,165,70)",
- briefLabelYou: "rgb(122,180,232)",
- briefLabelClaude: "rgb(255,153,51)",
- rainbow_red: "rgb(235,95,87)",
- rainbow_orange: "rgb(245,139,87)",
- rainbow_yellow: "rgb(250,195,95)",
- rainbow_green: "rgb(145,200,130)",
- rainbow_blue: "rgb(130,170,220)",
- rainbow_indigo: "rgb(155,130,200)",
- rainbow_violet: "rgb(200,130,180)",
- rainbow_red_shimmer: "rgb(250,155,147)",
- rainbow_orange_shimmer: "rgb(255,185,137)",
- rainbow_yellow_shimmer: "rgb(255,225,155)",
- rainbow_green_shimmer: "rgb(185,230,180)",
- rainbow_blue_shimmer: "rgb(180,205,240)",
- rainbow_indigo_shimmer: "rgb(195,180,230)",
- rainbow_violet_shimmer: "rgb(230,180,210)"
- };
- chalkForChart = env2.terminal === "Apple_Terminal" ? new Chalk({ level: 2 }) : source_default;
-});
-
-// src/components/design-system/color.ts
-function color(c8, theme, type = "foreground") {
- return (text) => {
- if (!c8) {
- return text;
- }
- if (c8.startsWith("rgb(") || c8.startsWith("#") || c8.startsWith("ansi256(") || c8.startsWith("ansi:")) {
- return colorize(text, c8, type);
- }
- return colorize(text, getTheme(theme)[c8], type);
- };
-}
-var init_color = __esm(() => {
- init_colorize();
- init_theme();
-});
-
-// src/components/design-system/ThemedBox.tsx
-function resolveColor(color2, theme) {
- if (!color2)
- return;
- if (color2.startsWith("rgb(") || color2.startsWith("#") || color2.startsWith("ansi256(") || color2.startsWith("ansi:")) {
- return color2;
- }
- return theme[color2];
-}
-function ThemedBox(t0) {
- const $2 = import_compiler_runtime6.c(33);
- let backgroundColor;
- let borderBottomColor;
- let borderColor;
- let borderLeftColor;
- let borderRightColor;
- let borderTopColor;
- let children;
- let ref;
- let rest;
- if ($2[0] !== t0) {
- ({
- borderColor,
- borderTopColor,
- borderBottomColor,
- borderLeftColor,
- borderRightColor,
- backgroundColor,
- children,
- ref,
- ...rest
- } = t0);
- $2[0] = t0;
- $2[1] = backgroundColor;
- $2[2] = borderBottomColor;
- $2[3] = borderColor;
- $2[4] = borderLeftColor;
- $2[5] = borderRightColor;
- $2[6] = borderTopColor;
- $2[7] = children;
- $2[8] = ref;
- $2[9] = rest;
- } else {
- backgroundColor = $2[1];
- borderBottomColor = $2[2];
- borderColor = $2[3];
- borderLeftColor = $2[4];
- borderRightColor = $2[5];
- borderTopColor = $2[6];
- children = $2[7];
- ref = $2[8];
- rest = $2[9];
- }
- const [themeName] = useTheme();
- let resolvedBorderBottomColor;
- let resolvedBorderColor;
- let resolvedBorderLeftColor;
- let resolvedBorderRightColor;
- let resolvedBorderTopColor;
- let t1;
- if ($2[10] !== backgroundColor || $2[11] !== borderBottomColor || $2[12] !== borderColor || $2[13] !== borderLeftColor || $2[14] !== borderRightColor || $2[15] !== borderTopColor || $2[16] !== themeName) {
- const theme = getTheme(themeName);
- resolvedBorderColor = resolveColor(borderColor, theme);
- resolvedBorderTopColor = resolveColor(borderTopColor, theme);
- resolvedBorderBottomColor = resolveColor(borderBottomColor, theme);
- resolvedBorderLeftColor = resolveColor(borderLeftColor, theme);
- resolvedBorderRightColor = resolveColor(borderRightColor, theme);
- t1 = resolveColor(backgroundColor, theme);
- $2[10] = backgroundColor;
- $2[11] = borderBottomColor;
- $2[12] = borderColor;
- $2[13] = borderLeftColor;
- $2[14] = borderRightColor;
- $2[15] = borderTopColor;
- $2[16] = themeName;
- $2[17] = resolvedBorderBottomColor;
- $2[18] = resolvedBorderColor;
- $2[19] = resolvedBorderLeftColor;
- $2[20] = resolvedBorderRightColor;
- $2[21] = resolvedBorderTopColor;
- $2[22] = t1;
- } else {
- resolvedBorderBottomColor = $2[17];
- resolvedBorderColor = $2[18];
- resolvedBorderLeftColor = $2[19];
- resolvedBorderRightColor = $2[20];
- resolvedBorderTopColor = $2[21];
- t1 = $2[22];
- }
- const resolvedBackgroundColor = t1;
- let t22;
- if ($2[23] !== children || $2[24] !== ref || $2[25] !== resolvedBackgroundColor || $2[26] !== resolvedBorderBottomColor || $2[27] !== resolvedBorderColor || $2[28] !== resolvedBorderLeftColor || $2[29] !== resolvedBorderRightColor || $2[30] !== resolvedBorderTopColor || $2[31] !== rest) {
- t22 = /* @__PURE__ */ jsx_dev_runtime9.jsxDEV(Box_default, {
- ref,
- borderColor: resolvedBorderColor,
- borderTopColor: resolvedBorderTopColor,
- borderBottomColor: resolvedBorderBottomColor,
- borderLeftColor: resolvedBorderLeftColor,
- borderRightColor: resolvedBorderRightColor,
- backgroundColor: resolvedBackgroundColor,
- ...rest,
- children
- }, undefined, false, undefined, this);
- $2[23] = children;
- $2[24] = ref;
- $2[25] = resolvedBackgroundColor;
- $2[26] = resolvedBorderBottomColor;
- $2[27] = resolvedBorderColor;
- $2[28] = resolvedBorderLeftColor;
- $2[29] = resolvedBorderRightColor;
- $2[30] = resolvedBorderTopColor;
- $2[31] = rest;
- $2[32] = t22;
- } else {
- t22 = $2[32];
- }
- return t22;
-}
-var import_compiler_runtime6, jsx_dev_runtime9, ThemedBox_default;
-var init_ThemedBox = __esm(() => {
- init_Box();
- init_theme();
- init_ThemeProvider();
- import_compiler_runtime6 = __toESM(require_compiler_runtime(), 1);
- jsx_dev_runtime9 = __toESM(require_jsx_dev_runtime(), 1);
- ThemedBox_default = ThemedBox;
-});
-
-// src/components/design-system/ThemedText.tsx
-function resolveColor2(color2, theme) {
- if (!color2)
- return;
- if (color2.startsWith("rgb(") || color2.startsWith("#") || color2.startsWith("ansi256(") || color2.startsWith("ansi:")) {
- return color2;
- }
- return theme[color2];
-}
-function ThemedText(t0) {
- const $2 = import_compiler_runtime7.c(10);
- const {
- color: color2,
- backgroundColor,
- dimColor: t1,
- bold: t22,
- italic: t32,
- underline: t4,
- strikethrough: t5,
- inverse: t6,
- wrap: t7,
- children
- } = t0;
- const dimColor = t1 === undefined ? false : t1;
- const bold2 = t22 === undefined ? false : t22;
- const italic2 = t32 === undefined ? false : t32;
- const underline2 = t4 === undefined ? false : t4;
- const strikethrough2 = t5 === undefined ? false : t5;
- const inverse2 = t6 === undefined ? false : t6;
- const wrap = t7 === undefined ? "wrap" : t7;
- const [themeName] = useTheme();
- const theme = getTheme(themeName);
- const hoverColor = import_react12.useContext(TextHoverColorContext);
- const resolvedColor = !color2 && hoverColor ? resolveColor2(hoverColor, theme) : dimColor ? theme.inactive : resolveColor2(color2, theme);
- const resolvedBackgroundColor = backgroundColor ? theme[backgroundColor] : undefined;
- let t8;
- if ($2[0] !== bold2 || $2[1] !== children || $2[2] !== inverse2 || $2[3] !== italic2 || $2[4] !== resolvedBackgroundColor || $2[5] !== resolvedColor || $2[6] !== strikethrough2 || $2[7] !== underline2 || $2[8] !== wrap) {
- t8 = /* @__PURE__ */ jsx_dev_runtime10.jsxDEV(Text, {
- color: resolvedColor,
- backgroundColor: resolvedBackgroundColor,
- bold: bold2,
- italic: italic2,
- underline: underline2,
- strikethrough: strikethrough2,
- inverse: inverse2,
- wrap,
- children
- }, undefined, false, undefined, this);
- $2[0] = bold2;
- $2[1] = children;
- $2[2] = inverse2;
- $2[3] = italic2;
- $2[4] = resolvedBackgroundColor;
- $2[5] = resolvedColor;
- $2[6] = strikethrough2;
- $2[7] = underline2;
- $2[8] = wrap;
- $2[9] = t8;
- } else {
- t8 = $2[9];
- }
- return t8;
-}
-var import_compiler_runtime7, import_react12, jsx_dev_runtime10, TextHoverColorContext;
-var init_ThemedText = __esm(() => {
- init_Text();
- init_theme();
- init_ThemeProvider();
- import_compiler_runtime7 = __toESM(require_compiler_runtime(), 1);
- import_react12 = __toESM(require_react(), 1);
- jsx_dev_runtime10 = __toESM(require_jsx_dev_runtime(), 1);
- TextHoverColorContext = import_react12.default.createContext(undefined);
-});
-
-// node_modules/supports-hyperlinks/index.js
-var require_supports_hyperlinks = __commonJS((exports, module) => {
- var supportsColor2 = require_supports_color();
- var hasFlag2 = require_has_flag();
- function parseVersion(versionString) {
- if (/^\d{3,4}$/.test(versionString)) {
- const m4 = /(\d{1,2})(\d{2})/.exec(versionString) || [];
- return {
- major: 0,
- minor: parseInt(m4[1], 10),
- patch: parseInt(m4[2], 10)
- };
- }
- const versions2 = (versionString || "").split(".").map((n5) => parseInt(n5, 10));
- return {
- major: versions2[0],
- minor: versions2[1],
- patch: versions2[2]
- };
- }
- function supportsHyperlink(stream10) {
- const {
- CI,
- FORCE_HYPERLINK,
- NETLIFY,
- TEAMCITY_VERSION,
- TERM_PROGRAM,
- TERM_PROGRAM_VERSION,
- VTE_VERSION,
- TERM
- } = process.env;
- if (FORCE_HYPERLINK) {
- return !(FORCE_HYPERLINK.length > 0 && parseInt(FORCE_HYPERLINK, 10) === 0);
- }
- if (hasFlag2("no-hyperlink") || hasFlag2("no-hyperlinks") || hasFlag2("hyperlink=false") || hasFlag2("hyperlink=never")) {
- return false;
- }
- if (hasFlag2("hyperlink=true") || hasFlag2("hyperlink=always")) {
- return true;
- }
- if (NETLIFY) {
- return true;
- }
- if (!supportsColor2.supportsColor(stream10)) {
- return false;
- }
- if (stream10 && !stream10.isTTY) {
- return false;
- }
- if ("WT_SESSION" in process.env) {
- return true;
- }
- if (process.platform === "win32") {
- return false;
- }
- if (CI) {
- return false;
- }
- if (TEAMCITY_VERSION) {
- return false;
- }
- if (TERM_PROGRAM) {
- const version6 = parseVersion(TERM_PROGRAM_VERSION || "");
- switch (TERM_PROGRAM) {
- case "iTerm.app":
- if (version6.major === 3) {
- return version6.minor >= 1;
- }
- return version6.major > 3;
- case "WezTerm":
- return version6.major >= 20200620;
- case "vscode":
- return version6.major > 1 || version6.major === 1 && version6.minor >= 72;
- case "ghostty":
- return true;
- }
- }
- if (VTE_VERSION) {
- if (VTE_VERSION === "0.50.0") {
- return false;
- }
- const version6 = parseVersion(VTE_VERSION);
- return version6.major > 0 || version6.minor >= 50;
- }
- switch (TERM) {
- case "alacritty":
- return true;
- }
- return false;
- }
- module.exports = {
- supportsHyperlink,
- stdout: supportsHyperlink(process.stdout),
- stderr: supportsHyperlink(process.stderr)
- };
-});
-
-// src/ink/supports-hyperlinks.ts
-function supportsHyperlinks(options2) {
- const stdoutSupported = options2?.stdoutSupported ?? import_supports_hyperlinks.default.stdout;
- if (stdoutSupported) {
- return true;
- }
- const env5 = options2?.env ?? process.env;
- const termProgram = env5["TERM_PROGRAM"];
- if (termProgram && ADDITIONAL_HYPERLINK_TERMINALS.includes(termProgram)) {
- return true;
- }
- const lcTerminal = env5["LC_TERMINAL"];
- if (lcTerminal && ADDITIONAL_HYPERLINK_TERMINALS.includes(lcTerminal)) {
- return true;
- }
- const term = env5["TERM"];
- if (term?.includes("kitty")) {
- return true;
- }
- return false;
-}
-var import_supports_hyperlinks, ADDITIONAL_HYPERLINK_TERMINALS;
-var init_supports_hyperlinks = __esm(() => {
- import_supports_hyperlinks = __toESM(require_supports_hyperlinks(), 1);
- ADDITIONAL_HYPERLINK_TERMINALS = [
- "ghostty",
- "Hyper",
- "kitty",
- "alacritty",
- "iTerm.app",
- "iTerm2"
- ];
-});
-
-// src/ink/components/Link.tsx
-function Link(t0) {
- const $2 = import_compiler_runtime8.c(5);
- const {
- children,
- url: url3,
- fallback
- } = t0;
- const content = children ?? url3;
- if (supportsHyperlinks()) {
- let t12;
- if ($2[0] !== content || $2[1] !== url3) {
- t12 = /* @__PURE__ */ jsx_dev_runtime11.jsxDEV(Text, {
- children: /* @__PURE__ */ jsx_dev_runtime11.jsxDEV("ink-link", {
- href: url3,
- children: content
- }, undefined, false, undefined, this)
- }, undefined, false, undefined, this);
- $2[0] = content;
- $2[1] = url3;
- $2[2] = t12;
- } else {
- t12 = $2[2];
- }
- return t12;
- }
- const t1 = fallback ?? content;
- let t22;
- if ($2[3] !== t1) {
- t22 = /* @__PURE__ */ jsx_dev_runtime11.jsxDEV(Text, {
- children: t1
- }, undefined, false, undefined, this);
- $2[3] = t1;
- $2[4] = t22;
- } else {
- t22 = $2[4];
- }
- return t22;
-}
-var import_compiler_runtime8, jsx_dev_runtime11;
-var init_Link = __esm(() => {
- init_supports_hyperlinks();
- init_Text();
- import_compiler_runtime8 = __toESM(require_compiler_runtime(), 1);
- jsx_dev_runtime11 = __toESM(require_jsx_dev_runtime(), 1);
-});
-
-// src/ink/termio/esc.ts
-function parseEsc(chars) {
- if (chars.length === 0)
- return null;
- const first = chars[0];
- if (first === "c") {
- return { type: "reset" };
- }
- if (first === "7") {
- return { type: "cursor", action: { type: "save" } };
- }
- if (first === "8") {
- return { type: "cursor", action: { type: "restore" } };
- }
- if (first === "D") {
- return {
- type: "cursor",
- action: { type: "move", direction: "down", count: 1 }
- };
- }
- if (first === "M") {
- return {
- type: "cursor",
- action: { type: "move", direction: "up", count: 1 }
- };
- }
- if (first === "E") {
- return { type: "cursor", action: { type: "nextLine", count: 1 } };
- }
- if (first === "H") {
- return null;
- }
- if ("()".includes(first) && chars.length >= 2) {
- return null;
- }
- return { type: "unknown", sequence: `\x1B${chars}` };
-}
-
-// src/ink/termio/types.ts
-function defaultStyle2() {
- return {
- bold: false,
- dim: false,
- italic: false,
- underline: "none",
- blink: false,
- inverse: false,
- hidden: false,
- strikethrough: false,
- overline: false,
- fg: { type: "default" },
- bg: { type: "default" },
- underlineColor: { type: "default" }
- };
-}
-
-// src/ink/termio/sgr.ts
-function parseParams(str) {
- if (str === "")
- return [{ value: 0, subparams: [], colon: false }];
- const result = [];
- let current = { value: null, subparams: [], colon: false };
- let num = "";
- let inSub = false;
- for (let i5 = 0;i5 <= str.length; i5++) {
- const c8 = str[i5];
- if (c8 === ";" || c8 === undefined) {
- const n5 = num === "" ? null : parseInt(num, 10);
- if (inSub) {
- if (n5 !== null)
- current.subparams.push(n5);
- } else {
- current.value = n5;
- }
- result.push(current);
- current = { value: null, subparams: [], colon: false };
- num = "";
- inSub = false;
- } else if (c8 === ":") {
- const n5 = num === "" ? null : parseInt(num, 10);
- if (!inSub) {
- current.value = n5;
- current.colon = true;
- inSub = true;
- } else {
- if (n5 !== null)
- current.subparams.push(n5);
- }
- num = "";
- } else if (c8 >= "0" && c8 <= "9") {
- num += c8;
- }
- }
- return result;
-}
-function parseExtendedColor(params, idx) {
- const p4 = params[idx];
- if (!p4)
- return null;
- if (p4.colon && p4.subparams.length >= 1) {
- if (p4.subparams[0] === 5 && p4.subparams.length >= 2) {
- return { index: p4.subparams[1] };
- }
- if (p4.subparams[0] === 2 && p4.subparams.length >= 4) {
- const off = p4.subparams.length >= 5 ? 1 : 0;
- return {
- r: p4.subparams[1 + off],
- g: p4.subparams[2 + off],
- b: p4.subparams[3 + off]
- };
- }
- }
- const next = params[idx + 1];
- if (!next)
- return null;
- if (next.value === 5 && params[idx + 2]?.value !== null && params[idx + 2]?.value !== undefined) {
- return { index: params[idx + 2].value };
- }
- if (next.value === 2) {
- const r4 = params[idx + 2]?.value;
- const g4 = params[idx + 3]?.value;
- const b4 = params[idx + 4]?.value;
- if (r4 !== null && r4 !== undefined && g4 !== null && g4 !== undefined && b4 !== null && b4 !== undefined) {
- return { r: r4, g: g4, b: b4 };
- }
- }
- return null;
-}
-function applySGR(paramStr, style) {
- const params = parseParams(paramStr);
- let s4 = { ...style };
- let i5 = 0;
- while (i5 < params.length) {
- const p4 = params[i5];
- const code = p4.value ?? 0;
- if (code === 0) {
- s4 = defaultStyle2();
- i5++;
- continue;
- }
- if (code === 1) {
- s4.bold = true;
- i5++;
- continue;
- }
- if (code === 2) {
- s4.dim = true;
- i5++;
- continue;
- }
- if (code === 3) {
- s4.italic = true;
- i5++;
- continue;
- }
- if (code === 4) {
- s4.underline = p4.colon ? UNDERLINE_STYLES[p4.subparams[0]] ?? "single" : "single";
- i5++;
- continue;
- }
- if (code === 5 || code === 6) {
- s4.blink = true;
- i5++;
- continue;
- }
- if (code === 7) {
- s4.inverse = true;
- i5++;
- continue;
- }
- if (code === 8) {
- s4.hidden = true;
- i5++;
- continue;
- }
- if (code === 9) {
- s4.strikethrough = true;
- i5++;
- continue;
- }
- if (code === 21) {
- s4.underline = "double";
- i5++;
- continue;
- }
- if (code === 22) {
- s4.bold = false;
- s4.dim = false;
- i5++;
- continue;
- }
- if (code === 23) {
- s4.italic = false;
- i5++;
- continue;
- }
- if (code === 24) {
- s4.underline = "none";
- i5++;
- continue;
- }
- if (code === 25) {
- s4.blink = false;
- i5++;
- continue;
- }
- if (code === 27) {
- s4.inverse = false;
- i5++;
- continue;
- }
- if (code === 28) {
- s4.hidden = false;
- i5++;
- continue;
- }
- if (code === 29) {
- s4.strikethrough = false;
- i5++;
- continue;
- }
- if (code === 53) {
- s4.overline = true;
- i5++;
- continue;
- }
- if (code === 55) {
- s4.overline = false;
- i5++;
- continue;
- }
- if (code >= 30 && code <= 37) {
- s4.fg = { type: "named", name: NAMED_COLORS[code - 30] };
- i5++;
- continue;
- }
- if (code === 39) {
- s4.fg = { type: "default" };
- i5++;
- continue;
- }
- if (code >= 40 && code <= 47) {
- s4.bg = { type: "named", name: NAMED_COLORS[code - 40] };
- i5++;
- continue;
- }
- if (code === 49) {
- s4.bg = { type: "default" };
- i5++;
- continue;
- }
- if (code >= 90 && code <= 97) {
- s4.fg = { type: "named", name: NAMED_COLORS[code - 90 + 8] };
- i5++;
- continue;
- }
- if (code >= 100 && code <= 107) {
- s4.bg = { type: "named", name: NAMED_COLORS[code - 100 + 8] };
- i5++;
- continue;
- }
- if (code === 38) {
- const c8 = parseExtendedColor(params, i5);
- if (c8) {
- s4.fg = "index" in c8 ? { type: "indexed", index: c8.index } : { type: "rgb", ...c8 };
- i5 += p4.colon ? 1 : ("index" in c8) ? 3 : 5;
- continue;
- }
- }
- if (code === 48) {
- const c8 = parseExtendedColor(params, i5);
- if (c8) {
- s4.bg = "index" in c8 ? { type: "indexed", index: c8.index } : { type: "rgb", ...c8 };
- i5 += p4.colon ? 1 : ("index" in c8) ? 3 : 5;
- continue;
- }
- }
- if (code === 58) {
- const c8 = parseExtendedColor(params, i5);
- if (c8) {
- s4.underlineColor = "index" in c8 ? { type: "indexed", index: c8.index } : { type: "rgb", ...c8 };
- i5 += p4.colon ? 1 : ("index" in c8) ? 3 : 5;
- continue;
- }
- }
- if (code === 59) {
- s4.underlineColor = { type: "default" };
- i5++;
- continue;
- }
- i5++;
- }
- return s4;
-}
-var NAMED_COLORS, UNDERLINE_STYLES;
-var init_sgr = __esm(() => {
- NAMED_COLORS = [
- "black",
- "red",
- "green",
- "yellow",
- "blue",
- "magenta",
- "cyan",
- "white",
- "brightBlack",
- "brightRed",
- "brightGreen",
- "brightYellow",
- "brightBlue",
- "brightMagenta",
- "brightCyan",
- "brightWhite"
- ];
- UNDERLINE_STYLES = [
- "none",
- "single",
- "double",
- "curly",
- "dotted",
- "dashed"
- ];
-});
-
-// src/ink/termio/parser.ts
-function isEmoji(codePoint) {
- return codePoint >= 9728 && codePoint <= 9983 || codePoint >= 9984 && codePoint <= 10175 || codePoint >= 127744 && codePoint <= 129535 || codePoint >= 129536 && codePoint <= 129791 || codePoint >= 127456 && codePoint <= 127487;
-}
-function isEastAsianWide(codePoint) {
- return codePoint >= 4352 && codePoint <= 4447 || codePoint >= 11904 && codePoint <= 40959 || codePoint >= 44032 && codePoint <= 55203 || codePoint >= 63744 && codePoint <= 64255 || codePoint >= 65040 && codePoint <= 65055 || codePoint >= 65072 && codePoint <= 65135 || codePoint >= 65280 && codePoint <= 65376 || codePoint >= 65504 && codePoint <= 65510 || codePoint >= 131072 && codePoint <= 196605 || codePoint >= 196608 && codePoint <= 262141;
-}
-function hasMultipleCodepoints(str) {
- let count3 = 0;
- for (const _ of str) {
- count3++;
- if (count3 > 1)
- return true;
- }
- return false;
-}
-function graphemeWidth(grapheme) {
- if (hasMultipleCodepoints(grapheme))
- return 2;
- const codePoint = grapheme.codePointAt(0);
- if (codePoint === undefined)
- return 1;
- if (isEmoji(codePoint) || isEastAsianWide(codePoint))
- return 2;
- return 1;
-}
-function* segmentGraphemes(str) {
- for (const { segment } of getGraphemeSegmenter().segment(str)) {
- yield { value: segment, width: graphemeWidth(segment) };
- }
-}
-function parseCSIParams(paramStr) {
- if (paramStr === "")
- return [];
- return paramStr.split(/[;:]/).map((s4) => s4 === "" ? 0 : parseInt(s4, 10));
-}
-function parseCSI(rawSequence) {
- const inner = rawSequence.slice(2);
- if (inner.length === 0)
- return null;
- const finalByte = inner.charCodeAt(inner.length - 1);
- const beforeFinal = inner.slice(0, -1);
- let privateMode = "";
- let paramStr = beforeFinal;
- let intermediate = "";
- if (beforeFinal.length > 0 && "?>=".includes(beforeFinal[0])) {
- privateMode = beforeFinal[0];
- paramStr = beforeFinal.slice(1);
- }
- const intermediateMatch = paramStr.match(/([^0-9;:]+)$/);
- if (intermediateMatch) {
- intermediate = intermediateMatch[1];
- paramStr = paramStr.slice(0, -intermediate.length);
- }
- const params = parseCSIParams(paramStr);
- const p0 = params[0] ?? 1;
- const p1 = params[1] ?? 1;
- if (finalByte === CSI.SGR && privateMode === "") {
- return { type: "sgr", params: paramStr };
- }
- if (finalByte === CSI.CUU) {
- return {
- type: "cursor",
- action: { type: "move", direction: "up", count: p0 }
- };
- }
- if (finalByte === CSI.CUD) {
- return {
- type: "cursor",
- action: { type: "move", direction: "down", count: p0 }
- };
- }
- if (finalByte === CSI.CUF) {
- return {
- type: "cursor",
- action: { type: "move", direction: "forward", count: p0 }
- };
- }
- if (finalByte === CSI.CUB) {
- return {
- type: "cursor",
- action: { type: "move", direction: "back", count: p0 }
- };
- }
- if (finalByte === CSI.CNL) {
- return { type: "cursor", action: { type: "nextLine", count: p0 } };
- }
- if (finalByte === CSI.CPL) {
- return { type: "cursor", action: { type: "prevLine", count: p0 } };
- }
- if (finalByte === CSI.CHA) {
- return { type: "cursor", action: { type: "column", col: p0 } };
- }
- if (finalByte === CSI.CUP || finalByte === CSI.HVP) {
- return { type: "cursor", action: { type: "position", row: p0, col: p1 } };
- }
- if (finalByte === CSI.VPA) {
- return { type: "cursor", action: { type: "row", row: p0 } };
- }
- if (finalByte === CSI.ED) {
- const region = ERASE_DISPLAY[params[0] ?? 0] ?? "toEnd";
- return { type: "erase", action: { type: "display", region } };
- }
- if (finalByte === CSI.EL) {
- const region = ERASE_LINE_REGION[params[0] ?? 0] ?? "toEnd";
- return { type: "erase", action: { type: "line", region } };
- }
- if (finalByte === CSI.ECH) {
- return { type: "erase", action: { type: "chars", count: p0 } };
- }
- if (finalByte === CSI.SU) {
- return { type: "scroll", action: { type: "up", count: p0 } };
- }
- if (finalByte === CSI.SD) {
- return { type: "scroll", action: { type: "down", count: p0 } };
- }
- if (finalByte === CSI.DECSTBM) {
- return {
- type: "scroll",
- action: { type: "setRegion", top: p0, bottom: p1 }
- };
- }
- if (finalByte === CSI.SCOSC) {
- return { type: "cursor", action: { type: "save" } };
- }
- if (finalByte === CSI.SCORC) {
- return { type: "cursor", action: { type: "restore" } };
- }
- if (finalByte === CSI.DECSCUSR && intermediate === " ") {
- const styleInfo = CURSOR_STYLES[p0] ?? CURSOR_STYLES[0];
- return { type: "cursor", action: { type: "style", ...styleInfo } };
- }
- if (privateMode === "?" && (finalByte === CSI.SM || finalByte === CSI.RM)) {
- const enabled2 = finalByte === CSI.SM;
- if (p0 === DEC.CURSOR_VISIBLE) {
- return {
- type: "cursor",
- action: enabled2 ? { type: "show" } : { type: "hide" }
- };
- }
- if (p0 === DEC.ALT_SCREEN_CLEAR || p0 === DEC.ALT_SCREEN) {
- return { type: "mode", action: { type: "alternateScreen", enabled: enabled2 } };
- }
- if (p0 === DEC.BRACKETED_PASTE) {
- return { type: "mode", action: { type: "bracketedPaste", enabled: enabled2 } };
- }
- if (p0 === DEC.MOUSE_NORMAL) {
- return {
- type: "mode",
- action: { type: "mouseTracking", mode: enabled2 ? "normal" : "off" }
- };
- }
- if (p0 === DEC.MOUSE_BUTTON) {
- return {
- type: "mode",
- action: { type: "mouseTracking", mode: enabled2 ? "button" : "off" }
- };
- }
- if (p0 === DEC.MOUSE_ANY) {
- return {
- type: "mode",
- action: { type: "mouseTracking", mode: enabled2 ? "any" : "off" }
- };
- }
- if (p0 === DEC.FOCUS_EVENTS) {
- return { type: "mode", action: { type: "focusEvents", enabled: enabled2 } };
- }
- }
- return { type: "unknown", sequence: rawSequence };
-}
-function identifySequence(seq) {
- if (seq.length < 2)
- return "unknown";
- if (seq.charCodeAt(0) !== C0.ESC)
- return "unknown";
- const second = seq.charCodeAt(1);
- if (second === 91)
- return "csi";
- if (second === 93)
- return "osc";
- if (second === 79)
- return "ss3";
- return "esc";
-}
-
-class Parser {
- tokenizer = createTokenizer();
- style = defaultStyle2();
- inLink = false;
- linkUrl;
- reset() {
- this.tokenizer.reset();
- this.style = defaultStyle2();
- this.inLink = false;
- this.linkUrl = undefined;
- }
- feed(input) {
- const tokens = this.tokenizer.feed(input);
- const actions = [];
- for (const token of tokens) {
- const tokenActions = this.processToken(token);
- actions.push(...tokenActions);
- }
- return actions;
- }
- processToken(token) {
- switch (token.type) {
- case "text":
- return this.processText(token.value);
- case "sequence":
- return this.processSequence(token.value);
- }
- }
- processText(text) {
- const actions = [];
- let current = "";
- for (const char of text) {
- if (char.charCodeAt(0) === C0.BEL) {
- if (current) {
- const graphemes = [...segmentGraphemes(current)];
- if (graphemes.length > 0) {
- actions.push({ type: "text", graphemes, style: { ...this.style } });
- }
- current = "";
- }
- actions.push({ type: "bell" });
- } else {
- current += char;
- }
- }
- if (current) {
- const graphemes = [...segmentGraphemes(current)];
- if (graphemes.length > 0) {
- actions.push({ type: "text", graphemes, style: { ...this.style } });
- }
- }
- return actions;
- }
- processSequence(seq) {
- const seqType = identifySequence(seq);
- switch (seqType) {
- case "csi": {
- const action = parseCSI(seq);
- if (!action)
- return [];
- if (action.type === "sgr") {
- this.style = applySGR(action.params, this.style);
- return [];
- }
- return [action];
- }
- case "osc": {
- let content = seq.slice(2);
- if (content.endsWith("\x07")) {
- content = content.slice(0, -1);
- } else if (content.endsWith("\x1B\\")) {
- content = content.slice(0, -2);
- }
- const action = parseOSC(content);
- if (action) {
- if (action.type === "link") {
- if (action.action.type === "start") {
- this.inLink = true;
- this.linkUrl = action.action.url;
- } else {
- this.inLink = false;
- this.linkUrl = undefined;
- }
- }
- return [action];
- }
- return [];
- }
- case "esc": {
- const escContent = seq.slice(1);
- const action = parseEsc(escContent);
- return action ? [action] : [];
- }
- case "ss3":
- return [{ type: "unknown", sequence: seq }];
- default:
- return [{ type: "unknown", sequence: seq }];
- }
- }
-}
-var init_parser9 = __esm(() => {
- init_intl();
- init_ansi();
- init_csi();
- init_dec();
- init_osc();
- init_sgr();
- init_tokenize();
-});
-
-// src/ink/termio.ts
-var init_termio = __esm(() => {
- init_parser9();
-});
-
-// src/ink/Ansi.tsx
-function parseToSpans(input) {
- const parser2 = new Parser;
- const actions = parser2.feed(input);
- const spans = [];
- let currentHyperlink;
- for (const action of actions) {
- if (action.type === "link") {
- if (action.action.type === "start") {
- currentHyperlink = action.action.url;
- } else {
- currentHyperlink = undefined;
- }
- continue;
- }
- if (action.type === "text") {
- const text = action.graphemes.map((g4) => g4.value).join("");
- if (!text)
- continue;
- const props = textStyleToSpanProps(action.style);
- if (currentHyperlink) {
- props.hyperlink = currentHyperlink;
- }
- const lastSpan = spans[spans.length - 1];
- if (lastSpan && propsEqual(lastSpan.props, props)) {
- lastSpan.text += text;
- } else {
- spans.push({
- text,
- props
- });
- }
- }
- }
- return spans;
-}
-function textStyleToSpanProps(style) {
- const props = {};
- if (style.bold)
- props.bold = true;
- if (style.dim)
- props.dim = true;
- if (style.italic)
- props.italic = true;
- if (style.underline !== "none")
- props.underline = true;
- if (style.strikethrough)
- props.strikethrough = true;
- if (style.inverse)
- props.inverse = true;
- const fgColor = colorToString(style.fg);
- if (fgColor)
- props.color = fgColor;
- const bgColor = colorToString(style.bg);
- if (bgColor)
- props.backgroundColor = bgColor;
- return props;
-}
-function colorToString(color2) {
- switch (color2.type) {
- case "named":
- return NAMED_COLOR_MAP[color2.name];
- case "indexed":
- return `ansi256(${color2.index})`;
- case "rgb":
- return `rgb(${color2.r},${color2.g},${color2.b})`;
- case "default":
- return;
- }
-}
-function propsEqual(a5, b4) {
- return a5.color === b4.color && a5.backgroundColor === b4.backgroundColor && a5.bold === b4.bold && a5.dim === b4.dim && a5.italic === b4.italic && a5.underline === b4.underline && a5.strikethrough === b4.strikethrough && a5.inverse === b4.inverse && a5.hyperlink === b4.hyperlink;
-}
-function hasAnyProps(props) {
- return props.color !== undefined || props.backgroundColor !== undefined || props.dim === true || props.bold === true || props.italic === true || props.underline === true || props.strikethrough === true || props.inverse === true || props.hyperlink !== undefined;
-}
-function hasAnyTextProps(props) {
- return props.color !== undefined || props.backgroundColor !== undefined || props.dim === true || props.bold === true || props.italic === true || props.underline === true || props.strikethrough === true || props.inverse === true;
-}
-function StyledText(t0) {
- const $2 = import_compiler_runtime9.c(14);
- let bold2;
- let children;
- let dim2;
- let rest;
- if ($2[0] !== t0) {
- ({
- bold: bold2,
- dim: dim2,
- children,
- ...rest
- } = t0);
- $2[0] = t0;
- $2[1] = bold2;
- $2[2] = children;
- $2[3] = dim2;
- $2[4] = rest;
- } else {
- bold2 = $2[1];
- children = $2[2];
- dim2 = $2[3];
- rest = $2[4];
- }
- if (dim2) {
- let t12;
- if ($2[5] !== children || $2[6] !== rest) {
- t12 = /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
- ...rest,
- dim: true,
- children
- }, undefined, false, undefined, this);
- $2[5] = children;
- $2[6] = rest;
- $2[7] = t12;
- } else {
- t12 = $2[7];
- }
- return t12;
- }
- if (bold2) {
- let t12;
- if ($2[8] !== children || $2[9] !== rest) {
- t12 = /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
- ...rest,
- bold: true,
- children
- }, undefined, false, undefined, this);
- $2[8] = children;
- $2[9] = rest;
- $2[10] = t12;
- } else {
- t12 = $2[10];
- }
- return t12;
- }
- let t1;
- if ($2[11] !== children || $2[12] !== rest) {
- t1 = /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
- ...rest,
- children
- }, undefined, false, undefined, this);
- $2[11] = children;
- $2[12] = rest;
- $2[13] = t1;
- } else {
- t1 = $2[13];
- }
- return t1;
-}
-var import_compiler_runtime9, import_react13, jsx_dev_runtime12, Ansi, NAMED_COLOR_MAP;
-var init_Ansi = __esm(() => {
- init_Link();
- init_Text();
- init_termio();
- import_compiler_runtime9 = __toESM(require_compiler_runtime(), 1);
- import_react13 = __toESM(require_react(), 1);
- jsx_dev_runtime12 = __toESM(require_jsx_dev_runtime(), 1);
- Ansi = import_react13.default.memo(function Ansi2(t0) {
- const $2 = import_compiler_runtime9.c(12);
- const {
- children,
- dimColor
- } = t0;
- if (typeof children !== "string") {
- let t12;
- if ($2[0] !== children || $2[1] !== dimColor) {
- t12 = dimColor ? /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
- dim: true,
- children: String(children)
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
- children: String(children)
- }, undefined, false, undefined, this);
- $2[0] = children;
- $2[1] = dimColor;
- $2[2] = t12;
- } else {
- t12 = $2[2];
- }
- return t12;
- }
- if (children === "") {
- return null;
- }
- let t1;
- let t22;
- if ($2[3] !== children || $2[4] !== dimColor) {
- t22 = Symbol.for("react.early_return_sentinel");
- bb0: {
- const spans = parseToSpans(children);
- if (spans.length === 0) {
- t22 = null;
- break bb0;
- }
- if (spans.length === 1 && !hasAnyProps(spans[0].props)) {
- t22 = dimColor ? /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
- dim: true,
- children: spans[0].text
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
- children: spans[0].text
- }, undefined, false, undefined, this);
- break bb0;
- }
- let t33;
- if ($2[7] !== dimColor) {
- t33 = (span, i5) => {
- const hyperlink = span.props.hyperlink;
- if (dimColor) {
- span.props.dim = true;
- }
- const hasTextProps = hasAnyTextProps(span.props);
- if (hyperlink) {
- return hasTextProps ? /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Link, {
- url: hyperlink,
- children: /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(StyledText, {
- color: span.props.color,
- backgroundColor: span.props.backgroundColor,
- dim: span.props.dim,
- bold: span.props.bold,
- italic: span.props.italic,
- underline: span.props.underline,
- strikethrough: span.props.strikethrough,
- inverse: span.props.inverse,
- children: span.text
- }, undefined, false, undefined, this)
- }, i5, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Link, {
- url: hyperlink,
- children: span.text
- }, i5, false, undefined, this);
- }
- return hasTextProps ? /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(StyledText, {
- color: span.props.color,
- backgroundColor: span.props.backgroundColor,
- dim: span.props.dim,
- bold: span.props.bold,
- italic: span.props.italic,
- underline: span.props.underline,
- strikethrough: span.props.strikethrough,
- inverse: span.props.inverse,
- children: span.text
- }, i5, false, undefined, this) : span.text;
- };
- $2[7] = dimColor;
- $2[8] = t33;
- } else {
- t33 = $2[8];
- }
- t1 = spans.map(t33);
- }
- $2[3] = children;
- $2[4] = dimColor;
- $2[5] = t1;
- $2[6] = t22;
- } else {
- t1 = $2[5];
- t22 = $2[6];
- }
- if (t22 !== Symbol.for("react.early_return_sentinel")) {
- return t22;
- }
- const content = t1;
- let t32;
- if ($2[9] !== content || $2[10] !== dimColor) {
- t32 = dimColor ? /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
- dim: true,
- children: content
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime12.jsxDEV(Text, {
- children: content
- }, undefined, false, undefined, this);
- $2[9] = content;
- $2[10] = dimColor;
- $2[11] = t32;
- } else {
- t32 = $2[11];
- }
- return t32;
- });
- NAMED_COLOR_MAP = {
- black: "ansi:black",
- red: "ansi:red",
- green: "ansi:green",
- yellow: "ansi:yellow",
- blue: "ansi:blue",
- magenta: "ansi:magenta",
- cyan: "ansi:cyan",
- white: "ansi:white",
- brightBlack: "ansi:blackBright",
- brightRed: "ansi:redBright",
- brightGreen: "ansi:greenBright",
- brightYellow: "ansi:yellowBright",
- brightBlue: "ansi:blueBright",
- brightMagenta: "ansi:magentaBright",
- brightCyan: "ansi:cyanBright",
- brightWhite: "ansi:whiteBright"
- };
-});
-
-// src/ink/components/Button.tsx
-function Button(t0) {
- const $2 = import_compiler_runtime10.c(30);
- let autoFocus;
- let children;
- let onAction;
- let ref;
- let style;
- let t1;
- if ($2[0] !== t0) {
- ({
- onAction,
- tabIndex: t1,
- autoFocus,
- children,
- ref,
- ...style
- } = t0);
- $2[0] = t0;
- $2[1] = autoFocus;
- $2[2] = children;
- $2[3] = onAction;
- $2[4] = ref;
- $2[5] = style;
- $2[6] = t1;
- } else {
- autoFocus = $2[1];
- children = $2[2];
- onAction = $2[3];
- ref = $2[4];
- style = $2[5];
- t1 = $2[6];
- }
- const tabIndex = t1 === undefined ? 0 : t1;
- const [isFocused, setIsFocused] = import_react14.useState(false);
- const [isHovered, setIsHovered] = import_react14.useState(false);
- const [isActive, setIsActive] = import_react14.useState(false);
- const activeTimer = import_react14.useRef(null);
- let t22;
- let t32;
- if ($2[7] === Symbol.for("react.memo_cache_sentinel")) {
- t22 = () => () => {
- if (activeTimer.current) {
- clearTimeout(activeTimer.current);
- }
- };
- t32 = [];
- $2[7] = t22;
- $2[8] = t32;
- } else {
- t22 = $2[7];
- t32 = $2[8];
- }
- import_react14.useEffect(t22, t32);
- let t4;
- if ($2[9] !== onAction) {
- t4 = (e4) => {
- if (e4.key === "return" || e4.key === " ") {
- e4.preventDefault();
- setIsActive(true);
- onAction();
- if (activeTimer.current) {
- clearTimeout(activeTimer.current);
- }
- activeTimer.current = setTimeout(_temp2, 100, setIsActive);
- }
- };
- $2[9] = onAction;
- $2[10] = t4;
- } else {
- t4 = $2[10];
- }
- const handleKeyDown = t4;
- let t5;
- if ($2[11] !== onAction) {
- t5 = (_e4) => {
- onAction();
- };
- $2[11] = onAction;
- $2[12] = t5;
- } else {
- t5 = $2[12];
- }
- const handleClick = t5;
- let t6;
- if ($2[13] === Symbol.for("react.memo_cache_sentinel")) {
- t6 = (_e_0) => setIsFocused(true);
- $2[13] = t6;
- } else {
- t6 = $2[13];
- }
- const handleFocus = t6;
- let t7;
- if ($2[14] === Symbol.for("react.memo_cache_sentinel")) {
- t7 = (_e_1) => setIsFocused(false);
- $2[14] = t7;
- } else {
- t7 = $2[14];
- }
- const handleBlur = t7;
- let t8;
- if ($2[15] === Symbol.for("react.memo_cache_sentinel")) {
- t8 = () => setIsHovered(true);
- $2[15] = t8;
- } else {
- t8 = $2[15];
- }
- const handleMouseEnter = t8;
- let t9;
- if ($2[16] === Symbol.for("react.memo_cache_sentinel")) {
- t9 = () => setIsHovered(false);
- $2[16] = t9;
- } else {
- t9 = $2[16];
- }
- const handleMouseLeave = t9;
- let t10;
- if ($2[17] !== children || $2[18] !== isActive || $2[19] !== isFocused || $2[20] !== isHovered) {
- const state3 = {
- focused: isFocused,
- hovered: isHovered,
- active: isActive
- };
- t10 = typeof children === "function" ? children(state3) : children;
- $2[17] = children;
- $2[18] = isActive;
- $2[19] = isFocused;
- $2[20] = isHovered;
- $2[21] = t10;
- } else {
- t10 = $2[21];
- }
- const content = t10;
- let t11;
- if ($2[22] !== autoFocus || $2[23] !== content || $2[24] !== handleClick || $2[25] !== handleKeyDown || $2[26] !== ref || $2[27] !== style || $2[28] !== tabIndex) {
- t11 = /* @__PURE__ */ jsx_dev_runtime13.jsxDEV(Box_default, {
- ref,
- tabIndex,
- autoFocus,
- onKeyDown: handleKeyDown,
- onClick: handleClick,
- onFocus: handleFocus,
- onBlur: handleBlur,
- onMouseEnter: handleMouseEnter,
- onMouseLeave: handleMouseLeave,
- ...style,
- children: content
- }, undefined, false, undefined, this);
- $2[22] = autoFocus;
- $2[23] = content;
- $2[24] = handleClick;
- $2[25] = handleKeyDown;
- $2[26] = ref;
- $2[27] = style;
- $2[28] = tabIndex;
- $2[29] = t11;
- } else {
- t11 = $2[29];
- }
- return t11;
-}
-function _temp2(setter) {
- return setter(false);
-}
-var import_compiler_runtime10, import_react14, jsx_dev_runtime13, Button_default;
-var init_Button = __esm(() => {
- init_Box();
- import_compiler_runtime10 = __toESM(require_compiler_runtime(), 1);
- import_react14 = __toESM(require_react(), 1);
- jsx_dev_runtime13 = __toESM(require_jsx_dev_runtime(), 1);
- Button_default = Button;
-});
-
-// src/ink/components/Newline.tsx
-function Newline(t0) {
- const $2 = import_compiler_runtime11.c(4);
- const {
- count: t1
- } = t0;
- const count3 = t1 === undefined ? 1 : t1;
- let t22;
- if ($2[0] !== count3) {
- t22 = `
-`.repeat(count3);
- $2[0] = count3;
- $2[1] = t22;
- } else {
- t22 = $2[1];
- }
- let t32;
- if ($2[2] !== t22) {
- t32 = /* @__PURE__ */ jsx_dev_runtime14.jsxDEV("ink-text", {
- children: t22
- }, undefined, false, undefined, this);
- $2[2] = t22;
- $2[3] = t32;
- } else {
- t32 = $2[3];
- }
- return t32;
-}
-var import_compiler_runtime11, jsx_dev_runtime14;
-var init_Newline = __esm(() => {
- import_compiler_runtime11 = __toESM(require_compiler_runtime(), 1);
- jsx_dev_runtime14 = __toESM(require_jsx_dev_runtime(), 1);
-});
-
-// src/ink/components/NoSelect.tsx
-function NoSelect(t0) {
- const $2 = import_compiler_runtime12.c(8);
- let boxProps;
- let children;
- let fromLeftEdge;
- if ($2[0] !== t0) {
- ({
- children,
- fromLeftEdge,
- ...boxProps
- } = t0);
- $2[0] = t0;
- $2[1] = boxProps;
- $2[2] = children;
- $2[3] = fromLeftEdge;
- } else {
- boxProps = $2[1];
- children = $2[2];
- fromLeftEdge = $2[3];
- }
- const t1 = fromLeftEdge ? "from-left-edge" : true;
- let t22;
- if ($2[4] !== boxProps || $2[5] !== children || $2[6] !== t1) {
- t22 = /* @__PURE__ */ jsx_dev_runtime15.jsxDEV(Box_default, {
- ...boxProps,
- noSelect: t1,
- children
- }, undefined, false, undefined, this);
- $2[4] = boxProps;
- $2[5] = children;
- $2[6] = t1;
- $2[7] = t22;
- } else {
- t22 = $2[7];
- }
- return t22;
-}
-var import_compiler_runtime12, jsx_dev_runtime15;
-var init_NoSelect = __esm(() => {
- init_Box();
- import_compiler_runtime12 = __toESM(require_compiler_runtime(), 1);
- jsx_dev_runtime15 = __toESM(require_jsx_dev_runtime(), 1);
-});
-
-// src/ink/components/RawAnsi.tsx
-function RawAnsi(t0) {
- const $2 = import_compiler_runtime13.c(6);
- const {
- lines,
- width
- } = t0;
- if (lines.length === 0) {
- return null;
- }
- let t1;
- if ($2[0] !== lines) {
- t1 = lines.join(`
-`);
- $2[0] = lines;
- $2[1] = t1;
- } else {
- t1 = $2[1];
- }
- let t22;
- if ($2[2] !== lines.length || $2[3] !== t1 || $2[4] !== width) {
- t22 = /* @__PURE__ */ jsx_dev_runtime16.jsxDEV("ink-raw-ansi", {
- rawText: t1,
- rawWidth: width,
- rawHeight: lines.length
- }, undefined, false, undefined, this);
- $2[2] = lines.length;
- $2[3] = t1;
- $2[4] = width;
- $2[5] = t22;
- } else {
- t22 = $2[5];
- }
- return t22;
-}
-var import_compiler_runtime13, jsx_dev_runtime16;
-var init_RawAnsi = __esm(() => {
- import_compiler_runtime13 = __toESM(require_compiler_runtime(), 1);
- jsx_dev_runtime16 = __toESM(require_jsx_dev_runtime(), 1);
-});
-
-// src/ink/components/Spacer.tsx
-function Spacer() {
- const $2 = import_compiler_runtime14.c(1);
- let t0;
- if ($2[0] === Symbol.for("react.memo_cache_sentinel")) {
- t0 = /* @__PURE__ */ jsx_dev_runtime17.jsxDEV(Box_default, {
- flexGrow: 1
- }, undefined, false, undefined, this);
- $2[0] = t0;
- } else {
- t0 = $2[0];
- }
- return t0;
-}
-var import_compiler_runtime14, jsx_dev_runtime17;
-var init_Spacer = __esm(() => {
- init_Box();
- import_compiler_runtime14 = __toESM(require_compiler_runtime(), 1);
- jsx_dev_runtime17 = __toESM(require_jsx_dev_runtime(), 1);
-});
-
-// src/ink/hooks/use-terminal-viewport.ts
-function useTerminalViewport() {
- const terminalSize = import_react15.useContext(TerminalSizeContext);
- const elementRef = import_react15.useRef(null);
- const entryRef = import_react15.useRef({ isVisible: true });
- const setElement = import_react15.useCallback((el) => {
- elementRef.current = el;
- }, []);
- import_react15.useLayoutEffect(() => {
- const element = elementRef.current;
- if (!element?.yogaNode || !terminalSize) {
- return;
- }
- const height = element.yogaNode.getComputedHeight();
- const rows = terminalSize.rows;
- let absoluteTop = element.yogaNode.getComputedTop();
- let parent = element.parentNode;
- let root2 = element.yogaNode;
- while (parent) {
- if (parent.yogaNode) {
- absoluteTop += parent.yogaNode.getComputedTop();
- root2 = parent.yogaNode;
- }
- if (parent.scrollTop)
- absoluteTop -= parent.scrollTop;
- parent = parent.parentNode;
- }
- const screenHeight = root2.getComputedHeight();
- const bottom = absoluteTop + height;
- const cursorRestoreScroll = screenHeight > rows ? 1 : 0;
- const viewportY = Math.max(0, screenHeight - rows) + cursorRestoreScroll;
- const viewportBottom = viewportY + rows;
- const visible = bottom > viewportY && absoluteTop < viewportBottom;
- if (visible !== entryRef.current.isVisible) {
- entryRef.current = { isVisible: visible };
- }
- });
- return [setElement, entryRef.current];
-}
-var import_react15;
-var init_use_terminal_viewport = __esm(() => {
- init_TerminalSizeContext();
- import_react15 = __toESM(require_react(), 1);
-});
-
-// src/ink/hooks/use-animation-frame.ts
-function useAnimationFrame(intervalMs = 16) {
- const clock = import_react16.useContext(ClockContext);
- const [viewportRef, { isVisible }] = useTerminalViewport();
- const [time3, setTime] = import_react16.useState(() => clock?.now() ?? 0);
- const active = isVisible && intervalMs !== null;
- import_react16.useEffect(() => {
- if (!clock || !active)
- return;
- let lastUpdate = clock.now();
- const onChange = () => {
- const now2 = clock.now();
- if (now2 - lastUpdate >= intervalMs) {
- lastUpdate = now2;
- setTime(now2);
- }
- };
- return clock.subscribe(onChange, true);
- }, [clock, intervalMs, active]);
- return [viewportRef, time3];
-}
-var import_react16;
-var init_use_animation_frame = __esm(() => {
- init_ClockContext();
- init_use_terminal_viewport();
- import_react16 = __toESM(require_react(), 1);
-});
-
-// src/ink/hooks/use-app.ts
-var import_react17, useApp = () => import_react17.useContext(AppContext_default), use_app_default;
-var init_use_app = __esm(() => {
- init_AppContext();
- import_react17 = __toESM(require_react(), 1);
- use_app_default = useApp;
-});
-
-// node_modules/lodash.debounce/index.js
-var require_lodash8 = __commonJS((exports, module) => {
- var FUNC_ERROR_TEXT4 = "Expected a function";
- var NAN2 = 0 / 0;
- var symbolTag5 = "[object Symbol]";
- var reTrim = /^\s+|\s+$/g;
- var reIsBadHex2 = /^[-+]0x[0-9a-f]+$/i;
- var reIsBinary2 = /^0b[01]+$/i;
- var reIsOctal2 = /^0o[0-7]+$/i;
- var freeParseInt2 = parseInt;
- var freeGlobal2 = typeof global == "object" && global && global.Object === Object && global;
- var freeSelf2 = typeof self == "object" && self && self.Object === Object && self;
- var root2 = freeGlobal2 || freeSelf2 || Function("return this")();
- var objectProto17 = Object.prototype;
- var objectToString4 = objectProto17.toString;
- var nativeMax3 = Math.max;
- var nativeMin2 = Math.min;
- var now2 = function() {
- return root2.Date.now();
- };
- function debounce2(func, wait, options2) {
- var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
- if (typeof func != "function") {
- throw new TypeError(FUNC_ERROR_TEXT4);
- }
- wait = toNumber2(wait) || 0;
- if (isObject6(options2)) {
- leading = !!options2.leading;
- maxing = "maxWait" in options2;
- maxWait = maxing ? nativeMax3(toNumber2(options2.maxWait) || 0, wait) : maxWait;
- trailing = "trailing" in options2 ? !!options2.trailing : trailing;
- }
- function invokeFunc(time3) {
- var args = lastArgs, thisArg = lastThis;
- lastArgs = lastThis = undefined;
- lastInvokeTime = time3;
- result = func.apply(thisArg, args);
- return result;
- }
- function leadingEdge2(time3) {
- lastInvokeTime = time3;
- timerId = setTimeout(timerExpired, wait);
- return leading ? invokeFunc(time3) : result;
- }
- function remainingWait(time3) {
- var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime, result2 = wait - timeSinceLastCall;
- return maxing ? nativeMin2(result2, maxWait - timeSinceLastInvoke) : result2;
- }
- function shouldInvoke(time3) {
- var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime;
- return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
- }
- function timerExpired() {
- var time3 = now2();
- if (shouldInvoke(time3)) {
- return trailingEdge2(time3);
- }
- timerId = setTimeout(timerExpired, remainingWait(time3));
- }
- function trailingEdge2(time3) {
- timerId = undefined;
- if (trailing && lastArgs) {
- return invokeFunc(time3);
- }
- lastArgs = lastThis = undefined;
- return result;
- }
- function cancel() {
- if (timerId !== undefined) {
- clearTimeout(timerId);
- }
- lastInvokeTime = 0;
- lastArgs = lastCallTime = lastThis = timerId = undefined;
- }
- function flush() {
- return timerId === undefined ? result : trailingEdge2(now2());
- }
- function debounced() {
- var time3 = now2(), isInvoking = shouldInvoke(time3);
- lastArgs = arguments;
- lastThis = this;
- lastCallTime = time3;
- if (isInvoking) {
- if (timerId === undefined) {
- return leadingEdge2(lastCallTime);
- }
- if (maxing) {
- timerId = setTimeout(timerExpired, wait);
- return invokeFunc(lastCallTime);
- }
- }
- if (timerId === undefined) {
- timerId = setTimeout(timerExpired, wait);
- }
- return result;
- }
- debounced.cancel = cancel;
- debounced.flush = flush;
- return debounced;
- }
- function isObject6(value) {
- var type = typeof value;
- return !!value && (type == "object" || type == "function");
- }
- function isObjectLike2(value) {
- return !!value && typeof value == "object";
- }
- function isSymbol2(value) {
- return typeof value == "symbol" || isObjectLike2(value) && objectToString4.call(value) == symbolTag5;
- }
- function toNumber2(value) {
- if (typeof value == "number") {
- return value;
- }
- if (isSymbol2(value)) {
- return NAN2;
- }
- if (isObject6(value)) {
- var other2 = typeof value.valueOf == "function" ? value.valueOf() : value;
- value = isObject6(other2) ? other2 + "" : other2;
- }
- if (typeof value != "string") {
- return value === 0 ? value : +value;
- }
- value = value.replace(reTrim, "");
- var isBinary = reIsBinary2.test(value);
- return isBinary || reIsOctal2.test(value) ? freeParseInt2(value.slice(2), isBinary ? 2 : 8) : reIsBadHex2.test(value) ? NAN2 : +value;
- }
- module.exports = debounce2;
-});
-
-// node_modules/usehooks-ts/dist/index.js
-function useInterval(callback, delay4) {
- const savedCallback = import_react18.useRef(callback);
- useIsomorphicLayoutEffect(() => {
- savedCallback.current = callback;
- }, [callback]);
- import_react18.useEffect(() => {
- if (delay4 === null) {
- return;
- }
- const id = setInterval(() => {
- savedCallback.current();
- }, delay4);
- return () => {
- clearInterval(id);
- };
- }, [delay4]);
-}
-function useEventCallback(fn) {
- const ref = import_react18.useRef(() => {
- throw new Error("Cannot call an event handler while rendering.");
- });
- useIsomorphicLayoutEffect(() => {
- ref.current = fn;
- }, [fn]);
- return import_react18.useCallback((...args) => {
- var _a8;
- return (_a8 = ref.current) == null ? undefined : _a8.call(ref, ...args);
- }, [ref]);
-}
-function useUnmount(func) {
- const funcRef = import_react18.useRef(func);
- funcRef.current = func;
- import_react18.useEffect(() => () => {
- funcRef.current();
- }, []);
-}
-function useDebounceCallback(func, delay4 = 500, options2) {
- const debouncedFunc = import_react18.useRef();
- useUnmount(() => {
- if (debouncedFunc.current) {
- debouncedFunc.current.cancel();
- }
- });
- const debounced = import_react18.useMemo(() => {
- const debouncedFuncInstance = import_lodash.default(func, delay4, options2);
- const wrappedFunc = (...args) => {
- return debouncedFuncInstance(...args);
- };
- wrappedFunc.cancel = () => {
- debouncedFuncInstance.cancel();
- };
- wrappedFunc.isPending = () => {
- return !!debouncedFunc.current;
- };
- wrappedFunc.flush = () => {
- return debouncedFuncInstance.flush();
- };
- return wrappedFunc;
- }, [func, delay4, options2]);
- import_react18.useEffect(() => {
- debouncedFunc.current = import_lodash.default(func, delay4, options2);
- }, [func, delay4, options2]);
- return debounced;
-}
-var import_react18, import_lodash, useIsomorphicLayoutEffect;
-var init_dist4 = __esm(() => {
- import_react18 = __toESM(require_react(), 1);
- import_lodash = __toESM(require_lodash8(), 1);
- useIsomorphicLayoutEffect = typeof window !== "undefined" ? import_react18.useLayoutEffect : import_react18.useEffect;
-});
-
-// src/ink/hooks/use-input.ts
-var import_react19, useInput = (inputHandler, options2 = {}) => {
- const { setRawMode, internal_exitOnCtrlC, internal_eventEmitter } = use_stdin_default();
- import_react19.useLayoutEffect(() => {
- if (options2.isActive === false) {
- return;
- }
- setRawMode(true);
- return () => {
- setRawMode(false);
- };
- }, [options2.isActive, setRawMode]);
- const handleData = useEventCallback((event) => {
- if (options2.isActive === false) {
- return;
- }
- const { input, key } = event;
- if (!(input === "c" && key.ctrl) || !internal_exitOnCtrlC) {
- inputHandler(input, key, event);
- }
- });
- import_react19.useEffect(() => {
- internal_eventEmitter?.on("input", handleData);
- return () => {
- internal_eventEmitter?.removeListener("input", handleData);
- };
- }, [internal_eventEmitter, handleData]);
-}, use_input_default;
-var init_use_input = __esm(() => {
- init_dist4();
- init_use_stdin();
- import_react19 = __toESM(require_react(), 1);
- use_input_default = useInput;
-});
-
-// src/ink/hooks/use-interval.ts
-function useAnimationTimer(intervalMs) {
- const clock = import_react20.useContext(ClockContext);
- const [time3, setTime] = import_react20.useState(() => clock?.now() ?? 0);
- import_react20.useEffect(() => {
- if (!clock)
- return;
- let lastUpdate = clock.now();
- const onChange = () => {
- const now2 = clock.now();
- if (now2 - lastUpdate >= intervalMs) {
- lastUpdate = now2;
- setTime(now2);
- }
- };
- return clock.subscribe(onChange, false);
- }, [clock, intervalMs]);
- return time3;
-}
-function useInterval2(callback, intervalMs) {
- const callbackRef = import_react20.useRef(callback);
- callbackRef.current = callback;
- const clock = import_react20.useContext(ClockContext);
- import_react20.useEffect(() => {
- if (!clock || intervalMs === null)
- return;
- let lastUpdate = clock.now();
- const onChange = () => {
- const now2 = clock.now();
- if (now2 - lastUpdate >= intervalMs) {
- lastUpdate = now2;
- callbackRef.current();
- }
- };
- return clock.subscribe(onChange, false);
- }, [clock, intervalMs]);
-}
-var import_react20;
-var init_use_interval = __esm(() => {
- init_ClockContext();
- import_react20 = __toESM(require_react(), 1);
-});
-
-// src/ink/hooks/use-selection.ts
-function useSelection() {
- import_react21.useContext(StdinContext_default);
- const ink = instances_default.get(process.stdout);
- return import_react21.useMemo(() => {
- if (!ink) {
- return {
- copySelection: () => "",
- copySelectionNoClear: () => "",
- clearSelection: () => {},
- hasSelection: () => false,
- getState: () => null,
- subscribe: () => () => {},
- shiftAnchor: () => {},
- shiftSelection: () => {},
- moveFocus: () => {},
- captureScrolledRows: () => {},
- setSelectionBgColor: () => {}
- };
- }
- return {
- copySelection: () => ink.copySelection(),
- copySelectionNoClear: () => ink.copySelectionNoClear(),
- clearSelection: () => ink.clearTextSelection(),
- hasSelection: () => ink.hasTextSelection(),
- getState: () => ink.selection,
- subscribe: (cb) => ink.subscribeToSelectionChange(cb),
- shiftAnchor: (dRow, minRow, maxRow) => shiftAnchor(ink.selection, dRow, minRow, maxRow),
- shiftSelection: (dRow, minRow, maxRow) => ink.shiftSelectionForScroll(dRow, minRow, maxRow),
- moveFocus: (move) => ink.moveSelectionFocus(move),
- captureScrolledRows: (firstRow, lastRow, side) => ink.captureScrolledRows(firstRow, lastRow, side),
- setSelectionBgColor: (color2) => ink.setSelectionBgColor(color2)
- };
- }, [ink]);
-}
-function useHasSelection() {
- import_react21.useContext(StdinContext_default);
- const ink = instances_default.get(process.stdout);
- return import_react21.useSyncExternalStore(ink ? ink.subscribeToSelectionChange : NO_SUBSCRIBE, ink ? ink.hasTextSelection : ALWAYS_FALSE);
-}
-var import_react21, NO_SUBSCRIBE = () => () => {}, ALWAYS_FALSE = () => false;
-var init_use_selection = __esm(() => {
- init_StdinContext();
- init_instances();
- init_selection();
- import_react21 = __toESM(require_react(), 1);
-});
-
-// src/ink/hooks/use-tab-status.ts
-function useTabStatus(kind2) {
- const writeRaw = import_react22.useContext(TerminalWriteContext);
- const prevKindRef = import_react22.useRef(null);
- import_react22.useEffect(() => {
- if (kind2 === null) {
- if (prevKindRef.current !== null && writeRaw && supportsTabStatus()) {
- writeRaw(wrapForMultiplexer(CLEAR_TAB_STATUS));
- }
- prevKindRef.current = null;
- return;
- }
- prevKindRef.current = kind2;
- if (!writeRaw || !supportsTabStatus())
- return;
- writeRaw(wrapForMultiplexer(tabStatus(TAB_STATUS_PRESETS[kind2])));
- }, [kind2, writeRaw]);
-}
-var import_react22, rgb = (r4, g4, b4) => ({
- type: "rgb",
- r: r4,
- g: g4,
- b: b4
-}), TAB_STATUS_PRESETS;
-var init_use_tab_status = __esm(() => {
- init_osc();
- init_useTerminalNotification();
- import_react22 = __toESM(require_react(), 1);
- TAB_STATUS_PRESETS = {
- idle: {
- indicator: rgb(0, 215, 95),
- status: "Idle",
- statusColor: rgb(136, 136, 136)
- },
- busy: {
- indicator: rgb(255, 149, 0),
- status: "Working\u2026",
- statusColor: rgb(255, 149, 0)
- },
- waiting: {
- indicator: rgb(95, 135, 255),
- status: "Waiting",
- statusColor: rgb(95, 135, 255)
- }
- };
-});
-
-// src/ink/hooks/use-terminal-title.ts
-function useTerminalTitle(title) {
- const writeRaw = import_react23.useContext(TerminalWriteContext);
- import_react23.useEffect(() => {
- if (title === null || !writeRaw)
- return;
- const clean = stripAnsi(title);
- if (process.platform === "win32") {
- process.title = clean;
- } else {
- writeRaw(osc(OSC.SET_TITLE_AND_ICON, clean));
- }
- }, [title, writeRaw]);
-}
-var import_react23;
-var init_use_terminal_title = __esm(() => {
- init_strip_ansi();
- init_osc();
- init_useTerminalNotification();
- import_react23 = __toESM(require_react(), 1);
-});
-
-// src/ink/measure-element.ts
-var measureElement = (node) => ({
- width: node.yogaNode?.getComputedWidth() ?? 0,
- height: node.yogaNode?.getComputedHeight() ?? 0
-}), measure_element_default;
-var init_measure_element = __esm(() => {
- measure_element_default = measureElement;
-});
-
-// src/ink.ts
-var exports_ink = {};
-__export(exports_ink, {
- wrapText: () => wrapText2,
- useThemeSetting: () => useThemeSetting,
- useTheme: () => useTheme,
- useTerminalViewport: () => useTerminalViewport,
- useTerminalTitle: () => useTerminalTitle,
- useTerminalFocus: () => useTerminalFocus,
- useTabStatus: () => useTabStatus,
- useStdin: () => use_stdin_default,
- useSelection: () => useSelection,
- usePreviewTheme: () => usePreviewTheme,
- useInterval: () => useInterval2,
- useInput: () => use_input_default,
- useApp: () => use_app_default,
- useAnimationTimer: () => useAnimationTimer,
- useAnimationFrame: () => useAnimationFrame,
- supportsTabStatus: () => supportsTabStatus,
- render: () => render,
- measureElement: () => measure_element_default,
- createRoot: () => createRoot2,
- color: () => color,
- ThemeProvider: () => ThemeProvider,
- Text: () => ThemedText,
- TerminalFocusEvent: () => TerminalFocusEvent,
- Spacer: () => Spacer,
- RawAnsi: () => RawAnsi,
- NoSelect: () => NoSelect,
- Newline: () => Newline,
- Link: () => Link,
- InputEvent: () => InputEvent,
- FocusManager: () => FocusManager,
- EventEmitter: () => EventEmitter3,
- Event: () => Event2,
- ClickEvent: () => ClickEvent,
- Button: () => Button_default,
- Box: () => ThemedBox_default,
- BaseText: () => Text,
- BaseBox: () => Box_default,
- Ansi: () => Ansi
-});
-function withTheme(node) {
- return import_react24.createElement(ThemeProvider, null, node);
-}
-async function render(node, options2) {
- return root_default(withTheme(node), options2);
-}
-async function createRoot2(options2) {
- const root2 = await createRoot(options2);
- return {
- ...root2,
- render: (node) => root2.render(withTheme(node))
- };
-}
-var import_react24;
-var init_ink2 = __esm(() => {
- init_ThemeProvider();
- init_root();
- init_color();
- init_ThemedBox();
- init_ThemedText();
- init_ThemeProvider();
- init_Ansi();
- init_Box();
- init_Button();
- init_Link();
- init_Newline();
- init_NoSelect();
- init_RawAnsi();
- init_Spacer();
- init_Text();
- init_click_event();
- init_emitter();
- init_input_event();
- init_terminal_focus_event();
- init_focus();
- init_use_animation_frame();
- init_use_app();
- init_use_input();
- init_use_interval();
- init_use_selection();
- init_use_stdin();
- init_use_tab_status();
- init_use_terminal_focus();
- init_use_terminal_title();
- init_use_terminal_viewport();
- init_measure_element();
- init_osc();
- init_wrap_text();
- import_react24 = __toESM(require_react(), 1);
-});
-
-// src/hooks/useTerminalSize.ts
-function useTerminalSize() {
- const size = import_react25.useContext(TerminalSizeContext);
- if (!size) {
- throw new Error("useTerminalSize must be used within an Ink App component");
- }
- return size;
-}
-var import_react25;
-var init_useTerminalSize = __esm(() => {
- init_TerminalSizeContext();
- import_react25 = __toESM(require_react(), 1);
-});
-
-// src/components/design-system/Ratchet.tsx
-function Ratchet(t0) {
- const $2 = import_compiler_runtime15.c(10);
- const {
- children,
- lock: t1
- } = t0;
- const lock2 = t1 === undefined ? "always" : t1;
- const [viewportRef, t22] = useTerminalViewport();
- const {
- isVisible
- } = t22;
- const {
- rows
- } = useTerminalSize();
- const innerRef = import_react26.useRef(null);
- const maxHeight = import_react26.useRef(0);
- const [minHeight, setMinHeight] = import_react26.useState(0);
- let t32;
- if ($2[0] !== viewportRef) {
- t32 = (el) => {
- viewportRef(el);
- };
- $2[0] = viewportRef;
- $2[1] = t32;
- } else {
- t32 = $2[1];
- }
- const outerRef = t32;
- const engaged = lock2 === "always" || !isVisible;
- let t4;
- if ($2[2] !== rows) {
- t4 = () => {
- if (!innerRef.current) {
- return;
- }
- const {
- height
- } = measure_element_default(innerRef.current);
- if (height > maxHeight.current) {
- maxHeight.current = Math.min(height, rows);
- setMinHeight(maxHeight.current);
- }
- };
- $2[2] = rows;
- $2[3] = t4;
- } else {
- t4 = $2[3];
- }
- import_react26.useLayoutEffect(t4);
- const t5 = engaged ? minHeight : undefined;
- let t6;
- if ($2[4] !== children) {
- t6 = /* @__PURE__ */ jsx_dev_runtime18.jsxDEV(ThemedBox_default, {
- ref: innerRef,
- flexDirection: "column",
- children
- }, undefined, false, undefined, this);
- $2[4] = children;
- $2[5] = t6;
- } else {
- t6 = $2[5];
- }
- let t7;
- if ($2[6] !== outerRef || $2[7] !== t5 || $2[8] !== t6) {
- t7 = /* @__PURE__ */ jsx_dev_runtime18.jsxDEV(ThemedBox_default, {
- minHeight: t5,
- ref: outerRef,
- children: t6
- }, undefined, false, undefined, this);
- $2[6] = outerRef;
- $2[7] = t5;
- $2[8] = t6;
- $2[9] = t7;
- } else {
- t7 = $2[9];
- }
- return t7;
-}
-var import_compiler_runtime15, import_react26, jsx_dev_runtime18;
-var init_Ratchet = __esm(() => {
- init_useTerminalSize();
- init_use_terminal_viewport();
- init_ink2();
- import_compiler_runtime15 = __toESM(require_compiler_runtime(), 1);
- import_react26 = __toESM(require_react(), 1);
- jsx_dev_runtime18 = __toESM(require_jsx_dev_runtime(), 1);
-});
-
-// src/components/MessageResponse.tsx
-function MessageResponse(t0) {
- const $2 = import_compiler_runtime16.c(8);
- const {
- children,
- height
- } = t0;
- const isMessageResponse = import_react27.useContext(MessageResponseContext);
- if (isMessageResponse) {
- return children;
- }
- let t1;
- if ($2[0] === Symbol.for("react.memo_cache_sentinel")) {
- t1 = /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(NoSelect, {
- fromLeftEdge: true,
- flexShrink: 0,
- children: /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(ThemedText, {
- dimColor: true,
- children: [
- " ",
- "\u23BF \xA0"
- ]
- }, undefined, true, undefined, this)
- }, undefined, false, undefined, this);
- $2[0] = t1;
- } else {
- t1 = $2[0];
- }
- let t22;
- if ($2[1] !== children) {
- t22 = /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(ThemedBox_default, {
- flexShrink: 1,
- flexGrow: 1,
- children
- }, undefined, false, undefined, this);
- $2[1] = children;
- $2[2] = t22;
- } else {
- t22 = $2[2];
- }
- let t32;
- if ($2[3] !== height || $2[4] !== t22) {
- t32 = /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(MessageResponseProvider, {
- children: /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(ThemedBox_default, {
- flexDirection: "row",
- height,
- overflowY: "hidden",
- children: [
- t1,
- t22
- ]
- }, undefined, true, undefined, this)
- }, undefined, false, undefined, this);
- $2[3] = height;
- $2[4] = t22;
- $2[5] = t32;
- } else {
- t32 = $2[5];
- }
- const content = t32;
- if (height !== undefined) {
- return content;
- }
- let t4;
- if ($2[6] !== content) {
- t4 = /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(Ratchet, {
- lock: "offscreen",
- children: content
- }, undefined, false, undefined, this);
- $2[6] = content;
- $2[7] = t4;
- } else {
- t4 = $2[7];
- }
- return t4;
-}
-function MessageResponseProvider(t0) {
- const $2 = import_compiler_runtime16.c(2);
- const {
- children
- } = t0;
- let t1;
- if ($2[0] !== children) {
- t1 = /* @__PURE__ */ jsx_dev_runtime19.jsxDEV(MessageResponseContext.Provider, {
- value: true,
- children
- }, undefined, false, undefined, this);
- $2[0] = children;
- $2[1] = t1;
- } else {
- t1 = $2[1];
- }
- return t1;
-}
-var import_compiler_runtime16, React9, import_react27, jsx_dev_runtime19, MessageResponseContext;
-var init_MessageResponse = __esm(() => {
- init_ink2();
- init_Ratchet();
- import_compiler_runtime16 = __toESM(require_compiler_runtime(), 1);
- React9 = __toESM(require_react(), 1);
- import_react27 = __toESM(require_react(), 1);
- jsx_dev_runtime19 = __toESM(require_jsx_dev_runtime(), 1);
- MessageResponseContext = React9.createContext(false);
-});
-
-// src/tools/AgentTool/agentMemory.ts
-import { join as join27, normalize as normalize4, sep as sep5 } from "path";
-function sanitizeAgentTypeForPath(agentType) {
- return agentType.replace(/:/g, "-");
-}
-function getLocalAgentMemoryDir(dirName) {
- if (process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR) {
- return join27(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR, "projects", sanitizePath2(findCanonicalGitRoot(getProjectRoot()) ?? getProjectRoot()), "agent-memory-local", dirName) + sep5;
- }
- return join27(getCwd(), ".claude", "agent-memory-local", dirName) + sep5;
-}
-function getAgentMemoryDir(agentType, scope) {
- const dirName = sanitizeAgentTypeForPath(agentType);
- switch (scope) {
- case "project":
- return join27(getCwd(), ".claude", "agent-memory", dirName) + sep5;
- case "local":
- return getLocalAgentMemoryDir(dirName);
- case "user":
- return join27(getMemoryBaseDir(), "agent-memory", dirName) + sep5;
- }
-}
-function isAgentMemoryPath(absolutePath) {
- const normalizedPath = normalize4(absolutePath);
- const memoryBase = getMemoryBaseDir();
- if (normalizedPath.startsWith(join27(memoryBase, "agent-memory") + sep5)) {
- return true;
- }
- if (normalizedPath.startsWith(join27(getCwd(), ".claude", "agent-memory") + sep5)) {
- return true;
- }
- if (process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR) {
- if (normalizedPath.includes(sep5 + "agent-memory-local" + sep5) && normalizedPath.startsWith(join27(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR, "projects") + sep5)) {
- return true;
- }
- } else if (normalizedPath.startsWith(join27(getCwd(), ".claude", "agent-memory-local") + sep5)) {
- return true;
- }
- return false;
-}
-function getMemoryScopeDisplay(memory) {
- switch (memory) {
- case "user":
- return `User (${join27(getMemoryBaseDir(), "agent-memory")}/)`;
- case "project":
- return "Project (.claude/agent-memory/)";
- case "local":
- return `Local (${getLocalAgentMemoryDir("...")})`;
- default:
- return "None";
- }
-}
-function loadAgentMemoryPrompt(agentType, scope) {
- let scopeNote;
- switch (scope) {
- case "user":
- scopeNote = "- Since this memory is user-scope, keep learnings general since they apply across all projects";
- break;
- case "project":
- scopeNote = "- Since this memory is project-scope and shared with your team via version control, tailor your memories to this project";
- break;
- case "local":
- scopeNote = "- Since this memory is local-scope (not checked into version control), tailor your memories to this project and machine";
- break;
- }
- const memoryDir = getAgentMemoryDir(agentType, scope);
- ensureMemoryDirExists(memoryDir);
- const coworkExtraGuidelines = process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES;
- return buildMemoryPrompt({
- displayName: "Persistent Agent Memory",
- memoryDir,
- extraGuidelines: coworkExtraGuidelines && coworkExtraGuidelines.trim().length > 0 ? [scopeNote, coworkExtraGuidelines] : [scopeNote]
- });
-}
-var init_agentMemory = __esm(() => {
- init_state();
- init_memdir();
- init_paths();
- init_cwd();
- init_git();
- init_path();
-});
-
-// src/tools/ExitPlanModeTool/constants.ts
-var EXIT_PLAN_MODE_TOOL_NAME = "ExitPlanMode", EXIT_PLAN_MODE_V2_TOOL_NAME = "ExitPlanMode";
-
-// src/utils/filePersistence/outputsScanner.ts
-function getEnvironmentKind() {
- const kind2 = process.env.CLAUDE_CODE_ENVIRONMENT_KIND;
- if (kind2 === "byoc" || kind2 === "anthropic_cloud") {
- return kind2;
- }
- return null;
-}
-var init_outputsScanner = __esm(() => {
- init_debug();
-});
-
-// src/utils/words.ts
-import { randomBytes as randomBytes2 } from "crypto";
-function randomInt(max) {
- const bytes = randomBytes2(4);
- const value = bytes.readUInt32BE(0);
- return value % max;
-}
-function pickRandom(array2) {
- return array2[randomInt(array2.length)];
-}
-function generateWordSlug() {
- const adjective = pickRandom(ADJECTIVES);
- const verb = pickRandom(VERBS);
- const noun = pickRandom(NOUNS);
- return `${adjective}-${verb}-${noun}`;
-}
-function generateShortWordSlug() {
- const adjective = pickRandom(ADJECTIVES);
- const noun = pickRandom(NOUNS);
- return `${adjective}-${noun}`;
-}
-var ADJECTIVES, NOUNS, VERBS;
-var init_words = __esm(() => {
- ADJECTIVES = [
- "abundant",
- "ancient",
- "bright",
- "calm",
- "cheerful",
- "clever",
- "cozy",
- "curious",
- "dapper",
- "dazzling",
- "deep",
- "delightful",
- "eager",
- "elegant",
- "enchanted",
- "fancy",
- "fluffy",
- "gentle",
- "gleaming",
- "golden",
- "graceful",
- "happy",
- "hidden",
- "humble",
- "jolly",
- "joyful",
- "keen",
- "kind",
- "lively",
- "lovely",
- "lucky",
- "luminous",
- "magical",
- "majestic",
- "mellow",
- "merry",
- "mighty",
- "misty",
- "noble",
- "peaceful",
- "playful",
- "polished",
- "precious",
- "proud",
- "quiet",
- "quirky",
- "radiant",
- "rosy",
- "serene",
- "shiny",
- "silly",
- "sleepy",
- "smooth",
- "snazzy",
- "snug",
- "snuggly",
- "soft",
- "sparkling",
- "spicy",
- "splendid",
- "sprightly",
- "starry",
- "steady",
- "sunny",
- "swift",
- "tender",
- "tidy",
- "toasty",
- "tranquil",
- "twinkly",
- "valiant",
- "vast",
- "velvet",
- "vivid",
- "warm",
- "whimsical",
- "wild",
- "wise",
- "witty",
- "wondrous",
- "zany",
- "zesty",
- "zippy",
- "breezy",
- "bubbly",
- "buzzing",
- "cheeky",
- "cosmic",
- "cozy",
- "crispy",
- "crystalline",
- "cuddly",
- "drifting",
- "dreamy",
- "effervescent",
- "ethereal",
- "fizzy",
- "flickering",
- "floating",
- "floofy",
- "fluttering",
- "foamy",
- "frolicking",
- "fuzzy",
- "giggly",
- "glimmering",
- "glistening",
- "glittery",
- "glowing",
- "goofy",
- "groovy",
- "harmonic",
- "hazy",
- "humming",
- "iridescent",
- "jaunty",
- "jazzy",
- "jiggly",
- "melodic",
- "moonlit",
- "mossy",
- "nifty",
- "peppy",
- "prancy",
- "purrfect",
- "purring",
- "quizzical",
- "rippling",
- "rustling",
- "shimmering",
- "shimmying",
- "snappy",
- "snoopy",
- "squishy",
- "swirling",
- "ticklish",
- "tingly",
- "twinkling",
- "velvety",
- "wiggly",
- "wobbly",
- "woolly",
- "zazzy",
- "abstract",
- "adaptive",
- "agile",
- "async",
- "atomic",
- "binary",
- "cached",
- "compiled",
- "composed",
- "compressed",
- "concurrent",
- "cryptic",
- "curried",
- "declarative",
- "delegated",
- "distributed",
- "dynamic",
- "eager",
- "elegant",
- "encapsulated",
- "enumerated",
- "eventual",
- "expressive",
- "federated",
- "functional",
- "generic",
- "greedy",
- "hashed",
- "idempotent",
- "immutable",
- "imperative",
- "indexed",
- "inherited",
- "iterative",
- "lazy",
- "lexical",
- "linear",
- "linked",
- "logical",
- "memoized",
- "modular",
- "mutable",
- "nested",
- "optimized",
- "parallel",
- "parsed",
- "partitioned",
- "piped",
- "polymorphic",
- "pure",
- "reactive",
- "recursive",
- "refactored",
- "reflective",
- "replicated",
- "resilient",
- "robust",
- "scalable",
- "sequential",
- "serialized",
- "sharded",
- "sorted",
- "staged",
- "stateful",
- "stateless",
- "streamed",
- "structured",
- "synchronous",
- "synthetic",
- "temporal",
- "transient",
- "typed",
- "unified",
- "validated",
- "vectorized",
- "virtual"
- ];
- NOUNS = [
- "aurora",
- "avalanche",
- "blossom",
- "breeze",
- "brook",
- "bubble",
- "canyon",
- "cascade",
- "cloud",
- "clover",
- "comet",
- "coral",
- "cosmos",
- "creek",
- "crescent",
- "crystal",
- "dawn",
- "dewdrop",
- "dusk",
- "eclipse",
- "ember",
- "feather",
- "fern",
- "firefly",
- "flame",
- "flurry",
- "fog",
- "forest",
- "frost",
- "galaxy",
- "garden",
- "glacier",
- "glade",
- "grove",
- "harbor",
- "horizon",
- "island",
- "lagoon",
- "lake",
- "leaf",
- "lightning",
- "meadow",
- "meteor",
- "mist",
- "moon",
- "moonbeam",
- "mountain",
- "nebula",
- "nova",
- "ocean",
- "orbit",
- "pebble",
- "petal",
- "pine",
- "planet",
- "pond",
- "puddle",
- "quasar",
- "rain",
- "rainbow",
- "reef",
- "ripple",
- "river",
- "shore",
- "sky",
- "snowflake",
- "spark",
- "spring",
- "star",
- "stardust",
- "starlight",
- "storm",
- "stream",
- "summit",
- "sun",
- "sunbeam",
- "sunrise",
- "sunset",
- "thunder",
- "tide",
- "twilight",
- "valley",
- "volcano",
- "waterfall",
- "wave",
- "willow",
- "wind",
- "alpaca",
- "axolotl",
- "badger",
- "bear",
- "beaver",
- "bee",
- "bird",
- "bumblebee",
- "bunny",
- "cat",
- "chipmunk",
- "crab",
- "crane",
- "deer",
- "dolphin",
- "dove",
- "dragon",
- "dragonfly",
- "duckling",
- "eagle",
- "elephant",
- "falcon",
- "finch",
- "flamingo",
- "fox",
- "frog",
- "giraffe",
- "goose",
- "hamster",
- "hare",
- "hedgehog",
- "hippo",
- "hummingbird",
- "jellyfish",
- "kitten",
- "koala",
- "ladybug",
- "lark",
- "lemur",
- "llama",
- "lobster",
- "lynx",
- "manatee",
- "meerkat",
- "moth",
- "narwhal",
- "newt",
- "octopus",
- "otter",
- "owl",
- "panda",
- "parrot",
- "peacock",
- "pelican",
- "penguin",
- "phoenix",
- "piglet",
- "platypus",
- "pony",
- "porcupine",
- "puffin",
- "puppy",
- "quail",
- "quokka",
- "rabbit",
- "raccoon",
- "raven",
- "robin",
- "salamander",
- "seahorse",
- "seal",
- "sloth",
- "snail",
- "sparrow",
- "sphinx",
- "squid",
- "squirrel",
- "starfish",
- "swan",
- "tiger",
- "toucan",
- "turtle",
- "unicorn",
- "walrus",
- "whale",
- "wolf",
- "wombat",
- "wren",
- "yeti",
- "zebra",
- "acorn",
- "anchor",
- "balloon",
- "beacon",
- "biscuit",
- "blanket",
- "bonbon",
- "book",
- "boot",
- "cake",
- "candle",
- "candy",
- "castle",
- "charm",
- "clock",
- "cocoa",
- "cookie",
- "crayon",
- "crown",
- "cupcake",
- "donut",
- "dream",
- "fairy",
- "fiddle",
- "flask",
- "flute",
- "fountain",
- "gadget",
- "gem",
- "gizmo",
- "globe",
- "goblet",
- "hammock",
- "harp",
- "haven",
- "hearth",
- "honey",
- "journal",
- "kazoo",
- "kettle",
- "key",
- "kite",
- "lantern",
- "lemon",
- "lighthouse",
- "locket",
- "lollipop",
- "mango",
- "map",
- "marble",
- "marshmallow",
- "melody",
- "mitten",
- "mochi",
- "muffin",
- "music",
- "nest",
- "noodle",
- "oasis",
- "origami",
- "pancake",
- "parasol",
- "peach",
- "pearl",
- "pebble",
- "pie",
- "pillow",
- "pinwheel",
- "pixel",
- "pizza",
- "plum",
- "popcorn",
- "pretzel",
- "prism",
- "pudding",
- "pumpkin",
- "puzzle",
- "quiche",
- "quill",
- "quilt",
- "riddle",
- "rocket",
- "rose",
- "scone",
- "scroll",
- "shell",
- "sketch",
- "snowglobe",
- "sonnet",
- "sparkle",
- "spindle",
- "sprout",
- "sundae",
- "swing",
- "taco",
- "teacup",
- "teapot",
- "thimble",
- "toast",
- "token",
- "tome",
- "tower",
- "treasure",
- "treehouse",
- "trinket",
- "truffle",
- "tulip",
- "umbrella",
- "waffle",
- "wand",
- "whisper",
- "whistle",
- "widget",
- "wreath",
- "zephyr",
- "abelson",
- "adleman",
- "aho",
- "allen",
- "babbage",
- "bachman",
- "backus",
- "barto",
- "bengio",
- "bentley",
- "blum",
- "boole",
- "brooks",
- "catmull",
- "cerf",
- "cherny",
- "church",
- "clarke",
- "cocke",
- "codd",
- "conway",
- "cook",
- "corbato",
- "cray",
- "curry",
- "dahl",
- "diffie",
- "dijkstra",
- "dongarra",
- "eich",
- "emerson",
- "engelbart",
- "feigenbaum",
- "floyd",
- "gosling",
- "graham",
- "gray",
- "hamming",
- "hanrahan",
- "hartmanis",
- "hejlsberg",
- "hellman",
- "hennessy",
- "hickey",
- "hinton",
- "hoare",
- "hollerith",
- "hopcroft",
- "hopper",
- "iverson",
- "kahan",
- "kahn",
- "karp",
- "kay",
- "kernighan",
- "knuth",
- "kurzweil",
- "lamport",
- "lampson",
- "lecun",
- "lerdorf",
- "liskov",
- "lovelace",
- "matsumoto",
- "mccarthy",
- "metcalfe",
- "micali",
- "milner",
- "minsky",
- "moler",
- "moore",
- "naur",
- "neumann",
- "newell",
- "nygaard",
- "papert",
- "parnas",
- "pascal",
- "patterson",
- "pearl",
- "perlis",
- "pike",
- "pnueli",
- "rabin",
- "reddy",
- "ritchie",
- "rivest",
- "rossum",
- "russell",
- "scott",
- "sedgewick",
- "shamir",
- "shannon",
- "sifakis",
- "simon",
- "stallman",
- "stearns",
- "steele",
- "stonebraker",
- "stroustrup",
- "sutherland",
- "sutton",
- "tarjan",
- "thacker",
- "thompson",
- "torvalds",
- "turing",
- "ullman",
- "valiant",
- "wadler",
- "wall",
- "wigderson",
- "wilkes",
- "wilkinson",
- "wirth",
- "wozniak",
- "yao"
- ];
- VERBS = [
- "baking",
- "beaming",
- "booping",
- "bouncing",
- "brewing",
- "bubbling",
- "chasing",
- "churning",
- "coalescing",
- "conjuring",
- "cooking",
- "crafting",
- "crunching",
- "cuddling",
- "dancing",
- "dazzling",
- "discovering",
- "doodling",
- "dreaming",
- "drifting",
- "enchanting",
- "exploring",
- "finding",
- "floating",
- "fluttering",
- "foraging",
- "forging",
- "frolicking",
- "gathering",
- "giggling",
- "gliding",
- "greeting",
- "growing",
- "hatching",
- "herding",
- "honking",
- "hopping",
- "hugging",
- "humming",
- "imagining",
- "inventing",
- "jingling",
- "juggling",
- "jumping",
- "kindling",
- "knitting",
- "launching",
- "leaping",
- "mapping",
- "marinating",
- "meandering",
- "mixing",
- "moseying",
- "munching",
- "napping",
- "nibbling",
- "noodling",
- "orbiting",
- "painting",
- "percolating",
- "petting",
- "plotting",
- "pondering",
- "popping",
- "prancing",
- "purring",
- "puzzling",
- "questing",
- "riding",
- "roaming",
- "rolling",
- "sauteeing",
- "scribbling",
- "seeking",
- "shimmying",
- "singing",
- "skipping",
- "sleeping",
- "snacking",
- "sniffing",
- "snuggling",
- "soaring",
- "sparking",
- "spinning",
- "splashing",
- "sprouting",
- "squishing",
- "stargazing",
- "stirring",
- "strolling",
- "swimming",
- "swinging",
- "tickling",
- "tinkering",
- "toasting",
- "tumbling",
- "twirling",
- "waddling",
- "wandering",
- "watching",
- "weaving",
- "whistling",
- "wibbling",
- "wiggling",
- "wishing",
- "wobbling",
- "wondering",
- "yawning",
- "zooming"
- ];
-});
-
-// src/utils/plans.ts
-import { randomUUID as randomUUID7 } from "crypto";
-import { copyFile, writeFile as writeFile5 } from "fs/promises";
-import { join as join28, resolve as resolve9, sep as sep6 } from "path";
-function getPlanSlug(sessionId) {
- const id = sessionId ?? getSessionId();
- const cache6 = getPlanSlugCache();
- let slug = cache6.get(id);
- if (!slug) {
- const plansDir = getPlansDirectory();
- for (let i5 = 0;i5 < MAX_SLUG_RETRIES; i5++) {
- slug = generateWordSlug();
- const filePath = join28(plansDir, `${slug}.md`);
- if (!getFsImplementation().existsSync(filePath)) {
- break;
- }
- }
- cache6.set(id, slug);
- }
- return slug;
-}
-function setPlanSlug(sessionId, slug) {
- getPlanSlugCache().set(sessionId, slug);
-}
-function clearAllPlanSlugs() {
- getPlanSlugCache().clear();
-}
-function getPlanFilePath(agentId) {
- const planSlug = getPlanSlug(getSessionId());
- if (!agentId) {
- return join28(getPlansDirectory(), `${planSlug}.md`);
- }
- return join28(getPlansDirectory(), `${planSlug}-agent-${agentId}.md`);
-}
-function getPlan(agentId) {
- const filePath = getPlanFilePath(agentId);
- try {
- return getFsImplementation().readFileSync(filePath, { encoding: "utf-8" });
- } catch (error46) {
- if (isENOENT(error46))
- return null;
- logError2(error46);
- return null;
- }
-}
-function getSlugFromLog(log3) {
- return log3.messages.find((m4) => m4.slug)?.slug;
-}
-async function copyPlanForResume(log3, targetSessionId) {
- const slug = getSlugFromLog(log3);
- if (!slug) {
- return false;
- }
- const sessionId = targetSessionId ?? getSessionId();
- setPlanSlug(sessionId, slug);
- const planPath = join28(getPlansDirectory(), `${slug}.md`);
- try {
- await getFsImplementation().readFile(planPath, { encoding: "utf-8" });
- return true;
- } catch (e4) {
- if (!isENOENT(e4)) {
- logError2(e4);
- return false;
- }
- if (getEnvironmentKind() === null) {
- return false;
- }
- logForDebugging(`Plan file missing during resume: ${planPath}. Attempting recovery.`);
- const snapshotPlan = findFileSnapshotEntry(log3.messages, "plan");
- let recovered = null;
- if (snapshotPlan && snapshotPlan.content.length > 0) {
- recovered = snapshotPlan.content;
- logForDebugging(`Plan recovered from file snapshot, ${recovered.length} chars`, { level: "info" });
- } else {
- recovered = recoverPlanFromMessages(log3);
- if (recovered) {
- logForDebugging(`Plan recovered from message history, ${recovered.length} chars`, { level: "info" });
- }
- }
- if (recovered) {
- try {
- await writeFile5(planPath, recovered, { encoding: "utf-8" });
- return true;
- } catch (writeError) {
- logError2(writeError);
- return false;
- }
- }
- logForDebugging("Plan file recovery failed: no file snapshot or plan content found in message history");
- return false;
- }
-}
-async function copyPlanForFork(log3, targetSessionId) {
- const originalSlug = getSlugFromLog(log3);
- if (!originalSlug) {
- return false;
- }
- const plansDir = getPlansDirectory();
- const originalPlanPath = join28(plansDir, `${originalSlug}.md`);
- const newSlug = getPlanSlug(targetSessionId);
- const newPlanPath = join28(plansDir, `${newSlug}.md`);
- try {
- await copyFile(originalPlanPath, newPlanPath);
- return true;
- } catch (error46) {
- if (isENOENT(error46)) {
- return false;
- }
- logError2(error46);
- return false;
- }
-}
-function recoverPlanFromMessages(log3) {
- for (let i5 = log3.messages.length - 1;i5 >= 0; i5--) {
- const msg = log3.messages[i5];
- if (!msg) {
- continue;
- }
- if (msg.type === "assistant") {
- const { content } = msg.message;
- if (Array.isArray(content)) {
- for (const block2 of content) {
- if (block2.type === "tool_use" && block2.name === EXIT_PLAN_MODE_V2_TOOL_NAME) {
- const input = block2.input;
- const plan = input?.plan;
- if (typeof plan === "string" && plan.length > 0) {
- return plan;
- }
- }
- }
- }
- }
- if (msg.type === "user") {
- const userMsg = msg;
- if (typeof userMsg.planContent === "string" && userMsg.planContent.length > 0) {
- return userMsg.planContent;
- }
- }
- if (msg.type === "attachment") {
- const attachmentMsg = msg;
- if (attachmentMsg.attachment?.type === "plan_file_reference") {
- const plan = attachmentMsg.attachment.planContent;
- if (typeof plan === "string" && plan.length > 0) {
- return plan;
- }
- }
- }
- }
- return null;
-}
-function findFileSnapshotEntry(messages, key) {
- for (let i5 = messages.length - 1;i5 >= 0; i5--) {
- const msg = messages[i5];
- if (msg?.type === "system" && "subtype" in msg && msg.subtype === "file_snapshot" && "snapshotFiles" in msg) {
- const files = msg.snapshotFiles;
- return files.find((f4) => f4.key === key);
- }
- }
- return;
-}
-async function persistFileSnapshotIfRemote() {
- if (getEnvironmentKind() === null) {
- return;
- }
- try {
- const snapshotFiles = [];
- const plan = getPlan();
- if (plan) {
- snapshotFiles.push({
- key: "plan",
- path: getPlanFilePath(),
- content: plan
- });
- }
- if (snapshotFiles.length === 0) {
- return;
- }
- const message = {
- type: "system",
- subtype: "file_snapshot",
- content: "File snapshot",
- level: "info",
- isMeta: true,
- timestamp: new Date().toISOString(),
- uuid: randomUUID7(),
- snapshotFiles
- };
- const { recordTranscript } = await Promise.resolve().then(() => (init_sessionStorage(), exports_sessionStorage));
- await recordTranscript([message]);
- } catch (error46) {
- logError2(error46);
- }
-}
-var MAX_SLUG_RETRIES = 10, getPlansDirectory;
-var init_plans = __esm(() => {
- init_memoize();
- init_state();
- init_cwd();
- init_debug();
- init_envUtils();
- init_errors();
- init_outputsScanner();
- init_fsOperations();
- init_log2();
- init_settings2();
- init_words();
- getPlansDirectory = memoize_default(function getPlansDirectory2() {
- const settings = getInitialSettings();
- const settingsDir = settings.plansDirectory;
- let plansPath;
- if (settingsDir) {
- const cwd2 = getCwd();
- const resolved = resolve9(cwd2, settingsDir);
- if (!resolved.startsWith(cwd2 + sep6) && resolved !== cwd2) {
- logError2(new Error(`plansDirectory must be within project root: ${settingsDir}`));
- plansPath = join28(getClaudeConfigHomeDir(), "plans");
- } else {
- plansPath = resolved;
- }
- } else {
- plansPath = join28(getClaudeConfigHomeDir(), "plans");
- }
- try {
- getFsImplementation().mkdirSync(plansPath);
- } catch (error46) {
- logError2(error46);
- }
- return plansPath;
- });
-});
-
-// src/utils/shell/readOnlyCommandValidation.ts
-function ghIsDangerousCallback(_rawCommand, args) {
- for (const token of args) {
- if (!token)
- continue;
- let value = token;
- if (token.startsWith("-")) {
- const eqIdx = token.indexOf("=");
- if (eqIdx === -1)
- continue;
- value = token.slice(eqIdx + 1);
- if (!value)
- continue;
- }
- if (!value.includes("/") && !value.includes("://") && !value.includes("@")) {
- continue;
- }
- if (value.includes("://")) {
- return true;
- }
- if (value.includes("@")) {
- return true;
- }
- const slashCount = (value.match(/\//g) || []).length;
- if (slashCount >= 2) {
- return true;
- }
- }
- return false;
-}
-function containsVulnerableUncPath(pathOrCommand) {
- if (getPlatform() !== "windows") {
- return false;
- }
- const backslashUncPattern = /\\\\[^\s\\/]+(?:@(?:\d+|ssl))?(?:[\\/]|$|\s)/i;
- if (backslashUncPattern.test(pathOrCommand)) {
- return true;
- }
- const forwardSlashUncPattern = /(? 1 && FLAG_PATTERN.test(token)) {
- const hasEquals = token.includes("=");
- const [flag, ...valueParts] = token.split("=");
- const inlineValue = valueParts.join("=");
- if (!flag) {
- return false;
- }
- const flagArgType = config8.safeFlags[flag];
- if (!flagArgType) {
- if (options2?.commandName === "git" && flag.match(/^-\d+$/)) {
- i5++;
- continue;
- }
- if ((options2?.commandName === "grep" || options2?.commandName === "rg") && flag.startsWith("-") && !flag.startsWith("--") && flag.length > 2) {
- const potentialFlag = flag.substring(0, 2);
- const potentialValue = flag.substring(2);
- if (config8.safeFlags[potentialFlag] && /^\d+$/.test(potentialValue)) {
- const flagArgType2 = config8.safeFlags[potentialFlag];
- if (flagArgType2 === "number" || flagArgType2 === "string") {
- if (validateFlagArgument(potentialValue, flagArgType2)) {
- i5++;
- continue;
- } else {
- return false;
- }
- }
- }
- }
- if (flag.startsWith("-") && !flag.startsWith("--") && flag.length > 2) {
- for (let j4 = 1;j4 < flag.length; j4++) {
- const singleFlag = "-" + flag[j4];
- const flagType = config8.safeFlags[singleFlag];
- if (!flagType) {
- return false;
- }
- if (flagType !== "none") {
- return false;
- }
- }
- i5++;
- continue;
- } else {
- return false;
- }
- }
- if (flagArgType === "none") {
- if (hasEquals) {
- return false;
- }
- i5++;
- } else {
- let argValue;
- if (hasEquals) {
- argValue = inlineValue;
- i5++;
- } else {
- if (i5 + 1 >= tokens.length || tokens[i5 + 1] && tokens[i5 + 1].startsWith("-") && tokens[i5 + 1].length > 1 && FLAG_PATTERN.test(tokens[i5 + 1])) {
- return false;
- }
- argValue = tokens[i5 + 1] || "";
- i5 += 2;
- }
- if (flagArgType === "string" && argValue.startsWith("-")) {
- if (flag === "--sort" && options2?.commandName === "git" && argValue.match(/^-[a-zA-Z]/)) {} else {
- return false;
- }
- }
- if (!validateFlagArgument(argValue, flagArgType)) {
- return false;
- }
- }
- } else {
- i5++;
- }
- }
- return true;
-}
-var GIT_REF_SELECTION_FLAGS, GIT_DATE_FILTER_FLAGS, GIT_LOG_DISPLAY_FLAGS, GIT_COUNT_FLAGS, GIT_STAT_FLAGS, GIT_COLOR_FLAGS, GIT_PATCH_FLAGS, GIT_AUTHOR_FILTER_FLAGS, GIT_READ_ONLY_COMMANDS, GH_READ_ONLY_COMMANDS, DOCKER_READ_ONLY_COMMANDS, RIPGREP_READ_ONLY_COMMANDS, PYRIGHT_READ_ONLY_COMMANDS, EXTERNAL_READONLY_COMMANDS, FLAG_PATTERN;
-var init_readOnlyCommandValidation = __esm(() => {
- init_platform2();
- GIT_REF_SELECTION_FLAGS = {
- "--all": "none",
- "--branches": "none",
- "--tags": "none",
- "--remotes": "none"
- };
- GIT_DATE_FILTER_FLAGS = {
- "--since": "string",
- "--after": "string",
- "--until": "string",
- "--before": "string"
- };
- GIT_LOG_DISPLAY_FLAGS = {
- "--oneline": "none",
- "--graph": "none",
- "--decorate": "none",
- "--no-decorate": "none",
- "--date": "string",
- "--relative-date": "none"
- };
- GIT_COUNT_FLAGS = {
- "--max-count": "number",
- "-n": "number"
- };
- GIT_STAT_FLAGS = {
- "--stat": "none",
- "--numstat": "none",
- "--shortstat": "none",
- "--name-only": "none",
- "--name-status": "none"
- };
- GIT_COLOR_FLAGS = {
- "--color": "none",
- "--no-color": "none"
- };
- GIT_PATCH_FLAGS = {
- "--patch": "none",
- "-p": "none",
- "--no-patch": "none",
- "--no-ext-diff": "none",
- "-s": "none"
- };
- GIT_AUTHOR_FILTER_FLAGS = {
- "--author": "string",
- "--committer": "string",
- "--grep": "string"
- };
- GIT_READ_ONLY_COMMANDS = {
- "git diff": {
- safeFlags: {
- ...GIT_STAT_FLAGS,
- ...GIT_COLOR_FLAGS,
- "--dirstat": "none",
- "--summary": "none",
- "--patch-with-stat": "none",
- "--word-diff": "none",
- "--word-diff-regex": "string",
- "--color-words": "none",
- "--no-renames": "none",
- "--no-ext-diff": "none",
- "--check": "none",
- "--ws-error-highlight": "string",
- "--full-index": "none",
- "--binary": "none",
- "--abbrev": "number",
- "--break-rewrites": "none",
- "--find-renames": "none",
- "--find-copies": "none",
- "--find-copies-harder": "none",
- "--irreversible-delete": "none",
- "--diff-algorithm": "string",
- "--histogram": "none",
- "--patience": "none",
- "--minimal": "none",
- "--ignore-space-at-eol": "none",
- "--ignore-space-change": "none",
- "--ignore-all-space": "none",
- "--ignore-blank-lines": "none",
- "--inter-hunk-context": "number",
- "--function-context": "none",
- "--exit-code": "none",
- "--quiet": "none",
- "--cached": "none",
- "--staged": "none",
- "--pickaxe-regex": "none",
- "--pickaxe-all": "none",
- "--no-index": "none",
- "--relative": "string",
- "--diff-filter": "string",
- "-p": "none",
- "-u": "none",
- "-s": "none",
- "-M": "none",
- "-C": "none",
- "-B": "none",
- "-D": "none",
- "-l": "none",
- "-S": "string",
- "-G": "string",
- "-O": "string",
- "-R": "none"
- }
- },
- "git log": {
- safeFlags: {
- ...GIT_LOG_DISPLAY_FLAGS,
- ...GIT_REF_SELECTION_FLAGS,
- ...GIT_DATE_FILTER_FLAGS,
- ...GIT_COUNT_FLAGS,
- ...GIT_STAT_FLAGS,
- ...GIT_COLOR_FLAGS,
- ...GIT_PATCH_FLAGS,
- ...GIT_AUTHOR_FILTER_FLAGS,
- "--abbrev-commit": "none",
- "--full-history": "none",
- "--dense": "none",
- "--sparse": "none",
- "--simplify-merges": "none",
- "--ancestry-path": "none",
- "--source": "none",
- "--first-parent": "none",
- "--merges": "none",
- "--no-merges": "none",
- "--reverse": "none",
- "--walk-reflogs": "none",
- "--skip": "number",
- "--max-age": "number",
- "--min-age": "number",
- "--no-min-parents": "none",
- "--no-max-parents": "none",
- "--follow": "none",
- "--no-walk": "none",
- "--left-right": "none",
- "--cherry-mark": "none",
- "--cherry-pick": "none",
- "--boundary": "none",
- "--topo-order": "none",
- "--date-order": "none",
- "--author-date-order": "none",
- "--pretty": "string",
- "--format": "string",
- "--diff-filter": "string",
- "-S": "string",
- "-G": "string",
- "--pickaxe-regex": "none",
- "--pickaxe-all": "none"
- }
- },
- "git show": {
- safeFlags: {
- ...GIT_LOG_DISPLAY_FLAGS,
- ...GIT_STAT_FLAGS,
- ...GIT_COLOR_FLAGS,
- ...GIT_PATCH_FLAGS,
- "--abbrev-commit": "none",
- "--word-diff": "none",
- "--word-diff-regex": "string",
- "--color-words": "none",
- "--pretty": "string",
- "--format": "string",
- "--first-parent": "none",
- "--raw": "none",
- "--diff-filter": "string",
- "-m": "none",
- "--quiet": "none"
- }
- },
- "git shortlog": {
- safeFlags: {
- ...GIT_REF_SELECTION_FLAGS,
- ...GIT_DATE_FILTER_FLAGS,
- "-s": "none",
- "--summary": "none",
- "-n": "none",
- "--numbered": "none",
- "-e": "none",
- "--email": "none",
- "-c": "none",
- "--committer": "none",
- "--group": "string",
- "--format": "string",
- "--no-merges": "none",
- "--author": "string"
- }
- },
- "git reflog": {
- safeFlags: {
- ...GIT_LOG_DISPLAY_FLAGS,
- ...GIT_REF_SELECTION_FLAGS,
- ...GIT_DATE_FILTER_FLAGS,
- ...GIT_COUNT_FLAGS,
- ...GIT_AUTHOR_FILTER_FLAGS
- },
- additionalCommandIsDangerousCallback: (_rawCommand, args) => {
- const DANGEROUS_SUBCOMMANDS = new Set(["expire", "delete", "exists"]);
- for (const token of args) {
- if (!token || token.startsWith("-"))
- continue;
- if (DANGEROUS_SUBCOMMANDS.has(token)) {
- return true;
- }
- return false;
- }
- return false;
- }
- },
- "git stash list": {
- safeFlags: {
- ...GIT_LOG_DISPLAY_FLAGS,
- ...GIT_REF_SELECTION_FLAGS,
- ...GIT_COUNT_FLAGS
- }
- },
- "git ls-remote": {
- safeFlags: {
- "--branches": "none",
- "-b": "none",
- "--tags": "none",
- "-t": "none",
- "--heads": "none",
- "-h": "none",
- "--refs": "none",
- "--quiet": "none",
- "-q": "none",
- "--exit-code": "none",
- "--get-url": "none",
- "--symref": "none",
- "--sort": "string"
- }
- },
- "git status": {
- safeFlags: {
- "--short": "none",
- "-s": "none",
- "--branch": "none",
- "-b": "none",
- "--porcelain": "none",
- "--long": "none",
- "--verbose": "none",
- "-v": "none",
- "--untracked-files": "string",
- "-u": "string",
- "--ignored": "none",
- "--ignore-submodules": "string",
- "--column": "none",
- "--no-column": "none",
- "--ahead-behind": "none",
- "--no-ahead-behind": "none",
- "--renames": "none",
- "--no-renames": "none",
- "--find-renames": "string",
- "-M": "string"
- }
- },
- "git blame": {
- safeFlags: {
- ...GIT_COLOR_FLAGS,
- "-L": "string",
- "--porcelain": "none",
- "-p": "none",
- "--line-porcelain": "none",
- "--incremental": "none",
- "--root": "none",
- "--show-stats": "none",
- "--show-name": "none",
- "--show-number": "none",
- "-n": "none",
- "--show-email": "none",
- "-e": "none",
- "-f": "none",
- "--date": "string",
- "-w": "none",
- "--ignore-rev": "string",
- "--ignore-revs-file": "string",
- "-M": "none",
- "-C": "none",
- "--score-debug": "none",
- "--abbrev": "number",
- "-s": "none",
- "-l": "none",
- "-t": "none"
- }
- },
- "git ls-files": {
- safeFlags: {
- "--cached": "none",
- "-c": "none",
- "--deleted": "none",
- "-d": "none",
- "--modified": "none",
- "-m": "none",
- "--others": "none",
- "-o": "none",
- "--ignored": "none",
- "-i": "none",
- "--stage": "none",
- "-s": "none",
- "--killed": "none",
- "-k": "none",
- "--unmerged": "none",
- "-u": "none",
- "--directory": "none",
- "--no-empty-directory": "none",
- "--eol": "none",
- "--full-name": "none",
- "--abbrev": "number",
- "--debug": "none",
- "-z": "none",
- "-t": "none",
- "-v": "none",
- "-f": "none",
- "--exclude": "string",
- "-x": "string",
- "--exclude-from": "string",
- "-X": "string",
- "--exclude-per-directory": "string",
- "--exclude-standard": "none",
- "--error-unmatch": "none",
- "--recurse-submodules": "none"
- }
- },
- "git config --get": {
- safeFlags: {
- "--local": "none",
- "--global": "none",
- "--system": "none",
- "--worktree": "none",
- "--default": "string",
- "--type": "string",
- "--bool": "none",
- "--int": "none",
- "--bool-or-int": "none",
- "--path": "none",
- "--expiry-date": "none",
- "-z": "none",
- "--null": "none",
- "--name-only": "none",
- "--show-origin": "none",
- "--show-scope": "none"
- }
- },
- "git remote show": {
- safeFlags: {
- "-n": "none"
- },
- additionalCommandIsDangerousCallback: (_rawCommand, args) => {
- const positional = args.filter((a5) => a5 !== "-n");
- if (positional.length !== 1)
- return true;
- return !/^[a-zA-Z0-9_-]+$/.test(positional[0]);
- }
- },
- "git remote": {
- safeFlags: {
- "-v": "none",
- "--verbose": "none"
- },
- additionalCommandIsDangerousCallback: (_rawCommand, args) => {
- return args.some((a5) => a5 !== "-v" && a5 !== "--verbose");
- }
- },
- "git merge-base": {
- safeFlags: {
- "--is-ancestor": "none",
- "--fork-point": "none",
- "--octopus": "none",
- "--independent": "none",
- "--all": "none"
- }
- },
- "git rev-parse": {
- safeFlags: {
- "--verify": "none",
- "--short": "string",
- "--abbrev-ref": "none",
- "--symbolic": "none",
- "--symbolic-full-name": "none",
- "--show-toplevel": "none",
- "--show-cdup": "none",
- "--show-prefix": "none",
- "--git-dir": "none",
- "--git-common-dir": "none",
- "--absolute-git-dir": "none",
- "--show-superproject-working-tree": "none",
- "--is-inside-work-tree": "none",
- "--is-inside-git-dir": "none",
- "--is-bare-repository": "none",
- "--is-shallow-repository": "none",
- "--is-shallow-update": "none",
- "--path-prefix": "none"
- }
- },
- "git rev-list": {
- safeFlags: {
- ...GIT_REF_SELECTION_FLAGS,
- ...GIT_DATE_FILTER_FLAGS,
- ...GIT_COUNT_FLAGS,
- ...GIT_AUTHOR_FILTER_FLAGS,
- "--count": "none",
- "--reverse": "none",
- "--first-parent": "none",
- "--ancestry-path": "none",
- "--merges": "none",
- "--no-merges": "none",
- "--min-parents": "number",
- "--max-parents": "number",
- "--no-min-parents": "none",
- "--no-max-parents": "none",
- "--skip": "number",
- "--max-age": "number",
- "--min-age": "number",
- "--walk-reflogs": "none",
- "--oneline": "none",
- "--abbrev-commit": "none",
- "--pretty": "string",
- "--format": "string",
- "--abbrev": "number",
- "--full-history": "none",
- "--dense": "none",
- "--sparse": "none",
- "--source": "none",
- "--graph": "none"
- }
- },
- "git describe": {
- safeFlags: {
- "--tags": "none",
- "--match": "string",
- "--exclude": "string",
- "--long": "none",
- "--abbrev": "number",
- "--always": "none",
- "--contains": "none",
- "--first-match": "none",
- "--exact-match": "none",
- "--candidates": "number",
- "--dirty": "none",
- "--broken": "none"
- }
- },
- "git cat-file": {
- safeFlags: {
- "-t": "none",
- "-s": "none",
- "-p": "none",
- "-e": "none",
- "--batch-check": "none",
- "--allow-undetermined-type": "none"
- }
- },
- "git for-each-ref": {
- safeFlags: {
- "--format": "string",
- "--sort": "string",
- "--count": "number",
- "--contains": "string",
- "--no-contains": "string",
- "--merged": "string",
- "--no-merged": "string",
- "--points-at": "string"
- }
- },
- "git grep": {
- safeFlags: {
- "-e": "string",
- "-E": "none",
- "--extended-regexp": "none",
- "-G": "none",
- "--basic-regexp": "none",
- "-F": "none",
- "--fixed-strings": "none",
- "-P": "none",
- "--perl-regexp": "none",
- "-i": "none",
- "--ignore-case": "none",
- "-v": "none",
- "--invert-match": "none",
- "-w": "none",
- "--word-regexp": "none",
- "-n": "none",
- "--line-number": "none",
- "-c": "none",
- "--count": "none",
- "-l": "none",
- "--files-with-matches": "none",
- "-L": "none",
- "--files-without-match": "none",
- "-h": "none",
- "-H": "none",
- "--heading": "none",
- "--break": "none",
- "--full-name": "none",
- "--color": "none",
- "--no-color": "none",
- "-o": "none",
- "--only-matching": "none",
- "-A": "number",
- "--after-context": "number",
- "-B": "number",
- "--before-context": "number",
- "-C": "number",
- "--context": "number",
- "--and": "none",
- "--or": "none",
- "--not": "none",
- "--max-depth": "number",
- "--untracked": "none",
- "--no-index": "none",
- "--recurse-submodules": "none",
- "--cached": "none",
- "--threads": "number",
- "-q": "none",
- "--quiet": "none"
- }
- },
- "git stash show": {
- safeFlags: {
- ...GIT_STAT_FLAGS,
- ...GIT_COLOR_FLAGS,
- ...GIT_PATCH_FLAGS,
- "--word-diff": "none",
- "--word-diff-regex": "string",
- "--diff-filter": "string",
- "--abbrev": "number"
- }
- },
- "git worktree list": {
- safeFlags: {
- "--porcelain": "none",
- "-v": "none",
- "--verbose": "none",
- "--expire": "string"
- }
- },
- "git tag": {
- safeFlags: {
- "-l": "none",
- "--list": "none",
- "-n": "number",
- "--contains": "string",
- "--no-contains": "string",
- "--merged": "string",
- "--no-merged": "string",
- "--sort": "string",
- "--format": "string",
- "--points-at": "string",
- "--column": "none",
- "--no-column": "none",
- "-i": "none",
- "--ignore-case": "none"
- },
- additionalCommandIsDangerousCallback: (_rawCommand, args) => {
- const flagsWithArgs = new Set([
- "--contains",
- "--no-contains",
- "--merged",
- "--no-merged",
- "--points-at",
- "--sort",
- "--format",
- "-n"
- ]);
- let i5 = 0;
- let seenListFlag = false;
- let seenDashDash = false;
- while (i5 < args.length) {
- const token = args[i5];
- if (!token) {
- i5++;
- continue;
- }
- if (token === "--" && !seenDashDash) {
- seenDashDash = true;
- i5++;
- continue;
- }
- if (!seenDashDash && token.startsWith("-")) {
- if (token === "--list" || token === "-l") {
- seenListFlag = true;
- } else if (token[0] === "-" && token[1] !== "-" && token.length > 2 && !token.includes("=") && token.slice(1).includes("l")) {
- seenListFlag = true;
- }
- if (token.includes("=")) {
- i5++;
- } else if (flagsWithArgs.has(token)) {
- i5 += 2;
- } else {
- i5++;
- }
- } else {
- if (!seenListFlag) {
- return true;
- }
- i5++;
- }
- }
- return false;
- }
- },
- "git branch": {
- safeFlags: {
- "-l": "none",
- "--list": "none",
- "-a": "none",
- "--all": "none",
- "-r": "none",
- "--remotes": "none",
- "-v": "none",
- "-vv": "none",
- "--verbose": "none",
- "--color": "none",
- "--no-color": "none",
- "--column": "none",
- "--no-column": "none",
- "--abbrev": "number",
- "--no-abbrev": "none",
- "--contains": "string",
- "--no-contains": "string",
- "--merged": "none",
- "--no-merged": "none",
- "--points-at": "string",
- "--sort": "string",
- "--show-current": "none",
- "-i": "none",
- "--ignore-case": "none"
- },
- additionalCommandIsDangerousCallback: (_rawCommand, args) => {
- const flagsWithArgs = new Set([
- "--contains",
- "--no-contains",
- "--points-at",
- "--sort"
- ]);
- const flagsWithOptionalArgs = new Set(["--merged", "--no-merged"]);
- let i5 = 0;
- let lastFlag = "";
- let seenListFlag = false;
- let seenDashDash = false;
- while (i5 < args.length) {
- const token = args[i5];
- if (!token) {
- i5++;
- continue;
- }
- if (token === "--" && !seenDashDash) {
- seenDashDash = true;
- lastFlag = "";
- i5++;
- continue;
- }
- if (!seenDashDash && token.startsWith("-")) {
- if (token === "--list" || token === "-l") {
- seenListFlag = true;
- } else if (token[0] === "-" && token[1] !== "-" && token.length > 2 && !token.includes("=") && token.slice(1).includes("l")) {
- seenListFlag = true;
- }
- if (token.includes("=")) {
- lastFlag = token.split("=")[0] || "";
- i5++;
- } else if (flagsWithArgs.has(token)) {
- lastFlag = token;
- i5 += 2;
- } else {
- lastFlag = token;
- i5++;
- }
- } else {
- const lastFlagHasOptionalArg = flagsWithOptionalArgs.has(lastFlag);
- if (!seenListFlag && !lastFlagHasOptionalArg) {
- return true;
- }
- i5++;
- }
- }
- return false;
- }
- }
- };
- GH_READ_ONLY_COMMANDS = {
- "gh pr view": {
- safeFlags: {
- "--json": "string",
- "--comments": "none",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh pr list": {
- safeFlags: {
- "--state": "string",
- "-s": "string",
- "--author": "string",
- "--assignee": "string",
- "--label": "string",
- "--limit": "number",
- "-L": "number",
- "--base": "string",
- "--head": "string",
- "--search": "string",
- "--json": "string",
- "--draft": "none",
- "--app": "string",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh pr diff": {
- safeFlags: {
- "--color": "string",
- "--name-only": "none",
- "--patch": "none",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh pr checks": {
- safeFlags: {
- "--watch": "none",
- "--required": "none",
- "--fail-fast": "none",
- "--json": "string",
- "--interval": "number",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh issue view": {
- safeFlags: {
- "--json": "string",
- "--comments": "none",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh issue list": {
- safeFlags: {
- "--state": "string",
- "-s": "string",
- "--assignee": "string",
- "--author": "string",
- "--label": "string",
- "--limit": "number",
- "-L": "number",
- "--milestone": "string",
- "--search": "string",
- "--json": "string",
- "--app": "string",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh repo view": {
- safeFlags: {
- "--json": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh run list": {
- safeFlags: {
- "--branch": "string",
- "-b": "string",
- "--status": "string",
- "-s": "string",
- "--workflow": "string",
- "-w": "string",
- "--limit": "number",
- "-L": "number",
- "--json": "string",
- "--repo": "string",
- "-R": "string",
- "--event": "string",
- "-e": "string",
- "--user": "string",
- "-u": "string",
- "--created": "string",
- "--commit": "string",
- "-c": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh run view": {
- safeFlags: {
- "--log": "none",
- "--log-failed": "none",
- "--exit-status": "none",
- "--verbose": "none",
- "-v": "none",
- "--json": "string",
- "--repo": "string",
- "-R": "string",
- "--job": "string",
- "-j": "string",
- "--attempt": "number",
- "-a": "number"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh auth status": {
- safeFlags: {
- "--active": "none",
- "-a": "none",
- "--hostname": "string",
- "-h": "string",
- "--json": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh pr status": {
- safeFlags: {
- "--conflict-status": "none",
- "-c": "none",
- "--json": "string",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh issue status": {
- safeFlags: {
- "--json": "string",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh release list": {
- safeFlags: {
- "--exclude-drafts": "none",
- "--exclude-pre-releases": "none",
- "--json": "string",
- "--limit": "number",
- "-L": "number",
- "--order": "string",
- "-O": "string",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh release view": {
- safeFlags: {
- "--json": "string",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh workflow list": {
- safeFlags: {
- "--all": "none",
- "-a": "none",
- "--json": "string",
- "--limit": "number",
- "-L": "number",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh workflow view": {
- safeFlags: {
- "--ref": "string",
- "-r": "string",
- "--yaml": "none",
- "-y": "none",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh label list": {
- safeFlags: {
- "--json": "string",
- "--limit": "number",
- "-L": "number",
- "--order": "string",
- "--search": "string",
- "-S": "string",
- "--sort": "string",
- "--repo": "string",
- "-R": "string"
- },
- additionalCommandIsDangerousCallback: ghIsDangerousCallback
- },
- "gh search repos": {
- safeFlags: {
- "--archived": "none",
- "--created": "string",
- "--followers": "string",
- "--forks": "string",
- "--good-first-issues": "string",
- "--help-wanted-issues": "string",
- "--include-forks": "string",
- "--json": "string",
- "--language": "string",
- "--license": "string",
- "--limit": "number",
- "-L": "number",
- "--match": "string",
- "--number-topics": "string",
- "--order": "string",
- "--owner": "string",
- "--size": "string",
- "--sort": "string",
- "--stars": "string",
- "--topic": "string",
- "--updated": "string",
- "--visibility": "string"
- }
- },
- "gh search issues": {
- safeFlags: {
- "--app": "string",
- "--assignee": "string",
- "--author": "string",
- "--closed": "string",
- "--commenter": "string",
- "--comments": "string",
- "--created": "string",
- "--include-prs": "none",
- "--interactions": "string",
- "--involves": "string",
- "--json": "string",
- "--label": "string",
- "--language": "string",
- "--limit": "number",
- "-L": "number",
- "--locked": "none",
- "--match": "string",
- "--mentions": "string",
- "--milestone": "string",
- "--no-assignee": "none",
- "--no-label": "none",
- "--no-milestone": "none",
- "--no-project": "none",
- "--order": "string",
- "--owner": "string",
- "--project": "string",
- "--reactions": "string",
- "--repo": "string",
- "-R": "string",
- "--sort": "string",
- "--state": "string",
- "--team-mentions": "string",
- "--updated": "string",
- "--visibility": "string"
- }
- },
- "gh search prs": {
- safeFlags: {
- "--app": "string",
- "--assignee": "string",
- "--author": "string",
- "--base": "string",
- "-B": "string",
- "--checks": "string",
- "--closed": "string",
- "--commenter": "string",
- "--comments": "string",
- "--created": "string",
- "--draft": "none",
- "--head": "string",
- "-H": "string",
- "--interactions": "string",
- "--involves": "string",
- "--json": "string",
- "--label": "string",
- "--language": "string",
- "--limit": "number",
- "-L": "number",
- "--locked": "none",
- "--match": "string",
- "--mentions": "string",
- "--merged": "none",
- "--merged-at": "string",
- "--milestone": "string",
- "--no-assignee": "none",
- "--no-label": "none",
- "--no-milestone": "none",
- "--no-project": "none",
- "--order": "string",
- "--owner": "string",
- "--project": "string",
- "--reactions": "string",
- "--repo": "string",
- "-R": "string",
- "--review": "string",
- "--review-requested": "string",
- "--reviewed-by": "string",
- "--sort": "string",
- "--state": "string",
- "--team-mentions": "string",
- "--updated": "string",
- "--visibility": "string"
- }
- },
- "gh search commits": {
- safeFlags: {
- "--author": "string",
- "--author-date": "string",
- "--author-email": "string",
- "--author-name": "string",
- "--committer": "string",
- "--committer-date": "string",
- "--committer-email": "string",
- "--committer-name": "string",
- "--hash": "string",
- "--json": "string",
- "--limit": "number",
- "-L": "number",
- "--merge": "none",
- "--order": "string",
- "--owner": "string",
- "--parent": "string",
- "--repo": "string",
- "-R": "string",
- "--sort": "string",
- "--tree": "string",
- "--visibility": "string"
- }
- },
- "gh search code": {
- safeFlags: {
- "--extension": "string",
- "--filename": "string",
- "--json": "string",
- "--language": "string",
- "--limit": "number",
- "-L": "number",
- "--match": "string",
- "--owner": "string",
- "--repo": "string",
- "-R": "string",
- "--size": "string"
- }
- }
- };
- DOCKER_READ_ONLY_COMMANDS = {
- "docker logs": {
- safeFlags: {
- "--follow": "none",
- "-f": "none",
- "--tail": "string",
- "-n": "string",
- "--timestamps": "none",
- "-t": "none",
- "--since": "string",
- "--until": "string",
- "--details": "none"
- }
- },
- "docker inspect": {
- safeFlags: {
- "--format": "string",
- "-f": "string",
- "--type": "string",
- "--size": "none",
- "-s": "none"
- }
- }
- };
- RIPGREP_READ_ONLY_COMMANDS = {
- rg: {
- safeFlags: {
- "-e": "string",
- "--regexp": "string",
- "-f": "string",
- "-i": "none",
- "--ignore-case": "none",
- "-S": "none",
- "--smart-case": "none",
- "-F": "none",
- "--fixed-strings": "none",
- "-w": "none",
- "--word-regexp": "none",
- "-v": "none",
- "--invert-match": "none",
- "-c": "none",
- "--count": "none",
- "-l": "none",
- "--files-with-matches": "none",
- "--files-without-match": "none",
- "-n": "none",
- "--line-number": "none",
- "-o": "none",
- "--only-matching": "none",
- "-A": "number",
- "--after-context": "number",
- "-B": "number",
- "--before-context": "number",
- "-C": "number",
- "--context": "number",
- "-H": "none",
- "-h": "none",
- "--heading": "none",
- "--no-heading": "none",
- "-q": "none",
- "--quiet": "none",
- "--column": "none",
- "-g": "string",
- "--glob": "string",
- "-t": "string",
- "--type": "string",
- "-T": "string",
- "--type-not": "string",
- "--type-list": "none",
- "--hidden": "none",
- "--no-ignore": "none",
- "-u": "none",
- "-m": "number",
- "--max-count": "number",
- "-d": "number",
- "--max-depth": "number",
- "-a": "none",
- "--text": "none",
- "-z": "none",
- "-L": "none",
- "--follow": "none",
- "--color": "string",
- "--json": "none",
- "--stats": "none",
- "--help": "none",
- "--version": "none",
- "--debug": "none",
- "--": "none"
- }
- }
- };
- PYRIGHT_READ_ONLY_COMMANDS = {
- pyright: {
- respectsDoubleDash: false,
- safeFlags: {
- "--outputjson": "none",
- "--project": "string",
- "-p": "string",
- "--pythonversion": "string",
- "--pythonplatform": "string",
- "--typeshedpath": "string",
- "--venvpath": "string",
- "--level": "string",
- "--stats": "none",
- "--verbose": "none",
- "--version": "none",
- "--dependencies": "none",
- "--warnings": "none"
- },
- additionalCommandIsDangerousCallback: (_rawCommand, args) => {
- return args.some((t4) => t4 === "--watch" || t4 === "-w");
- }
- }
- };
- EXTERNAL_READONLY_COMMANDS = [
- "docker ps",
- "docker images"
- ];
- FLAG_PATTERN = /^-[a-zA-Z0-9_-]/;
-});
-
-// src/constants/toolLimits.ts
-var DEFAULT_MAX_RESULT_SIZE_CHARS = 50000, MAX_TOOL_RESULT_TOKENS = 1e5, BYTES_PER_TOKEN = 4, MAX_TOOL_RESULT_BYTES, MAX_TOOL_RESULTS_PER_MESSAGE_CHARS = 200000, TOOL_SUMMARY_MAX_LENGTH = 50;
-var init_toolLimits = __esm(() => {
- MAX_TOOL_RESULT_BYTES = MAX_TOOL_RESULT_TOKENS * BYTES_PER_TOKEN;
-});
-
-// src/utils/toolResultStorage.ts
-import { mkdir as mkdir6, writeFile as writeFile6 } from "fs/promises";
-import { join as join29 } from "path";
-function getPersistenceThreshold(toolName, declaredMaxResultSizeChars) {
- if (!Number.isFinite(declaredMaxResultSizeChars)) {
- return declaredMaxResultSizeChars;
- }
- const overrides = getFeatureValue_CACHED_MAY_BE_STALE(PERSIST_THRESHOLD_OVERRIDE_FLAG, {});
- const override = overrides?.[toolName];
- if (typeof override === "number" && Number.isFinite(override) && override > 0) {
- return override;
- }
- return Math.min(declaredMaxResultSizeChars, DEFAULT_MAX_RESULT_SIZE_CHARS);
-}
-function getSessionDir() {
- return join29(getProjectDir2(getOriginalCwd()), getSessionId());
-}
-function getToolResultsDir() {
- return join29(getSessionDir(), TOOL_RESULTS_SUBDIR);
-}
-function getToolResultPath(id, isJson) {
- const ext = isJson ? "json" : "txt";
- return join29(getToolResultsDir(), `${id}.${ext}`);
-}
-async function ensureToolResultsDir() {
- try {
- await mkdir6(getToolResultsDir(), { recursive: true });
- } catch {}
-}
-async function persistToolResult(content, toolUseId) {
- const isJson = Array.isArray(content);
- if (isJson) {
- const hasNonTextContent = content.some((block2) => block2.type !== "text");
- if (hasNonTextContent) {
- return {
- error: "Cannot persist tool results containing non-text content"
- };
- }
- }
- await ensureToolResultsDir();
- const filepath = getToolResultPath(toolUseId, isJson);
- const contentStr = isJson ? jsonStringify(content, null, 2) : content;
- try {
- await writeFile6(filepath, contentStr, { encoding: "utf-8", flag: "wx" });
- logForDebugging(`Persisted tool result to ${filepath} (${formatFileSize(contentStr.length)})`);
- } catch (error46) {
- if (getErrnoCode(error46) !== "EEXIST") {
- logError2(toError(error46));
- return { error: getFileSystemErrorMessage(toError(error46)) };
- }
- }
- const { preview, hasMore } = generatePreview(contentStr, PREVIEW_SIZE_BYTES);
- return {
- filepath,
- originalSize: contentStr.length,
- isJson,
- preview,
- hasMore
- };
-}
-function buildLargeToolResultMessage(result) {
- let message = `${PERSISTED_OUTPUT_TAG}
-`;
- message += `Output too large (${formatFileSize(result.originalSize)}). Full output saved to: ${result.filepath}
-
-`;
- message += `Preview (first ${formatFileSize(PREVIEW_SIZE_BYTES)}):
-`;
- message += result.preview;
- message += result.hasMore ? `
-...
-` : `
-`;
- message += PERSISTED_OUTPUT_CLOSING_TAG;
- return message;
-}
-async function processToolResultBlock(tool, toolUseResult, toolUseID) {
- const toolResultBlock = tool.mapToolResultToToolResultBlockParam(toolUseResult, toolUseID);
- return maybePersistLargeToolResult(toolResultBlock, tool.name, getPersistenceThreshold(tool.name, tool.maxResultSizeChars));
-}
-async function processPreMappedToolResultBlock(toolResultBlock, toolName, maxResultSizeChars) {
- return maybePersistLargeToolResult(toolResultBlock, toolName, getPersistenceThreshold(toolName, maxResultSizeChars));
-}
-function isToolResultContentEmpty(content) {
- if (!content)
- return true;
- if (typeof content === "string")
- return content.trim() === "";
- if (!Array.isArray(content))
- return false;
- if (content.length === 0)
- return true;
- return content.every((block2) => typeof block2 === "object" && ("type" in block2) && block2.type === "text" && ("text" in block2) && (typeof block2.text !== "string" || block2.text.trim() === ""));
-}
-async function maybePersistLargeToolResult(toolResultBlock, toolName, persistenceThreshold) {
- const content = toolResultBlock.content;
- if (isToolResultContentEmpty(content)) {
- logEvent("tengu_tool_empty_result", {
- toolName: sanitizeToolNameForAnalytics(toolName)
- });
- return {
- ...toolResultBlock,
- content: `(${toolName} completed with no output)`
- };
- }
- if (!content) {
- return toolResultBlock;
- }
- if (hasImageBlock(content)) {
- return toolResultBlock;
- }
- const size = contentSize(content);
- const threshold = persistenceThreshold ?? MAX_TOOL_RESULT_BYTES;
- if (size <= threshold) {
- return toolResultBlock;
- }
- const result = await persistToolResult(content, toolResultBlock.tool_use_id);
- if (isPersistError(result)) {
- return toolResultBlock;
- }
- const message = buildLargeToolResultMessage(result);
- logEvent("tengu_tool_result_persisted", {
- toolName: sanitizeToolNameForAnalytics(toolName),
- originalSizeBytes: result.originalSize,
- persistedSizeBytes: message.length,
- estimatedOriginalTokens: Math.ceil(result.originalSize / BYTES_PER_TOKEN),
- estimatedPersistedTokens: Math.ceil(message.length / BYTES_PER_TOKEN),
- thresholdUsed: threshold
- });
- return { ...toolResultBlock, content: message };
-}
-function generatePreview(content, maxBytes) {
- if (content.length <= maxBytes) {
- return { preview: content, hasMore: false };
- }
- const truncated = content.slice(0, maxBytes);
- const lastNewline = truncated.lastIndexOf(`
-`);
- const cutPoint = lastNewline > maxBytes * 0.5 ? lastNewline : maxBytes;
- return { preview: content.slice(0, cutPoint), hasMore: true };
-}
-function isPersistError(result) {
- return "error" in result;
-}
-function createContentReplacementState() {
- return { seenIds: new Set, replacements: new Map };
-}
-function cloneContentReplacementState(source) {
- return {
- seenIds: new Set(source.seenIds),
- replacements: new Map(source.replacements)
- };
-}
-function getPerMessageBudgetLimit() {
- const override = getFeatureValue_CACHED_MAY_BE_STALE("tengu_hawthorn_window", null);
- if (typeof override === "number" && Number.isFinite(override) && override > 0) {
- return override;
- }
- return MAX_TOOL_RESULTS_PER_MESSAGE_CHARS;
-}
-function provisionContentReplacementState(initialMessages, initialContentReplacements) {
- const enabled2 = getFeatureValue_CACHED_MAY_BE_STALE("tengu_hawthorn_steeple", false);
- if (!enabled2)
- return;
- if (initialMessages) {
- return reconstructContentReplacementState(initialMessages, initialContentReplacements ?? []);
- }
- return createContentReplacementState();
-}
-function isContentAlreadyCompacted(content) {
- return typeof content === "string" && content.startsWith(PERSISTED_OUTPUT_TAG);
-}
-function hasImageBlock(content) {
- return Array.isArray(content) && content.some((b4) => typeof b4 === "object" && ("type" in b4) && b4.type === "image");
-}
-function contentSize(content) {
- if (typeof content === "string")
- return content.length;
- return content.reduce((sum, b4) => sum + (b4.type === "text" ? b4.text.length : 0), 0);
-}
-function buildToolNameMap(messages) {
- const map7 = new Map;
- for (const message of messages) {
- if (message.type !== "assistant")
- continue;
- const content = message.message.content;
- if (!Array.isArray(content))
- continue;
- for (const block2 of content) {
- if (block2.type === "tool_use") {
- map7.set(block2.id, block2.name);
- }
- }
- }
- return map7;
-}
-function collectCandidatesFromMessage(message) {
- if (message.type !== "user" || !Array.isArray(message.message.content)) {
- return [];
- }
- return message.message.content.flatMap((block2) => {
- if (block2.type !== "tool_result" || !block2.content)
- return [];
- if (isContentAlreadyCompacted(block2.content))
- return [];
- if (hasImageBlock(block2.content))
- return [];
- return [
- {
- toolUseId: block2.tool_use_id,
- content: block2.content,
- size: contentSize(block2.content)
- }
- ];
- });
-}
-function collectCandidatesByMessage(messages) {
- const groups = [];
- let current = [];
- const flush = () => {
- if (current.length > 0)
- groups.push(current);
- current = [];
- };
- const seenAsstIds = new Set;
- for (const message of messages) {
- if (message.type === "user") {
- current.push(...collectCandidatesFromMessage(message));
- } else if (message.type === "assistant") {
- if (!seenAsstIds.has(message.message.id)) {
- flush();
- seenAsstIds.add(message.message.id);
- }
- }
- }
- flush();
- return groups;
-}
-function partitionByPriorDecision(candidates, state3) {
- return candidates.reduce((acc, c8) => {
- const replacement = state3.replacements.get(c8.toolUseId);
- if (replacement !== undefined) {
- acc.mustReapply.push({ ...c8, replacement });
- } else if (state3.seenIds.has(c8.toolUseId)) {
- acc.frozen.push(c8);
- } else {
- acc.fresh.push(c8);
- }
- return acc;
- }, { mustReapply: [], frozen: [], fresh: [] });
-}
-function selectFreshToReplace(fresh, frozenSize, limit) {
- const sorted = [...fresh].sort((a5, b4) => b4.size - a5.size);
- const selected = [];
- let remaining = frozenSize + fresh.reduce((sum, c8) => sum + c8.size, 0);
- for (const c8 of sorted) {
- if (remaining <= limit)
- break;
- selected.push(c8);
- remaining -= c8.size;
- }
- return selected;
-}
-function replaceToolResultContents(messages, replacementMap) {
- return messages.map((message) => {
- if (message.type !== "user" || !Array.isArray(message.message.content)) {
- return message;
- }
- const content = message.message.content;
- const needsReplace = content.some((b4) => b4.type === "tool_result" && replacementMap.has(b4.tool_use_id));
- if (!needsReplace)
- return message;
- return {
- ...message,
- message: {
- ...message.message,
- content: content.map((block2) => {
- if (block2.type !== "tool_result")
- return block2;
- const replacement = replacementMap.get(block2.tool_use_id);
- return replacement === undefined ? block2 : { ...block2, content: replacement };
- })
- }
- };
- });
-}
-async function buildReplacement(candidate) {
- const result = await persistToolResult(candidate.content, candidate.toolUseId);
- if (isPersistError(result))
- return null;
- return {
- content: buildLargeToolResultMessage(result),
- originalSize: result.originalSize
- };
-}
-async function enforceToolResultBudget(messages, state3, skipToolNames = new Set) {
- const candidatesByMessage = collectCandidatesByMessage(messages);
- const nameByToolUseId = skipToolNames.size > 0 ? buildToolNameMap(messages) : undefined;
- const shouldSkip = (id) => nameByToolUseId !== undefined && skipToolNames.has(nameByToolUseId.get(id) ?? "");
- const limit = getPerMessageBudgetLimit();
- const replacementMap = new Map;
- const toPersist = [];
- let reappliedCount = 0;
- let messagesOverBudget = 0;
- for (const candidates of candidatesByMessage) {
- const { mustReapply, frozen, fresh } = partitionByPriorDecision(candidates, state3);
- mustReapply.forEach((c8) => replacementMap.set(c8.toolUseId, c8.replacement));
- reappliedCount += mustReapply.length;
- if (fresh.length === 0) {
- candidates.forEach((c8) => state3.seenIds.add(c8.toolUseId));
- continue;
- }
- const skipped = fresh.filter((c8) => shouldSkip(c8.toolUseId));
- skipped.forEach((c8) => state3.seenIds.add(c8.toolUseId));
- const eligible2 = fresh.filter((c8) => !shouldSkip(c8.toolUseId));
- const frozenSize = frozen.reduce((sum, c8) => sum + c8.size, 0);
- const freshSize = eligible2.reduce((sum, c8) => sum + c8.size, 0);
- const selected = frozenSize + freshSize > limit ? selectFreshToReplace(eligible2, frozenSize, limit) : [];
- const selectedIds = new Set(selected.map((c8) => c8.toolUseId));
- candidates.filter((c8) => !selectedIds.has(c8.toolUseId)).forEach((c8) => state3.seenIds.add(c8.toolUseId));
- if (selected.length === 0)
- continue;
- messagesOverBudget++;
- toPersist.push(...selected);
- }
- if (replacementMap.size === 0 && toPersist.length === 0) {
- return { messages, newlyReplaced: [] };
- }
- const freshReplacements = await Promise.all(toPersist.map(async (c8) => [c8, await buildReplacement(c8)]));
- const newlyReplaced = [];
- let replacedSize = 0;
- for (const [candidate, replacement] of freshReplacements) {
- state3.seenIds.add(candidate.toolUseId);
- if (replacement === null)
- continue;
- replacedSize += candidate.size;
- replacementMap.set(candidate.toolUseId, replacement.content);
- state3.replacements.set(candidate.toolUseId, replacement.content);
- newlyReplaced.push({
- kind: "tool-result",
- toolUseId: candidate.toolUseId,
- replacement: replacement.content
- });
- logEvent("tengu_tool_result_persisted_message_budget", {
- originalSizeBytes: replacement.originalSize,
- persistedSizeBytes: replacement.content.length,
- estimatedOriginalTokens: Math.ceil(replacement.originalSize / BYTES_PER_TOKEN),
- estimatedPersistedTokens: Math.ceil(replacement.content.length / BYTES_PER_TOKEN)
- });
- }
- if (replacementMap.size === 0) {
- return { messages, newlyReplaced: [] };
- }
- if (newlyReplaced.length > 0) {
- logForDebugging(`Per-message budget: persisted ${newlyReplaced.length} tool results ` + `across ${messagesOverBudget} over-budget message(s), ` + `shed ~${formatFileSize(replacedSize)}, ${reappliedCount} re-applied`);
- logEvent("tengu_message_level_tool_result_budget_enforced", {
- resultsPersisted: newlyReplaced.length,
- messagesOverBudget,
- replacedSizeBytes: replacedSize,
- reapplied: reappliedCount
- });
- }
- return {
- messages: replaceToolResultContents(messages, replacementMap),
- newlyReplaced
- };
-}
-async function applyToolResultBudget(messages, state3, writeToTranscript, skipToolNames) {
- if (!state3)
- return messages;
- const result = await enforceToolResultBudget(messages, state3, skipToolNames);
- if (result.newlyReplaced.length > 0) {
- writeToTranscript?.(result.newlyReplaced);
- }
- return result.messages;
-}
-function reconstructContentReplacementState(messages, records, inheritedReplacements) {
- const state3 = createContentReplacementState();
- const candidateIds = new Set(collectCandidatesByMessage(messages).flat().map((c8) => c8.toolUseId));
- for (const id of candidateIds) {
- state3.seenIds.add(id);
- }
- for (const r4 of records) {
- if (r4.kind === "tool-result" && candidateIds.has(r4.toolUseId)) {
- state3.replacements.set(r4.toolUseId, r4.replacement);
- }
- }
- if (inheritedReplacements) {
- for (const [id, replacement] of inheritedReplacements) {
- if (candidateIds.has(id) && !state3.replacements.has(id)) {
- state3.replacements.set(id, replacement);
- }
- }
- }
- return state3;
-}
-function reconstructForSubagentResume(parentState, resumedMessages, sidechainRecords) {
- if (!parentState)
- return;
- return reconstructContentReplacementState(resumedMessages, sidechainRecords, parentState.replacements);
-}
-function getFileSystemErrorMessage(error46) {
- const nodeError = error46;
- if (nodeError.code) {
- switch (nodeError.code) {
- case "ENOENT":
- return `Directory not found: ${nodeError.path ?? "unknown path"}`;
- case "EACCES":
- return `Permission denied: ${nodeError.path ?? "unknown path"}`;
- case "ENOSPC":
- return "No space left on device";
- case "EROFS":
- return "Read-only file system";
- case "EMFILE":
- return "Too many open files";
- case "EEXIST":
- return `File already exists: ${nodeError.path ?? "unknown path"}`;
- default:
- return `${nodeError.code}: ${nodeError.message}`;
- }
- }
- return error46.message;
-}
-var TOOL_RESULTS_SUBDIR = "tool-results", PERSISTED_OUTPUT_TAG = "", PERSISTED_OUTPUT_CLOSING_TAG = "", PERSIST_THRESHOLD_OVERRIDE_FLAG = "tengu_satin_quoll", PREVIEW_SIZE_BYTES = 2000;
-var init_toolResultStorage = __esm(() => {
- init_state();
- init_toolLimits();
- init_growthbook();
- init_analytics();
- init_metadata();
- init_debug();
- init_errors();
- init_format();
- init_log2();
- init_sessionStorage();
- init_slowOperations();
-});
-
-// src/utils/permissions/permissionsLoader.ts
-function shouldAllowManagedPermissionRulesOnly() {
- return getSettingsForSource("policySettings")?.allowManagedPermissionRulesOnly === true;
-}
-function shouldShowAlwaysAllowOptions() {
- return !shouldAllowManagedPermissionRulesOnly();
-}
-function getSettingsForSourceLenient_FOR_EDITING_ONLY_NOT_FOR_READING(source) {
- const filePath = getSettingsFilePathForSource(source);
- if (!filePath) {
- return null;
- }
- try {
- const { resolvedPath: resolvedPath5 } = safeResolvePath(getFsImplementation(), filePath);
- const content = readFileSync4(resolvedPath5);
- if (content.trim() === "") {
- return {};
- }
- const data = safeParseJSON(content, false);
- return data && typeof data === "object" ? data : null;
- } catch {
- return null;
- }
-}
-function settingsJsonToRules(data, source) {
- if (!data || !data.permissions) {
- return [];
- }
- const { permissions } = data;
- const rules = [];
- for (const behavior of SUPPORTED_RULE_BEHAVIORS) {
- const behaviorArray = permissions[behavior];
- if (behaviorArray) {
- for (const ruleString of behaviorArray) {
- rules.push({
- source,
- ruleBehavior: behavior,
- ruleValue: permissionRuleValueFromString(ruleString)
- });
- }
- }
- }
- return rules;
-}
-function loadAllPermissionRulesFromDisk() {
- if (shouldAllowManagedPermissionRulesOnly()) {
- return getPermissionRulesForSource("policySettings");
- }
- const rules = [];
- for (const source of getEnabledSettingSources()) {
- rules.push(...getPermissionRulesForSource(source));
- }
- return rules;
-}
-function getPermissionRulesForSource(source) {
- const settingsData = getSettingsForSource(source);
- return settingsJsonToRules(settingsData, source);
-}
-function deletePermissionRuleFromSettings(rule) {
- if (!EDITABLE_SOURCES.includes(rule.source)) {
- return false;
- }
- const ruleString = permissionRuleValueToString(rule.ruleValue);
- const settingsData = getSettingsForSource(rule.source);
- if (!settingsData || !settingsData.permissions) {
- return false;
- }
- const behaviorArray = settingsData.permissions[rule.ruleBehavior];
- if (!behaviorArray) {
- return false;
- }
- const normalizeEntry = (raw) => permissionRuleValueToString(permissionRuleValueFromString(raw));
- if (!behaviorArray.some((raw) => normalizeEntry(raw) === ruleString)) {
- return false;
- }
- try {
- const updatedSettingsData = {
- ...settingsData,
- permissions: {
- ...settingsData.permissions,
- [rule.ruleBehavior]: behaviorArray.filter((raw) => normalizeEntry(raw) !== ruleString)
- }
- };
- const { error: error46 } = updateSettingsForSource(rule.source, updatedSettingsData);
- if (error46) {
- return false;
- }
- return true;
- } catch (error46) {
- logError2(error46);
- return false;
- }
-}
-function getEmptyPermissionSettingsJson() {
- return {
- permissions: {}
- };
-}
-function addPermissionRulesToSettings({
- ruleValues,
- ruleBehavior
-}, source) {
- if (shouldAllowManagedPermissionRulesOnly()) {
- return false;
- }
- if (ruleValues.length < 1) {
- return true;
- }
- const ruleStrings = ruleValues.map(permissionRuleValueToString);
- const settingsData = getSettingsForSource(source) || getSettingsForSourceLenient_FOR_EDITING_ONLY_NOT_FOR_READING(source) || getEmptyPermissionSettingsJson();
- try {
- const existingPermissions = settingsData.permissions || {};
- const existingRules = existingPermissions[ruleBehavior] || [];
- const existingRulesSet = new Set(existingRules.map((raw) => permissionRuleValueToString(permissionRuleValueFromString(raw))));
- const newRules = ruleStrings.filter((rule) => !existingRulesSet.has(rule));
- if (newRules.length === 0) {
- return true;
- }
- const updatedSettingsData = {
- ...settingsData,
- permissions: {
- ...existingPermissions,
- [ruleBehavior]: [...existingRules, ...newRules]
- }
- };
- const result = updateSettingsForSource(source, updatedSettingsData);
- if (result.error) {
- throw result.error;
- }
- return true;
- } catch (error46) {
- logError2(error46);
- return false;
- }
-}
-var SUPPORTED_RULE_BEHAVIORS, EDITABLE_SOURCES;
-var init_permissionsLoader = __esm(() => {
- init_fileRead();
- init_fsOperations();
- init_json();
- init_log2();
- init_constants2();
- init_settings2();
- init_permissionRuleParser();
- SUPPORTED_RULE_BEHAVIORS = [
- "allow",
- "deny",
- "ask"
- ];
- EDITABLE_SOURCES = [
- "userSettings",
- "projectSettings",
- "localSettings"
- ];
-});
-
-// src/utils/permissions/PermissionUpdate.ts
-import { posix } from "path";
-function extractRules(updates) {
- if (!updates)
- return [];
- return updates.flatMap((update) => {
- switch (update.type) {
- case "addRules":
- return update.rules;
- default:
- return [];
- }
- });
-}
-function hasRules(updates) {
- return extractRules(updates).length > 0;
-}
-function applyPermissionUpdate(context4, update) {
- switch (update.type) {
- case "setMode":
- logForDebugging(`Applying permission update: Setting mode to '${update.mode}'`);
- return {
- ...context4,
- mode: update.mode
- };
- case "addRules": {
- const ruleStrings = update.rules.map((rule) => permissionRuleValueToString(rule));
- logForDebugging(`Applying permission update: Adding ${update.rules.length} ${update.behavior} rule(s) to destination '${update.destination}': ${jsonStringify(ruleStrings)}`);
- const ruleKind = update.behavior === "allow" ? "alwaysAllowRules" : update.behavior === "deny" ? "alwaysDenyRules" : "alwaysAskRules";
- return {
- ...context4,
- [ruleKind]: {
- ...context4[ruleKind],
- [update.destination]: [
- ...context4[ruleKind][update.destination] || [],
- ...ruleStrings
- ]
- }
- };
- }
- case "replaceRules": {
- const ruleStrings = update.rules.map((rule) => permissionRuleValueToString(rule));
- logForDebugging(`Replacing all ${update.behavior} rules for destination '${update.destination}' with ${update.rules.length} rule(s): ${jsonStringify(ruleStrings)}`);
- const ruleKind = update.behavior === "allow" ? "alwaysAllowRules" : update.behavior === "deny" ? "alwaysDenyRules" : "alwaysAskRules";
- return {
- ...context4,
- [ruleKind]: {
- ...context4[ruleKind],
- [update.destination]: ruleStrings
- }
- };
- }
- case "addDirectories": {
- logForDebugging(`Applying permission update: Adding ${update.directories.length} director${update.directories.length === 1 ? "y" : "ies"} with destination '${update.destination}': ${jsonStringify(update.directories)}`);
- const newAdditionalDirs = new Map(context4.additionalWorkingDirectories);
- for (const directory of update.directories) {
- newAdditionalDirs.set(directory, {
- path: directory,
- source: update.destination
- });
- }
- return {
- ...context4,
- additionalWorkingDirectories: newAdditionalDirs
- };
- }
- case "removeRules": {
- const ruleStrings = update.rules.map((rule) => permissionRuleValueToString(rule));
- logForDebugging(`Applying permission update: Removing ${update.rules.length} ${update.behavior} rule(s) from source '${update.destination}': ${jsonStringify(ruleStrings)}`);
- const ruleKind = update.behavior === "allow" ? "alwaysAllowRules" : update.behavior === "deny" ? "alwaysDenyRules" : "alwaysAskRules";
- const existingRules = context4[ruleKind][update.destination] || [];
- const rulesToRemove = new Set(ruleStrings);
- const filteredRules = existingRules.filter((rule) => !rulesToRemove.has(rule));
- return {
- ...context4,
- [ruleKind]: {
- ...context4[ruleKind],
- [update.destination]: filteredRules
- }
- };
- }
- case "removeDirectories": {
- logForDebugging(`Applying permission update: Removing ${update.directories.length} director${update.directories.length === 1 ? "y" : "ies"}: ${jsonStringify(update.directories)}`);
- const newAdditionalDirs = new Map(context4.additionalWorkingDirectories);
- for (const directory of update.directories) {
- newAdditionalDirs.delete(directory);
- }
- return {
- ...context4,
- additionalWorkingDirectories: newAdditionalDirs
- };
- }
- default:
- return context4;
- }
-}
-function applyPermissionUpdates(context4, updates) {
- let updatedContext = context4;
- for (const update of updates) {
- updatedContext = applyPermissionUpdate(updatedContext, update);
- }
- return updatedContext;
-}
-function supportsPersistence(destination) {
- return destination === "localSettings" || destination === "userSettings" || destination === "projectSettings";
-}
-function persistPermissionUpdate(update) {
- if (!supportsPersistence(update.destination))
- return;
- logForDebugging(`Persisting permission update: ${update.type} to source '${update.destination}'`);
- switch (update.type) {
- case "addRules": {
- logForDebugging(`Persisting ${update.rules.length} ${update.behavior} rule(s) to ${update.destination}`);
- addPermissionRulesToSettings({
- ruleValues: update.rules,
- ruleBehavior: update.behavior
- }, update.destination);
- break;
- }
- case "addDirectories": {
- logForDebugging(`Persisting ${update.directories.length} director${update.directories.length === 1 ? "y" : "ies"} to ${update.destination}`);
- const existingSettings = getSettingsForSource(update.destination);
- const existingDirs = existingSettings?.permissions?.additionalDirectories || [];
- const dirsToAdd = update.directories.filter((dir) => !existingDirs.includes(dir));
- if (dirsToAdd.length > 0) {
- const updatedDirs = [...existingDirs, ...dirsToAdd];
- updateSettingsForSource(update.destination, {
- permissions: {
- additionalDirectories: updatedDirs
- }
- });
- }
- break;
- }
- case "removeRules": {
- logForDebugging(`Removing ${update.rules.length} ${update.behavior} rule(s) from ${update.destination}`);
- const existingSettings = getSettingsForSource(update.destination);
- const existingPermissions = existingSettings?.permissions || {};
- const existingRules = existingPermissions[update.behavior] || [];
- const rulesToRemove = new Set(update.rules.map(permissionRuleValueToString));
- const filteredRules = existingRules.filter((rule) => {
- const normalized = permissionRuleValueToString(permissionRuleValueFromString(rule));
- return !rulesToRemove.has(normalized);
- });
- updateSettingsForSource(update.destination, {
- permissions: {
- [update.behavior]: filteredRules
- }
- });
- break;
- }
- case "removeDirectories": {
- logForDebugging(`Removing ${update.directories.length} director${update.directories.length === 1 ? "y" : "ies"} from ${update.destination}`);
- const existingSettings = getSettingsForSource(update.destination);
- const existingDirs = existingSettings?.permissions?.additionalDirectories || [];
- const dirsToRemove = new Set(update.directories);
- const filteredDirs = existingDirs.filter((dir) => !dirsToRemove.has(dir));
- updateSettingsForSource(update.destination, {
- permissions: {
- additionalDirectories: filteredDirs
- }
- });
- break;
- }
- case "setMode": {
- logForDebugging(`Persisting mode '${update.mode}' to ${update.destination}`);
- updateSettingsForSource(update.destination, {
- permissions: {
- defaultMode: update.mode
- }
- });
- break;
- }
- case "replaceRules": {
- logForDebugging(`Replacing all ${update.behavior} rules in ${update.destination} with ${update.rules.length} rule(s)`);
- const ruleStrings = update.rules.map(permissionRuleValueToString);
- updateSettingsForSource(update.destination, {
- permissions: {
- [update.behavior]: ruleStrings
- }
- });
- break;
- }
- }
-}
-function persistPermissionUpdates(updates) {
- for (const update of updates) {
- persistPermissionUpdate(update);
- }
-}
-function createReadRuleSuggestion(dirPath, destination = "session") {
- const pathForPattern = toPosixPath(dirPath);
- if (pathForPattern === "/") {
- return;
- }
- const ruleContent = posix.isAbsolute(pathForPattern) ? `/${pathForPattern}/**` : `${pathForPattern}/**`;
- return {
- type: "addRules",
- rules: [
- {
- toolName: "Read",
- ruleContent
- }
- ],
- behavior: "allow",
- destination
- };
-}
-var init_PermissionUpdate = __esm(() => {
- init_debug();
- init_settings2();
- init_slowOperations();
- init_filesystem();
- init_permissionRuleParser();
- init_permissionsLoader();
-});
-
-// src/constants/system.ts
-function getCLISyspromptPrefix(options2) {
- const apiProvider = getAPIProvider();
- if (apiProvider === "vertex") {
- return DEFAULT_PREFIX;
- }
- if (options2?.isNonInteractive) {
- if (options2.hasAppendSystemPrompt) {
- return AGENT_SDK_CLAUDE_CODE_PRESET_PREFIX;
- }
- return AGENT_SDK_PREFIX;
- }
- return DEFAULT_PREFIX;
-}
-function isAttributionHeaderEnabled() {
- if (isEnvDefinedFalsy(process.env.CLAUDE_CODE_ATTRIBUTION_HEADER)) {
- return false;
- }
- return getFeatureValue_CACHED_MAY_BE_STALE("tengu_attribution_header", true);
-}
-function getAttributionHeader(fingerprint) {
- if (!isAttributionHeaderEnabled()) {
- return "";
- }
- const version6 = `${MACRO.VERSION}.${fingerprint}`;
- const entrypoint = process.env.CLAUDE_CODE_ENTRYPOINT ?? "unknown";
- const cch = "";
- const workload = getWorkload();
- const workloadPair = workload ? ` cc_workload=${workload};` : "";
- const header = `x-anthropic-billing-header: cc_version=${version6}; cc_entrypoint=${entrypoint};${cch}${workloadPair}`;
- logForDebugging(`attribution header ${header}`);
- return header;
-}
-var DEFAULT_PREFIX = `You are Claude Code, Anthropic's official CLI for Claude.`, AGENT_SDK_CLAUDE_CODE_PRESET_PREFIX = `You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.`, AGENT_SDK_PREFIX = `You are a Claude agent, built on Anthropic's Claude Agent SDK.`, CLI_SYSPROMPT_PREFIX_VALUES, CLI_SYSPROMPT_PREFIXES;
-var init_system = __esm(() => {
- init_growthbook();
- init_debug();
- init_envUtils();
- init_providers();
- init_workloadContext();
- CLI_SYSPROMPT_PREFIX_VALUES = [
- DEFAULT_PREFIX,
- AGENT_SDK_CLAUDE_CODE_PRESET_PREFIX,
- AGENT_SDK_PREFIX
- ];
- CLI_SYSPROMPT_PREFIXES = new Set(CLI_SYSPROMPT_PREFIX_VALUES);
-});
-
-// src/Tool.ts
-function filterToolProgressMessages(progressMessagesForMessage) {
- return progressMessagesForMessage.filter((msg) => msg.data?.type !== "hook_progress");
-}
-function toolMatchesName(tool, name3) {
- return tool.name === name3 || (tool.aliases?.includes(name3) ?? false);
-}
-function findToolByName(tools, name3) {
- return tools.find((t4) => toolMatchesName(t4, name3));
-}
-function buildTool(def2) {
- return {
- ...TOOL_DEFAULTS,
- userFacingName: () => def2.name,
- ...def2
- };
-}
-var getEmptyToolPermissionContext = () => ({
- mode: "default",
- additionalWorkingDirectories: new Map,
- alwaysAllowRules: {},
- alwaysDenyRules: {},
- alwaysAskRules: {},
- isBypassPermissionsModeAvailable: false
-}), TOOL_DEFAULTS;
-var init_Tool = __esm(() => {
- TOOL_DEFAULTS = {
- isEnabled: () => true,
- isConcurrencySafe: (_input) => false,
- isReadOnly: (_input) => false,
- isDestructive: (_input) => false,
- checkPermissions: (input, _ctx) => Promise.resolve({ behavior: "allow", updatedInput: input }),
- toAutoClassifierInput: (_input) => "",
- userFacingName: (_input) => ""
- };
-});
-// node_modules/tree-kill/index.js
-var require_tree_kill = __commonJS((exports, module) => {
- var childProcess3 = __require("child_process");
- var spawn2 = childProcess3.spawn;
- var exec4 = childProcess3.exec;
- module.exports = function(pid, signal, callback) {
- if (typeof signal === "function" && callback === undefined) {
- callback = signal;
- signal = undefined;
- }
- pid = parseInt(pid);
- if (Number.isNaN(pid)) {
- if (callback) {
- return callback(new Error("pid must be a number"));
- } else {
- throw new Error("pid must be a number");
- }
- }
- var tree = {};
- var pidsToProcess = {};
- tree[pid] = [];
- pidsToProcess[pid] = 1;
- switch (process.platform) {
- case "win32":
- exec4("taskkill /pid " + pid + " /T /F", callback);
- break;
- case "darwin":
- buildProcessTree(pid, tree, pidsToProcess, function(parentPid) {
- return spawn2("pgrep", ["-P", parentPid]);
- }, function() {
- killAll(tree, signal, callback);
- });
- break;
- default:
- buildProcessTree(pid, tree, pidsToProcess, function(parentPid) {
- return spawn2("ps", ["-o", "pid", "--no-headers", "--ppid", parentPid]);
- }, function() {
- killAll(tree, signal, callback);
- });
- break;
- }
- };
- function killAll(tree, signal, callback) {
- var killed = {};
- try {
- Object.keys(tree).forEach(function(pid) {
- tree[pid].forEach(function(pidpid) {
- if (!killed[pidpid]) {
- killPid(pidpid, signal);
- killed[pidpid] = 1;
- }
- });
- if (!killed[pid]) {
- killPid(pid, signal);
- killed[pid] = 1;
- }
- });
- } catch (err) {
- if (callback) {
- return callback(err);
- } else {
- throw err;
- }
- }
- if (callback) {
- return callback();
- }
- }
- function killPid(pid, signal) {
- try {
- process.kill(parseInt(pid, 10), signal);
- } catch (err) {
- if (err.code !== "ESRCH")
- throw err;
- }
- }
- function buildProcessTree(parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) {
- var ps = spawnChildProcessesList(parentPid);
- var allData = "";
- ps.stdout.on("data", function(data) {
- var data = data.toString("ascii");
- allData += data;
- });
- var onClose = function(code) {
- delete pidsToProcess[parentPid];
- if (code != 0) {
- if (Object.keys(pidsToProcess).length == 0) {
- cb();
- }
- return;
- }
- allData.match(/\d+/g).forEach(function(pid) {
- pid = parseInt(pid, 10);
- tree[parentPid].push(pid);
- tree[pid] = [];
- pidsToProcess[pid] = 1;
- buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
- });
- };
- ps.on("close", onClose);
- }
-});
-
-// src/utils/task/diskOutput.ts
-import { constants as fsConstants4 } from "fs";
-import {
- mkdir as mkdir7,
- open as open5,
- stat as stat8,
- symlink as symlink2,
- unlink as unlink3
-} from "fs/promises";
-import { join as join30 } from "path";
-function getTaskOutputDir() {
- if (_taskOutputDir === undefined) {
- _taskOutputDir = join30(getProjectTempDir(), getSessionId(), "tasks");
- }
- return _taskOutputDir;
-}
-async function ensureOutputDir() {
- await mkdir7(getTaskOutputDir(), { recursive: true });
-}
-function getTaskOutputPath(taskId) {
- return join30(getTaskOutputDir(), `${taskId}.output`);
-}
-function track(p4) {
- _pendingOps.add(p4);
- p4.finally(() => _pendingOps.delete(p4)).catch(() => {});
- return p4;
-}
-
-class DiskTaskOutput {
- #path;
- #fileHandle = null;
- #queue = [];
- #bytesWritten = 0;
- #capped = false;
- #flushPromise = null;
- #flushResolve = null;
- constructor(taskId) {
- this.#path = getTaskOutputPath(taskId);
- }
- append(content) {
- if (this.#capped) {
- return;
- }
- this.#bytesWritten += content.length;
- if (this.#bytesWritten > MAX_TASK_OUTPUT_BYTES) {
- this.#capped = true;
- this.#queue.push(`
-[output truncated: exceeded ${MAX_TASK_OUTPUT_BYTES_DISPLAY} disk cap]
-`);
- } else {
- this.#queue.push(content);
- }
- if (!this.#flushPromise) {
- this.#flushPromise = new Promise((resolve10) => {
- this.#flushResolve = resolve10;
- });
- track(this.#drain());
- }
- }
- flush() {
- return this.#flushPromise ?? Promise.resolve();
- }
- cancel() {
- this.#queue.length = 0;
- }
- async#drainAllChunks() {
- while (true) {
- try {
- if (!this.#fileHandle) {
- await ensureOutputDir();
- this.#fileHandle = await open5(this.#path, process.platform === "win32" ? "a" : fsConstants4.O_WRONLY | fsConstants4.O_APPEND | fsConstants4.O_CREAT | O_NOFOLLOW);
- }
- while (true) {
- await this.#writeAllChunks();
- if (this.#queue.length === 0) {
- break;
- }
- }
- } finally {
- if (this.#fileHandle) {
- const fileHandle = this.#fileHandle;
- this.#fileHandle = null;
- await fileHandle.close();
- }
- }
- if (this.#queue.length) {
- continue;
- }
- break;
- }
- }
- #writeAllChunks() {
- return this.#fileHandle.appendFile(this.#queueToBuffers());
- }
- #queueToBuffers() {
- const queue = this.#queue.splice(0, this.#queue.length);
- let totalLength = 0;
- for (const str of queue) {
- totalLength += Buffer.byteLength(str, "utf8");
- }
- const buffer = Buffer.allocUnsafe(totalLength);
- let offset = 0;
- for (const str of queue) {
- offset += buffer.write(str, offset, "utf8");
- }
- return buffer;
- }
- async#drain() {
- try {
- await this.#drainAllChunks();
- } catch (e4) {
- logError2(e4);
- if (this.#queue.length > 0) {
- try {
- await this.#drainAllChunks();
- } catch (e22) {
- logError2(e22);
- }
- }
- } finally {
- const resolve10 = this.#flushResolve;
- this.#flushPromise = null;
- this.#flushResolve = null;
- resolve10();
- }
- }
-}
-function getOrCreateOutput(taskId) {
- let output = outputs.get(taskId);
- if (!output) {
- output = new DiskTaskOutput(taskId);
- outputs.set(taskId, output);
- }
- return output;
-}
-function appendTaskOutput(taskId, content) {
- getOrCreateOutput(taskId).append(content);
-}
-function evictTaskOutput(taskId) {
- return track((async () => {
- const output = outputs.get(taskId);
- if (output) {
- await output.flush();
- outputs.delete(taskId);
- }
- })());
-}
-async function getTaskOutputDelta(taskId, fromOffset, maxBytes = DEFAULT_MAX_READ_BYTES) {
- try {
- const result = await readFileRange(getTaskOutputPath(taskId), fromOffset, maxBytes);
- if (!result) {
- return { content: "", newOffset: fromOffset };
- }
- return {
- content: result.content,
- newOffset: fromOffset + result.bytesRead
- };
- } catch (e4) {
- const code = getErrnoCode(e4);
- if (code === "ENOENT") {
- return { content: "", newOffset: fromOffset };
- }
- logError2(e4);
- return { content: "", newOffset: fromOffset };
- }
-}
-async function getTaskOutput(taskId, maxBytes = DEFAULT_MAX_READ_BYTES) {
- try {
- const { content, bytesTotal, bytesRead } = await tailFile(getTaskOutputPath(taskId), maxBytes);
- if (bytesTotal > bytesRead) {
- return `[${Math.round((bytesTotal - bytesRead) / 1024)}KB of earlier output omitted]
-${content}`;
- }
- return content;
- } catch (e4) {
- const code = getErrnoCode(e4);
- if (code === "ENOENT") {
- return "";
- }
- logError2(e4);
- return "";
- }
-}
-function initTaskOutput(taskId) {
- return track((async () => {
- await ensureOutputDir();
- const outputPath = getTaskOutputPath(taskId);
- const fh = await open5(outputPath, process.platform === "win32" ? "wx" : fsConstants4.O_WRONLY | fsConstants4.O_CREAT | fsConstants4.O_EXCL | O_NOFOLLOW);
- await fh.close();
- return outputPath;
- })());
-}
-function initTaskOutputAsSymlink(taskId, targetPath) {
- return track((async () => {
- try {
- await ensureOutputDir();
- const outputPath = getTaskOutputPath(taskId);
- try {
- await symlink2(targetPath, outputPath);
- } catch {
- await unlink3(outputPath);
- await symlink2(targetPath, outputPath);
- }
- return outputPath;
- } catch (error46) {
- logError2(error46);
- return initTaskOutput(taskId);
- }
- })());
-}
-var O_NOFOLLOW, DEFAULT_MAX_READ_BYTES, MAX_TASK_OUTPUT_BYTES, MAX_TASK_OUTPUT_BYTES_DISPLAY = "5GB", _taskOutputDir, _pendingOps, outputs;
-var init_diskOutput = __esm(() => {
- init_state();
- init_errors();
- init_fsOperations();
- init_log2();
- init_filesystem();
- O_NOFOLLOW = fsConstants4.O_NOFOLLOW ?? 0;
- DEFAULT_MAX_READ_BYTES = 8 * 1024 * 1024;
- MAX_TASK_OUTPUT_BYTES = 5 * 1024 * 1024 * 1024;
- _pendingOps = new Set;
- outputs = new Map;
-});
-
-// src/Task.ts
-import { randomBytes as randomBytes3 } from "crypto";
-function isTerminalTaskStatus(status) {
- return status === "completed" || status === "failed" || status === "killed";
-}
-function getTaskIdPrefix(type) {
- return TASK_ID_PREFIXES[type] ?? "x";
-}
-function generateTaskId(type) {
- const prefix = getTaskIdPrefix(type);
- const bytes = randomBytes3(8);
- let id = prefix;
- for (let i5 = 0;i5 < 8; i5++) {
- id += TASK_ID_ALPHABET[bytes[i5] % TASK_ID_ALPHABET.length];
- }
- return id;
-}
-function createTaskStateBase(id, type, description, toolUseId) {
- return {
- id,
- type,
- status: "pending",
- description,
- toolUseId,
- startTime: Date.now(),
- outputFile: getTaskOutputPath(id),
- outputOffset: 0,
- notified: false
- };
-}
-var TASK_ID_PREFIXES, TASK_ID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
-var init_Task = __esm(() => {
- init_diskOutput();
- TASK_ID_PREFIXES = {
- local_bash: "b",
- local_agent: "a",
- remote_agent: "r",
- in_process_teammate: "t",
- local_workflow: "w",
- monitor_mcp: "m",
- dream: "d"
- };
-});
-
-// src/utils/CircularBuffer.ts
-class CircularBuffer {
- capacity;
- buffer;
- head = 0;
- size = 0;
- constructor(capacity) {
- this.capacity = capacity;
- this.buffer = new Array(capacity);
- }
- add(item) {
- this.buffer[this.head] = item;
- this.head = (this.head + 1) % this.capacity;
- if (this.size < this.capacity) {
- this.size++;
- }
- }
- addAll(items) {
- for (const item of items) {
- this.add(item);
- }
- }
- getRecent(count3) {
- const result = [];
- const start = this.size < this.capacity ? 0 : this.head;
- const available = Math.min(count3, this.size);
- for (let i5 = 0;i5 < available; i5++) {
- const index2 = (start + this.size - available + i5) % this.capacity;
- result.push(this.buffer[index2]);
- }
- return result;
- }
- toArray() {
- if (this.size === 0)
- return [];
- const result = [];
- const start = this.size < this.capacity ? 0 : this.head;
- for (let i5 = 0;i5 < this.size; i5++) {
- const index2 = (start + i5) % this.capacity;
- result.push(this.buffer[index2]);
- }
- return result;
- }
- clear() {
- this.buffer.length = 0;
- this.head = 0;
- this.size = 0;
- }
- length() {
- return this.size;
- }
-}
-
-// src/utils/envValidation.ts
-function validateBoundedIntEnvVar(name3, value, defaultValue, upperLimit) {
- if (!value) {
- return { effective: defaultValue, status: "valid" };
- }
- const parsed = parseInt(value, 10);
- if (isNaN(parsed) || parsed <= 0) {
- const result = {
- effective: defaultValue,
- status: "invalid",
- message: `Invalid value "${value}" (using default: ${defaultValue})`
- };
- logForDebugging(`${name3} ${result.message}`);
- return result;
- }
- if (parsed > upperLimit) {
- const result = {
- effective: upperLimit,
- status: "capped",
- message: `Capped from ${parsed} to ${upperLimit}`
- };
- logForDebugging(`${name3} ${result.message}`);
- return result;
- }
- return { effective: parsed, status: "valid" };
-}
-var init_envValidation = __esm(() => {
- init_debug();
-});
-
-// src/utils/shell/outputLimits.ts
-function getMaxOutputLength() {
- const result = validateBoundedIntEnvVar("BASH_MAX_OUTPUT_LENGTH", process.env.BASH_MAX_OUTPUT_LENGTH, BASH_MAX_OUTPUT_DEFAULT, BASH_MAX_OUTPUT_UPPER_LIMIT);
- return result.effective;
-}
-var BASH_MAX_OUTPUT_UPPER_LIMIT = 150000, BASH_MAX_OUTPUT_DEFAULT = 30000;
-var init_outputLimits = __esm(() => {
- init_envValidation();
-});
-
-// src/utils/task/TaskOutput.ts
-import { unlink as unlink4 } from "fs/promises";
-var DEFAULT_MAX_MEMORY, POLL_INTERVAL_MS = 1000, PROGRESS_TAIL_BYTES = 4096, TaskOutput;
-var init_TaskOutput = __esm(() => {
- init_debug();
- init_fsOperations();
- init_outputLimits();
- init_stringUtils();
- init_diskOutput();
- DEFAULT_MAX_MEMORY = 8 * 1024 * 1024;
- TaskOutput = class TaskOutput {
- taskId;
- path;
- stdoutToFile;
- #stdoutBuffer = "";
- #stderrBuffer = "";
- #disk = null;
- #recentLines = new CircularBuffer(1000);
- #totalLines = 0;
- #totalBytes = 0;
- #maxMemory;
- #onProgress;
- #outputFileRedundant = false;
- #outputFileSize = 0;
- static #registry = new Map;
- static #activePolling = new Map;
- static #pollInterval = null;
- constructor(taskId, onProgress, stdoutToFile = false, maxMemory = DEFAULT_MAX_MEMORY) {
- this.taskId = taskId;
- this.path = getTaskOutputPath(taskId);
- this.stdoutToFile = stdoutToFile;
- this.#maxMemory = maxMemory;
- this.#onProgress = onProgress;
- if (stdoutToFile && onProgress) {
- TaskOutput.#registry.set(taskId, this);
- }
- }
- static startPolling(taskId) {
- const instance = TaskOutput.#registry.get(taskId);
- if (!instance || !instance.#onProgress) {
- return;
- }
- TaskOutput.#activePolling.set(taskId, instance);
- if (!TaskOutput.#pollInterval) {
- TaskOutput.#pollInterval = setInterval(TaskOutput.#tick, POLL_INTERVAL_MS);
- TaskOutput.#pollInterval.unref();
- }
- }
- static stopPolling(taskId) {
- TaskOutput.#activePolling.delete(taskId);
- if (TaskOutput.#activePolling.size === 0 && TaskOutput.#pollInterval) {
- clearInterval(TaskOutput.#pollInterval);
- TaskOutput.#pollInterval = null;
- }
- }
- static #tick() {
- for (const [, entry] of TaskOutput.#activePolling) {
- if (!entry.#onProgress) {
- continue;
- }
- tailFile(entry.path, PROGRESS_TAIL_BYTES).then(({ content, bytesRead, bytesTotal }) => {
- if (!entry.#onProgress) {
- return;
- }
- if (!content) {
- entry.#onProgress("", "", entry.#totalLines, bytesTotal, false);
- return;
- }
- let pos = content.length;
- let n5 = 0;
- let n100 = 0;
- let lineCount = 0;
- while (pos > 0) {
- pos = content.lastIndexOf(`
-`, pos - 1);
- lineCount++;
- if (lineCount === 5)
- n5 = pos <= 0 ? 0 : pos + 1;
- if (lineCount === 100)
- n100 = pos <= 0 ? 0 : pos + 1;
- }
- const totalLines = bytesRead >= bytesTotal ? lineCount : Math.max(entry.#totalLines, Math.round(bytesTotal / bytesRead * lineCount));
- entry.#totalLines = totalLines;
- entry.#totalBytes = bytesTotal;
- entry.#onProgress(content.slice(n5), content.slice(n100), totalLines, bytesTotal, bytesRead < bytesTotal);
- }, () => {});
- }
- }
- writeStdout(data) {
- this.#writeBuffered(data, false);
- }
- writeStderr(data) {
- this.#writeBuffered(data, true);
- }
- #writeBuffered(data, isStderr) {
- this.#totalBytes += data.length;
- this.#updateProgress(data);
- if (this.#disk) {
- this.#disk.append(isStderr ? `[stderr] ${data}` : data);
- return;
- }
- const totalMem = this.#stdoutBuffer.length + this.#stderrBuffer.length + data.length;
- if (totalMem > this.#maxMemory) {
- this.#spillToDisk(isStderr ? data : null, isStderr ? null : data);
- return;
- }
- if (isStderr) {
- this.#stderrBuffer += data;
- } else {
- this.#stdoutBuffer += data;
- }
- }
- #updateProgress(data) {
- const MAX_PROGRESS_BYTES = 4096;
- const MAX_PROGRESS_LINES = 100;
- let lineCount = 0;
- const lines = [];
- let extractedBytes = 0;
- let pos = data.length;
- while (pos > 0) {
- const prev = data.lastIndexOf(`
-`, pos - 1);
- if (prev === -1) {
- break;
- }
- lineCount++;
- if (lines.length < MAX_PROGRESS_LINES && extractedBytes < MAX_PROGRESS_BYTES) {
- const lineLen = pos - prev - 1;
- if (lineLen > 0 && lineLen <= MAX_PROGRESS_BYTES - extractedBytes) {
- const line = data.slice(prev + 1, pos);
- if (line.trim()) {
- lines.push(Buffer.from(line).toString());
- extractedBytes += lineLen;
- }
- }
- }
- pos = prev;
- }
- this.#totalLines += lineCount;
- for (let i5 = lines.length - 1;i5 >= 0; i5--) {
- this.#recentLines.add(lines[i5]);
- }
- if (this.#onProgress && lines.length > 0) {
- const recent = this.#recentLines.getRecent(5);
- this.#onProgress(safeJoinLines(recent, `
-`), safeJoinLines(this.#recentLines.getRecent(100), `
-`), this.#totalLines, this.#totalBytes, this.#disk !== null);
- }
- }
- #spillToDisk(stderrChunk, stdoutChunk) {
- this.#disk = new DiskTaskOutput(this.taskId);
- if (this.#stdoutBuffer) {
- this.#disk.append(this.#stdoutBuffer);
- this.#stdoutBuffer = "";
- }
- if (this.#stderrBuffer) {
- this.#disk.append(`[stderr] ${this.#stderrBuffer}`);
- this.#stderrBuffer = "";
- }
- if (stdoutChunk) {
- this.#disk.append(stdoutChunk);
- }
- if (stderrChunk) {
- this.#disk.append(`[stderr] ${stderrChunk}`);
- }
- }
- async getStdout() {
- if (this.stdoutToFile) {
- return this.#readStdoutFromFile();
- }
- if (this.#disk) {
- const recent = this.#recentLines.getRecent(5);
- const tail = safeJoinLines(recent, `
-`);
- const sizeKB = Math.round(this.#totalBytes / 1024);
- const notice = `
-Output truncated (${sizeKB}KB total). Full output saved to: ${this.path}`;
- return tail ? tail + notice : notice.trimStart();
- }
- return this.#stdoutBuffer;
- }
- async#readStdoutFromFile() {
- const maxBytes = getMaxOutputLength();
- try {
- const result = await readFileRange(this.path, 0, maxBytes);
- if (!result) {
- this.#outputFileRedundant = true;
- return "";
- }
- const { content, bytesRead, bytesTotal } = result;
- this.#outputFileSize = bytesTotal;
- this.#outputFileRedundant = bytesTotal <= bytesRead;
- return content;
- } catch (err) {
- const code = err instanceof Error && "code" in err ? String(err.code) : "unknown";
- logForDebugging(`TaskOutput.#readStdoutFromFile: failed to read ${this.path} (${code}): ${err}`);
- return ``;
- }
- }
- getStderr() {
- if (this.#disk) {
- return "";
- }
- return this.#stderrBuffer;
- }
- get isOverflowed() {
- return this.#disk !== null;
- }
- get totalLines() {
- return this.#totalLines;
- }
- get totalBytes() {
- return this.#totalBytes;
- }
- get outputFileRedundant() {
- return this.#outputFileRedundant;
- }
- get outputFileSize() {
- return this.#outputFileSize;
- }
- spillToDisk() {
- if (!this.#disk) {
- this.#spillToDisk(null, null);
- }
- }
- async flush() {
- await this.#disk?.flush();
- }
- async deleteOutputFile() {
- try {
- await unlink4(this.path);
- } catch {}
- }
- clear() {
- this.#stdoutBuffer = "";
- this.#stderrBuffer = "";
- this.#recentLines.clear();
- this.#onProgress = null;
- this.#disk?.cancel();
- TaskOutput.stopPolling(this.taskId);
- TaskOutput.#registry.delete(this.taskId);
- }
- };
-});
-
-// src/utils/ShellCommand.ts
-import { stat as stat9 } from "fs/promises";
-function prependStderr(prefix, stderr) {
- return stderr ? `${prefix} ${stderr}` : prefix;
-}
-
-class StreamWrapper {
- #stream;
- #isCleanedUp = false;
- #taskOutput;
- #isStderr;
- #onData = this.#dataHandler.bind(this);
- constructor(stream10, taskOutput, isStderr) {
- this.#stream = stream10;
- this.#taskOutput = taskOutput;
- this.#isStderr = isStderr;
- stream10.setEncoding("utf-8");
- stream10.on("data", this.#onData);
- }
- #dataHandler(data) {
- const str = typeof data === "string" ? data : data.toString();
- if (this.#isStderr) {
- this.#taskOutput.writeStderr(str);
- } else {
- this.#taskOutput.writeStdout(str);
- }
- }
- cleanup() {
- if (this.#isCleanedUp) {
- return;
- }
- this.#isCleanedUp = true;
- this.#stream.removeListener("data", this.#onData);
- this.#stream = null;
- this.#taskOutput = null;
- this.#onData = () => {};
- }
-}
-
-class ShellCommandImpl {
- #status = "running";
- #backgroundTaskId;
- #stdoutWrapper;
- #stderrWrapper;
- #childProcess;
- #timeoutId = null;
- #sizeWatchdog = null;
- #killedForSize = false;
- #maxOutputBytes;
- #abortSignal;
- #onTimeoutCallback;
- #timeout;
- #shouldAutoBackground;
- #resultResolver = null;
- #exitCodeResolver = null;
- #boundAbortHandler = null;
- taskOutput;
- static #handleTimeout(self2) {
- if (self2.#shouldAutoBackground && self2.#onTimeoutCallback) {
- self2.#onTimeoutCallback(self2.background.bind(self2));
- } else {
- self2.#doKill(SIGTERM);
- }
- }
- result;
- onTimeout;
- constructor(childProcess3, abortSignal, timeout, taskOutput, shouldAutoBackground = false, maxOutputBytes = MAX_TASK_OUTPUT_BYTES) {
- this.#childProcess = childProcess3;
- this.#abortSignal = abortSignal;
- this.#timeout = timeout;
- this.#shouldAutoBackground = shouldAutoBackground;
- this.#maxOutputBytes = maxOutputBytes;
- this.taskOutput = taskOutput;
- this.#stderrWrapper = childProcess3.stderr ? new StreamWrapper(childProcess3.stderr, taskOutput, true) : null;
- this.#stdoutWrapper = childProcess3.stdout ? new StreamWrapper(childProcess3.stdout, taskOutput, false) : null;
- if (shouldAutoBackground) {
- this.onTimeout = (callback) => {
- this.#onTimeoutCallback = callback;
- };
- }
- this.result = this.#createResultPromise();
- }
- get status() {
- return this.#status;
- }
- #abortHandler() {
- if (this.#abortSignal.reason === "interrupt") {
- return;
- }
- this.kill();
- }
- #exitHandler(code, signal) {
- const exitCode = code !== null && code !== undefined ? code : signal === "SIGTERM" ? 144 : 1;
- this.#resolveExitCode(exitCode);
- }
- #errorHandler() {
- this.#resolveExitCode(1);
- }
- #resolveExitCode(code) {
- if (this.#exitCodeResolver) {
- this.#exitCodeResolver(code);
- this.#exitCodeResolver = null;
- }
- }
- #cleanupListeners() {
- this.#clearSizeWatchdog();
- const timeoutId = this.#timeoutId;
- if (timeoutId) {
- clearTimeout(timeoutId);
- this.#timeoutId = null;
- }
- const boundAbortHandler = this.#boundAbortHandler;
- if (boundAbortHandler) {
- this.#abortSignal.removeEventListener("abort", boundAbortHandler);
- this.#boundAbortHandler = null;
- }
- }
- #clearSizeWatchdog() {
- if (this.#sizeWatchdog) {
- clearInterval(this.#sizeWatchdog);
- this.#sizeWatchdog = null;
- }
- }
- #startSizeWatchdog() {
- this.#sizeWatchdog = setInterval(() => {
- stat9(this.taskOutput.path).then((s4) => {
- if (s4.size > this.#maxOutputBytes && this.#status === "backgrounded" && this.#sizeWatchdog !== null) {
- this.#killedForSize = true;
- this.#clearSizeWatchdog();
- this.#doKill(SIGKILL);
- }
- }, () => {});
- }, SIZE_WATCHDOG_INTERVAL_MS);
- this.#sizeWatchdog.unref();
- }
- #createResultPromise() {
- this.#boundAbortHandler = this.#abortHandler.bind(this);
- this.#abortSignal.addEventListener("abort", this.#boundAbortHandler, {
- once: true
- });
- this.#childProcess.once("exit", this.#exitHandler.bind(this));
- this.#childProcess.once("error", this.#errorHandler.bind(this));
- this.#timeoutId = setTimeout(ShellCommandImpl.#handleTimeout, this.#timeout, this);
- const exitPromise = new Promise((resolve10) => {
- this.#exitCodeResolver = resolve10;
- });
- return new Promise((resolve10) => {
- this.#resultResolver = resolve10;
- exitPromise.then(this.#handleExit.bind(this));
- });
- }
- async#handleExit(code) {
- this.#cleanupListeners();
- if (this.#status === "running" || this.#status === "backgrounded") {
- this.#status = "completed";
- }
- const stdout = await this.taskOutput.getStdout();
- const result = {
- code,
- stdout,
- stderr: this.taskOutput.getStderr(),
- interrupted: code === SIGKILL,
- backgroundTaskId: this.#backgroundTaskId
- };
- if (this.taskOutput.stdoutToFile && !this.#backgroundTaskId) {
- if (this.taskOutput.outputFileRedundant) {
- this.taskOutput.deleteOutputFile();
- } else {
- result.outputFilePath = this.taskOutput.path;
- result.outputFileSize = this.taskOutput.outputFileSize;
- result.outputTaskId = this.taskOutput.taskId;
- }
- }
- if (this.#killedForSize) {
- result.stderr = prependStderr(`Background command killed: output file exceeded ${MAX_TASK_OUTPUT_BYTES_DISPLAY}`, result.stderr);
- } else if (code === SIGTERM) {
- result.stderr = prependStderr(`Command timed out after ${formatDuration(this.#timeout)}`, result.stderr);
- }
- const resultResolver = this.#resultResolver;
- if (resultResolver) {
- this.#resultResolver = null;
- resultResolver(result);
- }
- }
- #doKill(code) {
- this.#status = "killed";
- if (this.#childProcess.pid) {
- import_tree_kill.default(this.#childProcess.pid, "SIGKILL");
- }
- this.#resolveExitCode(code ?? SIGKILL);
- }
- kill() {
- this.#doKill();
- }
- background(taskId) {
- if (this.#status === "running") {
- this.#backgroundTaskId = taskId;
- this.#status = "backgrounded";
- this.#cleanupListeners();
- if (this.taskOutput.stdoutToFile) {
- this.#startSizeWatchdog();
- } else {
- this.taskOutput.spillToDisk();
- }
- return true;
- }
- return false;
- }
- cleanup() {
- this.#stdoutWrapper?.cleanup();
- this.#stderrWrapper?.cleanup();
- this.taskOutput.clear();
- this.#cleanupListeners();
- this.#childProcess = null;
- this.#abortSignal = null;
- this.#onTimeoutCallback = undefined;
- }
-}
-function wrapSpawn(childProcess3, abortSignal, timeout, taskOutput, shouldAutoBackground = false, maxOutputBytes = MAX_TASK_OUTPUT_BYTES) {
- return new ShellCommandImpl(childProcess3, abortSignal, timeout, taskOutput, shouldAutoBackground, maxOutputBytes);
-}
-
-class AbortedShellCommand {
- status = "killed";
- result;
- taskOutput;
- constructor(opts) {
- this.taskOutput = new TaskOutput(generateTaskId("local_bash"), null);
- this.result = Promise.resolve({
- code: opts?.code ?? 145,
- stdout: "",
- stderr: opts?.stderr ?? "Command aborted before execution",
- interrupted: true,
- backgroundTaskId: opts?.backgroundTaskId
- });
- }
- background() {
- return false;
- }
- kill() {}
- cleanup() {}
-}
-function createAbortedCommand(backgroundTaskId, opts) {
- return new AbortedShellCommand({
- backgroundTaskId,
- ...opts
- });
-}
-function createFailedCommand(preSpawnError) {
- const taskOutput = new TaskOutput(generateTaskId("local_bash"), null);
- return {
- status: "completed",
- result: Promise.resolve({
- code: 1,
- stdout: "",
- stderr: preSpawnError,
- interrupted: false,
- preSpawnError
- }),
- taskOutput,
- background() {
- return false;
- },
- kill() {},
- cleanup() {}
- };
-}
-var import_tree_kill, SIGKILL = 137, SIGTERM = 143, SIZE_WATCHDOG_INTERVAL_MS = 5000;
-var init_ShellCommand = __esm(() => {
- init_Task();
- init_format();
- init_diskOutput();
- init_TaskOutput();
- import_tree_kill = __toESM(require_tree_kill(), 1);
-});
-
-// node_modules/shell-quote/quote.js
-var require_quote = __commonJS((exports, module) => {
- module.exports = function quote(xs) {
- return xs.map(function(s4) {
- if (s4 === "") {
- return "''";
- }
- if (s4 && typeof s4 === "object") {
- return s4.op.replace(/(.)/g, "\\$1");
- }
- if (/["\s\\]/.test(s4) && !/'/.test(s4)) {
- return "'" + s4.replace(/(['])/g, "\\$1") + "'";
- }
- if (/["'\s]/.test(s4)) {
- return '"' + s4.replace(/(["\\$`!])/g, "\\$1") + '"';
- }
- return String(s4).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, "$1\\$2");
- }).join(" ");
- };
-});
-
-// node_modules/shell-quote/parse.js
-var require_parse7 = __commonJS((exports, module) => {
- var CONTROL = "(?:" + [
- "\\|\\|",
- "\\&\\&",
- ";;",
- "\\|\\&",
- "\\<\\(",
- "\\<\\<\\<",
- ">>",
- ">\\&",
- "<\\&",
- "[&;()|<>]"
- ].join("|") + ")";
- var controlRE = new RegExp("^" + CONTROL + "$");
- var META = "|&;()<> \\t";
- var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
- var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
- var hash2 = /^#$/;
- var SQ = "'";
- var DQ = '"';
- var DS = "$";
- var TOKEN = "";
- var mult = 4294967296;
- for (i5 = 0;i5 < 4; i5++) {
- TOKEN += (mult * Math.random()).toString(16);
- }
- var i5;
- var startsWithToken = new RegExp("^" + TOKEN);
- function matchAll2(s4, r4) {
- var origIndex = r4.lastIndex;
- var matches = [];
- var matchObj;
- while (matchObj = r4.exec(s4)) {
- matches.push(matchObj);
- if (r4.lastIndex === matchObj.index) {
- r4.lastIndex += 1;
- }
- }
- r4.lastIndex = origIndex;
- return matches;
- }
- function getVar(env5, pre, key) {
- var r4 = typeof env5 === "function" ? env5(key) : env5[key];
- if (typeof r4 === "undefined" && key != "") {
- r4 = "";
- } else if (typeof r4 === "undefined") {
- r4 = "$";
- }
- if (typeof r4 === "object") {
- return pre + TOKEN + JSON.stringify(r4) + TOKEN;
- }
- return pre + r4;
- }
- function parseInternal(string4, env5, opts) {
- if (!opts) {
- opts = {};
- }
- var BS = opts.escape || "\\";
- var BAREWORD = "(\\" + BS + `['"` + META + `]|[^\\s'"` + META + "])+";
- var chunker = new RegExp([
- "(" + CONTROL + ")",
- "(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"
- ].join("|"), "g");
- var matches = matchAll2(string4, chunker);
- if (matches.length === 0) {
- return [];
- }
- if (!env5) {
- env5 = {};
- }
- var commented = false;
- return matches.map(function(match) {
- var s4 = match[0];
- if (!s4 || commented) {
- return;
- }
- if (controlRE.test(s4)) {
- return { op: s4 };
- }
- var quote = false;
- var esc2 = false;
- var out = "";
- var isGlob = false;
- var i6;
- function parseEnvVar() {
- i6 += 1;
- var varend;
- var varname;
- var char = s4.charAt(i6);
- if (char === "{") {
- i6 += 1;
- if (s4.charAt(i6) === "}") {
- throw new Error("Bad substitution: " + s4.slice(i6 - 2, i6 + 1));
- }
- varend = s4.indexOf("}", i6);
- if (varend < 0) {
- throw new Error("Bad substitution: " + s4.slice(i6));
- }
- varname = s4.slice(i6, varend);
- i6 = varend;
- } else if (/[*@#?$!_-]/.test(char)) {
- varname = char;
- i6 += 1;
- } else {
- var slicedFromI = s4.slice(i6);
- varend = slicedFromI.match(/[^\w\d_]/);
- if (!varend) {
- varname = slicedFromI;
- i6 = s4.length;
- } else {
- varname = slicedFromI.slice(0, varend.index);
- i6 += varend.index - 1;
- }
- }
- return getVar(env5, "", varname);
- }
- for (i6 = 0;i6 < s4.length; i6++) {
- var c8 = s4.charAt(i6);
- isGlob = isGlob || !quote && (c8 === "*" || c8 === "?");
- if (esc2) {
- out += c8;
- esc2 = false;
- } else if (quote) {
- if (c8 === quote) {
- quote = false;
- } else if (quote == SQ) {
- out += c8;
- } else {
- if (c8 === BS) {
- i6 += 1;
- c8 = s4.charAt(i6);
- if (c8 === DQ || c8 === BS || c8 === DS) {
- out += c8;
- } else {
- out += BS + c8;
- }
- } else if (c8 === DS) {
- out += parseEnvVar();
- } else {
- out += c8;
- }
- }
- } else if (c8 === DQ || c8 === SQ) {
- quote = c8;
- } else if (controlRE.test(c8)) {
- return { op: s4 };
- } else if (hash2.test(c8)) {
- commented = true;
- var commentObj = { comment: string4.slice(match.index + i6 + 1) };
- if (out.length) {
- return [out, commentObj];
- }
- return [commentObj];
- } else if (c8 === BS) {
- esc2 = true;
- } else if (c8 === DS) {
- out += parseEnvVar();
- } else {
- out += c8;
- }
- }
- if (isGlob) {
- return { op: "glob", pattern: out };
- }
- return out;
- }).reduce(function(prev, arg) {
- return typeof arg === "undefined" ? prev : prev.concat(arg);
- }, []);
- }
- module.exports = function parse10(s4, env5, opts) {
- var mapped = parseInternal(s4, env5, opts);
- if (typeof env5 !== "function") {
- return mapped;
- }
- return mapped.reduce(function(acc, s5) {
- if (typeof s5 === "object") {
- return acc.concat(s5);
- }
- var xs = s5.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
- if (xs.length === 1) {
- return acc.concat(xs[0]);
- }
- return acc.concat(xs.filter(Boolean).map(function(x3) {
- if (startsWithToken.test(x3)) {
- return JSON.parse(x3.split(TOKEN)[1]);
- }
- return x3;
- }));
- }, []);
- };
-});
-
-// node_modules/shell-quote/index.js
-var $quote, $parse;
-var init_shell_quote = __esm(() => {
- $quote = require_quote();
- $parse = require_parse7();
-});
-
-// src/utils/bash/shellQuote.ts
-function tryParseShellCommand(cmd, env5) {
- try {
- const tokens = typeof env5 === "function" ? $parse(cmd, env5) : $parse(cmd, env5);
- return { success: true, tokens };
- } catch (error46) {
- if (error46 instanceof Error) {
- logError2(error46);
- }
- return {
- success: false,
- error: error46 instanceof Error ? error46.message : "Unknown parse error"
- };
- }
-}
-function tryQuoteShellArgs(args) {
- try {
- const validated = args.map((arg, index2) => {
- if (arg === null || arg === undefined) {
- return String(arg);
- }
- const type = typeof arg;
- if (type === "string") {
- return arg;
- }
- if (type === "number" || type === "boolean") {
- return String(arg);
- }
- if (type === "object") {
- throw new Error(`Cannot quote argument at index ${index2}: object values are not supported`);
- }
- if (type === "symbol") {
- throw new Error(`Cannot quote argument at index ${index2}: symbol values are not supported`);
- }
- if (type === "function") {
- throw new Error(`Cannot quote argument at index ${index2}: function values are not supported`);
- }
- throw new Error(`Cannot quote argument at index ${index2}: unsupported type ${type}`);
- });
- const quoted = $quote(validated);
- return { success: true, quoted };
- } catch (error46) {
- if (error46 instanceof Error) {
- logError2(error46);
- }
- return {
- success: false,
- error: error46 instanceof Error ? error46.message : "Unknown quote error"
- };
- }
-}
-function hasMalformedTokens(command12, parsed) {
- let inSingle = false;
- let inDouble = false;
- let doubleCount = 0;
- let singleCount = 0;
- for (let i5 = 0;i5 < command12.length; i5++) {
- const c8 = command12[i5];
- if (c8 === "\\" && !inSingle) {
- i5++;
- continue;
- }
- if (c8 === '"' && !inSingle) {
- doubleCount++;
- inDouble = !inDouble;
- } else if (c8 === "'" && !inDouble) {
- singleCount++;
- inSingle = !inSingle;
- }
- }
- if (doubleCount % 2 !== 0 || singleCount % 2 !== 0)
- return true;
- for (const entry of parsed) {
- if (typeof entry !== "string")
- continue;
- const openBraces = (entry.match(/{/g) || []).length;
- const closeBraces = (entry.match(/}/g) || []).length;
- if (openBraces !== closeBraces)
- return true;
- const openParens = (entry.match(/\(/g) || []).length;
- const closeParens = (entry.match(/\)/g) || []).length;
- if (openParens !== closeParens)
- return true;
- const openBrackets = (entry.match(/\[/g) || []).length;
- const closeBrackets = (entry.match(/\]/g) || []).length;
- if (openBrackets !== closeBrackets)
- return true;
- const doubleQuotes = entry.match(/(?= 0 && command12[j4] === "\\") {
- backslashCount++;
- j4--;
- }
- if (backslashCount > 0 && backslashCount % 2 === 1) {
- return true;
- }
- if (backslashCount > 0 && backslashCount % 2 === 0 && command12.indexOf("'", i5 + 1) !== -1) {
- return true;
- }
- }
- continue;
- }
- }
- return false;
-}
-function quote(args) {
- const result = tryQuoteShellArgs([...args]);
- if (result.success) {
- return result.quoted;
- }
- try {
- const stringArgs = args.map((arg) => {
- if (arg === null || arg === undefined) {
- return String(arg);
- }
- const type = typeof arg;
- if (type === "string" || type === "number" || type === "boolean") {
- return String(arg);
- }
- return jsonStringify(arg);
- });
- return $quote(stringArgs);
- } catch (error46) {
- if (error46 instanceof Error) {
- logError2(error46);
- }
- throw new Error("Failed to quote shell arguments safely");
- }
-}
-var init_shellQuote = __esm(() => {
- init_shell_quote();
- init_log2();
- init_slowOperations();
-});
-
-// src/utils/bash/shellPrefix.ts
-function formatShellPrefixCommand(prefix, command12) {
- const spaceBeforeDash = prefix.lastIndexOf(" -");
- if (spaceBeforeDash > 0) {
- const execPath2 = prefix.substring(0, spaceBeforeDash);
- const args = prefix.substring(spaceBeforeDash + 1);
- return `${quote([execPath2])} ${args} ${quote([command12])}`;
- } else {
- return `${quote([prefix])} ${quote([command12])}`;
- }
-}
-var init_shellPrefix = __esm(() => {
- init_shellQuote();
-});
-
-// src/utils/sessionEnvironment.ts
-import { mkdir as mkdir8, readdir as readdir5, readFile as readFile12, writeFile as writeFile7 } from "fs/promises";
-import { join as join31 } from "path";
-async function getSessionEnvDirPath() {
- const sessionEnvDir = join31(getClaudeConfigHomeDir(), "session-env", getSessionId());
- await mkdir8(sessionEnvDir, { recursive: true });
- return sessionEnvDir;
-}
-async function getHookEnvFilePath(hookEvent, hookIndex) {
- const prefix = hookEvent.toLowerCase();
- return join31(await getSessionEnvDirPath(), `${prefix}-hook-${hookIndex}.sh`);
-}
-async function clearCwdEnvFiles() {
- try {
- const dir = await getSessionEnvDirPath();
- const files = await readdir5(dir);
- await Promise.all(files.filter((f4) => (f4.startsWith("filechanged-hook-") || f4.startsWith("cwdchanged-hook-")) && HOOK_ENV_REGEX.test(f4)).map((f4) => writeFile7(join31(dir, f4), "")));
- } catch (e4) {
- const code = getErrnoCode(e4);
- if (code !== "ENOENT") {
- logForDebugging(`Failed to clear cwd env files: ${errorMessage(e4)}`);
- }
- }
-}
-function invalidateSessionEnvCache() {
- logForDebugging("Invalidating session environment cache");
- sessionEnvScript = undefined;
-}
-async function getSessionEnvironmentScript() {
- if (getPlatform() === "windows") {
- logForDebugging("Session environment not yet supported on Windows");
- return null;
- }
- if (sessionEnvScript !== undefined) {
- return sessionEnvScript;
- }
- const scripts = [];
- const envFile = process.env.CLAUDE_ENV_FILE;
- if (envFile) {
- try {
- const envScript = (await readFile12(envFile, "utf8")).trim();
- if (envScript) {
- scripts.push(envScript);
- logForDebugging(`Session environment loaded from CLAUDE_ENV_FILE: ${envFile} (${envScript.length} chars)`);
- }
- } catch (e4) {
- const code = getErrnoCode(e4);
- if (code !== "ENOENT") {
- logForDebugging(`Failed to read CLAUDE_ENV_FILE: ${errorMessage(e4)}`);
- }
- }
- }
- const sessionEnvDir = await getSessionEnvDirPath();
- try {
- const files = await readdir5(sessionEnvDir);
- const hookFiles = files.filter((f4) => HOOK_ENV_REGEX.test(f4)).sort(sortHookEnvFiles);
- for (const file2 of hookFiles) {
- const filePath = join31(sessionEnvDir, file2);
- try {
- const content = (await readFile12(filePath, "utf8")).trim();
- if (content) {
- scripts.push(content);
- }
- } catch (e4) {
- const code = getErrnoCode(e4);
- if (code !== "ENOENT") {
- logForDebugging(`Failed to read hook file ${filePath}: ${errorMessage(e4)}`);
- }
- }
- }
- if (hookFiles.length > 0) {
- logForDebugging(`Session environment loaded from ${hookFiles.length} hook file(s)`);
- }
- } catch (e4) {
- const code = getErrnoCode(e4);
- if (code !== "ENOENT") {
- logForDebugging(`Failed to load session environment from hooks: ${errorMessage(e4)}`);
- }
- }
- if (scripts.length === 0) {
- logForDebugging("No session environment scripts found");
- sessionEnvScript = null;
- return sessionEnvScript;
- }
- sessionEnvScript = scripts.join(`
-`);
- logForDebugging(`Session environment script ready (${sessionEnvScript.length} chars total)`);
- return sessionEnvScript;
-}
-function sortHookEnvFiles(a5, b4) {
- const aMatch = a5.match(HOOK_ENV_REGEX);
- const bMatch = b4.match(HOOK_ENV_REGEX);
- const aType = aMatch?.[1] || "";
- const bType = bMatch?.[1] || "";
- if (aType !== bType) {
- return (HOOK_ENV_PRIORITY[aType] ?? 99) - (HOOK_ENV_PRIORITY[bType] ?? 99);
- }
- const aIndex = parseInt(aMatch?.[2] || "0", 10);
- const bIndex = parseInt(bMatch?.[2] || "0", 10);
- return aIndex - bIndex;
-}
-var sessionEnvScript = undefined, HOOK_ENV_PRIORITY, HOOK_ENV_REGEX;
-var init_sessionEnvironment = __esm(() => {
- init_state();
- init_debug();
- init_envUtils();
- init_errors();
- init_platform2();
- HOOK_ENV_PRIORITY = {
- setup: 0,
- sessionstart: 1,
- cwdchanged: 2,
- filechanged: 3
- };
- HOOK_ENV_REGEX = /^(setup|sessionstart|cwdchanged|filechanged)-hook-(\d+)\.sh$/;
-});
-
-// src/utils/subprocessEnv.ts
-var exports_subprocessEnv = {};
-__export(exports_subprocessEnv, {
- subprocessEnv: () => subprocessEnv,
- registerUpstreamProxyEnvFn: () => registerUpstreamProxyEnvFn
-});
-function registerUpstreamProxyEnvFn(fn) {
- _getUpstreamProxyEnv = fn;
-}
-function subprocessEnv() {
- const proxyEnv = _getUpstreamProxyEnv?.() ?? {};
- if (!isEnvTruthy(process.env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB)) {
- return Object.keys(proxyEnv).length > 0 ? { ...process.env, ...proxyEnv } : process.env;
- }
- const env5 = { ...process.env, ...proxyEnv };
- for (const k4 of GHA_SUBPROCESS_SCRUB) {
- delete env5[k4];
- delete env5[`INPUT_${k4}`];
- }
- return env5;
-}
-var GHA_SUBPROCESS_SCRUB, _getUpstreamProxyEnv;
-var init_subprocessEnv = __esm(() => {
- init_envUtils();
- GHA_SUBPROCESS_SCRUB = [
- "ANTHROPIC_API_KEY",
- "CLAUDE_CODE_OAUTH_TOKEN",
- "ANTHROPIC_AUTH_TOKEN",
- "ANTHROPIC_FOUNDRY_API_KEY",
- "ANTHROPIC_CUSTOM_HEADERS",
- "OTEL_EXPORTER_OTLP_HEADERS",
- "OTEL_EXPORTER_OTLP_LOGS_HEADERS",
- "OTEL_EXPORTER_OTLP_METRICS_HEADERS",
- "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
- "AWS_SECRET_ACCESS_KEY",
- "AWS_SESSION_TOKEN",
- "AWS_BEARER_TOKEN_BEDROCK",
- "GOOGLE_APPLICATION_CREDENTIALS",
- "AZURE_CLIENT_SECRET",
- "AZURE_CLIENT_CERTIFICATE_PATH",
- "ACTIONS_ID_TOKEN_REQUEST_TOKEN",
- "ACTIONS_ID_TOKEN_REQUEST_URL",
- "ACTIONS_RUNTIME_TOKEN",
- "ACTIONS_RUNTIME_URL",
- "ALL_INPUTS",
- "OVERRIDE_GITHUB_TOKEN",
- "DEFAULT_WORKFLOW_TOKEN",
- "SSH_SIGNING_KEY"
- ];
-});
-
-// src/utils/shell/powershellDetection.ts
-import { realpath as realpath4, stat as stat10 } from "fs/promises";
-async function probePath(p4) {
- try {
- return (await stat10(p4)).isFile() ? p4 : null;
- } catch {
- return null;
- }
-}
-async function findPowerShell() {
- const pwshPath = await which("pwsh");
- if (pwshPath) {
- if (getPlatform() === "linux") {
- const resolved = await realpath4(pwshPath).catch(() => pwshPath);
- if (pwshPath.startsWith("/snap/") || resolved.startsWith("/snap/")) {
- const direct = await probePath("/opt/microsoft/powershell/7/pwsh") ?? await probePath("/usr/bin/pwsh");
- if (direct) {
- const directResolved = await realpath4(direct).catch(() => direct);
- if (!direct.startsWith("/snap/") && !directResolved.startsWith("/snap/")) {
- return direct;
- }
- }
- }
- }
- return pwshPath;
- }
- const powershellPath = await which("powershell");
- if (powershellPath) {
- return powershellPath;
- }
- return null;
-}
-function getCachedPowerShellPath() {
- if (!cachedPowerShellPath) {
- cachedPowerShellPath = findPowerShell();
- }
- return cachedPowerShellPath;
-}
-async function getPowerShellEdition() {
- const p4 = await getCachedPowerShellPath();
- if (!p4)
- return null;
- const base2 = p4.split(/[/\\]/).pop().toLowerCase().replace(/\.exe$/, "");
- return base2 === "pwsh" ? "core" : "desktop";
-}
-var cachedPowerShellPath = null;
-var init_powershellDetection = __esm(() => {
- init_platform2();
- init_which();
-});
-
-// src/utils/sessionEnvVars.ts
-function getSessionEnvVars() {
- return sessionEnvVars;
-}
-function clearSessionEnvVars() {
- sessionEnvVars.clear();
-}
-var sessionEnvVars;
-var init_sessionEnvVars = __esm(() => {
- sessionEnvVars = new Map;
-});
-
-// src/utils/shell/powershellProvider.ts
-import { tmpdir as tmpdir2 } from "os";
-import { join as join32 } from "path";
-import { join as posixJoin } from "path/posix";
-function buildPowerShellArgs(cmd) {
- return ["-NoProfile", "-NonInteractive", "-Command", cmd];
-}
-function encodePowerShellCommand(psCommand) {
- return Buffer.from(psCommand, "utf16le").toString("base64");
-}
-function createPowerShellProvider(shellPath) {
- let currentSandboxTmpDir;
- return {
- type: "powershell",
- shellPath,
- detached: false,
- async buildExecCommand(command12, opts) {
- currentSandboxTmpDir = opts.useSandbox ? opts.sandboxTmpDir : undefined;
- const cwdFilePath = opts.useSandbox && opts.sandboxTmpDir ? posixJoin(opts.sandboxTmpDir, `claude-pwd-ps-${opts.id}`) : join32(tmpdir2(), `claude-pwd-ps-${opts.id}`);
- const escapedCwdFilePath = cwdFilePath.replace(/'/g, "''");
- const cwdTracking = `
-; $_ec = if ($null -ne $LASTEXITCODE) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }
-; (Get-Location).Path | Out-File -FilePath '${escapedCwdFilePath}' -Encoding utf8 -NoNewline
-; exit $_ec`;
- const psCommand = command12 + cwdTracking;
- const commandString = opts.useSandbox ? [
- `'${shellPath.replace(/'/g, `'\\''`)}'`,
- "-NoProfile",
- "-NonInteractive",
- "-EncodedCommand",
- encodePowerShellCommand(psCommand)
- ].join(" ") : psCommand;
- return { commandString, cwdFilePath };
- },
- getSpawnArgs(commandString) {
- return buildPowerShellArgs(commandString);
- },
- async getEnvironmentOverrides() {
- const env5 = {};
- for (const [key, value] of getSessionEnvVars()) {
- env5[key] = value;
- }
- if (currentSandboxTmpDir) {
- env5.TMPDIR = currentSandboxTmpDir;
- env5.CLAUDE_CODE_TMPDIR = currentSandboxTmpDir;
- }
- return env5;
- }
- };
-}
-var init_powershellProvider = __esm(() => {
- init_sessionEnvVars();
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/key.mjs
-var isUpKey = (key) => key.name === "up" || key.name === "k" || key.ctrl && key.name === "p", isDownKey = (key) => key.name === "down" || key.name === "j" || key.ctrl && key.name === "n", isBackspaceKey = (key) => key.name === "backspace", isNumberKey = (key) => "123456789".includes(key.name), isEnterKey = (key) => key.name === "enter" || key.name === "return";
-
-// node_modules/@inquirer/core/dist/esm/lib/errors.mjs
-var AbortPromptError, CancelPromptError, ExitPromptError, HookError, ValidationError;
-var init_errors8 = __esm(() => {
- AbortPromptError = class AbortPromptError extends Error {
- name = "AbortPromptError";
- message = "Prompt was aborted";
- constructor(options2) {
- super();
- this.cause = options2?.cause;
- }
- };
- CancelPromptError = class CancelPromptError extends Error {
- name = "CancelPromptError";
- message = "Prompt was canceled";
- };
- ExitPromptError = class ExitPromptError extends Error {
- name = "ExitPromptError";
- };
- HookError = class HookError extends Error {
- name = "HookError";
- };
- ValidationError = class ValidationError extends Error {
- name = "ValidationError";
- };
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs
-import { AsyncLocalStorage as AsyncLocalStorage5, AsyncResource } from "async_hooks";
-function createStore(rl) {
- const store = {
- rl,
- hooks: [],
- hooksCleanup: [],
- hooksEffect: [],
- index: 0,
- handleChange() {}
- };
- return store;
-}
-function withHooks(rl, cb) {
- const store = createStore(rl);
- return hookStorage.run(store, () => {
- function cycle(render2) {
- store.handleChange = () => {
- store.index = 0;
- render2();
- };
- store.handleChange();
- }
- return cb(cycle);
- });
-}
-function getStore() {
- const store = hookStorage.getStore();
- if (!store) {
- throw new HookError("[Inquirer] Hook functions can only be called from within a prompt");
- }
- return store;
-}
-function readline() {
- return getStore().rl;
-}
-function withUpdates(fn) {
- const wrapped = (...args) => {
- const store = getStore();
- let shouldUpdate = false;
- const oldHandleChange = store.handleChange;
- store.handleChange = () => {
- shouldUpdate = true;
- };
- const returnValue = fn(...args);
- if (shouldUpdate) {
- oldHandleChange();
- }
- store.handleChange = oldHandleChange;
- return returnValue;
- };
- return AsyncResource.bind(wrapped);
-}
-function withPointer(cb) {
- const store = getStore();
- const { index: index2 } = store;
- const pointer = {
- get() {
- return store.hooks[index2];
- },
- set(value) {
- store.hooks[index2] = value;
- },
- initialized: index2 in store.hooks
- };
- const returnValue = cb(pointer);
- store.index++;
- return returnValue;
-}
-function handleChange() {
- getStore().handleChange();
-}
-var hookStorage, effectScheduler;
-var init_hook_engine = __esm(() => {
- init_errors8();
- hookStorage = new AsyncLocalStorage5;
- effectScheduler = {
- queue(cb) {
- const store = getStore();
- const { index: index2 } = store;
- store.hooksEffect.push(() => {
- store.hooksCleanup[index2]?.();
- const cleanFn = cb(readline());
- if (cleanFn != null && typeof cleanFn !== "function") {
- throw new ValidationError("useEffect return value must be a cleanup function or nothing.");
- }
- store.hooksCleanup[index2] = cleanFn;
- });
- },
- run() {
- const store = getStore();
- withUpdates(() => {
- store.hooksEffect.forEach((effect) => {
- effect();
- });
- store.hooksEffect.length = 0;
- })();
- },
- clearAll() {
- const store = getStore();
- store.hooksCleanup.forEach((cleanFn) => {
- cleanFn?.();
- });
- store.hooksEffect.length = 0;
- store.hooksCleanup.length = 0;
- }
- };
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/use-state.mjs
-function useState8(defaultValue) {
- return withPointer((pointer) => {
- const setFn = (newValue) => {
- if (pointer.get() !== newValue) {
- pointer.set(newValue);
- handleChange();
- }
- };
- if (pointer.initialized) {
- return [pointer.get(), setFn];
- }
- const value = typeof defaultValue === "function" ? defaultValue() : defaultValue;
- pointer.set(value);
- return [value, setFn];
- });
-}
-var init_use_state = __esm(() => {
- init_hook_engine();
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs
-function useEffect10(cb, depArray) {
- withPointer((pointer) => {
- const oldDeps = pointer.get();
- const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i5) => !Object.is(dep, oldDeps[i5]));
- if (hasChanged) {
- effectScheduler.queue(cb);
- }
- pointer.set(depArray);
- });
-}
-var init_use_effect = __esm(() => {
- init_hook_engine();
-});
-
-// node_modules/yoctocolors-cjs/index.js
-var require_yoctocolors_cjs = __commonJS((exports, module) => {
- var tty4 = __require("tty");
- var hasColors2 = tty4?.WriteStream?.prototype?.hasColors?.() ?? false;
- var format4 = (open6, close) => {
- if (!hasColors2) {
- return (input) => input;
- }
- const openCode = `\x1B[${open6}m`;
- const closeCode = `\x1B[${close}m`;
- return (input) => {
- const string4 = input + "";
- let index2 = string4.indexOf(closeCode);
- if (index2 === -1) {
- return openCode + string4 + closeCode;
- }
- let result = openCode;
- let lastIndex = 0;
- const reopenOnNestedClose = close === 22;
- const replaceCode = (reopenOnNestedClose ? closeCode : "") + openCode;
- while (index2 !== -1) {
- result += string4.slice(lastIndex, index2) + replaceCode;
- lastIndex = index2 + closeCode.length;
- index2 = string4.indexOf(closeCode, lastIndex);
- }
- result += string4.slice(lastIndex) + closeCode;
- return result;
- };
- };
- var colors = {};
- colors.reset = format4(0, 0);
- colors.bold = format4(1, 22);
- colors.dim = format4(2, 22);
- colors.italic = format4(3, 23);
- colors.underline = format4(4, 24);
- colors.overline = format4(53, 55);
- colors.inverse = format4(7, 27);
- colors.hidden = format4(8, 28);
- colors.strikethrough = format4(9, 29);
- colors.black = format4(30, 39);
- colors.red = format4(31, 39);
- colors.green = format4(32, 39);
- colors.yellow = format4(33, 39);
- colors.blue = format4(34, 39);
- colors.magenta = format4(35, 39);
- colors.cyan = format4(36, 39);
- colors.white = format4(37, 39);
- colors.gray = format4(90, 39);
- colors.bgBlack = format4(40, 49);
- colors.bgRed = format4(41, 49);
- colors.bgGreen = format4(42, 49);
- colors.bgYellow = format4(43, 49);
- colors.bgBlue = format4(44, 49);
- colors.bgMagenta = format4(45, 49);
- colors.bgCyan = format4(46, 49);
- colors.bgWhite = format4(47, 49);
- colors.bgGray = format4(100, 49);
- colors.redBright = format4(91, 39);
- colors.greenBright = format4(92, 39);
- colors.yellowBright = format4(93, 39);
- colors.blueBright = format4(94, 39);
- colors.magentaBright = format4(95, 39);
- colors.cyanBright = format4(96, 39);
- colors.whiteBright = format4(97, 39);
- colors.bgRedBright = format4(101, 49);
- colors.bgGreenBright = format4(102, 49);
- colors.bgYellowBright = format4(103, 49);
- colors.bgBlueBright = format4(104, 49);
- colors.bgMagentaBright = format4(105, 49);
- colors.bgCyanBright = format4(106, 49);
- colors.bgWhiteBright = format4(107, 49);
- module.exports = colors;
-});
-
-// node_modules/@inquirer/figures/dist/esm/index.js
-import process20 from "process";
-function isUnicodeSupported2() {
- if (process20.platform !== "win32") {
- return process20.env["TERM"] !== "linux";
- }
- return Boolean(process20.env["WT_SESSION"]) || Boolean(process20.env["TERMINUS_SUBLIME"]) || process20.env["ConEmuTask"] === "{cmd::Cmder}" || process20.env["TERM_PROGRAM"] === "Terminus-Sublime" || process20.env["TERM_PROGRAM"] === "vscode" || process20.env["TERM"] === "xterm-256color" || process20.env["TERM"] === "alacritty" || process20.env["TERMINAL_EMULATOR"] === "JetBrains-JediTerm";
-}
-var common2, specialMainSymbols2, specialFallbackSymbols2, mainSymbols2, fallbackSymbols2, shouldUseMain2, figures2, esm_default, replacements2;
-var init_esm12 = __esm(() => {
- common2 = {
- circleQuestionMark: "(?)",
- questionMarkPrefix: "(?)",
- square: "\u2588",
- squareDarkShade: "\u2593",
- squareMediumShade: "\u2592",
- squareLightShade: "\u2591",
- squareTop: "\u2580",
- squareBottom: "\u2584",
- squareLeft: "\u258C",
- squareRight: "\u2590",
- squareCenter: "\u25A0",
- bullet: "\u25CF",
- dot: "\u2024",
- ellipsis: "\u2026",
- pointerSmall: "\u203A",
- triangleUp: "\u25B2",
- triangleUpSmall: "\u25B4",
- triangleDown: "\u25BC",
- triangleDownSmall: "\u25BE",
- triangleLeftSmall: "\u25C2",
- triangleRightSmall: "\u25B8",
- home: "\u2302",
- heart: "\u2665",
- musicNote: "\u266A",
- musicNoteBeamed: "\u266B",
- arrowUp: "\u2191",
- arrowDown: "\u2193",
- arrowLeft: "\u2190",
- arrowRight: "\u2192",
- arrowLeftRight: "\u2194",
- arrowUpDown: "\u2195",
- almostEqual: "\u2248",
- notEqual: "\u2260",
- lessOrEqual: "\u2264",
- greaterOrEqual: "\u2265",
- identical: "\u2261",
- infinity: "\u221E",
- subscriptZero: "\u2080",
- subscriptOne: "\u2081",
- subscriptTwo: "\u2082",
- subscriptThree: "\u2083",
- subscriptFour: "\u2084",
- subscriptFive: "\u2085",
- subscriptSix: "\u2086",
- subscriptSeven: "\u2087",
- subscriptEight: "\u2088",
- subscriptNine: "\u2089",
- oneHalf: "\xBD",
- oneThird: "\u2153",
- oneQuarter: "\xBC",
- oneFifth: "\u2155",
- oneSixth: "\u2159",
- oneEighth: "\u215B",
- twoThirds: "\u2154",
- twoFifths: "\u2156",
- threeQuarters: "\xBE",
- threeFifths: "\u2157",
- threeEighths: "\u215C",
- fourFifths: "\u2158",
- fiveSixths: "\u215A",
- fiveEighths: "\u215D",
- sevenEighths: "\u215E",
- line: "\u2500",
- lineBold: "\u2501",
- lineDouble: "\u2550",
- lineDashed0: "\u2504",
- lineDashed1: "\u2505",
- lineDashed2: "\u2508",
- lineDashed3: "\u2509",
- lineDashed4: "\u254C",
- lineDashed5: "\u254D",
- lineDashed6: "\u2574",
- lineDashed7: "\u2576",
- lineDashed8: "\u2578",
- lineDashed9: "\u257A",
- lineDashed10: "\u257C",
- lineDashed11: "\u257E",
- lineDashed12: "\u2212",
- lineDashed13: "\u2013",
- lineDashed14: "\u2010",
- lineDashed15: "\u2043",
- lineVertical: "\u2502",
- lineVerticalBold: "\u2503",
- lineVerticalDouble: "\u2551",
- lineVerticalDashed0: "\u2506",
- lineVerticalDashed1: "\u2507",
- lineVerticalDashed2: "\u250A",
- lineVerticalDashed3: "\u250B",
- lineVerticalDashed4: "\u254E",
- lineVerticalDashed5: "\u254F",
- lineVerticalDashed6: "\u2575",
- lineVerticalDashed7: "\u2577",
- lineVerticalDashed8: "\u2579",
- lineVerticalDashed9: "\u257B",
- lineVerticalDashed10: "\u257D",
- lineVerticalDashed11: "\u257F",
- lineDownLeft: "\u2510",
- lineDownLeftArc: "\u256E",
- lineDownBoldLeftBold: "\u2513",
- lineDownBoldLeft: "\u2512",
- lineDownLeftBold: "\u2511",
- lineDownDoubleLeftDouble: "\u2557",
- lineDownDoubleLeft: "\u2556",
- lineDownLeftDouble: "\u2555",
- lineDownRight: "\u250C",
- lineDownRightArc: "\u256D",
- lineDownBoldRightBold: "\u250F",
- lineDownBoldRight: "\u250E",
- lineDownRightBold: "\u250D",
- lineDownDoubleRightDouble: "\u2554",
- lineDownDoubleRight: "\u2553",
- lineDownRightDouble: "\u2552",
- lineUpLeft: "\u2518",
- lineUpLeftArc: "\u256F",
- lineUpBoldLeftBold: "\u251B",
- lineUpBoldLeft: "\u251A",
- lineUpLeftBold: "\u2519",
- lineUpDoubleLeftDouble: "\u255D",
- lineUpDoubleLeft: "\u255C",
- lineUpLeftDouble: "\u255B",
- lineUpRight: "\u2514",
- lineUpRightArc: "\u2570",
- lineUpBoldRightBold: "\u2517",
- lineUpBoldRight: "\u2516",
- lineUpRightBold: "\u2515",
- lineUpDoubleRightDouble: "\u255A",
- lineUpDoubleRight: "\u2559",
- lineUpRightDouble: "\u2558",
- lineUpDownLeft: "\u2524",
- lineUpBoldDownBoldLeftBold: "\u252B",
- lineUpBoldDownBoldLeft: "\u2528",
- lineUpDownLeftBold: "\u2525",
- lineUpBoldDownLeftBold: "\u2529",
- lineUpDownBoldLeftBold: "\u252A",
- lineUpDownBoldLeft: "\u2527",
- lineUpBoldDownLeft: "\u2526",
- lineUpDoubleDownDoubleLeftDouble: "\u2563",
- lineUpDoubleDownDoubleLeft: "\u2562",
- lineUpDownLeftDouble: "\u2561",
- lineUpDownRight: "\u251C",
- lineUpBoldDownBoldRightBold: "\u2523",
- lineUpBoldDownBoldRight: "\u2520",
- lineUpDownRightBold: "\u251D",
- lineUpBoldDownRightBold: "\u2521",
- lineUpDownBoldRightBold: "\u2522",
- lineUpDownBoldRight: "\u251F",
- lineUpBoldDownRight: "\u251E",
- lineUpDoubleDownDoubleRightDouble: "\u2560",
- lineUpDoubleDownDoubleRight: "\u255F",
- lineUpDownRightDouble: "\u255E",
- lineDownLeftRight: "\u252C",
- lineDownBoldLeftBoldRightBold: "\u2533",
- lineDownLeftBoldRightBold: "\u252F",
- lineDownBoldLeftRight: "\u2530",
- lineDownBoldLeftBoldRight: "\u2531",
- lineDownBoldLeftRightBold: "\u2532",
- lineDownLeftRightBold: "\u252E",
- lineDownLeftBoldRight: "\u252D",
- lineDownDoubleLeftDoubleRightDouble: "\u2566",
- lineDownDoubleLeftRight: "\u2565",
- lineDownLeftDoubleRightDouble: "\u2564",
- lineUpLeftRight: "\u2534",
- lineUpBoldLeftBoldRightBold: "\u253B",
- lineUpLeftBoldRightBold: "\u2537",
- lineUpBoldLeftRight: "\u2538",
- lineUpBoldLeftBoldRight: "\u2539",
- lineUpBoldLeftRightBold: "\u253A",
- lineUpLeftRightBold: "\u2536",
- lineUpLeftBoldRight: "\u2535",
- lineUpDoubleLeftDoubleRightDouble: "\u2569",
- lineUpDoubleLeftRight: "\u2568",
- lineUpLeftDoubleRightDouble: "\u2567",
- lineUpDownLeftRight: "\u253C",
- lineUpBoldDownBoldLeftBoldRightBold: "\u254B",
- lineUpDownBoldLeftBoldRightBold: "\u2548",
- lineUpBoldDownLeftBoldRightBold: "\u2547",
- lineUpBoldDownBoldLeftRightBold: "\u254A",
- lineUpBoldDownBoldLeftBoldRight: "\u2549",
- lineUpBoldDownLeftRight: "\u2540",
- lineUpDownBoldLeftRight: "\u2541",
- lineUpDownLeftBoldRight: "\u253D",
- lineUpDownLeftRightBold: "\u253E",
- lineUpBoldDownBoldLeftRight: "\u2542",
- lineUpDownLeftBoldRightBold: "\u253F",
- lineUpBoldDownLeftBoldRight: "\u2543",
- lineUpBoldDownLeftRightBold: "\u2544",
- lineUpDownBoldLeftBoldRight: "\u2545",
- lineUpDownBoldLeftRightBold: "\u2546",
- lineUpDoubleDownDoubleLeftDoubleRightDouble: "\u256C",
- lineUpDoubleDownDoubleLeftRight: "\u256B",
- lineUpDownLeftDoubleRightDouble: "\u256A",
- lineCross: "\u2573",
- lineBackslash: "\u2572",
- lineSlash: "\u2571"
- };
- specialMainSymbols2 = {
- tick: "\u2714",
- info: "\u2139",
- warning: "\u26A0",
- cross: "\u2718",
- squareSmall: "\u25FB",
- squareSmallFilled: "\u25FC",
- circle: "\u25EF",
- circleFilled: "\u25C9",
- circleDotted: "\u25CC",
- circleDouble: "\u25CE",
- circleCircle: "\u24DE",
- circleCross: "\u24E7",
- circlePipe: "\u24BE",
- radioOn: "\u25C9",
- radioOff: "\u25EF",
- checkboxOn: "\u2612",
- checkboxOff: "\u2610",
- checkboxCircleOn: "\u24E7",
- checkboxCircleOff: "\u24BE",
- pointer: "\u276F",
- triangleUpOutline: "\u25B3",
- triangleLeft: "\u25C0",
- triangleRight: "\u25B6",
- lozenge: "\u25C6",
- lozengeOutline: "\u25C7",
- hamburger: "\u2630",
- smiley: "\u32E1",
- mustache: "\u0DF4",
- star: "\u2605",
- play: "\u25B6",
- nodejs: "\u2B22",
- oneSeventh: "\u2150",
- oneNinth: "\u2151",
- oneTenth: "\u2152"
- };
- specialFallbackSymbols2 = {
- tick: "\u221A",
- info: "i",
- warning: "\u203C",
- cross: "\xD7",
- squareSmall: "\u25A1",
- squareSmallFilled: "\u25A0",
- circle: "( )",
- circleFilled: "(*)",
- circleDotted: "( )",
- circleDouble: "( )",
- circleCircle: "(\u25CB)",
- circleCross: "(\xD7)",
- circlePipe: "(\u2502)",
- radioOn: "(*)",
- radioOff: "( )",
- checkboxOn: "[\xD7]",
- checkboxOff: "[ ]",
- checkboxCircleOn: "(\xD7)",
- checkboxCircleOff: "( )",
- pointer: ">",
- triangleUpOutline: "\u2206",
- triangleLeft: "\u25C4",
- triangleRight: "\u25BA",
- lozenge: "\u2666",
- lozengeOutline: "\u25CA",
- hamburger: "\u2261",
- smiley: "\u263A",
- mustache: "\u250C\u2500\u2510",
- star: "\u2736",
- play: "\u25BA",
- nodejs: "\u2666",
- oneSeventh: "1/7",
- oneNinth: "1/9",
- oneTenth: "1/10"
- };
- mainSymbols2 = {
- ...common2,
- ...specialMainSymbols2
- };
- fallbackSymbols2 = {
- ...common2,
- ...specialFallbackSymbols2
- };
- shouldUseMain2 = isUnicodeSupported2();
- figures2 = shouldUseMain2 ? mainSymbols2 : fallbackSymbols2;
- esm_default = figures2;
- replacements2 = Object.entries(specialMainSymbols2);
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/theme.mjs
-var import_yoctocolors_cjs, defaultTheme;
-var init_theme2 = __esm(() => {
- init_esm12();
- import_yoctocolors_cjs = __toESM(require_yoctocolors_cjs(), 1);
- defaultTheme = {
- prefix: {
- idle: import_yoctocolors_cjs.default.blue("?"),
- done: import_yoctocolors_cjs.default.green(esm_default.tick)
- },
- spinner: {
- interval: 80,
- frames: ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"].map((frame) => import_yoctocolors_cjs.default.yellow(frame))
- },
- style: {
- answer: import_yoctocolors_cjs.default.cyan,
- message: import_yoctocolors_cjs.default.bold,
- error: (text) => import_yoctocolors_cjs.default.red(`> ${text}`),
- defaultAnswer: (text) => import_yoctocolors_cjs.default.dim(`(${text})`),
- help: import_yoctocolors_cjs.default.dim,
- highlight: import_yoctocolors_cjs.default.cyan,
- key: (text) => import_yoctocolors_cjs.default.cyan(import_yoctocolors_cjs.default.bold(`<${text}>`))
- }
- };
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs
-function isPlainObject5(value) {
- if (typeof value !== "object" || value === null)
- return false;
- let proto2 = value;
- while (Object.getPrototypeOf(proto2) !== null) {
- proto2 = Object.getPrototypeOf(proto2);
- }
- return Object.getPrototypeOf(value) === proto2;
-}
-function deepMerge(...objects) {
- const output = {};
- for (const obj of objects) {
- for (const [key, value] of Object.entries(obj)) {
- const prevValue = output[key];
- output[key] = isPlainObject5(prevValue) && isPlainObject5(value) ? deepMerge(prevValue, value) : value;
- }
- }
- return output;
-}
-function makeTheme(...themes) {
- const themesToMerge = [
- defaultTheme,
- ...themes.filter((theme) => theme != null)
- ];
- return deepMerge(...themesToMerge);
-}
-var init_make_theme = __esm(() => {
- init_theme2();
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs
-import { AsyncResource as AsyncResource2 } from "async_hooks";
-function usePrefix({ status = "idle", theme }) {
- const [showLoader, setShowLoader] = useState8(false);
- const [tick, setTick] = useState8(0);
- const { prefix, spinner } = makeTheme(theme);
- useEffect10(() => {
- if (status === "loading") {
- let tickInterval;
- let inc = -1;
- const delayTimeout = setTimeout(AsyncResource2.bind(() => {
- setShowLoader(true);
- tickInterval = setInterval(AsyncResource2.bind(() => {
- inc = inc + 1;
- setTick(inc % spinner.frames.length);
- }), spinner.interval);
- }), 300);
- return () => {
- clearTimeout(delayTimeout);
- clearInterval(tickInterval);
- };
- } else {
- setShowLoader(false);
- }
- }, [status]);
- if (showLoader) {
- return spinner.frames[tick];
- }
- const iconName = status === "loading" ? "idle" : status;
- return typeof prefix === "string" ? prefix : prefix[iconName];
-}
-var init_use_prefix = __esm(() => {
- init_use_state();
- init_use_effect();
- init_make_theme();
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs
-function useMemo6(fn, dependencies) {
- return withPointer((pointer) => {
- const prev = pointer.get();
- if (!prev || prev.dependencies.length !== dependencies.length || prev.dependencies.some((dep, i5) => dep !== dependencies[i5])) {
- const value = fn();
- pointer.set({ value, dependencies });
- return value;
- }
- return prev.value;
- });
-}
-var init_use_memo = __esm(() => {
- init_hook_engine();
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs
-function useRef7(val) {
- return useState8({ current: val })[0];
-}
-var init_use_ref = __esm(() => {
- init_use_state();
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs
-function useKeypress(userHandler) {
- const signal = useRef7(userHandler);
- signal.current = userHandler;
- useEffect10((rl) => {
- let ignore = false;
- const handler = withUpdates((_input, event) => {
- if (ignore)
- return;
- signal.current(event, rl);
- });
- rl.input.on("keypress", handler);
- return () => {
- ignore = true;
- rl.input.removeListener("keypress", handler);
- };
- }, []);
-}
-var init_use_keypress = __esm(() => {
- init_use_ref();
- init_use_effect();
- init_hook_engine();
-});
-
-// node_modules/cli-width/index.js
-var require_cli_width = __commonJS((exports, module) => {
- module.exports = cliWidth;
- function normalizeOpts(options2) {
- const defaultOpts = {
- defaultWidth: 0,
- output: process.stdout,
- tty: __require("tty")
- };
- if (!options2) {
- return defaultOpts;
- }
- Object.keys(defaultOpts).forEach(function(key) {
- if (!options2[key]) {
- options2[key] = defaultOpts[key];
- }
- });
- return options2;
- }
- function cliWidth(options2) {
- const opts = normalizeOpts(options2);
- if (opts.output.getWindowSize) {
- return opts.output.getWindowSize()[0] || opts.defaultWidth;
- }
- if (opts.tty.getWindowSize) {
- return opts.tty.getWindowSize()[1] || opts.defaultWidth;
- }
- if (opts.output.columns) {
- return opts.output.columns;
- }
- if (process.env.CLI_WIDTH) {
- const width = parseInt(process.env.CLI_WIDTH, 10);
- if (!isNaN(width) && width !== 0) {
- return width;
- }
- }
- return opts.defaultWidth;
- }
-});
-
-// node_modules/@inquirer/core/node_modules/strip-ansi/node_modules/ansi-regex/index.js
-var require_ansi_regex = __commonJS((exports, module) => {
- module.exports = ({ onlyFirst = false } = {}) => {
- const pattern = [
- "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
- "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"
- ].join("|");
- return new RegExp(pattern, onlyFirst ? undefined : "g");
- };
-});
-
-// node_modules/@inquirer/core/node_modules/strip-ansi/index.js
-var require_strip_ansi = __commonJS((exports, module) => {
- var ansiRegex2 = require_ansi_regex();
- module.exports = (string4) => typeof string4 === "string" ? string4.replace(ansiRegex2(), "") : string4;
-});
-
-// node_modules/@inquirer/core/node_modules/wrap-ansi/node_modules/string-width/node_modules/is-fullwidth-code-point/index.js
-var require_is_fullwidth_code_point = __commonJS((exports, module) => {
- var isFullwidthCodePoint2 = (codePoint) => {
- if (Number.isNaN(codePoint)) {
- return false;
- }
- if (codePoint >= 4352 && (codePoint <= 4447 || codePoint === 9001 || codePoint === 9002 || 11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || 12880 <= codePoint && codePoint <= 19903 || 19968 <= codePoint && codePoint <= 42182 || 43360 <= codePoint && codePoint <= 43388 || 44032 <= codePoint && codePoint <= 55203 || 63744 <= codePoint && codePoint <= 64255 || 65040 <= codePoint && codePoint <= 65049 || 65072 <= codePoint && codePoint <= 65131 || 65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || 110592 <= codePoint && codePoint <= 110593 || 127488 <= codePoint && codePoint <= 127569 || 131072 <= codePoint && codePoint <= 262141)) {
- return true;
- }
- return false;
- };
- module.exports = isFullwidthCodePoint2;
- module.exports.default = isFullwidthCodePoint2;
-});
-
-// node_modules/@inquirer/core/node_modules/wrap-ansi/node_modules/string-width/node_modules/emoji-regex/index.js
-var require_emoji_regex = __commonJS((exports, module) => {
- module.exports = function() {
- return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
- };
-});
-
-// node_modules/@inquirer/core/node_modules/wrap-ansi/node_modules/string-width/index.js
-var require_string_width = __commonJS((exports, module) => {
- var stripAnsi2 = require_strip_ansi();
- var isFullwidthCodePoint2 = require_is_fullwidth_code_point();
- var emojiRegex = require_emoji_regex();
- var stringWidth3 = (string4) => {
- if (typeof string4 !== "string" || string4.length === 0) {
- return 0;
- }
- string4 = stripAnsi2(string4);
- if (string4.length === 0) {
- return 0;
- }
- string4 = string4.replace(emojiRegex(), " ");
- let width = 0;
- for (let i5 = 0;i5 < string4.length; i5++) {
- const code = string4.codePointAt(i5);
- if (code <= 31 || code >= 127 && code <= 159) {
- continue;
- }
- if (code >= 768 && code <= 879) {
- continue;
- }
- if (code > 65535) {
- i5++;
- }
- width += isFullwidthCodePoint2(code) ? 2 : 1;
- }
- return width;
- };
- module.exports = stringWidth3;
- module.exports.default = stringWidth3;
-});
-
-// node_modules/color-name/index.js
-var require_color_name = __commonJS((exports, module) => {
- module.exports = {
- aliceblue: [240, 248, 255],
- antiquewhite: [250, 235, 215],
- aqua: [0, 255, 255],
- aquamarine: [127, 255, 212],
- azure: [240, 255, 255],
- beige: [245, 245, 220],
- bisque: [255, 228, 196],
- black: [0, 0, 0],
- blanchedalmond: [255, 235, 205],
- blue: [0, 0, 255],
- blueviolet: [138, 43, 226],
- brown: [165, 42, 42],
- burlywood: [222, 184, 135],
- cadetblue: [95, 158, 160],
- chartreuse: [127, 255, 0],
- chocolate: [210, 105, 30],
- coral: [255, 127, 80],
- cornflowerblue: [100, 149, 237],
- cornsilk: [255, 248, 220],
- crimson: [220, 20, 60],
- cyan: [0, 255, 255],
- darkblue: [0, 0, 139],
- darkcyan: [0, 139, 139],
- darkgoldenrod: [184, 134, 11],
- darkgray: [169, 169, 169],
- darkgreen: [0, 100, 0],
- darkgrey: [169, 169, 169],
- darkkhaki: [189, 183, 107],
- darkmagenta: [139, 0, 139],
- darkolivegreen: [85, 107, 47],
- darkorange: [255, 140, 0],
- darkorchid: [153, 50, 204],
- darkred: [139, 0, 0],
- darksalmon: [233, 150, 122],
- darkseagreen: [143, 188, 143],
- darkslateblue: [72, 61, 139],
- darkslategray: [47, 79, 79],
- darkslategrey: [47, 79, 79],
- darkturquoise: [0, 206, 209],
- darkviolet: [148, 0, 211],
- deeppink: [255, 20, 147],
- deepskyblue: [0, 191, 255],
- dimgray: [105, 105, 105],
- dimgrey: [105, 105, 105],
- dodgerblue: [30, 144, 255],
- firebrick: [178, 34, 34],
- floralwhite: [255, 250, 240],
- forestgreen: [34, 139, 34],
- fuchsia: [255, 0, 255],
- gainsboro: [220, 220, 220],
- ghostwhite: [248, 248, 255],
- gold: [255, 215, 0],
- goldenrod: [218, 165, 32],
- gray: [128, 128, 128],
- green: [0, 128, 0],
- greenyellow: [173, 255, 47],
- grey: [128, 128, 128],
- honeydew: [240, 255, 240],
- hotpink: [255, 105, 180],
- indianred: [205, 92, 92],
- indigo: [75, 0, 130],
- ivory: [255, 255, 240],
- khaki: [240, 230, 140],
- lavender: [230, 230, 250],
- lavenderblush: [255, 240, 245],
- lawngreen: [124, 252, 0],
- lemonchiffon: [255, 250, 205],
- lightblue: [173, 216, 230],
- lightcoral: [240, 128, 128],
- lightcyan: [224, 255, 255],
- lightgoldenrodyellow: [250, 250, 210],
- lightgray: [211, 211, 211],
- lightgreen: [144, 238, 144],
- lightgrey: [211, 211, 211],
- lightpink: [255, 182, 193],
- lightsalmon: [255, 160, 122],
- lightseagreen: [32, 178, 170],
- lightskyblue: [135, 206, 250],
- lightslategray: [119, 136, 153],
- lightslategrey: [119, 136, 153],
- lightsteelblue: [176, 196, 222],
- lightyellow: [255, 255, 224],
- lime: [0, 255, 0],
- limegreen: [50, 205, 50],
- linen: [250, 240, 230],
- magenta: [255, 0, 255],
- maroon: [128, 0, 0],
- mediumaquamarine: [102, 205, 170],
- mediumblue: [0, 0, 205],
- mediumorchid: [186, 85, 211],
- mediumpurple: [147, 112, 219],
- mediumseagreen: [60, 179, 113],
- mediumslateblue: [123, 104, 238],
- mediumspringgreen: [0, 250, 154],
- mediumturquoise: [72, 209, 204],
- mediumvioletred: [199, 21, 133],
- midnightblue: [25, 25, 112],
- mintcream: [245, 255, 250],
- mistyrose: [255, 228, 225],
- moccasin: [255, 228, 181],
- navajowhite: [255, 222, 173],
- navy: [0, 0, 128],
- oldlace: [253, 245, 230],
- olive: [128, 128, 0],
- olivedrab: [107, 142, 35],
- orange: [255, 165, 0],
- orangered: [255, 69, 0],
- orchid: [218, 112, 214],
- palegoldenrod: [238, 232, 170],
- palegreen: [152, 251, 152],
- paleturquoise: [175, 238, 238],
- palevioletred: [219, 112, 147],
- papayawhip: [255, 239, 213],
- peachpuff: [255, 218, 185],
- peru: [205, 133, 63],
- pink: [255, 192, 203],
- plum: [221, 160, 221],
- powderblue: [176, 224, 230],
- purple: [128, 0, 128],
- rebeccapurple: [102, 51, 153],
- red: [255, 0, 0],
- rosybrown: [188, 143, 143],
- royalblue: [65, 105, 225],
- saddlebrown: [139, 69, 19],
- salmon: [250, 128, 114],
- sandybrown: [244, 164, 96],
- seagreen: [46, 139, 87],
- seashell: [255, 245, 238],
- sienna: [160, 82, 45],
- silver: [192, 192, 192],
- skyblue: [135, 206, 235],
- slateblue: [106, 90, 205],
- slategray: [112, 128, 144],
- slategrey: [112, 128, 144],
- snow: [255, 250, 250],
- springgreen: [0, 255, 127],
- steelblue: [70, 130, 180],
- tan: [210, 180, 140],
- teal: [0, 128, 128],
- thistle: [216, 191, 216],
- tomato: [255, 99, 71],
- turquoise: [64, 224, 208],
- violet: [238, 130, 238],
- wheat: [245, 222, 179],
- white: [255, 255, 255],
- whitesmoke: [245, 245, 245],
- yellow: [255, 255, 0],
- yellowgreen: [154, 205, 50]
- };
-});
-
-// node_modules/color-convert/conversions.js
-var require_conversions = __commonJS((exports, module) => {
- var cssKeywords = require_color_name();
- var reverseKeywords = {};
- for (const key of Object.keys(cssKeywords)) {
- reverseKeywords[cssKeywords[key]] = key;
- }
- var convert = {
- rgb: { channels: 3, labels: "rgb" },
- hsl: { channels: 3, labels: "hsl" },
- hsv: { channels: 3, labels: "hsv" },
- hwb: { channels: 3, labels: "hwb" },
- cmyk: { channels: 4, labels: "cmyk" },
- xyz: { channels: 3, labels: "xyz" },
- lab: { channels: 3, labels: "lab" },
- lch: { channels: 3, labels: "lch" },
- hex: { channels: 1, labels: ["hex"] },
- keyword: { channels: 1, labels: ["keyword"] },
- ansi16: { channels: 1, labels: ["ansi16"] },
- ansi256: { channels: 1, labels: ["ansi256"] },
- hcg: { channels: 3, labels: ["h", "c", "g"] },
- apple: { channels: 3, labels: ["r16", "g16", "b16"] },
- gray: { channels: 1, labels: ["gray"] }
- };
- module.exports = convert;
- for (const model of Object.keys(convert)) {
- if (!("channels" in convert[model])) {
- throw new Error("missing channels property: " + model);
- }
- if (!("labels" in convert[model])) {
- throw new Error("missing channel labels property: " + model);
- }
- if (convert[model].labels.length !== convert[model].channels) {
- throw new Error("channel and label counts mismatch: " + model);
- }
- const { channels, labels } = convert[model];
- delete convert[model].channels;
- delete convert[model].labels;
- Object.defineProperty(convert[model], "channels", { value: channels });
- Object.defineProperty(convert[model], "labels", { value: labels });
- }
- convert.rgb.hsl = function(rgb2) {
- const r4 = rgb2[0] / 255;
- const g4 = rgb2[1] / 255;
- const b4 = rgb2[2] / 255;
- const min = Math.min(r4, g4, b4);
- const max = Math.max(r4, g4, b4);
- const delta = max - min;
- let h5;
- let s4;
- if (max === min) {
- h5 = 0;
- } else if (r4 === max) {
- h5 = (g4 - b4) / delta;
- } else if (g4 === max) {
- h5 = 2 + (b4 - r4) / delta;
- } else if (b4 === max) {
- h5 = 4 + (r4 - g4) / delta;
- }
- h5 = Math.min(h5 * 60, 360);
- if (h5 < 0) {
- h5 += 360;
- }
- const l4 = (min + max) / 2;
- if (max === min) {
- s4 = 0;
- } else if (l4 <= 0.5) {
- s4 = delta / (max + min);
- } else {
- s4 = delta / (2 - max - min);
- }
- return [h5, s4 * 100, l4 * 100];
- };
- convert.rgb.hsv = function(rgb2) {
- let rdif;
- let gdif;
- let bdif;
- let h5;
- let s4;
- const r4 = rgb2[0] / 255;
- const g4 = rgb2[1] / 255;
- const b4 = rgb2[2] / 255;
- const v6 = Math.max(r4, g4, b4);
- const diff2 = v6 - Math.min(r4, g4, b4);
- const diffc = function(c8) {
- return (v6 - c8) / 6 / diff2 + 1 / 2;
- };
- if (diff2 === 0) {
- h5 = 0;
- s4 = 0;
- } else {
- s4 = diff2 / v6;
- rdif = diffc(r4);
- gdif = diffc(g4);
- bdif = diffc(b4);
- if (r4 === v6) {
- h5 = bdif - gdif;
- } else if (g4 === v6) {
- h5 = 1 / 3 + rdif - bdif;
- } else if (b4 === v6) {
- h5 = 2 / 3 + gdif - rdif;
- }
- if (h5 < 0) {
- h5 += 1;
- } else if (h5 > 1) {
- h5 -= 1;
- }
- }
- return [
- h5 * 360,
- s4 * 100,
- v6 * 100
- ];
- };
- convert.rgb.hwb = function(rgb2) {
- const r4 = rgb2[0];
- const g4 = rgb2[1];
- let b4 = rgb2[2];
- const h5 = convert.rgb.hsl(rgb2)[0];
- const w2 = 1 / 255 * Math.min(r4, Math.min(g4, b4));
- b4 = 1 - 1 / 255 * Math.max(r4, Math.max(g4, b4));
- return [h5, w2 * 100, b4 * 100];
- };
- convert.rgb.cmyk = function(rgb2) {
- const r4 = rgb2[0] / 255;
- const g4 = rgb2[1] / 255;
- const b4 = rgb2[2] / 255;
- const k4 = Math.min(1 - r4, 1 - g4, 1 - b4);
- const c8 = (1 - r4 - k4) / (1 - k4) || 0;
- const m4 = (1 - g4 - k4) / (1 - k4) || 0;
- const y3 = (1 - b4 - k4) / (1 - k4) || 0;
- return [c8 * 100, m4 * 100, y3 * 100, k4 * 100];
- };
- function comparativeDistance(x3, y3) {
- return (x3[0] - y3[0]) ** 2 + (x3[1] - y3[1]) ** 2 + (x3[2] - y3[2]) ** 2;
- }
- convert.rgb.keyword = function(rgb2) {
- const reversed = reverseKeywords[rgb2];
- if (reversed) {
- return reversed;
- }
- let currentClosestDistance = Infinity;
- let currentClosestKeyword;
- for (const keyword of Object.keys(cssKeywords)) {
- const value = cssKeywords[keyword];
- const distance = comparativeDistance(rgb2, value);
- if (distance < currentClosestDistance) {
- currentClosestDistance = distance;
- currentClosestKeyword = keyword;
- }
- }
- return currentClosestKeyword;
- };
- convert.keyword.rgb = function(keyword) {
- return cssKeywords[keyword];
- };
- convert.rgb.xyz = function(rgb2) {
- let r4 = rgb2[0] / 255;
- let g4 = rgb2[1] / 255;
- let b4 = rgb2[2] / 255;
- r4 = r4 > 0.04045 ? ((r4 + 0.055) / 1.055) ** 2.4 : r4 / 12.92;
- g4 = g4 > 0.04045 ? ((g4 + 0.055) / 1.055) ** 2.4 : g4 / 12.92;
- b4 = b4 > 0.04045 ? ((b4 + 0.055) / 1.055) ** 2.4 : b4 / 12.92;
- const x3 = r4 * 0.4124 + g4 * 0.3576 + b4 * 0.1805;
- const y3 = r4 * 0.2126 + g4 * 0.7152 + b4 * 0.0722;
- const z3 = r4 * 0.0193 + g4 * 0.1192 + b4 * 0.9505;
- return [x3 * 100, y3 * 100, z3 * 100];
- };
- convert.rgb.lab = function(rgb2) {
- const xyz = convert.rgb.xyz(rgb2);
- let x3 = xyz[0];
- let y3 = xyz[1];
- let z3 = xyz[2];
- x3 /= 95.047;
- y3 /= 100;
- z3 /= 108.883;
- x3 = x3 > 0.008856 ? x3 ** (1 / 3) : 7.787 * x3 + 16 / 116;
- y3 = y3 > 0.008856 ? y3 ** (1 / 3) : 7.787 * y3 + 16 / 116;
- z3 = z3 > 0.008856 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116;
- const l4 = 116 * y3 - 16;
- const a5 = 500 * (x3 - y3);
- const b4 = 200 * (y3 - z3);
- return [l4, a5, b4];
- };
- convert.hsl.rgb = function(hsl) {
- const h5 = hsl[0] / 360;
- const s4 = hsl[1] / 100;
- const l4 = hsl[2] / 100;
- let t22;
- let t32;
- let val;
- if (s4 === 0) {
- val = l4 * 255;
- return [val, val, val];
- }
- if (l4 < 0.5) {
- t22 = l4 * (1 + s4);
- } else {
- t22 = l4 + s4 - l4 * s4;
- }
- const t1 = 2 * l4 - t22;
- const rgb2 = [0, 0, 0];
- for (let i5 = 0;i5 < 3; i5++) {
- t32 = h5 + 1 / 3 * -(i5 - 1);
- if (t32 < 0) {
- t32++;
- }
- if (t32 > 1) {
- t32--;
- }
- if (6 * t32 < 1) {
- val = t1 + (t22 - t1) * 6 * t32;
- } else if (2 * t32 < 1) {
- val = t22;
- } else if (3 * t32 < 2) {
- val = t1 + (t22 - t1) * (2 / 3 - t32) * 6;
- } else {
- val = t1;
- }
- rgb2[i5] = val * 255;
- }
- return rgb2;
- };
- convert.hsl.hsv = function(hsl) {
- const h5 = hsl[0];
- let s4 = hsl[1] / 100;
- let l4 = hsl[2] / 100;
- let smin = s4;
- const lmin = Math.max(l4, 0.01);
- l4 *= 2;
- s4 *= l4 <= 1 ? l4 : 2 - l4;
- smin *= lmin <= 1 ? lmin : 2 - lmin;
- const v6 = (l4 + s4) / 2;
- const sv = l4 === 0 ? 2 * smin / (lmin + smin) : 2 * s4 / (l4 + s4);
- return [h5, sv * 100, v6 * 100];
- };
- convert.hsv.rgb = function(hsv) {
- const h5 = hsv[0] / 60;
- const s4 = hsv[1] / 100;
- let v6 = hsv[2] / 100;
- const hi = Math.floor(h5) % 6;
- const f4 = h5 - Math.floor(h5);
- const p4 = 255 * v6 * (1 - s4);
- const q4 = 255 * v6 * (1 - s4 * f4);
- const t4 = 255 * v6 * (1 - s4 * (1 - f4));
- v6 *= 255;
- switch (hi) {
- case 0:
- return [v6, t4, p4];
- case 1:
- return [q4, v6, p4];
- case 2:
- return [p4, v6, t4];
- case 3:
- return [p4, q4, v6];
- case 4:
- return [t4, p4, v6];
- case 5:
- return [v6, p4, q4];
- }
- };
- convert.hsv.hsl = function(hsv) {
- const h5 = hsv[0];
- const s4 = hsv[1] / 100;
- const v6 = hsv[2] / 100;
- const vmin = Math.max(v6, 0.01);
- let sl;
- let l4;
- l4 = (2 - s4) * v6;
- const lmin = (2 - s4) * vmin;
- sl = s4 * vmin;
- sl /= lmin <= 1 ? lmin : 2 - lmin;
- sl = sl || 0;
- l4 /= 2;
- return [h5, sl * 100, l4 * 100];
- };
- convert.hwb.rgb = function(hwb) {
- const h5 = hwb[0] / 360;
- let wh = hwb[1] / 100;
- let bl = hwb[2] / 100;
- const ratio = wh + bl;
- let f4;
- if (ratio > 1) {
- wh /= ratio;
- bl /= ratio;
- }
- const i5 = Math.floor(6 * h5);
- const v6 = 1 - bl;
- f4 = 6 * h5 - i5;
- if ((i5 & 1) !== 0) {
- f4 = 1 - f4;
- }
- const n5 = wh + f4 * (v6 - wh);
- let r4;
- let g4;
- let b4;
- switch (i5) {
- default:
- case 6:
- case 0:
- r4 = v6;
- g4 = n5;
- b4 = wh;
- break;
- case 1:
- r4 = n5;
- g4 = v6;
- b4 = wh;
- break;
- case 2:
- r4 = wh;
- g4 = v6;
- b4 = n5;
- break;
- case 3:
- r4 = wh;
- g4 = n5;
- b4 = v6;
- break;
- case 4:
- r4 = n5;
- g4 = wh;
- b4 = v6;
- break;
- case 5:
- r4 = v6;
- g4 = wh;
- b4 = n5;
- break;
- }
- return [r4 * 255, g4 * 255, b4 * 255];
- };
- convert.cmyk.rgb = function(cmyk) {
- const c8 = cmyk[0] / 100;
- const m4 = cmyk[1] / 100;
- const y3 = cmyk[2] / 100;
- const k4 = cmyk[3] / 100;
- const r4 = 1 - Math.min(1, c8 * (1 - k4) + k4);
- const g4 = 1 - Math.min(1, m4 * (1 - k4) + k4);
- const b4 = 1 - Math.min(1, y3 * (1 - k4) + k4);
- return [r4 * 255, g4 * 255, b4 * 255];
- };
- convert.xyz.rgb = function(xyz) {
- const x3 = xyz[0] / 100;
- const y3 = xyz[1] / 100;
- const z3 = xyz[2] / 100;
- let r4;
- let g4;
- let b4;
- r4 = x3 * 3.2406 + y3 * -1.5372 + z3 * -0.4986;
- g4 = x3 * -0.9689 + y3 * 1.8758 + z3 * 0.0415;
- b4 = x3 * 0.0557 + y3 * -0.204 + z3 * 1.057;
- r4 = r4 > 0.0031308 ? 1.055 * r4 ** (1 / 2.4) - 0.055 : r4 * 12.92;
- g4 = g4 > 0.0031308 ? 1.055 * g4 ** (1 / 2.4) - 0.055 : g4 * 12.92;
- b4 = b4 > 0.0031308 ? 1.055 * b4 ** (1 / 2.4) - 0.055 : b4 * 12.92;
- r4 = Math.min(Math.max(0, r4), 1);
- g4 = Math.min(Math.max(0, g4), 1);
- b4 = Math.min(Math.max(0, b4), 1);
- return [r4 * 255, g4 * 255, b4 * 255];
- };
- convert.xyz.lab = function(xyz) {
- let x3 = xyz[0];
- let y3 = xyz[1];
- let z3 = xyz[2];
- x3 /= 95.047;
- y3 /= 100;
- z3 /= 108.883;
- x3 = x3 > 0.008856 ? x3 ** (1 / 3) : 7.787 * x3 + 16 / 116;
- y3 = y3 > 0.008856 ? y3 ** (1 / 3) : 7.787 * y3 + 16 / 116;
- z3 = z3 > 0.008856 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116;
- const l4 = 116 * y3 - 16;
- const a5 = 500 * (x3 - y3);
- const b4 = 200 * (y3 - z3);
- return [l4, a5, b4];
- };
- convert.lab.xyz = function(lab) {
- const l4 = lab[0];
- const a5 = lab[1];
- const b4 = lab[2];
- let x3;
- let y3;
- let z3;
- y3 = (l4 + 16) / 116;
- x3 = a5 / 500 + y3;
- z3 = y3 - b4 / 200;
- const y22 = y3 ** 3;
- const x22 = x3 ** 3;
- const z22 = z3 ** 3;
- y3 = y22 > 0.008856 ? y22 : (y3 - 16 / 116) / 7.787;
- x3 = x22 > 0.008856 ? x22 : (x3 - 16 / 116) / 7.787;
- z3 = z22 > 0.008856 ? z22 : (z3 - 16 / 116) / 7.787;
- x3 *= 95.047;
- y3 *= 100;
- z3 *= 108.883;
- return [x3, y3, z3];
- };
- convert.lab.lch = function(lab) {
- const l4 = lab[0];
- const a5 = lab[1];
- const b4 = lab[2];
- let h5;
- const hr2 = Math.atan2(b4, a5);
- h5 = hr2 * 360 / 2 / Math.PI;
- if (h5 < 0) {
- h5 += 360;
- }
- const c8 = Math.sqrt(a5 * a5 + b4 * b4);
- return [l4, c8, h5];
- };
- convert.lch.lab = function(lch) {
- const l4 = lch[0];
- const c8 = lch[1];
- const h5 = lch[2];
- const hr2 = h5 / 360 * 2 * Math.PI;
- const a5 = c8 * Math.cos(hr2);
- const b4 = c8 * Math.sin(hr2);
- return [l4, a5, b4];
- };
- convert.rgb.ansi16 = function(args, saturation = null) {
- const [r4, g4, b4] = args;
- let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation;
- value = Math.round(value / 50);
- if (value === 0) {
- return 30;
- }
- let ansi = 30 + (Math.round(b4 / 255) << 2 | Math.round(g4 / 255) << 1 | Math.round(r4 / 255));
- if (value === 2) {
- ansi += 60;
- }
- return ansi;
- };
- convert.hsv.ansi16 = function(args) {
- return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
- };
- convert.rgb.ansi256 = function(args) {
- const r4 = args[0];
- const g4 = args[1];
- const b4 = args[2];
- if (r4 === g4 && g4 === b4) {
- if (r4 < 8) {
- return 16;
- }
- if (r4 > 248) {
- return 231;
- }
- return Math.round((r4 - 8) / 247 * 24) + 232;
- }
- const ansi = 16 + 36 * Math.round(r4 / 255 * 5) + 6 * Math.round(g4 / 255 * 5) + Math.round(b4 / 255 * 5);
- return ansi;
- };
- convert.ansi16.rgb = function(args) {
- let color2 = args % 10;
- if (color2 === 0 || color2 === 7) {
- if (args > 50) {
- color2 += 3.5;
- }
- color2 = color2 / 10.5 * 255;
- return [color2, color2, color2];
- }
- const mult = (~~(args > 50) + 1) * 0.5;
- const r4 = (color2 & 1) * mult * 255;
- const g4 = (color2 >> 1 & 1) * mult * 255;
- const b4 = (color2 >> 2 & 1) * mult * 255;
- return [r4, g4, b4];
- };
- convert.ansi256.rgb = function(args) {
- if (args >= 232) {
- const c8 = (args - 232) * 10 + 8;
- return [c8, c8, c8];
- }
- args -= 16;
- let rem;
- const r4 = Math.floor(args / 36) / 5 * 255;
- const g4 = Math.floor((rem = args % 36) / 6) / 5 * 255;
- const b4 = rem % 6 / 5 * 255;
- return [r4, g4, b4];
- };
- convert.rgb.hex = function(args) {
- const integer2 = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255);
- const string4 = integer2.toString(16).toUpperCase();
- return "000000".substring(string4.length) + string4;
- };
- convert.hex.rgb = function(args) {
- const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
- if (!match) {
- return [0, 0, 0];
- }
- let colorString = match[0];
- if (match[0].length === 3) {
- colorString = colorString.split("").map((char) => {
- return char + char;
- }).join("");
- }
- const integer2 = parseInt(colorString, 16);
- const r4 = integer2 >> 16 & 255;
- const g4 = integer2 >> 8 & 255;
- const b4 = integer2 & 255;
- return [r4, g4, b4];
- };
- convert.rgb.hcg = function(rgb2) {
- const r4 = rgb2[0] / 255;
- const g4 = rgb2[1] / 255;
- const b4 = rgb2[2] / 255;
- const max = Math.max(Math.max(r4, g4), b4);
- const min = Math.min(Math.min(r4, g4), b4);
- const chroma = max - min;
- let grayscale;
- let hue;
- if (chroma < 1) {
- grayscale = min / (1 - chroma);
- } else {
- grayscale = 0;
- }
- if (chroma <= 0) {
- hue = 0;
- } else if (max === r4) {
- hue = (g4 - b4) / chroma % 6;
- } else if (max === g4) {
- hue = 2 + (b4 - r4) / chroma;
- } else {
- hue = 4 + (r4 - g4) / chroma;
- }
- hue /= 6;
- hue %= 1;
- return [hue * 360, chroma * 100, grayscale * 100];
- };
- convert.hsl.hcg = function(hsl) {
- const s4 = hsl[1] / 100;
- const l4 = hsl[2] / 100;
- const c8 = l4 < 0.5 ? 2 * s4 * l4 : 2 * s4 * (1 - l4);
- let f4 = 0;
- if (c8 < 1) {
- f4 = (l4 - 0.5 * c8) / (1 - c8);
- }
- return [hsl[0], c8 * 100, f4 * 100];
- };
- convert.hsv.hcg = function(hsv) {
- const s4 = hsv[1] / 100;
- const v6 = hsv[2] / 100;
- const c8 = s4 * v6;
- let f4 = 0;
- if (c8 < 1) {
- f4 = (v6 - c8) / (1 - c8);
- }
- return [hsv[0], c8 * 100, f4 * 100];
- };
- convert.hcg.rgb = function(hcg) {
- const h5 = hcg[0] / 360;
- const c8 = hcg[1] / 100;
- const g4 = hcg[2] / 100;
- if (c8 === 0) {
- return [g4 * 255, g4 * 255, g4 * 255];
- }
- const pure = [0, 0, 0];
- const hi = h5 % 1 * 6;
- const v6 = hi % 1;
- const w2 = 1 - v6;
- let mg = 0;
- switch (Math.floor(hi)) {
- case 0:
- pure[0] = 1;
- pure[1] = v6;
- pure[2] = 0;
- break;
- case 1:
- pure[0] = w2;
- pure[1] = 1;
- pure[2] = 0;
- break;
- case 2:
- pure[0] = 0;
- pure[1] = 1;
- pure[2] = v6;
- break;
- case 3:
- pure[0] = 0;
- pure[1] = w2;
- pure[2] = 1;
- break;
- case 4:
- pure[0] = v6;
- pure[1] = 0;
- pure[2] = 1;
- break;
- default:
- pure[0] = 1;
- pure[1] = 0;
- pure[2] = w2;
- }
- mg = (1 - c8) * g4;
- return [
- (c8 * pure[0] + mg) * 255,
- (c8 * pure[1] + mg) * 255,
- (c8 * pure[2] + mg) * 255
- ];
- };
- convert.hcg.hsv = function(hcg) {
- const c8 = hcg[1] / 100;
- const g4 = hcg[2] / 100;
- const v6 = c8 + g4 * (1 - c8);
- let f4 = 0;
- if (v6 > 0) {
- f4 = c8 / v6;
- }
- return [hcg[0], f4 * 100, v6 * 100];
- };
- convert.hcg.hsl = function(hcg) {
- const c8 = hcg[1] / 100;
- const g4 = hcg[2] / 100;
- const l4 = g4 * (1 - c8) + 0.5 * c8;
- let s4 = 0;
- if (l4 > 0 && l4 < 0.5) {
- s4 = c8 / (2 * l4);
- } else if (l4 >= 0.5 && l4 < 1) {
- s4 = c8 / (2 * (1 - l4));
- }
- return [hcg[0], s4 * 100, l4 * 100];
- };
- convert.hcg.hwb = function(hcg) {
- const c8 = hcg[1] / 100;
- const g4 = hcg[2] / 100;
- const v6 = c8 + g4 * (1 - c8);
- return [hcg[0], (v6 - c8) * 100, (1 - v6) * 100];
- };
- convert.hwb.hcg = function(hwb) {
- const w2 = hwb[1] / 100;
- const b4 = hwb[2] / 100;
- const v6 = 1 - b4;
- const c8 = v6 - w2;
- let g4 = 0;
- if (c8 < 1) {
- g4 = (v6 - c8) / (1 - c8);
- }
- return [hwb[0], c8 * 100, g4 * 100];
- };
- convert.apple.rgb = function(apple) {
- return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
- };
- convert.rgb.apple = function(rgb2) {
- return [rgb2[0] / 255 * 65535, rgb2[1] / 255 * 65535, rgb2[2] / 255 * 65535];
- };
- convert.gray.rgb = function(args) {
- return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
- };
- convert.gray.hsl = function(args) {
- return [0, 0, args[0]];
- };
- convert.gray.hsv = convert.gray.hsl;
- convert.gray.hwb = function(gray2) {
- return [0, 100, gray2[0]];
- };
- convert.gray.cmyk = function(gray2) {
- return [0, 0, 0, gray2[0]];
- };
- convert.gray.lab = function(gray2) {
- return [gray2[0], 0, 0];
- };
- convert.gray.hex = function(gray2) {
- const val = Math.round(gray2[0] / 100 * 255) & 255;
- const integer2 = (val << 16) + (val << 8) + val;
- const string4 = integer2.toString(16).toUpperCase();
- return "000000".substring(string4.length) + string4;
- };
- convert.rgb.gray = function(rgb2) {
- const val = (rgb2[0] + rgb2[1] + rgb2[2]) / 3;
- return [val / 255 * 100];
- };
-});
-
-// node_modules/color-convert/route.js
-var require_route = __commonJS((exports, module) => {
- var conversions = require_conversions();
- function buildGraph() {
- const graph = {};
- const models = Object.keys(conversions);
- for (let len = models.length, i5 = 0;i5 < len; i5++) {
- graph[models[i5]] = {
- distance: -1,
- parent: null
- };
- }
- return graph;
- }
- function deriveBFS(fromModel) {
- const graph = buildGraph();
- const queue = [fromModel];
- graph[fromModel].distance = 0;
- while (queue.length) {
- const current = queue.pop();
- const adjacents = Object.keys(conversions[current]);
- for (let len = adjacents.length, i5 = 0;i5 < len; i5++) {
- const adjacent = adjacents[i5];
- const node = graph[adjacent];
- if (node.distance === -1) {
- node.distance = graph[current].distance + 1;
- node.parent = current;
- queue.unshift(adjacent);
- }
- }
- }
- return graph;
- }
- function link3(from, to) {
- return function(args) {
- return to(from(args));
- };
- }
- function wrapConversion(toModel, graph) {
- const path15 = [graph[toModel].parent, toModel];
- let fn = conversions[graph[toModel].parent][toModel];
- let cur = graph[toModel].parent;
- while (graph[cur].parent) {
- path15.unshift(graph[cur].parent);
- fn = link3(conversions[graph[cur].parent][cur], fn);
- cur = graph[cur].parent;
- }
- fn.conversion = path15;
- return fn;
- }
- module.exports = function(fromModel) {
- const graph = deriveBFS(fromModel);
- const conversion = {};
- const models = Object.keys(graph);
- for (let len = models.length, i5 = 0;i5 < len; i5++) {
- const toModel = models[i5];
- const node = graph[toModel];
- if (node.parent === null) {
- continue;
- }
- conversion[toModel] = wrapConversion(toModel, graph);
- }
- return conversion;
- };
-});
-
-// node_modules/color-convert/index.js
-var require_color_convert = __commonJS((exports, module) => {
- var conversions = require_conversions();
- var route = require_route();
- var convert = {};
- var models = Object.keys(conversions);
- function wrapRaw(fn) {
- const wrappedFn = function(...args) {
- const arg0 = args[0];
- if (arg0 === undefined || arg0 === null) {
- return arg0;
- }
- if (arg0.length > 1) {
- args = arg0;
- }
- return fn(args);
- };
- if ("conversion" in fn) {
- wrappedFn.conversion = fn.conversion;
- }
- return wrappedFn;
- }
- function wrapRounded(fn) {
- const wrappedFn = function(...args) {
- const arg0 = args[0];
- if (arg0 === undefined || arg0 === null) {
- return arg0;
- }
- if (arg0.length > 1) {
- args = arg0;
- }
- const result = fn(args);
- if (typeof result === "object") {
- for (let len = result.length, i5 = 0;i5 < len; i5++) {
- result[i5] = Math.round(result[i5]);
- }
- }
- return result;
- };
- if ("conversion" in fn) {
- wrappedFn.conversion = fn.conversion;
- }
- return wrappedFn;
- }
- models.forEach((fromModel) => {
- convert[fromModel] = {};
- Object.defineProperty(convert[fromModel], "channels", { value: conversions[fromModel].channels });
- Object.defineProperty(convert[fromModel], "labels", { value: conversions[fromModel].labels });
- const routes = route(fromModel);
- const routeModels = Object.keys(routes);
- routeModels.forEach((toModel) => {
- const fn = routes[toModel];
- convert[fromModel][toModel] = wrapRounded(fn);
- convert[fromModel][toModel].raw = wrapRaw(fn);
- });
- });
- module.exports = convert;
-});
-
-// node_modules/@inquirer/core/node_modules/wrap-ansi/node_modules/ansi-styles/index.js
-var require_ansi_styles = __commonJS((exports, module) => {
- var wrapAnsi163 = (fn, offset) => (...args) => {
- const code = fn(...args);
- return `\x1B[${code + offset}m`;
- };
- var wrapAnsi2563 = (fn, offset) => (...args) => {
- const code = fn(...args);
- return `\x1B[${38 + offset};5;${code}m`;
- };
- var wrapAnsi16m3 = (fn, offset) => (...args) => {
- const rgb2 = fn(...args);
- return `\x1B[${38 + offset};2;${rgb2[0]};${rgb2[1]};${rgb2[2]}m`;
- };
- var ansi2ansi = (n5) => n5;
- var rgb2rgb = (r4, g4, b4) => [r4, g4, b4];
- var setLazyProperty = (object2, property2, get2) => {
- Object.defineProperty(object2, property2, {
- get: () => {
- const value = get2();
- Object.defineProperty(object2, property2, {
- value,
- enumerable: true,
- configurable: true
- });
- return value;
- },
- enumerable: true,
- configurable: true
- });
- };
- var colorConvert;
- var makeDynamicStyles = (wrap, targetSpace, identity16, isBackground) => {
- if (colorConvert === undefined) {
- colorConvert = require_color_convert();
- }
- const offset = isBackground ? 10 : 0;
- const styles5 = {};
- for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
- const name3 = sourceSpace === "ansi16" ? "ansi" : sourceSpace;
- if (sourceSpace === targetSpace) {
- styles5[name3] = wrap(identity16, offset);
- } else if (typeof suite === "object") {
- styles5[name3] = wrap(suite[targetSpace], offset);
- }
- }
- return styles5;
- };
- function assembleStyles3() {
- const codes = new Map;
- const styles5 = {
- modifier: {
- reset: [0, 0],
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29]
- },
- color: {
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
- blackBright: [90, 39],
- redBright: [91, 39],
- greenBright: [92, 39],
- yellowBright: [93, 39],
- blueBright: [94, 39],
- magentaBright: [95, 39],
- cyanBright: [96, 39],
- whiteBright: [97, 39]
- },
- bgColor: {
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
- bgBlackBright: [100, 49],
- bgRedBright: [101, 49],
- bgGreenBright: [102, 49],
- bgYellowBright: [103, 49],
- bgBlueBright: [104, 49],
- bgMagentaBright: [105, 49],
- bgCyanBright: [106, 49],
- bgWhiteBright: [107, 49]
- }
- };
- styles5.color.gray = styles5.color.blackBright;
- styles5.bgColor.bgGray = styles5.bgColor.bgBlackBright;
- styles5.color.grey = styles5.color.blackBright;
- styles5.bgColor.bgGrey = styles5.bgColor.bgBlackBright;
- for (const [groupName, group] of Object.entries(styles5)) {
- for (const [styleName, style] of Object.entries(group)) {
- styles5[styleName] = {
- open: `\x1B[${style[0]}m`,
- close: `\x1B[${style[1]}m`
- };
- group[styleName] = styles5[styleName];
- codes.set(style[0], style[1]);
- }
- Object.defineProperty(styles5, groupName, {
- value: group,
- enumerable: false
- });
- }
- Object.defineProperty(styles5, "codes", {
- value: codes,
- enumerable: false
- });
- styles5.color.close = "\x1B[39m";
- styles5.bgColor.close = "\x1B[49m";
- setLazyProperty(styles5.color, "ansi", () => makeDynamicStyles(wrapAnsi163, "ansi16", ansi2ansi, false));
- setLazyProperty(styles5.color, "ansi256", () => makeDynamicStyles(wrapAnsi2563, "ansi256", ansi2ansi, false));
- setLazyProperty(styles5.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m3, "rgb", rgb2rgb, false));
- setLazyProperty(styles5.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi163, "ansi16", ansi2ansi, true));
- setLazyProperty(styles5.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi2563, "ansi256", ansi2ansi, true));
- setLazyProperty(styles5.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m3, "rgb", rgb2rgb, true));
- return styles5;
- }
- Object.defineProperty(module, "exports", {
- enumerable: true,
- get: assembleStyles3
- });
-});
-
-// node_modules/@inquirer/core/node_modules/wrap-ansi/index.js
-var require_wrap_ansi = __commonJS((exports, module) => {
- var stringWidth3 = require_string_width();
- var stripAnsi2 = require_strip_ansi();
- var ansiStyles3 = require_ansi_styles();
- var ESCAPES3 = new Set([
- "\x1B",
- "\x9B"
- ]);
- var END_CODE2 = 39;
- var wrapAnsi3 = (code) => `${ESCAPES3.values().next().value}[${code}m`;
- var wordLengths2 = (string4) => string4.split(" ").map((character) => stringWidth3(character));
- var wrapWord2 = (rows, word, columns) => {
- const characters = [...word];
- let isInsideEscape = false;
- let visible = stringWidth3(stripAnsi2(rows[rows.length - 1]));
- for (const [index2, character] of characters.entries()) {
- const characterLength = stringWidth3(character);
- if (visible + characterLength <= columns) {
- rows[rows.length - 1] += character;
- } else {
- rows.push(character);
- visible = 0;
- }
- if (ESCAPES3.has(character)) {
- isInsideEscape = true;
- } else if (isInsideEscape && character === "m") {
- isInsideEscape = false;
- continue;
- }
- if (isInsideEscape) {
- continue;
- }
- visible += characterLength;
- if (visible === columns && index2 < characters.length - 1) {
- rows.push("");
- visible = 0;
- }
- }
- if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
- rows[rows.length - 2] += rows.pop();
- }
- };
- var stringVisibleTrimSpacesRight2 = (str) => {
- const words = str.split(" ");
- let last = words.length;
- while (last > 0) {
- if (stringWidth3(words[last - 1]) > 0) {
- break;
- }
- last--;
- }
- if (last === words.length) {
- return str;
- }
- return words.slice(0, last).join(" ") + words.slice(last).join("");
- };
- var exec4 = (string4, columns, options2 = {}) => {
- if (options2.trim !== false && string4.trim() === "") {
- return "";
- }
- let pre = "";
- let ret = "";
- let escapeCode;
- const lengths = wordLengths2(string4);
- let rows = [""];
- for (const [index2, word] of string4.split(" ").entries()) {
- if (options2.trim !== false) {
- rows[rows.length - 1] = rows[rows.length - 1].trimLeft();
- }
- let rowLength = stringWidth3(rows[rows.length - 1]);
- if (index2 !== 0) {
- if (rowLength >= columns && (options2.wordWrap === false || options2.trim === false)) {
- rows.push("");
- rowLength = 0;
- }
- if (rowLength > 0 || options2.trim === false) {
- rows[rows.length - 1] += " ";
- rowLength++;
- }
- }
- if (options2.hard && lengths[index2] > columns) {
- const remainingColumns = columns - rowLength;
- const breaksStartingThisLine = 1 + Math.floor((lengths[index2] - remainingColumns - 1) / columns);
- const breaksStartingNextLine = Math.floor((lengths[index2] - 1) / columns);
- if (breaksStartingNextLine < breaksStartingThisLine) {
- rows.push("");
- }
- wrapWord2(rows, word, columns);
- continue;
- }
- if (rowLength + lengths[index2] > columns && rowLength > 0 && lengths[index2] > 0) {
- if (options2.wordWrap === false && rowLength < columns) {
- wrapWord2(rows, word, columns);
- continue;
- }
- rows.push("");
- }
- if (rowLength + lengths[index2] > columns && options2.wordWrap === false) {
- wrapWord2(rows, word, columns);
- continue;
- }
- rows[rows.length - 1] += word;
- }
- if (options2.trim !== false) {
- rows = rows.map(stringVisibleTrimSpacesRight2);
- }
- pre = rows.join(`
-`);
- for (const [index2, character] of [...pre].entries()) {
- ret += character;
- if (ESCAPES3.has(character)) {
- const code2 = parseFloat(/\d[^m]*/.exec(pre.slice(index2, index2 + 4)));
- escapeCode = code2 === END_CODE2 ? null : code2;
- }
- const code = ansiStyles3.codes.get(Number(escapeCode));
- if (escapeCode && code) {
- if (pre[index2 + 1] === `
-`) {
- ret += wrapAnsi3(code);
- } else if (character === `
-`) {
- ret += wrapAnsi3(escapeCode);
- }
- }
- }
- return ret;
- };
- module.exports = (string4, columns, options2) => {
- return String(string4).normalize().replace(/\r\n/g, `
-`).split(`
-`).map((line) => exec4(line, columns, options2)).join(`
-`);
- };
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/utils.mjs
-function breakLines(content, width) {
- return content.split(`
-`).flatMap((line) => import_wrap_ansi2.default(line, width, { trim: false, hard: true }).split(`
-`).map((str) => str.trimEnd())).join(`
-`);
-}
-function readlineWidth() {
- return import_cli_width.default({ defaultWidth: 80, output: readline().output });
-}
-var import_cli_width, import_wrap_ansi2;
-var init_utils6 = __esm(() => {
- init_hook_engine();
- import_cli_width = __toESM(require_cli_width(), 1);
- import_wrap_ansi2 = __toESM(require_wrap_ansi(), 1);
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs
-function split(content, width) {
- return breakLines(content, width).split(`
-`);
-}
-function rotate(count3, items) {
- const max = items.length;
- const offset = (count3 % max + max) % max;
- return [...items.slice(offset), ...items.slice(0, offset)];
-}
-function lines({ items, width, renderItem, active, position: requested, pageSize }) {
- const layouts = items.map((item, index2) => ({
- item,
- index: index2,
- isActive: index2 === active
- }));
- const layoutsInPage = rotate(active - requested, layouts).slice(0, pageSize);
- const renderItemAt = (index2) => layoutsInPage[index2] == null ? [] : split(renderItem(layoutsInPage[index2]), width);
- const pageBuffer = Array.from({ length: pageSize });
- const activeItem = renderItemAt(requested).slice(0, pageSize);
- const position2 = requested + activeItem.length <= pageSize ? requested : pageSize - activeItem.length;
- pageBuffer.splice(position2, activeItem.length, ...activeItem);
- let bufferPointer = position2 + activeItem.length;
- let layoutPointer = requested + 1;
- while (bufferPointer < pageSize && layoutPointer < layoutsInPage.length) {
- for (const line of renderItemAt(layoutPointer)) {
- pageBuffer[bufferPointer++] = line;
- if (bufferPointer >= pageSize)
- break;
- }
- layoutPointer++;
- }
- bufferPointer = position2 - 1;
- layoutPointer = requested - 1;
- while (bufferPointer >= 0 && layoutPointer >= 0) {
- for (const line of renderItemAt(layoutPointer).reverse()) {
- pageBuffer[bufferPointer--] = line;
- if (bufferPointer < 0)
- break;
- }
- layoutPointer--;
- }
- return pageBuffer.filter((line) => typeof line === "string");
-}
-var init_lines = __esm(() => {
- init_utils6();
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs
-function finite({ active, pageSize, total }) {
- const middle = Math.floor(pageSize / 2);
- if (total <= pageSize || active < middle)
- return active;
- if (active >= total - middle)
- return active + pageSize - total;
- return middle;
-}
-function infinite({ active, lastActive, total, pageSize, pointer }) {
- if (total <= pageSize)
- return active;
- if (lastActive < active && active - lastActive < pageSize) {
- return Math.min(Math.floor(pageSize / 2), pointer + active - lastActive);
- }
- return pointer;
-}
-
-// node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs
-function usePagination({ items, active, renderItem, pageSize, loop = true }) {
- const state3 = useRef7({ position: 0, lastActive: 0 });
- const position2 = loop ? infinite({
- active,
- lastActive: state3.current.lastActive,
- total: items.length,
- pageSize,
- pointer: state3.current.position
- }) : finite({
- active,
- total: items.length,
- pageSize
- });
- state3.current.position = position2;
- state3.current.lastActive = active;
- return lines({
- items,
- width: readlineWidth(),
- renderItem,
- active,
- position: position2,
- pageSize
- }).join(`
-`);
-}
-var init_use_pagination = __esm(() => {
- init_use_ref();
- init_utils6();
- init_lines();
-});
-
-// node_modules/mute-stream/lib/index.js
-var require_lib = __commonJS((exports, module) => {
- var Stream7 = __require("stream");
-
- class MuteStream extends Stream7 {
- #isTTY = null;
- constructor(opts = {}) {
- super(opts);
- this.writable = this.readable = true;
- this.muted = false;
- this.on("pipe", this._onpipe);
- this.replace = opts.replace;
- this._prompt = opts.prompt || null;
- this._hadControl = false;
- }
- #destSrc(key, def2) {
- if (this._dest) {
- return this._dest[key];
- }
- if (this._src) {
- return this._src[key];
- }
- return def2;
- }
- #proxy(method, ...args) {
- if (typeof this._dest?.[method] === "function") {
- this._dest[method](...args);
- }
- if (typeof this._src?.[method] === "function") {
- this._src[method](...args);
- }
- }
- get isTTY() {
- if (this.#isTTY !== null) {
- return this.#isTTY;
- }
- return this.#destSrc("isTTY", false);
- }
- set isTTY(val) {
- this.#isTTY = val;
- }
- get rows() {
- return this.#destSrc("rows");
- }
- get columns() {
- return this.#destSrc("columns");
- }
- mute() {
- this.muted = true;
- }
- unmute() {
- this.muted = false;
- }
- _onpipe(src) {
- this._src = src;
- }
- pipe(dest, options2) {
- this._dest = dest;
- return super.pipe(dest, options2);
- }
- pause() {
- if (this._src) {
- return this._src.pause();
- }
- }
- resume() {
- if (this._src) {
- return this._src.resume();
- }
- }
- write(c8) {
- if (this.muted) {
- if (!this.replace) {
- return true;
- }
- if (c8.match(/^\u001b/)) {
- if (c8.indexOf(this._prompt) === 0) {
- c8 = c8.slice(this._prompt.length);
- c8 = c8.replace(/./g, this.replace);
- c8 = this._prompt + c8;
- }
- this._hadControl = true;
- return this.emit("data", c8);
- } else {
- if (this._prompt && this._hadControl && c8.indexOf(this._prompt) === 0) {
- this._hadControl = false;
- this.emit("data", this._prompt);
- c8 = c8.slice(this._prompt.length);
- }
- c8 = c8.toString().replace(/./g, this.replace);
- }
- }
- this.emit("data", c8);
- }
- end(c8) {
- if (this.muted) {
- if (c8 && this.replace) {
- c8 = c8.toString().replace(/./g, this.replace);
- } else {
- c8 = null;
- }
- }
- if (c8) {
- this.emit("data", c8);
- }
- this.emit("end");
- }
- destroy(...args) {
- return this.#proxy("destroy", ...args);
- }
- destroySoon(...args) {
- return this.#proxy("destroySoon", ...args);
- }
- close(...args) {
- return this.#proxy("close", ...args);
- }
- }
- module.exports = MuteStream;
-});
-
-// node_modules/@inquirer/core/node_modules/ansi-escapes/index.js
-var require_ansi_escapes = __commonJS((exports, module) => {
- var ansiEscapes = exports;
- exports.default = ansiEscapes;
- var ESC2 = "\x1B[";
- var OSC3 = "\x1B]";
- var BEL3 = "\x07";
- var SEP2 = ";";
- var isTerminalApp = process.env.TERM_PROGRAM === "Apple_Terminal";
- ansiEscapes.cursorTo = (x3, y3) => {
- if (typeof x3 !== "number") {
- throw new TypeError("The `x` argument is required");
- }
- if (typeof y3 !== "number") {
- return ESC2 + (x3 + 1) + "G";
- }
- return ESC2 + (y3 + 1) + ";" + (x3 + 1) + "H";
- };
- ansiEscapes.cursorMove = (x3, y3) => {
- if (typeof x3 !== "number") {
- throw new TypeError("The `x` argument is required");
- }
- let ret = "";
- if (x3 < 0) {
- ret += ESC2 + -x3 + "D";
- } else if (x3 > 0) {
- ret += ESC2 + x3 + "C";
- }
- if (y3 < 0) {
- ret += ESC2 + -y3 + "A";
- } else if (y3 > 0) {
- ret += ESC2 + y3 + "B";
- }
- return ret;
- };
- ansiEscapes.cursorUp = (count3 = 1) => ESC2 + count3 + "A";
- ansiEscapes.cursorDown = (count3 = 1) => ESC2 + count3 + "B";
- ansiEscapes.cursorForward = (count3 = 1) => ESC2 + count3 + "C";
- ansiEscapes.cursorBackward = (count3 = 1) => ESC2 + count3 + "D";
- ansiEscapes.cursorLeft = ESC2 + "G";
- ansiEscapes.cursorSavePosition = isTerminalApp ? "\x1B7" : ESC2 + "s";
- ansiEscapes.cursorRestorePosition = isTerminalApp ? "\x1B8" : ESC2 + "u";
- ansiEscapes.cursorGetPosition = ESC2 + "6n";
- ansiEscapes.cursorNextLine = ESC2 + "E";
- ansiEscapes.cursorPrevLine = ESC2 + "F";
- ansiEscapes.cursorHide = ESC2 + "?25l";
- ansiEscapes.cursorShow = ESC2 + "?25h";
- ansiEscapes.eraseLines = (count3) => {
- let clear = "";
- for (let i5 = 0;i5 < count3; i5++) {
- clear += ansiEscapes.eraseLine + (i5 < count3 - 1 ? ansiEscapes.cursorUp() : "");
- }
- if (count3) {
- clear += ansiEscapes.cursorLeft;
- }
- return clear;
- };
- ansiEscapes.eraseEndLine = ESC2 + "K";
- ansiEscapes.eraseStartLine = ESC2 + "1K";
- ansiEscapes.eraseLine = ESC2 + "2K";
- ansiEscapes.eraseDown = ESC2 + "J";
- ansiEscapes.eraseUp = ESC2 + "1J";
- ansiEscapes.eraseScreen = ESC2 + "2J";
- ansiEscapes.scrollUp = ESC2 + "S";
- ansiEscapes.scrollDown = ESC2 + "T";
- ansiEscapes.clearScreen = "\x1Bc";
- ansiEscapes.clearTerminal = process.platform === "win32" ? `${ansiEscapes.eraseScreen}${ESC2}0f` : `${ansiEscapes.eraseScreen}${ESC2}3J${ESC2}H`;
- ansiEscapes.beep = BEL3;
- ansiEscapes.link = (text, url3) => {
- return [
- OSC3,
- "8",
- SEP2,
- SEP2,
- url3,
- BEL3,
- text,
- OSC3,
- "8",
- SEP2,
- SEP2,
- BEL3
- ].join("");
- };
- ansiEscapes.image = (buffer, options2 = {}) => {
- let ret = `${OSC3}1337;File=inline=1`;
- if (options2.width) {
- ret += `;width=${options2.width}`;
- }
- if (options2.height) {
- ret += `;height=${options2.height}`;
- }
- if (options2.preserveAspectRatio === false) {
- ret += ";preserveAspectRatio=0";
- }
- return ret + ":" + buffer.toString("base64") + BEL3;
- };
- ansiEscapes.iTerm = {
- setCwd: (cwd2 = process.cwd()) => `${OSC3}50;CurrentDir=${cwd2}${BEL3}`,
- annotation: (message, options2 = {}) => {
- let ret = `${OSC3}1337;`;
- const hasX = typeof options2.x !== "undefined";
- const hasY = typeof options2.y !== "undefined";
- if ((hasX || hasY) && !(hasX && hasY && typeof options2.length !== "undefined")) {
- throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");
- }
- message = message.replace(/\|/g, "");
- ret += options2.isHidden ? "AddHiddenAnnotation=" : "AddAnnotation=";
- if (options2.length > 0) {
- ret += (hasX ? [message, options2.length, options2.x, options2.y] : [options2.length, message]).join("|");
- } else {
- ret += message;
- }
- return ret + BEL3;
- }
- };
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs
-function cursorDown2(n5) {
- return n5 > 0 ? import_ansi_escapes.default.cursorDown(n5) : "";
-}
-
-class ScreenManager {
- rl;
- height = 0;
- extraLinesUnderPrompt = 0;
- cursorPos;
- constructor(rl) {
- this.rl = rl;
- this.rl = rl;
- this.cursorPos = rl.getCursorPos();
- }
- write(content) {
- this.rl.output.unmute();
- this.rl.output.write(content);
- this.rl.output.mute();
- }
- render(content, bottomContent = "") {
- const promptLine = lastLine(content);
- const rawPromptLine = import_strip_ansi5.default(promptLine);
- let prompt = rawPromptLine;
- if (this.rl.line.length > 0) {
- prompt = prompt.slice(0, -this.rl.line.length);
- }
- this.rl.setPrompt(prompt);
- this.cursorPos = this.rl.getCursorPos();
- const width = readlineWidth();
- content = breakLines(content, width);
- bottomContent = breakLines(bottomContent, width);
- if (rawPromptLine.length % width === 0) {
- content += `
-`;
- }
- let output = content + (bottomContent ? `
-` + bottomContent : "");
- const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - this.cursorPos.rows;
- const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0);
- if (bottomContentHeight > 0)
- output += import_ansi_escapes.default.cursorUp(bottomContentHeight);
- output += import_ansi_escapes.default.cursorTo(this.cursorPos.cols);
- this.write(cursorDown2(this.extraLinesUnderPrompt) + import_ansi_escapes.default.eraseLines(this.height) + output);
- this.extraLinesUnderPrompt = bottomContentHeight;
- this.height = height(output);
- }
- checkCursorPos() {
- const cursorPos = this.rl.getCursorPos();
- if (cursorPos.cols !== this.cursorPos.cols) {
- this.write(import_ansi_escapes.default.cursorTo(cursorPos.cols));
- this.cursorPos = cursorPos;
- }
- }
- done({ clearContent }) {
- this.rl.setPrompt("");
- let output = cursorDown2(this.extraLinesUnderPrompt);
- output += clearContent ? import_ansi_escapes.default.eraseLines(this.height) : `
-`;
- output += import_ansi_escapes.default.cursorShow;
- this.write(output);
- this.rl.close();
- }
-}
-var import_strip_ansi5, import_ansi_escapes, height = (content) => content.split(`
-`).length, lastLine = (content) => content.split(`
-`).pop() ?? "";
-var init_screen_manager = __esm(() => {
- init_utils6();
- import_strip_ansi5 = __toESM(require_strip_ansi(), 1);
- import_ansi_escapes = __toESM(require_ansi_escapes(), 1);
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/promise-polyfill.mjs
-var PromisePolyfill;
-var init_promise_polyfill = __esm(() => {
- PromisePolyfill = class PromisePolyfill extends Promise {
- static withResolver() {
- let resolve10;
- let reject;
- const promise2 = new Promise((res, rej) => {
- resolve10 = res;
- reject = rej;
- });
- return { promise: promise2, resolve: resolve10, reject };
- }
- };
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs
-import * as readline2 from "readline";
-import { AsyncResource as AsyncResource3 } from "async_hooks";
-function createPrompt(view) {
- const prompt = (config8, context4 = {}) => {
- const { input = process.stdin, signal } = context4;
- const cleanups = new Set;
- const output = new import_mute_stream.default;
- output.pipe(context4.output ?? process.stdout);
- const rl = readline2.createInterface({
- terminal: true,
- input,
- output
- });
- const screen = new ScreenManager(rl);
- const { promise: promise2, resolve: resolve10, reject } = PromisePolyfill.withResolver();
- const cancel = () => reject(new CancelPromptError);
- if (signal) {
- const abort7 = () => reject(new AbortPromptError({ cause: signal.reason }));
- if (signal.aborted) {
- abort7();
- return Object.assign(promise2, { cancel });
- }
- signal.addEventListener("abort", abort7);
- cleanups.add(() => signal.removeEventListener("abort", abort7));
- }
- cleanups.add(onExit((code, signal2) => {
- reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal2}`));
- }));
- const checkCursorPos = () => screen.checkCursorPos();
- rl.input.on("keypress", checkCursorPos);
- cleanups.add(() => rl.input.removeListener("keypress", checkCursorPos));
- return withHooks(rl, (cycle) => {
- const hooksCleanup = AsyncResource3.bind(() => effectScheduler.clearAll());
- rl.on("close", hooksCleanup);
- cleanups.add(() => rl.removeListener("close", hooksCleanup));
- cycle(() => {
- try {
- const nextView = view(config8, (value) => {
- setImmediate(() => resolve10(value));
- });
- const [content, bottomContent] = typeof nextView === "string" ? [nextView] : nextView;
- screen.render(content, bottomContent);
- effectScheduler.run();
- } catch (error46) {
- reject(error46);
- }
- });
- return Object.assign(promise2.then((answer) => {
- effectScheduler.clearAll();
- return answer;
- }, (error46) => {
- effectScheduler.clearAll();
- throw error46;
- }).finally(() => {
- cleanups.forEach((cleanup) => cleanup());
- screen.done({ clearContent: Boolean(context4?.clearPromptOnDone) });
- output.end();
- }).then(() => promise2), { cancel });
- });
- };
- return prompt;
-}
-var import_mute_stream;
-var init_create_prompt = __esm(() => {
- init_mjs();
- init_screen_manager();
- init_promise_polyfill();
- init_hook_engine();
- init_errors8();
- import_mute_stream = __toESM(require_lib(), 1);
-});
-
-// node_modules/@inquirer/core/dist/esm/lib/Separator.mjs
-class Separator {
- separator = import_yoctocolors_cjs2.default.dim(Array.from({ length: 15 }).join(esm_default.line));
- type = "separator";
- constructor(separator) {
- if (separator) {
- this.separator = separator;
- }
- }
- static isSeparator(choice) {
- return Boolean(choice && typeof choice === "object" && "type" in choice && choice.type === "separator");
- }
-}
-var import_yoctocolors_cjs2;
-var init_Separator = __esm(() => {
- init_esm12();
- import_yoctocolors_cjs2 = __toESM(require_yoctocolors_cjs(), 1);
-});
-
-// node_modules/@inquirer/core/dist/esm/index.mjs
-var init_esm13 = __esm(() => {
- init_use_prefix();
- init_use_state();
- init_use_effect();
- init_use_memo();
- init_use_ref();
- init_use_keypress();
- init_make_theme();
- init_use_pagination();
- init_create_prompt();
- init_Separator();
- init_errors8();
-});
-
-// node_modules/@inquirer/confirm/dist/esm/index.mjs
-var esm_default2;
-var init_esm14 = __esm(() => {
- init_esm13();
- esm_default2 = createPrompt((config8, done) => {
- const { transformer = (answer) => answer ? "yes" : "no" } = config8;
- const [status, setStatus] = useState8("idle");
- const [value, setValue2] = useState8("");
- const theme = makeTheme(config8.theme);
- const prefix = usePrefix({ status, theme });
- useKeypress((key2, rl) => {
- if (isEnterKey(key2)) {
- let answer = config8.default !== false;
- if (/^(y|yes)/i.test(value))
- answer = true;
- else if (/^(n|no)/i.test(value))
- answer = false;
- setValue2(transformer(answer));
- setStatus("done");
- done(answer);
- } else {
- setValue2(rl.line);
- }
- });
- let formattedValue = value;
- let defaultValue = "";
- if (status === "done") {
- formattedValue = theme.style.answer(value);
- } else {
- defaultValue = ` ${theme.style.defaultAnswer(config8.default === false ? "y/N" : "Y/n")}`;
- }
- const message = theme.style.message(config8.message, status);
- return `${prefix} ${message}${defaultValue} ${formattedValue}`;
- });
-});
-
-// node_modules/@inquirer/input/dist/esm/index.mjs
-var esm_default3;
-var init_esm15 = __esm(() => {
- init_esm13();
- esm_default3 = createPrompt((config8, done) => {
- const { required: required2, validate: validate3 = () => true } = config8;
- const theme = makeTheme(config8.theme);
- const [status, setStatus] = useState8("idle");
- const [defaultValue = "", setDefaultValue] = useState8(config8.default);
- const [errorMsg, setError] = useState8();
- const [value, setValue2] = useState8("");
- const prefix = usePrefix({ status, theme });
- useKeypress(async (key2, rl) => {
- if (status !== "idle") {
- return;
- }
- if (isEnterKey(key2)) {
- const answer = value || defaultValue;
- setStatus("loading");
- const isValid = required2 && !answer ? "You must provide a value" : await validate3(answer);
- if (isValid === true) {
- setValue2(answer);
- setStatus("done");
- done(answer);
- } else {
- rl.write(value);
- setError(isValid || "You must provide a valid value");
- setStatus("idle");
- }
- } else if (isBackspaceKey(key2) && !value) {
- setDefaultValue(undefined);
- } else if (key2.name === "tab" && !value) {
- setDefaultValue(undefined);
- rl.clearLine(0);
- rl.write(defaultValue);
- setValue2(defaultValue);
- } else {
- setValue2(rl.line);
- setError(undefined);
- }
- });
- const message = theme.style.message(config8.message, status);
- let formattedValue = value;
- if (typeof config8.transformer === "function") {
- formattedValue = config8.transformer(value, { isFinal: status === "done" });
- } else if (status === "done") {
- formattedValue = theme.style.answer(value);
- }
- let defaultStr;
- if (defaultValue && status !== "done" && !value) {
- defaultStr = theme.style.defaultAnswer(defaultValue);
- }
- let error46 = "";
- if (errorMsg) {
- error46 = theme.style.error(errorMsg);
- }
- return [
- [prefix, message, defaultStr, formattedValue].filter((v6) => v6 !== undefined).join(" "),
- error46
- ];
- });
-});
-
-// node_modules/@inquirer/select/node_modules/ansi-escapes/index.js
-var require_ansi_escapes2 = __commonJS((exports, module) => {
- var ansiEscapes2 = exports;
- exports.default = ansiEscapes2;
- var ESC2 = "\x1B[";
- var OSC3 = "\x1B]";
- var BEL3 = "\x07";
- var SEP2 = ";";
- var isTerminalApp = process.env.TERM_PROGRAM === "Apple_Terminal";
- ansiEscapes2.cursorTo = (x3, y3) => {
- if (typeof x3 !== "number") {
- throw new TypeError("The `x` argument is required");
- }
- if (typeof y3 !== "number") {
- return ESC2 + (x3 + 1) + "G";
- }
- return ESC2 + (y3 + 1) + ";" + (x3 + 1) + "H";
- };
- ansiEscapes2.cursorMove = (x3, y3) => {
- if (typeof x3 !== "number") {
- throw new TypeError("The `x` argument is required");
- }
- let ret = "";
- if (x3 < 0) {
- ret += ESC2 + -x3 + "D";
- } else if (x3 > 0) {
- ret += ESC2 + x3 + "C";
- }
- if (y3 < 0) {
- ret += ESC2 + -y3 + "A";
- } else if (y3 > 0) {
- ret += ESC2 + y3 + "B";
- }
- return ret;
- };
- ansiEscapes2.cursorUp = (count3 = 1) => ESC2 + count3 + "A";
- ansiEscapes2.cursorDown = (count3 = 1) => ESC2 + count3 + "B";
- ansiEscapes2.cursorForward = (count3 = 1) => ESC2 + count3 + "C";
- ansiEscapes2.cursorBackward = (count3 = 1) => ESC2 + count3 + "D";
- ansiEscapes2.cursorLeft = ESC2 + "G";
- ansiEscapes2.cursorSavePosition = isTerminalApp ? "\x1B7" : ESC2 + "s";
- ansiEscapes2.cursorRestorePosition = isTerminalApp ? "\x1B8" : ESC2 + "u";
- ansiEscapes2.cursorGetPosition = ESC2 + "6n";
- ansiEscapes2.cursorNextLine = ESC2 + "E";
- ansiEscapes2.cursorPrevLine = ESC2 + "F";
- ansiEscapes2.cursorHide = ESC2 + "?25l";
- ansiEscapes2.cursorShow = ESC2 + "?25h";
- ansiEscapes2.eraseLines = (count3) => {
- let clear = "";
- for (let i5 = 0;i5 < count3; i5++) {
- clear += ansiEscapes2.eraseLine + (i5 < count3 - 1 ? ansiEscapes2.cursorUp() : "");
- }
- if (count3) {
- clear += ansiEscapes2.cursorLeft;
- }
- return clear;
- };
- ansiEscapes2.eraseEndLine = ESC2 + "K";
- ansiEscapes2.eraseStartLine = ESC2 + "1K";
- ansiEscapes2.eraseLine = ESC2 + "2K";
- ansiEscapes2.eraseDown = ESC2 + "J";
- ansiEscapes2.eraseUp = ESC2 + "1J";
- ansiEscapes2.eraseScreen = ESC2 + "2J";
- ansiEscapes2.scrollUp = ESC2 + "S";
- ansiEscapes2.scrollDown = ESC2 + "T";
- ansiEscapes2.clearScreen = "\x1Bc";
- ansiEscapes2.clearTerminal = process.platform === "win32" ? `${ansiEscapes2.eraseScreen}${ESC2}0f` : `${ansiEscapes2.eraseScreen}${ESC2}3J${ESC2}H`;
- ansiEscapes2.beep = BEL3;
- ansiEscapes2.link = (text, url3) => {
- return [
- OSC3,
- "8",
- SEP2,
- SEP2,
- url3,
- BEL3,
- text,
- OSC3,
- "8",
- SEP2,
- SEP2,
- BEL3
- ].join("");
- };
- ansiEscapes2.image = (buffer, options2 = {}) => {
- let ret = `${OSC3}1337;File=inline=1`;
- if (options2.width) {
- ret += `;width=${options2.width}`;
- }
- if (options2.height) {
- ret += `;height=${options2.height}`;
- }
- if (options2.preserveAspectRatio === false) {
- ret += ";preserveAspectRatio=0";
- }
- return ret + ":" + buffer.toString("base64") + BEL3;
- };
- ansiEscapes2.iTerm = {
- setCwd: (cwd2 = process.cwd()) => `${OSC3}50;CurrentDir=${cwd2}${BEL3}`,
- annotation: (message, options2 = {}) => {
- let ret = `${OSC3}1337;`;
- const hasX = typeof options2.x !== "undefined";
- const hasY = typeof options2.y !== "undefined";
- if ((hasX || hasY) && !(hasX && hasY && typeof options2.length !== "undefined")) {
- throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");
- }
- message = message.replace(/\|/g, "");
- ret += options2.isHidden ? "AddHiddenAnnotation=" : "AddAnnotation=";
- if (options2.length > 0) {
- ret += (hasX ? [message, options2.length, options2.x, options2.y] : [options2.length, message]).join("|");
- } else {
- ret += message;
- }
- return ret + BEL3;
- }
- };
-});
-
-// node_modules/@inquirer/select/dist/esm/index.mjs
-function isSelectable(item) {
- return !Separator.isSeparator(item) && !item.disabled;
-}
-function normalizeChoices(choices) {
- return choices.map((choice) => {
- if (Separator.isSeparator(choice))
- return choice;
- if (typeof choice === "string") {
- return {
- value: choice,
- name: choice,
- short: choice,
- disabled: false
- };
- }
- const name3 = choice.name ?? String(choice.value);
- return {
- value: choice.value,
- name: name3,
- description: choice.description,
- short: choice.short ?? name3,
- disabled: choice.disabled ?? false
- };
- });
-}
-var import_yoctocolors_cjs3, import_ansi_escapes2, selectTheme, esm_default4;
-var init_esm16 = __esm(() => {
- init_esm13();
- init_esm12();
- import_yoctocolors_cjs3 = __toESM(require_yoctocolors_cjs(), 1);
- import_ansi_escapes2 = __toESM(require_ansi_escapes2(), 1);
- selectTheme = {
- icon: { cursor: esm_default.pointer },
- style: {
- disabled: (text) => import_yoctocolors_cjs3.default.dim(`- ${text}`),
- description: (text) => import_yoctocolors_cjs3.default.cyan(text)
- },
- helpMode: "auto"
- };
- esm_default4 = createPrompt((config8, done) => {
- const { loop = true, pageSize = 7 } = config8;
- const firstRender = useRef7(true);
- const theme = makeTheme(selectTheme, config8.theme);
- const [status, setStatus] = useState8("idle");
- const prefix = usePrefix({ status, theme });
- const searchTimeoutRef = useRef7();
- const items = useMemo6(() => normalizeChoices(config8.choices), [config8.choices]);
- const bounds = useMemo6(() => {
- const first = items.findIndex(isSelectable);
- const last = items.findLastIndex(isSelectable);
- if (first < 0) {
- throw new ValidationError("[select prompt] No selectable choices. All choices are disabled.");
- }
- return { first, last };
- }, [items]);
- const defaultItemIndex = useMemo6(() => {
- if (!("default" in config8))
- return -1;
- return items.findIndex((item) => isSelectable(item) && item.value === config8.default);
- }, [config8.default, items]);
- const [active, setActive] = useState8(defaultItemIndex === -1 ? bounds.first : defaultItemIndex);
- const selectedChoice = items[active];
- useKeypress((key2, rl) => {
- clearTimeout(searchTimeoutRef.current);
- if (isEnterKey(key2)) {
- setStatus("done");
- done(selectedChoice.value);
- } else if (isUpKey(key2) || isDownKey(key2)) {
- rl.clearLine(0);
- if (loop || isUpKey(key2) && active !== bounds.first || isDownKey(key2) && active !== bounds.last) {
- const offset = isUpKey(key2) ? -1 : 1;
- let next = active;
- do {
- next = (next + offset + items.length) % items.length;
- } while (!isSelectable(items[next]));
- setActive(next);
- }
- } else if (isNumberKey(key2)) {
- rl.clearLine(0);
- const position2 = Number(key2.name) - 1;
- const item = items[position2];
- if (item != null && isSelectable(item)) {
- setActive(position2);
- }
- } else if (isBackspaceKey(key2)) {
- rl.clearLine(0);
- } else {
- const searchTerm = rl.line.toLowerCase();
- const matchIndex = items.findIndex((item) => {
- if (Separator.isSeparator(item) || !isSelectable(item))
- return false;
- return item.name.toLowerCase().startsWith(searchTerm);
- });
- if (matchIndex >= 0) {
- setActive(matchIndex);
- }
- searchTimeoutRef.current = setTimeout(() => {
- rl.clearLine(0);
- }, 700);
- }
- });
- useEffect10(() => () => {
- clearTimeout(searchTimeoutRef.current);
- }, []);
- const message = theme.style.message(config8.message, status);
- let helpTipTop = "";
- let helpTipBottom = "";
- if (theme.helpMode === "always" || theme.helpMode === "auto" && firstRender.current) {
- firstRender.current = false;
- if (items.length > pageSize) {
- helpTipBottom = `
-${theme.style.help("(Use arrow keys to reveal more choices)")}`;
- } else {
- helpTipTop = theme.style.help("(Use arrow keys)");
- }
- }
- const page = usePagination({
- items,
- active,
- renderItem({ item, isActive }) {
- if (Separator.isSeparator(item)) {
- return ` ${item.separator}`;
- }
- if (item.disabled) {
- const disabledLabel = typeof item.disabled === "string" ? item.disabled : "(disabled)";
- return theme.style.disabled(`${item.name} ${disabledLabel}`);
- }
- const color2 = isActive ? theme.style.highlight : (x3) => x3;
- const cursor = isActive ? theme.icon.cursor : ` `;
- return color2(`${cursor} ${item.name}`);
- },
- pageSize,
- loop
- });
- if (status === "done") {
- return `${prefix} ${message} ${theme.style.answer(selectedChoice.short)}`;
- }
- const choiceDescription = selectedChoice.description ? `
-${theme.style.description(selectedChoice.description)}` : ``;
- return `${[prefix, message, helpTipTop].filter(Boolean).join(" ")}
-${page}${helpTipBottom}${choiceDescription}${import_ansi_escapes2.default.cursorHide}`;
- });
-});
-
-// node_modules/@inquirer/prompts/dist/esm/index.mjs
-var init_esm17 = __esm(() => {
- init_esm14();
- init_esm15();
- init_esm16();
-});
-
-// node_modules/zod/v3/helpers/util.js
-var util10, objectUtil, ZodParsedType, getParsedType2 = (data) => {
- const t4 = typeof data;
- switch (t4) {
- case "undefined":
- return ZodParsedType.undefined;
- case "string":
- return ZodParsedType.string;
- case "number":
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
- case "boolean":
- return ZodParsedType.boolean;
- case "function":
- return ZodParsedType.function;
- case "bigint":
- return ZodParsedType.bigint;
- case "symbol":
- return ZodParsedType.symbol;
- case "object":
- if (Array.isArray(data)) {
- return ZodParsedType.array;
- }
- if (data === null) {
- return ZodParsedType.null;
- }
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
- return ZodParsedType.promise;
- }
- if (typeof Map !== "undefined" && data instanceof Map) {
- return ZodParsedType.map;
- }
- if (typeof Set !== "undefined" && data instanceof Set) {
- return ZodParsedType.set;
- }
- if (typeof Date !== "undefined" && data instanceof Date) {
- return ZodParsedType.date;
- }
- return ZodParsedType.object;
- default:
- return ZodParsedType.unknown;
- }
-};
-var init_util9 = __esm(() => {
- (function(util11) {
- util11.assertEqual = (_) => {};
- function assertIs2(_arg) {}
- util11.assertIs = assertIs2;
- function assertNever2(_x) {
- throw new Error;
- }
- util11.assertNever = assertNever2;
- util11.arrayToEnum = (items) => {
- const obj = {};
- for (const item of items) {
- obj[item] = item;
- }
- return obj;
- };
- util11.getValidEnumValues = (obj) => {
- const validKeys = util11.objectKeys(obj).filter((k4) => typeof obj[obj[k4]] !== "number");
- const filtered = {};
- for (const k4 of validKeys) {
- filtered[k4] = obj[k4];
- }
- return util11.objectValues(filtered);
- };
- util11.objectValues = (obj) => {
- return util11.objectKeys(obj).map(function(e4) {
- return obj[e4];
- });
- };
- util11.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
- const keys2 = [];
- for (const key2 in object2) {
- if (Object.prototype.hasOwnProperty.call(object2, key2)) {
- keys2.push(key2);
- }
- }
- return keys2;
- };
- util11.find = (arr, checker) => {
- for (const item of arr) {
- if (checker(item))
- return item;
- }
- return;
- };
- util11.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
- function joinValues2(array2, separator = " | ") {
- return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
- }
- util11.joinValues = joinValues2;
- util11.jsonStringifyReplacer = (_, value) => {
- if (typeof value === "bigint") {
- return value.toString();
- }
- return value;
- };
- })(util10 || (util10 = {}));
- (function(objectUtil2) {
- objectUtil2.mergeShapes = (first, second) => {
- return {
- ...first,
- ...second
- };
- };
- })(objectUtil || (objectUtil = {}));
- ZodParsedType = util10.arrayToEnum([
- "string",
- "nan",
- "number",
- "integer",
- "float",
- "boolean",
- "date",
- "bigint",
- "symbol",
- "function",
- "undefined",
- "null",
- "array",
- "object",
- "unknown",
- "promise",
- "void",
- "never",
- "map",
- "set"
- ]);
-});
-
-// node_modules/zod/v3/ZodError.js
-var ZodIssueCode2, quotelessJson = (obj) => {
- const json2 = JSON.stringify(obj, null, 2);
- return json2.replace(/"([^"]+)":/g, "$1:");
-}, ZodError2;
-var init_ZodError = __esm(() => {
- init_util9();
- ZodIssueCode2 = util10.arrayToEnum([
- "invalid_type",
- "invalid_literal",
- "custom",
- "invalid_union",
- "invalid_union_discriminator",
- "invalid_enum_value",
- "unrecognized_keys",
- "invalid_arguments",
- "invalid_return_type",
- "invalid_date",
- "invalid_string",
- "too_small",
- "too_big",
- "invalid_intersection_types",
- "not_multiple_of",
- "not_finite"
- ]);
- ZodError2 = class ZodError2 extends Error {
- get errors() {
- return this.issues;
- }
- constructor(issues) {
- super();
- this.issues = [];
- this.addIssue = (sub) => {
- this.issues = [...this.issues, sub];
- };
- this.addIssues = (subs = []) => {
- this.issues = [...this.issues, ...subs];
- };
- const actualProto = new.target.prototype;
- if (Object.setPrototypeOf) {
- Object.setPrototypeOf(this, actualProto);
- } else {
- this.__proto__ = actualProto;
- }
- this.name = "ZodError";
- this.issues = issues;
- }
- format(_mapper) {
- const mapper = _mapper || function(issue2) {
- return issue2.message;
- };
- const fieldErrors = { _errors: [] };
- const processError = (error46) => {
- for (const issue2 of error46.issues) {
- if (issue2.code === "invalid_union") {
- issue2.unionErrors.map(processError);
- } else if (issue2.code === "invalid_return_type") {
- processError(issue2.returnTypeError);
- } else if (issue2.code === "invalid_arguments") {
- processError(issue2.argumentsError);
- } else if (issue2.path.length === 0) {
- fieldErrors._errors.push(mapper(issue2));
- } else {
- let curr = fieldErrors;
- let i5 = 0;
- while (i5 < issue2.path.length) {
- const el = issue2.path[i5];
- const terminal = i5 === issue2.path.length - 1;
- if (!terminal) {
- curr[el] = curr[el] || { _errors: [] };
- } else {
- curr[el] = curr[el] || { _errors: [] };
- curr[el]._errors.push(mapper(issue2));
- }
- curr = curr[el];
- i5++;
- }
- }
- }
- };
- processError(this);
- return fieldErrors;
- }
- static assert(value) {
- if (!(value instanceof ZodError2)) {
- throw new Error(`Not a ZodError: ${value}`);
- }
- }
- toString() {
- return this.message;
- }
- get message() {
- return JSON.stringify(this.issues, util10.jsonStringifyReplacer, 2);
- }
- get isEmpty() {
- return this.issues.length === 0;
- }
- flatten(mapper = (issue2) => issue2.message) {
- const fieldErrors = {};
- const formErrors = [];
- for (const sub of this.issues) {
- if (sub.path.length > 0) {
- const firstEl = sub.path[0];
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
- fieldErrors[firstEl].push(mapper(sub));
- } else {
- formErrors.push(mapper(sub));
- }
- }
- return { formErrors, fieldErrors };
- }
- get formErrors() {
- return this.flatten();
- }
- };
- ZodError2.create = (issues) => {
- const error46 = new ZodError2(issues);
- return error46;
- };
-});
-
-// node_modules/zod/v3/locales/en.js
-var errorMap = (issue2, _ctx) => {
- let message;
- switch (issue2.code) {
- case ZodIssueCode2.invalid_type:
- if (issue2.received === ZodParsedType.undefined) {
- message = "Required";
- } else {
- message = `Expected ${issue2.expected}, received ${issue2.received}`;
- }
- break;
- case ZodIssueCode2.invalid_literal:
- message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util10.jsonStringifyReplacer)}`;
- break;
- case ZodIssueCode2.unrecognized_keys:
- message = `Unrecognized key(s) in object: ${util10.joinValues(issue2.keys, ", ")}`;
- break;
- case ZodIssueCode2.invalid_union:
- message = `Invalid input`;
- break;
- case ZodIssueCode2.invalid_union_discriminator:
- message = `Invalid discriminator value. Expected ${util10.joinValues(issue2.options)}`;
- break;
- case ZodIssueCode2.invalid_enum_value:
- message = `Invalid enum value. Expected ${util10.joinValues(issue2.options)}, received '${issue2.received}'`;
- break;
- case ZodIssueCode2.invalid_arguments:
- message = `Invalid function arguments`;
- break;
- case ZodIssueCode2.invalid_return_type:
- message = `Invalid function return type`;
- break;
- case ZodIssueCode2.invalid_date:
- message = `Invalid date`;
- break;
- case ZodIssueCode2.invalid_string:
- if (typeof issue2.validation === "object") {
- if ("includes" in issue2.validation) {
- message = `Invalid input: must include "${issue2.validation.includes}"`;
- if (typeof issue2.validation.position === "number") {
- message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`;
- }
- } else if ("startsWith" in issue2.validation) {
- message = `Invalid input: must start with "${issue2.validation.startsWith}"`;
- } else if ("endsWith" in issue2.validation) {
- message = `Invalid input: must end with "${issue2.validation.endsWith}"`;
- } else {
- util10.assertNever(issue2.validation);
- }
- } else if (issue2.validation !== "regex") {
- message = `Invalid ${issue2.validation}`;
- } else {
- message = "Invalid";
- }
- break;
- case ZodIssueCode2.too_small:
- if (issue2.type === "array")
- message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`;
- else if (issue2.type === "string")
- message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`;
- else if (issue2.type === "number")
- message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
- else if (issue2.type === "bigint")
- message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
- else if (issue2.type === "date")
- message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`;
- else
- message = "Invalid input";
- break;
- case ZodIssueCode2.too_big:
- if (issue2.type === "array")
- message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`;
- else if (issue2.type === "string")
- message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`;
- else if (issue2.type === "number")
- message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
- else if (issue2.type === "bigint")
- message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
- else if (issue2.type === "date")
- message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`;
- else
- message = "Invalid input";
- break;
- case ZodIssueCode2.custom:
- message = `Invalid input`;
- break;
- case ZodIssueCode2.invalid_intersection_types:
- message = `Intersection results could not be merged`;
- break;
- case ZodIssueCode2.not_multiple_of:
- message = `Number must be a multiple of ${issue2.multipleOf}`;
- break;
- case ZodIssueCode2.not_finite:
- message = "Number must be finite";
- break;
- default:
- message = _ctx.defaultError;
- util10.assertNever(issue2);
- }
- return { message };
-}, en_default2;
-var init_en2 = __esm(() => {
- init_ZodError();
- init_util9();
- en_default2 = errorMap;
-});
-
-// node_modules/zod/v3/errors.js
-function setErrorMap2(map7) {
- overrideErrorMap = map7;
-}
-function getErrorMap2() {
- return overrideErrorMap;
-}
-var overrideErrorMap;
-var init_errors9 = __esm(() => {
- init_en2();
- overrideErrorMap = en_default2;
-});
-
-// node_modules/zod/v3/helpers/parseUtil.js
-function addIssueToContext(ctx, issueData) {
- const overrideMap = getErrorMap2();
- const issue2 = makeIssue({
- issueData,
- data: ctx.data,
- path: ctx.path,
- errorMaps: [
- ctx.common.contextualErrorMap,
- ctx.schemaErrorMap,
- overrideMap,
- overrideMap === en_default2 ? undefined : en_default2
- ].filter((x3) => !!x3)
- });
- ctx.common.issues.push(issue2);
-}
-
-class ParseStatus {
- constructor() {
- this.value = "valid";
- }
- dirty() {
- if (this.value === "valid")
- this.value = "dirty";
- }
- abort() {
- if (this.value !== "aborted")
- this.value = "aborted";
- }
- static mergeArray(status, results) {
- const arrayValue = [];
- for (const s4 of results) {
- if (s4.status === "aborted")
- return INVALID;
- if (s4.status === "dirty")
- status.dirty();
- arrayValue.push(s4.value);
- }
- return { status: status.value, value: arrayValue };
- }
- static async mergeObjectAsync(status, pairs) {
- const syncPairs = [];
- for (const pair of pairs) {
- const key2 = await pair.key;
- const value = await pair.value;
- syncPairs.push({
- key: key2,
- value
- });
- }
- return ParseStatus.mergeObjectSync(status, syncPairs);
- }
- static mergeObjectSync(status, pairs) {
- const finalObject = {};
- for (const pair of pairs) {
- const { key: key2, value } = pair;
- if (key2.status === "aborted")
- return INVALID;
- if (value.status === "aborted")
- return INVALID;
- if (key2.status === "dirty")
- status.dirty();
- if (value.status === "dirty")
- status.dirty();
- if (key2.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
- finalObject[key2.value] = value.value;
- }
- }
- return { status: status.value, value: finalObject };
- }
-}
-var makeIssue = (params) => {
- const { data, path: path15, errorMaps, issueData } = params;
- const fullPath = [...path15, ...issueData.path || []];
- const fullIssue = {
- ...issueData,
- path: fullPath
- };
- if (issueData.message !== undefined) {
- return {
- ...issueData,
- path: fullPath,
- message: issueData.message
- };
- }
- let errorMessage2 = "";
- const maps = errorMaps.filter((m4) => !!m4).slice().reverse();
- for (const map7 of maps) {
- errorMessage2 = map7(fullIssue, { data, defaultError: errorMessage2 }).message;
- }
- return {
- ...issueData,
- path: fullPath,
- message: errorMessage2
- };
-}, EMPTY_PATH, INVALID, DIRTY = (value) => ({ status: "dirty", value }), OK = (value) => ({ status: "valid", value }), isAborted = (x3) => x3.status === "aborted", isDirty = (x3) => x3.status === "dirty", isValid = (x3) => x3.status === "valid", isAsync = (x3) => typeof Promise !== "undefined" && x3 instanceof Promise;
-var init_parseUtil = __esm(() => {
- init_errors9();
- init_en2();
- EMPTY_PATH = [];
- INVALID = Object.freeze({
- status: "aborted"
- });
-});
-
-// node_modules/zod/v3/helpers/typeAliases.js
-var init_typeAliases = () => {};
-
-// node_modules/zod/v3/helpers/errorUtil.js
-var errorUtil;
-var init_errorUtil = __esm(() => {
- (function(errorUtil2) {
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
- errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
- })(errorUtil || (errorUtil = {}));
-});
-
-// node_modules/zod/v3/types.js
-class ParseInputLazyPath {
- constructor(parent, value, path15, key2) {
- this._cachedPath = [];
- this.parent = parent;
- this.data = value;
- this._path = path15;
- this._key = key2;
- }
- get path() {
- if (!this._cachedPath.length) {
- if (Array.isArray(this._key)) {
- this._cachedPath.push(...this._path, ...this._key);
- } else {
- this._cachedPath.push(...this._path, this._key);
- }
- }
- return this._cachedPath;
- }
-}
-function processCreateParams(params) {
- if (!params)
- return {};
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
- if (errorMap2 && (invalid_type_error || required_error)) {
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
- }
- if (errorMap2)
- return { errorMap: errorMap2, description };
- const customMap = (iss, ctx) => {
- const { message } = params;
- if (iss.code === "invalid_enum_value") {
- return { message: message ?? ctx.defaultError };
- }
- if (typeof ctx.data === "undefined") {
- return { message: message ?? required_error ?? ctx.defaultError };
- }
- if (iss.code !== "invalid_type")
- return { message: ctx.defaultError };
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
- };
- return { errorMap: customMap, description };
-}
-
-class ZodType2 {
- get description() {
- return this._def.description;
- }
- _getType(input) {
- return getParsedType2(input.data);
- }
- _getOrReturnCtx(input, ctx) {
- return ctx || {
- common: input.parent.common,
- data: input.data,
- parsedType: getParsedType2(input.data),
- schemaErrorMap: this._def.errorMap,
- path: input.path,
- parent: input.parent
- };
- }
- _processInputParams(input) {
- return {
- status: new ParseStatus,
- ctx: {
- common: input.parent.common,
- data: input.data,
- parsedType: getParsedType2(input.data),
- schemaErrorMap: this._def.errorMap,
- path: input.path,
- parent: input.parent
- }
- };
- }
- _parseSync(input) {
- const result = this._parse(input);
- if (isAsync(result)) {
- throw new Error("Synchronous parse encountered promise.");
- }
- return result;
- }
- _parseAsync(input) {
- const result = this._parse(input);
- return Promise.resolve(result);
- }
- parse(data, params) {
- const result = this.safeParse(data, params);
- if (result.success)
- return result.data;
- throw result.error;
- }
- safeParse(data, params) {
- const ctx = {
- common: {
- issues: [],
- async: params?.async ?? false,
- contextualErrorMap: params?.errorMap
- },
- path: params?.path || [],
- schemaErrorMap: this._def.errorMap,
- parent: null,
- data,
- parsedType: getParsedType2(data)
- };
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
- return handleResult2(ctx, result);
- }
- "~validate"(data) {
- const ctx = {
- common: {
- issues: [],
- async: !!this["~standard"].async
- },
- path: [],
- schemaErrorMap: this._def.errorMap,
- parent: null,
- data,
- parsedType: getParsedType2(data)
- };
- if (!this["~standard"].async) {
- try {
- const result = this._parseSync({ data, path: [], parent: ctx });
- return isValid(result) ? {
- value: result.value
- } : {
- issues: ctx.common.issues
- };
- } catch (err) {
- if (err?.message?.toLowerCase()?.includes("encountered")) {
- this["~standard"].async = true;
- }
- ctx.common = {
- issues: [],
- async: true
- };
- }
- }
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
- value: result.value
- } : {
- issues: ctx.common.issues
- });
- }
- async parseAsync(data, params) {
- const result = await this.safeParseAsync(data, params);
- if (result.success)
- return result.data;
- throw result.error;
- }
- async safeParseAsync(data, params) {
- const ctx = {
- common: {
- issues: [],
- contextualErrorMap: params?.errorMap,
- async: true
- },
- path: params?.path || [],
- schemaErrorMap: this._def.errorMap,
- parent: null,
- data,
- parsedType: getParsedType2(data)
- };
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
- return handleResult2(ctx, result);
- }
- refine(check3, message) {
- const getIssueProperties = (val) => {
- if (typeof message === "string" || typeof message === "undefined") {
- return { message };
- } else if (typeof message === "function") {
- return message(val);
- } else {
- return message;
- }
- };
- return this._refinement((val, ctx) => {
- const result = check3(val);
- const setError = () => ctx.addIssue({
- code: ZodIssueCode2.custom,
- ...getIssueProperties(val)
- });
- if (typeof Promise !== "undefined" && result instanceof Promise) {
- return result.then((data) => {
- if (!data) {
- setError();
- return false;
- } else {
- return true;
- }
- });
- }
- if (!result) {
- setError();
- return false;
- } else {
- return true;
- }
- });
- }
- refinement(check3, refinementData) {
- return this._refinement((val, ctx) => {
- if (!check3(val)) {
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
- return false;
- } else {
- return true;
- }
- });
- }
- _refinement(refinement) {
- return new ZodEffects({
- schema: this,
- typeName: ZodFirstPartyTypeKind.ZodEffects,
- effect: { type: "refinement", refinement }
- });
- }
- superRefine(refinement) {
- return this._refinement(refinement);
- }
- constructor(def2) {
- this.spa = this.safeParseAsync;
- this._def = def2;
- this.parse = this.parse.bind(this);
- this.safeParse = this.safeParse.bind(this);
- this.parseAsync = this.parseAsync.bind(this);
- this.safeParseAsync = this.safeParseAsync.bind(this);
- this.spa = this.spa.bind(this);
- this.refine = this.refine.bind(this);
- this.refinement = this.refinement.bind(this);
- this.superRefine = this.superRefine.bind(this);
- this.optional = this.optional.bind(this);
- this.nullable = this.nullable.bind(this);
- this.nullish = this.nullish.bind(this);
- this.array = this.array.bind(this);
- this.promise = this.promise.bind(this);
- this.or = this.or.bind(this);
- this.and = this.and.bind(this);
- this.transform = this.transform.bind(this);
- this.brand = this.brand.bind(this);
- this.default = this.default.bind(this);
- this.catch = this.catch.bind(this);
- this.describe = this.describe.bind(this);
- this.pipe = this.pipe.bind(this);
- this.readonly = this.readonly.bind(this);
- this.isNullable = this.isNullable.bind(this);
- this.isOptional = this.isOptional.bind(this);
- this["~standard"] = {
- version: 1,
- vendor: "zod",
- validate: (data) => this["~validate"](data)
- };
- }
- optional() {
- return ZodOptional2.create(this, this._def);
- }
- nullable() {
- return ZodNullable2.create(this, this._def);
- }
- nullish() {
- return this.nullable().optional();
- }
- array() {
- return ZodArray2.create(this);
- }
- promise() {
- return ZodPromise2.create(this, this._def);
- }
- or(option) {
- return ZodUnion2.create([this, option], this._def);
- }
- and(incoming) {
- return ZodIntersection2.create(this, incoming, this._def);
- }
- transform(transform2) {
- return new ZodEffects({
- ...processCreateParams(this._def),
- schema: this,
- typeName: ZodFirstPartyTypeKind.ZodEffects,
- effect: { type: "transform", transform: transform2 }
- });
- }
- default(def2) {
- const defaultValueFunc = typeof def2 === "function" ? def2 : () => def2;
- return new ZodDefault2({
- ...processCreateParams(this._def),
- innerType: this,
- defaultValue: defaultValueFunc,
- typeName: ZodFirstPartyTypeKind.ZodDefault
- });
- }
- brand() {
- return new ZodBranded({
- typeName: ZodFirstPartyTypeKind.ZodBranded,
- type: this,
- ...processCreateParams(this._def)
- });
- }
- catch(def2) {
- const catchValueFunc = typeof def2 === "function" ? def2 : () => def2;
- return new ZodCatch2({
- ...processCreateParams(this._def),
- innerType: this,
- catchValue: catchValueFunc,
- typeName: ZodFirstPartyTypeKind.ZodCatch
- });
- }
- describe(description) {
- const This = this.constructor;
- return new This({
- ...this._def,
- description
- });
- }
- pipe(target) {
- return ZodPipeline.create(this, target);
- }
- readonly() {
- return ZodReadonly2.create(this);
- }
- isOptional() {
- return this.safeParse(undefined).success;
- }
- isNullable() {
- return this.safeParse(null).success;
- }
-}
-function timeRegexSource(args) {
- let secondsRegexSource = `[0-5]\\d`;
- if (args.precision) {
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
- } else if (args.precision == null) {
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
- }
- const secondsQuantifier = args.precision ? "+" : "?";
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
-}
-function timeRegex(args) {
- return new RegExp(`^${timeRegexSource(args)}$`);
-}
-function datetimeRegex(args) {
- let regex2 = `${dateRegexSource}T${timeRegexSource(args)}`;
- const opts = [];
- opts.push(args.local ? `Z?` : `Z`);
- if (args.offset)
- opts.push(`([+-]\\d{2}:?\\d{2})`);
- regex2 = `${regex2}(${opts.join("|")})`;
- return new RegExp(`^${regex2}$`);
-}
-function isValidIP(ip, version6) {
- if ((version6 === "v4" || !version6) && ipv4Regex.test(ip)) {
- return true;
- }
- if ((version6 === "v6" || !version6) && ipv6Regex.test(ip)) {
- return true;
- }
- return false;
-}
-function isValidJWT2(jwt3, alg) {
- if (!jwtRegex.test(jwt3))
- return false;
- try {
- const [header] = jwt3.split(".");
- if (!header)
- return false;
- const base644 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
- const decoded = JSON.parse(atob(base644));
- if (typeof decoded !== "object" || decoded === null)
- return false;
- if ("typ" in decoded && decoded?.typ !== "JWT")
- return false;
- if (!decoded.alg)
- return false;
- if (alg && decoded.alg !== alg)
- return false;
- return true;
- } catch {
- return false;
- }
-}
-function isValidCidr(ip, version6) {
- if ((version6 === "v4" || !version6) && ipv4CidrRegex.test(ip)) {
- return true;
- }
- if ((version6 === "v6" || !version6) && ipv6CidrRegex.test(ip)) {
- return true;
- }
- return false;
-}
-function floatSafeRemainder2(val, step) {
- const valDecCount = (val.toString().split(".")[1] || "").length;
- const stepDecCount = (step.toString().split(".")[1] || "").length;
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
- return valInt % stepInt / 10 ** decCount;
-}
-function deepPartialify(schema5) {
- if (schema5 instanceof ZodObject2) {
- const newShape = {};
- for (const key2 in schema5.shape) {
- const fieldSchema = schema5.shape[key2];
- newShape[key2] = ZodOptional2.create(deepPartialify(fieldSchema));
- }
- return new ZodObject2({
- ...schema5._def,
- shape: () => newShape
- });
- } else if (schema5 instanceof ZodArray2) {
- return new ZodArray2({
- ...schema5._def,
- type: deepPartialify(schema5.element)
- });
- } else if (schema5 instanceof ZodOptional2) {
- return ZodOptional2.create(deepPartialify(schema5.unwrap()));
- } else if (schema5 instanceof ZodNullable2) {
- return ZodNullable2.create(deepPartialify(schema5.unwrap()));
- } else if (schema5 instanceof ZodTuple2) {
- return ZodTuple2.create(schema5.items.map((item) => deepPartialify(item)));
- } else {
- return schema5;
- }
-}
-function mergeValues2(a5, b4) {
- const aType = getParsedType2(a5);
- const bType = getParsedType2(b4);
- if (a5 === b4) {
- return { valid: true, data: a5 };
- } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
- const bKeys = util10.objectKeys(b4);
- const sharedKeys = util10.objectKeys(a5).filter((key2) => bKeys.indexOf(key2) !== -1);
- const newObj = { ...a5, ...b4 };
- for (const key2 of sharedKeys) {
- const sharedValue = mergeValues2(a5[key2], b4[key2]);
- if (!sharedValue.valid) {
- return { valid: false };
- }
- newObj[key2] = sharedValue.data;
- }
- return { valid: true, data: newObj };
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
- if (a5.length !== b4.length) {
- return { valid: false };
- }
- const newArray = [];
- for (let index2 = 0;index2 < a5.length; index2++) {
- const itemA = a5[index2];
- const itemB = b4[index2];
- const sharedValue = mergeValues2(itemA, itemB);
- if (!sharedValue.valid) {
- return { valid: false };
- }
- newArray.push(sharedValue.data);
- }
- return { valid: true, data: newArray };
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a5 === +b4) {
- return { valid: true, data: a5 };
- } else {
- return { valid: false };
- }
-}
-function createZodEnum(values2, params) {
- return new ZodEnum2({
- values: values2,
- typeName: ZodFirstPartyTypeKind.ZodEnum,
- ...processCreateParams(params)
- });
-}
-function cleanParams(params, data) {
- const p4 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
- const p22 = typeof p4 === "string" ? { message: p4 } : p4;
- return p22;
-}
-function custom3(check3, _params = {}, fatal) {
- if (check3)
- return ZodAny2.create().superRefine((data, ctx) => {
- const r4 = check3(data);
- if (r4 instanceof Promise) {
- return r4.then((r5) => {
- if (!r5) {
- const params = cleanParams(_params, data);
- const _fatal = params.fatal ?? fatal ?? true;
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
- }
- });
- }
- if (!r4) {
- const params = cleanParams(_params, data);
- const _fatal = params.fatal ?? fatal ?? true;
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
- }
- return;
- });
- return ZodAny2.create();
-}
-var handleResult2 = (ctx, result) => {
- if (isValid(result)) {
- return { success: true, data: result.value };
- } else {
- if (!ctx.common.issues.length) {
- throw new Error("Validation failed but no issues detected.");
- }
- return {
- success: false,
- get error() {
- if (this._error)
- return this._error;
- const error46 = new ZodError2(ctx.common.issues);
- this._error = error46;
- return this._error;
- }
- };
- }
-}, cuidRegex, cuid2Regex, ulidRegex, uuidRegex2, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`, dateRegex, ZodString2, ZodNumber2, ZodBigInt2, ZodBoolean2, ZodDate2, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodArray2, ZodObject2, ZodUnion2, getDiscriminator = (type) => {
- if (type instanceof ZodLazy2) {
- return getDiscriminator(type.schema);
- } else if (type instanceof ZodEffects) {
- return getDiscriminator(type.innerType());
- } else if (type instanceof ZodLiteral2) {
- return [type.value];
- } else if (type instanceof ZodEnum2) {
- return type.options;
- } else if (type instanceof ZodNativeEnum) {
- return util10.objectValues(type.enum);
- } else if (type instanceof ZodDefault2) {
- return getDiscriminator(type._def.innerType);
- } else if (type instanceof ZodUndefined2) {
- return [undefined];
- } else if (type instanceof ZodNull2) {
- return [null];
- } else if (type instanceof ZodOptional2) {
- return [undefined, ...getDiscriminator(type.unwrap())];
- } else if (type instanceof ZodNullable2) {
- return [null, ...getDiscriminator(type.unwrap())];
- } else if (type instanceof ZodBranded) {
- return getDiscriminator(type.unwrap());
- } else if (type instanceof ZodReadonly2) {
- return getDiscriminator(type.unwrap());
- } else if (type instanceof ZodCatch2) {
- return getDiscriminator(type._def.innerType);
- } else {
- return [];
- }
-}, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodFunction, ZodLazy2, ZodLiteral2, ZodEnum2, ZodNativeEnum, ZodPromise2, ZodEffects, ZodOptional2, ZodNullable2, ZodDefault2, ZodCatch2, ZodNaN2, BRAND, ZodBranded, ZodPipeline, ZodReadonly2, late, ZodFirstPartyTypeKind, instanceOfType = (cls, params = {
- message: `Input not instance of ${cls.name}`
-}) => custom3((data) => data instanceof cls, params), stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring = () => stringType().optional(), onumber = () => numberType().optional(), oboolean = () => booleanType().optional(), coerce2, NEVER2;
-var init_types14 = __esm(() => {
- init_ZodError();
- init_errors9();
- init_errorUtil();
- init_parseUtil();
- init_util9();
- cuidRegex = /^c[^\s-]{8,}$/i;
- cuid2Regex = /^[0-9a-z]+$/;
- ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
- uuidRegex2 = /^[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}$/i;
- nanoidRegex = /^[a-z0-9_-]{21}$/i;
- jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
- durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
- emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
- ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
- ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
- ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
- ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
- base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
- base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
- dateRegex = new RegExp(`^${dateRegexSource}$`);
- ZodString2 = class ZodString2 extends ZodType2 {
- _parse(input) {
- if (this._def.coerce) {
- input.data = String(input.data);
- }
- const parsedType4 = this._getType(input);
- if (parsedType4 !== ZodParsedType.string) {
- const ctx2 = this._getOrReturnCtx(input);
- addIssueToContext(ctx2, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.string,
- received: ctx2.parsedType
- });
- return INVALID;
- }
- const status = new ParseStatus;
- let ctx = undefined;
- for (const check3 of this._def.checks) {
- if (check3.kind === "min") {
- if (input.data.length < check3.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_small,
- minimum: check3.value,
- type: "string",
- inclusive: true,
- exact: false,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "max") {
- if (input.data.length > check3.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_big,
- maximum: check3.value,
- type: "string",
- inclusive: true,
- exact: false,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "length") {
- const tooBig = input.data.length > check3.value;
- const tooSmall = input.data.length < check3.value;
- if (tooBig || tooSmall) {
- ctx = this._getOrReturnCtx(input, ctx);
- if (tooBig) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_big,
- maximum: check3.value,
- type: "string",
- inclusive: true,
- exact: true,
- message: check3.message
- });
- } else if (tooSmall) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_small,
- minimum: check3.value,
- type: "string",
- inclusive: true,
- exact: true,
- message: check3.message
- });
- }
- status.dirty();
- }
- } else if (check3.kind === "email") {
- if (!emailRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "email",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "emoji") {
- if (!emojiRegex) {
- emojiRegex = new RegExp(_emojiRegex, "u");
- }
- if (!emojiRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "emoji",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "uuid") {
- if (!uuidRegex2.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "uuid",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "nanoid") {
- if (!nanoidRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "nanoid",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "cuid") {
- if (!cuidRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "cuid",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "cuid2") {
- if (!cuid2Regex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "cuid2",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "ulid") {
- if (!ulidRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "ulid",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "url") {
- try {
- new URL(input.data);
- } catch {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "url",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "regex") {
- check3.regex.lastIndex = 0;
- const testResult = check3.regex.test(input.data);
- if (!testResult) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "regex",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "trim") {
- input.data = input.data.trim();
- } else if (check3.kind === "includes") {
- if (!input.data.includes(check3.value, check3.position)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_string,
- validation: { includes: check3.value, position: check3.position },
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "toLowerCase") {
- input.data = input.data.toLowerCase();
- } else if (check3.kind === "toUpperCase") {
- input.data = input.data.toUpperCase();
- } else if (check3.kind === "startsWith") {
- if (!input.data.startsWith(check3.value)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_string,
- validation: { startsWith: check3.value },
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "endsWith") {
- if (!input.data.endsWith(check3.value)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_string,
- validation: { endsWith: check3.value },
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "datetime") {
- const regex2 = datetimeRegex(check3);
- if (!regex2.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_string,
- validation: "datetime",
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "date") {
- const regex2 = dateRegex;
- if (!regex2.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_string,
- validation: "date",
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "time") {
- const regex2 = timeRegex(check3);
- if (!regex2.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_string,
- validation: "time",
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "duration") {
- if (!durationRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "duration",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "ip") {
- if (!isValidIP(input.data, check3.version)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "ip",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "jwt") {
- if (!isValidJWT2(input.data, check3.alg)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "jwt",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "cidr") {
- if (!isValidCidr(input.data, check3.version)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "cidr",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "base64") {
- if (!base64Regex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "base64",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "base64url") {
- if (!base64urlRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "base64url",
- code: ZodIssueCode2.invalid_string,
- message: check3.message
- });
- status.dirty();
- }
- } else {
- util10.assertNever(check3);
- }
- }
- return { status: status.value, value: input.data };
- }
- _regex(regex2, validation, message) {
- return this.refinement((data) => regex2.test(data), {
- validation,
- code: ZodIssueCode2.invalid_string,
- ...errorUtil.errToObj(message)
- });
- }
- _addCheck(check3) {
- return new ZodString2({
- ...this._def,
- checks: [...this._def.checks, check3]
- });
- }
- email(message) {
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
- }
- url(message) {
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
- }
- emoji(message) {
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
- }
- uuid(message) {
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
- }
- nanoid(message) {
- return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
- }
- cuid(message) {
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
- }
- cuid2(message) {
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
- }
- ulid(message) {
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
- }
- base64(message) {
- return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
- }
- base64url(message) {
- return this._addCheck({
- kind: "base64url",
- ...errorUtil.errToObj(message)
- });
- }
- jwt(options2) {
- return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options2) });
- }
- ip(options2) {
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options2) });
- }
- cidr(options2) {
- return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options2) });
- }
- datetime(options2) {
- if (typeof options2 === "string") {
- return this._addCheck({
- kind: "datetime",
- precision: null,
- offset: false,
- local: false,
- message: options2
- });
- }
- return this._addCheck({
- kind: "datetime",
- precision: typeof options2?.precision === "undefined" ? null : options2?.precision,
- offset: options2?.offset ?? false,
- local: options2?.local ?? false,
- ...errorUtil.errToObj(options2?.message)
- });
- }
- date(message) {
- return this._addCheck({ kind: "date", message });
- }
- time(options2) {
- if (typeof options2 === "string") {
- return this._addCheck({
- kind: "time",
- precision: null,
- message: options2
- });
- }
- return this._addCheck({
- kind: "time",
- precision: typeof options2?.precision === "undefined" ? null : options2?.precision,
- ...errorUtil.errToObj(options2?.message)
- });
- }
- duration(message) {
- return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
- }
- regex(regex2, message) {
- return this._addCheck({
- kind: "regex",
- regex: regex2,
- ...errorUtil.errToObj(message)
- });
- }
- includes(value, options2) {
- return this._addCheck({
- kind: "includes",
- value,
- position: options2?.position,
- ...errorUtil.errToObj(options2?.message)
- });
- }
- startsWith(value, message) {
- return this._addCheck({
- kind: "startsWith",
- value,
- ...errorUtil.errToObj(message)
- });
- }
- endsWith(value, message) {
- return this._addCheck({
- kind: "endsWith",
- value,
- ...errorUtil.errToObj(message)
- });
- }
- min(minLength, message) {
- return this._addCheck({
- kind: "min",
- value: minLength,
- ...errorUtil.errToObj(message)
- });
- }
- max(maxLength, message) {
- return this._addCheck({
- kind: "max",
- value: maxLength,
- ...errorUtil.errToObj(message)
- });
- }
- length(len, message) {
- return this._addCheck({
- kind: "length",
- value: len,
- ...errorUtil.errToObj(message)
- });
- }
- nonempty(message) {
- return this.min(1, errorUtil.errToObj(message));
- }
- trim() {
- return new ZodString2({
- ...this._def,
- checks: [...this._def.checks, { kind: "trim" }]
- });
- }
- toLowerCase() {
- return new ZodString2({
- ...this._def,
- checks: [...this._def.checks, { kind: "toLowerCase" }]
- });
- }
- toUpperCase() {
- return new ZodString2({
- ...this._def,
- checks: [...this._def.checks, { kind: "toUpperCase" }]
- });
- }
- get isDatetime() {
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
- }
- get isDate() {
- return !!this._def.checks.find((ch) => ch.kind === "date");
- }
- get isTime() {
- return !!this._def.checks.find((ch) => ch.kind === "time");
- }
- get isDuration() {
- return !!this._def.checks.find((ch) => ch.kind === "duration");
- }
- get isEmail() {
- return !!this._def.checks.find((ch) => ch.kind === "email");
- }
- get isURL() {
- return !!this._def.checks.find((ch) => ch.kind === "url");
- }
- get isEmoji() {
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
- }
- get isUUID() {
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
- }
- get isNANOID() {
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
- }
- get isCUID() {
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
- }
- get isCUID2() {
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
- }
- get isULID() {
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
- }
- get isIP() {
- return !!this._def.checks.find((ch) => ch.kind === "ip");
- }
- get isCIDR() {
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
- }
- get isBase64() {
- return !!this._def.checks.find((ch) => ch.kind === "base64");
- }
- get isBase64url() {
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
- }
- get minLength() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min;
- }
- get maxLength() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max;
- }
- };
- ZodString2.create = (params) => {
- return new ZodString2({
- checks: [],
- typeName: ZodFirstPartyTypeKind.ZodString,
- coerce: params?.coerce ?? false,
- ...processCreateParams(params)
- });
- };
- ZodNumber2 = class ZodNumber2 extends ZodType2 {
- constructor() {
- super(...arguments);
- this.min = this.gte;
- this.max = this.lte;
- this.step = this.multipleOf;
- }
- _parse(input) {
- if (this._def.coerce) {
- input.data = Number(input.data);
- }
- const parsedType4 = this._getType(input);
- if (parsedType4 !== ZodParsedType.number) {
- const ctx2 = this._getOrReturnCtx(input);
- addIssueToContext(ctx2, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.number,
- received: ctx2.parsedType
- });
- return INVALID;
- }
- let ctx = undefined;
- const status = new ParseStatus;
- for (const check3 of this._def.checks) {
- if (check3.kind === "int") {
- if (!util10.isInteger(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: "integer",
- received: "float",
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "min") {
- const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value;
- if (tooSmall) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_small,
- minimum: check3.value,
- type: "number",
- inclusive: check3.inclusive,
- exact: false,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "max") {
- const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value;
- if (tooBig) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_big,
- maximum: check3.value,
- type: "number",
- inclusive: check3.inclusive,
- exact: false,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "multipleOf") {
- if (floatSafeRemainder2(input.data, check3.value) !== 0) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.not_multiple_of,
- multipleOf: check3.value,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "finite") {
- if (!Number.isFinite(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.not_finite,
- message: check3.message
- });
- status.dirty();
- }
- } else {
- util10.assertNever(check3);
- }
- }
- return { status: status.value, value: input.data };
- }
- gte(value, message) {
- return this.setLimit("min", value, true, errorUtil.toString(message));
- }
- gt(value, message) {
- return this.setLimit("min", value, false, errorUtil.toString(message));
- }
- lte(value, message) {
- return this.setLimit("max", value, true, errorUtil.toString(message));
- }
- lt(value, message) {
- return this.setLimit("max", value, false, errorUtil.toString(message));
- }
- setLimit(kind2, value, inclusive, message) {
- return new ZodNumber2({
- ...this._def,
- checks: [
- ...this._def.checks,
- {
- kind: kind2,
- value,
- inclusive,
- message: errorUtil.toString(message)
- }
- ]
- });
- }
- _addCheck(check3) {
- return new ZodNumber2({
- ...this._def,
- checks: [...this._def.checks, check3]
- });
- }
- int(message) {
- return this._addCheck({
- kind: "int",
- message: errorUtil.toString(message)
- });
- }
- positive(message) {
- return this._addCheck({
- kind: "min",
- value: 0,
- inclusive: false,
- message: errorUtil.toString(message)
- });
- }
- negative(message) {
- return this._addCheck({
- kind: "max",
- value: 0,
- inclusive: false,
- message: errorUtil.toString(message)
- });
- }
- nonpositive(message) {
- return this._addCheck({
- kind: "max",
- value: 0,
- inclusive: true,
- message: errorUtil.toString(message)
- });
- }
- nonnegative(message) {
- return this._addCheck({
- kind: "min",
- value: 0,
- inclusive: true,
- message: errorUtil.toString(message)
- });
- }
- multipleOf(value, message) {
- return this._addCheck({
- kind: "multipleOf",
- value,
- message: errorUtil.toString(message)
- });
- }
- finite(message) {
- return this._addCheck({
- kind: "finite",
- message: errorUtil.toString(message)
- });
- }
- safe(message) {
- return this._addCheck({
- kind: "min",
- inclusive: true,
- value: Number.MIN_SAFE_INTEGER,
- message: errorUtil.toString(message)
- })._addCheck({
- kind: "max",
- inclusive: true,
- value: Number.MAX_SAFE_INTEGER,
- message: errorUtil.toString(message)
- });
- }
- get minValue() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min;
- }
- get maxValue() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max;
- }
- get isInt() {
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util10.isInteger(ch.value));
- }
- get isFinite() {
- let max = null;
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
- return true;
- } else if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- } else if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return Number.isFinite(min) && Number.isFinite(max);
- }
- };
- ZodNumber2.create = (params) => {
- return new ZodNumber2({
- checks: [],
- typeName: ZodFirstPartyTypeKind.ZodNumber,
- coerce: params?.coerce || false,
- ...processCreateParams(params)
- });
- };
- ZodBigInt2 = class ZodBigInt2 extends ZodType2 {
- constructor() {
- super(...arguments);
- this.min = this.gte;
- this.max = this.lte;
- }
- _parse(input) {
- if (this._def.coerce) {
- try {
- input.data = BigInt(input.data);
- } catch {
- return this._getInvalidInput(input);
- }
- }
- const parsedType4 = this._getType(input);
- if (parsedType4 !== ZodParsedType.bigint) {
- return this._getInvalidInput(input);
- }
- let ctx = undefined;
- const status = new ParseStatus;
- for (const check3 of this._def.checks) {
- if (check3.kind === "min") {
- const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value;
- if (tooSmall) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_small,
- type: "bigint",
- minimum: check3.value,
- inclusive: check3.inclusive,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "max") {
- const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value;
- if (tooBig) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_big,
- type: "bigint",
- maximum: check3.value,
- inclusive: check3.inclusive,
- message: check3.message
- });
- status.dirty();
- }
- } else if (check3.kind === "multipleOf") {
- if (input.data % check3.value !== BigInt(0)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.not_multiple_of,
- multipleOf: check3.value,
- message: check3.message
- });
- status.dirty();
- }
- } else {
- util10.assertNever(check3);
- }
- }
- return { status: status.value, value: input.data };
- }
- _getInvalidInput(input) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.bigint,
- received: ctx.parsedType
- });
- return INVALID;
- }
- gte(value, message) {
- return this.setLimit("min", value, true, errorUtil.toString(message));
- }
- gt(value, message) {
- return this.setLimit("min", value, false, errorUtil.toString(message));
- }
- lte(value, message) {
- return this.setLimit("max", value, true, errorUtil.toString(message));
- }
- lt(value, message) {
- return this.setLimit("max", value, false, errorUtil.toString(message));
- }
- setLimit(kind2, value, inclusive, message) {
- return new ZodBigInt2({
- ...this._def,
- checks: [
- ...this._def.checks,
- {
- kind: kind2,
- value,
- inclusive,
- message: errorUtil.toString(message)
- }
- ]
- });
- }
- _addCheck(check3) {
- return new ZodBigInt2({
- ...this._def,
- checks: [...this._def.checks, check3]
- });
- }
- positive(message) {
- return this._addCheck({
- kind: "min",
- value: BigInt(0),
- inclusive: false,
- message: errorUtil.toString(message)
- });
- }
- negative(message) {
- return this._addCheck({
- kind: "max",
- value: BigInt(0),
- inclusive: false,
- message: errorUtil.toString(message)
- });
- }
- nonpositive(message) {
- return this._addCheck({
- kind: "max",
- value: BigInt(0),
- inclusive: true,
- message: errorUtil.toString(message)
- });
- }
- nonnegative(message) {
- return this._addCheck({
- kind: "min",
- value: BigInt(0),
- inclusive: true,
- message: errorUtil.toString(message)
- });
- }
- multipleOf(value, message) {
- return this._addCheck({
- kind: "multipleOf",
- value,
- message: errorUtil.toString(message)
- });
- }
- get minValue() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min;
- }
- get maxValue() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max;
- }
- };
- ZodBigInt2.create = (params) => {
- return new ZodBigInt2({
- checks: [],
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
- coerce: params?.coerce ?? false,
- ...processCreateParams(params)
- });
- };
- ZodBoolean2 = class ZodBoolean2 extends ZodType2 {
- _parse(input) {
- if (this._def.coerce) {
- input.data = Boolean(input.data);
- }
- const parsedType4 = this._getType(input);
- if (parsedType4 !== ZodParsedType.boolean) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.boolean,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return OK(input.data);
- }
- };
- ZodBoolean2.create = (params) => {
- return new ZodBoolean2({
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
- coerce: params?.coerce || false,
- ...processCreateParams(params)
- });
- };
- ZodDate2 = class ZodDate2 extends ZodType2 {
- _parse(input) {
- if (this._def.coerce) {
- input.data = new Date(input.data);
- }
- const parsedType4 = this._getType(input);
- if (parsedType4 !== ZodParsedType.date) {
- const ctx2 = this._getOrReturnCtx(input);
- addIssueToContext(ctx2, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.date,
- received: ctx2.parsedType
- });
- return INVALID;
- }
- if (Number.isNaN(input.data.getTime())) {
- const ctx2 = this._getOrReturnCtx(input);
- addIssueToContext(ctx2, {
- code: ZodIssueCode2.invalid_date
- });
- return INVALID;
- }
- const status = new ParseStatus;
- let ctx = undefined;
- for (const check3 of this._def.checks) {
- if (check3.kind === "min") {
- if (input.data.getTime() < check3.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_small,
- message: check3.message,
- inclusive: true,
- exact: false,
- minimum: check3.value,
- type: "date"
- });
- status.dirty();
- }
- } else if (check3.kind === "max") {
- if (input.data.getTime() > check3.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_big,
- message: check3.message,
- inclusive: true,
- exact: false,
- maximum: check3.value,
- type: "date"
- });
- status.dirty();
- }
- } else {
- util10.assertNever(check3);
- }
- }
- return {
- status: status.value,
- value: new Date(input.data.getTime())
- };
- }
- _addCheck(check3) {
- return new ZodDate2({
- ...this._def,
- checks: [...this._def.checks, check3]
- });
- }
- min(minDate, message) {
- return this._addCheck({
- kind: "min",
- value: minDate.getTime(),
- message: errorUtil.toString(message)
- });
- }
- max(maxDate, message) {
- return this._addCheck({
- kind: "max",
- value: maxDate.getTime(),
- message: errorUtil.toString(message)
- });
- }
- get minDate() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min != null ? new Date(min) : null;
- }
- get maxDate() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max != null ? new Date(max) : null;
- }
- };
- ZodDate2.create = (params) => {
- return new ZodDate2({
- checks: [],
- coerce: params?.coerce || false,
- typeName: ZodFirstPartyTypeKind.ZodDate,
- ...processCreateParams(params)
- });
- };
- ZodSymbol2 = class ZodSymbol2 extends ZodType2 {
- _parse(input) {
- const parsedType4 = this._getType(input);
- if (parsedType4 !== ZodParsedType.symbol) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.symbol,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return OK(input.data);
- }
- };
- ZodSymbol2.create = (params) => {
- return new ZodSymbol2({
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
- ...processCreateParams(params)
- });
- };
- ZodUndefined2 = class ZodUndefined2 extends ZodType2 {
- _parse(input) {
- const parsedType4 = this._getType(input);
- if (parsedType4 !== ZodParsedType.undefined) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.undefined,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return OK(input.data);
- }
- };
- ZodUndefined2.create = (params) => {
- return new ZodUndefined2({
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
- ...processCreateParams(params)
- });
- };
- ZodNull2 = class ZodNull2 extends ZodType2 {
- _parse(input) {
- const parsedType4 = this._getType(input);
- if (parsedType4 !== ZodParsedType.null) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.null,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return OK(input.data);
- }
- };
- ZodNull2.create = (params) => {
- return new ZodNull2({
- typeName: ZodFirstPartyTypeKind.ZodNull,
- ...processCreateParams(params)
- });
- };
- ZodAny2 = class ZodAny2 extends ZodType2 {
- constructor() {
- super(...arguments);
- this._any = true;
- }
- _parse(input) {
- return OK(input.data);
- }
- };
- ZodAny2.create = (params) => {
- return new ZodAny2({
- typeName: ZodFirstPartyTypeKind.ZodAny,
- ...processCreateParams(params)
- });
- };
- ZodUnknown2 = class ZodUnknown2 extends ZodType2 {
- constructor() {
- super(...arguments);
- this._unknown = true;
- }
- _parse(input) {
- return OK(input.data);
- }
- };
- ZodUnknown2.create = (params) => {
- return new ZodUnknown2({
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
- ...processCreateParams(params)
- });
- };
- ZodNever2 = class ZodNever2 extends ZodType2 {
- _parse(input) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.never,
- received: ctx.parsedType
- });
- return INVALID;
- }
- };
- ZodNever2.create = (params) => {
- return new ZodNever2({
- typeName: ZodFirstPartyTypeKind.ZodNever,
- ...processCreateParams(params)
- });
- };
- ZodVoid2 = class ZodVoid2 extends ZodType2 {
- _parse(input) {
- const parsedType4 = this._getType(input);
- if (parsedType4 !== ZodParsedType.undefined) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.void,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return OK(input.data);
- }
- };
- ZodVoid2.create = (params) => {
- return new ZodVoid2({
- typeName: ZodFirstPartyTypeKind.ZodVoid,
- ...processCreateParams(params)
- });
- };
- ZodArray2 = class ZodArray2 extends ZodType2 {
- _parse(input) {
- const { ctx, status } = this._processInputParams(input);
- const def2 = this._def;
- if (ctx.parsedType !== ZodParsedType.array) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.array,
- received: ctx.parsedType
- });
- return INVALID;
- }
- if (def2.exactLength !== null) {
- const tooBig = ctx.data.length > def2.exactLength.value;
- const tooSmall = ctx.data.length < def2.exactLength.value;
- if (tooBig || tooSmall) {
- addIssueToContext(ctx, {
- code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small,
- minimum: tooSmall ? def2.exactLength.value : undefined,
- maximum: tooBig ? def2.exactLength.value : undefined,
- type: "array",
- inclusive: true,
- exact: true,
- message: def2.exactLength.message
- });
- status.dirty();
- }
- }
- if (def2.minLength !== null) {
- if (ctx.data.length < def2.minLength.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_small,
- minimum: def2.minLength.value,
- type: "array",
- inclusive: true,
- exact: false,
- message: def2.minLength.message
- });
- status.dirty();
- }
- }
- if (def2.maxLength !== null) {
- if (ctx.data.length > def2.maxLength.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_big,
- maximum: def2.maxLength.value,
- type: "array",
- inclusive: true,
- exact: false,
- message: def2.maxLength.message
- });
- status.dirty();
- }
- }
- if (ctx.common.async) {
- return Promise.all([...ctx.data].map((item, i5) => {
- return def2.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i5));
- })).then((result2) => {
- return ParseStatus.mergeArray(status, result2);
- });
- }
- const result = [...ctx.data].map((item, i5) => {
- return def2.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i5));
- });
- return ParseStatus.mergeArray(status, result);
- }
- get element() {
- return this._def.type;
- }
- min(minLength, message) {
- return new ZodArray2({
- ...this._def,
- minLength: { value: minLength, message: errorUtil.toString(message) }
- });
- }
- max(maxLength, message) {
- return new ZodArray2({
- ...this._def,
- maxLength: { value: maxLength, message: errorUtil.toString(message) }
- });
- }
- length(len, message) {
- return new ZodArray2({
- ...this._def,
- exactLength: { value: len, message: errorUtil.toString(message) }
- });
- }
- nonempty(message) {
- return this.min(1, message);
- }
- };
- ZodArray2.create = (schema5, params) => {
- return new ZodArray2({
- type: schema5,
- minLength: null,
- maxLength: null,
- exactLength: null,
- typeName: ZodFirstPartyTypeKind.ZodArray,
- ...processCreateParams(params)
- });
- };
- ZodObject2 = class ZodObject2 extends ZodType2 {
- constructor() {
- super(...arguments);
- this._cached = null;
- this.nonstrict = this.passthrough;
- this.augment = this.extend;
- }
- _getCached() {
- if (this._cached !== null)
- return this._cached;
- const shape = this._def.shape();
- const keys2 = util10.objectKeys(shape);
- this._cached = { shape, keys: keys2 };
- return this._cached;
- }
- _parse(input) {
- const parsedType4 = this._getType(input);
- if (parsedType4 !== ZodParsedType.object) {
- const ctx2 = this._getOrReturnCtx(input);
- addIssueToContext(ctx2, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.object,
- received: ctx2.parsedType
- });
- return INVALID;
- }
- const { status, ctx } = this._processInputParams(input);
- const { shape, keys: shapeKeys } = this._getCached();
- const extraKeys = [];
- if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) {
- for (const key2 in ctx.data) {
- if (!shapeKeys.includes(key2)) {
- extraKeys.push(key2);
- }
- }
- }
- const pairs = [];
- for (const key2 of shapeKeys) {
- const keyValidator = shape[key2];
- const value = ctx.data[key2];
- pairs.push({
- key: { status: "valid", value: key2 },
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key2)),
- alwaysSet: key2 in ctx.data
- });
- }
- if (this._def.catchall instanceof ZodNever2) {
- const unknownKeys = this._def.unknownKeys;
- if (unknownKeys === "passthrough") {
- for (const key2 of extraKeys) {
- pairs.push({
- key: { status: "valid", value: key2 },
- value: { status: "valid", value: ctx.data[key2] }
- });
- }
- } else if (unknownKeys === "strict") {
- if (extraKeys.length > 0) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.unrecognized_keys,
- keys: extraKeys
- });
- status.dirty();
- }
- } else if (unknownKeys === "strip") {} else {
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
- }
- } else {
- const catchall = this._def.catchall;
- for (const key2 of extraKeys) {
- const value = ctx.data[key2];
- pairs.push({
- key: { status: "valid", value: key2 },
- value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key2)),
- alwaysSet: key2 in ctx.data
- });
- }
- }
- if (ctx.common.async) {
- return Promise.resolve().then(async () => {
- const syncPairs = [];
- for (const pair of pairs) {
- const key2 = await pair.key;
- const value = await pair.value;
- syncPairs.push({
- key: key2,
- value,
- alwaysSet: pair.alwaysSet
- });
- }
- return syncPairs;
- }).then((syncPairs) => {
- return ParseStatus.mergeObjectSync(status, syncPairs);
- });
- } else {
- return ParseStatus.mergeObjectSync(status, pairs);
- }
- }
- get shape() {
- return this._def.shape();
- }
- strict(message) {
- errorUtil.errToObj;
- return new ZodObject2({
- ...this._def,
- unknownKeys: "strict",
- ...message !== undefined ? {
- errorMap: (issue2, ctx) => {
- const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError;
- if (issue2.code === "unrecognized_keys")
- return {
- message: errorUtil.errToObj(message).message ?? defaultError
- };
- return {
- message: defaultError
- };
- }
- } : {}
- });
- }
- strip() {
- return new ZodObject2({
- ...this._def,
- unknownKeys: "strip"
- });
- }
- passthrough() {
- return new ZodObject2({
- ...this._def,
- unknownKeys: "passthrough"
- });
- }
- extend(augmentation) {
- return new ZodObject2({
- ...this._def,
- shape: () => ({
- ...this._def.shape(),
- ...augmentation
- })
- });
- }
- merge(merging) {
- const merged = new ZodObject2({
- unknownKeys: merging._def.unknownKeys,
- catchall: merging._def.catchall,
- shape: () => ({
- ...this._def.shape(),
- ...merging._def.shape()
- }),
- typeName: ZodFirstPartyTypeKind.ZodObject
- });
- return merged;
- }
- setKey(key2, schema5) {
- return this.augment({ [key2]: schema5 });
- }
- catchall(index2) {
- return new ZodObject2({
- ...this._def,
- catchall: index2
- });
- }
- pick(mask) {
- const shape = {};
- for (const key2 of util10.objectKeys(mask)) {
- if (mask[key2] && this.shape[key2]) {
- shape[key2] = this.shape[key2];
- }
- }
- return new ZodObject2({
- ...this._def,
- shape: () => shape
- });
- }
- omit(mask) {
- const shape = {};
- for (const key2 of util10.objectKeys(this.shape)) {
- if (!mask[key2]) {
- shape[key2] = this.shape[key2];
- }
- }
- return new ZodObject2({
- ...this._def,
- shape: () => shape
- });
- }
- deepPartial() {
- return deepPartialify(this);
- }
- partial(mask) {
- const newShape = {};
- for (const key2 of util10.objectKeys(this.shape)) {
- const fieldSchema = this.shape[key2];
- if (mask && !mask[key2]) {
- newShape[key2] = fieldSchema;
- } else {
- newShape[key2] = fieldSchema.optional();
- }
- }
- return new ZodObject2({
- ...this._def,
- shape: () => newShape
- });
- }
- required(mask) {
- const newShape = {};
- for (const key2 of util10.objectKeys(this.shape)) {
- if (mask && !mask[key2]) {
- newShape[key2] = this.shape[key2];
- } else {
- const fieldSchema = this.shape[key2];
- let newField = fieldSchema;
- while (newField instanceof ZodOptional2) {
- newField = newField._def.innerType;
- }
- newShape[key2] = newField;
- }
- }
- return new ZodObject2({
- ...this._def,
- shape: () => newShape
- });
- }
- keyof() {
- return createZodEnum(util10.objectKeys(this.shape));
- }
- };
- ZodObject2.create = (shape, params) => {
- return new ZodObject2({
- shape: () => shape,
- unknownKeys: "strip",
- catchall: ZodNever2.create(),
- typeName: ZodFirstPartyTypeKind.ZodObject,
- ...processCreateParams(params)
- });
- };
- ZodObject2.strictCreate = (shape, params) => {
- return new ZodObject2({
- shape: () => shape,
- unknownKeys: "strict",
- catchall: ZodNever2.create(),
- typeName: ZodFirstPartyTypeKind.ZodObject,
- ...processCreateParams(params)
- });
- };
- ZodObject2.lazycreate = (shape, params) => {
- return new ZodObject2({
- shape,
- unknownKeys: "strip",
- catchall: ZodNever2.create(),
- typeName: ZodFirstPartyTypeKind.ZodObject,
- ...processCreateParams(params)
- });
- };
- ZodUnion2 = class ZodUnion2 extends ZodType2 {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- const options2 = this._def.options;
- function handleResults(results) {
- for (const result of results) {
- if (result.result.status === "valid") {
- return result.result;
- }
- }
- for (const result of results) {
- if (result.result.status === "dirty") {
- ctx.common.issues.push(...result.ctx.common.issues);
- return result.result;
- }
- }
- const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues));
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_union,
- unionErrors
- });
- return INVALID;
- }
- if (ctx.common.async) {
- return Promise.all(options2.map(async (option) => {
- const childCtx = {
- ...ctx,
- common: {
- ...ctx.common,
- issues: []
- },
- parent: null
- };
- return {
- result: await option._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: childCtx
- }),
- ctx: childCtx
- };
- })).then(handleResults);
- } else {
- let dirty = undefined;
- const issues = [];
- for (const option of options2) {
- const childCtx = {
- ...ctx,
- common: {
- ...ctx.common,
- issues: []
- },
- parent: null
- };
- const result = option._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: childCtx
- });
- if (result.status === "valid") {
- return result;
- } else if (result.status === "dirty" && !dirty) {
- dirty = { result, ctx: childCtx };
- }
- if (childCtx.common.issues.length) {
- issues.push(childCtx.common.issues);
- }
- }
- if (dirty) {
- ctx.common.issues.push(...dirty.ctx.common.issues);
- return dirty.result;
- }
- const unionErrors = issues.map((issues2) => new ZodError2(issues2));
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_union,
- unionErrors
- });
- return INVALID;
- }
- }
- get options() {
- return this._def.options;
- }
- };
- ZodUnion2.create = (types12, params) => {
- return new ZodUnion2({
- options: types12,
- typeName: ZodFirstPartyTypeKind.ZodUnion,
- ...processCreateParams(params)
- });
- };
- ZodDiscriminatedUnion2 = class ZodDiscriminatedUnion2 extends ZodType2 {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.object) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.object,
- received: ctx.parsedType
- });
- return INVALID;
- }
- const discriminator = this.discriminator;
- const discriminatorValue = ctx.data[discriminator];
- const option = this.optionsMap.get(discriminatorValue);
- if (!option) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_union_discriminator,
- options: Array.from(this.optionsMap.keys()),
- path: [discriminator]
- });
- return INVALID;
- }
- if (ctx.common.async) {
- return option._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- } else {
- return option._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- }
- }
- get discriminator() {
- return this._def.discriminator;
- }
- get options() {
- return this._def.options;
- }
- get optionsMap() {
- return this._def.optionsMap;
- }
- static create(discriminator, options2, params) {
- const optionsMap = new Map;
- for (const type of options2) {
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
- if (!discriminatorValues.length) {
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
- }
- for (const value of discriminatorValues) {
- if (optionsMap.has(value)) {
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
- }
- optionsMap.set(value, type);
- }
- }
- return new ZodDiscriminatedUnion2({
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
- discriminator,
- options: options2,
- optionsMap,
- ...processCreateParams(params)
- });
- }
- };
- ZodIntersection2 = class ZodIntersection2 extends ZodType2 {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- const handleParsed = (parsedLeft, parsedRight) => {
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
- return INVALID;
- }
- const merged = mergeValues2(parsedLeft.value, parsedRight.value);
- if (!merged.valid) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_intersection_types
- });
- return INVALID;
- }
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
- status.dirty();
- }
- return { status: status.value, value: merged.data };
- };
- if (ctx.common.async) {
- return Promise.all([
- this._def.left._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- }),
- this._def.right._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- })
- ]).then(([left, right]) => handleParsed(left, right));
- } else {
- return handleParsed(this._def.left._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- }), this._def.right._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- }));
- }
- }
- };
- ZodIntersection2.create = (left, right, params) => {
- return new ZodIntersection2({
- left,
- right,
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
- ...processCreateParams(params)
- });
- };
- ZodTuple2 = class ZodTuple2 extends ZodType2 {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.array) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.array,
- received: ctx.parsedType
- });
- return INVALID;
- }
- if (ctx.data.length < this._def.items.length) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_small,
- minimum: this._def.items.length,
- inclusive: true,
- exact: false,
- type: "array"
- });
- return INVALID;
- }
- const rest = this._def.rest;
- if (!rest && ctx.data.length > this._def.items.length) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_big,
- maximum: this._def.items.length,
- inclusive: true,
- exact: false,
- type: "array"
- });
- status.dirty();
- }
- const items = [...ctx.data].map((item, itemIndex) => {
- const schema5 = this._def.items[itemIndex] || this._def.rest;
- if (!schema5)
- return null;
- return schema5._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
- }).filter((x3) => !!x3);
- if (ctx.common.async) {
- return Promise.all(items).then((results) => {
- return ParseStatus.mergeArray(status, results);
- });
- } else {
- return ParseStatus.mergeArray(status, items);
- }
- }
- get items() {
- return this._def.items;
- }
- rest(rest) {
- return new ZodTuple2({
- ...this._def,
- rest
- });
- }
- };
- ZodTuple2.create = (schemas3, params) => {
- if (!Array.isArray(schemas3)) {
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
- }
- return new ZodTuple2({
- items: schemas3,
- typeName: ZodFirstPartyTypeKind.ZodTuple,
- rest: null,
- ...processCreateParams(params)
- });
- };
- ZodRecord2 = class ZodRecord2 extends ZodType2 {
- get keySchema() {
- return this._def.keyType;
- }
- get valueSchema() {
- return this._def.valueType;
- }
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.object) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.object,
- received: ctx.parsedType
- });
- return INVALID;
- }
- const pairs = [];
- const keyType = this._def.keyType;
- const valueType = this._def.valueType;
- for (const key2 in ctx.data) {
- pairs.push({
- key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, key2)),
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key2], ctx.path, key2)),
- alwaysSet: key2 in ctx.data
- });
- }
- if (ctx.common.async) {
- return ParseStatus.mergeObjectAsync(status, pairs);
- } else {
- return ParseStatus.mergeObjectSync(status, pairs);
- }
- }
- get element() {
- return this._def.valueType;
- }
- static create(first, second, third) {
- if (second instanceof ZodType2) {
- return new ZodRecord2({
- keyType: first,
- valueType: second,
- typeName: ZodFirstPartyTypeKind.ZodRecord,
- ...processCreateParams(third)
- });
- }
- return new ZodRecord2({
- keyType: ZodString2.create(),
- valueType: first,
- typeName: ZodFirstPartyTypeKind.ZodRecord,
- ...processCreateParams(second)
- });
- }
- };
- ZodMap2 = class ZodMap2 extends ZodType2 {
- get keySchema() {
- return this._def.keyType;
- }
- get valueSchema() {
- return this._def.valueType;
- }
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.map) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.map,
- received: ctx.parsedType
- });
- return INVALID;
- }
- const keyType = this._def.keyType;
- const valueType = this._def.valueType;
- const pairs = [...ctx.data.entries()].map(([key2, value], index2) => {
- return {
- key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, [index2, "key"])),
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"]))
- };
- });
- if (ctx.common.async) {
- const finalMap = new Map;
- return Promise.resolve().then(async () => {
- for (const pair of pairs) {
- const key2 = await pair.key;
- const value = await pair.value;
- if (key2.status === "aborted" || value.status === "aborted") {
- return INVALID;
- }
- if (key2.status === "dirty" || value.status === "dirty") {
- status.dirty();
- }
- finalMap.set(key2.value, value.value);
- }
- return { status: status.value, value: finalMap };
- });
- } else {
- const finalMap = new Map;
- for (const pair of pairs) {
- const key2 = pair.key;
- const value = pair.value;
- if (key2.status === "aborted" || value.status === "aborted") {
- return INVALID;
- }
- if (key2.status === "dirty" || value.status === "dirty") {
- status.dirty();
- }
- finalMap.set(key2.value, value.value);
- }
- return { status: status.value, value: finalMap };
- }
- }
- };
- ZodMap2.create = (keyType, valueType, params) => {
- return new ZodMap2({
- valueType,
- keyType,
- typeName: ZodFirstPartyTypeKind.ZodMap,
- ...processCreateParams(params)
- });
- };
- ZodSet2 = class ZodSet2 extends ZodType2 {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.set) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.set,
- received: ctx.parsedType
- });
- return INVALID;
- }
- const def2 = this._def;
- if (def2.minSize !== null) {
- if (ctx.data.size < def2.minSize.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_small,
- minimum: def2.minSize.value,
- type: "set",
- inclusive: true,
- exact: false,
- message: def2.minSize.message
- });
- status.dirty();
- }
- }
- if (def2.maxSize !== null) {
- if (ctx.data.size > def2.maxSize.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.too_big,
- maximum: def2.maxSize.value,
- type: "set",
- inclusive: true,
- exact: false,
- message: def2.maxSize.message
- });
- status.dirty();
- }
- }
- const valueType = this._def.valueType;
- function finalizeSet(elements3) {
- const parsedSet = new Set;
- for (const element of elements3) {
- if (element.status === "aborted")
- return INVALID;
- if (element.status === "dirty")
- status.dirty();
- parsedSet.add(element.value);
- }
- return { status: status.value, value: parsedSet };
- }
- const elements2 = [...ctx.data.values()].map((item, i5) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i5)));
- if (ctx.common.async) {
- return Promise.all(elements2).then((elements3) => finalizeSet(elements3));
- } else {
- return finalizeSet(elements2);
- }
- }
- min(minSize, message) {
- return new ZodSet2({
- ...this._def,
- minSize: { value: minSize, message: errorUtil.toString(message) }
- });
- }
- max(maxSize, message) {
- return new ZodSet2({
- ...this._def,
- maxSize: { value: maxSize, message: errorUtil.toString(message) }
- });
- }
- size(size, message) {
- return this.min(size, message).max(size, message);
- }
- nonempty(message) {
- return this.min(1, message);
- }
- };
- ZodSet2.create = (valueType, params) => {
- return new ZodSet2({
- valueType,
- minSize: null,
- maxSize: null,
- typeName: ZodFirstPartyTypeKind.ZodSet,
- ...processCreateParams(params)
- });
- };
- ZodFunction = class ZodFunction extends ZodType2 {
- constructor() {
- super(...arguments);
- this.validate = this.implement;
- }
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.function) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.function,
- received: ctx.parsedType
- });
- return INVALID;
- }
- function makeArgsIssue(args, error46) {
- return makeIssue({
- data: args,
- path: ctx.path,
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x3) => !!x3),
- issueData: {
- code: ZodIssueCode2.invalid_arguments,
- argumentsError: error46
- }
- });
- }
- function makeReturnsIssue(returns, error46) {
- return makeIssue({
- data: returns,
- path: ctx.path,
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x3) => !!x3),
- issueData: {
- code: ZodIssueCode2.invalid_return_type,
- returnTypeError: error46
- }
- });
- }
- const params = { errorMap: ctx.common.contextualErrorMap };
- const fn = ctx.data;
- if (this._def.returns instanceof ZodPromise2) {
- const me = this;
- return OK(async function(...args) {
- const error46 = new ZodError2([]);
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e4) => {
- error46.addIssue(makeArgsIssue(args, e4));
- throw error46;
- });
- const result = await Reflect.apply(fn, this, parsedArgs);
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e4) => {
- error46.addIssue(makeReturnsIssue(result, e4));
- throw error46;
- });
- return parsedReturns;
- });
- } else {
- const me = this;
- return OK(function(...args) {
- const parsedArgs = me._def.args.safeParse(args, params);
- if (!parsedArgs.success) {
- throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]);
- }
- const result = Reflect.apply(fn, this, parsedArgs.data);
- const parsedReturns = me._def.returns.safeParse(result, params);
- if (!parsedReturns.success) {
- throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]);
- }
- return parsedReturns.data;
- });
- }
- }
- parameters() {
- return this._def.args;
- }
- returnType() {
- return this._def.returns;
- }
- args(...items) {
- return new ZodFunction({
- ...this._def,
- args: ZodTuple2.create(items).rest(ZodUnknown2.create())
- });
- }
- returns(returnType) {
- return new ZodFunction({
- ...this._def,
- returns: returnType
- });
- }
- implement(func) {
- const validatedFunc = this.parse(func);
- return validatedFunc;
- }
- strictImplement(func) {
- const validatedFunc = this.parse(func);
- return validatedFunc;
- }
- static create(args, returns, params) {
- return new ZodFunction({
- args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()),
- returns: returns || ZodUnknown2.create(),
- typeName: ZodFirstPartyTypeKind.ZodFunction,
- ...processCreateParams(params)
- });
- }
- };
- ZodLazy2 = class ZodLazy2 extends ZodType2 {
- get schema() {
- return this._def.getter();
- }
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- const lazySchema2 = this._def.getter();
- return lazySchema2._parse({ data: ctx.data, path: ctx.path, parent: ctx });
- }
- };
- ZodLazy2.create = (getter, params) => {
- return new ZodLazy2({
- getter,
- typeName: ZodFirstPartyTypeKind.ZodLazy,
- ...processCreateParams(params)
- });
- };
- ZodLiteral2 = class ZodLiteral2 extends ZodType2 {
- _parse(input) {
- if (input.data !== this._def.value) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- received: ctx.data,
- code: ZodIssueCode2.invalid_literal,
- expected: this._def.value
- });
- return INVALID;
- }
- return { status: "valid", value: input.data };
- }
- get value() {
- return this._def.value;
- }
- };
- ZodLiteral2.create = (value, params) => {
- return new ZodLiteral2({
- value,
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
- ...processCreateParams(params)
- });
- };
- ZodEnum2 = class ZodEnum2 extends ZodType2 {
- _parse(input) {
- if (typeof input.data !== "string") {
- const ctx = this._getOrReturnCtx(input);
- const expectedValues = this._def.values;
- addIssueToContext(ctx, {
- expected: util10.joinValues(expectedValues),
- received: ctx.parsedType,
- code: ZodIssueCode2.invalid_type
- });
- return INVALID;
- }
- if (!this._cache) {
- this._cache = new Set(this._def.values);
- }
- if (!this._cache.has(input.data)) {
- const ctx = this._getOrReturnCtx(input);
- const expectedValues = this._def.values;
- addIssueToContext(ctx, {
- received: ctx.data,
- code: ZodIssueCode2.invalid_enum_value,
- options: expectedValues
- });
- return INVALID;
- }
- return OK(input.data);
- }
- get options() {
- return this._def.values;
- }
- get enum() {
- const enumValues = {};
- for (const val of this._def.values) {
- enumValues[val] = val;
- }
- return enumValues;
- }
- get Values() {
- const enumValues = {};
- for (const val of this._def.values) {
- enumValues[val] = val;
- }
- return enumValues;
- }
- get Enum() {
- const enumValues = {};
- for (const val of this._def.values) {
- enumValues[val] = val;
- }
- return enumValues;
- }
- extract(values2, newDef = this._def) {
- return ZodEnum2.create(values2, {
- ...this._def,
- ...newDef
- });
- }
- exclude(values2, newDef = this._def) {
- return ZodEnum2.create(this.options.filter((opt) => !values2.includes(opt)), {
- ...this._def,
- ...newDef
- });
- }
- };
- ZodEnum2.create = createZodEnum;
- ZodNativeEnum = class ZodNativeEnum extends ZodType2 {
- _parse(input) {
- const nativeEnumValues = util10.getValidEnumValues(this._def.values);
- const ctx = this._getOrReturnCtx(input);
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
- const expectedValues = util10.objectValues(nativeEnumValues);
- addIssueToContext(ctx, {
- expected: util10.joinValues(expectedValues),
- received: ctx.parsedType,
- code: ZodIssueCode2.invalid_type
- });
- return INVALID;
- }
- if (!this._cache) {
- this._cache = new Set(util10.getValidEnumValues(this._def.values));
- }
- if (!this._cache.has(input.data)) {
- const expectedValues = util10.objectValues(nativeEnumValues);
- addIssueToContext(ctx, {
- received: ctx.data,
- code: ZodIssueCode2.invalid_enum_value,
- options: expectedValues
- });
- return INVALID;
- }
- return OK(input.data);
- }
- get enum() {
- return this._def.values;
- }
- };
- ZodNativeEnum.create = (values2, params) => {
- return new ZodNativeEnum({
- values: values2,
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
- ...processCreateParams(params)
- });
- };
- ZodPromise2 = class ZodPromise2 extends ZodType2 {
- unwrap() {
- return this._def.type;
- }
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.promise,
- received: ctx.parsedType
- });
- return INVALID;
- }
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
- return OK(promisified.then((data) => {
- return this._def.type.parseAsync(data, {
- path: ctx.path,
- errorMap: ctx.common.contextualErrorMap
- });
- }));
- }
- };
- ZodPromise2.create = (schema5, params) => {
- return new ZodPromise2({
- type: schema5,
- typeName: ZodFirstPartyTypeKind.ZodPromise,
- ...processCreateParams(params)
- });
- };
- ZodEffects = class ZodEffects extends ZodType2 {
- innerType() {
- return this._def.schema;
- }
- sourceType() {
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
- }
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- const effect = this._def.effect || null;
- const checkCtx = {
- addIssue: (arg) => {
- addIssueToContext(ctx, arg);
- if (arg.fatal) {
- status.abort();
- } else {
- status.dirty();
- }
- },
- get path() {
- return ctx.path;
- }
- };
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
- if (effect.type === "preprocess") {
- const processed = effect.transform(ctx.data, checkCtx);
- if (ctx.common.async) {
- return Promise.resolve(processed).then(async (processed2) => {
- if (status.value === "aborted")
- return INVALID;
- const result = await this._def.schema._parseAsync({
- data: processed2,
- path: ctx.path,
- parent: ctx
- });
- if (result.status === "aborted")
- return INVALID;
- if (result.status === "dirty")
- return DIRTY(result.value);
- if (status.value === "dirty")
- return DIRTY(result.value);
- return result;
- });
- } else {
- if (status.value === "aborted")
- return INVALID;
- const result = this._def.schema._parseSync({
- data: processed,
- path: ctx.path,
- parent: ctx
- });
- if (result.status === "aborted")
- return INVALID;
- if (result.status === "dirty")
- return DIRTY(result.value);
- if (status.value === "dirty")
- return DIRTY(result.value);
- return result;
- }
- }
- if (effect.type === "refinement") {
- const executeRefinement = (acc) => {
- const result = effect.refinement(acc, checkCtx);
- if (ctx.common.async) {
- return Promise.resolve(result);
- }
- if (result instanceof Promise) {
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
- }
- return acc;
- };
- if (ctx.common.async === false) {
- const inner = this._def.schema._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- if (inner.status === "aborted")
- return INVALID;
- if (inner.status === "dirty")
- status.dirty();
- executeRefinement(inner.value);
- return { status: status.value, value: inner.value };
- } else {
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
- if (inner.status === "aborted")
- return INVALID;
- if (inner.status === "dirty")
- status.dirty();
- return executeRefinement(inner.value).then(() => {
- return { status: status.value, value: inner.value };
- });
- });
- }
- }
- if (effect.type === "transform") {
- if (ctx.common.async === false) {
- const base2 = this._def.schema._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- if (!isValid(base2))
- return INVALID;
- const result = effect.transform(base2.value, checkCtx);
- if (result instanceof Promise) {
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
- }
- return { status: status.value, value: result };
- } else {
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base2) => {
- if (!isValid(base2))
- return INVALID;
- return Promise.resolve(effect.transform(base2.value, checkCtx)).then((result) => ({
- status: status.value,
- value: result
- }));
- });
- }
- }
- util10.assertNever(effect);
- }
- };
- ZodEffects.create = (schema5, effect, params) => {
- return new ZodEffects({
- schema: schema5,
- typeName: ZodFirstPartyTypeKind.ZodEffects,
- effect,
- ...processCreateParams(params)
- });
- };
- ZodEffects.createWithPreprocess = (preprocess2, schema5, params) => {
- return new ZodEffects({
- schema: schema5,
- effect: { type: "preprocess", transform: preprocess2 },
- typeName: ZodFirstPartyTypeKind.ZodEffects,
- ...processCreateParams(params)
- });
- };
- ZodOptional2 = class ZodOptional2 extends ZodType2 {
- _parse(input) {
- const parsedType4 = this._getType(input);
- if (parsedType4 === ZodParsedType.undefined) {
- return OK(undefined);
- }
- return this._def.innerType._parse(input);
- }
- unwrap() {
- return this._def.innerType;
- }
- };
- ZodOptional2.create = (type, params) => {
- return new ZodOptional2({
- innerType: type,
- typeName: ZodFirstPartyTypeKind.ZodOptional,
- ...processCreateParams(params)
- });
- };
- ZodNullable2 = class ZodNullable2 extends ZodType2 {
- _parse(input) {
- const parsedType4 = this._getType(input);
- if (parsedType4 === ZodParsedType.null) {
- return OK(null);
- }
- return this._def.innerType._parse(input);
- }
- unwrap() {
- return this._def.innerType;
- }
- };
- ZodNullable2.create = (type, params) => {
- return new ZodNullable2({
- innerType: type,
- typeName: ZodFirstPartyTypeKind.ZodNullable,
- ...processCreateParams(params)
- });
- };
- ZodDefault2 = class ZodDefault2 extends ZodType2 {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- let data = ctx.data;
- if (ctx.parsedType === ZodParsedType.undefined) {
- data = this._def.defaultValue();
- }
- return this._def.innerType._parse({
- data,
- path: ctx.path,
- parent: ctx
- });
- }
- removeDefault() {
- return this._def.innerType;
- }
- };
- ZodDefault2.create = (type, params) => {
- return new ZodDefault2({
- innerType: type,
- typeName: ZodFirstPartyTypeKind.ZodDefault,
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
- ...processCreateParams(params)
- });
- };
- ZodCatch2 = class ZodCatch2 extends ZodType2 {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- const newCtx = {
- ...ctx,
- common: {
- ...ctx.common,
- issues: []
- }
- };
- const result = this._def.innerType._parse({
- data: newCtx.data,
- path: newCtx.path,
- parent: {
- ...newCtx
- }
- });
- if (isAsync(result)) {
- return result.then((result2) => {
- return {
- status: "valid",
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
- get error() {
- return new ZodError2(newCtx.common.issues);
- },
- input: newCtx.data
- })
- };
- });
- } else {
- return {
- status: "valid",
- value: result.status === "valid" ? result.value : this._def.catchValue({
- get error() {
- return new ZodError2(newCtx.common.issues);
- },
- input: newCtx.data
- })
- };
- }
- }
- removeCatch() {
- return this._def.innerType;
- }
- };
- ZodCatch2.create = (type, params) => {
- return new ZodCatch2({
- innerType: type,
- typeName: ZodFirstPartyTypeKind.ZodCatch,
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
- ...processCreateParams(params)
- });
- };
- ZodNaN2 = class ZodNaN2 extends ZodType2 {
- _parse(input) {
- const parsedType4 = this._getType(input);
- if (parsedType4 !== ZodParsedType.nan) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode2.invalid_type,
- expected: ZodParsedType.nan,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return { status: "valid", value: input.data };
- }
- };
- ZodNaN2.create = (params) => {
- return new ZodNaN2({
- typeName: ZodFirstPartyTypeKind.ZodNaN,
- ...processCreateParams(params)
- });
- };
- BRAND = Symbol("zod_brand");
- ZodBranded = class ZodBranded extends ZodType2 {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- const data = ctx.data;
- return this._def.type._parse({
- data,
- path: ctx.path,
- parent: ctx
- });
- }
- unwrap() {
- return this._def.type;
- }
- };
- ZodPipeline = class ZodPipeline extends ZodType2 {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.common.async) {
- const handleAsync = async () => {
- const inResult = await this._def.in._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- if (inResult.status === "aborted")
- return INVALID;
- if (inResult.status === "dirty") {
- status.dirty();
- return DIRTY(inResult.value);
- } else {
- return this._def.out._parseAsync({
- data: inResult.value,
- path: ctx.path,
- parent: ctx
- });
- }
- };
- return handleAsync();
- } else {
- const inResult = this._def.in._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- if (inResult.status === "aborted")
- return INVALID;
- if (inResult.status === "dirty") {
- status.dirty();
- return {
- status: "dirty",
- value: inResult.value
- };
- } else {
- return this._def.out._parseSync({
- data: inResult.value,
- path: ctx.path,
- parent: ctx
- });
- }
- }
- }
- static create(a5, b4) {
- return new ZodPipeline({
- in: a5,
- out: b4,
- typeName: ZodFirstPartyTypeKind.ZodPipeline
- });
- }
- };
- ZodReadonly2 = class ZodReadonly2 extends ZodType2 {
- _parse(input) {
- const result = this._def.innerType._parse(input);
- const freeze = (data) => {
- if (isValid(data)) {
- data.value = Object.freeze(data.value);
- }
- return data;
- };
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
- }
- unwrap() {
- return this._def.innerType;
- }
- };
- ZodReadonly2.create = (type, params) => {
- return new ZodReadonly2({
- innerType: type,
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
- ...processCreateParams(params)
- });
- };
- late = {
- object: ZodObject2.lazycreate
- };
- (function(ZodFirstPartyTypeKind2) {
- ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
- ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
- ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
- ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
- ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
- ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
- ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
- ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
- ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
- ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
- ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
- ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
- ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
- ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
- ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
- ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
- ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
- ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
- ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
- ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
- ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
- ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
- ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
- ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
- ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
- ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
- ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
- ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
- ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
- ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
- ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
- ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
- ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
- ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
- ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
- ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
- stringType = ZodString2.create;
- numberType = ZodNumber2.create;
- nanType = ZodNaN2.create;
- bigIntType = ZodBigInt2.create;
- booleanType = ZodBoolean2.create;
- dateType = ZodDate2.create;
- symbolType = ZodSymbol2.create;
- undefinedType = ZodUndefined2.create;
- nullType = ZodNull2.create;
- anyType = ZodAny2.create;
- unknownType = ZodUnknown2.create;
- neverType = ZodNever2.create;
- voidType = ZodVoid2.create;
- arrayType = ZodArray2.create;
- objectType = ZodObject2.create;
- strictObjectType = ZodObject2.strictCreate;
- unionType = ZodUnion2.create;
- discriminatedUnionType = ZodDiscriminatedUnion2.create;
- intersectionType = ZodIntersection2.create;
- tupleType = ZodTuple2.create;
- recordType = ZodRecord2.create;
- mapType = ZodMap2.create;
- setType = ZodSet2.create;
- functionType = ZodFunction.create;
- lazyType = ZodLazy2.create;
- literalType = ZodLiteral2.create;
- enumType = ZodEnum2.create;
- nativeEnumType = ZodNativeEnum.create;
- promiseType = ZodPromise2.create;
- effectsType = ZodEffects.create;
- optionalType = ZodOptional2.create;
- nullableType = ZodNullable2.create;
- preprocessType = ZodEffects.createWithPreprocess;
- pipelineType = ZodPipeline.create;
- coerce2 = {
- string: (arg) => ZodString2.create({ ...arg, coerce: true }),
- number: (arg) => ZodNumber2.create({ ...arg, coerce: true }),
- boolean: (arg) => ZodBoolean2.create({
- ...arg,
- coerce: true
- }),
- bigint: (arg) => ZodBigInt2.create({ ...arg, coerce: true }),
- date: (arg) => ZodDate2.create({ ...arg, coerce: true })
- };
- NEVER2 = INVALID;
-});
-
-// node_modules/zod/v3/external.js
-var exports_external2 = {};
-__export(exports_external2, {
- void: () => voidType,
- util: () => util10,
- unknown: () => unknownType,
- union: () => unionType,
- undefined: () => undefinedType,
- tuple: () => tupleType,
- transformer: () => effectsType,
- symbol: () => symbolType,
- string: () => stringType,
- strictObject: () => strictObjectType,
- setErrorMap: () => setErrorMap2,
- set: () => setType,
- record: () => recordType,
- quotelessJson: () => quotelessJson,
- promise: () => promiseType,
- preprocess: () => preprocessType,
- pipeline: () => pipelineType,
- ostring: () => ostring,
- optional: () => optionalType,
- onumber: () => onumber,
- oboolean: () => oboolean,
- objectUtil: () => objectUtil,
- object: () => objectType,
- number: () => numberType,
- nullable: () => nullableType,
- null: () => nullType,
- never: () => neverType,
- nativeEnum: () => nativeEnumType,
- nan: () => nanType,
- map: () => mapType,
- makeIssue: () => makeIssue,
- literal: () => literalType,
- lazy: () => lazyType,
- late: () => late,
- isValid: () => isValid,
- isDirty: () => isDirty,
- isAsync: () => isAsync,
- isAborted: () => isAborted,
- intersection: () => intersectionType,
- instanceof: () => instanceOfType,
- getParsedType: () => getParsedType2,
- getErrorMap: () => getErrorMap2,
- function: () => functionType,
- enum: () => enumType,
- effect: () => effectsType,
- discriminatedUnion: () => discriminatedUnionType,
- defaultErrorMap: () => en_default2,
- datetimeRegex: () => datetimeRegex,
- date: () => dateType,
- custom: () => custom3,
- coerce: () => coerce2,
- boolean: () => booleanType,
- bigint: () => bigIntType,
- array: () => arrayType,
- any: () => anyType,
- addIssueToContext: () => addIssueToContext,
- ZodVoid: () => ZodVoid2,
- ZodUnknown: () => ZodUnknown2,
- ZodUnion: () => ZodUnion2,
- ZodUndefined: () => ZodUndefined2,
- ZodType: () => ZodType2,
- ZodTuple: () => ZodTuple2,
- ZodTransformer: () => ZodEffects,
- ZodSymbol: () => ZodSymbol2,
- ZodString: () => ZodString2,
- ZodSet: () => ZodSet2,
- ZodSchema: () => ZodType2,
- ZodRecord: () => ZodRecord2,
- ZodReadonly: () => ZodReadonly2,
- ZodPromise: () => ZodPromise2,
- ZodPipeline: () => ZodPipeline,
- ZodParsedType: () => ZodParsedType,
- ZodOptional: () => ZodOptional2,
- ZodObject: () => ZodObject2,
- ZodNumber: () => ZodNumber2,
- ZodNullable: () => ZodNullable2,
- ZodNull: () => ZodNull2,
- ZodNever: () => ZodNever2,
- ZodNativeEnum: () => ZodNativeEnum,
- ZodNaN: () => ZodNaN2,
- ZodMap: () => ZodMap2,
- ZodLiteral: () => ZodLiteral2,
- ZodLazy: () => ZodLazy2,
- ZodIssueCode: () => ZodIssueCode2,
- ZodIntersection: () => ZodIntersection2,
- ZodFunction: () => ZodFunction,
- ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
- ZodError: () => ZodError2,
- ZodEnum: () => ZodEnum2,
- ZodEffects: () => ZodEffects,
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2,
- ZodDefault: () => ZodDefault2,
- ZodDate: () => ZodDate2,
- ZodCatch: () => ZodCatch2,
- ZodBranded: () => ZodBranded,
- ZodBoolean: () => ZodBoolean2,
- ZodBigInt: () => ZodBigInt2,
- ZodArray: () => ZodArray2,
- ZodAny: () => ZodAny2,
- Schema: () => ZodType2,
- ParseStatus: () => ParseStatus,
- OK: () => OK,
- NEVER: () => NEVER2,
- INVALID: () => INVALID,
- EMPTY_PATH: () => EMPTY_PATH,
- DIRTY: () => DIRTY,
- BRAND: () => BRAND
-});
-var init_external2 = __esm(() => {
- init_errors9();
- init_parseUtil();
- init_typeAliases();
- init_util9();
- init_types14();
- init_ZodError();
-});
-
-// node_modules/zod/index.js
-var init_zod = __esm(() => {
- init_external2();
- init_external2();
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/schemas/0.1.js
-var exports_0_1 = {};
-__export(exports_0_1, {
- McpbUserConfigurationOptionSchema: () => McpbUserConfigurationOptionSchema,
- McpbManifestToolSchema: () => McpbManifestToolSchema,
- McpbManifestServerSchema: () => McpbManifestServerSchema,
- McpbManifestSchema: () => McpbManifestSchema,
- McpbManifestRepositorySchema: () => McpbManifestRepositorySchema,
- McpbManifestPromptSchema: () => McpbManifestPromptSchema,
- McpbManifestPlatformOverrideSchema: () => McpbManifestPlatformOverrideSchema,
- McpbManifestMcpConfigSchema: () => McpbManifestMcpConfigSchema,
- McpbManifestCompatibilitySchema: () => McpbManifestCompatibilitySchema,
- McpbManifestAuthorSchema: () => McpbManifestAuthorSchema,
- McpServerConfigSchema: () => McpServerConfigSchema2,
- MANIFEST_VERSION: () => MANIFEST_VERSION
-});
-var MANIFEST_VERSION = "0.1", McpServerConfigSchema2, McpbManifestAuthorSchema, McpbManifestRepositorySchema, McpbManifestPlatformOverrideSchema, McpbManifestMcpConfigSchema, McpbManifestServerSchema, McpbManifestCompatibilitySchema, McpbManifestToolSchema, McpbManifestPromptSchema, McpbUserConfigurationOptionSchema, McpbManifestSchema;
-var init_0_1 = __esm(() => {
- init_zod();
- McpServerConfigSchema2 = strictObjectType({
- command: stringType(),
- args: arrayType(stringType()).optional(),
- env: recordType(stringType(), stringType()).optional()
- });
- McpbManifestAuthorSchema = strictObjectType({
- name: stringType(),
- email: stringType().email().optional(),
- url: stringType().url().optional()
- });
- McpbManifestRepositorySchema = strictObjectType({
- type: stringType(),
- url: stringType().url()
- });
- McpbManifestPlatformOverrideSchema = McpServerConfigSchema2.partial();
- McpbManifestMcpConfigSchema = McpServerConfigSchema2.extend({
- platform_overrides: recordType(stringType(), McpbManifestPlatformOverrideSchema).optional()
- });
- McpbManifestServerSchema = strictObjectType({
- type: enumType(["python", "node", "binary"]),
- entry_point: stringType(),
- mcp_config: McpbManifestMcpConfigSchema
- });
- McpbManifestCompatibilitySchema = strictObjectType({
- claude_desktop: stringType().optional(),
- platforms: arrayType(enumType(["darwin", "win32", "linux"])).optional(),
- runtimes: strictObjectType({
- python: stringType().optional(),
- node: stringType().optional()
- }).optional()
- });
- McpbManifestToolSchema = strictObjectType({
- name: stringType(),
- description: stringType().optional()
- });
- McpbManifestPromptSchema = strictObjectType({
- name: stringType(),
- description: stringType().optional(),
- arguments: arrayType(stringType()).optional(),
- text: stringType()
- });
- McpbUserConfigurationOptionSchema = strictObjectType({
- type: enumType(["string", "number", "boolean", "directory", "file"]),
- title: stringType(),
- description: stringType(),
- required: booleanType().optional(),
- default: unionType([stringType(), numberType(), booleanType(), arrayType(stringType())]).optional(),
- multiple: booleanType().optional(),
- sensitive: booleanType().optional(),
- min: numberType().optional(),
- max: numberType().optional()
- });
- McpbManifestSchema = strictObjectType({
- $schema: stringType().optional(),
- dxt_version: literalType(MANIFEST_VERSION).optional().describe("@deprecated Use manifest_version instead"),
- manifest_version: literalType(MANIFEST_VERSION).optional(),
- name: stringType(),
- display_name: stringType().optional(),
- version: stringType(),
- description: stringType(),
- long_description: stringType().optional(),
- author: McpbManifestAuthorSchema,
- repository: McpbManifestRepositorySchema.optional(),
- homepage: stringType().url().optional(),
- documentation: stringType().url().optional(),
- support: stringType().url().optional(),
- icon: stringType().optional(),
- screenshots: arrayType(stringType()).optional(),
- server: McpbManifestServerSchema,
- tools: arrayType(McpbManifestToolSchema).optional(),
- tools_generated: booleanType().optional(),
- prompts: arrayType(McpbManifestPromptSchema).optional(),
- prompts_generated: booleanType().optional(),
- keywords: arrayType(stringType()).optional(),
- license: stringType().optional(),
- compatibility: McpbManifestCompatibilitySchema.optional(),
- user_config: recordType(stringType(), McpbUserConfigurationOptionSchema).optional()
- }).refine((data) => !!(data.dxt_version || data.manifest_version), {
- message: "Either 'dxt_version' (deprecated) or 'manifest_version' must be provided"
- });
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/schemas/0.2.js
-var exports_0_2 = {};
-__export(exports_0_2, {
- McpbUserConfigurationOptionSchema: () => McpbUserConfigurationOptionSchema2,
- McpbManifestToolSchema: () => McpbManifestToolSchema2,
- McpbManifestServerSchema: () => McpbManifestServerSchema2,
- McpbManifestSchema: () => McpbManifestSchema2,
- McpbManifestRepositorySchema: () => McpbManifestRepositorySchema2,
- McpbManifestPromptSchema: () => McpbManifestPromptSchema2,
- McpbManifestPlatformOverrideSchema: () => McpbManifestPlatformOverrideSchema2,
- McpbManifestMcpConfigSchema: () => McpbManifestMcpConfigSchema2,
- McpbManifestCompatibilitySchema: () => McpbManifestCompatibilitySchema2,
- McpbManifestAuthorSchema: () => McpbManifestAuthorSchema2,
- McpServerConfigSchema: () => McpServerConfigSchema3,
- MANIFEST_VERSION: () => MANIFEST_VERSION2
-});
-var MANIFEST_VERSION2 = "0.2", McpServerConfigSchema3, McpbManifestAuthorSchema2, McpbManifestRepositorySchema2, McpbManifestPlatformOverrideSchema2, McpbManifestMcpConfigSchema2, McpbManifestServerSchema2, McpbManifestCompatibilitySchema2, McpbManifestToolSchema2, McpbManifestPromptSchema2, McpbUserConfigurationOptionSchema2, McpbManifestSchema2;
-var init_0_2 = __esm(() => {
- init_zod();
- McpServerConfigSchema3 = strictObjectType({
- command: stringType(),
- args: arrayType(stringType()).optional(),
- env: recordType(stringType(), stringType()).optional()
- });
- McpbManifestAuthorSchema2 = strictObjectType({
- name: stringType(),
- email: stringType().email().optional(),
- url: stringType().url().optional()
- });
- McpbManifestRepositorySchema2 = strictObjectType({
- type: stringType(),
- url: stringType().url()
- });
- McpbManifestPlatformOverrideSchema2 = McpServerConfigSchema3.partial();
- McpbManifestMcpConfigSchema2 = McpServerConfigSchema3.extend({
- platform_overrides: recordType(stringType(), McpbManifestPlatformOverrideSchema2).optional()
- });
- McpbManifestServerSchema2 = strictObjectType({
- type: enumType(["python", "node", "binary"]),
- entry_point: stringType(),
- mcp_config: McpbManifestMcpConfigSchema2
- });
- McpbManifestCompatibilitySchema2 = strictObjectType({
- claude_desktop: stringType().optional(),
- platforms: arrayType(enumType(["darwin", "win32", "linux"])).optional(),
- runtimes: strictObjectType({
- python: stringType().optional(),
- node: stringType().optional()
- }).optional()
- });
- McpbManifestToolSchema2 = strictObjectType({
- name: stringType(),
- description: stringType().optional()
- });
- McpbManifestPromptSchema2 = strictObjectType({
- name: stringType(),
- description: stringType().optional(),
- arguments: arrayType(stringType()).optional(),
- text: stringType()
- });
- McpbUserConfigurationOptionSchema2 = strictObjectType({
- type: enumType(["string", "number", "boolean", "directory", "file"]),
- title: stringType(),
- description: stringType(),
- required: booleanType().optional(),
- default: unionType([stringType(), numberType(), booleanType(), arrayType(stringType())]).optional(),
- multiple: booleanType().optional(),
- sensitive: booleanType().optional(),
- min: numberType().optional(),
- max: numberType().optional()
- });
- McpbManifestSchema2 = strictObjectType({
- $schema: stringType().optional(),
- dxt_version: literalType(MANIFEST_VERSION2).optional().describe("@deprecated Use manifest_version instead"),
- manifest_version: literalType(MANIFEST_VERSION2).optional(),
- name: stringType(),
- display_name: stringType().optional(),
- version: stringType(),
- description: stringType(),
- long_description: stringType().optional(),
- author: McpbManifestAuthorSchema2,
- repository: McpbManifestRepositorySchema2.optional(),
- homepage: stringType().url().optional(),
- documentation: stringType().url().optional(),
- support: stringType().url().optional(),
- icon: stringType().optional(),
- screenshots: arrayType(stringType()).optional(),
- server: McpbManifestServerSchema2,
- tools: arrayType(McpbManifestToolSchema2).optional(),
- tools_generated: booleanType().optional(),
- prompts: arrayType(McpbManifestPromptSchema2).optional(),
- prompts_generated: booleanType().optional(),
- keywords: arrayType(stringType()).optional(),
- license: stringType().optional(),
- privacy_policies: arrayType(stringType().url()).optional(),
- compatibility: McpbManifestCompatibilitySchema2.optional(),
- user_config: recordType(stringType(), McpbUserConfigurationOptionSchema2).optional()
- }).refine((data) => !!(data.dxt_version || data.manifest_version), {
- message: "Either 'dxt_version' (deprecated) or 'manifest_version' must be provided"
- });
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/schemas/0.3.js
-var exports_0_3 = {};
-__export(exports_0_3, {
- McpbUserConfigurationOptionSchema: () => McpbUserConfigurationOptionSchema3,
- McpbManifestToolSchema: () => McpbManifestToolSchema3,
- McpbManifestServerSchema: () => McpbManifestServerSchema3,
- McpbManifestSchema: () => McpbManifestSchema3,
- McpbManifestRepositorySchema: () => McpbManifestRepositorySchema3,
- McpbManifestPromptSchema: () => McpbManifestPromptSchema3,
- McpbManifestPlatformOverrideSchema: () => McpbManifestPlatformOverrideSchema3,
- McpbManifestMcpConfigSchema: () => McpbManifestMcpConfigSchema3,
- McpbManifestLocalizationSchema: () => McpbManifestLocalizationSchema,
- McpbManifestIconSchema: () => McpbManifestIconSchema,
- McpbManifestCompatibilitySchema: () => McpbManifestCompatibilitySchema3,
- McpbManifestAuthorSchema: () => McpbManifestAuthorSchema3,
- McpServerConfigSchema: () => McpServerConfigSchema4,
- MANIFEST_VERSION: () => MANIFEST_VERSION3
-});
-var MANIFEST_VERSION3 = "0.3", LOCALE_PLACEHOLDER_REGEX, BCP47_REGEX, ICON_SIZE_REGEX, McpServerConfigSchema4, McpbManifestAuthorSchema3, McpbManifestRepositorySchema3, McpbManifestPlatformOverrideSchema3, McpbManifestMcpConfigSchema3, McpbManifestServerSchema3, McpbManifestCompatibilitySchema3, McpbManifestToolSchema3, McpbManifestPromptSchema3, McpbUserConfigurationOptionSchema3, McpbManifestLocalizationSchema, McpbManifestIconSchema, McpbManifestSchema3;
-var init_0_3 = __esm(() => {
- init_zod();
- LOCALE_PLACEHOLDER_REGEX = /\$\{locale\}/i;
- BCP47_REGEX = /^[A-Za-z0-9]{2,8}(?:-[A-Za-z0-9]{1,8})*$/;
- ICON_SIZE_REGEX = /^\d+x\d+$/;
- McpServerConfigSchema4 = strictObjectType({
- command: stringType(),
- args: arrayType(stringType()).optional(),
- env: recordType(stringType(), stringType()).optional()
- });
- McpbManifestAuthorSchema3 = strictObjectType({
- name: stringType(),
- email: stringType().email().optional(),
- url: stringType().url().optional()
- });
- McpbManifestRepositorySchema3 = strictObjectType({
- type: stringType(),
- url: stringType().url()
- });
- McpbManifestPlatformOverrideSchema3 = McpServerConfigSchema4.partial();
- McpbManifestMcpConfigSchema3 = McpServerConfigSchema4.extend({
- platform_overrides: recordType(stringType(), McpbManifestPlatformOverrideSchema3).optional()
- });
- McpbManifestServerSchema3 = strictObjectType({
- type: enumType(["python", "node", "binary"]),
- entry_point: stringType(),
- mcp_config: McpbManifestMcpConfigSchema3
- });
- McpbManifestCompatibilitySchema3 = strictObjectType({
- claude_desktop: stringType().optional(),
- platforms: arrayType(enumType(["darwin", "win32", "linux"])).optional(),
- runtimes: strictObjectType({
- python: stringType().optional(),
- node: stringType().optional()
- }).optional()
- });
- McpbManifestToolSchema3 = strictObjectType({
- name: stringType(),
- description: stringType().optional()
- });
- McpbManifestPromptSchema3 = strictObjectType({
- name: stringType(),
- description: stringType().optional(),
- arguments: arrayType(stringType()).optional(),
- text: stringType()
- });
- McpbUserConfigurationOptionSchema3 = strictObjectType({
- type: enumType(["string", "number", "boolean", "directory", "file"]),
- title: stringType(),
- description: stringType(),
- required: booleanType().optional(),
- default: unionType([stringType(), numberType(), booleanType(), arrayType(stringType())]).optional(),
- multiple: booleanType().optional(),
- sensitive: booleanType().optional(),
- min: numberType().optional(),
- max: numberType().optional()
- });
- McpbManifestLocalizationSchema = strictObjectType({
- resources: stringType().regex(LOCALE_PLACEHOLDER_REGEX, 'resources must include a "${locale}" placeholder'),
- default_locale: stringType().regex(BCP47_REGEX, "default_locale must be a valid BCP 47 locale identifier")
- });
- McpbManifestIconSchema = strictObjectType({
- src: stringType(),
- size: stringType().regex(ICON_SIZE_REGEX, 'size must be in the format "WIDTHxHEIGHT" (e.g., "16x16")'),
- theme: stringType().min(1, "theme cannot be empty when provided").optional()
- });
- McpbManifestSchema3 = strictObjectType({
- $schema: stringType().optional(),
- dxt_version: literalType(MANIFEST_VERSION3).optional().describe("@deprecated Use manifest_version instead"),
- manifest_version: literalType(MANIFEST_VERSION3).optional(),
- name: stringType(),
- display_name: stringType().optional(),
- version: stringType(),
- description: stringType(),
- long_description: stringType().optional(),
- author: McpbManifestAuthorSchema3,
- repository: McpbManifestRepositorySchema3.optional(),
- homepage: stringType().url().optional(),
- documentation: stringType().url().optional(),
- support: stringType().url().optional(),
- icon: stringType().optional(),
- icons: arrayType(McpbManifestIconSchema).optional(),
- screenshots: arrayType(stringType()).optional(),
- localization: McpbManifestLocalizationSchema.optional(),
- server: McpbManifestServerSchema3,
- tools: arrayType(McpbManifestToolSchema3).optional(),
- tools_generated: booleanType().optional(),
- prompts: arrayType(McpbManifestPromptSchema3).optional(),
- prompts_generated: booleanType().optional(),
- keywords: arrayType(stringType()).optional(),
- license: stringType().optional(),
- privacy_policies: arrayType(stringType().url()).optional(),
- compatibility: McpbManifestCompatibilitySchema3.optional(),
- user_config: recordType(stringType(), McpbUserConfigurationOptionSchema3).optional(),
- _meta: recordType(stringType(), recordType(stringType(), anyType())).optional()
- }).refine((data) => !!(data.dxt_version || data.manifest_version), {
- message: "Either 'dxt_version' (deprecated) or 'manifest_version' must be provided"
- });
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/schemas/0.4.js
-var exports_0_4 = {};
-__export(exports_0_4, {
- McpbUserConfigurationOptionSchema: () => McpbUserConfigurationOptionSchema4,
- McpbManifestToolSchema: () => McpbManifestToolSchema4,
- McpbManifestServerSchema: () => McpbManifestServerSchema4,
- McpbManifestSchema: () => McpbManifestSchema4,
- McpbManifestRepositorySchema: () => McpbManifestRepositorySchema4,
- McpbManifestPromptSchema: () => McpbManifestPromptSchema4,
- McpbManifestPlatformOverrideSchema: () => McpbManifestPlatformOverrideSchema4,
- McpbManifestMcpConfigSchema: () => McpbManifestMcpConfigSchema4,
- McpbManifestLocalizationSchema: () => McpbManifestLocalizationSchema2,
- McpbManifestIconSchema: () => McpbManifestIconSchema2,
- McpbManifestCompatibilitySchema: () => McpbManifestCompatibilitySchema4,
- McpbManifestAuthorSchema: () => McpbManifestAuthorSchema4,
- McpServerConfigSchema: () => McpServerConfigSchema5,
- MANIFEST_VERSION: () => MANIFEST_VERSION4
-});
-var MANIFEST_VERSION4 = "0.4", LOCALE_PLACEHOLDER_REGEX2, BCP47_REGEX2, ICON_SIZE_REGEX2, McpServerConfigSchema5, McpbManifestAuthorSchema4, McpbManifestRepositorySchema4, McpbManifestPlatformOverrideSchema4, McpbManifestMcpConfigSchema4, McpbManifestServerSchema4, McpbManifestCompatibilitySchema4, McpbManifestToolSchema4, McpbManifestPromptSchema4, McpbUserConfigurationOptionSchema4, McpbManifestLocalizationSchema2, McpbManifestIconSchema2, McpbManifestSchema4;
-var init_0_4 = __esm(() => {
- init_zod();
- LOCALE_PLACEHOLDER_REGEX2 = /\$\{locale\}/i;
- BCP47_REGEX2 = /^[A-Za-z0-9]{2,8}(?:-[A-Za-z0-9]{1,8})*$/;
- ICON_SIZE_REGEX2 = /^\d+x\d+$/;
- McpServerConfigSchema5 = strictObjectType({
- command: stringType(),
- args: arrayType(stringType()).optional(),
- env: recordType(stringType(), stringType()).optional()
- });
- McpbManifestAuthorSchema4 = strictObjectType({
- name: stringType(),
- email: stringType().email().optional(),
- url: stringType().url().optional()
- });
- McpbManifestRepositorySchema4 = strictObjectType({
- type: stringType(),
- url: stringType().url()
- });
- McpbManifestPlatformOverrideSchema4 = McpServerConfigSchema5.partial();
- McpbManifestMcpConfigSchema4 = McpServerConfigSchema5.extend({
- platform_overrides: recordType(stringType(), McpbManifestPlatformOverrideSchema4).optional()
- });
- McpbManifestServerSchema4 = strictObjectType({
- type: enumType(["python", "node", "binary", "uv"]),
- entry_point: stringType(),
- mcp_config: McpbManifestMcpConfigSchema4
- });
- McpbManifestCompatibilitySchema4 = strictObjectType({
- claude_desktop: stringType().optional(),
- platforms: arrayType(enumType(["darwin", "win32", "linux"])).optional(),
- runtimes: strictObjectType({
- python: stringType().optional(),
- node: stringType().optional()
- }).optional()
- });
- McpbManifestToolSchema4 = strictObjectType({
- name: stringType(),
- description: stringType().optional()
- });
- McpbManifestPromptSchema4 = strictObjectType({
- name: stringType(),
- description: stringType().optional(),
- arguments: arrayType(stringType()).optional(),
- text: stringType()
- });
- McpbUserConfigurationOptionSchema4 = strictObjectType({
- type: enumType(["string", "number", "boolean", "directory", "file"]),
- title: stringType(),
- description: stringType(),
- required: booleanType().optional(),
- default: unionType([stringType(), numberType(), booleanType(), arrayType(stringType())]).optional(),
- multiple: booleanType().optional(),
- sensitive: booleanType().optional(),
- min: numberType().optional(),
- max: numberType().optional()
- });
- McpbManifestLocalizationSchema2 = strictObjectType({
- resources: stringType().regex(LOCALE_PLACEHOLDER_REGEX2, 'resources must include a "${locale}" placeholder'),
- default_locale: stringType().regex(BCP47_REGEX2, "default_locale must be a valid BCP 47 locale identifier")
- });
- McpbManifestIconSchema2 = strictObjectType({
- src: stringType(),
- size: stringType().regex(ICON_SIZE_REGEX2, 'size must be in the format "WIDTHxHEIGHT" (e.g., "16x16")'),
- theme: stringType().min(1, "theme cannot be empty when provided").optional()
- });
- McpbManifestSchema4 = strictObjectType({
- $schema: stringType().optional(),
- dxt_version: literalType(MANIFEST_VERSION4).optional().describe("@deprecated Use manifest_version instead"),
- manifest_version: literalType(MANIFEST_VERSION4).optional(),
- name: stringType(),
- display_name: stringType().optional(),
- version: stringType(),
- description: stringType(),
- long_description: stringType().optional(),
- author: McpbManifestAuthorSchema4,
- repository: McpbManifestRepositorySchema4.optional(),
- homepage: stringType().url().optional(),
- documentation: stringType().url().optional(),
- support: stringType().url().optional(),
- icon: stringType().optional(),
- icons: arrayType(McpbManifestIconSchema2).optional(),
- screenshots: arrayType(stringType()).optional(),
- localization: McpbManifestLocalizationSchema2.optional(),
- server: McpbManifestServerSchema4,
- tools: arrayType(McpbManifestToolSchema4).optional(),
- tools_generated: booleanType().optional(),
- prompts: arrayType(McpbManifestPromptSchema4).optional(),
- prompts_generated: booleanType().optional(),
- keywords: arrayType(stringType()).optional(),
- license: stringType().optional(),
- privacy_policies: arrayType(stringType().url()).optional(),
- compatibility: McpbManifestCompatibilitySchema4.optional(),
- user_config: recordType(stringType(), McpbUserConfigurationOptionSchema4).optional(),
- _meta: recordType(stringType(), recordType(stringType(), anyType())).optional()
- }).refine((data) => !!(data.dxt_version || data.manifest_version), {
- message: "Either 'dxt_version' (deprecated) or 'manifest_version' must be provided"
- });
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/schemas_loose/0.1.js
-var MANIFEST_VERSION5 = "0.1", McpServerConfigSchema6, McpbManifestAuthorSchema5, McpbManifestRepositorySchema5, McpbManifestPlatformOverrideSchema5, McpbManifestMcpConfigSchema5, McpbManifestServerSchema5, McpbManifestCompatibilitySchema5, McpbManifestToolSchema5, McpbManifestPromptSchema5, McpbUserConfigurationOptionSchema5, McpbManifestSchema5;
-var init_0_12 = __esm(() => {
- init_zod();
- McpServerConfigSchema6 = objectType({
- command: stringType(),
- args: arrayType(stringType()).optional(),
- env: recordType(stringType(), stringType()).optional()
- });
- McpbManifestAuthorSchema5 = objectType({
- name: stringType(),
- email: stringType().email().optional(),
- url: stringType().url().optional()
- });
- McpbManifestRepositorySchema5 = objectType({
- type: stringType(),
- url: stringType().url()
- });
- McpbManifestPlatformOverrideSchema5 = McpServerConfigSchema6.partial();
- McpbManifestMcpConfigSchema5 = McpServerConfigSchema6.extend({
- platform_overrides: recordType(stringType(), McpbManifestPlatformOverrideSchema5).optional()
- });
- McpbManifestServerSchema5 = objectType({
- type: enumType(["python", "node", "binary"]),
- entry_point: stringType(),
- mcp_config: McpbManifestMcpConfigSchema5
- });
- McpbManifestCompatibilitySchema5 = objectType({
- claude_desktop: stringType().optional(),
- platforms: arrayType(enumType(["darwin", "win32", "linux"])).optional(),
- runtimes: objectType({
- python: stringType().optional(),
- node: stringType().optional()
- }).optional()
- }).passthrough();
- McpbManifestToolSchema5 = objectType({
- name: stringType(),
- description: stringType().optional()
- });
- McpbManifestPromptSchema5 = objectType({
- name: stringType(),
- description: stringType().optional(),
- arguments: arrayType(stringType()).optional(),
- text: stringType()
- });
- McpbUserConfigurationOptionSchema5 = objectType({
- type: enumType(["string", "number", "boolean", "directory", "file"]),
- title: stringType(),
- description: stringType(),
- required: booleanType().optional(),
- default: unionType([stringType(), numberType(), booleanType(), arrayType(stringType())]).optional(),
- multiple: booleanType().optional(),
- sensitive: booleanType().optional(),
- min: numberType().optional(),
- max: numberType().optional()
- });
- McpbManifestSchema5 = objectType({
- $schema: stringType().optional(),
- dxt_version: literalType(MANIFEST_VERSION5).optional().describe("@deprecated Use manifest_version instead"),
- manifest_version: literalType(MANIFEST_VERSION5).optional(),
- name: stringType(),
- display_name: stringType().optional(),
- version: stringType(),
- description: stringType(),
- long_description: stringType().optional(),
- author: McpbManifestAuthorSchema5,
- repository: McpbManifestRepositorySchema5.optional(),
- homepage: stringType().url().optional(),
- documentation: stringType().url().optional(),
- support: stringType().url().optional(),
- icon: stringType().optional(),
- screenshots: arrayType(stringType()).optional(),
- server: McpbManifestServerSchema5,
- tools: arrayType(McpbManifestToolSchema5).optional(),
- tools_generated: booleanType().optional(),
- prompts: arrayType(McpbManifestPromptSchema5).optional(),
- prompts_generated: booleanType().optional(),
- keywords: arrayType(stringType()).optional(),
- license: stringType().optional(),
- compatibility: McpbManifestCompatibilitySchema5.optional(),
- user_config: recordType(stringType(), McpbUserConfigurationOptionSchema5).optional()
- }).refine((data) => !!(data.dxt_version || data.manifest_version), {
- message: "Either 'dxt_version' (deprecated) or 'manifest_version' must be provided"
- });
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/schemas_loose/0.2.js
-var MANIFEST_VERSION6 = "0.2", McpServerConfigSchema7, McpbManifestAuthorSchema6, McpbManifestRepositorySchema6, McpbManifestPlatformOverrideSchema6, McpbManifestMcpConfigSchema6, McpbManifestServerSchema6, McpbManifestCompatibilitySchema6, McpbManifestToolSchema6, McpbManifestPromptSchema6, McpbUserConfigurationOptionSchema6, McpbManifestSchema6;
-var init_0_22 = __esm(() => {
- init_zod();
- McpServerConfigSchema7 = objectType({
- command: stringType(),
- args: arrayType(stringType()).optional(),
- env: recordType(stringType(), stringType()).optional()
- });
- McpbManifestAuthorSchema6 = objectType({
- name: stringType(),
- email: stringType().email().optional(),
- url: stringType().url().optional()
- });
- McpbManifestRepositorySchema6 = objectType({
- type: stringType(),
- url: stringType().url()
- });
- McpbManifestPlatformOverrideSchema6 = McpServerConfigSchema7.partial();
- McpbManifestMcpConfigSchema6 = McpServerConfigSchema7.extend({
- platform_overrides: recordType(stringType(), McpbManifestPlatformOverrideSchema6).optional()
- });
- McpbManifestServerSchema6 = objectType({
- type: enumType(["python", "node", "binary"]),
- entry_point: stringType(),
- mcp_config: McpbManifestMcpConfigSchema6
- });
- McpbManifestCompatibilitySchema6 = objectType({
- claude_desktop: stringType().optional(),
- platforms: arrayType(enumType(["darwin", "win32", "linux"])).optional(),
- runtimes: objectType({
- python: stringType().optional(),
- node: stringType().optional()
- }).optional()
- }).passthrough();
- McpbManifestToolSchema6 = objectType({
- name: stringType(),
- description: stringType().optional()
- });
- McpbManifestPromptSchema6 = objectType({
- name: stringType(),
- description: stringType().optional(),
- arguments: arrayType(stringType()).optional(),
- text: stringType()
- });
- McpbUserConfigurationOptionSchema6 = objectType({
- type: enumType(["string", "number", "boolean", "directory", "file"]),
- title: stringType(),
- description: stringType(),
- required: booleanType().optional(),
- default: unionType([stringType(), numberType(), booleanType(), arrayType(stringType())]).optional(),
- multiple: booleanType().optional(),
- sensitive: booleanType().optional(),
- min: numberType().optional(),
- max: numberType().optional()
- });
- McpbManifestSchema6 = objectType({
- $schema: stringType().optional(),
- dxt_version: literalType(MANIFEST_VERSION6).optional().describe("@deprecated Use manifest_version instead"),
- manifest_version: literalType(MANIFEST_VERSION6).optional(),
- name: stringType(),
- display_name: stringType().optional(),
- version: stringType(),
- description: stringType(),
- long_description: stringType().optional(),
- author: McpbManifestAuthorSchema6,
- repository: McpbManifestRepositorySchema6.optional(),
- homepage: stringType().url().optional(),
- documentation: stringType().url().optional(),
- support: stringType().url().optional(),
- icon: stringType().optional(),
- screenshots: arrayType(stringType()).optional(),
- server: McpbManifestServerSchema6,
- tools: arrayType(McpbManifestToolSchema6).optional(),
- tools_generated: booleanType().optional(),
- prompts: arrayType(McpbManifestPromptSchema6).optional(),
- prompts_generated: booleanType().optional(),
- keywords: arrayType(stringType()).optional(),
- license: stringType().optional(),
- privacy_policies: arrayType(stringType().url()).optional(),
- compatibility: McpbManifestCompatibilitySchema6.optional(),
- user_config: recordType(stringType(), McpbUserConfigurationOptionSchema6).optional()
- }).passthrough().refine((data) => !!(data.dxt_version || data.manifest_version), {
- message: "Either 'dxt_version' (deprecated) or 'manifest_version' must be provided"
- });
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/schemas_loose/0.3.js
-var MANIFEST_VERSION7 = "0.3", LOCALE_PLACEHOLDER_REGEX3, BCP47_REGEX3, ICON_SIZE_REGEX3, McpServerConfigSchema8, McpbManifestAuthorSchema7, McpbManifestRepositorySchema7, McpbManifestPlatformOverrideSchema7, McpbManifestMcpConfigSchema7, McpbManifestServerSchema7, McpbManifestCompatibilitySchema7, McpbManifestToolSchema7, McpbManifestPromptSchema7, McpbUserConfigurationOptionSchema7, McpbManifestLocalizationSchema3, McpbManifestIconSchema3, McpbManifestSchema7;
-var init_0_32 = __esm(() => {
- init_zod();
- LOCALE_PLACEHOLDER_REGEX3 = /\$\{locale\}/i;
- BCP47_REGEX3 = /^[A-Za-z0-9]{2,8}(?:-[A-Za-z0-9]{1,8})*$/;
- ICON_SIZE_REGEX3 = /^\d+x\d+$/;
- McpServerConfigSchema8 = objectType({
- command: stringType(),
- args: arrayType(stringType()).optional(),
- env: recordType(stringType(), stringType()).optional()
- });
- McpbManifestAuthorSchema7 = objectType({
- name: stringType(),
- email: stringType().email().optional(),
- url: stringType().url().optional()
- });
- McpbManifestRepositorySchema7 = objectType({
- type: stringType(),
- url: stringType().url()
- });
- McpbManifestPlatformOverrideSchema7 = McpServerConfigSchema8.partial();
- McpbManifestMcpConfigSchema7 = McpServerConfigSchema8.extend({
- platform_overrides: recordType(stringType(), McpbManifestPlatformOverrideSchema7).optional()
- });
- McpbManifestServerSchema7 = objectType({
- type: enumType(["python", "node", "binary"]),
- entry_point: stringType(),
- mcp_config: McpbManifestMcpConfigSchema7
- });
- McpbManifestCompatibilitySchema7 = objectType({
- claude_desktop: stringType().optional(),
- platforms: arrayType(enumType(["darwin", "win32", "linux"])).optional(),
- runtimes: objectType({
- python: stringType().optional(),
- node: stringType().optional()
- }).optional()
- }).passthrough();
- McpbManifestToolSchema7 = objectType({
- name: stringType(),
- description: stringType().optional()
- });
- McpbManifestPromptSchema7 = objectType({
- name: stringType(),
- description: stringType().optional(),
- arguments: arrayType(stringType()).optional(),
- text: stringType()
- });
- McpbUserConfigurationOptionSchema7 = objectType({
- type: enumType(["string", "number", "boolean", "directory", "file"]),
- title: stringType(),
- description: stringType(),
- required: booleanType().optional(),
- default: unionType([stringType(), numberType(), booleanType(), arrayType(stringType())]).optional(),
- multiple: booleanType().optional(),
- sensitive: booleanType().optional(),
- min: numberType().optional(),
- max: numberType().optional()
- });
- McpbManifestLocalizationSchema3 = objectType({
- resources: stringType().regex(LOCALE_PLACEHOLDER_REGEX3, 'resources must include a "${locale}" placeholder'),
- default_locale: stringType().regex(BCP47_REGEX3, "default_locale must be a valid BCP 47 locale identifier")
- }).passthrough();
- McpbManifestIconSchema3 = objectType({
- src: stringType(),
- size: stringType().regex(ICON_SIZE_REGEX3, 'size must be in the format "WIDTHxHEIGHT" (e.g., "16x16")'),
- theme: stringType().min(1).optional()
- }).passthrough();
- McpbManifestSchema7 = objectType({
- $schema: stringType().optional(),
- dxt_version: literalType(MANIFEST_VERSION7).optional().describe("@deprecated Use manifest_version instead"),
- manifest_version: literalType(MANIFEST_VERSION7).optional(),
- name: stringType(),
- display_name: stringType().optional(),
- version: stringType(),
- description: stringType(),
- long_description: stringType().optional(),
- author: McpbManifestAuthorSchema7,
- repository: McpbManifestRepositorySchema7.optional(),
- homepage: stringType().url().optional(),
- documentation: stringType().url().optional(),
- support: stringType().url().optional(),
- icon: stringType().optional(),
- icons: arrayType(McpbManifestIconSchema3).optional(),
- screenshots: arrayType(stringType()).optional(),
- localization: McpbManifestLocalizationSchema3.optional(),
- server: McpbManifestServerSchema7,
- tools: arrayType(McpbManifestToolSchema7).optional(),
- tools_generated: booleanType().optional(),
- prompts: arrayType(McpbManifestPromptSchema7).optional(),
- prompts_generated: booleanType().optional(),
- keywords: arrayType(stringType()).optional(),
- license: stringType().optional(),
- privacy_policies: arrayType(stringType().url()).optional(),
- compatibility: McpbManifestCompatibilitySchema7.optional(),
- user_config: recordType(stringType(), McpbUserConfigurationOptionSchema7).optional(),
- _meta: recordType(stringType(), recordType(stringType(), anyType())).optional()
- }).passthrough().refine((data) => !!(data.dxt_version || data.manifest_version), {
- message: "Either 'dxt_version' (deprecated) or 'manifest_version' must be provided"
- });
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/schemas_loose/0.4.js
-var MANIFEST_VERSION8 = "0.4", LOCALE_PLACEHOLDER_REGEX4, BCP47_REGEX4, ICON_SIZE_REGEX4, McpServerConfigSchema9, McpbManifestAuthorSchema8, McpbManifestRepositorySchema8, McpbManifestPlatformOverrideSchema8, McpbManifestMcpConfigSchema8, McpbManifestServerSchema8, McpbManifestCompatibilitySchema8, McpbManifestToolSchema8, McpbManifestPromptSchema8, McpbUserConfigurationOptionSchema8, McpbManifestLocalizationSchema4, McpbManifestIconSchema4, McpbManifestSchema8;
-var init_0_42 = __esm(() => {
- init_zod();
- LOCALE_PLACEHOLDER_REGEX4 = /\$\{locale\}/i;
- BCP47_REGEX4 = /^[A-Za-z0-9]{2,8}(?:-[A-Za-z0-9]{1,8})*$/;
- ICON_SIZE_REGEX4 = /^\d+x\d+$/;
- McpServerConfigSchema9 = objectType({
- command: stringType(),
- args: arrayType(stringType()).optional(),
- env: recordType(stringType(), stringType()).optional()
- });
- McpbManifestAuthorSchema8 = objectType({
- name: stringType(),
- email: stringType().email().optional(),
- url: stringType().url().optional()
- });
- McpbManifestRepositorySchema8 = objectType({
- type: stringType(),
- url: stringType().url()
- });
- McpbManifestPlatformOverrideSchema8 = McpServerConfigSchema9.partial();
- McpbManifestMcpConfigSchema8 = McpServerConfigSchema9.extend({
- platform_overrides: recordType(stringType(), McpbManifestPlatformOverrideSchema8).optional()
- });
- McpbManifestServerSchema8 = objectType({
- type: enumType(["python", "node", "binary", "uv"]),
- entry_point: stringType(),
- mcp_config: McpbManifestMcpConfigSchema8.optional()
- });
- McpbManifestCompatibilitySchema8 = objectType({
- claude_desktop: stringType().optional(),
- platforms: arrayType(enumType(["darwin", "win32", "linux"])).optional(),
- runtimes: objectType({
- python: stringType().optional(),
- node: stringType().optional()
- }).optional()
- }).passthrough();
- McpbManifestToolSchema8 = objectType({
- name: stringType(),
- description: stringType().optional()
- });
- McpbManifestPromptSchema8 = objectType({
- name: stringType(),
- description: stringType().optional(),
- arguments: arrayType(stringType()).optional(),
- text: stringType()
- });
- McpbUserConfigurationOptionSchema8 = objectType({
- type: enumType(["string", "number", "boolean", "directory", "file"]),
- title: stringType(),
- description: stringType(),
- required: booleanType().optional(),
- default: unionType([stringType(), numberType(), booleanType(), arrayType(stringType())]).optional(),
- multiple: booleanType().optional(),
- sensitive: booleanType().optional(),
- min: numberType().optional(),
- max: numberType().optional()
- });
- McpbManifestLocalizationSchema4 = objectType({
- resources: stringType().regex(LOCALE_PLACEHOLDER_REGEX4, 'resources must include a "${locale}" placeholder'),
- default_locale: stringType().regex(BCP47_REGEX4, "default_locale must be a valid BCP 47 locale identifier")
- }).passthrough();
- McpbManifestIconSchema4 = objectType({
- src: stringType(),
- size: stringType().regex(ICON_SIZE_REGEX4, 'size must be in the format "WIDTHxHEIGHT" (e.g., "16x16")'),
- theme: stringType().min(1).optional()
- }).passthrough();
- McpbManifestSchema8 = objectType({
- $schema: stringType().optional(),
- dxt_version: literalType(MANIFEST_VERSION8).optional().describe("@deprecated Use manifest_version instead"),
- manifest_version: literalType(MANIFEST_VERSION8).optional(),
- name: stringType(),
- display_name: stringType().optional(),
- version: stringType(),
- description: stringType(),
- long_description: stringType().optional(),
- author: McpbManifestAuthorSchema8,
- repository: McpbManifestRepositorySchema8.optional(),
- homepage: stringType().url().optional(),
- documentation: stringType().url().optional(),
- support: stringType().url().optional(),
- icon: stringType().optional(),
- icons: arrayType(McpbManifestIconSchema4).optional(),
- screenshots: arrayType(stringType()).optional(),
- localization: McpbManifestLocalizationSchema4.optional(),
- server: McpbManifestServerSchema8,
- tools: arrayType(McpbManifestToolSchema8).optional(),
- tools_generated: booleanType().optional(),
- prompts: arrayType(McpbManifestPromptSchema8).optional(),
- prompts_generated: booleanType().optional(),
- keywords: arrayType(stringType()).optional(),
- license: stringType().optional(),
- privacy_policies: arrayType(stringType().url()).optional(),
- compatibility: McpbManifestCompatibilitySchema8.optional(),
- user_config: recordType(stringType(), McpbUserConfigurationOptionSchema8).optional(),
- _meta: recordType(stringType(), recordType(stringType(), anyType())).optional()
- }).passthrough().refine((data) => !!(data.dxt_version || data.manifest_version), {
- message: "Either 'dxt_version' (deprecated) or 'manifest_version' must be provided"
- });
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/shared/constants.js
-var LATEST_MANIFEST_VERSION = "0.4", DEFAULT_MANIFEST_VERSION = "0.2", MANIFEST_SCHEMAS, MANIFEST_SCHEMAS_LOOSE;
-var init_constants12 = __esm(() => {
- init_0_1();
- init_0_2();
- init_0_3();
- init_0_4();
- init_0_12();
- init_0_22();
- init_0_32();
- init_0_42();
- MANIFEST_SCHEMAS = {
- "0.1": McpbManifestSchema,
- "0.2": McpbManifestSchema2,
- "0.3": McpbManifestSchema3,
- "0.4": McpbManifestSchema4
- };
- MANIFEST_SCHEMAS_LOOSE = {
- "0.1": McpbManifestSchema5,
- "0.2": McpbManifestSchema6,
- "0.3": McpbManifestSchema7,
- "0.4": McpbManifestSchema8
- };
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/cli/init.js
-import { existsSync as existsSync3, readFileSync as readFileSync10, writeFileSync as writeFileSync3 } from "fs";
-import { basename as basename5, join as join33, resolve as resolve10 } from "path";
-function readPackageJson(dirPath) {
- const packageJsonPath = join33(dirPath, "package.json");
- if (existsSync3(packageJsonPath)) {
- try {
- return JSON.parse(readFileSync10(packageJsonPath, "utf-8"));
- } catch (e4) {}
- }
- return {};
-}
-function getDefaultAuthorName(packageData) {
- if (typeof packageData.author === "string") {
- return packageData.author;
- }
- return packageData.author?.name || "";
-}
-function getDefaultAuthorEmail(packageData) {
- if (typeof packageData.author === "object") {
- return packageData.author?.email || "";
- }
- return "";
-}
-function getDefaultAuthorUrl(packageData) {
- if (typeof packageData.author === "object") {
- return packageData.author?.url || "";
- }
- return "";
-}
-function getDefaultRepositoryUrl(packageData) {
- if (typeof packageData.repository === "string") {
- return packageData.repository;
- }
- return packageData.repository?.url || "";
-}
-function getDefaultBasicInfo(packageData, resolvedPath5) {
- const name3 = packageData.name || basename5(resolvedPath5);
- const authorName = getDefaultAuthorName(packageData) || "Unknown Author";
- const displayName = name3;
- const version6 = packageData.version || "1.0.0";
- const description = packageData.description || "A MCPB bundle";
- return { name: name3, authorName, displayName, version: version6, description };
-}
-function getDefaultAuthorInfo(packageData) {
- return {
- authorEmail: getDefaultAuthorEmail(packageData),
- authorUrl: getDefaultAuthorUrl(packageData)
- };
-}
-function getDefaultServerConfig(packageData) {
- const serverType = "node";
- const entryPoint = getDefaultEntryPoint(serverType, packageData);
- const mcp_config = createMcpConfig(serverType, entryPoint);
- return { serverType, entryPoint, mcp_config };
-}
-function getDefaultOptionalFields(packageData) {
- return {
- keywords: "",
- license: packageData.license || "MIT",
- repository: undefined
- };
-}
-function createMcpConfig(serverType, entryPoint) {
- switch (serverType) {
- case "node":
- return {
- command: "node",
- args: ["${__dirname}/" + entryPoint],
- env: {}
- };
- case "python":
- return {
- command: "python",
- args: ["${__dirname}/" + entryPoint],
- env: {
- PYTHONPATH: "${__dirname}/server/lib"
- }
- };
- case "binary":
- return {
- command: "${__dirname}/" + entryPoint,
- args: [],
- env: {}
- };
- }
-}
-function getDefaultEntryPoint(serverType, packageData) {
- switch (serverType) {
- case "node":
- return packageData?.main || "server/index.js";
- case "python":
- return "server/main.py";
- case "binary":
- return "server/my-server";
- }
-}
-async function promptBasicInfo(packageData, resolvedPath5) {
- const defaultName = packageData.name || basename5(resolvedPath5);
- const name3 = await esm_default3({
- message: "Extension name:",
- default: defaultName,
- validate: (value) => value.trim().length > 0 || "Name is required"
- });
- const authorName = await esm_default3({
- message: "Author name:",
- default: getDefaultAuthorName(packageData),
- validate: (value) => value.trim().length > 0 || "Author name is required"
- });
- const displayName = await esm_default3({
- message: "Display name (optional):",
- default: name3
- });
- const version6 = await esm_default3({
- message: "Version:",
- default: packageData.version || "1.0.0",
- validate: (value) => {
- if (!value.trim())
- return "Version is required";
- if (!/^\d+\.\d+\.\d+/.test(value)) {
- return "Version must follow semantic versioning (e.g., 1.0.0)";
- }
- return true;
- }
- });
- const description = await esm_default3({
- message: "Description:",
- default: packageData.description || "",
- validate: (value) => value.trim().length > 0 || "Description is required"
- });
- return { name: name3, authorName, displayName, version: version6, description };
-}
-async function promptAuthorInfo(packageData) {
- const authorEmail = await esm_default3({
- message: "Author email (optional):",
- default: getDefaultAuthorEmail(packageData)
- });
- const authorUrl = await esm_default3({
- message: "Author URL (optional):",
- default: getDefaultAuthorUrl(packageData)
- });
- return { authorEmail, authorUrl };
-}
-async function promptServerConfig(packageData) {
- const serverType = await esm_default4({
- message: "Server type:",
- choices: [
- { name: "Node.js", value: "node" },
- { name: "Python", value: "python" },
- { name: "Binary", value: "binary" }
- ],
- default: "node"
- });
- const entryPoint = await esm_default3({
- message: "Entry point:",
- default: getDefaultEntryPoint(serverType, packageData)
- });
- const mcp_config = createMcpConfig(serverType, entryPoint);
- return { serverType, entryPoint, mcp_config };
-}
-async function promptTools() {
- const addTools = await esm_default2({
- message: "Does your MCP Server provide tools you want to advertise (optional)?",
- default: true
- });
- const tools = [];
- let toolsGenerated = false;
- if (addTools) {
- let addMore = true;
- while (addMore) {
- const toolName = await esm_default3({
- message: "Tool name:",
- validate: (value) => value.trim().length > 0 || "Tool name is required"
- });
- const toolDescription = await esm_default3({
- message: "Tool description (optional):"
- });
- tools.push({
- name: toolName,
- ...toolDescription ? { description: toolDescription } : {}
- });
- addMore = await esm_default2({
- message: "Add another tool?",
- default: false
- });
- }
- toolsGenerated = await esm_default2({
- message: "Does your server generate additional tools at runtime?",
- default: false
- });
- }
- return { tools, toolsGenerated };
-}
-async function promptPrompts() {
- const addPrompts = await esm_default2({
- message: "Does your MCP Server provide prompts you want to advertise (optional)?",
- default: false
- });
- const prompts = [];
- let promptsGenerated = false;
- if (addPrompts) {
- let addMore = true;
- while (addMore) {
- const promptName = await esm_default3({
- message: "Prompt name:",
- validate: (value) => value.trim().length > 0 || "Prompt name is required"
- });
- const promptDescription = await esm_default3({
- message: "Prompt description (optional):"
- });
- const hasArguments = await esm_default2({
- message: "Does this prompt have arguments?",
- default: false
- });
- const argumentNames = [];
- if (hasArguments) {
- let addMoreArgs = true;
- while (addMoreArgs) {
- const argName = await esm_default3({
- message: "Argument name:",
- validate: (value) => {
- if (!value.trim())
- return "Argument name is required";
- if (argumentNames.includes(value)) {
- return "Argument names must be unique";
- }
- return true;
- }
- });
- argumentNames.push(argName);
- addMoreArgs = await esm_default2({
- message: "Add another argument?",
- default: false
- });
- }
- }
- const promptText = await esm_default3({
- message: hasArguments ? `Prompt text (use \${arguments.name} for arguments: ${argumentNames.join(", ")}):` : "Prompt text:",
- validate: (value) => value.trim().length > 0 || "Prompt text is required"
- });
- prompts.push({
- name: promptName,
- ...promptDescription ? { description: promptDescription } : {},
- ...argumentNames.length > 0 ? { arguments: argumentNames } : {},
- text: promptText
- });
- addMore = await esm_default2({
- message: "Add another prompt?",
- default: false
- });
- }
- promptsGenerated = await esm_default2({
- message: "Does your server generate additional prompts at runtime?",
- default: false
- });
- }
- return { prompts, promptsGenerated };
-}
-async function promptOptionalFields(packageData) {
- const keywords = await esm_default3({
- message: "Keywords (comma-separated, optional):",
- default: ""
- });
- const license = await esm_default3({
- message: "License:",
- default: packageData.license || "MIT"
- });
- const addRepository = await esm_default2({
- message: "Add repository information?",
- default: !!packageData.repository
- });
- let repository;
- if (addRepository) {
- const repoUrl = await esm_default3({
- message: "Repository URL:",
- default: getDefaultRepositoryUrl(packageData)
- });
- if (repoUrl) {
- repository = {
- type: "git",
- url: repoUrl
- };
- }
- }
- return { keywords, license, repository };
-}
-async function promptLongDescription(description) {
- const hasLongDescription = await esm_default2({
- message: "Add a detailed long description?",
- default: false
- });
- if (hasLongDescription) {
- const longDescription = await esm_default3({
- message: "Long description (supports basic markdown):",
- default: description
- });
- return longDescription;
- }
- return;
-}
-async function promptUrls() {
- const homepage = await esm_default3({
- message: "Homepage URL (optional):",
- validate: (value) => {
- if (!value.trim())
- return true;
- try {
- new URL(value);
- return true;
- } catch {
- return "Must be a valid URL (e.g., https://example.com)";
- }
- }
- });
- const documentation = await esm_default3({
- message: "Documentation URL (optional):",
- validate: (value) => {
- if (!value.trim())
- return true;
- try {
- new URL(value);
- return true;
- } catch {
- return "Must be a valid URL";
- }
- }
- });
- const support = await esm_default3({
- message: "Support URL (optional):",
- validate: (value) => {
- if (!value.trim())
- return true;
- try {
- new URL(value);
- return true;
- } catch {
- return "Must be a valid URL";
- }
- }
- });
- return { homepage, documentation, support };
-}
-async function promptVisualAssets() {
- const icon = await esm_default3({
- message: "Icon file path (optional, relative to manifest):",
- validate: (value) => {
- if (!value.trim())
- return true;
- if (value.includes(".."))
- return "Relative paths cannot include '..'";
- return true;
- }
- });
- const addIconVariants = await esm_default2({
- message: "Add theme/size-specific icons array?",
- default: false
- });
- const icons = [];
- if (addIconVariants) {
- let addMoreIcons = true;
- while (addMoreIcons) {
- const iconSrc = await esm_default3({
- message: "Icon source path (relative to manifest):",
- validate: (value) => {
- if (!value.trim())
- return "Icon path is required";
- if (value.includes(".."))
- return "Relative paths cannot include '..'";
- return true;
- }
- });
- const iconSize = await esm_default3({
- message: "Icon size (e.g., 16x16):",
- validate: (value) => {
- if (!value.trim())
- return "Icon size is required";
- if (!/^\d+x\d+$/.test(value)) {
- return "Icon size must be in WIDTHxHEIGHT format (e.g., 128x128)";
- }
- return true;
- }
- });
- const iconTheme = await esm_default3({
- message: "Icon theme (light, dark, or custom - optional):",
- default: ""
- });
- icons.push({
- src: iconSrc,
- size: iconSize,
- ...iconTheme.trim() ? { theme: iconTheme.trim() } : {}
- });
- addMoreIcons = await esm_default2({
- message: "Add another icon entry?",
- default: false
- });
- }
- }
- const addScreenshots = await esm_default2({
- message: "Add screenshots?",
- default: false
- });
- const screenshots = [];
- if (addScreenshots) {
- let addMore = true;
- while (addMore) {
- const screenshot = await esm_default3({
- message: "Screenshot file path (relative to manifest):",
- validate: (value) => {
- if (!value.trim())
- return "Screenshot path is required";
- if (value.includes(".."))
- return "Relative paths cannot include '..'";
- return true;
- }
- });
- screenshots.push(screenshot);
- addMore = await esm_default2({
- message: "Add another screenshot?",
- default: false
- });
- }
- }
- return { icon, icons, screenshots };
-}
-async function promptLocalization() {
- const configureLocalization = await esm_default2({
- message: "Configure localization resources?",
- default: false
- });
- if (!configureLocalization) {
- return;
- }
- const placeholderRegex = /\$\{locale\}/i;
- const resourcesPath = await esm_default3({
- message: "Localization resources path (must include ${locale} placeholder):",
- default: "resources/${locale}.json",
- validate: (value) => {
- if (!value.trim()) {
- return "Resources path is required";
- }
- if (value.includes("..")) {
- return "Relative paths cannot include '..'";
- }
- if (!placeholderRegex.test(value)) {
- return "Path must include a ${locale} placeholder";
- }
- return true;
- }
- });
- const defaultLocale = await esm_default3({
- message: "Default locale (BCP 47, e.g., en-US):",
- default: "en-US",
- validate: (value) => {
- if (!value.trim()) {
- return "Default locale is required";
- }
- if (!/^[A-Za-z0-9]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(value)) {
- return "Default locale must follow BCP 47 (e.g., en-US or zh-Hans)";
- }
- return true;
- }
- });
- return {
- resources: resourcesPath,
- default_locale: defaultLocale
- };
-}
-async function promptCompatibility(serverType) {
- const addCompatibility = await esm_default2({
- message: "Add compatibility constraints?",
- default: false
- });
- if (!addCompatibility) {
- return;
- }
- const addPlatforms = await esm_default2({
- message: "Specify supported platforms?",
- default: false
- });
- let platforms;
- if (addPlatforms) {
- const selectedPlatforms = [];
- const supportsDarwin = await esm_default2({
- message: "Support macOS (darwin)?",
- default: true
- });
- if (supportsDarwin)
- selectedPlatforms.push("darwin");
- const supportsWin32 = await esm_default2({
- message: "Support Windows (win32)?",
- default: true
- });
- if (supportsWin32)
- selectedPlatforms.push("win32");
- const supportsLinux = await esm_default2({
- message: "Support Linux?",
- default: true
- });
- if (supportsLinux)
- selectedPlatforms.push("linux");
- platforms = selectedPlatforms.length > 0 ? selectedPlatforms : undefined;
- }
- let runtimes;
- if (serverType !== "binary") {
- const addRuntimes = await esm_default2({
- message: "Specify runtime version constraints?",
- default: false
- });
- if (addRuntimes) {
- if (serverType === "python") {
- const pythonVersion = await esm_default3({
- message: "Python version constraint (e.g., >=3.8,<4.0):",
- validate: (value) => value.trim().length > 0 || "Python version constraint is required"
- });
- runtimes = { python: pythonVersion };
- } else if (serverType === "node") {
- const nodeVersion = await esm_default3({
- message: "Node.js version constraint (e.g., >=16.0.0):",
- validate: (value) => value.trim().length > 0 || "Node.js version constraint is required"
- });
- runtimes = { node: nodeVersion };
- }
- }
- }
- return {
- ...platforms ? { platforms } : {},
- ...runtimes ? { runtimes } : {}
- };
-}
-async function promptUserConfig() {
- const addUserConfig = await esm_default2({
- message: "Add user-configurable options?",
- default: false
- });
- if (!addUserConfig) {
- return {};
- }
- const userConfig = {};
- let addMore = true;
- while (addMore) {
- const optionKey = await esm_default3({
- message: "Configuration option key (unique identifier):",
- validate: (value) => {
- if (!value.trim())
- return "Key is required";
- if (userConfig[value])
- return "Key must be unique";
- return true;
- }
- });
- const optionType = await esm_default4({
- message: "Option type:",
- choices: [
- { name: "String", value: "string" },
- { name: "Number", value: "number" },
- { name: "Boolean", value: "boolean" },
- { name: "Directory", value: "directory" },
- { name: "File", value: "file" }
- ]
- });
- const optionTitle = await esm_default3({
- message: "Option title (human-readable name):",
- validate: (value) => value.trim().length > 0 || "Title is required"
- });
- const optionDescription = await esm_default3({
- message: "Option description:",
- validate: (value) => value.trim().length > 0 || "Description is required"
- });
- const optionRequired = await esm_default2({
- message: "Is this option required?",
- default: false
- });
- const optionSensitive = await esm_default2({
- message: "Is this option sensitive (like a password)?",
- default: false
- });
- const option = {
- type: optionType,
- title: optionTitle,
- description: optionDescription,
- required: optionRequired,
- sensitive: optionSensitive
- };
- if (!optionRequired) {
- let defaultValue;
- if (optionType === "boolean") {
- defaultValue = await esm_default2({
- message: "Default value:",
- default: false
- });
- } else if (optionType === "number") {
- const defaultStr = await esm_default3({
- message: "Default value (number):",
- validate: (value) => {
- if (!value.trim())
- return true;
- return !isNaN(Number(value)) || "Must be a valid number";
- }
- });
- defaultValue = defaultStr ? Number(defaultStr) : undefined;
- } else {
- defaultValue = await esm_default3({
- message: "Default value (optional):"
- });
- }
- if (defaultValue !== undefined && defaultValue !== "") {
- option.default = defaultValue;
- }
- }
- if (optionType === "number") {
- const addConstraints = await esm_default2({
- message: "Add min/max constraints?",
- default: false
- });
- if (addConstraints) {
- const min = await esm_default3({
- message: "Minimum value (optional):",
- validate: (value) => {
- if (!value.trim())
- return true;
- return !isNaN(Number(value)) || "Must be a valid number";
- }
- });
- const max = await esm_default3({
- message: "Maximum value (optional):",
- validate: (value) => {
- if (!value.trim())
- return true;
- return !isNaN(Number(value)) || "Must be a valid number";
- }
- });
- if (min)
- option.min = Number(min);
- if (max)
- option.max = Number(max);
- }
- }
- userConfig[optionKey] = option;
- addMore = await esm_default2({
- message: "Add another configuration option?",
- default: false
- });
- }
- return userConfig;
-}
-function buildManifest(basicInfo, longDescription, authorInfo, urls, visualAssets, serverConfig, tools, toolsGenerated, prompts, promptsGenerated, compatibility, userConfig, optionalFields) {
- const { name: name3, displayName, version: version6, description, authorName } = basicInfo;
- const { authorEmail, authorUrl } = authorInfo;
- const { serverType, entryPoint, mcp_config } = serverConfig;
- const { keywords, license, repository } = optionalFields;
- return {
- manifest_version: DEFAULT_MANIFEST_VERSION,
- name: name3,
- ...displayName && displayName !== name3 ? { display_name: displayName } : {},
- version: version6,
- description,
- ...longDescription ? { long_description: longDescription } : {},
- author: {
- name: authorName,
- ...authorEmail ? { email: authorEmail } : {},
- ...authorUrl ? { url: authorUrl } : {}
- },
- ...urls.homepage ? { homepage: urls.homepage } : {},
- ...urls.documentation ? { documentation: urls.documentation } : {},
- ...urls.support ? { support: urls.support } : {},
- ...visualAssets.icon ? { icon: visualAssets.icon } : {},
- ...visualAssets.icons.length > 0 ? { icons: visualAssets.icons } : {},
- ...visualAssets.screenshots.length > 0 ? { screenshots: visualAssets.screenshots } : {},
- server: {
- type: serverType,
- entry_point: entryPoint,
- mcp_config
- },
- ...tools.length > 0 ? { tools } : {},
- ...toolsGenerated ? { tools_generated: true } : {},
- ...prompts.length > 0 ? { prompts } : {},
- ...promptsGenerated ? { prompts_generated: true } : {},
- ...compatibility ? { compatibility } : {},
- ...Object.keys(userConfig).length > 0 ? { user_config: userConfig } : {},
- ...keywords ? {
- keywords: keywords.split(",").map((k4) => k4.trim()).filter((k4) => k4)
- } : {},
- ...license ? { license } : {},
- ...repository ? { repository } : {}
- };
-}
-function printNextSteps() {
- console.log(`
-Next steps:`);
- console.log(`1. Ensure all your production dependencies are in this directory`);
- console.log(`2. Run 'mcpb pack' to create your .mcpb file`);
-}
-async function initExtension(targetPath = process.cwd(), nonInteractive = false) {
- const resolvedPath5 = resolve10(targetPath);
- const manifestPath = join33(resolvedPath5, "manifest.json");
- if (existsSync3(manifestPath)) {
- if (nonInteractive) {
- console.log("manifest.json already exists. Use --force to overwrite in non-interactive mode.");
- return false;
- }
- const overwrite = await esm_default2({
- message: "manifest.json already exists. Overwrite?",
- default: false
- });
- if (!overwrite) {
- console.log("Cancelled");
- return false;
- }
- }
- if (!nonInteractive) {
- console.log("This utility will help you create a manifest.json file for your MCPB bundle.");
- console.log(`Press ^C at any time to quit.
-`);
- } else {
- console.log("Creating manifest.json with default values...");
- }
- try {
- const packageData = readPackageJson(resolvedPath5);
- const basicInfo = nonInteractive ? getDefaultBasicInfo(packageData, resolvedPath5) : await promptBasicInfo(packageData, resolvedPath5);
- const longDescription = nonInteractive ? undefined : await promptLongDescription(basicInfo.description);
- const authorInfo = nonInteractive ? getDefaultAuthorInfo(packageData) : await promptAuthorInfo(packageData);
- const urls = nonInteractive ? { homepage: "", documentation: "", support: "" } : await promptUrls();
- const visualAssets = nonInteractive ? { icon: "", icons: [], screenshots: [] } : await promptVisualAssets();
- const serverConfig = nonInteractive ? getDefaultServerConfig(packageData) : await promptServerConfig(packageData);
- const toolsData = nonInteractive ? { tools: [], toolsGenerated: false } : await promptTools();
- const promptsData = nonInteractive ? { prompts: [], promptsGenerated: false } : await promptPrompts();
- const compatibility = nonInteractive ? undefined : await promptCompatibility(serverConfig.serverType);
- const userConfig = nonInteractive ? {} : await promptUserConfig();
- const optionalFields = nonInteractive ? getDefaultOptionalFields(packageData) : await promptOptionalFields(packageData);
- const manifest = buildManifest(basicInfo, longDescription, authorInfo, urls, visualAssets, serverConfig, toolsData.tools, toolsData.toolsGenerated, promptsData.prompts, promptsData.promptsGenerated, compatibility, userConfig, optionalFields);
- writeFileSync3(manifestPath, JSON.stringify(manifest, null, 2) + `
-`);
- console.log(`
-Created manifest.json at ${manifestPath}`);
- printNextSteps();
- return true;
- } catch (error46) {
- if (error46 instanceof Error && error46.message.includes("User force closed")) {
- console.log(`
-Cancelled`);
- return false;
- }
- throw error46;
- }
-}
-var init_init = __esm(() => {
- init_esm17();
- init_constants12();
-});
-
-// node_modules/fflate/esm/index.mjs
-var exports_esm2 = {};
-__export(exports_esm2, {
- zlibSync: () => zlibSync,
- zlib: () => zlib3,
- zipSync: () => zipSync,
- zip: () => zip,
- unzlibSync: () => unzlibSync,
- unzlib: () => unzlib,
- unzipSync: () => unzipSync,
- unzip: () => unzip,
- strToU8: () => strToU8,
- strFromU8: () => strFromU8,
- inflateSync: () => inflateSync,
- inflate: () => inflate,
- gzipSync: () => gzipSync,
- gzip: () => gzip,
- gunzipSync: () => gunzipSync,
- gunzip: () => gunzip,
- deflateSync: () => deflateSync,
- deflate: () => deflate,
- decompressSync: () => decompressSync,
- decompress: () => decompress,
- compressSync: () => gzipSync,
- compress: () => gzip,
- Zlib: () => Zlib,
- ZipPassThrough: () => ZipPassThrough,
- ZipDeflate: () => ZipDeflate,
- Zip: () => Zip,
- Unzlib: () => Unzlib,
- UnzipPassThrough: () => UnzipPassThrough,
- UnzipInflate: () => UnzipInflate,
- Unzip: () => Unzip,
- Inflate: () => Inflate,
- Gzip: () => Gzip,
- Gunzip: () => Gunzip,
- FlateErrorCode: () => FlateErrorCode,
- EncodeUTF8: () => EncodeUTF8,
- Deflate: () => Deflate,
- Decompress: () => Decompress,
- DecodeUTF8: () => DecodeUTF8,
- Compress: () => Gzip,
- AsyncZlib: () => AsyncZlib,
- AsyncZipDeflate: () => AsyncZipDeflate,
- AsyncUnzlib: () => AsyncUnzlib,
- AsyncUnzipInflate: () => AsyncUnzipInflate,
- AsyncInflate: () => AsyncInflate,
- AsyncGzip: () => AsyncGzip,
- AsyncGunzip: () => AsyncGunzip,
- AsyncDeflate: () => AsyncDeflate,
- AsyncDecompress: () => AsyncDecompress,
- AsyncCompress: () => AsyncGzip
-});
-import { createRequire } from "module";
-function StrmOpt(opts, cb) {
- if (typeof opts == "function")
- cb = opts, opts = {};
- this.ondata = cb;
- return opts;
-}
-function deflate(data, opts, cb) {
- if (!cb)
- cb = opts, opts = {};
- if (typeof cb != "function")
- err(7);
- return cbify(data, opts, [
- bDflt
- ], function(ev) {
- return pbf(deflateSync(ev.data[0], ev.data[1]));
- }, 0, cb);
-}
-function deflateSync(data, opts) {
- return dopt(data, opts || {}, 0, 0);
-}
-function inflate(data, opts, cb) {
- if (!cb)
- cb = opts, opts = {};
- if (typeof cb != "function")
- err(7);
- return cbify(data, opts, [
- bInflt
- ], function(ev) {
- return pbf(inflateSync(ev.data[0], gopt(ev.data[1])));
- }, 1, cb);
-}
-function inflateSync(data, opts) {
- return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
-}
-function gzip(data, opts, cb) {
- if (!cb)
- cb = opts, opts = {};
- if (typeof cb != "function")
- err(7);
- return cbify(data, opts, [
- bDflt,
- gze,
- function() {
- return [gzipSync];
- }
- ], function(ev) {
- return pbf(gzipSync(ev.data[0], ev.data[1]));
- }, 2, cb);
-}
-function gzipSync(data, opts) {
- if (!opts)
- opts = {};
- var c8 = crc(), l4 = data.length;
- c8.p(data);
- var d4 = dopt(data, opts, gzhl(opts), 8), s4 = d4.length;
- return gzh(d4, opts), wbytes(d4, s4 - 8, c8.d()), wbytes(d4, s4 - 4, l4), d4;
-}
-function gunzip(data, opts, cb) {
- if (!cb)
- cb = opts, opts = {};
- if (typeof cb != "function")
- err(7);
- return cbify(data, opts, [
- bInflt,
- guze,
- function() {
- return [gunzipSync];
- }
- ], function(ev) {
- return pbf(gunzipSync(ev.data[0], ev.data[1]));
- }, 3, cb);
-}
-function gunzipSync(data, opts) {
- var st = gzs(data);
- if (st + 8 > data.length)
- err(6, "invalid gzip data");
- return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);
-}
-function zlib3(data, opts, cb) {
- if (!cb)
- cb = opts, opts = {};
- if (typeof cb != "function")
- err(7);
- return cbify(data, opts, [
- bDflt,
- zle,
- function() {
- return [zlibSync];
- }
- ], function(ev) {
- return pbf(zlibSync(ev.data[0], ev.data[1]));
- }, 4, cb);
-}
-function zlibSync(data, opts) {
- if (!opts)
- opts = {};
- var a5 = adler();
- a5.p(data);
- var d4 = dopt(data, opts, opts.dictionary ? 6 : 2, 4);
- return zlh(d4, opts), wbytes(d4, d4.length - 4, a5.d()), d4;
-}
-function unzlib(data, opts, cb) {
- if (!cb)
- cb = opts, opts = {};
- if (typeof cb != "function")
- err(7);
- return cbify(data, opts, [
- bInflt,
- zule,
- function() {
- return [unzlibSync];
- }
- ], function(ev) {
- return pbf(unzlibSync(ev.data[0], gopt(ev.data[1])));
- }, 5, cb);
-}
-function unzlibSync(data, opts) {
- return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);
-}
-function decompress(data, opts, cb) {
- if (!cb)
- cb = opts, opts = {};
- if (typeof cb != "function")
- err(7);
- return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzip(data, opts, cb) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflate(data, opts, cb) : unzlib(data, opts, cb);
-}
-function decompressSync(data, opts) {
- return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzipSync(data, opts) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflateSync(data, opts) : unzlibSync(data, opts);
-}
-function strToU8(str, latin1) {
- if (latin1) {
- var ar_1 = new u8(str.length);
- for (var i6 = 0;i6 < str.length; ++i6)
- ar_1[i6] = str.charCodeAt(i6);
- return ar_1;
- }
- if (te)
- return te.encode(str);
- var l4 = str.length;
- var ar = new u8(str.length + (str.length >> 1));
- var ai = 0;
- var w2 = function(v6) {
- ar[ai++] = v6;
- };
- for (var i6 = 0;i6 < l4; ++i6) {
- if (ai + 5 > ar.length) {
- var n5 = new u8(ai + 8 + (l4 - i6 << 1));
- n5.set(ar);
- ar = n5;
- }
- var c8 = str.charCodeAt(i6);
- if (c8 < 128 || latin1)
- w2(c8);
- else if (c8 < 2048)
- w2(192 | c8 >> 6), w2(128 | c8 & 63);
- else if (c8 > 55295 && c8 < 57344)
- c8 = 65536 + (c8 & 1023 << 10) | str.charCodeAt(++i6) & 1023, w2(240 | c8 >> 18), w2(128 | c8 >> 12 & 63), w2(128 | c8 >> 6 & 63), w2(128 | c8 & 63);
- else
- w2(224 | c8 >> 12), w2(128 | c8 >> 6 & 63), w2(128 | c8 & 63);
- }
- return slc(ar, 0, ai);
-}
-function strFromU8(dat, latin1) {
- if (latin1) {
- var r4 = "";
- for (var i6 = 0;i6 < dat.length; i6 += 16384)
- r4 += String.fromCharCode.apply(null, dat.subarray(i6, i6 + 16384));
- return r4;
- } else if (td) {
- return td.decode(dat);
- } else {
- var _a9 = dutf8(dat), s4 = _a9.s, r4 = _a9.r;
- if (r4.length)
- err(8);
- return s4;
- }
-}
-function zip(data, opts, cb) {
- if (!cb)
- cb = opts, opts = {};
- if (typeof cb != "function")
- err(7);
- var r4 = {};
- fltn(data, "", r4, opts);
- var k4 = Object.keys(r4);
- var lft = k4.length, o5 = 0, tot = 0;
- var slft = lft, files = new Array(lft);
- var term = [];
- var tAll = function() {
- for (var i7 = 0;i7 < term.length; ++i7)
- term[i7]();
- };
- var cbd = function(a5, b5) {
- mt(function() {
- cb(a5, b5);
- });
- };
- mt(function() {
- cbd = cb;
- });
- var cbf = function() {
- var out = new u8(tot + 22), oe = o5, cdl = tot - o5;
- tot = 0;
- for (var i7 = 0;i7 < slft; ++i7) {
- var f4 = files[i7];
- try {
- var l4 = f4.c.length;
- wzh(out, tot, f4, f4.f, f4.u, l4);
- var badd = 30 + f4.f.length + exfl(f4.extra);
- var loc = tot + badd;
- out.set(f4.c, loc);
- wzh(out, o5, f4, f4.f, f4.u, l4, tot, f4.m), o5 += 16 + badd + (f4.m ? f4.m.length : 0), tot = loc + l4;
- } catch (e4) {
- return cbd(e4, null);
- }
- }
- wzf(out, o5, files.length, cdl, oe);
- cbd(null, out);
- };
- if (!lft)
- cbf();
- var _loop_1 = function(i7) {
- var fn = k4[i7];
- var _a9 = r4[fn], file2 = _a9[0], p4 = _a9[1];
- var c8 = crc(), size = file2.length;
- c8.p(file2);
- var f4 = strToU8(fn), s4 = f4.length;
- var com = p4.comment, m4 = com && strToU8(com), ms = m4 && m4.length;
- var exl = exfl(p4.extra);
- var compression = p4.level == 0 ? 0 : 8;
- var cbl = function(e4, d4) {
- if (e4) {
- tAll();
- cbd(e4, null);
- } else {
- var l4 = d4.length;
- files[i7] = mrg(p4, {
- size,
- crc: c8.d(),
- c: d4,
- f: f4,
- m: m4,
- u: s4 != fn.length || m4 && com.length != ms,
- compression
- });
- o5 += 30 + s4 + exl + l4;
- tot += 76 + 2 * (s4 + exl) + (ms || 0) + l4;
- if (!--lft)
- cbf();
- }
- };
- if (s4 > 65535)
- cbl(err(11, 0, 1), null);
- if (!compression)
- cbl(null, file2);
- else if (size < 160000) {
- try {
- cbl(null, deflateSync(file2, p4));
- } catch (e4) {
- cbl(e4, null);
- }
- } else
- term.push(deflate(file2, p4, cbl));
- };
- for (var i6 = 0;i6 < slft; ++i6) {
- _loop_1(i6);
- }
- return tAll;
-}
-function zipSync(data, opts) {
- if (!opts)
- opts = {};
- var r4 = {};
- var files = [];
- fltn(data, "", r4, opts);
- var o5 = 0;
- var tot = 0;
- for (var fn in r4) {
- var _a9 = r4[fn], file2 = _a9[0], p4 = _a9[1];
- var compression = p4.level == 0 ? 0 : 8;
- var f4 = strToU8(fn), s4 = f4.length;
- var com = p4.comment, m4 = com && strToU8(com), ms = m4 && m4.length;
- var exl = exfl(p4.extra);
- if (s4 > 65535)
- err(11);
- var d4 = compression ? deflateSync(file2, p4) : file2, l4 = d4.length;
- var c8 = crc();
- c8.p(file2);
- files.push(mrg(p4, {
- size: file2.length,
- crc: c8.d(),
- c: d4,
- f: f4,
- m: m4,
- u: s4 != fn.length || m4 && com.length != ms,
- o: o5,
- compression
- }));
- o5 += 30 + s4 + exl + l4;
- tot += 76 + 2 * (s4 + exl) + (ms || 0) + l4;
- }
- var out = new u8(tot + 22), oe = o5, cdl = tot - o5;
- for (var i6 = 0;i6 < files.length; ++i6) {
- var f4 = files[i6];
- wzh(out, f4.o, f4, f4.f, f4.u, f4.c.length);
- var badd = 30 + f4.f.length + exfl(f4.extra);
- out.set(f4.c, f4.o + badd);
- wzh(out, o5, f4, f4.f, f4.u, f4.c.length, f4.o, f4.m), o5 += 16 + badd + (f4.m ? f4.m.length : 0);
- }
- wzf(out, o5, files.length, cdl, oe);
- return out;
-}
-function unzip(data, opts, cb) {
- if (!cb)
- cb = opts, opts = {};
- if (typeof cb != "function")
- err(7);
- var term = [];
- var tAll = function() {
- for (var i7 = 0;i7 < term.length; ++i7)
- term[i7]();
- };
- var files = {};
- var cbd = function(a5, b5) {
- mt(function() {
- cb(a5, b5);
- });
- };
- mt(function() {
- cbd = cb;
- });
- var e4 = data.length - 22;
- for (;b4(data, e4) != 101010256; --e4) {
- if (!e4 || data.length - e4 > 65558) {
- cbd(err(13, 0, 1), null);
- return tAll;
- }
- }
- var lft = b22(data, e4 + 8);
- if (lft) {
- var c8 = lft;
- var o5 = b4(data, e4 + 16);
- var z3 = o5 == 4294967295 || c8 == 65535;
- if (z3) {
- var ze = b4(data, e4 - 12);
- z3 = b4(data, ze) == 101075792;
- if (z3) {
- c8 = lft = b4(data, ze + 32);
- o5 = b4(data, ze + 48);
- }
- }
- var fltr = opts && opts.filter;
- var _loop_3 = function(i7) {
- var _a9 = zh(data, o5, z3), c_1 = _a9[0], sc = _a9[1], su = _a9[2], fn = _a9[3], no = _a9[4], off = _a9[5], b5 = slzh(data, off);
- o5 = no;
- var cbl = function(e5, d4) {
- if (e5) {
- tAll();
- cbd(e5, null);
- } else {
- if (d4)
- files[fn] = d4;
- if (!--lft)
- cbd(null, files);
- }
- };
- if (!fltr || fltr({
- name: fn,
- size: sc,
- originalSize: su,
- compression: c_1
- })) {
- if (!c_1)
- cbl(null, slc(data, b5, b5 + sc));
- else if (c_1 == 8) {
- var infl = data.subarray(b5, b5 + sc);
- if (su < 524288 || sc > 0.8 * su) {
- try {
- cbl(null, inflateSync(infl, { out: new u8(su) }));
- } catch (e5) {
- cbl(e5, null);
- }
- } else
- term.push(inflate(infl, { size: su }, cbl));
- } else
- cbl(err(14, "unknown compression type " + c_1, 1), null);
- } else
- cbl(null, null);
- };
- for (var i6 = 0;i6 < c8; ++i6) {
- _loop_3(i6);
- }
- } else
- cbd(null, {});
- return tAll;
-}
-function unzipSync(data, opts) {
- var files = {};
- var e4 = data.length - 22;
- for (;b4(data, e4) != 101010256; --e4) {
- if (!e4 || data.length - e4 > 65558)
- err(13);
- }
- var c8 = b22(data, e4 + 8);
- if (!c8)
- return {};
- var o5 = b4(data, e4 + 16);
- var z3 = o5 == 4294967295 || c8 == 65535;
- if (z3) {
- var ze = b4(data, e4 - 12);
- z3 = b4(data, ze) == 101075792;
- if (z3) {
- c8 = b4(data, ze + 32);
- o5 = b4(data, ze + 48);
- }
- }
- var fltr = opts && opts.filter;
- for (var i6 = 0;i6 < c8; ++i6) {
- var _a9 = zh(data, o5, z3), c_2 = _a9[0], sc = _a9[1], su = _a9[2], fn = _a9[3], no = _a9[4], off = _a9[5], b5 = slzh(data, off);
- o5 = no;
- if (!fltr || fltr({
- name: fn,
- size: sc,
- originalSize: su,
- compression: c_2
- })) {
- if (!c_2)
- files[fn] = slc(data, b5, b5 + sc);
- else if (c_2 == 8)
- files[fn] = inflateSync(data.subarray(b5, b5 + sc), { out: new u8(su) });
- else
- err(14, "unknown compression type " + c_2);
- }
- }
- return files;
-}
-var require2, Worker2, workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global", wk, u8, u16, i32, fleb, fdeb, clim, freb = function(eb, start) {
- var b4 = new u16(31);
- for (var i5 = 0;i5 < 31; ++i5) {
- b4[i5] = start += 1 << eb[i5 - 1];
- }
- var r4 = new i32(b4[30]);
- for (var i5 = 1;i5 < 30; ++i5) {
- for (var j4 = b4[i5];j4 < b4[i5 + 1]; ++j4) {
- r4[j4] = j4 - b4[i5] << 5 | i5;
- }
- }
- return { b: b4, r: r4 };
-}, _a8, fl, revfl, _b2, fd, revfd, rev, x3, i5, hMap = function(cd, mb, r4) {
- var s4 = cd.length;
- var i6 = 0;
- var l4 = new u16(mb);
- for (;i6 < s4; ++i6) {
- if (cd[i6])
- ++l4[cd[i6] - 1];
- }
- var le = new u16(mb);
- for (i6 = 1;i6 < mb; ++i6) {
- le[i6] = le[i6 - 1] + l4[i6 - 1] << 1;
- }
- var co;
- if (r4) {
- co = new u16(1 << mb);
- var rvb = 15 - mb;
- for (i6 = 0;i6 < s4; ++i6) {
- if (cd[i6]) {
- var sv = i6 << 4 | cd[i6];
- var r_1 = mb - cd[i6];
- var v6 = le[cd[i6] - 1]++ << r_1;
- for (var m4 = v6 | (1 << r_1) - 1;v6 <= m4; ++v6) {
- co[rev[v6] >> rvb] = sv;
- }
- }
- }
- } else {
- co = new u16(s4);
- for (i6 = 0;i6 < s4; ++i6) {
- if (cd[i6]) {
- co[i6] = rev[le[cd[i6] - 1]++] >> 15 - cd[i6];
- }
- }
- }
- return co;
-}, flt, i5, i5, i5, i5, fdt, i5, flm, flrm, fdm, fdrm, max = function(a5) {
- var m4 = a5[0];
- for (var i6 = 1;i6 < a5.length; ++i6) {
- if (a5[i6] > m4)
- m4 = a5[i6];
- }
- return m4;
-}, bits = function(d4, p4, m4) {
- var o5 = p4 / 8 | 0;
- return (d4[o5] | d4[o5 + 1] << 8) >> (p4 & 7) & m4;
-}, bits16 = function(d4, p4) {
- var o5 = p4 / 8 | 0;
- return (d4[o5] | d4[o5 + 1] << 8 | d4[o5 + 2] << 16) >> (p4 & 7);
-}, shft = function(p4) {
- return (p4 + 7) / 8 | 0;
-}, slc = function(v6, s4, e4) {
- if (s4 == null || s4 < 0)
- s4 = 0;
- if (e4 == null || e4 > v6.length)
- e4 = v6.length;
- return new u8(v6.subarray(s4, e4));
-}, FlateErrorCode, ec, err = function(ind, msg, nt) {
- var e4 = new Error(msg || ec[ind]);
- e4.code = ind;
- if (Error.captureStackTrace)
- Error.captureStackTrace(e4, err);
- if (!nt)
- throw e4;
- return e4;
-}, inflt = function(dat, st, buf, dict) {
- var sl = dat.length, dl = dict ? dict.length : 0;
- if (!sl || st.f && !st.l)
- return buf || new u8(0);
- var noBuf = !buf;
- var resize = noBuf || st.i != 2;
- var noSt = st.i;
- if (noBuf)
- buf = new u8(sl * 3);
- var cbuf = function(l5) {
- var bl = buf.length;
- if (l5 > bl) {
- var nbuf = new u8(Math.max(bl * 2, l5));
- nbuf.set(buf);
- buf = nbuf;
- }
- };
- var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
- var tbts = sl * 8;
- do {
- if (!lm) {
- final = bits(dat, pos, 1);
- var type = bits(dat, pos + 1, 3);
- pos += 3;
- if (!type) {
- var s4 = shft(pos) + 4, l4 = dat[s4 - 4] | dat[s4 - 3] << 8, t4 = s4 + l4;
- if (t4 > sl) {
- if (noSt)
- err(0);
- break;
- }
- if (resize)
- cbuf(bt + l4);
- buf.set(dat.subarray(s4, t4), bt);
- st.b = bt += l4, st.p = pos = t4 * 8, st.f = final;
- continue;
- } else if (type == 1)
- lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
- else if (type == 2) {
- var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
- var tl = hLit + bits(dat, pos + 5, 31) + 1;
- pos += 14;
- var ldt = new u8(tl);
- var clt = new u8(19);
- for (var i6 = 0;i6 < hcLen; ++i6) {
- clt[clim[i6]] = bits(dat, pos + i6 * 3, 7);
- }
- pos += hcLen * 3;
- var clb = max(clt), clbmsk = (1 << clb) - 1;
- var clm = hMap(clt, clb, 1);
- for (var i6 = 0;i6 < tl; ) {
- var r4 = clm[bits(dat, pos, clbmsk)];
- pos += r4 & 15;
- var s4 = r4 >> 4;
- if (s4 < 16) {
- ldt[i6++] = s4;
- } else {
- var c8 = 0, n5 = 0;
- if (s4 == 16)
- n5 = 3 + bits(dat, pos, 3), pos += 2, c8 = ldt[i6 - 1];
- else if (s4 == 17)
- n5 = 3 + bits(dat, pos, 7), pos += 3;
- else if (s4 == 18)
- n5 = 11 + bits(dat, pos, 127), pos += 7;
- while (n5--)
- ldt[i6++] = c8;
- }
- }
- var lt2 = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
- lbt = max(lt2);
- dbt = max(dt);
- lm = hMap(lt2, lbt, 1);
- dm = hMap(dt, dbt, 1);
- } else
- err(1);
- if (pos > tbts) {
- if (noSt)
- err(0);
- break;
- }
- }
- if (resize)
- cbuf(bt + 131072);
- var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
- var lpos = pos;
- for (;; lpos = pos) {
- var c8 = lm[bits16(dat, pos) & lms], sym = c8 >> 4;
- pos += c8 & 15;
- if (pos > tbts) {
- if (noSt)
- err(0);
- break;
- }
- if (!c8)
- err(2);
- if (sym < 256)
- buf[bt++] = sym;
- else if (sym == 256) {
- lpos = pos, lm = null;
- break;
- } else {
- var add = sym - 254;
- if (sym > 264) {
- var i6 = sym - 257, b4 = fleb[i6];
- add = bits(dat, pos, (1 << b4) - 1) + fl[i6];
- pos += b4;
- }
- var d4 = dm[bits16(dat, pos) & dms], dsym = d4 >> 4;
- if (!d4)
- err(3);
- pos += d4 & 15;
- var dt = fd[dsym];
- if (dsym > 3) {
- var b4 = fdeb[dsym];
- dt += bits16(dat, pos) & (1 << b4) - 1, pos += b4;
- }
- if (pos > tbts) {
- if (noSt)
- err(0);
- break;
- }
- if (resize)
- cbuf(bt + 131072);
- var end = bt + add;
- if (bt < dt) {
- var shift = dl - dt, dend = Math.min(dt, end);
- if (shift + bt < 0)
- err(3);
- for (;bt < dend; ++bt)
- buf[bt] = dict[shift + bt];
- }
- for (;bt < end; ++bt)
- buf[bt] = buf[bt - dt];
- }
- }
- st.l = lm, st.p = lpos, st.b = bt, st.f = final;
- if (lm)
- final = 1, st.m = lbt, st.d = dm, st.n = dbt;
- } while (!final);
- return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
-}, wbits = function(d4, p4, v6) {
- v6 <<= p4 & 7;
- var o5 = p4 / 8 | 0;
- d4[o5] |= v6;
- d4[o5 + 1] |= v6 >> 8;
-}, wbits16 = function(d4, p4, v6) {
- v6 <<= p4 & 7;
- var o5 = p4 / 8 | 0;
- d4[o5] |= v6;
- d4[o5 + 1] |= v6 >> 8;
- d4[o5 + 2] |= v6 >> 16;
-}, hTree = function(d4, mb) {
- var t4 = [];
- for (var i6 = 0;i6 < d4.length; ++i6) {
- if (d4[i6])
- t4.push({ s: i6, f: d4[i6] });
- }
- var s4 = t4.length;
- var t22 = t4.slice();
- if (!s4)
- return { t: et, l: 0 };
- if (s4 == 1) {
- var v6 = new u8(t4[0].s + 1);
- v6[t4[0].s] = 1;
- return { t: v6, l: 1 };
- }
- t4.sort(function(a5, b4) {
- return a5.f - b4.f;
- });
- t4.push({ s: -1, f: 25001 });
- var l4 = t4[0], r4 = t4[1], i0 = 0, i1 = 1, i22 = 2;
- t4[0] = { s: -1, f: l4.f + r4.f, l: l4, r: r4 };
- while (i1 != s4 - 1) {
- l4 = t4[t4[i0].f < t4[i22].f ? i0++ : i22++];
- r4 = t4[i0 != i1 && t4[i0].f < t4[i22].f ? i0++ : i22++];
- t4[i1++] = { s: -1, f: l4.f + r4.f, l: l4, r: r4 };
- }
- var maxSym = t22[0].s;
- for (var i6 = 1;i6 < s4; ++i6) {
- if (t22[i6].s > maxSym)
- maxSym = t22[i6].s;
- }
- var tr = new u16(maxSym + 1);
- var mbt = ln(t4[i1 - 1], tr, 0);
- if (mbt > mb) {
- var i6 = 0, dt = 0;
- var lft = mbt - mb, cst = 1 << lft;
- t22.sort(function(a5, b4) {
- return tr[b4.s] - tr[a5.s] || a5.f - b4.f;
- });
- for (;i6 < s4; ++i6) {
- var i2_1 = t22[i6].s;
- if (tr[i2_1] > mb) {
- dt += cst - (1 << mbt - tr[i2_1]);
- tr[i2_1] = mb;
- } else
- break;
- }
- dt >>= lft;
- while (dt > 0) {
- var i2_2 = t22[i6].s;
- if (tr[i2_2] < mb)
- dt -= 1 << mb - tr[i2_2]++ - 1;
- else
- ++i6;
- }
- for (;i6 >= 0 && dt; --i6) {
- var i2_3 = t22[i6].s;
- if (tr[i2_3] == mb) {
- --tr[i2_3];
- ++dt;
- }
- }
- mbt = mb;
- }
- return { t: new u8(tr), l: mbt };
-}, ln = function(n5, l4, d4) {
- return n5.s == -1 ? Math.max(ln(n5.l, l4, d4 + 1), ln(n5.r, l4, d4 + 1)) : l4[n5.s] = d4;
-}, lc = function(c8) {
- var s4 = c8.length;
- while (s4 && !c8[--s4])
- ;
- var cl = new u16(++s4);
- var cli = 0, cln = c8[0], cls = 1;
- var w2 = function(v6) {
- cl[cli++] = v6;
- };
- for (var i6 = 1;i6 <= s4; ++i6) {
- if (c8[i6] == cln && i6 != s4)
- ++cls;
- else {
- if (!cln && cls > 2) {
- for (;cls > 138; cls -= 138)
- w2(32754);
- if (cls > 2) {
- w2(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
- cls = 0;
- }
- } else if (cls > 3) {
- w2(cln), --cls;
- for (;cls > 6; cls -= 6)
- w2(8304);
- if (cls > 2)
- w2(cls - 3 << 5 | 8208), cls = 0;
- }
- while (cls--)
- w2(cln);
- cls = 1;
- cln = c8[i6];
- }
- }
- return { c: cl.subarray(0, cli), n: s4 };
-}, clen = function(cf, cl) {
- var l4 = 0;
- for (var i6 = 0;i6 < cl.length; ++i6)
- l4 += cf[i6] * cl[i6];
- return l4;
-}, wfblk = function(out, pos, dat) {
- var s4 = dat.length;
- var o5 = shft(pos + 2);
- out[o5] = s4 & 255;
- out[o5 + 1] = s4 >> 8;
- out[o5 + 2] = out[o5] ^ 255;
- out[o5 + 3] = out[o5 + 1] ^ 255;
- for (var i6 = 0;i6 < s4; ++i6)
- out[o5 + i6 + 4] = dat[i6];
- return (o5 + 4 + s4) * 8;
-}, wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p4) {
- wbits(out, p4++, final);
- ++lf[256];
- var _a9 = hTree(lf, 15), dlt = _a9.t, mlb = _a9.l;
- var _b3 = hTree(df, 15), ddt = _b3.t, mdb = _b3.l;
- var _c20 = lc(dlt), lclt = _c20.c, nlc = _c20.n;
- var _d3 = lc(ddt), lcdt = _d3.c, ndc = _d3.n;
- var lcfreq = new u16(19);
- for (var i6 = 0;i6 < lclt.length; ++i6)
- ++lcfreq[lclt[i6] & 31];
- for (var i6 = 0;i6 < lcdt.length; ++i6)
- ++lcfreq[lcdt[i6] & 31];
- var _e4 = hTree(lcfreq, 7), lct = _e4.t, mlcb = _e4.l;
- var nlcc = 19;
- for (;nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
- ;
- var flen = bl + 5 << 3;
- var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
- var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
- if (bs >= 0 && flen <= ftlen && flen <= dtlen)
- return wfblk(out, p4, dat.subarray(bs, bs + bl));
- var lm, ll, dm, dl;
- wbits(out, p4, 1 + (dtlen < ftlen)), p4 += 2;
- if (dtlen < ftlen) {
- lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
- var llm = hMap(lct, mlcb, 0);
- wbits(out, p4, nlc - 257);
- wbits(out, p4 + 5, ndc - 1);
- wbits(out, p4 + 10, nlcc - 4);
- p4 += 14;
- for (var i6 = 0;i6 < nlcc; ++i6)
- wbits(out, p4 + 3 * i6, lct[clim[i6]]);
- p4 += 3 * nlcc;
- var lcts = [lclt, lcdt];
- for (var it = 0;it < 2; ++it) {
- var clct = lcts[it];
- for (var i6 = 0;i6 < clct.length; ++i6) {
- var len = clct[i6] & 31;
- wbits(out, p4, llm[len]), p4 += lct[len];
- if (len > 15)
- wbits(out, p4, clct[i6] >> 5 & 127), p4 += clct[i6] >> 12;
- }
- }
- } else {
- lm = flm, ll = flt, dm = fdm, dl = fdt;
- }
- for (var i6 = 0;i6 < li; ++i6) {
- var sym = syms[i6];
- if (sym > 255) {
- var len = sym >> 18 & 31;
- wbits16(out, p4, lm[len + 257]), p4 += ll[len + 257];
- if (len > 7)
- wbits(out, p4, sym >> 23 & 31), p4 += fleb[len];
- var dst = sym & 31;
- wbits16(out, p4, dm[dst]), p4 += dl[dst];
- if (dst > 3)
- wbits16(out, p4, sym >> 5 & 8191), p4 += fdeb[dst];
- } else {
- wbits16(out, p4, lm[sym]), p4 += ll[sym];
- }
- }
- wbits16(out, p4, lm[256]);
- return p4 + ll[256];
-}, deo, et, dflt = function(dat, lvl, plvl, pre, post, st) {
- var s4 = st.z || dat.length;
- var o5 = new u8(pre + s4 + 5 * (1 + Math.ceil(s4 / 7000)) + post);
- var w2 = o5.subarray(pre, o5.length - post);
- var lst = st.l;
- var pos = (st.r || 0) & 7;
- if (lvl) {
- if (pos)
- w2[0] = st.r >> 3;
- var opt = deo[lvl - 1];
- var n5 = opt >> 13, c8 = opt & 8191;
- var msk_1 = (1 << plvl) - 1;
- var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
- var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
- var hsh = function(i7) {
- return (dat[i7] ^ dat[i7 + 1] << bs1_1 ^ dat[i7 + 2] << bs2_1) & msk_1;
- };
- var syms = new i32(25000);
- var lf = new u16(288), df = new u16(32);
- var lc_1 = 0, eb = 0, i6 = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
- for (;i6 + 2 < s4; ++i6) {
- var hv = hsh(i6);
- var imod = i6 & 32767, pimod = head[hv];
- prev[imod] = pimod;
- head[hv] = imod;
- if (wi <= i6) {
- var rem = s4 - i6;
- if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {
- pos = wblk(dat, w2, 0, syms, lf, df, eb, li, bs, i6 - bs, pos);
- li = lc_1 = eb = 0, bs = i6;
- for (var j4 = 0;j4 < 286; ++j4)
- lf[j4] = 0;
- for (var j4 = 0;j4 < 30; ++j4)
- df[j4] = 0;
- }
- var l4 = 2, d4 = 0, ch_1 = c8, dif = imod - pimod & 32767;
- if (rem > 2 && hv == hsh(i6 - dif)) {
- var maxn = Math.min(n5, rem) - 1;
- var maxd = Math.min(32767, i6);
- var ml = Math.min(258, rem);
- while (dif <= maxd && --ch_1 && imod != pimod) {
- if (dat[i6 + l4] == dat[i6 + l4 - dif]) {
- var nl = 0;
- for (;nl < ml && dat[i6 + nl] == dat[i6 + nl - dif]; ++nl)
- ;
- if (nl > l4) {
- l4 = nl, d4 = dif;
- if (nl > maxn)
- break;
- var mmd = Math.min(dif, nl - 2);
- var md = 0;
- for (var j4 = 0;j4 < mmd; ++j4) {
- var ti = i6 - dif + j4 & 32767;
- var pti = prev[ti];
- var cd = ti - pti & 32767;
- if (cd > md)
- md = cd, pimod = ti;
- }
- }
- }
- imod = pimod, pimod = prev[imod];
- dif += imod - pimod & 32767;
- }
- }
- if (d4) {
- syms[li++] = 268435456 | revfl[l4] << 18 | revfd[d4];
- var lin = revfl[l4] & 31, din = revfd[d4] & 31;
- eb += fleb[lin] + fdeb[din];
- ++lf[257 + lin];
- ++df[din];
- wi = i6 + l4;
- ++lc_1;
- } else {
- syms[li++] = dat[i6];
- ++lf[dat[i6]];
- }
- }
- }
- for (i6 = Math.max(i6, wi);i6 < s4; ++i6) {
- syms[li++] = dat[i6];
- ++lf[dat[i6]];
- }
- pos = wblk(dat, w2, lst, syms, lf, df, eb, li, bs, i6 - bs, pos);
- if (!lst) {
- st.r = pos & 7 | w2[pos / 8 | 0] << 3;
- pos -= 7;
- st.h = head, st.p = prev, st.i = i6, st.w = wi;
- }
- } else {
- for (var i6 = st.w || 0;i6 < s4 + lst; i6 += 65535) {
- var e4 = i6 + 65535;
- if (e4 >= s4) {
- w2[pos / 8 | 0] = lst;
- e4 = s4;
- }
- pos = wfblk(w2, pos + 1, dat.subarray(i6, e4));
- }
- st.i = s4;
- }
- return slc(o5, 0, pre + shft(pos) + post);
-}, crct, crc = function() {
- var c8 = -1;
- return {
- p: function(d4) {
- var cr = c8;
- for (var i6 = 0;i6 < d4.length; ++i6)
- cr = crct[cr & 255 ^ d4[i6]] ^ cr >>> 8;
- c8 = cr;
- },
- d: function() {
- return ~c8;
- }
- };
-}, adler = function() {
- var a5 = 1, b4 = 0;
- return {
- p: function(d4) {
- var n5 = a5, m4 = b4;
- var l4 = d4.length | 0;
- for (var i6 = 0;i6 != l4; ) {
- var e4 = Math.min(i6 + 2655, l4);
- for (;i6 < e4; ++i6)
- m4 += n5 += d4[i6];
- n5 = (n5 & 65535) + 15 * (n5 >> 16), m4 = (m4 & 65535) + 15 * (m4 >> 16);
- }
- a5 = n5, b4 = m4;
- },
- d: function() {
- a5 %= 65521, b4 %= 65521;
- return (a5 & 255) << 24 | (a5 & 65280) << 8 | (b4 & 255) << 8 | b4 >> 8;
- }
- };
-}, dopt = function(dat, opt, pre, post, st) {
- if (!st) {
- st = { l: 1 };
- if (opt.dictionary) {
- var dict = opt.dictionary.subarray(-32768);
- var newDat = new u8(dict.length + dat.length);
- newDat.set(dict);
- newDat.set(dat, dict.length);
- dat = newDat;
- st.w = dict.length;
- }
- }
- return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
-}, mrg = function(a5, b4) {
- var o5 = {};
- for (var k4 in a5)
- o5[k4] = a5[k4];
- for (var k4 in b4)
- o5[k4] = b4[k4];
- return o5;
-}, wcln = function(fn, fnStr, td) {
- var dt = fn();
- var st = fn.toString();
- var ks = st.slice(st.indexOf("[") + 1, st.lastIndexOf("]")).replace(/\s+/g, "").split(",");
- for (var i6 = 0;i6 < dt.length; ++i6) {
- var v6 = dt[i6], k4 = ks[i6];
- if (typeof v6 == "function") {
- fnStr += ";" + k4 + "=";
- var st_1 = v6.toString();
- if (v6.prototype) {
- if (st_1.indexOf("[native code]") != -1) {
- var spInd = st_1.indexOf(" ", 8) + 1;
- fnStr += st_1.slice(spInd, st_1.indexOf("(", spInd));
- } else {
- fnStr += st_1;
- for (var t4 in v6.prototype)
- fnStr += ";" + k4 + ".prototype." + t4 + "=" + v6.prototype[t4].toString();
- }
- } else
- fnStr += st_1;
- } else
- td[k4] = v6;
- }
- return fnStr;
-}, ch, cbfs = function(v6) {
- var tl = [];
- for (var k4 in v6) {
- if (v6[k4].buffer) {
- tl.push((v6[k4] = new v6[k4].constructor(v6[k4])).buffer);
- }
- }
- return tl;
-}, wrkr = function(fns, init, id, cb) {
- if (!ch[id]) {
- var fnStr = "", td_1 = {}, m4 = fns.length - 1;
- for (var i6 = 0;i6 < m4; ++i6)
- fnStr = wcln(fns[i6], fnStr, td_1);
- ch[id] = { c: wcln(fns[m4], fnStr, td_1), e: td_1 };
- }
- var td = mrg({}, ch[id].e);
- return wk(ch[id].c + ";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=" + init.toString() + "}", id, td, cbfs(td), cb);
-}, bInflt = function() {
- return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt];
-}, bDflt = function() {
- return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf];
-}, gze = function() {
- return [gzh, gzhl, wbytes, crc, crct];
-}, guze = function() {
- return [gzs, gzl];
-}, zle = function() {
- return [zlh, wbytes, adler];
-}, zule = function() {
- return [zls];
-}, pbf = function(msg) {
- return postMessage(msg, [msg.buffer]);
-}, gopt = function(o5) {
- return o5 && {
- out: o5.size && new u8(o5.size),
- dictionary: o5.dictionary
- };
-}, cbify = function(dat, opts, fns, init, id, cb) {
- var w2 = wrkr(fns, init, id, function(err2, dat2) {
- w2.terminate();
- cb(err2, dat2);
- });
- w2.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);
- return function() {
- w2.terminate();
- };
-}, astrm = function(strm) {
- strm.ondata = function(dat, final) {
- return postMessage([dat, final], [dat.buffer]);
- };
- return function(ev) {
- if (ev.data.length) {
- strm.push(ev.data[0], ev.data[1]);
- postMessage([ev.data[0].length]);
- } else
- strm.flush();
- };
-}, astrmify = function(fns, strm, opts, init, id, flush, ext) {
- var t4;
- var w2 = wrkr(fns, init, id, function(err2, dat) {
- if (err2)
- w2.terminate(), strm.ondata.call(strm, err2);
- else if (!Array.isArray(dat))
- ext(dat);
- else if (dat.length == 1) {
- strm.queuedSize -= dat[0];
- if (strm.ondrain)
- strm.ondrain(dat[0]);
- } else {
- if (dat[1])
- w2.terminate();
- strm.ondata.call(strm, err2, dat[0], dat[1]);
- }
- });
- w2.postMessage(opts);
- strm.queuedSize = 0;
- strm.push = function(d4, f4) {
- if (!strm.ondata)
- err(5);
- if (t4)
- strm.ondata(err(4, 0, 1), null, !!f4);
- strm.queuedSize += d4.length;
- w2.postMessage([d4, t4 = f4], [d4.buffer]);
- };
- strm.terminate = function() {
- w2.terminate();
- };
- if (flush) {
- strm.flush = function() {
- w2.postMessage([]);
- };
- }
-}, b22 = function(d4, b4) {
- return d4[b4] | d4[b4 + 1] << 8;
-}, b4 = function(d4, b5) {
- return (d4[b5] | d4[b5 + 1] << 8 | d4[b5 + 2] << 16 | d4[b5 + 3] << 24) >>> 0;
-}, b8 = function(d4, b5) {
- return b4(d4, b5) + b4(d4, b5 + 4) * 4294967296;
-}, wbytes = function(d4, b5, v6) {
- for (;v6; ++b5)
- d4[b5] = v6, v6 >>>= 8;
-}, gzh = function(c8, o5) {
- var fn = o5.filename;
- c8[0] = 31, c8[1] = 139, c8[2] = 8, c8[8] = o5.level < 2 ? 4 : o5.level == 9 ? 2 : 0, c8[9] = 3;
- if (o5.mtime != 0)
- wbytes(c8, 4, Math.floor(new Date(o5.mtime || Date.now()) / 1000));
- if (fn) {
- c8[3] = 8;
- for (var i6 = 0;i6 <= fn.length; ++i6)
- c8[i6 + 10] = fn.charCodeAt(i6);
- }
-}, gzs = function(d4) {
- if (d4[0] != 31 || d4[1] != 139 || d4[2] != 8)
- err(6, "invalid gzip data");
- var flg = d4[3];
- var st = 10;
- if (flg & 4)
- st += (d4[10] | d4[11] << 8) + 2;
- for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1);zs > 0; zs -= !d4[st++])
- ;
- return st + (flg & 2);
-}, gzl = function(d4) {
- var l4 = d4.length;
- return (d4[l4 - 4] | d4[l4 - 3] << 8 | d4[l4 - 2] << 16 | d4[l4 - 1] << 24) >>> 0;
-}, gzhl = function(o5) {
- return 10 + (o5.filename ? o5.filename.length + 1 : 0);
-}, zlh = function(c8, o5) {
- var lv = o5.level, fl2 = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
- c8[0] = 120, c8[1] = fl2 << 6 | (o5.dictionary && 32);
- c8[1] |= 31 - (c8[0] << 8 | c8[1]) % 31;
- if (o5.dictionary) {
- var h5 = adler();
- h5.p(o5.dictionary);
- wbytes(c8, 2, h5.d());
- }
-}, zls = function(d4, dict) {
- if ((d4[0] & 15) != 8 || d4[0] >> 4 > 7 || (d4[0] << 8 | d4[1]) % 31)
- err(6, "invalid zlib data");
- if ((d4[1] >> 5 & 1) == +!dict)
- err(6, "invalid zlib data: " + (d4[1] & 32 ? "need" : "unexpected") + " dictionary");
- return (d4[1] >> 3 & 4) + 2;
-}, Deflate, AsyncDeflate, Inflate, AsyncInflate, Gzip, AsyncGzip, Gunzip, AsyncGunzip, Zlib, AsyncZlib, Unzlib, AsyncUnzlib, Decompress, AsyncDecompress, fltn = function(d4, p4, t4, o5) {
- for (var k4 in d4) {
- var val = d4[k4], n5 = p4 + k4, op = o5;
- if (Array.isArray(val))
- op = mrg(o5, val[1]), val = val[0];
- if (val instanceof u8)
- t4[n5] = [val, op];
- else {
- t4[n5 += "/"] = [new u8(0), op];
- fltn(val, n5, t4, o5);
- }
- }
-}, te, td, tds = 0, dutf8 = function(d4) {
- for (var r4 = "", i6 = 0;; ) {
- var c8 = d4[i6++];
- var eb = (c8 > 127) + (c8 > 223) + (c8 > 239);
- if (i6 + eb > d4.length)
- return { s: r4, r: slc(d4, i6 - 1) };
- if (!eb)
- r4 += String.fromCharCode(c8);
- else if (eb == 3) {
- c8 = ((c8 & 15) << 18 | (d4[i6++] & 63) << 12 | (d4[i6++] & 63) << 6 | d4[i6++] & 63) - 65536, r4 += String.fromCharCode(55296 | c8 >> 10, 56320 | c8 & 1023);
- } else if (eb & 1)
- r4 += String.fromCharCode((c8 & 31) << 6 | d4[i6++] & 63);
- else
- r4 += String.fromCharCode((c8 & 15) << 12 | (d4[i6++] & 63) << 6 | d4[i6++] & 63);
- }
-}, DecodeUTF8, EncodeUTF8, dbf = function(l4) {
- return l4 == 1 ? 3 : l4 < 6 ? 2 : l4 == 9 ? 1 : 0;
-}, slzh = function(d4, b5) {
- return b5 + 30 + b22(d4, b5 + 26) + b22(d4, b5 + 28);
-}, zh = function(d4, b5, z3) {
- var fnl = b22(d4, b5 + 28), fn = strFromU8(d4.subarray(b5 + 46, b5 + 46 + fnl), !(b22(d4, b5 + 8) & 2048)), es = b5 + 46 + fnl, bs = b4(d4, b5 + 20);
- var _a9 = z3 && bs == 4294967295 ? z64e(d4, es) : [bs, b4(d4, b5 + 24), b4(d4, b5 + 42)], sc = _a9[0], su = _a9[1], off = _a9[2];
- return [b22(d4, b5 + 10), sc, su, fn, es + b22(d4, b5 + 30) + b22(d4, b5 + 32), off];
-}, z64e = function(d4, b5) {
- for (;b22(d4, b5) != 1; b5 += 4 + b22(d4, b5 + 2))
- ;
- return [b8(d4, b5 + 12), b8(d4, b5 + 4), b8(d4, b5 + 20)];
-}, exfl = function(ex) {
- var le = 0;
- if (ex) {
- for (var k4 in ex) {
- var l4 = ex[k4].length;
- if (l4 > 65535)
- err(9);
- le += l4 + 4;
- }
- }
- return le;
-}, wzh = function(d4, b5, f4, fn, u5, c8, ce, co) {
- var fl2 = fn.length, ex = f4.extra, col = co && co.length;
- var exl = exfl(ex);
- wbytes(d4, b5, ce != null ? 33639248 : 67324752), b5 += 4;
- if (ce != null)
- d4[b5++] = 20, d4[b5++] = f4.os;
- d4[b5] = 20, b5 += 2;
- d4[b5++] = f4.flag << 1 | (c8 < 0 && 8), d4[b5++] = u5 && 8;
- d4[b5++] = f4.compression & 255, d4[b5++] = f4.compression >> 8;
- var dt = new Date(f4.mtime == null ? Date.now() : f4.mtime), y3 = dt.getFullYear() - 1980;
- if (y3 < 0 || y3 > 119)
- err(10);
- wbytes(d4, b5, y3 << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b5 += 4;
- if (c8 != -1) {
- wbytes(d4, b5, f4.crc);
- wbytes(d4, b5 + 4, c8 < 0 ? -c8 - 2 : c8);
- wbytes(d4, b5 + 8, f4.size);
- }
- wbytes(d4, b5 + 12, fl2);
- wbytes(d4, b5 + 14, exl), b5 += 16;
- if (ce != null) {
- wbytes(d4, b5, col);
- wbytes(d4, b5 + 6, f4.attrs);
- wbytes(d4, b5 + 10, ce), b5 += 14;
- }
- d4.set(fn, b5);
- b5 += fl2;
- if (exl) {
- for (var k4 in ex) {
- var exf = ex[k4], l4 = exf.length;
- wbytes(d4, b5, +k4);
- wbytes(d4, b5 + 2, l4);
- d4.set(exf, b5 + 4), b5 += 4 + l4;
- }
- }
- if (col)
- d4.set(co, b5), b5 += col;
- return b5;
-}, wzf = function(o5, b5, c8, d4, e4) {
- wbytes(o5, b5, 101010256);
- wbytes(o5, b5 + 8, c8);
- wbytes(o5, b5 + 10, c8);
- wbytes(o5, b5 + 12, d4);
- wbytes(o5, b5 + 16, e4);
-}, ZipPassThrough, ZipDeflate, AsyncZipDeflate, Zip, UnzipPassThrough, UnzipInflate, AsyncUnzipInflate, Unzip, mt;
-var init_esm18 = __esm(() => {
- require2 = createRequire("/");
- try {
- Worker2 = require2("worker_threads").Worker;
- } catch (e4) {}
- wk = Worker2 ? function(c8, _, msg, transfer7, cb) {
- var done = false;
- var w2 = new Worker2(c8 + workerAdd, { eval: true }).on("error", function(e4) {
- return cb(e4, null);
- }).on("message", function(m4) {
- return cb(null, m4);
- }).on("exit", function(c9) {
- if (c9 && !done)
- cb(new Error("exited with code " + c9), null);
- });
- w2.postMessage(msg, transfer7);
- w2.terminate = function() {
- done = true;
- return Worker2.prototype.terminate.call(w2);
- };
- return w2;
- } : function(_, __, ___, ____, cb) {
- setImmediate(function() {
- return cb(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"), null);
- });
- var NOP = function() {};
- return {
- terminate: NOP,
- postMessage: NOP
- };
- };
- u8 = Uint8Array;
- u16 = Uint16Array;
- i32 = Int32Array;
- fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0]);
- fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0]);
- clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
- _a8 = freb(fleb, 2);
- fl = _a8.b;
- revfl = _a8.r;
- fl[28] = 258, revfl[258] = 28;
- _b2 = freb(fdeb, 0);
- fd = _b2.b;
- revfd = _b2.r;
- rev = new u16(32768);
- for (i5 = 0;i5 < 32768; ++i5) {
- x3 = (i5 & 43690) >> 1 | (i5 & 21845) << 1;
- x3 = (x3 & 52428) >> 2 | (x3 & 13107) << 2;
- x3 = (x3 & 61680) >> 4 | (x3 & 3855) << 4;
- rev[i5] = ((x3 & 65280) >> 8 | (x3 & 255) << 8) >> 1;
- }
- flt = new u8(288);
- for (i5 = 0;i5 < 144; ++i5)
- flt[i5] = 8;
- for (i5 = 144;i5 < 256; ++i5)
- flt[i5] = 9;
- for (i5 = 256;i5 < 280; ++i5)
- flt[i5] = 7;
- for (i5 = 280;i5 < 288; ++i5)
- flt[i5] = 8;
- fdt = new u8(32);
- for (i5 = 0;i5 < 32; ++i5)
- fdt[i5] = 5;
- flm = /* @__PURE__ */ hMap(flt, 9, 0);
- flrm = /* @__PURE__ */ hMap(flt, 9, 1);
- fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
- fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
- FlateErrorCode = {
- UnexpectedEOF: 0,
- InvalidBlockType: 1,
- InvalidLengthLiteral: 2,
- InvalidDistance: 3,
- StreamFinished: 4,
- NoStreamHandler: 5,
- InvalidHeader: 6,
- NoCallback: 7,
- InvalidUTF8: 8,
- ExtraFieldTooLong: 9,
- InvalidDate: 10,
- FilenameTooLong: 11,
- StreamFinishing: 12,
- InvalidZipData: 13,
- UnknownCompressionMethod: 14
- };
- ec = [
- "unexpected EOF",
- "invalid block type",
- "invalid length/literal",
- "invalid distance",
- "stream finished",
- "no stream handler",
- ,
- "no callback",
- "invalid UTF-8 data",
- "extra field too long",
- "date not in range 1980-2099",
- "filename too long",
- "stream finishing",
- "invalid zip data"
- ];
- deo = /* @__PURE__ */ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
- et = /* @__PURE__ */ new u8(0);
- crct = /* @__PURE__ */ function() {
- var t4 = new Int32Array(256);
- for (var i6 = 0;i6 < 256; ++i6) {
- var c8 = i6, k4 = 9;
- while (--k4)
- c8 = (c8 & 1 && -306674912) ^ c8 >>> 1;
- t4[i6] = c8;
- }
- return t4;
- }();
- ch = [];
- Deflate = /* @__PURE__ */ function() {
- function Deflate2(opts, cb) {
- if (typeof opts == "function")
- cb = opts, opts = {};
- this.ondata = cb;
- this.o = opts || {};
- this.s = { l: 0, i: 32768, w: 32768, z: 32768 };
- this.b = new u8(98304);
- if (this.o.dictionary) {
- var dict = this.o.dictionary.subarray(-32768);
- this.b.set(dict, 32768 - dict.length);
- this.s.i = 32768 - dict.length;
- }
- }
- Deflate2.prototype.p = function(c8, f4) {
- this.ondata(dopt(c8, this.o, 0, 0, this.s), f4);
- };
- Deflate2.prototype.push = function(chunk, final) {
- if (!this.ondata)
- err(5);
- if (this.s.l)
- err(4);
- var endLen = chunk.length + this.s.z;
- if (endLen > this.b.length) {
- if (endLen > 2 * this.b.length - 32768) {
- var newBuf = new u8(endLen & -32768);
- newBuf.set(this.b.subarray(0, this.s.z));
- this.b = newBuf;
- }
- var split2 = this.b.length - this.s.z;
- this.b.set(chunk.subarray(0, split2), this.s.z);
- this.s.z = this.b.length;
- this.p(this.b, false);
- this.b.set(this.b.subarray(-32768));
- this.b.set(chunk.subarray(split2), 32768);
- this.s.z = chunk.length - split2 + 32768;
- this.s.i = 32766, this.s.w = 32768;
- } else {
- this.b.set(chunk, this.s.z);
- this.s.z += chunk.length;
- }
- this.s.l = final & 1;
- if (this.s.z > this.s.w + 8191 || final) {
- this.p(this.b, final || false);
- this.s.w = this.s.i, this.s.i -= 2;
- }
- };
- Deflate2.prototype.flush = function() {
- if (!this.ondata)
- err(5);
- if (this.s.l)
- err(4);
- this.p(this.b, false);
- this.s.w = this.s.i, this.s.i -= 2;
- };
- return Deflate2;
- }();
- AsyncDeflate = /* @__PURE__ */ function() {
- function AsyncDeflate2(opts, cb) {
- astrmify([
- bDflt,
- function() {
- return [astrm, Deflate];
- }
- ], this, StrmOpt.call(this, opts, cb), function(ev) {
- var strm = new Deflate(ev.data);
- onmessage = astrm(strm);
- }, 6, 1);
- }
- return AsyncDeflate2;
- }();
- Inflate = /* @__PURE__ */ function() {
- function Inflate2(opts, cb) {
- if (typeof opts == "function")
- cb = opts, opts = {};
- this.ondata = cb;
- var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
- this.s = { i: 0, b: dict ? dict.length : 0 };
- this.o = new u8(32768);
- this.p = new u8(0);
- if (dict)
- this.o.set(dict);
- }
- Inflate2.prototype.e = function(c8) {
- if (!this.ondata)
- err(5);
- if (this.d)
- err(4);
- if (!this.p.length)
- this.p = c8;
- else if (c8.length) {
- var n5 = new u8(this.p.length + c8.length);
- n5.set(this.p), n5.set(c8, this.p.length), this.p = n5;
- }
- };
- Inflate2.prototype.c = function(final) {
- this.s.i = +(this.d = final || false);
- var bts = this.s.b;
- var dt = inflt(this.p, this.s, this.o);
- this.ondata(slc(dt, bts, this.s.b), this.d);
- this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
- this.p = slc(this.p, this.s.p / 8 | 0), this.s.p &= 7;
- };
- Inflate2.prototype.push = function(chunk, final) {
- this.e(chunk), this.c(final);
- };
- return Inflate2;
- }();
- AsyncInflate = /* @__PURE__ */ function() {
- function AsyncInflate2(opts, cb) {
- astrmify([
- bInflt,
- function() {
- return [astrm, Inflate];
- }
- ], this, StrmOpt.call(this, opts, cb), function(ev) {
- var strm = new Inflate(ev.data);
- onmessage = astrm(strm);
- }, 7, 0);
- }
- return AsyncInflate2;
- }();
- Gzip = /* @__PURE__ */ function() {
- function Gzip2(opts, cb) {
- this.c = crc();
- this.l = 0;
- this.v = 1;
- Deflate.call(this, opts, cb);
- }
- Gzip2.prototype.push = function(chunk, final) {
- this.c.p(chunk);
- this.l += chunk.length;
- Deflate.prototype.push.call(this, chunk, final);
- };
- Gzip2.prototype.p = function(c8, f4) {
- var raw = dopt(c8, this.o, this.v && gzhl(this.o), f4 && 8, this.s);
- if (this.v)
- gzh(raw, this.o), this.v = 0;
- if (f4)
- wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);
- this.ondata(raw, f4);
- };
- Gzip2.prototype.flush = function() {
- Deflate.prototype.flush.call(this);
- };
- return Gzip2;
- }();
- AsyncGzip = /* @__PURE__ */ function() {
- function AsyncGzip2(opts, cb) {
- astrmify([
- bDflt,
- gze,
- function() {
- return [astrm, Deflate, Gzip];
- }
- ], this, StrmOpt.call(this, opts, cb), function(ev) {
- var strm = new Gzip(ev.data);
- onmessage = astrm(strm);
- }, 8, 1);
- }
- return AsyncGzip2;
- }();
- Gunzip = /* @__PURE__ */ function() {
- function Gunzip2(opts, cb) {
- this.v = 1;
- this.r = 0;
- Inflate.call(this, opts, cb);
- }
- Gunzip2.prototype.push = function(chunk, final) {
- Inflate.prototype.e.call(this, chunk);
- this.r += chunk.length;
- if (this.v) {
- var p4 = this.p.subarray(this.v - 1);
- var s4 = p4.length > 3 ? gzs(p4) : 4;
- if (s4 > p4.length) {
- if (!final)
- return;
- } else if (this.v > 1 && this.onmember) {
- this.onmember(this.r - p4.length);
- }
- this.p = p4.subarray(s4), this.v = 0;
- }
- Inflate.prototype.c.call(this, final);
- if (this.s.f && !this.s.l && !final) {
- this.v = shft(this.s.p) + 9;
- this.s = { i: 0 };
- this.o = new u8(0);
- this.push(new u8(0), final);
- }
- };
- return Gunzip2;
- }();
- AsyncGunzip = /* @__PURE__ */ function() {
- function AsyncGunzip2(opts, cb) {
- var _this = this;
- astrmify([
- bInflt,
- guze,
- function() {
- return [astrm, Inflate, Gunzip];
- }
- ], this, StrmOpt.call(this, opts, cb), function(ev) {
- var strm = new Gunzip(ev.data);
- strm.onmember = function(offset) {
- return postMessage(offset);
- };
- onmessage = astrm(strm);
- }, 9, 0, function(offset) {
- return _this.onmember && _this.onmember(offset);
- });
- }
- return AsyncGunzip2;
- }();
- Zlib = /* @__PURE__ */ function() {
- function Zlib2(opts, cb) {
- this.c = adler();
- this.v = 1;
- Deflate.call(this, opts, cb);
- }
- Zlib2.prototype.push = function(chunk, final) {
- this.c.p(chunk);
- Deflate.prototype.push.call(this, chunk, final);
- };
- Zlib2.prototype.p = function(c8, f4) {
- var raw = dopt(c8, this.o, this.v && (this.o.dictionary ? 6 : 2), f4 && 4, this.s);
- if (this.v)
- zlh(raw, this.o), this.v = 0;
- if (f4)
- wbytes(raw, raw.length - 4, this.c.d());
- this.ondata(raw, f4);
- };
- Zlib2.prototype.flush = function() {
- Deflate.prototype.flush.call(this);
- };
- return Zlib2;
- }();
- AsyncZlib = /* @__PURE__ */ function() {
- function AsyncZlib2(opts, cb) {
- astrmify([
- bDflt,
- zle,
- function() {
- return [astrm, Deflate, Zlib];
- }
- ], this, StrmOpt.call(this, opts, cb), function(ev) {
- var strm = new Zlib(ev.data);
- onmessage = astrm(strm);
- }, 10, 1);
- }
- return AsyncZlib2;
- }();
- Unzlib = /* @__PURE__ */ function() {
- function Unzlib2(opts, cb) {
- Inflate.call(this, opts, cb);
- this.v = opts && opts.dictionary ? 2 : 1;
- }
- Unzlib2.prototype.push = function(chunk, final) {
- Inflate.prototype.e.call(this, chunk);
- if (this.v) {
- if (this.p.length < 6 && !final)
- return;
- this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;
- }
- if (final) {
- if (this.p.length < 4)
- err(6, "invalid zlib data");
- this.p = this.p.subarray(0, -4);
- }
- Inflate.prototype.c.call(this, final);
- };
- return Unzlib2;
- }();
- AsyncUnzlib = /* @__PURE__ */ function() {
- function AsyncUnzlib2(opts, cb) {
- astrmify([
- bInflt,
- zule,
- function() {
- return [astrm, Inflate, Unzlib];
- }
- ], this, StrmOpt.call(this, opts, cb), function(ev) {
- var strm = new Unzlib(ev.data);
- onmessage = astrm(strm);
- }, 11, 0);
- }
- return AsyncUnzlib2;
- }();
- Decompress = /* @__PURE__ */ function() {
- function Decompress2(opts, cb) {
- this.o = StrmOpt.call(this, opts, cb) || {};
- this.G = Gunzip;
- this.I = Inflate;
- this.Z = Unzlib;
- }
- Decompress2.prototype.i = function() {
- var _this = this;
- this.s.ondata = function(dat, final) {
- _this.ondata(dat, final);
- };
- };
- Decompress2.prototype.push = function(chunk, final) {
- if (!this.ondata)
- err(5);
- if (!this.s) {
- if (this.p && this.p.length) {
- var n5 = new u8(this.p.length + chunk.length);
- n5.set(this.p), n5.set(chunk, this.p.length);
- } else
- this.p = chunk;
- if (this.p.length > 2) {
- this.s = this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8 ? new this.G(this.o) : (this.p[0] & 15) != 8 || this.p[0] >> 4 > 7 || (this.p[0] << 8 | this.p[1]) % 31 ? new this.I(this.o) : new this.Z(this.o);
- this.i();
- this.s.push(this.p, final);
- this.p = null;
- }
- } else
- this.s.push(chunk, final);
- };
- return Decompress2;
- }();
- AsyncDecompress = /* @__PURE__ */ function() {
- function AsyncDecompress2(opts, cb) {
- Decompress.call(this, opts, cb);
- this.queuedSize = 0;
- this.G = AsyncGunzip;
- this.I = AsyncInflate;
- this.Z = AsyncUnzlib;
- }
- AsyncDecompress2.prototype.i = function() {
- var _this = this;
- this.s.ondata = function(err2, dat, final) {
- _this.ondata(err2, dat, final);
- };
- this.s.ondrain = function(size) {
- _this.queuedSize -= size;
- if (_this.ondrain)
- _this.ondrain(size);
- };
- };
- AsyncDecompress2.prototype.push = function(chunk, final) {
- this.queuedSize += chunk.length;
- Decompress.prototype.push.call(this, chunk, final);
- };
- return AsyncDecompress2;
- }();
- te = typeof TextEncoder != "undefined" && /* @__PURE__ */ new TextEncoder;
- td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder;
- try {
- td.decode(et, { stream: true });
- tds = 1;
- } catch (e4) {}
- DecodeUTF8 = /* @__PURE__ */ function() {
- function DecodeUTF82(cb) {
- this.ondata = cb;
- if (tds)
- this.t = new TextDecoder;
- else
- this.p = et;
- }
- DecodeUTF82.prototype.push = function(chunk, final) {
- if (!this.ondata)
- err(5);
- final = !!final;
- if (this.t) {
- this.ondata(this.t.decode(chunk, { stream: true }), final);
- if (final) {
- if (this.t.decode().length)
- err(8);
- this.t = null;
- }
- return;
- }
- if (!this.p)
- err(4);
- var dat = new u8(this.p.length + chunk.length);
- dat.set(this.p);
- dat.set(chunk, this.p.length);
- var _a9 = dutf8(dat), s4 = _a9.s, r4 = _a9.r;
- if (final) {
- if (r4.length)
- err(8);
- this.p = null;
- } else
- this.p = r4;
- this.ondata(s4, final);
- };
- return DecodeUTF82;
- }();
- EncodeUTF8 = /* @__PURE__ */ function() {
- function EncodeUTF82(cb) {
- this.ondata = cb;
- }
- EncodeUTF82.prototype.push = function(chunk, final) {
- if (!this.ondata)
- err(5);
- if (this.d)
- err(4);
- this.ondata(strToU8(chunk), this.d = final || false);
- };
- return EncodeUTF82;
- }();
- ZipPassThrough = /* @__PURE__ */ function() {
- function ZipPassThrough2(filename) {
- this.filename = filename;
- this.c = crc();
- this.size = 0;
- this.compression = 0;
- }
- ZipPassThrough2.prototype.process = function(chunk, final) {
- this.ondata(null, chunk, final);
- };
- ZipPassThrough2.prototype.push = function(chunk, final) {
- if (!this.ondata)
- err(5);
- this.c.p(chunk);
- this.size += chunk.length;
- if (final)
- this.crc = this.c.d();
- this.process(chunk, final || false);
- };
- return ZipPassThrough2;
- }();
- ZipDeflate = /* @__PURE__ */ function() {
- function ZipDeflate2(filename, opts) {
- var _this = this;
- if (!opts)
- opts = {};
- ZipPassThrough.call(this, filename);
- this.d = new Deflate(opts, function(dat, final) {
- _this.ondata(null, dat, final);
- });
- this.compression = 8;
- this.flag = dbf(opts.level);
- }
- ZipDeflate2.prototype.process = function(chunk, final) {
- try {
- this.d.push(chunk, final);
- } catch (e4) {
- this.ondata(e4, null, final);
- }
- };
- ZipDeflate2.prototype.push = function(chunk, final) {
- ZipPassThrough.prototype.push.call(this, chunk, final);
- };
- return ZipDeflate2;
- }();
- AsyncZipDeflate = /* @__PURE__ */ function() {
- function AsyncZipDeflate2(filename, opts) {
- var _this = this;
- if (!opts)
- opts = {};
- ZipPassThrough.call(this, filename);
- this.d = new AsyncDeflate(opts, function(err2, dat, final) {
- _this.ondata(err2, dat, final);
- });
- this.compression = 8;
- this.flag = dbf(opts.level);
- this.terminate = this.d.terminate;
- }
- AsyncZipDeflate2.prototype.process = function(chunk, final) {
- this.d.push(chunk, final);
- };
- AsyncZipDeflate2.prototype.push = function(chunk, final) {
- ZipPassThrough.prototype.push.call(this, chunk, final);
- };
- return AsyncZipDeflate2;
- }();
- Zip = /* @__PURE__ */ function() {
- function Zip2(cb) {
- this.ondata = cb;
- this.u = [];
- this.d = 1;
- }
- Zip2.prototype.add = function(file2) {
- var _this = this;
- if (!this.ondata)
- err(5);
- if (this.d & 2)
- this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);
- else {
- var f4 = strToU8(file2.filename), fl_1 = f4.length;
- var com = file2.comment, o5 = com && strToU8(com);
- var u5 = fl_1 != file2.filename.length || o5 && com.length != o5.length;
- var hl_1 = fl_1 + exfl(file2.extra) + 30;
- if (fl_1 > 65535)
- this.ondata(err(11, 0, 1), null, false);
- var header = new u8(hl_1);
- wzh(header, 0, file2, f4, u5, -1);
- var chks_1 = [header];
- var pAll_1 = function() {
- for (var _i3 = 0, chks_2 = chks_1;_i3 < chks_2.length; _i3++) {
- var chk = chks_2[_i3];
- _this.ondata(null, chk, false);
- }
- chks_1 = [];
- };
- var tr_1 = this.d;
- this.d = 0;
- var ind_1 = this.u.length;
- var uf_1 = mrg(file2, {
- f: f4,
- u: u5,
- o: o5,
- t: function() {
- if (file2.terminate)
- file2.terminate();
- },
- r: function() {
- pAll_1();
- if (tr_1) {
- var nxt = _this.u[ind_1 + 1];
- if (nxt)
- nxt.r();
- else
- _this.d = 1;
- }
- tr_1 = 1;
- }
- });
- var cl_1 = 0;
- file2.ondata = function(err2, dat, final) {
- if (err2) {
- _this.ondata(err2, dat, final);
- _this.terminate();
- } else {
- cl_1 += dat.length;
- chks_1.push(dat);
- if (final) {
- var dd = new u8(16);
- wbytes(dd, 0, 134695760);
- wbytes(dd, 4, file2.crc);
- wbytes(dd, 8, cl_1);
- wbytes(dd, 12, file2.size);
- chks_1.push(dd);
- uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file2.crc, uf_1.size = file2.size;
- if (tr_1)
- uf_1.r();
- tr_1 = 1;
- } else if (tr_1)
- pAll_1();
- }
- };
- this.u.push(uf_1);
- }
- };
- Zip2.prototype.end = function() {
- var _this = this;
- if (this.d & 2) {
- this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);
- return;
- }
- if (this.d)
- this.e();
- else
- this.u.push({
- r: function() {
- if (!(_this.d & 1))
- return;
- _this.u.splice(-1, 1);
- _this.e();
- },
- t: function() {}
- });
- this.d = 3;
- };
- Zip2.prototype.e = function() {
- var bt = 0, l4 = 0, tl = 0;
- for (var _i3 = 0, _a9 = this.u;_i3 < _a9.length; _i3++) {
- var f4 = _a9[_i3];
- tl += 46 + f4.f.length + exfl(f4.extra) + (f4.o ? f4.o.length : 0);
- }
- var out = new u8(tl + 22);
- for (var _b3 = 0, _c20 = this.u;_b3 < _c20.length; _b3++) {
- var f4 = _c20[_b3];
- wzh(out, bt, f4, f4.f, f4.u, -f4.c - 2, l4, f4.o);
- bt += 46 + f4.f.length + exfl(f4.extra) + (f4.o ? f4.o.length : 0), l4 += f4.b;
- }
- wzf(out, bt, this.u.length, tl, l4);
- this.ondata(null, out, true);
- this.d = 2;
- };
- Zip2.prototype.terminate = function() {
- for (var _i3 = 0, _a9 = this.u;_i3 < _a9.length; _i3++) {
- var f4 = _a9[_i3];
- f4.t();
- }
- this.d = 2;
- };
- return Zip2;
- }();
- UnzipPassThrough = /* @__PURE__ */ function() {
- function UnzipPassThrough2() {}
- UnzipPassThrough2.prototype.push = function(data, final) {
- this.ondata(null, data, final);
- };
- UnzipPassThrough2.compression = 0;
- return UnzipPassThrough2;
- }();
- UnzipInflate = /* @__PURE__ */ function() {
- function UnzipInflate2() {
- var _this = this;
- this.i = new Inflate(function(dat, final) {
- _this.ondata(null, dat, final);
- });
- }
- UnzipInflate2.prototype.push = function(data, final) {
- try {
- this.i.push(data, final);
- } catch (e4) {
- this.ondata(e4, null, final);
- }
- };
- UnzipInflate2.compression = 8;
- return UnzipInflate2;
- }();
- AsyncUnzipInflate = /* @__PURE__ */ function() {
- function AsyncUnzipInflate2(_, sz) {
- var _this = this;
- if (sz < 320000) {
- this.i = new Inflate(function(dat, final) {
- _this.ondata(null, dat, final);
- });
- } else {
- this.i = new AsyncInflate(function(err2, dat, final) {
- _this.ondata(err2, dat, final);
- });
- this.terminate = this.i.terminate;
- }
- }
- AsyncUnzipInflate2.prototype.push = function(data, final) {
- if (this.i.terminate)
- data = slc(data, 0);
- this.i.push(data, final);
- };
- AsyncUnzipInflate2.compression = 8;
- return AsyncUnzipInflate2;
- }();
- Unzip = /* @__PURE__ */ function() {
- function Unzip2(cb) {
- this.onfile = cb;
- this.k = [];
- this.o = {
- 0: UnzipPassThrough
- };
- this.p = et;
- }
- Unzip2.prototype.push = function(chunk, final) {
- var _this = this;
- if (!this.onfile)
- err(5);
- if (!this.p)
- err(4);
- if (this.c > 0) {
- var len = Math.min(this.c, chunk.length);
- var toAdd = chunk.subarray(0, len);
- this.c -= len;
- if (this.d)
- this.d.push(toAdd, !this.c);
- else
- this.k[0].push(toAdd);
- chunk = chunk.subarray(len);
- if (chunk.length)
- return this.push(chunk, final);
- } else {
- var f4 = 0, i6 = 0, is = undefined, buf = undefined;
- if (!this.p.length)
- buf = chunk;
- else if (!chunk.length)
- buf = this.p;
- else {
- buf = new u8(this.p.length + chunk.length);
- buf.set(this.p), buf.set(chunk, this.p.length);
- }
- var l4 = buf.length, oc = this.c, add = oc && this.d;
- var _loop_2 = function() {
- var _a9;
- var sig = b4(buf, i6);
- if (sig == 67324752) {
- f4 = 1, is = i6;
- this_1.d = null;
- this_1.c = 0;
- var bf = b22(buf, i6 + 6), cmp_1 = b22(buf, i6 + 8), u5 = bf & 2048, dd = bf & 8, fnl = b22(buf, i6 + 26), es = b22(buf, i6 + 28);
- if (l4 > i6 + 30 + fnl + es) {
- var chks_3 = [];
- this_1.k.unshift(chks_3);
- f4 = 2;
- var sc_1 = b4(buf, i6 + 18), su_1 = b4(buf, i6 + 22);
- var fn_1 = strFromU8(buf.subarray(i6 + 30, i6 += 30 + fnl), !u5);
- if (sc_1 == 4294967295) {
- _a9 = dd ? [-2] : z64e(buf, i6), sc_1 = _a9[0], su_1 = _a9[1];
- } else if (dd)
- sc_1 = -1;
- i6 += es;
- this_1.c = sc_1;
- var d_1;
- var file_1 = {
- name: fn_1,
- compression: cmp_1,
- start: function() {
- if (!file_1.ondata)
- err(5);
- if (!sc_1)
- file_1.ondata(null, et, true);
- else {
- var ctr = _this.o[cmp_1];
- if (!ctr)
- file_1.ondata(err(14, "unknown compression type " + cmp_1, 1), null, false);
- d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);
- d_1.ondata = function(err2, dat3, final2) {
- file_1.ondata(err2, dat3, final2);
- };
- for (var _i3 = 0, chks_4 = chks_3;_i3 < chks_4.length; _i3++) {
- var dat2 = chks_4[_i3];
- d_1.push(dat2, false);
- }
- if (_this.k[0] == chks_3 && _this.c)
- _this.d = d_1;
- else
- d_1.push(et, true);
- }
- },
- terminate: function() {
- if (d_1 && d_1.terminate)
- d_1.terminate();
- }
- };
- if (sc_1 >= 0)
- file_1.size = sc_1, file_1.originalSize = su_1;
- this_1.onfile(file_1);
- }
- return "break";
- } else if (oc) {
- if (sig == 134695760) {
- is = i6 += 12 + (oc == -2 && 8), f4 = 3, this_1.c = 0;
- return "break";
- } else if (sig == 33639248) {
- is = i6 -= 4, f4 = 3, this_1.c = 0;
- return "break";
- }
- }
- };
- var this_1 = this;
- for (;i6 < l4 - 4; ++i6) {
- var state_1 = _loop_2();
- if (state_1 === "break")
- break;
- }
- this.p = et;
- if (oc < 0) {
- var dat = f4 ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 134695760 && 4)) : buf.subarray(0, i6);
- if (add)
- add.push(dat, !!f4);
- else
- this.k[+(f4 == 2)].push(dat);
- }
- if (f4 & 2)
- return this.push(buf.subarray(i6), final);
- this.p = buf.subarray(i6);
- }
- if (final) {
- if (this.c)
- err(13);
- this.p = null;
- }
- };
- Unzip2.prototype.register = function(decoder) {
- this.o[decoder.compression] = decoder;
- };
- return Unzip2;
- }();
- mt = typeof queueMicrotask == "function" ? queueMicrotask : typeof setTimeout == "function" ? setTimeout : function(fn) {
- fn();
- };
-});
-
-// node_modules/@anthropic-ai/mcpb/node_modules/ignore/index.js
-var require_ignore2 = __commonJS((exports, module) => {
- function makeArray(subject) {
- return Array.isArray(subject) ? subject : [subject];
- }
- var UNDEFINED = undefined;
- var EMPTY5 = "";
- var SPACE = " ";
- var ESCAPE = "\\";
- var REGEX_TEST_BLANK_LINE = /^\s+$/;
- var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
- var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
- var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
- var REGEX_SPLITALL_CRLF = /\r?\n/g;
- var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
- var REGEX_TEST_TRAILING_SLASH = /\/$/;
- var SLASH = "/";
- var TMP_KEY_IGNORE = "node-ignore";
- if (typeof Symbol !== "undefined") {
- TMP_KEY_IGNORE = Symbol.for("node-ignore");
- }
- var KEY_IGNORE = TMP_KEY_IGNORE;
- var define2 = (object2, key2, value) => {
- Object.defineProperty(object2, key2, { value });
- return value;
- };
- var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
- var RETURN_FALSE = () => false;
- var sanitizeRange = (range) => range.replace(REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY5);
- var cleanRangeBackSlash = (slashes) => {
- const { length } = slashes;
- return slashes.slice(0, length - length % 2);
- };
- var REPLACERS = [
- [
- /^\uFEFF/,
- () => EMPTY5
- ],
- [
- /((?:\\\\)*?)(\\?\s+)$/,
- (_, m1, m22) => m1 + (m22.indexOf("\\") === 0 ? SPACE : EMPTY5)
- ],
- [
- /(\\+?)\s/g,
- (_, m1) => {
- const { length } = m1;
- return m1.slice(0, length - length % 2) + SPACE;
- }
- ],
- [
- /[\\$.|*+(){^]/g,
- (match) => `\\${match}`
- ],
- [
- /(?!\\)\?/g,
- () => "[^/]"
- ],
- [
- /^\//,
- () => "^"
- ],
- [
- /\//g,
- () => "\\/"
- ],
- [
- /^\^*\\\*\\\*\\\//,
- () => "^(?:.*\\/)?"
- ],
- [
- /^(?=[^^])/,
- function startingReplacer() {
- return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
- }
- ],
- [
- /\\\/\\\*\\\*(?=\\\/|$)/g,
- (_, index2, str) => index2 + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
- ],
- [
- /(^|[^\\]+)(\\\*)+(?=.+)/g,
- (_, p1, p22) => {
- const unescaped = p22.replace(/\\\*/g, "[^\\/]*");
- return p1 + unescaped;
- }
- ],
- [
- /\\\\\\(?=[$.|*+(){^])/g,
- () => ESCAPE
- ],
- [
- /\\\\/g,
- () => ESCAPE
- ],
- [
- /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
- (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
- ],
- [
- /(?:[^*])$/,
- (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`
- ]
- ];
- var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/;
- var MODE_IGNORE = "regex";
- var MODE_CHECK_IGNORE = "checkRegex";
- var UNDERSCORE = "_";
- var TRAILING_WILD_CARD_REPLACERS = {
- [MODE_IGNORE](_, p1) {
- const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
- return `${prefix}(?=$|\\/$)`;
- },
- [MODE_CHECK_IGNORE](_, p1) {
- const prefix = p1 ? `${p1}[^/]*` : "[^/]*";
- return `${prefix}(?=$|\\/$)`;
- }
- };
- var makeRegexPrefix = (pattern) => REPLACERS.reduce((prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)), pattern);
- var isString2 = (subject) => typeof subject === "string";
- var checkPattern = (pattern) => pattern && isString2(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
- var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
-
- class IgnoreRule {
- constructor(pattern, mark, body, ignoreCase, negative, prefix) {
- this.pattern = pattern;
- this.mark = mark;
- this.negative = negative;
- define2(this, "body", body);
- define2(this, "ignoreCase", ignoreCase);
- define2(this, "regexPrefix", prefix);
- }
- get regex() {
- const key2 = UNDERSCORE + MODE_IGNORE;
- if (this[key2]) {
- return this[key2];
- }
- return this._make(MODE_IGNORE, key2);
- }
- get checkRegex() {
- const key2 = UNDERSCORE + MODE_CHECK_IGNORE;
- if (this[key2]) {
- return this[key2];
- }
- return this._make(MODE_CHECK_IGNORE, key2);
- }
- _make(mode, key2) {
- const str = this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD, TRAILING_WILD_CARD_REPLACERS[mode]);
- const regex2 = this.ignoreCase ? new RegExp(str, "i") : new RegExp(str);
- return define2(this, key2, regex2);
- }
- }
- var createRule = ({
- pattern,
- mark
- }, ignoreCase) => {
- let negative = false;
- let body = pattern;
- if (body.indexOf("!") === 0) {
- negative = true;
- body = body.substr(1);
- }
- body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
- const regexPrefix = makeRegexPrefix(body);
- return new IgnoreRule(pattern, mark, body, ignoreCase, negative, regexPrefix);
- };
-
- class RuleManager {
- constructor(ignoreCase) {
- this._ignoreCase = ignoreCase;
- this._rules = [];
- }
- _add(pattern) {
- if (pattern && pattern[KEY_IGNORE]) {
- this._rules = this._rules.concat(pattern._rules._rules);
- this._added = true;
- return;
- }
- if (isString2(pattern)) {
- pattern = {
- pattern
- };
- }
- if (checkPattern(pattern.pattern)) {
- const rule = createRule(pattern, this._ignoreCase);
- this._added = true;
- this._rules.push(rule);
- }
- }
- add(pattern) {
- this._added = false;
- makeArray(isString2(pattern) ? splitPattern(pattern) : pattern).forEach(this._add, this);
- return this._added;
- }
- test(path15, checkUnignored, mode) {
- let ignored = false;
- let unignored = false;
- let matchedRule;
- this._rules.forEach((rule) => {
- const { negative } = rule;
- if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
- return;
- }
- const matched = rule[mode].test(path15);
- if (!matched) {
- return;
- }
- ignored = !negative;
- unignored = negative;
- matchedRule = negative ? UNDEFINED : rule;
- });
- const ret = {
- ignored,
- unignored
- };
- if (matchedRule) {
- ret.rule = matchedRule;
- }
- return ret;
- }
- }
- var throwError = (message, Ctor) => {
- throw new Ctor(message);
- };
- var checkPath = (path15, originalPath, doThrow) => {
- if (!isString2(path15)) {
- return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
- }
- if (!path15) {
- return doThrow(`path must not be empty`, TypeError);
- }
- if (checkPath.isNotRelative(path15)) {
- const r4 = "`path.relative()`d";
- return doThrow(`path should be a ${r4} string, but got "${originalPath}"`, RangeError);
- }
- return true;
- };
- var isNotRelative = (path15) => REGEX_TEST_INVALID_PATH.test(path15);
- checkPath.isNotRelative = isNotRelative;
- checkPath.convert = (p4) => p4;
-
- class Ignore {
- constructor({
- ignorecase = true,
- ignoreCase = ignorecase,
- allowRelativePaths = false
- } = {}) {
- define2(this, KEY_IGNORE, true);
- this._rules = new RuleManager(ignoreCase);
- this._strictPathCheck = !allowRelativePaths;
- this._initCache();
- }
- _initCache() {
- this._ignoreCache = Object.create(null);
- this._testCache = Object.create(null);
- }
- add(pattern) {
- if (this._rules.add(pattern)) {
- this._initCache();
- }
- return this;
- }
- addPattern(pattern) {
- return this.add(pattern);
- }
- _test(originalPath, cache6, checkUnignored, slices) {
- const path15 = originalPath && checkPath.convert(originalPath);
- checkPath(path15, originalPath, this._strictPathCheck ? throwError : RETURN_FALSE);
- return this._t(path15, cache6, checkUnignored, slices);
- }
- checkIgnore(path15) {
- if (!REGEX_TEST_TRAILING_SLASH.test(path15)) {
- return this.test(path15);
- }
- const slices = path15.split(SLASH).filter(Boolean);
- slices.pop();
- if (slices.length) {
- const parent = this._t(slices.join(SLASH) + SLASH, this._testCache, true, slices);
- if (parent.ignored) {
- return parent;
- }
- }
- return this._rules.test(path15, false, MODE_CHECK_IGNORE);
- }
- _t(path15, cache6, checkUnignored, slices) {
- if (path15 in cache6) {
- return cache6[path15];
- }
- if (!slices) {
- slices = path15.split(SLASH).filter(Boolean);
- }
- slices.pop();
- if (!slices.length) {
- return cache6[path15] = this._rules.test(path15, checkUnignored, MODE_IGNORE);
- }
- const parent = this._t(slices.join(SLASH) + SLASH, cache6, checkUnignored, slices);
- return cache6[path15] = parent.ignored ? parent : this._rules.test(path15, checkUnignored, MODE_IGNORE);
- }
- ignores(path15) {
- return this._test(path15, this._ignoreCache, false).ignored;
- }
- createFilter() {
- return (path15) => !this.ignores(path15);
- }
- filter(paths2) {
- return makeArray(paths2).filter(this.createFilter());
- }
- test(path15) {
- return this._test(path15, this._testCache, true);
- }
- }
- var factory2 = (options2) => new Ignore(options2);
- var isPathValid = (path15) => checkPath(path15 && checkPath.convert(path15), path15, RETURN_FALSE);
- var setupWindows = () => {
- const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
- checkPath.convert = makePosix;
- const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
- checkPath.isNotRelative = (path15) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path15) || isNotRelative(path15);
- };
- if (typeof process !== "undefined" && process.platform === "win32") {
- setupWindows();
- }
- module.exports = factory2;
- factory2.default = factory2;
- module.exports.isPathValid = isPathValid;
- define2(module.exports, Symbol.for("setupWindows"), setupWindows);
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/node/files.js
-import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync11, statSync as statSync5 } from "fs";
-import { join as join34, relative as relative3, sep as sep7 } from "path";
-function readMcpbIgnorePatterns(baseDir) {
- const mcpbIgnorePath = join34(baseDir, ".mcpbignore");
- if (!existsSync4(mcpbIgnorePath)) {
- return [];
- }
- try {
- const content = readFileSync11(mcpbIgnorePath, "utf-8");
- return content.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
- } catch (error46) {
- console.warn(`Warning: Could not read .mcpbignore file: ${error46 instanceof Error ? error46.message : "Unknown error"}`);
- return [];
- }
-}
-function buildIgnoreChecker(additionalPatterns) {
- return import_ignore.default().add(EXCLUDE_PATTERNS).add(additionalPatterns);
-}
-function shouldExclude(filePath, additionalPatterns = []) {
- return buildIgnoreChecker(additionalPatterns).ignores(filePath);
-}
-function getAllFiles(dirPath, baseDir = dirPath, fileList = {}, additionalPatterns = []) {
- const files = readdirSync2(dirPath);
- const ignoreChecker = buildIgnoreChecker(additionalPatterns);
- for (const file2 of files) {
- const filePath = join34(dirPath, file2);
- const relativePath = relative3(baseDir, filePath);
- if (ignoreChecker.ignores(relativePath)) {
- continue;
- }
- const stat11 = statSync5(filePath);
- if (stat11.isDirectory()) {
- getAllFiles(filePath, baseDir, fileList, additionalPatterns);
- } else {
- const zipPath = relativePath.split(sep7).join("/");
- fileList[zipPath] = readFileSync11(filePath);
- }
- }
- return fileList;
-}
-function getAllFilesWithCount(dirPath, baseDir = dirPath, fileList = {}, additionalPatterns = [], ignoredCount = 0) {
- const files = readdirSync2(dirPath);
- const ignoreChecker = buildIgnoreChecker(additionalPatterns);
- for (const file2 of files) {
- const filePath = join34(dirPath, file2);
- const relativePath = relative3(baseDir, filePath);
- if (ignoreChecker.ignores(relativePath)) {
- ignoredCount++;
- continue;
- }
- const stat11 = statSync5(filePath);
- if (stat11.isDirectory()) {
- const result = getAllFilesWithCount(filePath, baseDir, fileList, additionalPatterns, ignoredCount);
- ignoredCount = result.ignoredCount;
- } else {
- const zipPath = relativePath.split(sep7).join("/");
- fileList[zipPath] = {
- data: readFileSync11(filePath),
- mode: stat11.mode
- };
- }
- }
- return { files: fileList, ignoredCount };
-}
-var import_ignore, EXCLUDE_PATTERNS;
-var init_files5 = __esm(() => {
- import_ignore = __toESM(require_ignore2(), 1);
- EXCLUDE_PATTERNS = [
- ".DS_Store",
- "Thumbs.db",
- ".gitignore",
- ".git",
- ".mcpbignore",
- "*.log",
- ".env*",
- ".npm",
- ".npmrc",
- ".yarnrc",
- ".yarn",
- ".eslintrc",
- ".editorconfig",
- ".prettierrc",
- ".prettierignore",
- ".eslintignore",
- ".nycrc",
- ".babelrc",
- ".pnp.*",
- "node_modules/.cache",
- "node_modules/.bin",
- "*.map",
- ".env.local",
- ".env.*.local",
- "npm-debug.log*",
- "yarn-debug.log*",
- "yarn-error.log*",
- "package-lock.json",
- "yarn.lock",
- "*.mcpb",
- "*.d.ts",
- "*.tsbuildinfo",
- "tsconfig.json"
- ];
-});
-
-// node_modules/universalify/index.js
-var require_universalify = __commonJS((exports) => {
- exports.fromCallback = function(fn) {
- return Object.defineProperty(function(...args) {
- if (typeof args[args.length - 1] === "function")
- fn.apply(this, args);
- else {
- return new Promise((resolve11, reject) => {
- args.push((err2, res) => err2 != null ? reject(err2) : resolve11(res));
- fn.apply(this, args);
- });
- }
- }, "name", { value: fn.name });
- };
- exports.fromPromise = function(fn) {
- return Object.defineProperty(function(...args) {
- const cb = args[args.length - 1];
- if (typeof cb !== "function")
- return fn.apply(this, args);
- else {
- args.pop();
- fn.apply(this, args).then((r4) => cb(null, r4), cb);
- }
- }, "name", { value: fn.name });
- };
-});
-
-// node_modules/fs-extra/lib/fs/index.js
-var require_fs = __commonJS((exports) => {
- var u5 = require_universalify().fromCallback;
- var fs9 = require_graceful_fs();
- var api3 = [
- "access",
- "appendFile",
- "chmod",
- "chown",
- "close",
- "copyFile",
- "fchmod",
- "fchown",
- "fdatasync",
- "fstat",
- "fsync",
- "ftruncate",
- "futimes",
- "lchmod",
- "lchown",
- "link",
- "lstat",
- "mkdir",
- "mkdtemp",
- "open",
- "opendir",
- "readdir",
- "readFile",
- "readlink",
- "realpath",
- "rename",
- "rm",
- "rmdir",
- "stat",
- "symlink",
- "truncate",
- "unlink",
- "utimes",
- "writeFile"
- ].filter((key2) => {
- return typeof fs9[key2] === "function";
- });
- Object.assign(exports, fs9);
- api3.forEach((method) => {
- exports[method] = u5(fs9[method]);
- });
- exports.exists = function(filename, callback) {
- if (typeof callback === "function") {
- return fs9.exists(filename, callback);
- }
- return new Promise((resolve11) => {
- return fs9.exists(filename, resolve11);
- });
- };
- exports.read = function(fd2, buffer, offset, length, position2, callback) {
- if (typeof callback === "function") {
- return fs9.read(fd2, buffer, offset, length, position2, callback);
- }
- return new Promise((resolve11, reject) => {
- fs9.read(fd2, buffer, offset, length, position2, (err2, bytesRead, buffer2) => {
- if (err2)
- return reject(err2);
- resolve11({ bytesRead, buffer: buffer2 });
- });
- });
- };
- exports.write = function(fd2, buffer, ...args) {
- if (typeof args[args.length - 1] === "function") {
- return fs9.write(fd2, buffer, ...args);
- }
- return new Promise((resolve11, reject) => {
- fs9.write(fd2, buffer, ...args, (err2, bytesWritten, buffer2) => {
- if (err2)
- return reject(err2);
- resolve11({ bytesWritten, buffer: buffer2 });
- });
- });
- };
- if (typeof fs9.writev === "function") {
- exports.writev = function(fd2, buffers, ...args) {
- if (typeof args[args.length - 1] === "function") {
- return fs9.writev(fd2, buffers, ...args);
- }
- return new Promise((resolve11, reject) => {
- fs9.writev(fd2, buffers, ...args, (err2, bytesWritten, buffers2) => {
- if (err2)
- return reject(err2);
- resolve11({ bytesWritten, buffers: buffers2 });
- });
- });
- };
- }
- if (typeof fs9.realpath.native === "function") {
- exports.realpath.native = u5(fs9.realpath.native);
- } else {
- process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?", "Warning", "fs-extra-WARN0003");
- }
-});
-
-// node_modules/fs-extra/lib/mkdirs/utils.js
-var require_utils8 = __commonJS((exports, module) => {
- var path15 = __require("path");
- exports.checkPath = function checkPath(pth) {
- if (process.platform === "win32") {
- const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path15.parse(pth).root, ""));
- if (pathHasInvalidWinCharacters) {
- const error46 = new Error(`Path contains invalid characters: ${pth}`);
- error46.code = "EINVAL";
- throw error46;
- }
- }
- };
-});
-
-// node_modules/fs-extra/lib/mkdirs/make-dir.js
-var require_make_dir = __commonJS((exports, module) => {
- var fs9 = require_fs();
- var { checkPath } = require_utils8();
- var getMode = (options2) => {
- const defaults2 = { mode: 511 };
- if (typeof options2 === "number")
- return options2;
- return { ...defaults2, ...options2 }.mode;
- };
- exports.makeDir = async (dir, options2) => {
- checkPath(dir);
- return fs9.mkdir(dir, {
- mode: getMode(options2),
- recursive: true
- });
- };
- exports.makeDirSync = (dir, options2) => {
- checkPath(dir);
- return fs9.mkdirSync(dir, {
- mode: getMode(options2),
- recursive: true
- });
- };
-});
-
-// node_modules/fs-extra/lib/mkdirs/index.js
-var require_mkdirs = __commonJS((exports, module) => {
- var u5 = require_universalify().fromPromise;
- var { makeDir: _makeDir, makeDirSync } = require_make_dir();
- var makeDir = u5(_makeDir);
- module.exports = {
- mkdirs: makeDir,
- mkdirsSync: makeDirSync,
- mkdirp: makeDir,
- mkdirpSync: makeDirSync,
- ensureDir: makeDir,
- ensureDirSync: makeDirSync
- };
-});
-
-// node_modules/fs-extra/lib/path-exists/index.js
-var require_path_exists = __commonJS((exports, module) => {
- var u5 = require_universalify().fromPromise;
- var fs9 = require_fs();
- function pathExists2(path15) {
- return fs9.access(path15).then(() => true).catch(() => false);
- }
- module.exports = {
- pathExists: u5(pathExists2),
- pathExistsSync: fs9.existsSync
- };
-});
-
-// node_modules/fs-extra/lib/util/utimes.js
-var require_utimes = __commonJS((exports, module) => {
- var fs9 = require_graceful_fs();
- function utimesMillis(path15, atime, mtime, callback) {
- fs9.open(path15, "r+", (err2, fd2) => {
- if (err2)
- return callback(err2);
- fs9.futimes(fd2, atime, mtime, (futimesErr) => {
- fs9.close(fd2, (closeErr) => {
- if (callback)
- callback(futimesErr || closeErr);
- });
- });
- });
- }
- function utimesMillisSync(path15, atime, mtime) {
- const fd2 = fs9.openSync(path15, "r+");
- fs9.futimesSync(fd2, atime, mtime);
- return fs9.closeSync(fd2);
- }
- module.exports = {
- utimesMillis,
- utimesMillisSync
- };
-});
-
-// node_modules/fs-extra/lib/util/stat.js
-var require_stat = __commonJS((exports, module) => {
- var fs9 = require_fs();
- var path15 = __require("path");
- var util12 = __require("util");
- function getStats(src, dest, opts) {
- const statFunc = opts.dereference ? (file2) => fs9.stat(file2, { bigint: true }) : (file2) => fs9.lstat(file2, { bigint: true });
- return Promise.all([
- statFunc(src),
- statFunc(dest).catch((err2) => {
- if (err2.code === "ENOENT")
- return null;
- throw err2;
- })
- ]).then(([srcStat, destStat]) => ({ srcStat, destStat }));
- }
- function getStatsSync(src, dest, opts) {
- let destStat;
- const statFunc = opts.dereference ? (file2) => fs9.statSync(file2, { bigint: true }) : (file2) => fs9.lstatSync(file2, { bigint: true });
- const srcStat = statFunc(src);
- try {
- destStat = statFunc(dest);
- } catch (err2) {
- if (err2.code === "ENOENT")
- return { srcStat, destStat: null };
- throw err2;
- }
- return { srcStat, destStat };
- }
- function checkPaths(src, dest, funcName, opts, cb) {
- util12.callbackify(getStats)(src, dest, opts, (err2, stats) => {
- if (err2)
- return cb(err2);
- const { srcStat, destStat } = stats;
- if (destStat) {
- if (areIdentical(srcStat, destStat)) {
- const srcBaseName = path15.basename(src);
- const destBaseName = path15.basename(dest);
- if (funcName === "move" && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
- return cb(null, { srcStat, destStat, isChangingCase: true });
- }
- return cb(new Error("Source and destination must not be the same."));
- }
- if (srcStat.isDirectory() && !destStat.isDirectory()) {
- return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`));
- }
- if (!srcStat.isDirectory() && destStat.isDirectory()) {
- return cb(new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`));
- }
- }
- if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
- return cb(new Error(errMsg(src, dest, funcName)));
- }
- return cb(null, { srcStat, destStat });
- });
- }
- function checkPathsSync(src, dest, funcName, opts) {
- const { srcStat, destStat } = getStatsSync(src, dest, opts);
- if (destStat) {
- if (areIdentical(srcStat, destStat)) {
- const srcBaseName = path15.basename(src);
- const destBaseName = path15.basename(dest);
- if (funcName === "move" && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
- return { srcStat, destStat, isChangingCase: true };
- }
- throw new Error("Source and destination must not be the same.");
- }
- if (srcStat.isDirectory() && !destStat.isDirectory()) {
- throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`);
- }
- if (!srcStat.isDirectory() && destStat.isDirectory()) {
- throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`);
- }
- }
- if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
- throw new Error(errMsg(src, dest, funcName));
- }
- return { srcStat, destStat };
- }
- function checkParentPaths(src, srcStat, dest, funcName, cb) {
- const srcParent = path15.resolve(path15.dirname(src));
- const destParent = path15.resolve(path15.dirname(dest));
- if (destParent === srcParent || destParent === path15.parse(destParent).root)
- return cb();
- fs9.stat(destParent, { bigint: true }, (err2, destStat) => {
- if (err2) {
- if (err2.code === "ENOENT")
- return cb();
- return cb(err2);
- }
- if (areIdentical(srcStat, destStat)) {
- return cb(new Error(errMsg(src, dest, funcName)));
- }
- return checkParentPaths(src, srcStat, destParent, funcName, cb);
- });
- }
- function checkParentPathsSync(src, srcStat, dest, funcName) {
- const srcParent = path15.resolve(path15.dirname(src));
- const destParent = path15.resolve(path15.dirname(dest));
- if (destParent === srcParent || destParent === path15.parse(destParent).root)
- return;
- let destStat;
- try {
- destStat = fs9.statSync(destParent, { bigint: true });
- } catch (err2) {
- if (err2.code === "ENOENT")
- return;
- throw err2;
- }
- if (areIdentical(srcStat, destStat)) {
- throw new Error(errMsg(src, dest, funcName));
- }
- return checkParentPathsSync(src, srcStat, destParent, funcName);
- }
- function areIdentical(srcStat, destStat) {
- return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev;
- }
- function isSrcSubdir(src, dest) {
- const srcArr = path15.resolve(src).split(path15.sep).filter((i6) => i6);
- const destArr = path15.resolve(dest).split(path15.sep).filter((i6) => i6);
- return srcArr.reduce((acc, cur, i6) => acc && destArr[i6] === cur, true);
- }
- function errMsg(src, dest, funcName) {
- return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`;
- }
- module.exports = {
- checkPaths,
- checkPathsSync,
- checkParentPaths,
- checkParentPathsSync,
- isSrcSubdir,
- areIdentical
- };
-});
-
-// node_modules/fs-extra/lib/copy/copy.js
-var require_copy = __commonJS((exports, module) => {
- var fs9 = require_graceful_fs();
- var path15 = __require("path");
- var mkdirs = require_mkdirs().mkdirs;
- var pathExists2 = require_path_exists().pathExists;
- var utimesMillis = require_utimes().utimesMillis;
- var stat11 = require_stat();
- function copy(src, dest, opts, cb) {
- if (typeof opts === "function" && !cb) {
- cb = opts;
- opts = {};
- } else if (typeof opts === "function") {
- opts = { filter: opts };
- }
- cb = cb || function() {};
- opts = opts || {};
- opts.clobber = "clobber" in opts ? !!opts.clobber : true;
- opts.overwrite = "overwrite" in opts ? !!opts.overwrite : opts.clobber;
- if (opts.preserveTimestamps && process.arch === "ia32") {
- process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
-
-` + "\tsee https://github.com/jprichardson/node-fs-extra/issues/269", "Warning", "fs-extra-WARN0001");
- }
- stat11.checkPaths(src, dest, "copy", opts, (err2, stats) => {
- if (err2)
- return cb(err2);
- const { srcStat, destStat } = stats;
- stat11.checkParentPaths(src, srcStat, dest, "copy", (err3) => {
- if (err3)
- return cb(err3);
- if (opts.filter)
- return handleFilter(checkParentDir, destStat, src, dest, opts, cb);
- return checkParentDir(destStat, src, dest, opts, cb);
- });
- });
- }
- function checkParentDir(destStat, src, dest, opts, cb) {
- const destParent = path15.dirname(dest);
- pathExists2(destParent, (err2, dirExists) => {
- if (err2)
- return cb(err2);
- if (dirExists)
- return getStats(destStat, src, dest, opts, cb);
- mkdirs(destParent, (err3) => {
- if (err3)
- return cb(err3);
- return getStats(destStat, src, dest, opts, cb);
- });
- });
- }
- function handleFilter(onInclude, destStat, src, dest, opts, cb) {
- Promise.resolve(opts.filter(src, dest)).then((include) => {
- if (include)
- return onInclude(destStat, src, dest, opts, cb);
- return cb();
- }, (error46) => cb(error46));
- }
- function startCopy(destStat, src, dest, opts, cb) {
- if (opts.filter)
- return handleFilter(getStats, destStat, src, dest, opts, cb);
- return getStats(destStat, src, dest, opts, cb);
- }
- function getStats(destStat, src, dest, opts, cb) {
- const stat12 = opts.dereference ? fs9.stat : fs9.lstat;
- stat12(src, (err2, srcStat) => {
- if (err2)
- return cb(err2);
- if (srcStat.isDirectory())
- return onDir(srcStat, destStat, src, dest, opts, cb);
- else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice())
- return onFile(srcStat, destStat, src, dest, opts, cb);
- else if (srcStat.isSymbolicLink())
- return onLink(destStat, src, dest, opts, cb);
- else if (srcStat.isSocket())
- return cb(new Error(`Cannot copy a socket file: ${src}`));
- else if (srcStat.isFIFO())
- return cb(new Error(`Cannot copy a FIFO pipe: ${src}`));
- return cb(new Error(`Unknown file: ${src}`));
- });
- }
- function onFile(srcStat, destStat, src, dest, opts, cb) {
- if (!destStat)
- return copyFile2(srcStat, src, dest, opts, cb);
- return mayCopyFile(srcStat, src, dest, opts, cb);
- }
- function mayCopyFile(srcStat, src, dest, opts, cb) {
- if (opts.overwrite) {
- fs9.unlink(dest, (err2) => {
- if (err2)
- return cb(err2);
- return copyFile2(srcStat, src, dest, opts, cb);
- });
- } else if (opts.errorOnExist) {
- return cb(new Error(`'${dest}' already exists`));
- } else
- return cb();
- }
- function copyFile2(srcStat, src, dest, opts, cb) {
- fs9.copyFile(src, dest, (err2) => {
- if (err2)
- return cb(err2);
- if (opts.preserveTimestamps)
- return handleTimestampsAndMode(srcStat.mode, src, dest, cb);
- return setDestMode(dest, srcStat.mode, cb);
- });
- }
- function handleTimestampsAndMode(srcMode, src, dest, cb) {
- if (fileIsNotWritable(srcMode)) {
- return makeFileWritable(dest, srcMode, (err2) => {
- if (err2)
- return cb(err2);
- return setDestTimestampsAndMode(srcMode, src, dest, cb);
- });
- }
- return setDestTimestampsAndMode(srcMode, src, dest, cb);
- }
- function fileIsNotWritable(srcMode) {
- return (srcMode & 128) === 0;
- }
- function makeFileWritable(dest, srcMode, cb) {
- return setDestMode(dest, srcMode | 128, cb);
- }
- function setDestTimestampsAndMode(srcMode, src, dest, cb) {
- setDestTimestamps(src, dest, (err2) => {
- if (err2)
- return cb(err2);
- return setDestMode(dest, srcMode, cb);
- });
- }
- function setDestMode(dest, srcMode, cb) {
- return fs9.chmod(dest, srcMode, cb);
- }
- function setDestTimestamps(src, dest, cb) {
- fs9.stat(src, (err2, updatedSrcStat) => {
- if (err2)
- return cb(err2);
- return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb);
- });
- }
- function onDir(srcStat, destStat, src, dest, opts, cb) {
- if (!destStat)
- return mkDirAndCopy(srcStat.mode, src, dest, opts, cb);
- return copyDir(src, dest, opts, cb);
- }
- function mkDirAndCopy(srcMode, src, dest, opts, cb) {
- fs9.mkdir(dest, (err2) => {
- if (err2)
- return cb(err2);
- copyDir(src, dest, opts, (err3) => {
- if (err3)
- return cb(err3);
- return setDestMode(dest, srcMode, cb);
- });
- });
- }
- function copyDir(src, dest, opts, cb) {
- fs9.readdir(src, (err2, items) => {
- if (err2)
- return cb(err2);
- return copyDirItems(items, src, dest, opts, cb);
- });
- }
- function copyDirItems(items, src, dest, opts, cb) {
- const item = items.pop();
- if (!item)
- return cb();
- return copyDirItem(items, item, src, dest, opts, cb);
- }
- function copyDirItem(items, item, src, dest, opts, cb) {
- const srcItem = path15.join(src, item);
- const destItem = path15.join(dest, item);
- stat11.checkPaths(srcItem, destItem, "copy", opts, (err2, stats) => {
- if (err2)
- return cb(err2);
- const { destStat } = stats;
- startCopy(destStat, srcItem, destItem, opts, (err3) => {
- if (err3)
- return cb(err3);
- return copyDirItems(items, src, dest, opts, cb);
- });
- });
- }
- function onLink(destStat, src, dest, opts, cb) {
- fs9.readlink(src, (err2, resolvedSrc) => {
- if (err2)
- return cb(err2);
- if (opts.dereference) {
- resolvedSrc = path15.resolve(process.cwd(), resolvedSrc);
- }
- if (!destStat) {
- return fs9.symlink(resolvedSrc, dest, cb);
- } else {
- fs9.readlink(dest, (err3, resolvedDest) => {
- if (err3) {
- if (err3.code === "EINVAL" || err3.code === "UNKNOWN")
- return fs9.symlink(resolvedSrc, dest, cb);
- return cb(err3);
- }
- if (opts.dereference) {
- resolvedDest = path15.resolve(process.cwd(), resolvedDest);
- }
- if (stat11.isSrcSubdir(resolvedSrc, resolvedDest)) {
- return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`));
- }
- if (destStat.isDirectory() && stat11.isSrcSubdir(resolvedDest, resolvedSrc)) {
- return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`));
- }
- return copyLink(resolvedSrc, dest, cb);
- });
- }
- });
- }
- function copyLink(resolvedSrc, dest, cb) {
- fs9.unlink(dest, (err2) => {
- if (err2)
- return cb(err2);
- return fs9.symlink(resolvedSrc, dest, cb);
- });
- }
- module.exports = copy;
-});
-
-// node_modules/fs-extra/lib/copy/copy-sync.js
-var require_copy_sync = __commonJS((exports, module) => {
- var fs9 = require_graceful_fs();
- var path15 = __require("path");
- var mkdirsSync = require_mkdirs().mkdirsSync;
- var utimesMillisSync = require_utimes().utimesMillisSync;
- var stat11 = require_stat();
- function copySync(src, dest, opts) {
- if (typeof opts === "function") {
- opts = { filter: opts };
- }
- opts = opts || {};
- opts.clobber = "clobber" in opts ? !!opts.clobber : true;
- opts.overwrite = "overwrite" in opts ? !!opts.overwrite : opts.clobber;
- if (opts.preserveTimestamps && process.arch === "ia32") {
- process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
-
-` + "\tsee https://github.com/jprichardson/node-fs-extra/issues/269", "Warning", "fs-extra-WARN0002");
- }
- const { srcStat, destStat } = stat11.checkPathsSync(src, dest, "copy", opts);
- stat11.checkParentPathsSync(src, srcStat, dest, "copy");
- return handleFilterAndCopy(destStat, src, dest, opts);
- }
- function handleFilterAndCopy(destStat, src, dest, opts) {
- if (opts.filter && !opts.filter(src, dest))
- return;
- const destParent = path15.dirname(dest);
- if (!fs9.existsSync(destParent))
- mkdirsSync(destParent);
- return getStats(destStat, src, dest, opts);
- }
- function startCopy(destStat, src, dest, opts) {
- if (opts.filter && !opts.filter(src, dest))
- return;
- return getStats(destStat, src, dest, opts);
- }
- function getStats(destStat, src, dest, opts) {
- const statSync6 = opts.dereference ? fs9.statSync : fs9.lstatSync;
- const srcStat = statSync6(src);
- if (srcStat.isDirectory())
- return onDir(srcStat, destStat, src, dest, opts);
- else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice())
- return onFile(srcStat, destStat, src, dest, opts);
- else if (srcStat.isSymbolicLink())
- return onLink(destStat, src, dest, opts);
- else if (srcStat.isSocket())
- throw new Error(`Cannot copy a socket file: ${src}`);
- else if (srcStat.isFIFO())
- throw new Error(`Cannot copy a FIFO pipe: ${src}`);
- throw new Error(`Unknown file: ${src}`);
- }
- function onFile(srcStat, destStat, src, dest, opts) {
- if (!destStat)
- return copyFile2(srcStat, src, dest, opts);
- return mayCopyFile(srcStat, src, dest, opts);
- }
- function mayCopyFile(srcStat, src, dest, opts) {
- if (opts.overwrite) {
- fs9.unlinkSync(dest);
- return copyFile2(srcStat, src, dest, opts);
- } else if (opts.errorOnExist) {
- throw new Error(`'${dest}' already exists`);
- }
- }
- function copyFile2(srcStat, src, dest, opts) {
- fs9.copyFileSync(src, dest);
- if (opts.preserveTimestamps)
- handleTimestamps(srcStat.mode, src, dest);
- return setDestMode(dest, srcStat.mode);
- }
- function handleTimestamps(srcMode, src, dest) {
- if (fileIsNotWritable(srcMode))
- makeFileWritable(dest, srcMode);
- return setDestTimestamps(src, dest);
- }
- function fileIsNotWritable(srcMode) {
- return (srcMode & 128) === 0;
- }
- function makeFileWritable(dest, srcMode) {
- return setDestMode(dest, srcMode | 128);
- }
- function setDestMode(dest, srcMode) {
- return fs9.chmodSync(dest, srcMode);
- }
- function setDestTimestamps(src, dest) {
- const updatedSrcStat = fs9.statSync(src);
- return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime);
- }
- function onDir(srcStat, destStat, src, dest, opts) {
- if (!destStat)
- return mkDirAndCopy(srcStat.mode, src, dest, opts);
- return copyDir(src, dest, opts);
- }
- function mkDirAndCopy(srcMode, src, dest, opts) {
- fs9.mkdirSync(dest);
- copyDir(src, dest, opts);
- return setDestMode(dest, srcMode);
- }
- function copyDir(src, dest, opts) {
- fs9.readdirSync(src).forEach((item) => copyDirItem(item, src, dest, opts));
- }
- function copyDirItem(item, src, dest, opts) {
- const srcItem = path15.join(src, item);
- const destItem = path15.join(dest, item);
- const { destStat } = stat11.checkPathsSync(srcItem, destItem, "copy", opts);
- return startCopy(destStat, srcItem, destItem, opts);
- }
- function onLink(destStat, src, dest, opts) {
- let resolvedSrc = fs9.readlinkSync(src);
- if (opts.dereference) {
- resolvedSrc = path15.resolve(process.cwd(), resolvedSrc);
- }
- if (!destStat) {
- return fs9.symlinkSync(resolvedSrc, dest);
- } else {
- let resolvedDest;
- try {
- resolvedDest = fs9.readlinkSync(dest);
- } catch (err2) {
- if (err2.code === "EINVAL" || err2.code === "UNKNOWN")
- return fs9.symlinkSync(resolvedSrc, dest);
- throw err2;
- }
- if (opts.dereference) {
- resolvedDest = path15.resolve(process.cwd(), resolvedDest);
- }
- if (stat11.isSrcSubdir(resolvedSrc, resolvedDest)) {
- throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`);
- }
- if (fs9.statSync(dest).isDirectory() && stat11.isSrcSubdir(resolvedDest, resolvedSrc)) {
- throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`);
- }
- return copyLink(resolvedSrc, dest);
- }
- }
- function copyLink(resolvedSrc, dest) {
- fs9.unlinkSync(dest);
- return fs9.symlinkSync(resolvedSrc, dest);
- }
- module.exports = copySync;
-});
-
-// node_modules/fs-extra/lib/copy/index.js
-var require_copy2 = __commonJS((exports, module) => {
- var u5 = require_universalify().fromCallback;
- module.exports = {
- copy: u5(require_copy()),
- copySync: require_copy_sync()
- };
-});
-
-// node_modules/fs-extra/lib/remove/rimraf.js
-var require_rimraf = __commonJS((exports, module) => {
- var fs9 = require_graceful_fs();
- var path15 = __require("path");
- var assert3 = __require("assert");
- var isWindows2 = process.platform === "win32";
- function defaults2(options2) {
- const methods = [
- "unlink",
- "chmod",
- "stat",
- "lstat",
- "rmdir",
- "readdir"
- ];
- methods.forEach((m4) => {
- options2[m4] = options2[m4] || fs9[m4];
- m4 = m4 + "Sync";
- options2[m4] = options2[m4] || fs9[m4];
- });
- options2.maxBusyTries = options2.maxBusyTries || 3;
- }
- function rimraf(p4, options2, cb) {
- let busyTries = 0;
- if (typeof options2 === "function") {
- cb = options2;
- options2 = {};
- }
- assert3(p4, "rimraf: missing path");
- assert3.strictEqual(typeof p4, "string", "rimraf: path should be a string");
- assert3.strictEqual(typeof cb, "function", "rimraf: callback function required");
- assert3(options2, "rimraf: invalid options argument provided");
- assert3.strictEqual(typeof options2, "object", "rimraf: options should be object");
- defaults2(options2);
- rimraf_(p4, options2, function CB(er) {
- if (er) {
- if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options2.maxBusyTries) {
- busyTries++;
- const time3 = busyTries * 100;
- return setTimeout(() => rimraf_(p4, options2, CB), time3);
- }
- if (er.code === "ENOENT")
- er = null;
- }
- cb(er);
- });
- }
- function rimraf_(p4, options2, cb) {
- assert3(p4);
- assert3(options2);
- assert3(typeof cb === "function");
- options2.lstat(p4, (er, st) => {
- if (er && er.code === "ENOENT") {
- return cb(null);
- }
- if (er && er.code === "EPERM" && isWindows2) {
- return fixWinEPERM(p4, options2, er, cb);
- }
- if (st && st.isDirectory()) {
- return rmdir(p4, options2, er, cb);
- }
- options2.unlink(p4, (er2) => {
- if (er2) {
- if (er2.code === "ENOENT") {
- return cb(null);
- }
- if (er2.code === "EPERM") {
- return isWindows2 ? fixWinEPERM(p4, options2, er2, cb) : rmdir(p4, options2, er2, cb);
- }
- if (er2.code === "EISDIR") {
- return rmdir(p4, options2, er2, cb);
- }
- }
- return cb(er2);
- });
- });
- }
- function fixWinEPERM(p4, options2, er, cb) {
- assert3(p4);
- assert3(options2);
- assert3(typeof cb === "function");
- options2.chmod(p4, 438, (er2) => {
- if (er2) {
- cb(er2.code === "ENOENT" ? null : er);
- } else {
- options2.stat(p4, (er3, stats) => {
- if (er3) {
- cb(er3.code === "ENOENT" ? null : er);
- } else if (stats.isDirectory()) {
- rmdir(p4, options2, er, cb);
- } else {
- options2.unlink(p4, cb);
- }
- });
- }
- });
- }
- function fixWinEPERMSync(p4, options2, er) {
- let stats;
- assert3(p4);
- assert3(options2);
- try {
- options2.chmodSync(p4, 438);
- } catch (er2) {
- if (er2.code === "ENOENT") {
- return;
- } else {
- throw er;
- }
- }
- try {
- stats = options2.statSync(p4);
- } catch (er3) {
- if (er3.code === "ENOENT") {
- return;
- } else {
- throw er;
- }
- }
- if (stats.isDirectory()) {
- rmdirSync2(p4, options2, er);
- } else {
- options2.unlinkSync(p4);
- }
- }
- function rmdir(p4, options2, originalEr, cb) {
- assert3(p4);
- assert3(options2);
- assert3(typeof cb === "function");
- options2.rmdir(p4, (er) => {
- if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) {
- rmkids(p4, options2, cb);
- } else if (er && er.code === "ENOTDIR") {
- cb(originalEr);
- } else {
- cb(er);
- }
- });
- }
- function rmkids(p4, options2, cb) {
- assert3(p4);
- assert3(options2);
- assert3(typeof cb === "function");
- options2.readdir(p4, (er, files) => {
- if (er)
- return cb(er);
- let n5 = files.length;
- let errState;
- if (n5 === 0)
- return options2.rmdir(p4, cb);
- files.forEach((f4) => {
- rimraf(path15.join(p4, f4), options2, (er2) => {
- if (errState) {
- return;
- }
- if (er2)
- return cb(errState = er2);
- if (--n5 === 0) {
- options2.rmdir(p4, cb);
- }
- });
- });
- });
- }
- function rimrafSync(p4, options2) {
- let st;
- options2 = options2 || {};
- defaults2(options2);
- assert3(p4, "rimraf: missing path");
- assert3.strictEqual(typeof p4, "string", "rimraf: path should be a string");
- assert3(options2, "rimraf: missing options");
- assert3.strictEqual(typeof options2, "object", "rimraf: options should be object");
- try {
- st = options2.lstatSync(p4);
- } catch (er) {
- if (er.code === "ENOENT") {
- return;
- }
- if (er.code === "EPERM" && isWindows2) {
- fixWinEPERMSync(p4, options2, er);
- }
- }
- try {
- if (st && st.isDirectory()) {
- rmdirSync2(p4, options2, null);
- } else {
- options2.unlinkSync(p4);
- }
- } catch (er) {
- if (er.code === "ENOENT") {
- return;
- } else if (er.code === "EPERM") {
- return isWindows2 ? fixWinEPERMSync(p4, options2, er) : rmdirSync2(p4, options2, er);
- } else if (er.code !== "EISDIR") {
- throw er;
- }
- rmdirSync2(p4, options2, er);
- }
- }
- function rmdirSync2(p4, options2, originalEr) {
- assert3(p4);
- assert3(options2);
- try {
- options2.rmdirSync(p4);
- } catch (er) {
- if (er.code === "ENOTDIR") {
- throw originalEr;
- } else if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") {
- rmkidsSync(p4, options2);
- } else if (er.code !== "ENOENT") {
- throw er;
- }
- }
- }
- function rmkidsSync(p4, options2) {
- assert3(p4);
- assert3(options2);
- options2.readdirSync(p4).forEach((f4) => rimrafSync(path15.join(p4, f4), options2));
- if (isWindows2) {
- const startTime = Date.now();
- do {
- try {
- const ret = options2.rmdirSync(p4, options2);
- return ret;
- } catch {}
- } while (Date.now() - startTime < 500);
- } else {
- const ret = options2.rmdirSync(p4, options2);
- return ret;
- }
- }
- module.exports = rimraf;
- rimraf.sync = rimrafSync;
-});
-
-// node_modules/fs-extra/lib/remove/index.js
-var require_remove = __commonJS((exports, module) => {
- var fs9 = require_graceful_fs();
- var u5 = require_universalify().fromCallback;
- var rimraf = require_rimraf();
- function remove(path15, callback) {
- if (fs9.rm)
- return fs9.rm(path15, { recursive: true, force: true }, callback);
- rimraf(path15, callback);
- }
- function removeSync(path15) {
- if (fs9.rmSync)
- return fs9.rmSync(path15, { recursive: true, force: true });
- rimraf.sync(path15);
- }
- module.exports = {
- remove: u5(remove),
- removeSync
- };
-});
-
-// node_modules/fs-extra/lib/empty/index.js
-var require_empty = __commonJS((exports, module) => {
- var u5 = require_universalify().fromPromise;
- var fs9 = require_fs();
- var path15 = __require("path");
- var mkdir9 = require_mkdirs();
- var remove = require_remove();
- var emptyDir = u5(async function emptyDir2(dir) {
- let items;
- try {
- items = await fs9.readdir(dir);
- } catch {
- return mkdir9.mkdirs(dir);
- }
- return Promise.all(items.map((item) => remove.remove(path15.join(dir, item))));
- });
- function emptyDirSync(dir) {
- let items;
- try {
- items = fs9.readdirSync(dir);
- } catch {
- return mkdir9.mkdirsSync(dir);
- }
- items.forEach((item) => {
- item = path15.join(dir, item);
- remove.removeSync(item);
- });
- }
- module.exports = {
- emptyDirSync,
- emptydirSync: emptyDirSync,
- emptyDir,
- emptydir: emptyDir
- };
-});
-
-// node_modules/fs-extra/lib/ensure/file.js
-var require_file = __commonJS((exports, module) => {
- var u5 = require_universalify().fromCallback;
- var path15 = __require("path");
- var fs9 = require_graceful_fs();
- var mkdir9 = require_mkdirs();
- function createFile2(file2, callback) {
- function makeFile4() {
- fs9.writeFile(file2, "", (err2) => {
- if (err2)
- return callback(err2);
- callback();
- });
- }
- fs9.stat(file2, (err2, stats) => {
- if (!err2 && stats.isFile())
- return callback();
- const dir = path15.dirname(file2);
- fs9.stat(dir, (err3, stats2) => {
- if (err3) {
- if (err3.code === "ENOENT") {
- return mkdir9.mkdirs(dir, (err4) => {
- if (err4)
- return callback(err4);
- makeFile4();
- });
- }
- return callback(err3);
- }
- if (stats2.isDirectory())
- makeFile4();
- else {
- fs9.readdir(dir, (err4) => {
- if (err4)
- return callback(err4);
- });
- }
- });
- });
- }
- function createFileSync(file2) {
- let stats;
- try {
- stats = fs9.statSync(file2);
- } catch {}
- if (stats && stats.isFile())
- return;
- const dir = path15.dirname(file2);
- try {
- if (!fs9.statSync(dir).isDirectory()) {
- fs9.readdirSync(dir);
- }
- } catch (err2) {
- if (err2 && err2.code === "ENOENT")
- mkdir9.mkdirsSync(dir);
- else
- throw err2;
- }
- fs9.writeFileSync(file2, "");
- }
- module.exports = {
- createFile: u5(createFile2),
- createFileSync
- };
-});
-
-// node_modules/fs-extra/lib/ensure/link.js
-var require_link = __commonJS((exports, module) => {
- var u5 = require_universalify().fromCallback;
- var path15 = __require("path");
- var fs9 = require_graceful_fs();
- var mkdir9 = require_mkdirs();
- var pathExists2 = require_path_exists().pathExists;
- var { areIdentical } = require_stat();
- function createLink(srcpath, dstpath, callback) {
- function makeLink(srcpath2, dstpath2) {
- fs9.link(srcpath2, dstpath2, (err2) => {
- if (err2)
- return callback(err2);
- callback(null);
- });
- }
- fs9.lstat(dstpath, (_, dstStat) => {
- fs9.lstat(srcpath, (err2, srcStat) => {
- if (err2) {
- err2.message = err2.message.replace("lstat", "ensureLink");
- return callback(err2);
- }
- if (dstStat && areIdentical(srcStat, dstStat))
- return callback(null);
- const dir = path15.dirname(dstpath);
- pathExists2(dir, (err3, dirExists) => {
- if (err3)
- return callback(err3);
- if (dirExists)
- return makeLink(srcpath, dstpath);
- mkdir9.mkdirs(dir, (err4) => {
- if (err4)
- return callback(err4);
- makeLink(srcpath, dstpath);
- });
- });
- });
- });
- }
- function createLinkSync(srcpath, dstpath) {
- let dstStat;
- try {
- dstStat = fs9.lstatSync(dstpath);
- } catch {}
- try {
- const srcStat = fs9.lstatSync(srcpath);
- if (dstStat && areIdentical(srcStat, dstStat))
- return;
- } catch (err2) {
- err2.message = err2.message.replace("lstat", "ensureLink");
- throw err2;
- }
- const dir = path15.dirname(dstpath);
- const dirExists = fs9.existsSync(dir);
- if (dirExists)
- return fs9.linkSync(srcpath, dstpath);
- mkdir9.mkdirsSync(dir);
- return fs9.linkSync(srcpath, dstpath);
- }
- module.exports = {
- createLink: u5(createLink),
- createLinkSync
- };
-});
-
-// node_modules/fs-extra/lib/ensure/symlink-paths.js
-var require_symlink_paths = __commonJS((exports, module) => {
- var path15 = __require("path");
- var fs9 = require_graceful_fs();
- var pathExists2 = require_path_exists().pathExists;
- function symlinkPaths(srcpath, dstpath, callback) {
- if (path15.isAbsolute(srcpath)) {
- return fs9.lstat(srcpath, (err2) => {
- if (err2) {
- err2.message = err2.message.replace("lstat", "ensureSymlink");
- return callback(err2);
- }
- return callback(null, {
- toCwd: srcpath,
- toDst: srcpath
- });
- });
- } else {
- const dstdir = path15.dirname(dstpath);
- const relativeToDst = path15.join(dstdir, srcpath);
- return pathExists2(relativeToDst, (err2, exists) => {
- if (err2)
- return callback(err2);
- if (exists) {
- return callback(null, {
- toCwd: relativeToDst,
- toDst: srcpath
- });
- } else {
- return fs9.lstat(srcpath, (err3) => {
- if (err3) {
- err3.message = err3.message.replace("lstat", "ensureSymlink");
- return callback(err3);
- }
- return callback(null, {
- toCwd: srcpath,
- toDst: path15.relative(dstdir, srcpath)
- });
- });
- }
- });
- }
- }
- function symlinkPathsSync(srcpath, dstpath) {
- let exists;
- if (path15.isAbsolute(srcpath)) {
- exists = fs9.existsSync(srcpath);
- if (!exists)
- throw new Error("absolute srcpath does not exist");
- return {
- toCwd: srcpath,
- toDst: srcpath
- };
- } else {
- const dstdir = path15.dirname(dstpath);
- const relativeToDst = path15.join(dstdir, srcpath);
- exists = fs9.existsSync(relativeToDst);
- if (exists) {
- return {
- toCwd: relativeToDst,
- toDst: srcpath
- };
- } else {
- exists = fs9.existsSync(srcpath);
- if (!exists)
- throw new Error("relative srcpath does not exist");
- return {
- toCwd: srcpath,
- toDst: path15.relative(dstdir, srcpath)
- };
- }
- }
- }
- module.exports = {
- symlinkPaths,
- symlinkPathsSync
- };
-});
-
-// node_modules/fs-extra/lib/ensure/symlink-type.js
-var require_symlink_type = __commonJS((exports, module) => {
- var fs9 = require_graceful_fs();
- function symlinkType(srcpath, type, callback) {
- callback = typeof type === "function" ? type : callback;
- type = typeof type === "function" ? false : type;
- if (type)
- return callback(null, type);
- fs9.lstat(srcpath, (err2, stats) => {
- if (err2)
- return callback(null, "file");
- type = stats && stats.isDirectory() ? "dir" : "file";
- callback(null, type);
- });
- }
- function symlinkTypeSync(srcpath, type) {
- let stats;
- if (type)
- return type;
- try {
- stats = fs9.lstatSync(srcpath);
- } catch {
- return "file";
- }
- return stats && stats.isDirectory() ? "dir" : "file";
- }
- module.exports = {
- symlinkType,
- symlinkTypeSync
- };
-});
-
-// node_modules/fs-extra/lib/ensure/symlink.js
-var require_symlink = __commonJS((exports, module) => {
- var u5 = require_universalify().fromCallback;
- var path15 = __require("path");
- var fs9 = require_fs();
- var _mkdirs = require_mkdirs();
- var mkdirs = _mkdirs.mkdirs;
- var mkdirsSync = _mkdirs.mkdirsSync;
- var _symlinkPaths = require_symlink_paths();
- var symlinkPaths = _symlinkPaths.symlinkPaths;
- var symlinkPathsSync = _symlinkPaths.symlinkPathsSync;
- var _symlinkType = require_symlink_type();
- var symlinkType = _symlinkType.symlinkType;
- var symlinkTypeSync = _symlinkType.symlinkTypeSync;
- var pathExists2 = require_path_exists().pathExists;
- var { areIdentical } = require_stat();
- function createSymlink(srcpath, dstpath, type, callback) {
- callback = typeof type === "function" ? type : callback;
- type = typeof type === "function" ? false : type;
- fs9.lstat(dstpath, (err2, stats) => {
- if (!err2 && stats.isSymbolicLink()) {
- Promise.all([
- fs9.stat(srcpath),
- fs9.stat(dstpath)
- ]).then(([srcStat, dstStat]) => {
- if (areIdentical(srcStat, dstStat))
- return callback(null);
- _createSymlink(srcpath, dstpath, type, callback);
- });
- } else
- _createSymlink(srcpath, dstpath, type, callback);
- });
- }
- function _createSymlink(srcpath, dstpath, type, callback) {
- symlinkPaths(srcpath, dstpath, (err2, relative4) => {
- if (err2)
- return callback(err2);
- srcpath = relative4.toDst;
- symlinkType(relative4.toCwd, type, (err3, type2) => {
- if (err3)
- return callback(err3);
- const dir = path15.dirname(dstpath);
- pathExists2(dir, (err4, dirExists) => {
- if (err4)
- return callback(err4);
- if (dirExists)
- return fs9.symlink(srcpath, dstpath, type2, callback);
- mkdirs(dir, (err5) => {
- if (err5)
- return callback(err5);
- fs9.symlink(srcpath, dstpath, type2, callback);
- });
- });
- });
- });
- }
- function createSymlinkSync(srcpath, dstpath, type) {
- let stats;
- try {
- stats = fs9.lstatSync(dstpath);
- } catch {}
- if (stats && stats.isSymbolicLink()) {
- const srcStat = fs9.statSync(srcpath);
- const dstStat = fs9.statSync(dstpath);
- if (areIdentical(srcStat, dstStat))
- return;
- }
- const relative4 = symlinkPathsSync(srcpath, dstpath);
- srcpath = relative4.toDst;
- type = symlinkTypeSync(relative4.toCwd, type);
- const dir = path15.dirname(dstpath);
- const exists = fs9.existsSync(dir);
- if (exists)
- return fs9.symlinkSync(srcpath, dstpath, type);
- mkdirsSync(dir);
- return fs9.symlinkSync(srcpath, dstpath, type);
- }
- module.exports = {
- createSymlink: u5(createSymlink),
- createSymlinkSync
- };
-});
-
-// node_modules/fs-extra/lib/ensure/index.js
-var require_ensure = __commonJS((exports, module) => {
- var { createFile: createFile2, createFileSync } = require_file();
- var { createLink, createLinkSync } = require_link();
- var { createSymlink, createSymlinkSync } = require_symlink();
- module.exports = {
- createFile: createFile2,
- createFileSync,
- ensureFile: createFile2,
- ensureFileSync: createFileSync,
- createLink,
- createLinkSync,
- ensureLink: createLink,
- ensureLinkSync: createLinkSync,
- createSymlink,
- createSymlinkSync,
- ensureSymlink: createSymlink,
- ensureSymlinkSync: createSymlinkSync
- };
-});
-
-// node_modules/jsonfile/utils.js
-var require_utils9 = __commonJS((exports, module) => {
- function stringify2(obj, { EOL: EOL2 = `
-`, finalEOL = true, replacer = null, spaces } = {}) {
- const EOF = finalEOL ? EOL2 : "";
- const str = JSON.stringify(obj, replacer, spaces);
- return str.replace(/\n/g, EOL2) + EOF;
- }
- function stripBom(content) {
- if (Buffer.isBuffer(content))
- content = content.toString("utf8");
- return content.replace(/^\uFEFF/, "");
- }
- module.exports = { stringify: stringify2, stripBom };
-});
-
-// node_modules/jsonfile/index.js
-var require_jsonfile = __commonJS((exports, module) => {
- var _fs;
- try {
- _fs = require_graceful_fs();
- } catch (_) {
- _fs = __require("fs");
- }
- var universalify = require_universalify();
- var { stringify: stringify2, stripBom } = require_utils9();
- async function _readFile(file2, options2 = {}) {
- if (typeof options2 === "string") {
- options2 = { encoding: options2 };
- }
- const fs9 = options2.fs || _fs;
- const shouldThrow = "throws" in options2 ? options2.throws : true;
- let data = await universalify.fromCallback(fs9.readFile)(file2, options2);
- data = stripBom(data);
- let obj;
- try {
- obj = JSON.parse(data, options2 ? options2.reviver : null);
- } catch (err2) {
- if (shouldThrow) {
- err2.message = `${file2}: ${err2.message}`;
- throw err2;
- } else {
- return null;
- }
- }
- return obj;
- }
- var readFile13 = universalify.fromPromise(_readFile);
- function readFileSync12(file2, options2 = {}) {
- if (typeof options2 === "string") {
- options2 = { encoding: options2 };
- }
- const fs9 = options2.fs || _fs;
- const shouldThrow = "throws" in options2 ? options2.throws : true;
- try {
- let content = fs9.readFileSync(file2, options2);
- content = stripBom(content);
- return JSON.parse(content, options2.reviver);
- } catch (err2) {
- if (shouldThrow) {
- err2.message = `${file2}: ${err2.message}`;
- throw err2;
- } else {
- return null;
- }
- }
- }
- async function _writeFile(file2, obj, options2 = {}) {
- const fs9 = options2.fs || _fs;
- const str = stringify2(obj, options2);
- await universalify.fromCallback(fs9.writeFile)(file2, str, options2);
- }
- var writeFile8 = universalify.fromPromise(_writeFile);
- function writeFileSync4(file2, obj, options2 = {}) {
- const fs9 = options2.fs || _fs;
- const str = stringify2(obj, options2);
- return fs9.writeFileSync(file2, str, options2);
- }
- module.exports = {
- readFile: readFile13,
- readFileSync: readFileSync12,
- writeFile: writeFile8,
- writeFileSync: writeFileSync4
- };
-});
-
-// node_modules/fs-extra/lib/json/jsonfile.js
-var require_jsonfile2 = __commonJS((exports, module) => {
- var jsonFile = require_jsonfile();
- module.exports = {
- readJson: jsonFile.readFile,
- readJsonSync: jsonFile.readFileSync,
- writeJson: jsonFile.writeFile,
- writeJsonSync: jsonFile.writeFileSync
- };
-});
-
-// node_modules/fs-extra/lib/output-file/index.js
-var require_output_file = __commonJS((exports, module) => {
- var u5 = require_universalify().fromCallback;
- var fs9 = require_graceful_fs();
- var path15 = __require("path");
- var mkdir9 = require_mkdirs();
- var pathExists2 = require_path_exists().pathExists;
- function outputFile(file2, data, encoding, callback) {
- if (typeof encoding === "function") {
- callback = encoding;
- encoding = "utf8";
- }
- const dir = path15.dirname(file2);
- pathExists2(dir, (err2, itDoes) => {
- if (err2)
- return callback(err2);
- if (itDoes)
- return fs9.writeFile(file2, data, encoding, callback);
- mkdir9.mkdirs(dir, (err3) => {
- if (err3)
- return callback(err3);
- fs9.writeFile(file2, data, encoding, callback);
- });
- });
- }
- function outputFileSync(file2, ...args) {
- const dir = path15.dirname(file2);
- if (fs9.existsSync(dir)) {
- return fs9.writeFileSync(file2, ...args);
- }
- mkdir9.mkdirsSync(dir);
- fs9.writeFileSync(file2, ...args);
- }
- module.exports = {
- outputFile: u5(outputFile),
- outputFileSync
- };
-});
-
-// node_modules/fs-extra/lib/json/output-json.js
-var require_output_json = __commonJS((exports, module) => {
- var { stringify: stringify2 } = require_utils9();
- var { outputFile } = require_output_file();
- async function outputJson(file2, data, options2 = {}) {
- const str = stringify2(data, options2);
- await outputFile(file2, str, options2);
- }
- module.exports = outputJson;
-});
-
-// node_modules/fs-extra/lib/json/output-json-sync.js
-var require_output_json_sync = __commonJS((exports, module) => {
- var { stringify: stringify2 } = require_utils9();
- var { outputFileSync } = require_output_file();
- function outputJsonSync(file2, data, options2) {
- const str = stringify2(data, options2);
- outputFileSync(file2, str, options2);
- }
- module.exports = outputJsonSync;
-});
-
-// node_modules/fs-extra/lib/json/index.js
-var require_json = __commonJS((exports, module) => {
- var u5 = require_universalify().fromPromise;
- var jsonFile = require_jsonfile2();
- jsonFile.outputJson = u5(require_output_json());
- jsonFile.outputJsonSync = require_output_json_sync();
- jsonFile.outputJSON = jsonFile.outputJson;
- jsonFile.outputJSONSync = jsonFile.outputJsonSync;
- jsonFile.writeJSON = jsonFile.writeJson;
- jsonFile.writeJSONSync = jsonFile.writeJsonSync;
- jsonFile.readJSON = jsonFile.readJson;
- jsonFile.readJSONSync = jsonFile.readJsonSync;
- module.exports = jsonFile;
-});
-
-// node_modules/fs-extra/lib/move/move.js
-var require_move = __commonJS((exports, module) => {
- var fs9 = require_graceful_fs();
- var path15 = __require("path");
- var copy = require_copy2().copy;
- var remove = require_remove().remove;
- var mkdirp = require_mkdirs().mkdirp;
- var pathExists2 = require_path_exists().pathExists;
- var stat11 = require_stat();
- function move(src, dest, opts, cb) {
- if (typeof opts === "function") {
- cb = opts;
- opts = {};
- }
- opts = opts || {};
- const overwrite = opts.overwrite || opts.clobber || false;
- stat11.checkPaths(src, dest, "move", opts, (err2, stats) => {
- if (err2)
- return cb(err2);
- const { srcStat, isChangingCase = false } = stats;
- stat11.checkParentPaths(src, srcStat, dest, "move", (err3) => {
- if (err3)
- return cb(err3);
- if (isParentRoot(dest))
- return doRename(src, dest, overwrite, isChangingCase, cb);
- mkdirp(path15.dirname(dest), (err4) => {
- if (err4)
- return cb(err4);
- return doRename(src, dest, overwrite, isChangingCase, cb);
- });
- });
- });
- }
- function isParentRoot(dest) {
- const parent = path15.dirname(dest);
- const parsedPath = path15.parse(parent);
- return parsedPath.root === parent;
- }
- function doRename(src, dest, overwrite, isChangingCase, cb) {
- if (isChangingCase)
- return rename(src, dest, overwrite, cb);
- if (overwrite) {
- return remove(dest, (err2) => {
- if (err2)
- return cb(err2);
- return rename(src, dest, overwrite, cb);
- });
- }
- pathExists2(dest, (err2, destExists) => {
- if (err2)
- return cb(err2);
- if (destExists)
- return cb(new Error("dest already exists."));
- return rename(src, dest, overwrite, cb);
- });
- }
- function rename(src, dest, overwrite, cb) {
- fs9.rename(src, dest, (err2) => {
- if (!err2)
- return cb();
- if (err2.code !== "EXDEV")
- return cb(err2);
- return moveAcrossDevice(src, dest, overwrite, cb);
- });
- }
- function moveAcrossDevice(src, dest, overwrite, cb) {
- const opts = {
- overwrite,
- errorOnExist: true
- };
- copy(src, dest, opts, (err2) => {
- if (err2)
- return cb(err2);
- return remove(src, cb);
- });
- }
- module.exports = move;
-});
-
-// node_modules/fs-extra/lib/move/move-sync.js
-var require_move_sync = __commonJS((exports, module) => {
- var fs9 = require_graceful_fs();
- var path15 = __require("path");
- var copySync = require_copy2().copySync;
- var removeSync = require_remove().removeSync;
- var mkdirpSync = require_mkdirs().mkdirpSync;
- var stat11 = require_stat();
- function moveSync(src, dest, opts) {
- opts = opts || {};
- const overwrite = opts.overwrite || opts.clobber || false;
- const { srcStat, isChangingCase = false } = stat11.checkPathsSync(src, dest, "move", opts);
- stat11.checkParentPathsSync(src, srcStat, dest, "move");
- if (!isParentRoot(dest))
- mkdirpSync(path15.dirname(dest));
- return doRename(src, dest, overwrite, isChangingCase);
- }
- function isParentRoot(dest) {
- const parent = path15.dirname(dest);
- const parsedPath = path15.parse(parent);
- return parsedPath.root === parent;
- }
- function doRename(src, dest, overwrite, isChangingCase) {
- if (isChangingCase)
- return rename(src, dest, overwrite);
- if (overwrite) {
- removeSync(dest);
- return rename(src, dest, overwrite);
- }
- if (fs9.existsSync(dest))
- throw new Error("dest already exists.");
- return rename(src, dest, overwrite);
- }
- function rename(src, dest, overwrite) {
- try {
- fs9.renameSync(src, dest);
- } catch (err2) {
- if (err2.code !== "EXDEV")
- throw err2;
- return moveAcrossDevice(src, dest, overwrite);
- }
- }
- function moveAcrossDevice(src, dest, overwrite) {
- const opts = {
- overwrite,
- errorOnExist: true
- };
- copySync(src, dest, opts);
- return removeSync(src);
- }
- module.exports = moveSync;
-});
-
-// node_modules/fs-extra/lib/move/index.js
-var require_move2 = __commonJS((exports, module) => {
- var u5 = require_universalify().fromCallback;
- module.exports = {
- move: u5(require_move()),
- moveSync: require_move_sync()
- };
-});
-
-// node_modules/fs-extra/lib/index.js
-var require_lib2 = __commonJS((exports, module) => {
- module.exports = {
- ...require_fs(),
- ...require_copy2(),
- ...require_empty(),
- ...require_ensure(),
- ...require_json(),
- ...require_mkdirs(),
- ...require_move2(),
- ...require_output_file(),
- ...require_path_exists(),
- ...require_remove()
- };
-});
-
-// node_modules/flora-colossus/lib/depTypes.js
-var require_depTypes = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.childDepType = exports.depTypeGreater = exports.DepType = undefined;
- var DepType;
- (function(DepType2) {
- DepType2[DepType2["PROD"] = 0] = "PROD";
- DepType2[DepType2["DEV"] = 1] = "DEV";
- DepType2[DepType2["OPTIONAL"] = 2] = "OPTIONAL";
- DepType2[DepType2["DEV_OPTIONAL"] = 3] = "DEV_OPTIONAL";
- DepType2[DepType2["ROOT"] = 4] = "ROOT";
- })(DepType = exports.DepType || (exports.DepType = {}));
- var depTypeGreater = (newType, existing) => {
- switch (existing) {
- case DepType.DEV:
- switch (newType) {
- case DepType.OPTIONAL:
- case DepType.PROD:
- case DepType.ROOT:
- return true;
- case DepType.DEV:
- case DepType.DEV_OPTIONAL:
- default:
- return false;
- }
- case DepType.DEV_OPTIONAL:
- switch (newType) {
- case DepType.OPTIONAL:
- case DepType.PROD:
- case DepType.ROOT:
- case DepType.DEV:
- return true;
- case DepType.DEV_OPTIONAL:
- default:
- return false;
- }
- case DepType.OPTIONAL:
- switch (newType) {
- case DepType.PROD:
- case DepType.ROOT:
- return true;
- case DepType.OPTIONAL:
- case DepType.DEV:
- case DepType.DEV_OPTIONAL:
- default:
- return false;
- }
- case DepType.PROD:
- switch (newType) {
- case DepType.ROOT:
- return true;
- case DepType.PROD:
- case DepType.OPTIONAL:
- case DepType.DEV:
- case DepType.DEV_OPTIONAL:
- default:
- return false;
- }
- case DepType.ROOT:
- switch (newType) {
- case DepType.ROOT:
- case DepType.PROD:
- case DepType.OPTIONAL:
- case DepType.DEV:
- case DepType.DEV_OPTIONAL:
- default:
- return false;
- }
- default:
- return false;
- }
- };
- exports.depTypeGreater = depTypeGreater;
- var childDepType = (parentType, childType) => {
- if (childType === DepType.ROOT) {
- throw new Error("Something went wrong, a child dependency can't be marked as the ROOT");
- }
- switch (parentType) {
- case DepType.ROOT:
- return childType;
- case DepType.PROD:
- if (childType === DepType.OPTIONAL)
- return DepType.OPTIONAL;
- return DepType.PROD;
- case DepType.OPTIONAL:
- return DepType.OPTIONAL;
- case DepType.DEV_OPTIONAL:
- return DepType.DEV_OPTIONAL;
- case DepType.DEV:
- if (childType === DepType.OPTIONAL)
- return DepType.DEV_OPTIONAL;
- return DepType.DEV;
- }
- };
- exports.childDepType = childDepType;
-});
-
-// node_modules/flora-colossus/lib/nativeModuleTypes.js
-var require_nativeModuleTypes = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.NativeModuleType = undefined;
- var NativeModuleType;
- (function(NativeModuleType2) {
- NativeModuleType2[NativeModuleType2["NONE"] = 0] = "NONE";
- NativeModuleType2[NativeModuleType2["NODE_GYP"] = 1] = "NODE_GYP";
- NativeModuleType2[NativeModuleType2["PREBUILD"] = 2] = "PREBUILD";
- })(NativeModuleType = exports.NativeModuleType || (exports.NativeModuleType = {}));
-});
-
-// node_modules/flora-colossus/lib/Walker.js
-var require_Walker = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Walker = undefined;
- var debug2 = require_src();
- var fs9 = require_lib2();
- var path15 = __require("path");
- var depTypes_1 = require_depTypes();
- var nativeModuleTypes_1 = require_nativeModuleTypes();
- var d4 = debug2("flora-colossus");
-
- class Walker {
- constructor(modulePath) {
- this.modules = [];
- this.walkHistory = new Set;
- this.cache = null;
- if (!modulePath || typeof modulePath !== "string") {
- throw new Error("modulePath must be provided as a string");
- }
- d4(`creating walker with rootModule=${modulePath}`);
- this.rootModule = modulePath;
- }
- relativeModule(rootPath, moduleName2) {
- return path15.resolve(rootPath, "node_modules", moduleName2);
- }
- async loadPackageJSON(modulePath) {
- const pJPath = path15.resolve(modulePath, "package.json");
- if (await fs9.pathExists(pJPath)) {
- const pJ = await fs9.readJson(pJPath);
- if (!pJ.dependencies)
- pJ.dependencies = {};
- if (!pJ.devDependencies)
- pJ.devDependencies = {};
- if (!pJ.optionalDependencies)
- pJ.optionalDependencies = {};
- return pJ;
- }
- return null;
- }
- async walkDependenciesForModuleInModule(moduleName2, modulePath, depType) {
- let testPath = modulePath;
- let discoveredPath = null;
- let lastRelative = null;
- while (!discoveredPath && this.relativeModule(testPath, moduleName2) !== lastRelative) {
- lastRelative = this.relativeModule(testPath, moduleName2);
- if (await fs9.pathExists(lastRelative)) {
- discoveredPath = lastRelative;
- } else {
- if (path15.basename(path15.dirname(testPath)) !== "node_modules") {
- testPath = path15.dirname(testPath);
- }
- testPath = path15.dirname(path15.dirname(testPath));
- }
- }
- if (!discoveredPath && depType !== depTypes_1.DepType.OPTIONAL && depType !== depTypes_1.DepType.DEV_OPTIONAL) {
- throw new Error(`Failed to locate module "${moduleName2}" from "${modulePath}"
-
- This normally means that either you have deleted this package already somehow (check your ignore settings if using electron-packager). Or your module installation failed.`);
- }
- if (discoveredPath) {
- await this.walkDependenciesForModule(discoveredPath, depType);
- }
- }
- async detectNativeModuleType(modulePath, pJ) {
- if (pJ.dependencies["prebuild-install"]) {
- return nativeModuleTypes_1.NativeModuleType.PREBUILD;
- } else if (await fs9.pathExists(path15.join(modulePath, "binding.gyp"))) {
- return nativeModuleTypes_1.NativeModuleType.NODE_GYP;
- }
- return nativeModuleTypes_1.NativeModuleType.NONE;
- }
- async walkDependenciesForModule(modulePath, depType) {
- d4("walk reached:", modulePath, " Type is:", depTypes_1.DepType[depType]);
- if (this.walkHistory.has(modulePath)) {
- d4("already walked this route");
- const existingModule = this.modules.find((module2) => module2.path === modulePath);
- if ((0, depTypes_1.depTypeGreater)(depType, existingModule.depType)) {
- d4(`existing module has a type of "${existingModule.depType}", new module type would be "${depType}" therefore updating`);
- existingModule.depType = depType;
- }
- return;
- }
- const pJ = await this.loadPackageJSON(modulePath);
- if (!pJ) {
- d4("walk hit a dead end, this module is incomplete");
- return;
- }
- this.walkHistory.add(modulePath);
- this.modules.push({
- depType,
- nativeModuleType: await this.detectNativeModuleType(modulePath, pJ),
- path: modulePath,
- name: pJ.name
- });
- for (const moduleName2 in pJ.dependencies) {
- if (moduleName2 in pJ.optionalDependencies) {
- d4(`found ${moduleName2} in prod deps of ${modulePath} but it is also marked optional`);
- continue;
- }
- await this.walkDependenciesForModuleInModule(moduleName2, modulePath, (0, depTypes_1.childDepType)(depType, depTypes_1.DepType.PROD));
- }
- for (const moduleName2 in pJ.optionalDependencies) {
- await this.walkDependenciesForModuleInModule(moduleName2, modulePath, (0, depTypes_1.childDepType)(depType, depTypes_1.DepType.OPTIONAL));
- }
- if (depType === depTypes_1.DepType.ROOT) {
- d4("we're still at the beginning, walking down the dev route");
- for (const moduleName2 in pJ.devDependencies) {
- await this.walkDependenciesForModuleInModule(moduleName2, modulePath, (0, depTypes_1.childDepType)(depType, depTypes_1.DepType.DEV));
- }
- }
- }
- async walkTree() {
- d4("starting tree walk");
- if (!this.cache) {
- this.cache = new Promise(async (resolve11, reject) => {
- this.modules = [];
- try {
- await this.walkDependenciesForModule(this.rootModule, depTypes_1.DepType.ROOT);
- } catch (err2) {
- reject(err2);
- return;
- }
- resolve11(this.modules);
- });
- } else {
- d4("tree walk in progress / completed already, waiting for existing walk to complete");
- }
- return await this.cache;
- }
- getRootModule() {
- return this.rootModule;
- }
- }
- exports.Walker = Walker;
-});
-
-// node_modules/flora-colossus/lib/index.js
-var require_lib3 = __commonJS((exports) => {
- var __createBinding2 = exports && exports.__createBinding || (Object.create ? function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- var desc = Object.getOwnPropertyDescriptor(m4, k4);
- if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() {
- return m4[k4];
- } };
- }
- Object.defineProperty(o5, k22, desc);
- } : function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- });
- var __exportStar2 = exports && exports.__exportStar || function(m4, exports2) {
- for (var p4 in m4)
- if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
- __createBinding2(exports2, m4, p4);
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- __exportStar2(require_Walker(), exports);
- __exportStar2(require_depTypes(), exports);
-});
-
-// node_modules/galactus/lib/DestroyerOfModules.js
-var require_DestroyerOfModules = __commonJS((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.DestroyerOfModules = undefined;
- var fs9 = require_lib2();
- var path15 = __require("path");
- var flora_colossus_1 = require_lib3();
-
- class DestroyerOfModules {
- constructor({ rootDirectory, walker, shouldKeepModuleTest }) {
- if (rootDirectory) {
- this.walker = new flora_colossus_1.Walker(rootDirectory);
- } else if (walker) {
- this.walker = walker;
- } else {
- throw new Error("Must either provide rootDirectory or walker argument");
- }
- if (shouldKeepModuleTest) {
- this.shouldKeepFn = shouldKeepModuleTest;
- }
- }
- async destroyModule(modulePath, moduleMap) {
- const module2 = moduleMap.get(modulePath);
- if (module2) {
- const nodeModulesPath = path15.resolve(modulePath, "node_modules");
- if (!await fs9.pathExists(nodeModulesPath)) {
- return;
- }
- for (const subModuleName of await fs9.readdir(nodeModulesPath)) {
- if (subModuleName.startsWith("@")) {
- for (const subScopedModuleName of await fs9.readdir(path15.resolve(nodeModulesPath, subModuleName))) {
- await this.destroyModule(path15.resolve(nodeModulesPath, subModuleName, subScopedModuleName), moduleMap);
- }
- } else {
- await this.destroyModule(path15.resolve(nodeModulesPath, subModuleName), moduleMap);
- }
- }
- } else {
- await fs9.remove(modulePath);
- }
- }
- async collectKeptModules({ relativePaths = false }) {
- const modules = await this.walker.walkTree();
- const moduleMap = new Map;
- const rootPath = path15.resolve(this.walker.getRootModule());
- for (const module2 of modules) {
- if (this.shouldKeepModule(module2)) {
- let modulePath = module2.path;
- if (relativePaths) {
- modulePath = modulePath.replace(`${rootPath}${path15.sep}`, "");
- }
- moduleMap.set(modulePath, module2);
- }
- }
- return moduleMap;
- }
- async destroy() {
- await this.destroyModule(this.walker.getRootModule(), await this.collectKeptModules({ relativePaths: false }));
- }
- shouldKeepModule(module2) {
- const isDevDep = module2.depType === flora_colossus_1.DepType.DEV || module2.depType === flora_colossus_1.DepType.DEV_OPTIONAL;
- const shouldKeep = this.shouldKeepFn ? this.shouldKeepFn(module2, isDevDep) : !isDevDep;
- return shouldKeep;
- }
- }
- exports.DestroyerOfModules = DestroyerOfModules;
-});
-
-// node_modules/galactus/lib/index.js
-var require_lib4 = __commonJS((exports) => {
- var __createBinding2 = exports && exports.__createBinding || (Object.create ? function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- var desc = Object.getOwnPropertyDescriptor(m4, k4);
- if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() {
- return m4[k4];
- } };
- }
- Object.defineProperty(o5, k22, desc);
- } : function(o5, m4, k4, k22) {
- if (k22 === undefined)
- k22 = k4;
- o5[k22] = m4[k4];
- });
- var __exportStar2 = exports && exports.__exportStar || function(m4, exports2) {
- for (var p4 in m4)
- if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
- __createBinding2(exports2, m4, p4);
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- __exportStar2(require_DestroyerOfModules(), exports);
- __exportStar2(require_lib3(), exports);
-});
-
-// node_modules/pretty-bytes/index.js
-var require_pretty_bytes = __commonJS((exports, module) => {
- var BYTE_UNITS = [
- "B",
- "kB",
- "MB",
- "GB",
- "TB",
- "PB",
- "EB",
- "ZB",
- "YB"
- ];
- var BIBYTE_UNITS = [
- "B",
- "kiB",
- "MiB",
- "GiB",
- "TiB",
- "PiB",
- "EiB",
- "ZiB",
- "YiB"
- ];
- var BIT_UNITS = [
- "b",
- "kbit",
- "Mbit",
- "Gbit",
- "Tbit",
- "Pbit",
- "Ebit",
- "Zbit",
- "Ybit"
- ];
- var BIBIT_UNITS = [
- "b",
- "kibit",
- "Mibit",
- "Gibit",
- "Tibit",
- "Pibit",
- "Eibit",
- "Zibit",
- "Yibit"
- ];
- var toLocaleString = (number4, locale, options2) => {
- let result = number4;
- if (typeof locale === "string" || Array.isArray(locale)) {
- result = number4.toLocaleString(locale, options2);
- } else if (locale === true || options2 !== undefined) {
- result = number4.toLocaleString(undefined, options2);
- }
- return result;
- };
- module.exports = (number4, options2) => {
- if (!Number.isFinite(number4)) {
- throw new TypeError(`Expected a finite number, got ${typeof number4}: ${number4}`);
- }
- options2 = Object.assign({ bits: false, binary: false }, options2);
- const UNITS = options2.bits ? options2.binary ? BIBIT_UNITS : BIT_UNITS : options2.binary ? BIBYTE_UNITS : BYTE_UNITS;
- if (options2.signed && number4 === 0) {
- return ` 0 ${UNITS[0]}`;
- }
- const isNegative = number4 < 0;
- const prefix = isNegative ? "-" : options2.signed ? "+" : "";
- if (isNegative) {
- number4 = -number4;
- }
- let localeOptions;
- if (options2.minimumFractionDigits !== undefined) {
- localeOptions = { minimumFractionDigits: options2.minimumFractionDigits };
- }
- if (options2.maximumFractionDigits !== undefined) {
- localeOptions = Object.assign({ maximumFractionDigits: options2.maximumFractionDigits }, localeOptions);
- }
- if (number4 < 1) {
- const numberString2 = toLocaleString(number4, options2.locale, localeOptions);
- return prefix + numberString2 + " " + UNITS[0];
- }
- const exponent = Math.min(Math.floor(options2.binary ? Math.log(number4) / Math.log(1024) : Math.log10(number4) / 3), UNITS.length - 1);
- number4 /= Math.pow(options2.binary ? 1024 : 1000, exponent);
- if (!localeOptions) {
- number4 = number4.toPrecision(3);
- }
- const numberString = toLocaleString(Number(number4), options2.locale, localeOptions);
- const unit = UNITS[exponent];
- return prefix + numberString + " " + unit;
- };
-});
-
-// node_modules/node-forge/lib/forge.js
-var require_forge = __commonJS((exports, module) => {
- module.exports = {
- options: {
- usePureJavaScript: false
- }
- };
-});
-
-// node_modules/node-forge/lib/baseN.js
-var require_baseN = __commonJS((exports, module) => {
- var api3 = {};
- module.exports = api3;
- var _reverseAlphabets = {};
- api3.encode = function(input, alphabet, maxline) {
- if (typeof alphabet !== "string") {
- throw new TypeError('"alphabet" must be a string.');
- }
- if (maxline !== undefined && typeof maxline !== "number") {
- throw new TypeError('"maxline" must be a number.');
- }
- var output = "";
- if (!(input instanceof Uint8Array)) {
- output = _encodeWithByteBuffer(input, alphabet);
- } else {
- var i6 = 0;
- var base2 = alphabet.length;
- var first = alphabet.charAt(0);
- var digits = [0];
- for (i6 = 0;i6 < input.length; ++i6) {
- for (var j4 = 0, carry = input[i6];j4 < digits.length; ++j4) {
- carry += digits[j4] << 8;
- digits[j4] = carry % base2;
- carry = carry / base2 | 0;
- }
- while (carry > 0) {
- digits.push(carry % base2);
- carry = carry / base2 | 0;
- }
- }
- for (i6 = 0;input[i6] === 0 && i6 < input.length - 1; ++i6) {
- output += first;
- }
- for (i6 = digits.length - 1;i6 >= 0; --i6) {
- output += alphabet[digits[i6]];
- }
- }
- if (maxline) {
- var regex2 = new RegExp(".{1," + maxline + "}", "g");
- output = output.match(regex2).join(`\r
-`);
- }
- return output;
- };
- api3.decode = function(input, alphabet) {
- if (typeof input !== "string") {
- throw new TypeError('"input" must be a string.');
- }
- if (typeof alphabet !== "string") {
- throw new TypeError('"alphabet" must be a string.');
- }
- var table = _reverseAlphabets[alphabet];
- if (!table) {
- table = _reverseAlphabets[alphabet] = [];
- for (var i6 = 0;i6 < alphabet.length; ++i6) {
- table[alphabet.charCodeAt(i6)] = i6;
- }
- }
- input = input.replace(/\s/g, "");
- var base2 = alphabet.length;
- var first = alphabet.charAt(0);
- var bytes = [0];
- for (var i6 = 0;i6 < input.length; i6++) {
- var value = table[input.charCodeAt(i6)];
- if (value === undefined) {
- return;
- }
- for (var j4 = 0, carry = value;j4 < bytes.length; ++j4) {
- carry += bytes[j4] * base2;
- bytes[j4] = carry & 255;
- carry >>= 8;
- }
- while (carry > 0) {
- bytes.push(carry & 255);
- carry >>= 8;
- }
- }
- for (var k4 = 0;input[k4] === first && k4 < input.length - 1; ++k4) {
- bytes.push(0);
- }
- if (typeof Buffer !== "undefined") {
- return Buffer.from(bytes.reverse());
- }
- return new Uint8Array(bytes.reverse());
- };
- function _encodeWithByteBuffer(input, alphabet) {
- var i6 = 0;
- var base2 = alphabet.length;
- var first = alphabet.charAt(0);
- var digits = [0];
- for (i6 = 0;i6 < input.length(); ++i6) {
- for (var j4 = 0, carry = input.at(i6);j4 < digits.length; ++j4) {
- carry += digits[j4] << 8;
- digits[j4] = carry % base2;
- carry = carry / base2 | 0;
- }
- while (carry > 0) {
- digits.push(carry % base2);
- carry = carry / base2 | 0;
- }
- }
- var output = "";
- for (i6 = 0;input.at(i6) === 0 && i6 < input.length() - 1; ++i6) {
- output += first;
- }
- for (i6 = digits.length - 1;i6 >= 0; --i6) {
- output += alphabet[digits[i6]];
- }
- return output;
- }
-});
-
-// node_modules/node-forge/lib/util.js
-var require_util3 = __commonJS((exports, module) => {
- var forge = require_forge();
- var baseN = require_baseN();
- var util12 = module.exports = forge.util = forge.util || {};
- (function() {
- if (typeof process !== "undefined" && process.nextTick && true) {
- util12.nextTick = process.nextTick;
- if (typeof setImmediate === "function") {
- util12.setImmediate = setImmediate;
- } else {
- util12.setImmediate = util12.nextTick;
- }
- return;
- }
- if (typeof setImmediate === "function") {
- util12.setImmediate = function() {
- return setImmediate.apply(undefined, arguments);
- };
- util12.nextTick = function(callback) {
- return setImmediate(callback);
- };
- return;
- }
- util12.setImmediate = function(callback) {
- setTimeout(callback, 0);
- };
- if (typeof window !== "undefined" && typeof window.postMessage === "function") {
- let handler2 = function(event) {
- if (event.source === window && event.data === msg) {
- event.stopPropagation();
- var copy = callbacks.slice();
- callbacks.length = 0;
- copy.forEach(function(callback) {
- callback();
- });
- }
- };
- var handler = handler2;
- var msg = "forge.setImmediate";
- var callbacks = [];
- util12.setImmediate = function(callback) {
- callbacks.push(callback);
- if (callbacks.length === 1) {
- window.postMessage(msg, "*");
- }
- };
- window.addEventListener("message", handler2, true);
- }
- if (typeof MutationObserver !== "undefined") {
- var now2 = Date.now();
- var attr = true;
- var div = document.createElement("div");
- var callbacks = [];
- new MutationObserver(function() {
- var copy = callbacks.slice();
- callbacks.length = 0;
- copy.forEach(function(callback) {
- callback();
- });
- }).observe(div, { attributes: true });
- var oldSetImmediate = util12.setImmediate;
- util12.setImmediate = function(callback) {
- if (Date.now() - now2 > 15) {
- now2 = Date.now();
- oldSetImmediate(callback);
- } else {
- callbacks.push(callback);
- if (callbacks.length === 1) {
- div.setAttribute("a", attr = !attr);
- }
- }
- };
- }
- util12.nextTick = util12.setImmediate;
- })();
- util12.isNodejs = typeof process !== "undefined" && process.versions && process.versions.node;
- util12.globalScope = function() {
- if (util12.isNodejs) {
- return global;
- }
- return typeof self === "undefined" ? window : self;
- }();
- util12.isArray = Array.isArray || function(x4) {
- return Object.prototype.toString.call(x4) === "[object Array]";
- };
- util12.isArrayBuffer = function(x4) {
- return typeof ArrayBuffer !== "undefined" && x4 instanceof ArrayBuffer;
- };
- util12.isArrayBufferView = function(x4) {
- return x4 && util12.isArrayBuffer(x4.buffer) && x4.byteLength !== undefined;
- };
- function _checkBitsParam(n5) {
- if (!(n5 === 8 || n5 === 16 || n5 === 24 || n5 === 32)) {
- throw new Error("Only 8, 16, 24, or 32 bits supported: " + n5);
- }
- }
- util12.ByteBuffer = ByteStringBuffer;
- function ByteStringBuffer(b5) {
- this.data = "";
- this.read = 0;
- if (typeof b5 === "string") {
- this.data = b5;
- } else if (util12.isArrayBuffer(b5) || util12.isArrayBufferView(b5)) {
- if (typeof Buffer !== "undefined" && b5 instanceof Buffer) {
- this.data = b5.toString("binary");
- } else {
- var arr = new Uint8Array(b5);
- try {
- this.data = String.fromCharCode.apply(null, arr);
- } catch (e4) {
- for (var i6 = 0;i6 < arr.length; ++i6) {
- this.putByte(arr[i6]);
- }
- }
- }
- } else if (b5 instanceof ByteStringBuffer || typeof b5 === "object" && typeof b5.data === "string" && typeof b5.read === "number") {
- this.data = b5.data;
- this.read = b5.read;
- }
- this._constructedStringLength = 0;
- }
- util12.ByteStringBuffer = ByteStringBuffer;
- var _MAX_CONSTRUCTED_STRING_LENGTH = 4096;
- util12.ByteStringBuffer.prototype._optimizeConstructedString = function(x4) {
- this._constructedStringLength += x4;
- if (this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {
- this.data.substr(0, 1);
- this._constructedStringLength = 0;
- }
- };
- util12.ByteStringBuffer.prototype.length = function() {
- return this.data.length - this.read;
- };
- util12.ByteStringBuffer.prototype.isEmpty = function() {
- return this.length() <= 0;
- };
- util12.ByteStringBuffer.prototype.putByte = function(b5) {
- return this.putBytes(String.fromCharCode(b5));
- };
- util12.ByteStringBuffer.prototype.fillWithByte = function(b5, n5) {
- b5 = String.fromCharCode(b5);
- var d4 = this.data;
- while (n5 > 0) {
- if (n5 & 1) {
- d4 += b5;
- }
- n5 >>>= 1;
- if (n5 > 0) {
- b5 += b5;
- }
- }
- this.data = d4;
- this._optimizeConstructedString(n5);
- return this;
- };
- util12.ByteStringBuffer.prototype.putBytes = function(bytes) {
- this.data += bytes;
- this._optimizeConstructedString(bytes.length);
- return this;
- };
- util12.ByteStringBuffer.prototype.putString = function(str) {
- return this.putBytes(util12.encodeUtf8(str));
- };
- util12.ByteStringBuffer.prototype.putInt16 = function(i6) {
- return this.putBytes(String.fromCharCode(i6 >> 8 & 255) + String.fromCharCode(i6 & 255));
- };
- util12.ByteStringBuffer.prototype.putInt24 = function(i6) {
- return this.putBytes(String.fromCharCode(i6 >> 16 & 255) + String.fromCharCode(i6 >> 8 & 255) + String.fromCharCode(i6 & 255));
- };
- util12.ByteStringBuffer.prototype.putInt32 = function(i6) {
- return this.putBytes(String.fromCharCode(i6 >> 24 & 255) + String.fromCharCode(i6 >> 16 & 255) + String.fromCharCode(i6 >> 8 & 255) + String.fromCharCode(i6 & 255));
- };
- util12.ByteStringBuffer.prototype.putInt16Le = function(i6) {
- return this.putBytes(String.fromCharCode(i6 & 255) + String.fromCharCode(i6 >> 8 & 255));
- };
- util12.ByteStringBuffer.prototype.putInt24Le = function(i6) {
- return this.putBytes(String.fromCharCode(i6 & 255) + String.fromCharCode(i6 >> 8 & 255) + String.fromCharCode(i6 >> 16 & 255));
- };
- util12.ByteStringBuffer.prototype.putInt32Le = function(i6) {
- return this.putBytes(String.fromCharCode(i6 & 255) + String.fromCharCode(i6 >> 8 & 255) + String.fromCharCode(i6 >> 16 & 255) + String.fromCharCode(i6 >> 24 & 255));
- };
- util12.ByteStringBuffer.prototype.putInt = function(i6, n5) {
- _checkBitsParam(n5);
- var bytes = "";
- do {
- n5 -= 8;
- bytes += String.fromCharCode(i6 >> n5 & 255);
- } while (n5 > 0);
- return this.putBytes(bytes);
- };
- util12.ByteStringBuffer.prototype.putSignedInt = function(i6, n5) {
- if (i6 < 0) {
- i6 += 2 << n5 - 1;
- }
- return this.putInt(i6, n5);
- };
- util12.ByteStringBuffer.prototype.putBuffer = function(buffer) {
- return this.putBytes(buffer.getBytes());
- };
- util12.ByteStringBuffer.prototype.getByte = function() {
- return this.data.charCodeAt(this.read++);
- };
- util12.ByteStringBuffer.prototype.getInt16 = function() {
- var rval = this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1);
- this.read += 2;
- return rval;
- };
- util12.ByteStringBuffer.prototype.getInt24 = function() {
- var rval = this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2);
- this.read += 3;
- return rval;
- };
- util12.ByteStringBuffer.prototype.getInt32 = function() {
- var rval = this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3);
- this.read += 4;
- return rval;
- };
- util12.ByteStringBuffer.prototype.getInt16Le = function() {
- var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8;
- this.read += 2;
- return rval;
- };
- util12.ByteStringBuffer.prototype.getInt24Le = function() {
- var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16;
- this.read += 3;
- return rval;
- };
- util12.ByteStringBuffer.prototype.getInt32Le = function() {
- var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24;
- this.read += 4;
- return rval;
- };
- util12.ByteStringBuffer.prototype.getInt = function(n5) {
- _checkBitsParam(n5);
- var rval = 0;
- do {
- rval = (rval << 8) + this.data.charCodeAt(this.read++);
- n5 -= 8;
- } while (n5 > 0);
- return rval;
- };
- util12.ByteStringBuffer.prototype.getSignedInt = function(n5) {
- var x4 = this.getInt(n5);
- var max2 = 2 << n5 - 2;
- if (x4 >= max2) {
- x4 -= max2 << 1;
- }
- return x4;
- };
- util12.ByteStringBuffer.prototype.getBytes = function(count3) {
- var rval;
- if (count3) {
- count3 = Math.min(this.length(), count3);
- rval = this.data.slice(this.read, this.read + count3);
- this.read += count3;
- } else if (count3 === 0) {
- rval = "";
- } else {
- rval = this.read === 0 ? this.data : this.data.slice(this.read);
- this.clear();
- }
- return rval;
- };
- util12.ByteStringBuffer.prototype.bytes = function(count3) {
- return typeof count3 === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count3);
- };
- util12.ByteStringBuffer.prototype.at = function(i6) {
- return this.data.charCodeAt(this.read + i6);
- };
- util12.ByteStringBuffer.prototype.setAt = function(i6, b5) {
- this.data = this.data.substr(0, this.read + i6) + String.fromCharCode(b5) + this.data.substr(this.read + i6 + 1);
- return this;
- };
- util12.ByteStringBuffer.prototype.last = function() {
- return this.data.charCodeAt(this.data.length - 1);
- };
- util12.ByteStringBuffer.prototype.copy = function() {
- var c8 = util12.createBuffer(this.data);
- c8.read = this.read;
- return c8;
- };
- util12.ByteStringBuffer.prototype.compact = function() {
- if (this.read > 0) {
- this.data = this.data.slice(this.read);
- this.read = 0;
- }
- return this;
- };
- util12.ByteStringBuffer.prototype.clear = function() {
- this.data = "";
- this.read = 0;
- return this;
- };
- util12.ByteStringBuffer.prototype.truncate = function(count3) {
- var len = Math.max(0, this.length() - count3);
- this.data = this.data.substr(this.read, len);
- this.read = 0;
- return this;
- };
- util12.ByteStringBuffer.prototype.toHex = function() {
- var rval = "";
- for (var i6 = this.read;i6 < this.data.length; ++i6) {
- var b5 = this.data.charCodeAt(i6);
- if (b5 < 16) {
- rval += "0";
- }
- rval += b5.toString(16);
- }
- return rval;
- };
- util12.ByteStringBuffer.prototype.toString = function() {
- return util12.decodeUtf8(this.bytes());
- };
- function DataBuffer(b5, options2) {
- options2 = options2 || {};
- this.read = options2.readOffset || 0;
- this.growSize = options2.growSize || 1024;
- var isArrayBuffer9 = util12.isArrayBuffer(b5);
- var isArrayBufferView2 = util12.isArrayBufferView(b5);
- if (isArrayBuffer9 || isArrayBufferView2) {
- if (isArrayBuffer9) {
- this.data = new DataView(b5);
- } else {
- this.data = new DataView(b5.buffer, b5.byteOffset, b5.byteLength);
- }
- this.write = "writeOffset" in options2 ? options2.writeOffset : this.data.byteLength;
- return;
- }
- this.data = new DataView(new ArrayBuffer(0));
- this.write = 0;
- if (b5 !== null && b5 !== undefined) {
- this.putBytes(b5);
- }
- if ("writeOffset" in options2) {
- this.write = options2.writeOffset;
- }
- }
- util12.DataBuffer = DataBuffer;
- util12.DataBuffer.prototype.length = function() {
- return this.write - this.read;
- };
- util12.DataBuffer.prototype.isEmpty = function() {
- return this.length() <= 0;
- };
- util12.DataBuffer.prototype.accommodate = function(amount, growSize) {
- if (this.length() >= amount) {
- return this;
- }
- growSize = Math.max(growSize || this.growSize, amount);
- var src = new Uint8Array(this.data.buffer, this.data.byteOffset, this.data.byteLength);
- var dst = new Uint8Array(this.length() + growSize);
- dst.set(src);
- this.data = new DataView(dst.buffer);
- return this;
- };
- util12.DataBuffer.prototype.putByte = function(b5) {
- this.accommodate(1);
- this.data.setUint8(this.write++, b5);
- return this;
- };
- util12.DataBuffer.prototype.fillWithByte = function(b5, n5) {
- this.accommodate(n5);
- for (var i6 = 0;i6 < n5; ++i6) {
- this.data.setUint8(b5);
- }
- return this;
- };
- util12.DataBuffer.prototype.putBytes = function(bytes, encoding) {
- if (util12.isArrayBufferView(bytes)) {
- var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- var len = src.byteLength - src.byteOffset;
- this.accommodate(len);
- var dst = new Uint8Array(this.data.buffer, this.write);
- dst.set(src);
- this.write += len;
- return this;
- }
- if (util12.isArrayBuffer(bytes)) {
- var src = new Uint8Array(bytes);
- this.accommodate(src.byteLength);
- var dst = new Uint8Array(this.data.buffer);
- dst.set(src, this.write);
- this.write += src.byteLength;
- return this;
- }
- if (bytes instanceof util12.DataBuffer || typeof bytes === "object" && typeof bytes.read === "number" && typeof bytes.write === "number" && util12.isArrayBufferView(bytes.data)) {
- var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());
- this.accommodate(src.byteLength);
- var dst = new Uint8Array(bytes.data.byteLength, this.write);
- dst.set(src);
- this.write += src.byteLength;
- return this;
- }
- if (bytes instanceof util12.ByteStringBuffer) {
- bytes = bytes.data;
- encoding = "binary";
- }
- encoding = encoding || "binary";
- if (typeof bytes === "string") {
- var view;
- if (encoding === "hex") {
- this.accommodate(Math.ceil(bytes.length / 2));
- view = new Uint8Array(this.data.buffer, this.write);
- this.write += util12.binary.hex.decode(bytes, view, this.write);
- return this;
- }
- if (encoding === "base64") {
- this.accommodate(Math.ceil(bytes.length / 4) * 3);
- view = new Uint8Array(this.data.buffer, this.write);
- this.write += util12.binary.base64.decode(bytes, view, this.write);
- return this;
- }
- if (encoding === "utf8") {
- bytes = util12.encodeUtf8(bytes);
- encoding = "binary";
- }
- if (encoding === "binary" || encoding === "raw") {
- this.accommodate(bytes.length);
- view = new Uint8Array(this.data.buffer, this.write);
- this.write += util12.binary.raw.decode(view);
- return this;
- }
- if (encoding === "utf16") {
- this.accommodate(bytes.length * 2);
- view = new Uint16Array(this.data.buffer, this.write);
- this.write += util12.text.utf16.encode(view);
- return this;
- }
- throw new Error("Invalid encoding: " + encoding);
- }
- throw Error("Invalid parameter: " + bytes);
- };
- util12.DataBuffer.prototype.putBuffer = function(buffer) {
- this.putBytes(buffer);
- buffer.clear();
- return this;
- };
- util12.DataBuffer.prototype.putString = function(str) {
- return this.putBytes(str, "utf16");
- };
- util12.DataBuffer.prototype.putInt16 = function(i6) {
- this.accommodate(2);
- this.data.setInt16(this.write, i6);
- this.write += 2;
- return this;
- };
- util12.DataBuffer.prototype.putInt24 = function(i6) {
- this.accommodate(3);
- this.data.setInt16(this.write, i6 >> 8 & 65535);
- this.data.setInt8(this.write, i6 >> 16 & 255);
- this.write += 3;
- return this;
- };
- util12.DataBuffer.prototype.putInt32 = function(i6) {
- this.accommodate(4);
- this.data.setInt32(this.write, i6);
- this.write += 4;
- return this;
- };
- util12.DataBuffer.prototype.putInt16Le = function(i6) {
- this.accommodate(2);
- this.data.setInt16(this.write, i6, true);
- this.write += 2;
- return this;
- };
- util12.DataBuffer.prototype.putInt24Le = function(i6) {
- this.accommodate(3);
- this.data.setInt8(this.write, i6 >> 16 & 255);
- this.data.setInt16(this.write, i6 >> 8 & 65535, true);
- this.write += 3;
- return this;
- };
- util12.DataBuffer.prototype.putInt32Le = function(i6) {
- this.accommodate(4);
- this.data.setInt32(this.write, i6, true);
- this.write += 4;
- return this;
- };
- util12.DataBuffer.prototype.putInt = function(i6, n5) {
- _checkBitsParam(n5);
- this.accommodate(n5 / 8);
- do {
- n5 -= 8;
- this.data.setInt8(this.write++, i6 >> n5 & 255);
- } while (n5 > 0);
- return this;
- };
- util12.DataBuffer.prototype.putSignedInt = function(i6, n5) {
- _checkBitsParam(n5);
- this.accommodate(n5 / 8);
- if (i6 < 0) {
- i6 += 2 << n5 - 1;
- }
- return this.putInt(i6, n5);
- };
- util12.DataBuffer.prototype.getByte = function() {
- return this.data.getInt8(this.read++);
- };
- util12.DataBuffer.prototype.getInt16 = function() {
- var rval = this.data.getInt16(this.read);
- this.read += 2;
- return rval;
- };
- util12.DataBuffer.prototype.getInt24 = function() {
- var rval = this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2);
- this.read += 3;
- return rval;
- };
- util12.DataBuffer.prototype.getInt32 = function() {
- var rval = this.data.getInt32(this.read);
- this.read += 4;
- return rval;
- };
- util12.DataBuffer.prototype.getInt16Le = function() {
- var rval = this.data.getInt16(this.read, true);
- this.read += 2;
- return rval;
- };
- util12.DataBuffer.prototype.getInt24Le = function() {
- var rval = this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8;
- this.read += 3;
- return rval;
- };
- util12.DataBuffer.prototype.getInt32Le = function() {
- var rval = this.data.getInt32(this.read, true);
- this.read += 4;
- return rval;
- };
- util12.DataBuffer.prototype.getInt = function(n5) {
- _checkBitsParam(n5);
- var rval = 0;
- do {
- rval = (rval << 8) + this.data.getInt8(this.read++);
- n5 -= 8;
- } while (n5 > 0);
- return rval;
- };
- util12.DataBuffer.prototype.getSignedInt = function(n5) {
- var x4 = this.getInt(n5);
- var max2 = 2 << n5 - 2;
- if (x4 >= max2) {
- x4 -= max2 << 1;
- }
- return x4;
- };
- util12.DataBuffer.prototype.getBytes = function(count3) {
- var rval;
- if (count3) {
- count3 = Math.min(this.length(), count3);
- rval = this.data.slice(this.read, this.read + count3);
- this.read += count3;
- } else if (count3 === 0) {
- rval = "";
- } else {
- rval = this.read === 0 ? this.data : this.data.slice(this.read);
- this.clear();
- }
- return rval;
- };
- util12.DataBuffer.prototype.bytes = function(count3) {
- return typeof count3 === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count3);
- };
- util12.DataBuffer.prototype.at = function(i6) {
- return this.data.getUint8(this.read + i6);
- };
- util12.DataBuffer.prototype.setAt = function(i6, b5) {
- this.data.setUint8(i6, b5);
- return this;
- };
- util12.DataBuffer.prototype.last = function() {
- return this.data.getUint8(this.write - 1);
- };
- util12.DataBuffer.prototype.copy = function() {
- return new util12.DataBuffer(this);
- };
- util12.DataBuffer.prototype.compact = function() {
- if (this.read > 0) {
- var src = new Uint8Array(this.data.buffer, this.read);
- var dst = new Uint8Array(src.byteLength);
- dst.set(src);
- this.data = new DataView(dst);
- this.write -= this.read;
- this.read = 0;
- }
- return this;
- };
- util12.DataBuffer.prototype.clear = function() {
- this.data = new DataView(new ArrayBuffer(0));
- this.read = this.write = 0;
- return this;
- };
- util12.DataBuffer.prototype.truncate = function(count3) {
- this.write = Math.max(0, this.length() - count3);
- this.read = Math.min(this.read, this.write);
- return this;
- };
- util12.DataBuffer.prototype.toHex = function() {
- var rval = "";
- for (var i6 = this.read;i6 < this.data.byteLength; ++i6) {
- var b5 = this.data.getUint8(i6);
- if (b5 < 16) {
- rval += "0";
- }
- rval += b5.toString(16);
- }
- return rval;
- };
- util12.DataBuffer.prototype.toString = function(encoding) {
- var view = new Uint8Array(this.data, this.read, this.length());
- encoding = encoding || "utf8";
- if (encoding === "binary" || encoding === "raw") {
- return util12.binary.raw.encode(view);
- }
- if (encoding === "hex") {
- return util12.binary.hex.encode(view);
- }
- if (encoding === "base64") {
- return util12.binary.base64.encode(view);
- }
- if (encoding === "utf8") {
- return util12.text.utf8.decode(view);
- }
- if (encoding === "utf16") {
- return util12.text.utf16.decode(view);
- }
- throw new Error("Invalid encoding: " + encoding);
- };
- util12.createBuffer = function(input, encoding) {
- encoding = encoding || "raw";
- if (input !== undefined && encoding === "utf8") {
- input = util12.encodeUtf8(input);
- }
- return new util12.ByteBuffer(input);
- };
- util12.fillString = function(c8, n5) {
- var s4 = "";
- while (n5 > 0) {
- if (n5 & 1) {
- s4 += c8;
- }
- n5 >>>= 1;
- if (n5 > 0) {
- c8 += c8;
- }
- }
- return s4;
- };
- util12.xorBytes = function(s1, s22, n5) {
- var s32 = "";
- var b5 = "";
- var t4 = "";
- var i6 = 0;
- var c8 = 0;
- for (;n5 > 0; --n5, ++i6) {
- b5 = s1.charCodeAt(i6) ^ s22.charCodeAt(i6);
- if (c8 >= 10) {
- s32 += t4;
- t4 = "";
- c8 = 0;
- }
- t4 += String.fromCharCode(b5);
- ++c8;
- }
- s32 += t4;
- return s32;
- };
- util12.hexToBytes = function(hex) {
- var rval = "";
- var i6 = 0;
- if (hex.length & true) {
- i6 = 1;
- rval += String.fromCharCode(parseInt(hex[0], 16));
- }
- for (;i6 < hex.length; i6 += 2) {
- rval += String.fromCharCode(parseInt(hex.substr(i6, 2), 16));
- }
- return rval;
- };
- util12.bytesToHex = function(bytes) {
- return util12.createBuffer(bytes).toHex();
- };
- util12.int32ToBytes = function(i6) {
- return String.fromCharCode(i6 >> 24 & 255) + String.fromCharCode(i6 >> 16 & 255) + String.fromCharCode(i6 >> 8 & 255) + String.fromCharCode(i6 & 255);
- };
- var _base642 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- var _base64Idx = [
- 62,
- -1,
- -1,
- -1,
- 63,
- 52,
- 53,
- 54,
- 55,
- 56,
- 57,
- 58,
- 59,
- 60,
- 61,
- -1,
- -1,
- -1,
- 64,
- -1,
- -1,
- -1,
- 0,
- 1,
- 2,
- 3,
- 4,
- 5,
- 6,
- 7,
- 8,
- 9,
- 10,
- 11,
- 12,
- 13,
- 14,
- 15,
- 16,
- 17,
- 18,
- 19,
- 20,
- 21,
- 22,
- 23,
- 24,
- 25,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- 26,
- 27,
- 28,
- 29,
- 30,
- 31,
- 32,
- 33,
- 34,
- 35,
- 36,
- 37,
- 38,
- 39,
- 40,
- 41,
- 42,
- 43,
- 44,
- 45,
- 46,
- 47,
- 48,
- 49,
- 50,
- 51
- ];
- var _base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
- util12.encode64 = function(input, maxline) {
- var line = "";
- var output = "";
- var chr1, chr2, chr3;
- var i6 = 0;
- while (i6 < input.length) {
- chr1 = input.charCodeAt(i6++);
- chr2 = input.charCodeAt(i6++);
- chr3 = input.charCodeAt(i6++);
- line += _base642.charAt(chr1 >> 2);
- line += _base642.charAt((chr1 & 3) << 4 | chr2 >> 4);
- if (isNaN(chr2)) {
- line += "==";
- } else {
- line += _base642.charAt((chr2 & 15) << 2 | chr3 >> 6);
- line += isNaN(chr3) ? "=" : _base642.charAt(chr3 & 63);
- }
- if (maxline && line.length > maxline) {
- output += line.substr(0, maxline) + `\r
-`;
- line = line.substr(maxline);
- }
- }
- output += line;
- return output;
- };
- util12.decode64 = function(input) {
- input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
- var output = "";
- var enc1, enc2, enc3, enc4;
- var i6 = 0;
- while (i6 < input.length) {
- enc1 = _base64Idx[input.charCodeAt(i6++) - 43];
- enc2 = _base64Idx[input.charCodeAt(i6++) - 43];
- enc3 = _base64Idx[input.charCodeAt(i6++) - 43];
- enc4 = _base64Idx[input.charCodeAt(i6++) - 43];
- output += String.fromCharCode(enc1 << 2 | enc2 >> 4);
- if (enc3 !== 64) {
- output += String.fromCharCode((enc2 & 15) << 4 | enc3 >> 2);
- if (enc4 !== 64) {
- output += String.fromCharCode((enc3 & 3) << 6 | enc4);
- }
- }
- }
- return output;
- };
- util12.encodeUtf8 = function(str) {
- return unescape(encodeURIComponent(str));
- };
- util12.decodeUtf8 = function(str) {
- return decodeURIComponent(escape(str));
- };
- util12.binary = {
- raw: {},
- hex: {},
- base64: {},
- base58: {},
- baseN: {
- encode: baseN.encode,
- decode: baseN.decode
- }
- };
- util12.binary.raw.encode = function(bytes) {
- return String.fromCharCode.apply(null, bytes);
- };
- util12.binary.raw.decode = function(str, output, offset) {
- var out = output;
- if (!out) {
- out = new Uint8Array(str.length);
- }
- offset = offset || 0;
- var j4 = offset;
- for (var i6 = 0;i6 < str.length; ++i6) {
- out[j4++] = str.charCodeAt(i6);
- }
- return output ? j4 - offset : out;
- };
- util12.binary.hex.encode = util12.bytesToHex;
- util12.binary.hex.decode = function(hex, output, offset) {
- var out = output;
- if (!out) {
- out = new Uint8Array(Math.ceil(hex.length / 2));
- }
- offset = offset || 0;
- var i6 = 0, j4 = offset;
- if (hex.length & 1) {
- i6 = 1;
- out[j4++] = parseInt(hex[0], 16);
- }
- for (;i6 < hex.length; i6 += 2) {
- out[j4++] = parseInt(hex.substr(i6, 2), 16);
- }
- return output ? j4 - offset : out;
- };
- util12.binary.base64.encode = function(input, maxline) {
- var line = "";
- var output = "";
- var chr1, chr2, chr3;
- var i6 = 0;
- while (i6 < input.byteLength) {
- chr1 = input[i6++];
- chr2 = input[i6++];
- chr3 = input[i6++];
- line += _base642.charAt(chr1 >> 2);
- line += _base642.charAt((chr1 & 3) << 4 | chr2 >> 4);
- if (isNaN(chr2)) {
- line += "==";
- } else {
- line += _base642.charAt((chr2 & 15) << 2 | chr3 >> 6);
- line += isNaN(chr3) ? "=" : _base642.charAt(chr3 & 63);
- }
- if (maxline && line.length > maxline) {
- output += line.substr(0, maxline) + `\r
-`;
- line = line.substr(maxline);
- }
- }
- output += line;
- return output;
- };
- util12.binary.base64.decode = function(input, output, offset) {
- var out = output;
- if (!out) {
- out = new Uint8Array(Math.ceil(input.length / 4) * 3);
- }
- input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
- offset = offset || 0;
- var enc1, enc2, enc3, enc4;
- var i6 = 0, j4 = offset;
- while (i6 < input.length) {
- enc1 = _base64Idx[input.charCodeAt(i6++) - 43];
- enc2 = _base64Idx[input.charCodeAt(i6++) - 43];
- enc3 = _base64Idx[input.charCodeAt(i6++) - 43];
- enc4 = _base64Idx[input.charCodeAt(i6++) - 43];
- out[j4++] = enc1 << 2 | enc2 >> 4;
- if (enc3 !== 64) {
- out[j4++] = (enc2 & 15) << 4 | enc3 >> 2;
- if (enc4 !== 64) {
- out[j4++] = (enc3 & 3) << 6 | enc4;
- }
- }
- }
- return output ? j4 - offset : out.subarray(0, j4);
- };
- util12.binary.base58.encode = function(input, maxline) {
- return util12.binary.baseN.encode(input, _base58, maxline);
- };
- util12.binary.base58.decode = function(input, maxline) {
- return util12.binary.baseN.decode(input, _base58, maxline);
- };
- util12.text = {
- utf8: {},
- utf16: {}
- };
- util12.text.utf8.encode = function(str, output, offset) {
- str = util12.encodeUtf8(str);
- var out = output;
- if (!out) {
- out = new Uint8Array(str.length);
- }
- offset = offset || 0;
- var j4 = offset;
- for (var i6 = 0;i6 < str.length; ++i6) {
- out[j4++] = str.charCodeAt(i6);
- }
- return output ? j4 - offset : out;
- };
- util12.text.utf8.decode = function(bytes) {
- return util12.decodeUtf8(String.fromCharCode.apply(null, bytes));
- };
- util12.text.utf16.encode = function(str, output, offset) {
- var out = output;
- if (!out) {
- out = new Uint8Array(str.length * 2);
- }
- var view = new Uint16Array(out.buffer);
- offset = offset || 0;
- var j4 = offset;
- var k4 = offset;
- for (var i6 = 0;i6 < str.length; ++i6) {
- view[k4++] = str.charCodeAt(i6);
- j4 += 2;
- }
- return output ? j4 - offset : out;
- };
- util12.text.utf16.decode = function(bytes) {
- return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));
- };
- util12.deflate = function(api3, bytes, raw) {
- bytes = util12.decode64(api3.deflate(util12.encode64(bytes)).rval);
- if (raw) {
- var start = 2;
- var flg = bytes.charCodeAt(1);
- if (flg & 32) {
- start = 6;
- }
- bytes = bytes.substring(start, bytes.length - 4);
- }
- return bytes;
- };
- util12.inflate = function(api3, bytes, raw) {
- var rval = api3.inflate(util12.encode64(bytes)).rval;
- return rval === null ? null : util12.decode64(rval);
- };
- var _setStorageObject = function(api3, id, obj) {
- if (!api3) {
- throw new Error("WebStorage not available.");
- }
- var rval;
- if (obj === null) {
- rval = api3.removeItem(id);
- } else {
- obj = util12.encode64(JSON.stringify(obj));
- rval = api3.setItem(id, obj);
- }
- if (typeof rval !== "undefined" && rval.rval !== true) {
- var error46 = new Error(rval.error.message);
- error46.id = rval.error.id;
- error46.name = rval.error.name;
- throw error46;
- }
- };
- var _getStorageObject = function(api3, id) {
- if (!api3) {
- throw new Error("WebStorage not available.");
- }
- var rval = api3.getItem(id);
- if (api3.init) {
- if (rval.rval === null) {
- if (rval.error) {
- var error46 = new Error(rval.error.message);
- error46.id = rval.error.id;
- error46.name = rval.error.name;
- throw error46;
- }
- rval = null;
- } else {
- rval = rval.rval;
- }
- }
- if (rval !== null) {
- rval = JSON.parse(util12.decode64(rval));
- }
- return rval;
- };
- var _setItem = function(api3, id, key2, data) {
- var obj = _getStorageObject(api3, id);
- if (obj === null) {
- obj = {};
- }
- obj[key2] = data;
- _setStorageObject(api3, id, obj);
- };
- var _getItem = function(api3, id, key2) {
- var rval = _getStorageObject(api3, id);
- if (rval !== null) {
- rval = key2 in rval ? rval[key2] : null;
- }
- return rval;
- };
- var _removeItem = function(api3, id, key2) {
- var obj = _getStorageObject(api3, id);
- if (obj !== null && key2 in obj) {
- delete obj[key2];
- var empty = true;
- for (var prop in obj) {
- empty = false;
- break;
- }
- if (empty) {
- obj = null;
- }
- _setStorageObject(api3, id, obj);
- }
- };
- var _clearItems = function(api3, id) {
- _setStorageObject(api3, id, null);
- };
- var _callStorageFunction = function(func, args, location) {
- var rval = null;
- if (typeof location === "undefined") {
- location = ["web", "flash"];
- }
- var type;
- var done = false;
- var exception = null;
- for (var idx in location) {
- type = location[idx];
- try {
- if (type === "flash" || type === "both") {
- if (args[0] === null) {
- throw new Error("Flash local storage not available.");
- }
- rval = func.apply(this, args);
- done = type === "flash";
- }
- if (type === "web" || type === "both") {
- args[0] = localStorage;
- rval = func.apply(this, args);
- done = true;
- }
- } catch (ex) {
- exception = ex;
- }
- if (done) {
- break;
- }
- }
- if (!done) {
- throw exception;
- }
- return rval;
- };
- util12.setItem = function(api3, id, key2, data, location) {
- _callStorageFunction(_setItem, arguments, location);
- };
- util12.getItem = function(api3, id, key2, location) {
- return _callStorageFunction(_getItem, arguments, location);
- };
- util12.removeItem = function(api3, id, key2, location) {
- _callStorageFunction(_removeItem, arguments, location);
- };
- util12.clearItems = function(api3, id, location) {
- _callStorageFunction(_clearItems, arguments, location);
- };
- util12.isEmpty = function(obj) {
- for (var prop in obj) {
- if (obj.hasOwnProperty(prop)) {
- return false;
- }
- }
- return true;
- };
- util12.format = function(format4) {
- var re = /%./g;
- var match;
- var part;
- var argi = 0;
- var parts = [];
- var last = 0;
- while (match = re.exec(format4)) {
- part = format4.substring(last, re.lastIndex - 2);
- if (part.length > 0) {
- parts.push(part);
- }
- last = re.lastIndex;
- var code = match[0][1];
- switch (code) {
- case "s":
- case "o":
- if (argi < arguments.length) {
- parts.push(arguments[argi++ + 1]);
- } else {
- parts.push(">");
- }
- break;
- case "%":
- parts.push("%");
- break;
- default:
- parts.push("<%" + code + "?>");
- }
- }
- parts.push(format4.substring(last));
- return parts.join("");
- };
- util12.formatNumber = function(number4, decimals, dec_point, thousands_sep) {
- var n5 = number4, c8 = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
- var d4 = dec_point === undefined ? "," : dec_point;
- var t4 = thousands_sep === undefined ? "." : thousands_sep, s4 = n5 < 0 ? "-" : "";
- var i6 = parseInt(n5 = Math.abs(+n5 || 0).toFixed(c8), 10) + "";
- var j4 = i6.length > 3 ? i6.length % 3 : 0;
- return s4 + (j4 ? i6.substr(0, j4) + t4 : "") + i6.substr(j4).replace(/(\d{3})(?=\d)/g, "$1" + t4) + (c8 ? d4 + Math.abs(n5 - i6).toFixed(c8).slice(2) : "");
- };
- util12.formatSize = function(size) {
- if (size >= 1073741824) {
- size = util12.formatNumber(size / 1073741824, 2, ".", "") + " GiB";
- } else if (size >= 1048576) {
- size = util12.formatNumber(size / 1048576, 2, ".", "") + " MiB";
- } else if (size >= 1024) {
- size = util12.formatNumber(size / 1024, 0) + " KiB";
- } else {
- size = util12.formatNumber(size, 0) + " bytes";
- }
- return size;
- };
- util12.bytesFromIP = function(ip) {
- if (ip.indexOf(".") !== -1) {
- return util12.bytesFromIPv4(ip);
- }
- if (ip.indexOf(":") !== -1) {
- return util12.bytesFromIPv6(ip);
- }
- return null;
- };
- util12.bytesFromIPv4 = function(ip) {
- ip = ip.split(".");
- if (ip.length !== 4) {
- return null;
- }
- var b5 = util12.createBuffer();
- for (var i6 = 0;i6 < ip.length; ++i6) {
- var num = parseInt(ip[i6], 10);
- if (isNaN(num)) {
- return null;
- }
- b5.putByte(num);
- }
- return b5.getBytes();
- };
- util12.bytesFromIPv6 = function(ip) {
- var blanks = 0;
- ip = ip.split(":").filter(function(e4) {
- if (e4.length === 0)
- ++blanks;
- return true;
- });
- var zeros = (8 - ip.length + blanks) * 2;
- var b5 = util12.createBuffer();
- for (var i6 = 0;i6 < 8; ++i6) {
- if (!ip[i6] || ip[i6].length === 0) {
- b5.fillWithByte(0, zeros);
- zeros = 0;
- continue;
- }
- var bytes = util12.hexToBytes(ip[i6]);
- if (bytes.length < 2) {
- b5.putByte(0);
- }
- b5.putBytes(bytes);
- }
- return b5.getBytes();
- };
- util12.bytesToIP = function(bytes) {
- if (bytes.length === 4) {
- return util12.bytesToIPv4(bytes);
- }
- if (bytes.length === 16) {
- return util12.bytesToIPv6(bytes);
- }
- return null;
- };
- util12.bytesToIPv4 = function(bytes) {
- if (bytes.length !== 4) {
- return null;
- }
- var ip = [];
- for (var i6 = 0;i6 < bytes.length; ++i6) {
- ip.push(bytes.charCodeAt(i6));
- }
- return ip.join(".");
- };
- util12.bytesToIPv6 = function(bytes) {
- if (bytes.length !== 16) {
- return null;
- }
- var ip = [];
- var zeroGroups = [];
- var zeroMaxGroup = 0;
- for (var i6 = 0;i6 < bytes.length; i6 += 2) {
- var hex = util12.bytesToHex(bytes[i6] + bytes[i6 + 1]);
- while (hex[0] === "0" && hex !== "0") {
- hex = hex.substr(1);
- }
- if (hex === "0") {
- var last = zeroGroups[zeroGroups.length - 1];
- var idx = ip.length;
- if (!last || idx !== last.end + 1) {
- zeroGroups.push({ start: idx, end: idx });
- } else {
- last.end = idx;
- if (last.end - last.start > zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start) {
- zeroMaxGroup = zeroGroups.length - 1;
- }
- }
- }
- ip.push(hex);
- }
- if (zeroGroups.length > 0) {
- var group = zeroGroups[zeroMaxGroup];
- if (group.end - group.start > 0) {
- ip.splice(group.start, group.end - group.start + 1, "");
- if (group.start === 0) {
- ip.unshift("");
- }
- if (group.end === 7) {
- ip.push("");
- }
- }
- }
- return ip.join(":");
- };
- util12.estimateCores = function(options2, callback) {
- if (typeof options2 === "function") {
- callback = options2;
- options2 = {};
- }
- options2 = options2 || {};
- if ("cores" in util12 && !options2.update) {
- return callback(null, util12.cores);
- }
- if (typeof navigator !== "undefined" && "hardwareConcurrency" in navigator && navigator.hardwareConcurrency > 0) {
- util12.cores = navigator.hardwareConcurrency;
- return callback(null, util12.cores);
- }
- if (typeof Worker === "undefined") {
- util12.cores = 1;
- return callback(null, util12.cores);
- }
- if (typeof Blob === "undefined") {
- util12.cores = 2;
- return callback(null, util12.cores);
- }
- var blobUrl = URL.createObjectURL(new Blob([
- "(",
- function() {
- self.addEventListener("message", function(e4) {
- var st = Date.now();
- var et2 = st + 4;
- while (Date.now() < et2)
- ;
- self.postMessage({ st, et: et2 });
- });
- }.toString(),
- ")()"
- ], { type: "application/javascript" }));
- sample([], 5, 16);
- function sample(max2, samples, numWorkers) {
- if (samples === 0) {
- var avg = Math.floor(max2.reduce(function(avg2, x4) {
- return avg2 + x4;
- }, 0) / max2.length);
- util12.cores = Math.max(1, avg);
- URL.revokeObjectURL(blobUrl);
- return callback(null, util12.cores);
- }
- map7(numWorkers, function(err2, results) {
- max2.push(reduce(numWorkers, results));
- sample(max2, samples - 1, numWorkers);
- });
- }
- function map7(numWorkers, callback2) {
- var workers = [];
- var results = [];
- for (var i6 = 0;i6 < numWorkers; ++i6) {
- var worker = new Worker(blobUrl);
- worker.addEventListener("message", function(e4) {
- results.push(e4.data);
- if (results.length === numWorkers) {
- for (var i7 = 0;i7 < numWorkers; ++i7) {
- workers[i7].terminate();
- }
- callback2(null, results);
- }
- });
- workers.push(worker);
- }
- for (var i6 = 0;i6 < numWorkers; ++i6) {
- workers[i6].postMessage(i6);
- }
- }
- function reduce(numWorkers, results) {
- var overlaps = [];
- for (var n5 = 0;n5 < numWorkers; ++n5) {
- var r1 = results[n5];
- var overlap = overlaps[n5] = [];
- for (var i6 = 0;i6 < numWorkers; ++i6) {
- if (n5 === i6) {
- continue;
- }
- var r22 = results[i6];
- if (r1.st > r22.st && r1.st < r22.et || r22.st > r1.st && r22.st < r1.et) {
- overlap.push(i6);
- }
- }
- }
- return overlaps.reduce(function(max2, overlap2) {
- return Math.max(max2, overlap2.length);
- }, 0);
- }
- };
-});
-
-// node_modules/node-forge/lib/cipher.js
-var require_cipher = __commonJS((exports, module) => {
- var forge = require_forge();
- require_util3();
- module.exports = forge.cipher = forge.cipher || {};
- forge.cipher.algorithms = forge.cipher.algorithms || {};
- forge.cipher.createCipher = function(algorithm, key2) {
- var api3 = algorithm;
- if (typeof api3 === "string") {
- api3 = forge.cipher.getAlgorithm(api3);
- if (api3) {
- api3 = api3();
- }
- }
- if (!api3) {
- throw new Error("Unsupported algorithm: " + algorithm);
- }
- return new forge.cipher.BlockCipher({
- algorithm: api3,
- key: key2,
- decrypt: false
- });
- };
- forge.cipher.createDecipher = function(algorithm, key2) {
- var api3 = algorithm;
- if (typeof api3 === "string") {
- api3 = forge.cipher.getAlgorithm(api3);
- if (api3) {
- api3 = api3();
- }
- }
- if (!api3) {
- throw new Error("Unsupported algorithm: " + algorithm);
- }
- return new forge.cipher.BlockCipher({
- algorithm: api3,
- key: key2,
- decrypt: true
- });
- };
- forge.cipher.registerAlgorithm = function(name3, algorithm) {
- name3 = name3.toUpperCase();
- forge.cipher.algorithms[name3] = algorithm;
- };
- forge.cipher.getAlgorithm = function(name3) {
- name3 = name3.toUpperCase();
- if (name3 in forge.cipher.algorithms) {
- return forge.cipher.algorithms[name3];
- }
- return null;
- };
- var BlockCipher = forge.cipher.BlockCipher = function(options2) {
- this.algorithm = options2.algorithm;
- this.mode = this.algorithm.mode;
- this.blockSize = this.mode.blockSize;
- this._finish = false;
- this._input = null;
- this.output = null;
- this._op = options2.decrypt ? this.mode.decrypt : this.mode.encrypt;
- this._decrypt = options2.decrypt;
- this.algorithm.initialize(options2);
- };
- BlockCipher.prototype.start = function(options2) {
- options2 = options2 || {};
- var opts = {};
- for (var key2 in options2) {
- opts[key2] = options2[key2];
- }
- opts.decrypt = this._decrypt;
- this._finish = false;
- this._input = forge.util.createBuffer();
- this.output = options2.output || forge.util.createBuffer();
- this.mode.start(opts);
- };
- BlockCipher.prototype.update = function(input) {
- if (input) {
- this._input.putBuffer(input);
- }
- while (!this._op.call(this.mode, this._input, this.output, this._finish) && !this._finish) {}
- this._input.compact();
- };
- BlockCipher.prototype.finish = function(pad) {
- if (pad && (this.mode.name === "ECB" || this.mode.name === "CBC")) {
- this.mode.pad = function(input) {
- return pad(this.blockSize, input, false);
- };
- this.mode.unpad = function(output) {
- return pad(this.blockSize, output, true);
- };
- }
- var options2 = {};
- options2.decrypt = this._decrypt;
- options2.overflow = this._input.length() % this.blockSize;
- if (!this._decrypt && this.mode.pad) {
- if (!this.mode.pad(this._input, options2)) {
- return false;
- }
- }
- this._finish = true;
- this.update();
- if (this._decrypt && this.mode.unpad) {
- if (!this.mode.unpad(this.output, options2)) {
- return false;
- }
- }
- if (this.mode.afterFinish) {
- if (!this.mode.afterFinish(this.output, options2)) {
- return false;
- }
- }
- return true;
- };
-});
-
-// node_modules/node-forge/lib/cipherModes.js
-var require_cipherModes = __commonJS((exports, module) => {
- var forge = require_forge();
- require_util3();
- forge.cipher = forge.cipher || {};
- var modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};
- modes.ecb = function(options2) {
- options2 = options2 || {};
- this.name = "ECB";
- this.cipher = options2.cipher;
- this.blockSize = options2.blockSize || 16;
- this._ints = this.blockSize / 4;
- this._inBlock = new Array(this._ints);
- this._outBlock = new Array(this._ints);
- };
- modes.ecb.prototype.start = function(options2) {};
- modes.ecb.prototype.encrypt = function(input, output, finish) {
- if (input.length() < this.blockSize && !(finish && input.length() > 0)) {
- return true;
- }
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._inBlock[i6] = input.getInt32();
- }
- this.cipher.encrypt(this._inBlock, this._outBlock);
- for (var i6 = 0;i6 < this._ints; ++i6) {
- output.putInt32(this._outBlock[i6]);
- }
- };
- modes.ecb.prototype.decrypt = function(input, output, finish) {
- if (input.length() < this.blockSize && !(finish && input.length() > 0)) {
- return true;
- }
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._inBlock[i6] = input.getInt32();
- }
- this.cipher.decrypt(this._inBlock, this._outBlock);
- for (var i6 = 0;i6 < this._ints; ++i6) {
- output.putInt32(this._outBlock[i6]);
- }
- };
- modes.ecb.prototype.pad = function(input, options2) {
- var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length();
- input.fillWithByte(padding, padding);
- return true;
- };
- modes.ecb.prototype.unpad = function(output, options2) {
- if (options2.overflow > 0) {
- return false;
- }
- var len = output.length();
- var count3 = output.at(len - 1);
- if (count3 > this.blockSize << 2) {
- return false;
- }
- output.truncate(count3);
- return true;
- };
- modes.cbc = function(options2) {
- options2 = options2 || {};
- this.name = "CBC";
- this.cipher = options2.cipher;
- this.blockSize = options2.blockSize || 16;
- this._ints = this.blockSize / 4;
- this._inBlock = new Array(this._ints);
- this._outBlock = new Array(this._ints);
- };
- modes.cbc.prototype.start = function(options2) {
- if (options2.iv === null) {
- if (!this._prev) {
- throw new Error("Invalid IV parameter.");
- }
- this._iv = this._prev.slice(0);
- } else if (!("iv" in options2)) {
- throw new Error("Invalid IV parameter.");
- } else {
- this._iv = transformIV(options2.iv, this.blockSize);
- this._prev = this._iv.slice(0);
- }
- };
- modes.cbc.prototype.encrypt = function(input, output, finish) {
- if (input.length() < this.blockSize && !(finish && input.length() > 0)) {
- return true;
- }
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._inBlock[i6] = this._prev[i6] ^ input.getInt32();
- }
- this.cipher.encrypt(this._inBlock, this._outBlock);
- for (var i6 = 0;i6 < this._ints; ++i6) {
- output.putInt32(this._outBlock[i6]);
- }
- this._prev = this._outBlock;
- };
- modes.cbc.prototype.decrypt = function(input, output, finish) {
- if (input.length() < this.blockSize && !(finish && input.length() > 0)) {
- return true;
- }
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._inBlock[i6] = input.getInt32();
- }
- this.cipher.decrypt(this._inBlock, this._outBlock);
- for (var i6 = 0;i6 < this._ints; ++i6) {
- output.putInt32(this._prev[i6] ^ this._outBlock[i6]);
- }
- this._prev = this._inBlock.slice(0);
- };
- modes.cbc.prototype.pad = function(input, options2) {
- var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length();
- input.fillWithByte(padding, padding);
- return true;
- };
- modes.cbc.prototype.unpad = function(output, options2) {
- if (options2.overflow > 0) {
- return false;
- }
- var len = output.length();
- var count3 = output.at(len - 1);
- if (count3 > this.blockSize << 2) {
- return false;
- }
- output.truncate(count3);
- return true;
- };
- modes.cfb = function(options2) {
- options2 = options2 || {};
- this.name = "CFB";
- this.cipher = options2.cipher;
- this.blockSize = options2.blockSize || 16;
- this._ints = this.blockSize / 4;
- this._inBlock = null;
- this._outBlock = new Array(this._ints);
- this._partialBlock = new Array(this._ints);
- this._partialOutput = forge.util.createBuffer();
- this._partialBytes = 0;
- };
- modes.cfb.prototype.start = function(options2) {
- if (!("iv" in options2)) {
- throw new Error("Invalid IV parameter.");
- }
- this._iv = transformIV(options2.iv, this.blockSize);
- this._inBlock = this._iv.slice(0);
- this._partialBytes = 0;
- };
- modes.cfb.prototype.encrypt = function(input, output, finish) {
- var inputLength = input.length();
- if (inputLength === 0) {
- return true;
- }
- this.cipher.encrypt(this._inBlock, this._outBlock);
- if (this._partialBytes === 0 && inputLength >= this.blockSize) {
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._inBlock[i6] = input.getInt32() ^ this._outBlock[i6];
- output.putInt32(this._inBlock[i6]);
- }
- return;
- }
- var partialBytes = (this.blockSize - inputLength) % this.blockSize;
- if (partialBytes > 0) {
- partialBytes = this.blockSize - partialBytes;
- }
- this._partialOutput.clear();
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._partialBlock[i6] = input.getInt32() ^ this._outBlock[i6];
- this._partialOutput.putInt32(this._partialBlock[i6]);
- }
- if (partialBytes > 0) {
- input.read -= this.blockSize;
- } else {
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._inBlock[i6] = this._partialBlock[i6];
- }
- }
- if (this._partialBytes > 0) {
- this._partialOutput.getBytes(this._partialBytes);
- }
- if (partialBytes > 0 && !finish) {
- output.putBytes(this._partialOutput.getBytes(partialBytes - this._partialBytes));
- this._partialBytes = partialBytes;
- return true;
- }
- output.putBytes(this._partialOutput.getBytes(inputLength - this._partialBytes));
- this._partialBytes = 0;
- };
- modes.cfb.prototype.decrypt = function(input, output, finish) {
- var inputLength = input.length();
- if (inputLength === 0) {
- return true;
- }
- this.cipher.encrypt(this._inBlock, this._outBlock);
- if (this._partialBytes === 0 && inputLength >= this.blockSize) {
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._inBlock[i6] = input.getInt32();
- output.putInt32(this._inBlock[i6] ^ this._outBlock[i6]);
- }
- return;
- }
- var partialBytes = (this.blockSize - inputLength) % this.blockSize;
- if (partialBytes > 0) {
- partialBytes = this.blockSize - partialBytes;
- }
- this._partialOutput.clear();
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._partialBlock[i6] = input.getInt32();
- this._partialOutput.putInt32(this._partialBlock[i6] ^ this._outBlock[i6]);
- }
- if (partialBytes > 0) {
- input.read -= this.blockSize;
- } else {
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._inBlock[i6] = this._partialBlock[i6];
- }
- }
- if (this._partialBytes > 0) {
- this._partialOutput.getBytes(this._partialBytes);
- }
- if (partialBytes > 0 && !finish) {
- output.putBytes(this._partialOutput.getBytes(partialBytes - this._partialBytes));
- this._partialBytes = partialBytes;
- return true;
- }
- output.putBytes(this._partialOutput.getBytes(inputLength - this._partialBytes));
- this._partialBytes = 0;
- };
- modes.ofb = function(options2) {
- options2 = options2 || {};
- this.name = "OFB";
- this.cipher = options2.cipher;
- this.blockSize = options2.blockSize || 16;
- this._ints = this.blockSize / 4;
- this._inBlock = null;
- this._outBlock = new Array(this._ints);
- this._partialOutput = forge.util.createBuffer();
- this._partialBytes = 0;
- };
- modes.ofb.prototype.start = function(options2) {
- if (!("iv" in options2)) {
- throw new Error("Invalid IV parameter.");
- }
- this._iv = transformIV(options2.iv, this.blockSize);
- this._inBlock = this._iv.slice(0);
- this._partialBytes = 0;
- };
- modes.ofb.prototype.encrypt = function(input, output, finish) {
- var inputLength = input.length();
- if (input.length() === 0) {
- return true;
- }
- this.cipher.encrypt(this._inBlock, this._outBlock);
- if (this._partialBytes === 0 && inputLength >= this.blockSize) {
- for (var i6 = 0;i6 < this._ints; ++i6) {
- output.putInt32(input.getInt32() ^ this._outBlock[i6]);
- this._inBlock[i6] = this._outBlock[i6];
- }
- return;
- }
- var partialBytes = (this.blockSize - inputLength) % this.blockSize;
- if (partialBytes > 0) {
- partialBytes = this.blockSize - partialBytes;
- }
- this._partialOutput.clear();
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i6]);
- }
- if (partialBytes > 0) {
- input.read -= this.blockSize;
- } else {
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._inBlock[i6] = this._outBlock[i6];
- }
- }
- if (this._partialBytes > 0) {
- this._partialOutput.getBytes(this._partialBytes);
- }
- if (partialBytes > 0 && !finish) {
- output.putBytes(this._partialOutput.getBytes(partialBytes - this._partialBytes));
- this._partialBytes = partialBytes;
- return true;
- }
- output.putBytes(this._partialOutput.getBytes(inputLength - this._partialBytes));
- this._partialBytes = 0;
- };
- modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;
- modes.ctr = function(options2) {
- options2 = options2 || {};
- this.name = "CTR";
- this.cipher = options2.cipher;
- this.blockSize = options2.blockSize || 16;
- this._ints = this.blockSize / 4;
- this._inBlock = null;
- this._outBlock = new Array(this._ints);
- this._partialOutput = forge.util.createBuffer();
- this._partialBytes = 0;
- };
- modes.ctr.prototype.start = function(options2) {
- if (!("iv" in options2)) {
- throw new Error("Invalid IV parameter.");
- }
- this._iv = transformIV(options2.iv, this.blockSize);
- this._inBlock = this._iv.slice(0);
- this._partialBytes = 0;
- };
- modes.ctr.prototype.encrypt = function(input, output, finish) {
- var inputLength = input.length();
- if (inputLength === 0) {
- return true;
- }
- this.cipher.encrypt(this._inBlock, this._outBlock);
- if (this._partialBytes === 0 && inputLength >= this.blockSize) {
- for (var i6 = 0;i6 < this._ints; ++i6) {
- output.putInt32(input.getInt32() ^ this._outBlock[i6]);
- }
- } else {
- var partialBytes = (this.blockSize - inputLength) % this.blockSize;
- if (partialBytes > 0) {
- partialBytes = this.blockSize - partialBytes;
- }
- this._partialOutput.clear();
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i6]);
- }
- if (partialBytes > 0) {
- input.read -= this.blockSize;
- }
- if (this._partialBytes > 0) {
- this._partialOutput.getBytes(this._partialBytes);
- }
- if (partialBytes > 0 && !finish) {
- output.putBytes(this._partialOutput.getBytes(partialBytes - this._partialBytes));
- this._partialBytes = partialBytes;
- return true;
- }
- output.putBytes(this._partialOutput.getBytes(inputLength - this._partialBytes));
- this._partialBytes = 0;
- }
- inc32(this._inBlock);
- };
- modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;
- modes.gcm = function(options2) {
- options2 = options2 || {};
- this.name = "GCM";
- this.cipher = options2.cipher;
- this.blockSize = options2.blockSize || 16;
- this._ints = this.blockSize / 4;
- this._inBlock = new Array(this._ints);
- this._outBlock = new Array(this._ints);
- this._partialOutput = forge.util.createBuffer();
- this._partialBytes = 0;
- this._R = 3774873600;
- };
- modes.gcm.prototype.start = function(options2) {
- if (!("iv" in options2)) {
- throw new Error("Invalid IV parameter.");
- }
- var iv = forge.util.createBuffer(options2.iv);
- this._cipherLength = 0;
- var additionalData;
- if ("additionalData" in options2) {
- additionalData = forge.util.createBuffer(options2.additionalData);
- } else {
- additionalData = forge.util.createBuffer();
- }
- if ("tagLength" in options2) {
- this._tagLength = options2.tagLength;
- } else {
- this._tagLength = 128;
- }
- this._tag = null;
- if (options2.decrypt) {
- this._tag = forge.util.createBuffer(options2.tag).getBytes();
- if (this._tag.length !== this._tagLength / 8) {
- throw new Error("Authentication tag does not match tag length.");
- }
- }
- this._hashBlock = new Array(this._ints);
- this.tag = null;
- this._hashSubkey = new Array(this._ints);
- this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);
- this.componentBits = 4;
- this._m = this.generateHashTable(this._hashSubkey, this.componentBits);
- var ivLength = iv.length();
- if (ivLength === 12) {
- this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];
- } else {
- this._j0 = [0, 0, 0, 0];
- while (iv.length() > 0) {
- this._j0 = this.ghash(this._hashSubkey, this._j0, [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);
- }
- this._j0 = this.ghash(this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));
- }
- this._inBlock = this._j0.slice(0);
- inc32(this._inBlock);
- this._partialBytes = 0;
- additionalData = forge.util.createBuffer(additionalData);
- this._aDataLength = from64To32(additionalData.length() * 8);
- var overflow = additionalData.length() % this.blockSize;
- if (overflow) {
- additionalData.fillWithByte(0, this.blockSize - overflow);
- }
- this._s = [0, 0, 0, 0];
- while (additionalData.length() > 0) {
- this._s = this.ghash(this._hashSubkey, this._s, [
- additionalData.getInt32(),
- additionalData.getInt32(),
- additionalData.getInt32(),
- additionalData.getInt32()
- ]);
- }
- };
- modes.gcm.prototype.encrypt = function(input, output, finish) {
- var inputLength = input.length();
- if (inputLength === 0) {
- return true;
- }
- this.cipher.encrypt(this._inBlock, this._outBlock);
- if (this._partialBytes === 0 && inputLength >= this.blockSize) {
- for (var i6 = 0;i6 < this._ints; ++i6) {
- output.putInt32(this._outBlock[i6] ^= input.getInt32());
- }
- this._cipherLength += this.blockSize;
- } else {
- var partialBytes = (this.blockSize - inputLength) % this.blockSize;
- if (partialBytes > 0) {
- partialBytes = this.blockSize - partialBytes;
- }
- this._partialOutput.clear();
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i6]);
- }
- if (partialBytes <= 0 || finish) {
- if (finish) {
- var overflow = inputLength % this.blockSize;
- this._cipherLength += overflow;
- this._partialOutput.truncate(this.blockSize - overflow);
- } else {
- this._cipherLength += this.blockSize;
- }
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this._outBlock[i6] = this._partialOutput.getInt32();
- }
- this._partialOutput.read -= this.blockSize;
- }
- if (this._partialBytes > 0) {
- this._partialOutput.getBytes(this._partialBytes);
- }
- if (partialBytes > 0 && !finish) {
- input.read -= this.blockSize;
- output.putBytes(this._partialOutput.getBytes(partialBytes - this._partialBytes));
- this._partialBytes = partialBytes;
- return true;
- }
- output.putBytes(this._partialOutput.getBytes(inputLength - this._partialBytes));
- this._partialBytes = 0;
- }
- this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);
- inc32(this._inBlock);
- };
- modes.gcm.prototype.decrypt = function(input, output, finish) {
- var inputLength = input.length();
- if (inputLength < this.blockSize && !(finish && inputLength > 0)) {
- return true;
- }
- this.cipher.encrypt(this._inBlock, this._outBlock);
- inc32(this._inBlock);
- this._hashBlock[0] = input.getInt32();
- this._hashBlock[1] = input.getInt32();
- this._hashBlock[2] = input.getInt32();
- this._hashBlock[3] = input.getInt32();
- this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);
- for (var i6 = 0;i6 < this._ints; ++i6) {
- output.putInt32(this._outBlock[i6] ^ this._hashBlock[i6]);
- }
- if (inputLength < this.blockSize) {
- this._cipherLength += inputLength % this.blockSize;
- } else {
- this._cipherLength += this.blockSize;
- }
- };
- modes.gcm.prototype.afterFinish = function(output, options2) {
- var rval = true;
- if (options2.decrypt && options2.overflow) {
- output.truncate(this.blockSize - options2.overflow);
- }
- this.tag = forge.util.createBuffer();
- var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));
- this._s = this.ghash(this._hashSubkey, this._s, lengths);
- var tag2 = [];
- this.cipher.encrypt(this._j0, tag2);
- for (var i6 = 0;i6 < this._ints; ++i6) {
- this.tag.putInt32(this._s[i6] ^ tag2[i6]);
- }
- this.tag.truncate(this.tag.length() % (this._tagLength / 8));
- if (options2.decrypt && this.tag.bytes() !== this._tag) {
- rval = false;
- }
- return rval;
- };
- modes.gcm.prototype.multiply = function(x4, y3) {
- var z_i = [0, 0, 0, 0];
- var v_i = y3.slice(0);
- for (var i6 = 0;i6 < 128; ++i6) {
- var x_i = x4[i6 / 32 | 0] & 1 << 31 - i6 % 32;
- if (x_i) {
- z_i[0] ^= v_i[0];
- z_i[1] ^= v_i[1];
- z_i[2] ^= v_i[2];
- z_i[3] ^= v_i[3];
- }
- this.pow(v_i, v_i);
- }
- return z_i;
- };
- modes.gcm.prototype.pow = function(x4, out) {
- var lsb = x4[3] & 1;
- for (var i6 = 3;i6 > 0; --i6) {
- out[i6] = x4[i6] >>> 1 | (x4[i6 - 1] & 1) << 31;
- }
- out[0] = x4[0] >>> 1;
- if (lsb) {
- out[0] ^= this._R;
- }
- };
- modes.gcm.prototype.tableMultiply = function(x4) {
- var z3 = [0, 0, 0, 0];
- for (var i6 = 0;i6 < 32; ++i6) {
- var idx = i6 / 8 | 0;
- var x_i = x4[idx] >>> (7 - i6 % 8) * 4 & 15;
- var ah = this._m[i6][x_i];
- z3[0] ^= ah[0];
- z3[1] ^= ah[1];
- z3[2] ^= ah[2];
- z3[3] ^= ah[3];
- }
- return z3;
- };
- modes.gcm.prototype.ghash = function(h5, y3, x4) {
- y3[0] ^= x4[0];
- y3[1] ^= x4[1];
- y3[2] ^= x4[2];
- y3[3] ^= x4[3];
- return this.tableMultiply(y3);
- };
- modes.gcm.prototype.generateHashTable = function(h5, bits2) {
- var multiplier = 8 / bits2;
- var perInt = 4 * multiplier;
- var size = 16 * multiplier;
- var m4 = new Array(size);
- for (var i6 = 0;i6 < size; ++i6) {
- var tmp = [0, 0, 0, 0];
- var idx = i6 / perInt | 0;
- var shft2 = (perInt - 1 - i6 % perInt) * bits2;
- tmp[idx] = 1 << bits2 - 1 << shft2;
- m4[i6] = this.generateSubHashTable(this.multiply(tmp, h5), bits2);
- }
- return m4;
- };
- modes.gcm.prototype.generateSubHashTable = function(mid, bits2) {
- var size = 1 << bits2;
- var half = size >>> 1;
- var m4 = new Array(size);
- m4[half] = mid.slice(0);
- var i6 = half >>> 1;
- while (i6 > 0) {
- this.pow(m4[2 * i6], m4[i6] = []);
- i6 >>= 1;
- }
- i6 = 2;
- while (i6 < half) {
- for (var j4 = 1;j4 < i6; ++j4) {
- var m_i = m4[i6];
- var m_j = m4[j4];
- m4[i6 + j4] = [
- m_i[0] ^ m_j[0],
- m_i[1] ^ m_j[1],
- m_i[2] ^ m_j[2],
- m_i[3] ^ m_j[3]
- ];
- }
- i6 *= 2;
- }
- m4[0] = [0, 0, 0, 0];
- for (i6 = half + 1;i6 < size; ++i6) {
- var c8 = m4[i6 ^ half];
- m4[i6] = [mid[0] ^ c8[0], mid[1] ^ c8[1], mid[2] ^ c8[2], mid[3] ^ c8[3]];
- }
- return m4;
- };
- function transformIV(iv, blockSize) {
- if (typeof iv === "string") {
- iv = forge.util.createBuffer(iv);
- }
- if (forge.util.isArray(iv) && iv.length > 4) {
- var tmp = iv;
- iv = forge.util.createBuffer();
- for (var i6 = 0;i6 < tmp.length; ++i6) {
- iv.putByte(tmp[i6]);
- }
- }
- if (iv.length() < blockSize) {
- throw new Error("Invalid IV length; got " + iv.length() + " bytes and expected " + blockSize + " bytes.");
- }
- if (!forge.util.isArray(iv)) {
- var ints = [];
- var blocks = blockSize / 4;
- for (var i6 = 0;i6 < blocks; ++i6) {
- ints.push(iv.getInt32());
- }
- iv = ints;
- }
- return iv;
- }
- function inc32(block2) {
- block2[block2.length - 1] = block2[block2.length - 1] + 1 & 4294967295;
- }
- function from64To32(num) {
- return [num / 4294967296 | 0, num & 4294967295];
- }
-});
-
-// node_modules/node-forge/lib/aes.js
-var require_aes = __commonJS((exports, module) => {
- var forge = require_forge();
- require_cipher();
- require_cipherModes();
- require_util3();
- module.exports = forge.aes = forge.aes || {};
- forge.aes.startEncrypting = function(key2, iv, output, mode) {
- var cipher = _createCipher({
- key: key2,
- output,
- decrypt: false,
- mode
- });
- cipher.start(iv);
- return cipher;
- };
- forge.aes.createEncryptionCipher = function(key2, mode) {
- return _createCipher({
- key: key2,
- output: null,
- decrypt: false,
- mode
- });
- };
- forge.aes.startDecrypting = function(key2, iv, output, mode) {
- var cipher = _createCipher({
- key: key2,
- output,
- decrypt: true,
- mode
- });
- cipher.start(iv);
- return cipher;
- };
- forge.aes.createDecryptionCipher = function(key2, mode) {
- return _createCipher({
- key: key2,
- output: null,
- decrypt: true,
- mode
- });
- };
- forge.aes.Algorithm = function(name3, mode) {
- if (!init) {
- initialize();
- }
- var self2 = this;
- self2.name = name3;
- self2.mode = new mode({
- blockSize: 16,
- cipher: {
- encrypt: function(inBlock, outBlock) {
- return _updateBlock(self2._w, inBlock, outBlock, false);
- },
- decrypt: function(inBlock, outBlock) {
- return _updateBlock(self2._w, inBlock, outBlock, true);
- }
- }
- });
- self2._init = false;
- };
- forge.aes.Algorithm.prototype.initialize = function(options2) {
- if (this._init) {
- return;
- }
- var key2 = options2.key;
- var tmp;
- if (typeof key2 === "string" && (key2.length === 16 || key2.length === 24 || key2.length === 32)) {
- key2 = forge.util.createBuffer(key2);
- } else if (forge.util.isArray(key2) && (key2.length === 16 || key2.length === 24 || key2.length === 32)) {
- tmp = key2;
- key2 = forge.util.createBuffer();
- for (var i6 = 0;i6 < tmp.length; ++i6) {
- key2.putByte(tmp[i6]);
- }
- }
- if (!forge.util.isArray(key2)) {
- tmp = key2;
- key2 = [];
- var len = tmp.length();
- if (len === 16 || len === 24 || len === 32) {
- len = len >>> 2;
- for (var i6 = 0;i6 < len; ++i6) {
- key2.push(tmp.getInt32());
- }
- }
- }
- if (!forge.util.isArray(key2) || !(key2.length === 4 || key2.length === 6 || key2.length === 8)) {
- throw new Error("Invalid key parameter.");
- }
- var mode = this.mode.name;
- var encryptOp = ["CFB", "OFB", "CTR", "GCM"].indexOf(mode) !== -1;
- this._w = _expandKey(key2, options2.decrypt && !encryptOp);
- this._init = true;
- };
- forge.aes._expandKey = function(key2, decrypt2) {
- if (!init) {
- initialize();
- }
- return _expandKey(key2, decrypt2);
- };
- forge.aes._updateBlock = _updateBlock;
- registerAlgorithm("AES-ECB", forge.cipher.modes.ecb);
- registerAlgorithm("AES-CBC", forge.cipher.modes.cbc);
- registerAlgorithm("AES-CFB", forge.cipher.modes.cfb);
- registerAlgorithm("AES-OFB", forge.cipher.modes.ofb);
- registerAlgorithm("AES-CTR", forge.cipher.modes.ctr);
- registerAlgorithm("AES-GCM", forge.cipher.modes.gcm);
- function registerAlgorithm(name3, mode) {
- var factory2 = function() {
- return new forge.aes.Algorithm(name3, mode);
- };
- forge.cipher.registerAlgorithm(name3, factory2);
- }
- var init = false;
- var Nb = 4;
- var sbox;
- var isbox;
- var rcon;
- var mix;
- var imix;
- function initialize() {
- init = true;
- rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
- var xtime = new Array(256);
- for (var i6 = 0;i6 < 128; ++i6) {
- xtime[i6] = i6 << 1;
- xtime[i6 + 128] = i6 + 128 << 1 ^ 283;
- }
- sbox = new Array(256);
- isbox = new Array(256);
- mix = new Array(4);
- imix = new Array(4);
- for (var i6 = 0;i6 < 4; ++i6) {
- mix[i6] = new Array(256);
- imix[i6] = new Array(256);
- }
- var e4 = 0, ei = 0, e22, e42, e8, sx, sx2, me, ime;
- for (var i6 = 0;i6 < 256; ++i6) {
- sx = ei ^ ei << 1 ^ ei << 2 ^ ei << 3 ^ ei << 4;
- sx = sx >> 8 ^ sx & 255 ^ 99;
- sbox[e4] = sx;
- isbox[sx] = e4;
- sx2 = xtime[sx];
- e22 = xtime[e4];
- e42 = xtime[e22];
- e8 = xtime[e42];
- me = sx2 << 24 ^ sx << 16 ^ sx << 8 ^ (sx ^ sx2);
- ime = (e22 ^ e42 ^ e8) << 24 ^ (e4 ^ e8) << 16 ^ (e4 ^ e42 ^ e8) << 8 ^ (e4 ^ e22 ^ e8);
- for (var n5 = 0;n5 < 4; ++n5) {
- mix[n5][e4] = me;
- imix[n5][sx] = ime;
- me = me << 24 | me >>> 8;
- ime = ime << 24 | ime >>> 8;
- }
- if (e4 === 0) {
- e4 = ei = 1;
- } else {
- e4 = e22 ^ xtime[xtime[xtime[e22 ^ e8]]];
- ei ^= xtime[xtime[ei]];
- }
- }
- }
- function _expandKey(key2, decrypt2) {
- var w2 = key2.slice(0);
- var temp, iNk = 1;
- var Nk = w2.length;
- var Nr1 = Nk + 6 + 1;
- var end = Nb * Nr1;
- for (var i6 = Nk;i6 < end; ++i6) {
- temp = w2[i6 - 1];
- if (i6 % Nk === 0) {
- temp = sbox[temp >>> 16 & 255] << 24 ^ sbox[temp >>> 8 & 255] << 16 ^ sbox[temp & 255] << 8 ^ sbox[temp >>> 24] ^ rcon[iNk] << 24;
- iNk++;
- } else if (Nk > 6 && i6 % Nk === 4) {
- temp = sbox[temp >>> 24] << 24 ^ sbox[temp >>> 16 & 255] << 16 ^ sbox[temp >>> 8 & 255] << 8 ^ sbox[temp & 255];
- }
- w2[i6] = w2[i6 - Nk] ^ temp;
- }
- if (decrypt2) {
- var tmp;
- var m0 = imix[0];
- var m1 = imix[1];
- var m22 = imix[2];
- var m32 = imix[3];
- var wnew = w2.slice(0);
- end = w2.length;
- for (var i6 = 0, wi = end - Nb;i6 < end; i6 += Nb, wi -= Nb) {
- if (i6 === 0 || i6 === end - Nb) {
- wnew[i6] = w2[wi];
- wnew[i6 + 1] = w2[wi + 3];
- wnew[i6 + 2] = w2[wi + 2];
- wnew[i6 + 3] = w2[wi + 1];
- } else {
- for (var n5 = 0;n5 < Nb; ++n5) {
- tmp = w2[wi + n5];
- wnew[i6 + (3 & -n5)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m22[sbox[tmp >>> 8 & 255]] ^ m32[sbox[tmp & 255]];
- }
- }
- }
- w2 = wnew;
- }
- return w2;
- }
- function _updateBlock(w2, input, output, decrypt2) {
- var Nr = w2.length / 4 - 1;
- var m0, m1, m22, m32, sub;
- if (decrypt2) {
- m0 = imix[0];
- m1 = imix[1];
- m22 = imix[2];
- m32 = imix[3];
- sub = isbox;
- } else {
- m0 = mix[0];
- m1 = mix[1];
- m22 = mix[2];
- m32 = mix[3];
- sub = sbox;
- }
- var a5, b5, c8, d4, a22, b23, c22;
- a5 = input[0] ^ w2[0];
- b5 = input[decrypt2 ? 3 : 1] ^ w2[1];
- c8 = input[2] ^ w2[2];
- d4 = input[decrypt2 ? 1 : 3] ^ w2[3];
- var i6 = 3;
- for (var round = 1;round < Nr; ++round) {
- a22 = m0[a5 >>> 24] ^ m1[b5 >>> 16 & 255] ^ m22[c8 >>> 8 & 255] ^ m32[d4 & 255] ^ w2[++i6];
- b23 = m0[b5 >>> 24] ^ m1[c8 >>> 16 & 255] ^ m22[d4 >>> 8 & 255] ^ m32[a5 & 255] ^ w2[++i6];
- c22 = m0[c8 >>> 24] ^ m1[d4 >>> 16 & 255] ^ m22[a5 >>> 8 & 255] ^ m32[b5 & 255] ^ w2[++i6];
- d4 = m0[d4 >>> 24] ^ m1[a5 >>> 16 & 255] ^ m22[b5 >>> 8 & 255] ^ m32[c8 & 255] ^ w2[++i6];
- a5 = a22;
- b5 = b23;
- c8 = c22;
- }
- output[0] = sub[a5 >>> 24] << 24 ^ sub[b5 >>> 16 & 255] << 16 ^ sub[c8 >>> 8 & 255] << 8 ^ sub[d4 & 255] ^ w2[++i6];
- output[decrypt2 ? 3 : 1] = sub[b5 >>> 24] << 24 ^ sub[c8 >>> 16 & 255] << 16 ^ sub[d4 >>> 8 & 255] << 8 ^ sub[a5 & 255] ^ w2[++i6];
- output[2] = sub[c8 >>> 24] << 24 ^ sub[d4 >>> 16 & 255] << 16 ^ sub[a5 >>> 8 & 255] << 8 ^ sub[b5 & 255] ^ w2[++i6];
- output[decrypt2 ? 1 : 3] = sub[d4 >>> 24] << 24 ^ sub[a5 >>> 16 & 255] << 16 ^ sub[b5 >>> 8 & 255] << 8 ^ sub[c8 & 255] ^ w2[++i6];
- }
- function _createCipher(options2) {
- options2 = options2 || {};
- var mode = (options2.mode || "CBC").toUpperCase();
- var algorithm = "AES-" + mode;
- var cipher;
- if (options2.decrypt) {
- cipher = forge.cipher.createDecipher(algorithm, options2.key);
- } else {
- cipher = forge.cipher.createCipher(algorithm, options2.key);
- }
- var start = cipher.start;
- cipher.start = function(iv, options3) {
- var output = null;
- if (options3 instanceof forge.util.ByteBuffer) {
- output = options3;
- options3 = {};
- }
- options3 = options3 || {};
- options3.output = output;
- options3.iv = iv;
- start.call(cipher, options3);
- };
- return cipher;
- }
-});
-
-// node_modules/node-forge/lib/oids.js
-var require_oids = __commonJS((exports, module) => {
- var forge = require_forge();
- forge.pki = forge.pki || {};
- var oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {};
- function _IN(id, name3) {
- oids[id] = name3;
- oids[name3] = id;
- }
- function _I_(id, name3) {
- oids[id] = name3;
- }
- _IN("1.2.840.113549.1.1.1", "rsaEncryption");
- _IN("1.2.840.113549.1.1.4", "md5WithRSAEncryption");
- _IN("1.2.840.113549.1.1.5", "sha1WithRSAEncryption");
- _IN("1.2.840.113549.1.1.7", "RSAES-OAEP");
- _IN("1.2.840.113549.1.1.8", "mgf1");
- _IN("1.2.840.113549.1.1.9", "pSpecified");
- _IN("1.2.840.113549.1.1.10", "RSASSA-PSS");
- _IN("1.2.840.113549.1.1.11", "sha256WithRSAEncryption");
- _IN("1.2.840.113549.1.1.12", "sha384WithRSAEncryption");
- _IN("1.2.840.113549.1.1.13", "sha512WithRSAEncryption");
- _IN("1.3.101.112", "EdDSA25519");
- _IN("1.2.840.10040.4.3", "dsa-with-sha1");
- _IN("1.3.14.3.2.7", "desCBC");
- _IN("1.3.14.3.2.26", "sha1");
- _IN("1.3.14.3.2.29", "sha1WithRSASignature");
- _IN("2.16.840.1.101.3.4.2.1", "sha256");
- _IN("2.16.840.1.101.3.4.2.2", "sha384");
- _IN("2.16.840.1.101.3.4.2.3", "sha512");
- _IN("2.16.840.1.101.3.4.2.4", "sha224");
- _IN("2.16.840.1.101.3.4.2.5", "sha512-224");
- _IN("2.16.840.1.101.3.4.2.6", "sha512-256");
- _IN("1.2.840.113549.2.2", "md2");
- _IN("1.2.840.113549.2.5", "md5");
- _IN("1.2.840.113549.1.7.1", "data");
- _IN("1.2.840.113549.1.7.2", "signedData");
- _IN("1.2.840.113549.1.7.3", "envelopedData");
- _IN("1.2.840.113549.1.7.4", "signedAndEnvelopedData");
- _IN("1.2.840.113549.1.7.5", "digestedData");
- _IN("1.2.840.113549.1.7.6", "encryptedData");
- _IN("1.2.840.113549.1.9.1", "emailAddress");
- _IN("1.2.840.113549.1.9.2", "unstructuredName");
- _IN("1.2.840.113549.1.9.3", "contentType");
- _IN("1.2.840.113549.1.9.4", "messageDigest");
- _IN("1.2.840.113549.1.9.5", "signingTime");
- _IN("1.2.840.113549.1.9.6", "counterSignature");
- _IN("1.2.840.113549.1.9.7", "challengePassword");
- _IN("1.2.840.113549.1.9.8", "unstructuredAddress");
- _IN("1.2.840.113549.1.9.14", "extensionRequest");
- _IN("1.2.840.113549.1.9.20", "friendlyName");
- _IN("1.2.840.113549.1.9.21", "localKeyId");
- _IN("1.2.840.113549.1.9.22.1", "x509Certificate");
- _IN("1.2.840.113549.1.12.10.1.1", "keyBag");
- _IN("1.2.840.113549.1.12.10.1.2", "pkcs8ShroudedKeyBag");
- _IN("1.2.840.113549.1.12.10.1.3", "certBag");
- _IN("1.2.840.113549.1.12.10.1.4", "crlBag");
- _IN("1.2.840.113549.1.12.10.1.5", "secretBag");
- _IN("1.2.840.113549.1.12.10.1.6", "safeContentsBag");
- _IN("1.2.840.113549.1.5.13", "pkcs5PBES2");
- _IN("1.2.840.113549.1.5.12", "pkcs5PBKDF2");
- _IN("1.2.840.113549.1.12.1.1", "pbeWithSHAAnd128BitRC4");
- _IN("1.2.840.113549.1.12.1.2", "pbeWithSHAAnd40BitRC4");
- _IN("1.2.840.113549.1.12.1.3", "pbeWithSHAAnd3-KeyTripleDES-CBC");
- _IN("1.2.840.113549.1.12.1.4", "pbeWithSHAAnd2-KeyTripleDES-CBC");
- _IN("1.2.840.113549.1.12.1.5", "pbeWithSHAAnd128BitRC2-CBC");
- _IN("1.2.840.113549.1.12.1.6", "pbewithSHAAnd40BitRC2-CBC");
- _IN("1.2.840.113549.2.7", "hmacWithSHA1");
- _IN("1.2.840.113549.2.8", "hmacWithSHA224");
- _IN("1.2.840.113549.2.9", "hmacWithSHA256");
- _IN("1.2.840.113549.2.10", "hmacWithSHA384");
- _IN("1.2.840.113549.2.11", "hmacWithSHA512");
- _IN("1.2.840.113549.3.7", "des-EDE3-CBC");
- _IN("2.16.840.1.101.3.4.1.2", "aes128-CBC");
- _IN("2.16.840.1.101.3.4.1.22", "aes192-CBC");
- _IN("2.16.840.1.101.3.4.1.42", "aes256-CBC");
- _IN("2.5.4.3", "commonName");
- _IN("2.5.4.4", "surname");
- _IN("2.5.4.5", "serialNumber");
- _IN("2.5.4.6", "countryName");
- _IN("2.5.4.7", "localityName");
- _IN("2.5.4.8", "stateOrProvinceName");
- _IN("2.5.4.9", "streetAddress");
- _IN("2.5.4.10", "organizationName");
- _IN("2.5.4.11", "organizationalUnitName");
- _IN("2.5.4.12", "title");
- _IN("2.5.4.13", "description");
- _IN("2.5.4.15", "businessCategory");
- _IN("2.5.4.17", "postalCode");
- _IN("2.5.4.42", "givenName");
- _IN("2.5.4.65", "pseudonym");
- _IN("1.3.6.1.4.1.311.60.2.1.2", "jurisdictionOfIncorporationStateOrProvinceName");
- _IN("1.3.6.1.4.1.311.60.2.1.3", "jurisdictionOfIncorporationCountryName");
- _IN("2.16.840.1.113730.1.1", "nsCertType");
- _IN("2.16.840.1.113730.1.13", "nsComment");
- _I_("2.5.29.1", "authorityKeyIdentifier");
- _I_("2.5.29.2", "keyAttributes");
- _I_("2.5.29.3", "certificatePolicies");
- _I_("2.5.29.4", "keyUsageRestriction");
- _I_("2.5.29.5", "policyMapping");
- _I_("2.5.29.6", "subtreesConstraint");
- _I_("2.5.29.7", "subjectAltName");
- _I_("2.5.29.8", "issuerAltName");
- _I_("2.5.29.9", "subjectDirectoryAttributes");
- _I_("2.5.29.10", "basicConstraints");
- _I_("2.5.29.11", "nameConstraints");
- _I_("2.5.29.12", "policyConstraints");
- _I_("2.5.29.13", "basicConstraints");
- _IN("2.5.29.14", "subjectKeyIdentifier");
- _IN("2.5.29.15", "keyUsage");
- _I_("2.5.29.16", "privateKeyUsagePeriod");
- _IN("2.5.29.17", "subjectAltName");
- _IN("2.5.29.18", "issuerAltName");
- _IN("2.5.29.19", "basicConstraints");
- _I_("2.5.29.20", "cRLNumber");
- _I_("2.5.29.21", "cRLReason");
- _I_("2.5.29.22", "expirationDate");
- _I_("2.5.29.23", "instructionCode");
- _I_("2.5.29.24", "invalidityDate");
- _I_("2.5.29.25", "cRLDistributionPoints");
- _I_("2.5.29.26", "issuingDistributionPoint");
- _I_("2.5.29.27", "deltaCRLIndicator");
- _I_("2.5.29.28", "issuingDistributionPoint");
- _I_("2.5.29.29", "certificateIssuer");
- _I_("2.5.29.30", "nameConstraints");
- _IN("2.5.29.31", "cRLDistributionPoints");
- _IN("2.5.29.32", "certificatePolicies");
- _I_("2.5.29.33", "policyMappings");
- _I_("2.5.29.34", "policyConstraints");
- _IN("2.5.29.35", "authorityKeyIdentifier");
- _I_("2.5.29.36", "policyConstraints");
- _IN("2.5.29.37", "extKeyUsage");
- _I_("2.5.29.46", "freshestCRL");
- _I_("2.5.29.54", "inhibitAnyPolicy");
- _IN("1.3.6.1.4.1.11129.2.4.2", "timestampList");
- _IN("1.3.6.1.5.5.7.1.1", "authorityInfoAccess");
- _IN("1.3.6.1.5.5.7.3.1", "serverAuth");
- _IN("1.3.6.1.5.5.7.3.2", "clientAuth");
- _IN("1.3.6.1.5.5.7.3.3", "codeSigning");
- _IN("1.3.6.1.5.5.7.3.4", "emailProtection");
- _IN("1.3.6.1.5.5.7.3.8", "timeStamping");
-});
-
-// node_modules/node-forge/lib/asn1.js
-var require_asn1 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_util3();
- require_oids();
- var asn1 = module.exports = forge.asn1 = forge.asn1 || {};
- asn1.Class = {
- UNIVERSAL: 0,
- APPLICATION: 64,
- CONTEXT_SPECIFIC: 128,
- PRIVATE: 192
- };
- asn1.Type = {
- NONE: 0,
- BOOLEAN: 1,
- INTEGER: 2,
- BITSTRING: 3,
- OCTETSTRING: 4,
- NULL: 5,
- OID: 6,
- ODESC: 7,
- EXTERNAL: 8,
- REAL: 9,
- ENUMERATED: 10,
- EMBEDDED: 11,
- UTF8: 12,
- ROID: 13,
- SEQUENCE: 16,
- SET: 17,
- PRINTABLESTRING: 19,
- IA5STRING: 22,
- UTCTIME: 23,
- GENERALIZEDTIME: 24,
- BMPSTRING: 30
- };
- asn1.maxDepth = 256;
- asn1.create = function(tagClass, type, constructed, value, options2) {
- if (forge.util.isArray(value)) {
- var tmp = [];
- for (var i6 = 0;i6 < value.length; ++i6) {
- if (value[i6] !== undefined) {
- tmp.push(value[i6]);
- }
- }
- value = tmp;
- }
- var obj = {
- tagClass,
- type,
- constructed,
- composed: constructed || forge.util.isArray(value),
- value
- };
- if (options2 && "bitStringContents" in options2) {
- obj.bitStringContents = options2.bitStringContents;
- obj.original = asn1.copy(obj);
- }
- return obj;
- };
- asn1.copy = function(obj, options2) {
- var copy;
- if (forge.util.isArray(obj)) {
- copy = [];
- for (var i6 = 0;i6 < obj.length; ++i6) {
- copy.push(asn1.copy(obj[i6], options2));
- }
- return copy;
- }
- if (typeof obj === "string") {
- return obj;
- }
- copy = {
- tagClass: obj.tagClass,
- type: obj.type,
- constructed: obj.constructed,
- composed: obj.composed,
- value: asn1.copy(obj.value, options2)
- };
- if (options2 && !options2.excludeBitStringContents) {
- copy.bitStringContents = obj.bitStringContents;
- }
- return copy;
- };
- asn1.equals = function(obj1, obj2, options2) {
- if (forge.util.isArray(obj1)) {
- if (!forge.util.isArray(obj2)) {
- return false;
- }
- if (obj1.length !== obj2.length) {
- return false;
- }
- for (var i6 = 0;i6 < obj1.length; ++i6) {
- if (!asn1.equals(obj1[i6], obj2[i6])) {
- return false;
- }
- }
- return true;
- }
- if (typeof obj1 !== typeof obj2) {
- return false;
- }
- if (typeof obj1 === "string") {
- return obj1 === obj2;
- }
- var equal = obj1.tagClass === obj2.tagClass && obj1.type === obj2.type && obj1.constructed === obj2.constructed && obj1.composed === obj2.composed && asn1.equals(obj1.value, obj2.value);
- if (options2 && options2.includeBitStringContents) {
- equal = equal && obj1.bitStringContents === obj2.bitStringContents;
- }
- return equal;
- };
- asn1.getBerValueLength = function(b5) {
- var b23 = b5.getByte();
- if (b23 === 128) {
- return;
- }
- var length;
- var longForm = b23 & 128;
- if (!longForm) {
- length = b23;
- } else {
- length = b5.getInt((b23 & 127) << 3);
- }
- return length;
- };
- function _checkBufferLength(bytes, remaining, n5) {
- if (n5 > remaining) {
- var error46 = new Error("Too few bytes to parse DER.");
- error46.available = bytes.length();
- error46.remaining = remaining;
- error46.requested = n5;
- throw error46;
- }
- }
- var _getValueLength = function(bytes, remaining) {
- var b23 = bytes.getByte();
- remaining--;
- if (b23 === 128) {
- return;
- }
- var length;
- var longForm = b23 & 128;
- if (!longForm) {
- length = b23;
- } else {
- var longFormBytes = b23 & 127;
- _checkBufferLength(bytes, remaining, longFormBytes);
- length = bytes.getInt(longFormBytes << 3);
- }
- if (length < 0) {
- throw new Error("Negative length: " + length);
- }
- return length;
- };
- asn1.fromDer = function(bytes, options2) {
- if (options2 === undefined) {
- options2 = {
- strict: true,
- parseAllBytes: true,
- decodeBitStrings: true
- };
- }
- if (typeof options2 === "boolean") {
- options2 = {
- strict: options2,
- parseAllBytes: true,
- decodeBitStrings: true
- };
- }
- if (!("strict" in options2)) {
- options2.strict = true;
- }
- if (!("parseAllBytes" in options2)) {
- options2.parseAllBytes = true;
- }
- if (!("decodeBitStrings" in options2)) {
- options2.decodeBitStrings = true;
- }
- if (!("maxDepth" in options2)) {
- options2.maxDepth = asn1.maxDepth;
- }
- if (typeof bytes === "string") {
- bytes = forge.util.createBuffer(bytes);
- }
- var byteCount = bytes.length();
- var value = _fromDer(bytes, bytes.length(), 0, options2);
- if (options2.parseAllBytes && bytes.length() !== 0) {
- var error46 = new Error("Unparsed DER bytes remain after ASN.1 parsing.");
- error46.byteCount = byteCount;
- error46.remaining = bytes.length();
- throw error46;
- }
- return value;
- };
- function _fromDer(bytes, remaining, depth, options2) {
- if (depth >= options2.maxDepth) {
- throw new Error("ASN.1 parsing error: Max depth exceeded.");
- }
- var start;
- _checkBufferLength(bytes, remaining, 2);
- var b1 = bytes.getByte();
- remaining--;
- var tagClass = b1 & 192;
- var type = b1 & 31;
- start = bytes.length();
- var length = _getValueLength(bytes, remaining);
- remaining -= start - bytes.length();
- if (length !== undefined && length > remaining) {
- if (options2.strict) {
- var error46 = new Error("Too few bytes to read ASN.1 value.");
- error46.available = bytes.length();
- error46.remaining = remaining;
- error46.requested = length;
- throw error46;
- }
- length = remaining;
- }
- var value;
- var bitStringContents;
- var constructed = (b1 & 32) === 32;
- if (constructed) {
- value = [];
- if (length === undefined) {
- for (;; ) {
- _checkBufferLength(bytes, remaining, 2);
- if (bytes.bytes(2) === String.fromCharCode(0, 0)) {
- bytes.getBytes(2);
- remaining -= 2;
- break;
- }
- start = bytes.length();
- value.push(_fromDer(bytes, remaining, depth + 1, options2));
- remaining -= start - bytes.length();
- }
- } else {
- while (length > 0) {
- start = bytes.length();
- value.push(_fromDer(bytes, length, depth + 1, options2));
- remaining -= start - bytes.length();
- length -= start - bytes.length();
- }
- }
- }
- if (value === undefined && tagClass === asn1.Class.UNIVERSAL && type === asn1.Type.BITSTRING) {
- bitStringContents = bytes.bytes(length);
- }
- if (value === undefined && options2.decodeBitStrings && tagClass === asn1.Class.UNIVERSAL && type === asn1.Type.BITSTRING && length > 1) {
- var savedRead = bytes.read;
- var savedRemaining = remaining;
- var unused = 0;
- if (type === asn1.Type.BITSTRING) {
- _checkBufferLength(bytes, remaining, 1);
- unused = bytes.getByte();
- remaining--;
- }
- if (unused === 0) {
- try {
- start = bytes.length();
- var subOptions = {
- strict: true,
- decodeBitStrings: true
- };
- var composed = _fromDer(bytes, remaining, depth + 1, subOptions);
- var used = start - bytes.length();
- remaining -= used;
- if (type == asn1.Type.BITSTRING) {
- used++;
- }
- var tc = composed.tagClass;
- if (used === length && (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {
- value = [composed];
- }
- } catch (ex) {}
- }
- if (value === undefined) {
- bytes.read = savedRead;
- remaining = savedRemaining;
- }
- }
- if (value === undefined) {
- if (length === undefined) {
- if (options2.strict) {
- throw new Error("Non-constructed ASN.1 object of indefinite length.");
- }
- length = remaining;
- }
- if (type === asn1.Type.BMPSTRING) {
- value = "";
- for (;length > 0; length -= 2) {
- _checkBufferLength(bytes, remaining, 2);
- value += String.fromCharCode(bytes.getInt16());
- remaining -= 2;
- }
- } else {
- value = bytes.getBytes(length);
- remaining -= length;
- }
- }
- var asn1Options = bitStringContents === undefined ? null : {
- bitStringContents
- };
- return asn1.create(tagClass, type, constructed, value, asn1Options);
- }
- asn1.toDer = function(obj) {
- var bytes = forge.util.createBuffer();
- var b1 = obj.tagClass | obj.type;
- var value = forge.util.createBuffer();
- var useBitStringContents = false;
- if ("bitStringContents" in obj) {
- useBitStringContents = true;
- if (obj.original) {
- useBitStringContents = asn1.equals(obj, obj.original);
- }
- }
- if (useBitStringContents) {
- value.putBytes(obj.bitStringContents);
- } else if (obj.composed) {
- if (obj.constructed) {
- b1 |= 32;
- } else {
- value.putByte(0);
- }
- for (var i6 = 0;i6 < obj.value.length; ++i6) {
- if (obj.value[i6] !== undefined) {
- value.putBuffer(asn1.toDer(obj.value[i6]));
- }
- }
- } else {
- if (obj.type === asn1.Type.BMPSTRING) {
- for (var i6 = 0;i6 < obj.value.length; ++i6) {
- value.putInt16(obj.value.charCodeAt(i6));
- }
- } else {
- if (obj.type === asn1.Type.INTEGER && obj.value.length > 1 && (obj.value.charCodeAt(0) === 0 && (obj.value.charCodeAt(1) & 128) === 0 || obj.value.charCodeAt(0) === 255 && (obj.value.charCodeAt(1) & 128) === 128)) {
- value.putBytes(obj.value.substr(1));
- } else {
- value.putBytes(obj.value);
- }
- }
- }
- bytes.putByte(b1);
- if (value.length() <= 127) {
- bytes.putByte(value.length() & 127);
- } else {
- var len = value.length();
- var lenBytes = "";
- do {
- lenBytes += String.fromCharCode(len & 255);
- len = len >>> 8;
- } while (len > 0);
- bytes.putByte(lenBytes.length | 128);
- for (var i6 = lenBytes.length - 1;i6 >= 0; --i6) {
- bytes.putByte(lenBytes.charCodeAt(i6));
- }
- }
- bytes.putBuffer(value);
- return bytes;
- };
- asn1.oidToDer = function(oid) {
- var values2 = oid.split(".");
- var bytes = forge.util.createBuffer();
- bytes.putByte(40 * parseInt(values2[0], 10) + parseInt(values2[1], 10));
- var last, valueBytes, value, b5;
- for (var i6 = 2;i6 < values2.length; ++i6) {
- last = true;
- valueBytes = [];
- value = parseInt(values2[i6], 10);
- if (value > 4294967295) {
- throw new Error("OID value too large; max is 32-bits.");
- }
- do {
- b5 = value & 127;
- value = value >>> 7;
- if (!last) {
- b5 |= 128;
- }
- valueBytes.push(b5);
- last = false;
- } while (value > 0);
- for (var n5 = valueBytes.length - 1;n5 >= 0; --n5) {
- bytes.putByte(valueBytes[n5]);
- }
- }
- return bytes;
- };
- asn1.derToOid = function(bytes) {
- var oid;
- if (typeof bytes === "string") {
- bytes = forge.util.createBuffer(bytes);
- }
- var b5 = bytes.getByte();
- oid = Math.floor(b5 / 40) + "." + b5 % 40;
- var value = 0;
- while (bytes.length() > 0) {
- if (value > 70368744177663) {
- throw new Error("OID value too large; max is 53-bits.");
- }
- b5 = bytes.getByte();
- value = value * 128;
- if (b5 & 128) {
- value += b5 & 127;
- } else {
- oid += "." + (value + b5);
- value = 0;
- }
- }
- return oid;
- };
- asn1.utcTimeToDate = function(utc) {
- var date5 = new Date;
- var year = parseInt(utc.substr(0, 2), 10);
- year = year >= 50 ? 1900 + year : 2000 + year;
- var MM = parseInt(utc.substr(2, 2), 10) - 1;
- var DD = parseInt(utc.substr(4, 2), 10);
- var hh = parseInt(utc.substr(6, 2), 10);
- var mm = parseInt(utc.substr(8, 2), 10);
- var ss = 0;
- if (utc.length > 11) {
- var c8 = utc.charAt(10);
- var end = 10;
- if (c8 !== "+" && c8 !== "-") {
- ss = parseInt(utc.substr(10, 2), 10);
- end += 2;
- }
- }
- date5.setUTCFullYear(year, MM, DD);
- date5.setUTCHours(hh, mm, ss, 0);
- if (end) {
- c8 = utc.charAt(end);
- if (c8 === "+" || c8 === "-") {
- var hhoffset = parseInt(utc.substr(end + 1, 2), 10);
- var mmoffset = parseInt(utc.substr(end + 4, 2), 10);
- var offset = hhoffset * 60 + mmoffset;
- offset *= 60000;
- if (c8 === "+") {
- date5.setTime(+date5 - offset);
- } else {
- date5.setTime(+date5 + offset);
- }
- }
- }
- return date5;
- };
- asn1.generalizedTimeToDate = function(gentime) {
- var date5 = new Date;
- var YYYY = parseInt(gentime.substr(0, 4), 10);
- var MM = parseInt(gentime.substr(4, 2), 10) - 1;
- var DD = parseInt(gentime.substr(6, 2), 10);
- var hh = parseInt(gentime.substr(8, 2), 10);
- var mm = parseInt(gentime.substr(10, 2), 10);
- var ss = parseInt(gentime.substr(12, 2), 10);
- var fff = 0;
- var offset = 0;
- var isUTC = false;
- if (gentime.charAt(gentime.length - 1) === "Z") {
- isUTC = true;
- }
- var end = gentime.length - 5, c8 = gentime.charAt(end);
- if (c8 === "+" || c8 === "-") {
- var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);
- var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);
- offset = hhoffset * 60 + mmoffset;
- offset *= 60000;
- if (c8 === "+") {
- offset *= -1;
- }
- isUTC = true;
- }
- if (gentime.charAt(14) === ".") {
- fff = parseFloat(gentime.substr(14), 10) * 1000;
- }
- if (isUTC) {
- date5.setUTCFullYear(YYYY, MM, DD);
- date5.setUTCHours(hh, mm, ss, fff);
- date5.setTime(+date5 + offset);
- } else {
- date5.setFullYear(YYYY, MM, DD);
- date5.setHours(hh, mm, ss, fff);
- }
- return date5;
- };
- asn1.dateToUtcTime = function(date5) {
- if (typeof date5 === "string") {
- return date5;
- }
- var rval = "";
- var format4 = [];
- format4.push(("" + date5.getUTCFullYear()).substr(2));
- format4.push("" + (date5.getUTCMonth() + 1));
- format4.push("" + date5.getUTCDate());
- format4.push("" + date5.getUTCHours());
- format4.push("" + date5.getUTCMinutes());
- format4.push("" + date5.getUTCSeconds());
- for (var i6 = 0;i6 < format4.length; ++i6) {
- if (format4[i6].length < 2) {
- rval += "0";
- }
- rval += format4[i6];
- }
- rval += "Z";
- return rval;
- };
- asn1.dateToGeneralizedTime = function(date5) {
- if (typeof date5 === "string") {
- return date5;
- }
- var rval = "";
- var format4 = [];
- format4.push("" + date5.getUTCFullYear());
- format4.push("" + (date5.getUTCMonth() + 1));
- format4.push("" + date5.getUTCDate());
- format4.push("" + date5.getUTCHours());
- format4.push("" + date5.getUTCMinutes());
- format4.push("" + date5.getUTCSeconds());
- for (var i6 = 0;i6 < format4.length; ++i6) {
- if (format4[i6].length < 2) {
- rval += "0";
- }
- rval += format4[i6];
- }
- rval += "Z";
- return rval;
- };
- asn1.integerToDer = function(x4) {
- var rval = forge.util.createBuffer();
- if (x4 >= -128 && x4 < 128) {
- return rval.putSignedInt(x4, 8);
- }
- if (x4 >= -32768 && x4 < 32768) {
- return rval.putSignedInt(x4, 16);
- }
- if (x4 >= -8388608 && x4 < 8388608) {
- return rval.putSignedInt(x4, 24);
- }
- if (x4 >= -2147483648 && x4 < 2147483648) {
- return rval.putSignedInt(x4, 32);
- }
- var error46 = new Error("Integer too large; max is 32-bits.");
- error46.integer = x4;
- throw error46;
- };
- asn1.derToInteger = function(bytes) {
- if (typeof bytes === "string") {
- bytes = forge.util.createBuffer(bytes);
- }
- var n5 = bytes.length() * 8;
- if (n5 > 32) {
- throw new Error("Integer too large; max is 32-bits.");
- }
- return bytes.getSignedInt(n5);
- };
- asn1.validate = function(obj, v6, capture, errors8) {
- var rval = false;
- if ((obj.tagClass === v6.tagClass || typeof v6.tagClass === "undefined") && (obj.type === v6.type || typeof v6.type === "undefined")) {
- if (obj.constructed === v6.constructed || typeof v6.constructed === "undefined") {
- rval = true;
- if (v6.value && forge.util.isArray(v6.value)) {
- var j4 = 0;
- for (var i6 = 0;rval && i6 < v6.value.length; ++i6) {
- var schemaItem = v6.value[i6];
- rval = !!schemaItem.optional;
- var objChild = obj.value[j4];
- if (!objChild) {
- if (!schemaItem.optional) {
- rval = false;
- if (errors8) {
- errors8.push("[" + v6.name + "] " + 'Missing required element. Expected tag class "' + schemaItem.tagClass + '", type "' + schemaItem.type + '"');
- }
- }
- continue;
- }
- var schemaHasTag = typeof schemaItem.tagClass !== "undefined" && typeof schemaItem.type !== "undefined";
- if (schemaHasTag && (objChild.tagClass !== schemaItem.tagClass || objChild.type !== schemaItem.type)) {
- if (schemaItem.optional) {
- rval = true;
- continue;
- } else {
- rval = false;
- if (errors8) {
- errors8.push("[" + v6.name + "] " + "Tag mismatch. Expected (" + schemaItem.tagClass + "," + schemaItem.type + "), got (" + objChild.tagClass + "," + objChild.type + ")");
- }
- break;
- }
- }
- var childRval = asn1.validate(objChild, schemaItem, capture, errors8);
- if (childRval) {
- ++j4;
- rval = true;
- } else if (schemaItem.optional) {
- rval = true;
- } else {
- rval = false;
- break;
- }
- }
- }
- if (rval && capture) {
- if (v6.capture) {
- capture[v6.capture] = obj.value;
- }
- if (v6.captureAsn1) {
- capture[v6.captureAsn1] = obj;
- }
- if (v6.captureBitStringContents && "bitStringContents" in obj) {
- capture[v6.captureBitStringContents] = obj.bitStringContents;
- }
- if (v6.captureBitStringValue && "bitStringContents" in obj) {
- var value;
- if (obj.bitStringContents.length < 2) {
- capture[v6.captureBitStringValue] = "";
- } else {
- var unused = obj.bitStringContents.charCodeAt(0);
- if (unused !== 0) {
- throw new Error("captureBitStringValue only supported for zero unused bits");
- }
- capture[v6.captureBitStringValue] = obj.bitStringContents.slice(1);
- }
- }
- }
- } else if (errors8) {
- errors8.push("[" + v6.name + "] " + 'Expected constructed "' + v6.constructed + '", got "' + obj.constructed + '"');
- }
- } else if (errors8) {
- if (obj.tagClass !== v6.tagClass) {
- errors8.push("[" + v6.name + "] " + 'Expected tag class "' + v6.tagClass + '", got "' + obj.tagClass + '"');
- }
- if (obj.type !== v6.type) {
- errors8.push("[" + v6.name + "] " + 'Expected type "' + v6.type + '", got "' + obj.type + '"');
- }
- }
- return rval;
- };
- var _nonLatinRegex = /[^\\u0000-\\u00ff]/;
- asn1.prettyPrint = function(obj, level, indentation) {
- var rval = "";
- level = level || 0;
- indentation = indentation || 2;
- if (level > 0) {
- rval += `
-`;
- }
- var indent = "";
- for (var i6 = 0;i6 < level * indentation; ++i6) {
- indent += " ";
- }
- rval += indent + "Tag: ";
- switch (obj.tagClass) {
- case asn1.Class.UNIVERSAL:
- rval += "Universal:";
- break;
- case asn1.Class.APPLICATION:
- rval += "Application:";
- break;
- case asn1.Class.CONTEXT_SPECIFIC:
- rval += "Context-Specific:";
- break;
- case asn1.Class.PRIVATE:
- rval += "Private:";
- break;
- }
- if (obj.tagClass === asn1.Class.UNIVERSAL) {
- rval += obj.type;
- switch (obj.type) {
- case asn1.Type.NONE:
- rval += " (None)";
- break;
- case asn1.Type.BOOLEAN:
- rval += " (Boolean)";
- break;
- case asn1.Type.INTEGER:
- rval += " (Integer)";
- break;
- case asn1.Type.BITSTRING:
- rval += " (Bit string)";
- break;
- case asn1.Type.OCTETSTRING:
- rval += " (Octet string)";
- break;
- case asn1.Type.NULL:
- rval += " (Null)";
- break;
- case asn1.Type.OID:
- rval += " (Object Identifier)";
- break;
- case asn1.Type.ODESC:
- rval += " (Object Descriptor)";
- break;
- case asn1.Type.EXTERNAL:
- rval += " (External or Instance of)";
- break;
- case asn1.Type.REAL:
- rval += " (Real)";
- break;
- case asn1.Type.ENUMERATED:
- rval += " (Enumerated)";
- break;
- case asn1.Type.EMBEDDED:
- rval += " (Embedded PDV)";
- break;
- case asn1.Type.UTF8:
- rval += " (UTF8)";
- break;
- case asn1.Type.ROID:
- rval += " (Relative Object Identifier)";
- break;
- case asn1.Type.SEQUENCE:
- rval += " (Sequence)";
- break;
- case asn1.Type.SET:
- rval += " (Set)";
- break;
- case asn1.Type.PRINTABLESTRING:
- rval += " (Printable String)";
- break;
- case asn1.Type.IA5String:
- rval += " (IA5String (ASCII))";
- break;
- case asn1.Type.UTCTIME:
- rval += " (UTC time)";
- break;
- case asn1.Type.GENERALIZEDTIME:
- rval += " (Generalized time)";
- break;
- case asn1.Type.BMPSTRING:
- rval += " (BMP String)";
- break;
- }
- } else {
- rval += obj.type;
- }
- rval += `
-`;
- rval += indent + "Constructed: " + obj.constructed + `
-`;
- if (obj.composed) {
- var subvalues = 0;
- var sub = "";
- for (var i6 = 0;i6 < obj.value.length; ++i6) {
- if (obj.value[i6] !== undefined) {
- subvalues += 1;
- sub += asn1.prettyPrint(obj.value[i6], level + 1, indentation);
- if (i6 + 1 < obj.value.length) {
- sub += ",";
- }
- }
- }
- rval += indent + "Sub values: " + subvalues + sub;
- } else {
- rval += indent + "Value: ";
- if (obj.type === asn1.Type.OID) {
- var oid = asn1.derToOid(obj.value);
- rval += oid;
- if (forge.pki && forge.pki.oids) {
- if (oid in forge.pki.oids) {
- rval += " (" + forge.pki.oids[oid] + ") ";
- }
- }
- }
- if (obj.type === asn1.Type.INTEGER) {
- try {
- rval += asn1.derToInteger(obj.value);
- } catch (ex) {
- rval += "0x" + forge.util.bytesToHex(obj.value);
- }
- } else if (obj.type === asn1.Type.BITSTRING) {
- if (obj.value.length > 1) {
- rval += "0x" + forge.util.bytesToHex(obj.value.slice(1));
- } else {
- rval += "(none)";
- }
- if (obj.value.length > 0) {
- var unused = obj.value.charCodeAt(0);
- if (unused == 1) {
- rval += " (1 unused bit shown)";
- } else if (unused > 1) {
- rval += " (" + unused + " unused bits shown)";
- }
- }
- } else if (obj.type === asn1.Type.OCTETSTRING) {
- if (!_nonLatinRegex.test(obj.value)) {
- rval += "(" + obj.value + ") ";
- }
- rval += "0x" + forge.util.bytesToHex(obj.value);
- } else if (obj.type === asn1.Type.UTF8) {
- try {
- rval += forge.util.decodeUtf8(obj.value);
- } catch (e4) {
- if (e4.message === "URI malformed") {
- rval += "0x" + forge.util.bytesToHex(obj.value) + " (malformed UTF8)";
- } else {
- throw e4;
- }
- }
- } else if (obj.type === asn1.Type.PRINTABLESTRING || obj.type === asn1.Type.IA5String) {
- rval += obj.value;
- } else if (_nonLatinRegex.test(obj.value)) {
- rval += "0x" + forge.util.bytesToHex(obj.value);
- } else if (obj.value.length === 0) {
- rval += "[null]";
- } else {
- rval += obj.value;
- }
- }
- return rval;
- };
-});
-
-// node_modules/node-forge/lib/md.js
-var require_md = __commonJS((exports, module) => {
- var forge = require_forge();
- module.exports = forge.md = forge.md || {};
- forge.md.algorithms = forge.md.algorithms || {};
-});
-
-// node_modules/node-forge/lib/hmac.js
-var require_hmac = __commonJS((exports, module) => {
- var forge = require_forge();
- require_md();
- require_util3();
- var hmac2 = module.exports = forge.hmac = forge.hmac || {};
- hmac2.create = function() {
- var _key = null;
- var _md = null;
- var _ipadding = null;
- var _opadding = null;
- var ctx = {};
- ctx.start = function(md, key2) {
- if (md !== null) {
- if (typeof md === "string") {
- md = md.toLowerCase();
- if (md in forge.md.algorithms) {
- _md = forge.md.algorithms[md].create();
- } else {
- throw new Error('Unknown hash algorithm "' + md + '"');
- }
- } else {
- _md = md;
- }
- }
- if (key2 === null) {
- key2 = _key;
- } else {
- if (typeof key2 === "string") {
- key2 = forge.util.createBuffer(key2);
- } else if (forge.util.isArray(key2)) {
- var tmp = key2;
- key2 = forge.util.createBuffer();
- for (var i6 = 0;i6 < tmp.length; ++i6) {
- key2.putByte(tmp[i6]);
- }
- }
- var keylen = key2.length();
- if (keylen > _md.blockLength) {
- _md.start();
- _md.update(key2.bytes());
- key2 = _md.digest();
- }
- _ipadding = forge.util.createBuffer();
- _opadding = forge.util.createBuffer();
- keylen = key2.length();
- for (var i6 = 0;i6 < keylen; ++i6) {
- var tmp = key2.at(i6);
- _ipadding.putByte(54 ^ tmp);
- _opadding.putByte(92 ^ tmp);
- }
- if (keylen < _md.blockLength) {
- var tmp = _md.blockLength - keylen;
- for (var i6 = 0;i6 < tmp; ++i6) {
- _ipadding.putByte(54);
- _opadding.putByte(92);
- }
- }
- _key = key2;
- _ipadding = _ipadding.bytes();
- _opadding = _opadding.bytes();
- }
- _md.start();
- _md.update(_ipadding);
- };
- ctx.update = function(bytes) {
- _md.update(bytes);
- };
- ctx.getMac = function() {
- var inner = _md.digest().bytes();
- _md.start();
- _md.update(_opadding);
- _md.update(inner);
- return _md.digest();
- };
- ctx.digest = ctx.getMac;
- return ctx;
- };
-});
-
-// node_modules/node-forge/lib/md5.js
-var require_md53 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_md();
- require_util3();
- var md5 = module.exports = forge.md5 = forge.md5 || {};
- forge.md.md5 = forge.md.algorithms.md5 = md5;
- md5.create = function() {
- if (!_initialized) {
- _init();
- }
- var _state = null;
- var _input = forge.util.createBuffer();
- var _w3 = new Array(16);
- var md = {
- algorithm: "md5",
- blockLength: 64,
- digestLength: 16,
- messageLength: 0,
- fullMessageLength: null,
- messageLengthSize: 8
- };
- md.start = function() {
- md.messageLength = 0;
- md.fullMessageLength = md.messageLength64 = [];
- var int32s = md.messageLengthSize / 4;
- for (var i6 = 0;i6 < int32s; ++i6) {
- md.fullMessageLength.push(0);
- }
- _input = forge.util.createBuffer();
- _state = {
- h0: 1732584193,
- h1: 4023233417,
- h2: 2562383102,
- h3: 271733878
- };
- return md;
- };
- md.start();
- md.update = function(msg, encoding) {
- if (encoding === "utf8") {
- msg = forge.util.encodeUtf8(msg);
- }
- var len = msg.length;
- md.messageLength += len;
- len = [len / 4294967296 >>> 0, len >>> 0];
- for (var i6 = md.fullMessageLength.length - 1;i6 >= 0; --i6) {
- md.fullMessageLength[i6] += len[1];
- len[1] = len[0] + (md.fullMessageLength[i6] / 4294967296 >>> 0);
- md.fullMessageLength[i6] = md.fullMessageLength[i6] >>> 0;
- len[0] = len[1] / 4294967296 >>> 0;
- }
- _input.putBytes(msg);
- _update(_state, _w3, _input);
- if (_input.read > 2048 || _input.length() === 0) {
- _input.compact();
- }
- return md;
- };
- md.digest = function() {
- var finalBlock = forge.util.createBuffer();
- finalBlock.putBytes(_input.bytes());
- var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize;
- var overflow = remaining & md.blockLength - 1;
- finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
- var bits2, carry = 0;
- for (var i6 = md.fullMessageLength.length - 1;i6 >= 0; --i6) {
- bits2 = md.fullMessageLength[i6] * 8 + carry;
- carry = bits2 / 4294967296 >>> 0;
- finalBlock.putInt32Le(bits2 >>> 0);
- }
- var s22 = {
- h0: _state.h0,
- h1: _state.h1,
- h2: _state.h2,
- h3: _state.h3
- };
- _update(s22, _w3, finalBlock);
- var rval = forge.util.createBuffer();
- rval.putInt32Le(s22.h0);
- rval.putInt32Le(s22.h1);
- rval.putInt32Le(s22.h2);
- rval.putInt32Le(s22.h3);
- return rval;
- };
- return md;
- };
- var _padding = null;
- var _g3 = null;
- var _r3 = null;
- var _k3 = null;
- var _initialized = false;
- function _init() {
- _padding = String.fromCharCode(128);
- _padding += forge.util.fillString(String.fromCharCode(0), 64);
- _g3 = [
- 0,
- 1,
- 2,
- 3,
- 4,
- 5,
- 6,
- 7,
- 8,
- 9,
- 10,
- 11,
- 12,
- 13,
- 14,
- 15,
- 1,
- 6,
- 11,
- 0,
- 5,
- 10,
- 15,
- 4,
- 9,
- 14,
- 3,
- 8,
- 13,
- 2,
- 7,
- 12,
- 5,
- 8,
- 11,
- 14,
- 1,
- 4,
- 7,
- 10,
- 13,
- 0,
- 3,
- 6,
- 9,
- 12,
- 15,
- 2,
- 0,
- 7,
- 14,
- 5,
- 12,
- 3,
- 10,
- 1,
- 8,
- 15,
- 6,
- 13,
- 4,
- 11,
- 2,
- 9
- ];
- _r3 = [
- 7,
- 12,
- 17,
- 22,
- 7,
- 12,
- 17,
- 22,
- 7,
- 12,
- 17,
- 22,
- 7,
- 12,
- 17,
- 22,
- 5,
- 9,
- 14,
- 20,
- 5,
- 9,
- 14,
- 20,
- 5,
- 9,
- 14,
- 20,
- 5,
- 9,
- 14,
- 20,
- 4,
- 11,
- 16,
- 23,
- 4,
- 11,
- 16,
- 23,
- 4,
- 11,
- 16,
- 23,
- 4,
- 11,
- 16,
- 23,
- 6,
- 10,
- 15,
- 21,
- 6,
- 10,
- 15,
- 21,
- 6,
- 10,
- 15,
- 21,
- 6,
- 10,
- 15,
- 21
- ];
- _k3 = new Array(64);
- for (var i6 = 0;i6 < 64; ++i6) {
- _k3[i6] = Math.floor(Math.abs(Math.sin(i6 + 1)) * 4294967296);
- }
- _initialized = true;
- }
- function _update(s4, w2, bytes) {
- var t4, a5, b5, c8, d4, f4, r4, i6;
- var len = bytes.length();
- while (len >= 64) {
- a5 = s4.h0;
- b5 = s4.h1;
- c8 = s4.h2;
- d4 = s4.h3;
- for (i6 = 0;i6 < 16; ++i6) {
- w2[i6] = bytes.getInt32Le();
- f4 = d4 ^ b5 & (c8 ^ d4);
- t4 = a5 + f4 + _k3[i6] + w2[i6];
- r4 = _r3[i6];
- a5 = d4;
- d4 = c8;
- c8 = b5;
- b5 += t4 << r4 | t4 >>> 32 - r4;
- }
- for (;i6 < 32; ++i6) {
- f4 = c8 ^ d4 & (b5 ^ c8);
- t4 = a5 + f4 + _k3[i6] + w2[_g3[i6]];
- r4 = _r3[i6];
- a5 = d4;
- d4 = c8;
- c8 = b5;
- b5 += t4 << r4 | t4 >>> 32 - r4;
- }
- for (;i6 < 48; ++i6) {
- f4 = b5 ^ c8 ^ d4;
- t4 = a5 + f4 + _k3[i6] + w2[_g3[i6]];
- r4 = _r3[i6];
- a5 = d4;
- d4 = c8;
- c8 = b5;
- b5 += t4 << r4 | t4 >>> 32 - r4;
- }
- for (;i6 < 64; ++i6) {
- f4 = c8 ^ (b5 | ~d4);
- t4 = a5 + f4 + _k3[i6] + w2[_g3[i6]];
- r4 = _r3[i6];
- a5 = d4;
- d4 = c8;
- c8 = b5;
- b5 += t4 << r4 | t4 >>> 32 - r4;
- }
- s4.h0 = s4.h0 + a5 | 0;
- s4.h1 = s4.h1 + b5 | 0;
- s4.h2 = s4.h2 + c8 | 0;
- s4.h3 = s4.h3 + d4 | 0;
- len -= 64;
- }
- }
-});
-
-// node_modules/node-forge/lib/pem.js
-var require_pem = __commonJS((exports, module) => {
- var forge = require_forge();
- require_util3();
- var pem = module.exports = forge.pem = forge.pem || {};
- pem.encode = function(msg, options2) {
- options2 = options2 || {};
- var rval = "-----BEGIN " + msg.type + `-----\r
-`;
- var header;
- if (msg.procType) {
- header = {
- name: "Proc-Type",
- values: [String(msg.procType.version), msg.procType.type]
- };
- rval += foldHeader(header);
- }
- if (msg.contentDomain) {
- header = { name: "Content-Domain", values: [msg.contentDomain] };
- rval += foldHeader(header);
- }
- if (msg.dekInfo) {
- header = { name: "DEK-Info", values: [msg.dekInfo.algorithm] };
- if (msg.dekInfo.parameters) {
- header.values.push(msg.dekInfo.parameters);
- }
- rval += foldHeader(header);
- }
- if (msg.headers) {
- for (var i6 = 0;i6 < msg.headers.length; ++i6) {
- rval += foldHeader(msg.headers[i6]);
- }
- }
- if (msg.procType) {
- rval += `\r
-`;
- }
- rval += forge.util.encode64(msg.body, options2.maxline || 64) + `\r
-`;
- rval += "-----END " + msg.type + `-----\r
-`;
- return rval;
- };
- pem.decode = function(str) {
- var rval = [];
- var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g;
- var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/;
- var rCRLF = /\r?\n/;
- var match;
- while (true) {
- match = rMessage.exec(str);
- if (!match) {
- break;
- }
- var type = match[1];
- if (type === "NEW CERTIFICATE REQUEST") {
- type = "CERTIFICATE REQUEST";
- }
- var msg = {
- type,
- procType: null,
- contentDomain: null,
- dekInfo: null,
- headers: [],
- body: forge.util.decode64(match[3])
- };
- rval.push(msg);
- if (!match[2]) {
- continue;
- }
- var lines2 = match[2].split(rCRLF);
- var li = 0;
- while (match && li < lines2.length) {
- var line = lines2[li].replace(/\s+$/, "");
- for (var nl = li + 1;nl < lines2.length; ++nl) {
- var next = lines2[nl];
- if (!/\s/.test(next[0])) {
- break;
- }
- line += next;
- li = nl;
- }
- match = line.match(rHeader);
- if (match) {
- var header = { name: match[1], values: [] };
- var values2 = match[2].split(",");
- for (var vi = 0;vi < values2.length; ++vi) {
- header.values.push(ltrim(values2[vi]));
- }
- if (!msg.procType) {
- if (header.name !== "Proc-Type") {
- throw new Error("Invalid PEM formatted message. The first " + 'encapsulated header must be "Proc-Type".');
- } else if (header.values.length !== 2) {
- throw new Error('Invalid PEM formatted message. The "Proc-Type" ' + "header must have two subfields.");
- }
- msg.procType = { version: values2[0], type: values2[1] };
- } else if (!msg.contentDomain && header.name === "Content-Domain") {
- msg.contentDomain = values2[0] || "";
- } else if (!msg.dekInfo && header.name === "DEK-Info") {
- if (header.values.length === 0) {
- throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + "header must have at least one subfield.");
- }
- msg.dekInfo = { algorithm: values2[0], parameters: values2[1] || null };
- } else {
- msg.headers.push(header);
- }
- }
- ++li;
- }
- if (msg.procType === "ENCRYPTED" && !msg.dekInfo) {
- throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + 'header must be present if "Proc-Type" is "ENCRYPTED".');
- }
- }
- if (rval.length === 0) {
- throw new Error("Invalid PEM formatted message.");
- }
- return rval;
- };
- function foldHeader(header) {
- var rval = header.name + ": ";
- var values2 = [];
- var insertSpace = function(match, $1) {
- return " " + $1;
- };
- for (var i6 = 0;i6 < header.values.length; ++i6) {
- values2.push(header.values[i6].replace(/^(\S+\r\n)/, insertSpace));
- }
- rval += values2.join(",") + `\r
-`;
- var length = 0;
- var candidate = -1;
- for (var i6 = 0;i6 < rval.length; ++i6, ++length) {
- if (length > 65 && candidate !== -1) {
- var insert = rval[candidate];
- if (insert === ",") {
- ++candidate;
- rval = rval.substr(0, candidate) + `\r
- ` + rval.substr(candidate);
- } else {
- rval = rval.substr(0, candidate) + `\r
-` + insert + rval.substr(candidate + 1);
- }
- length = i6 - candidate - 1;
- candidate = -1;
- ++i6;
- } else if (rval[i6] === " " || rval[i6] === "\t" || rval[i6] === ",") {
- candidate = i6;
- }
- }
- return rval;
- }
- function ltrim(str) {
- return str.replace(/^\s+/, "");
- }
-});
-
-// node_modules/node-forge/lib/des.js
-var require_des = __commonJS((exports, module) => {
- var forge = require_forge();
- require_cipher();
- require_cipherModes();
- require_util3();
- module.exports = forge.des = forge.des || {};
- forge.des.startEncrypting = function(key2, iv, output, mode) {
- var cipher = _createCipher({
- key: key2,
- output,
- decrypt: false,
- mode: mode || (iv === null ? "ECB" : "CBC")
- });
- cipher.start(iv);
- return cipher;
- };
- forge.des.createEncryptionCipher = function(key2, mode) {
- return _createCipher({
- key: key2,
- output: null,
- decrypt: false,
- mode
- });
- };
- forge.des.startDecrypting = function(key2, iv, output, mode) {
- var cipher = _createCipher({
- key: key2,
- output,
- decrypt: true,
- mode: mode || (iv === null ? "ECB" : "CBC")
- });
- cipher.start(iv);
- return cipher;
- };
- forge.des.createDecryptionCipher = function(key2, mode) {
- return _createCipher({
- key: key2,
- output: null,
- decrypt: true,
- mode
- });
- };
- forge.des.Algorithm = function(name3, mode) {
- var self2 = this;
- self2.name = name3;
- self2.mode = new mode({
- blockSize: 8,
- cipher: {
- encrypt: function(inBlock, outBlock) {
- return _updateBlock(self2._keys, inBlock, outBlock, false);
- },
- decrypt: function(inBlock, outBlock) {
- return _updateBlock(self2._keys, inBlock, outBlock, true);
- }
- }
- });
- self2._init = false;
- };
- forge.des.Algorithm.prototype.initialize = function(options2) {
- if (this._init) {
- return;
- }
- var key2 = forge.util.createBuffer(options2.key);
- if (this.name.indexOf("3DES") === 0) {
- if (key2.length() !== 24) {
- throw new Error("Invalid Triple-DES key size: " + key2.length() * 8);
- }
- }
- this._keys = _createKeys(key2);
- this._init = true;
- };
- registerAlgorithm("DES-ECB", forge.cipher.modes.ecb);
- registerAlgorithm("DES-CBC", forge.cipher.modes.cbc);
- registerAlgorithm("DES-CFB", forge.cipher.modes.cfb);
- registerAlgorithm("DES-OFB", forge.cipher.modes.ofb);
- registerAlgorithm("DES-CTR", forge.cipher.modes.ctr);
- registerAlgorithm("3DES-ECB", forge.cipher.modes.ecb);
- registerAlgorithm("3DES-CBC", forge.cipher.modes.cbc);
- registerAlgorithm("3DES-CFB", forge.cipher.modes.cfb);
- registerAlgorithm("3DES-OFB", forge.cipher.modes.ofb);
- registerAlgorithm("3DES-CTR", forge.cipher.modes.ctr);
- function registerAlgorithm(name3, mode) {
- var factory2 = function() {
- return new forge.des.Algorithm(name3, mode);
- };
- forge.cipher.registerAlgorithm(name3, factory2);
- }
- var spfunction1 = [16843776, 0, 65536, 16843780, 16842756, 66564, 4, 65536, 1024, 16843776, 16843780, 1024, 16778244, 16842756, 16777216, 4, 1028, 16778240, 16778240, 66560, 66560, 16842752, 16842752, 16778244, 65540, 16777220, 16777220, 65540, 0, 1028, 66564, 16777216, 65536, 16843780, 4, 16842752, 16843776, 16777216, 16777216, 1024, 16842756, 65536, 66560, 16777220, 1024, 4, 16778244, 66564, 16843780, 65540, 16842752, 16778244, 16777220, 1028, 66564, 16843776, 1028, 16778240, 16778240, 0, 65540, 66560, 0, 16842756];
- var spfunction2 = [-2146402272, -2147450880, 32768, 1081376, 1048576, 32, -2146435040, -2147450848, -2147483616, -2146402272, -2146402304, -2147483648, -2147450880, 1048576, 32, -2146435040, 1081344, 1048608, -2147450848, 0, -2147483648, 32768, 1081376, -2146435072, 1048608, -2147483616, 0, 1081344, 32800, -2146402304, -2146435072, 32800, 0, 1081376, -2146435040, 1048576, -2147450848, -2146435072, -2146402304, 32768, -2146435072, -2147450880, 32, -2146402272, 1081376, 32, 32768, -2147483648, 32800, -2146402304, 1048576, -2147483616, 1048608, -2147450848, -2147483616, 1048608, 1081344, 0, -2147450880, 32800, -2147483648, -2146435040, -2146402272, 1081344];
- var spfunction3 = [520, 134349312, 0, 134348808, 134218240, 0, 131592, 134218240, 131080, 134217736, 134217736, 131072, 134349320, 131080, 134348800, 520, 134217728, 8, 134349312, 512, 131584, 134348800, 134348808, 131592, 134218248, 131584, 131072, 134218248, 8, 134349320, 512, 134217728, 134349312, 134217728, 131080, 520, 131072, 134349312, 134218240, 0, 512, 131080, 134349320, 134218240, 134217736, 512, 0, 134348808, 134218248, 131072, 134217728, 134349320, 8, 131592, 131584, 134217736, 134348800, 134218248, 520, 134348800, 131592, 8, 134348808, 131584];
- var spfunction4 = [8396801, 8321, 8321, 128, 8396928, 8388737, 8388609, 8193, 0, 8396800, 8396800, 8396929, 129, 0, 8388736, 8388609, 1, 8192, 8388608, 8396801, 128, 8388608, 8193, 8320, 8388737, 1, 8320, 8388736, 8192, 8396928, 8396929, 129, 8388736, 8388609, 8396800, 8396929, 129, 0, 0, 8396800, 8320, 8388736, 8388737, 1, 8396801, 8321, 8321, 128, 8396929, 129, 1, 8192, 8388609, 8193, 8396928, 8388737, 8193, 8320, 8388608, 8396801, 128, 8388608, 8192, 8396928];
- var spfunction5 = [256, 34078976, 34078720, 1107296512, 524288, 256, 1073741824, 34078720, 1074266368, 524288, 33554688, 1074266368, 1107296512, 1107820544, 524544, 1073741824, 33554432, 1074266112, 1074266112, 0, 1073742080, 1107820800, 1107820800, 33554688, 1107820544, 1073742080, 0, 1107296256, 34078976, 33554432, 1107296256, 524544, 524288, 1107296512, 256, 33554432, 1073741824, 34078720, 1107296512, 1074266368, 33554688, 1073741824, 1107820544, 34078976, 1074266368, 256, 33554432, 1107820544, 1107820800, 524544, 1107296256, 1107820800, 34078720, 0, 1074266112, 1107296256, 524544, 33554688, 1073742080, 524288, 0, 1074266112, 34078976, 1073742080];
- var spfunction6 = [536870928, 541065216, 16384, 541081616, 541065216, 16, 541081616, 4194304, 536887296, 4210704, 4194304, 536870928, 4194320, 536887296, 536870912, 16400, 0, 4194320, 536887312, 16384, 4210688, 536887312, 16, 541065232, 541065232, 0, 4210704, 541081600, 16400, 4210688, 541081600, 536870912, 536887296, 16, 541065232, 4210688, 541081616, 4194304, 16400, 536870928, 4194304, 536887296, 536870912, 16400, 536870928, 541081616, 4210688, 541065216, 4210704, 541081600, 0, 541065232, 16, 16384, 541065216, 4210704, 16384, 4194320, 536887312, 0, 541081600, 536870912, 4194320, 536887312];
- var spfunction7 = [2097152, 69206018, 67110914, 0, 2048, 67110914, 2099202, 69208064, 69208066, 2097152, 0, 67108866, 2, 67108864, 69206018, 2050, 67110912, 2099202, 2097154, 67110912, 67108866, 69206016, 69208064, 2097154, 69206016, 2048, 2050, 69208066, 2099200, 2, 67108864, 2099200, 67108864, 2099200, 2097152, 67110914, 67110914, 69206018, 69206018, 2, 2097154, 67108864, 67110912, 2097152, 69208064, 2050, 2099202, 69208064, 2050, 67108866, 69208066, 69206016, 2099200, 0, 2, 69208066, 0, 2099202, 69206016, 2048, 67108866, 67110912, 2048, 2097154];
- var spfunction8 = [268439616, 4096, 262144, 268701760, 268435456, 268439616, 64, 268435456, 262208, 268697600, 268701760, 266240, 268701696, 266304, 4096, 64, 268697600, 268435520, 268439552, 4160, 266240, 262208, 268697664, 268701696, 4160, 0, 0, 268697664, 268435520, 268439552, 266304, 262144, 266304, 262144, 268701696, 4096, 64, 268697664, 4096, 266304, 268439552, 64, 268435520, 268697600, 268697664, 268435456, 262144, 268439616, 0, 268701760, 262208, 268435520, 268697600, 268439552, 268439616, 0, 268701760, 266240, 266240, 4160, 4160, 262208, 268435456, 268701696];
- function _createKeys(key2) {
- var pc2bytes0 = [0, 4, 536870912, 536870916, 65536, 65540, 536936448, 536936452, 512, 516, 536871424, 536871428, 66048, 66052, 536936960, 536936964], pc2bytes1 = [0, 1, 1048576, 1048577, 67108864, 67108865, 68157440, 68157441, 256, 257, 1048832, 1048833, 67109120, 67109121, 68157696, 68157697], pc2bytes2 = [0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272, 0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272], pc2bytes3 = [0, 2097152, 134217728, 136314880, 8192, 2105344, 134225920, 136323072, 131072, 2228224, 134348800, 136445952, 139264, 2236416, 134356992, 136454144], pc2bytes4 = [0, 262144, 16, 262160, 0, 262144, 16, 262160, 4096, 266240, 4112, 266256, 4096, 266240, 4112, 266256], pc2bytes5 = [0, 1024, 32, 1056, 0, 1024, 32, 1056, 33554432, 33555456, 33554464, 33555488, 33554432, 33555456, 33554464, 33555488], pc2bytes6 = [0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746, 0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746], pc2bytes7 = [0, 65536, 2048, 67584, 536870912, 536936448, 536872960, 536938496, 131072, 196608, 133120, 198656, 537001984, 537067520, 537004032, 537069568], pc2bytes8 = [0, 262144, 0, 262144, 2, 262146, 2, 262146, 33554432, 33816576, 33554432, 33816576, 33554434, 33816578, 33554434, 33816578], pc2bytes9 = [0, 268435456, 8, 268435464, 0, 268435456, 8, 268435464, 1024, 268436480, 1032, 268436488, 1024, 268436480, 1032, 268436488], pc2bytes10 = [0, 32, 0, 32, 1048576, 1048608, 1048576, 1048608, 8192, 8224, 8192, 8224, 1056768, 1056800, 1056768, 1056800], pc2bytes11 = [0, 16777216, 512, 16777728, 2097152, 18874368, 2097664, 18874880, 67108864, 83886080, 67109376, 83886592, 69206016, 85983232, 69206528, 85983744], pc2bytes12 = [0, 4096, 134217728, 134221824, 524288, 528384, 134742016, 134746112, 16, 4112, 134217744, 134221840, 524304, 528400, 134742032, 134746128], pc2bytes13 = [0, 4, 256, 260, 0, 4, 256, 260, 1, 5, 257, 261, 1, 5, 257, 261];
- var iterations = key2.length() > 8 ? 3 : 1;
- var keys2 = [];
- var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
- var n5 = 0, tmp;
- for (var j4 = 0;j4 < iterations; j4++) {
- var left = key2.getInt32();
- var right = key2.getInt32();
- tmp = (left >>> 4 ^ right) & 252645135;
- right ^= tmp;
- left ^= tmp << 4;
- tmp = (right >>> -16 ^ left) & 65535;
- left ^= tmp;
- right ^= tmp << -16;
- tmp = (left >>> 2 ^ right) & 858993459;
- right ^= tmp;
- left ^= tmp << 2;
- tmp = (right >>> -16 ^ left) & 65535;
- left ^= tmp;
- right ^= tmp << -16;
- tmp = (left >>> 1 ^ right) & 1431655765;
- right ^= tmp;
- left ^= tmp << 1;
- tmp = (right >>> 8 ^ left) & 16711935;
- left ^= tmp;
- right ^= tmp << 8;
- tmp = (left >>> 1 ^ right) & 1431655765;
- right ^= tmp;
- left ^= tmp << 1;
- tmp = left << 8 | right >>> 20 & 240;
- left = right << 24 | right << 8 & 16711680 | right >>> 8 & 65280 | right >>> 24 & 240;
- right = tmp;
- for (var i6 = 0;i6 < shifts.length; ++i6) {
- if (shifts[i6]) {
- left = left << 2 | left >>> 26;
- right = right << 2 | right >>> 26;
- } else {
- left = left << 1 | left >>> 27;
- right = right << 1 | right >>> 27;
- }
- left &= -15;
- right &= -15;
- var lefttmp = pc2bytes0[left >>> 28] | pc2bytes1[left >>> 24 & 15] | pc2bytes2[left >>> 20 & 15] | pc2bytes3[left >>> 16 & 15] | pc2bytes4[left >>> 12 & 15] | pc2bytes5[left >>> 8 & 15] | pc2bytes6[left >>> 4 & 15];
- var righttmp = pc2bytes7[right >>> 28] | pc2bytes8[right >>> 24 & 15] | pc2bytes9[right >>> 20 & 15] | pc2bytes10[right >>> 16 & 15] | pc2bytes11[right >>> 12 & 15] | pc2bytes12[right >>> 8 & 15] | pc2bytes13[right >>> 4 & 15];
- tmp = (righttmp >>> 16 ^ lefttmp) & 65535;
- keys2[n5++] = lefttmp ^ tmp;
- keys2[n5++] = righttmp ^ tmp << 16;
- }
- }
- return keys2;
- }
- function _updateBlock(keys2, input, output, decrypt2) {
- var iterations = keys2.length === 32 ? 3 : 9;
- var looping;
- if (iterations === 3) {
- looping = decrypt2 ? [30, -2, -2] : [0, 32, 2];
- } else {
- looping = decrypt2 ? [94, 62, -2, 32, 64, 2, 30, -2, -2] : [0, 32, 2, 62, 30, -2, 64, 96, 2];
- }
- var tmp;
- var left = input[0];
- var right = input[1];
- tmp = (left >>> 4 ^ right) & 252645135;
- right ^= tmp;
- left ^= tmp << 4;
- tmp = (left >>> 16 ^ right) & 65535;
- right ^= tmp;
- left ^= tmp << 16;
- tmp = (right >>> 2 ^ left) & 858993459;
- left ^= tmp;
- right ^= tmp << 2;
- tmp = (right >>> 8 ^ left) & 16711935;
- left ^= tmp;
- right ^= tmp << 8;
- tmp = (left >>> 1 ^ right) & 1431655765;
- right ^= tmp;
- left ^= tmp << 1;
- left = left << 1 | left >>> 31;
- right = right << 1 | right >>> 31;
- for (var j4 = 0;j4 < iterations; j4 += 3) {
- var endloop = looping[j4 + 1];
- var loopinc = looping[j4 + 2];
- for (var i6 = looping[j4];i6 != endloop; i6 += loopinc) {
- var right1 = right ^ keys2[i6];
- var right2 = (right >>> 4 | right << 28) ^ keys2[i6 + 1];
- tmp = left;
- left = right;
- right = tmp ^ (spfunction2[right1 >>> 24 & 63] | spfunction4[right1 >>> 16 & 63] | spfunction6[right1 >>> 8 & 63] | spfunction8[right1 & 63] | spfunction1[right2 >>> 24 & 63] | spfunction3[right2 >>> 16 & 63] | spfunction5[right2 >>> 8 & 63] | spfunction7[right2 & 63]);
- }
- tmp = left;
- left = right;
- right = tmp;
- }
- left = left >>> 1 | left << 31;
- right = right >>> 1 | right << 31;
- tmp = (left >>> 1 ^ right) & 1431655765;
- right ^= tmp;
- left ^= tmp << 1;
- tmp = (right >>> 8 ^ left) & 16711935;
- left ^= tmp;
- right ^= tmp << 8;
- tmp = (right >>> 2 ^ left) & 858993459;
- left ^= tmp;
- right ^= tmp << 2;
- tmp = (left >>> 16 ^ right) & 65535;
- right ^= tmp;
- left ^= tmp << 16;
- tmp = (left >>> 4 ^ right) & 252645135;
- right ^= tmp;
- left ^= tmp << 4;
- output[0] = left;
- output[1] = right;
- }
- function _createCipher(options2) {
- options2 = options2 || {};
- var mode = (options2.mode || "CBC").toUpperCase();
- var algorithm = "DES-" + mode;
- var cipher;
- if (options2.decrypt) {
- cipher = forge.cipher.createDecipher(algorithm, options2.key);
- } else {
- cipher = forge.cipher.createCipher(algorithm, options2.key);
- }
- var start = cipher.start;
- cipher.start = function(iv, options3) {
- var output = null;
- if (options3 instanceof forge.util.ByteBuffer) {
- output = options3;
- options3 = {};
- }
- options3 = options3 || {};
- options3.output = output;
- options3.iv = iv;
- start.call(cipher, options3);
- };
- return cipher;
- }
-});
-
-// node_modules/node-forge/lib/pbkdf2.js
-var require_pbkdf2 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_hmac();
- require_md();
- require_util3();
- var pkcs5 = forge.pkcs5 = forge.pkcs5 || {};
- var crypto11;
- if (forge.util.isNodejs && !forge.options.usePureJavaScript) {
- crypto11 = __require("crypto");
- }
- module.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(p4, s4, c8, dkLen, md, callback) {
- if (typeof md === "function") {
- callback = md;
- md = null;
- }
- if (forge.util.isNodejs && !forge.options.usePureJavaScript && crypto11.pbkdf2 && (md === null || typeof md !== "object") && (crypto11.pbkdf2Sync.length > 4 || (!md || md === "sha1"))) {
- if (typeof md !== "string") {
- md = "sha1";
- }
- p4 = Buffer.from(p4, "binary");
- s4 = Buffer.from(s4, "binary");
- if (!callback) {
- if (crypto11.pbkdf2Sync.length === 4) {
- return crypto11.pbkdf2Sync(p4, s4, c8, dkLen).toString("binary");
- }
- return crypto11.pbkdf2Sync(p4, s4, c8, dkLen, md).toString("binary");
- }
- if (crypto11.pbkdf2Sync.length === 4) {
- return crypto11.pbkdf2(p4, s4, c8, dkLen, function(err3, key2) {
- if (err3) {
- return callback(err3);
- }
- callback(null, key2.toString("binary"));
- });
- }
- return crypto11.pbkdf2(p4, s4, c8, dkLen, md, function(err3, key2) {
- if (err3) {
- return callback(err3);
- }
- callback(null, key2.toString("binary"));
- });
- }
- if (typeof md === "undefined" || md === null) {
- md = "sha1";
- }
- if (typeof md === "string") {
- if (!(md in forge.md.algorithms)) {
- throw new Error("Unknown hash algorithm: " + md);
- }
- md = forge.md[md].create();
- }
- var hLen = md.digestLength;
- if (dkLen > 4294967295 * hLen) {
- var err2 = new Error("Derived key is too long.");
- if (callback) {
- return callback(err2);
- }
- throw err2;
- }
- var len = Math.ceil(dkLen / hLen);
- var r4 = dkLen - (len - 1) * hLen;
- var prf = forge.hmac.create();
- prf.start(md, p4);
- var dk = "";
- var xor, u_c, u_c1;
- if (!callback) {
- for (var i6 = 1;i6 <= len; ++i6) {
- prf.start(null, null);
- prf.update(s4);
- prf.update(forge.util.int32ToBytes(i6));
- xor = u_c1 = prf.digest().getBytes();
- for (var j4 = 2;j4 <= c8; ++j4) {
- prf.start(null, null);
- prf.update(u_c1);
- u_c = prf.digest().getBytes();
- xor = forge.util.xorBytes(xor, u_c, hLen);
- u_c1 = u_c;
- }
- dk += i6 < len ? xor : xor.substr(0, r4);
- }
- return dk;
- }
- var i6 = 1, j4;
- function outer() {
- if (i6 > len) {
- return callback(null, dk);
- }
- prf.start(null, null);
- prf.update(s4);
- prf.update(forge.util.int32ToBytes(i6));
- xor = u_c1 = prf.digest().getBytes();
- j4 = 2;
- inner();
- }
- function inner() {
- if (j4 <= c8) {
- prf.start(null, null);
- prf.update(u_c1);
- u_c = prf.digest().getBytes();
- xor = forge.util.xorBytes(xor, u_c, hLen);
- u_c1 = u_c;
- ++j4;
- return forge.util.setImmediate(inner);
- }
- dk += i6 < len ? xor : xor.substr(0, r4);
- ++i6;
- outer();
- }
- outer();
- };
-});
-
-// node_modules/node-forge/lib/sha256.js
-var require_sha256 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_md();
- require_util3();
- var sha256 = module.exports = forge.sha256 = forge.sha256 || {};
- forge.md.sha256 = forge.md.algorithms.sha256 = sha256;
- sha256.create = function() {
- if (!_initialized) {
- _init();
- }
- var _state = null;
- var _input = forge.util.createBuffer();
- var _w3 = new Array(64);
- var md = {
- algorithm: "sha256",
- blockLength: 64,
- digestLength: 32,
- messageLength: 0,
- fullMessageLength: null,
- messageLengthSize: 8
- };
- md.start = function() {
- md.messageLength = 0;
- md.fullMessageLength = md.messageLength64 = [];
- var int32s = md.messageLengthSize / 4;
- for (var i6 = 0;i6 < int32s; ++i6) {
- md.fullMessageLength.push(0);
- }
- _input = forge.util.createBuffer();
- _state = {
- h0: 1779033703,
- h1: 3144134277,
- h2: 1013904242,
- h3: 2773480762,
- h4: 1359893119,
- h5: 2600822924,
- h6: 528734635,
- h7: 1541459225
- };
- return md;
- };
- md.start();
- md.update = function(msg, encoding) {
- if (encoding === "utf8") {
- msg = forge.util.encodeUtf8(msg);
- }
- var len = msg.length;
- md.messageLength += len;
- len = [len / 4294967296 >>> 0, len >>> 0];
- for (var i6 = md.fullMessageLength.length - 1;i6 >= 0; --i6) {
- md.fullMessageLength[i6] += len[1];
- len[1] = len[0] + (md.fullMessageLength[i6] / 4294967296 >>> 0);
- md.fullMessageLength[i6] = md.fullMessageLength[i6] >>> 0;
- len[0] = len[1] / 4294967296 >>> 0;
- }
- _input.putBytes(msg);
- _update(_state, _w3, _input);
- if (_input.read > 2048 || _input.length() === 0) {
- _input.compact();
- }
- return md;
- };
- md.digest = function() {
- var finalBlock = forge.util.createBuffer();
- finalBlock.putBytes(_input.bytes());
- var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize;
- var overflow = remaining & md.blockLength - 1;
- finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
- var next, carry;
- var bits2 = md.fullMessageLength[0] * 8;
- for (var i6 = 0;i6 < md.fullMessageLength.length - 1; ++i6) {
- next = md.fullMessageLength[i6 + 1] * 8;
- carry = next / 4294967296 >>> 0;
- bits2 += carry;
- finalBlock.putInt32(bits2 >>> 0);
- bits2 = next >>> 0;
- }
- finalBlock.putInt32(bits2);
- var s22 = {
- h0: _state.h0,
- h1: _state.h1,
- h2: _state.h2,
- h3: _state.h3,
- h4: _state.h4,
- h5: _state.h5,
- h6: _state.h6,
- h7: _state.h7
- };
- _update(s22, _w3, finalBlock);
- var rval = forge.util.createBuffer();
- rval.putInt32(s22.h0);
- rval.putInt32(s22.h1);
- rval.putInt32(s22.h2);
- rval.putInt32(s22.h3);
- rval.putInt32(s22.h4);
- rval.putInt32(s22.h5);
- rval.putInt32(s22.h6);
- rval.putInt32(s22.h7);
- return rval;
- };
- return md;
- };
- var _padding = null;
- var _initialized = false;
- var _k3 = null;
- function _init() {
- _padding = String.fromCharCode(128);
- _padding += forge.util.fillString(String.fromCharCode(0), 64);
- _k3 = [
- 1116352408,
- 1899447441,
- 3049323471,
- 3921009573,
- 961987163,
- 1508970993,
- 2453635748,
- 2870763221,
- 3624381080,
- 310598401,
- 607225278,
- 1426881987,
- 1925078388,
- 2162078206,
- 2614888103,
- 3248222580,
- 3835390401,
- 4022224774,
- 264347078,
- 604807628,
- 770255983,
- 1249150122,
- 1555081692,
- 1996064986,
- 2554220882,
- 2821834349,
- 2952996808,
- 3210313671,
- 3336571891,
- 3584528711,
- 113926993,
- 338241895,
- 666307205,
- 773529912,
- 1294757372,
- 1396182291,
- 1695183700,
- 1986661051,
- 2177026350,
- 2456956037,
- 2730485921,
- 2820302411,
- 3259730800,
- 3345764771,
- 3516065817,
- 3600352804,
- 4094571909,
- 275423344,
- 430227734,
- 506948616,
- 659060556,
- 883997877,
- 958139571,
- 1322822218,
- 1537002063,
- 1747873779,
- 1955562222,
- 2024104815,
- 2227730452,
- 2361852424,
- 2428436474,
- 2756734187,
- 3204031479,
- 3329325298
- ];
- _initialized = true;
- }
- function _update(s4, w2, bytes) {
- var t1, t22, s0, s1, ch2, maj, i6, a5, b5, c8, d4, e4, f4, g4, h5;
- var len = bytes.length();
- while (len >= 64) {
- for (i6 = 0;i6 < 16; ++i6) {
- w2[i6] = bytes.getInt32();
- }
- for (;i6 < 64; ++i6) {
- t1 = w2[i6 - 2];
- t1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10;
- t22 = w2[i6 - 15];
- t22 = (t22 >>> 7 | t22 << 25) ^ (t22 >>> 18 | t22 << 14) ^ t22 >>> 3;
- w2[i6] = t1 + w2[i6 - 7] + t22 + w2[i6 - 16] | 0;
- }
- a5 = s4.h0;
- b5 = s4.h1;
- c8 = s4.h2;
- d4 = s4.h3;
- e4 = s4.h4;
- f4 = s4.h5;
- g4 = s4.h6;
- h5 = s4.h7;
- for (i6 = 0;i6 < 64; ++i6) {
- s1 = (e4 >>> 6 | e4 << 26) ^ (e4 >>> 11 | e4 << 21) ^ (e4 >>> 25 | e4 << 7);
- ch2 = g4 ^ e4 & (f4 ^ g4);
- s0 = (a5 >>> 2 | a5 << 30) ^ (a5 >>> 13 | a5 << 19) ^ (a5 >>> 22 | a5 << 10);
- maj = a5 & b5 | c8 & (a5 ^ b5);
- t1 = h5 + s1 + ch2 + _k3[i6] + w2[i6];
- t22 = s0 + maj;
- h5 = g4;
- g4 = f4;
- f4 = e4;
- e4 = d4 + t1 >>> 0;
- d4 = c8;
- c8 = b5;
- b5 = a5;
- a5 = t1 + t22 >>> 0;
- }
- s4.h0 = s4.h0 + a5 | 0;
- s4.h1 = s4.h1 + b5 | 0;
- s4.h2 = s4.h2 + c8 | 0;
- s4.h3 = s4.h3 + d4 | 0;
- s4.h4 = s4.h4 + e4 | 0;
- s4.h5 = s4.h5 + f4 | 0;
- s4.h6 = s4.h6 + g4 | 0;
- s4.h7 = s4.h7 + h5 | 0;
- len -= 64;
- }
- }
-});
-
-// node_modules/node-forge/lib/prng.js
-var require_prng = __commonJS((exports, module) => {
- var forge = require_forge();
- require_util3();
- var _crypto = null;
- if (forge.util.isNodejs && !forge.options.usePureJavaScript && !process.versions["node-webkit"]) {
- _crypto = __require("crypto");
- }
- var prng = module.exports = forge.prng = forge.prng || {};
- prng.create = function(plugin) {
- var ctx = {
- plugin,
- key: null,
- seed: null,
- time: null,
- reseeds: 0,
- generated: 0,
- keyBytes: ""
- };
- var md = plugin.md;
- var pools = new Array(32);
- for (var i6 = 0;i6 < 32; ++i6) {
- pools[i6] = md.create();
- }
- ctx.pools = pools;
- ctx.pool = 0;
- ctx.generate = function(count3, callback) {
- if (!callback) {
- return ctx.generateSync(count3);
- }
- var cipher = ctx.plugin.cipher;
- var increment2 = ctx.plugin.increment;
- var formatKey = ctx.plugin.formatKey;
- var formatSeed = ctx.plugin.formatSeed;
- var b5 = forge.util.createBuffer();
- ctx.key = null;
- generate5();
- function generate5(err2) {
- if (err2) {
- return callback(err2);
- }
- if (b5.length() >= count3) {
- return callback(null, b5.getBytes(count3));
- }
- if (ctx.generated > 1048575) {
- ctx.key = null;
- }
- if (ctx.key === null) {
- return forge.util.nextTick(function() {
- _reseed(generate5);
- });
- }
- var bytes = cipher(ctx.key, ctx.seed);
- ctx.generated += bytes.length;
- b5.putBytes(bytes);
- ctx.key = formatKey(cipher(ctx.key, increment2(ctx.seed)));
- ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));
- forge.util.setImmediate(generate5);
- }
- };
- ctx.generateSync = function(count3) {
- var cipher = ctx.plugin.cipher;
- var increment2 = ctx.plugin.increment;
- var formatKey = ctx.plugin.formatKey;
- var formatSeed = ctx.plugin.formatSeed;
- ctx.key = null;
- var b5 = forge.util.createBuffer();
- while (b5.length() < count3) {
- if (ctx.generated > 1048575) {
- ctx.key = null;
- }
- if (ctx.key === null) {
- _reseedSync();
- }
- var bytes = cipher(ctx.key, ctx.seed);
- ctx.generated += bytes.length;
- b5.putBytes(bytes);
- ctx.key = formatKey(cipher(ctx.key, increment2(ctx.seed)));
- ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));
- }
- return b5.getBytes(count3);
- };
- function _reseed(callback) {
- if (ctx.pools[0].messageLength >= 32) {
- _seed();
- return callback();
- }
- var needed = 32 - ctx.pools[0].messageLength << 5;
- ctx.seedFile(needed, function(err2, bytes) {
- if (err2) {
- return callback(err2);
- }
- ctx.collect(bytes);
- _seed();
- callback();
- });
- }
- function _reseedSync() {
- if (ctx.pools[0].messageLength >= 32) {
- return _seed();
- }
- var needed = 32 - ctx.pools[0].messageLength << 5;
- ctx.collect(ctx.seedFileSync(needed));
- _seed();
- }
- function _seed() {
- ctx.reseeds = ctx.reseeds === 4294967295 ? 0 : ctx.reseeds + 1;
- var md2 = ctx.plugin.md.create();
- md2.update(ctx.keyBytes);
- var _2powK = 1;
- for (var k4 = 0;k4 < 32; ++k4) {
- if (ctx.reseeds % _2powK === 0) {
- md2.update(ctx.pools[k4].digest().getBytes());
- ctx.pools[k4].start();
- }
- _2powK = _2powK << 1;
- }
- ctx.keyBytes = md2.digest().getBytes();
- md2.start();
- md2.update(ctx.keyBytes);
- var seedBytes = md2.digest().getBytes();
- ctx.key = ctx.plugin.formatKey(ctx.keyBytes);
- ctx.seed = ctx.plugin.formatSeed(seedBytes);
- ctx.generated = 0;
- }
- function defaultSeedFile(needed) {
- var getRandomValues = null;
- var globalScope = forge.util.globalScope;
- var _crypto2 = globalScope.crypto || globalScope.msCrypto;
- if (_crypto2 && _crypto2.getRandomValues) {
- getRandomValues = function(arr) {
- return _crypto2.getRandomValues(arr);
- };
- }
- var b5 = forge.util.createBuffer();
- if (getRandomValues) {
- while (b5.length() < needed) {
- var count3 = Math.max(1, Math.min(needed - b5.length(), 65536) / 4);
- var entropy = new Uint32Array(Math.floor(count3));
- try {
- getRandomValues(entropy);
- for (var i7 = 0;i7 < entropy.length; ++i7) {
- b5.putInt32(entropy[i7]);
- }
- } catch (e4) {
- if (!(typeof QuotaExceededError !== "undefined" && e4 instanceof QuotaExceededError)) {
- throw e4;
- }
- }
- }
- }
- if (b5.length() < needed) {
- var hi, lo, next;
- var seed = Math.floor(Math.random() * 65536);
- while (b5.length() < needed) {
- lo = 16807 * (seed & 65535);
- hi = 16807 * (seed >> 16);
- lo += (hi & 32767) << 16;
- lo += hi >> 15;
- lo = (lo & 2147483647) + (lo >> 31);
- seed = lo & 4294967295;
- for (var i7 = 0;i7 < 3; ++i7) {
- next = seed >>> (i7 << 3);
- next ^= Math.floor(Math.random() * 256);
- b5.putByte(next & 255);
- }
- }
- }
- return b5.getBytes(needed);
- }
- if (_crypto) {
- ctx.seedFile = function(needed, callback) {
- _crypto.randomBytes(needed, function(err2, bytes) {
- if (err2) {
- return callback(err2);
- }
- callback(null, bytes.toString());
- });
- };
- ctx.seedFileSync = function(needed) {
- return _crypto.randomBytes(needed).toString();
- };
- } else {
- ctx.seedFile = function(needed, callback) {
- try {
- callback(null, defaultSeedFile(needed));
- } catch (e4) {
- callback(e4);
- }
- };
- ctx.seedFileSync = defaultSeedFile;
- }
- ctx.collect = function(bytes) {
- var count3 = bytes.length;
- for (var i7 = 0;i7 < count3; ++i7) {
- ctx.pools[ctx.pool].update(bytes.substr(i7, 1));
- ctx.pool = ctx.pool === 31 ? 0 : ctx.pool + 1;
- }
- };
- ctx.collectInt = function(i7, n5) {
- var bytes = "";
- for (var x4 = 0;x4 < n5; x4 += 8) {
- bytes += String.fromCharCode(i7 >> x4 & 255);
- }
- ctx.collect(bytes);
- };
- ctx.registerWorker = function(worker) {
- if (worker === self) {
- ctx.seedFile = function(needed, callback) {
- function listener2(e4) {
- var data = e4.data;
- if (data.forge && data.forge.prng) {
- self.removeEventListener("message", listener2);
- callback(data.forge.prng.err, data.forge.prng.bytes);
- }
- }
- self.addEventListener("message", listener2);
- self.postMessage({ forge: { prng: { needed } } });
- };
- } else {
- var listener = function(e4) {
- var data = e4.data;
- if (data.forge && data.forge.prng) {
- ctx.seedFile(data.forge.prng.needed, function(err2, bytes) {
- worker.postMessage({ forge: { prng: { err: err2, bytes } } });
- });
- }
- };
- worker.addEventListener("message", listener);
- }
- };
- return ctx;
- };
-});
-
-// node_modules/node-forge/lib/random.js
-var require_random = __commonJS((exports, module) => {
- var forge = require_forge();
- require_aes();
- require_sha256();
- require_prng();
- require_util3();
- (function() {
- if (forge.random && forge.random.getBytes) {
- module.exports = forge.random;
- return;
- }
- (function(jQuery2) {
- var prng_aes = {};
- var _prng_aes_output = new Array(4);
- var _prng_aes_buffer = forge.util.createBuffer();
- prng_aes.formatKey = function(key3) {
- var tmp = forge.util.createBuffer(key3);
- key3 = new Array(4);
- key3[0] = tmp.getInt32();
- key3[1] = tmp.getInt32();
- key3[2] = tmp.getInt32();
- key3[3] = tmp.getInt32();
- return forge.aes._expandKey(key3, false);
- };
- prng_aes.formatSeed = function(seed) {
- var tmp = forge.util.createBuffer(seed);
- seed = new Array(4);
- seed[0] = tmp.getInt32();
- seed[1] = tmp.getInt32();
- seed[2] = tmp.getInt32();
- seed[3] = tmp.getInt32();
- return seed;
- };
- prng_aes.cipher = function(key3, seed) {
- forge.aes._updateBlock(key3, seed, _prng_aes_output, false);
- _prng_aes_buffer.putInt32(_prng_aes_output[0]);
- _prng_aes_buffer.putInt32(_prng_aes_output[1]);
- _prng_aes_buffer.putInt32(_prng_aes_output[2]);
- _prng_aes_buffer.putInt32(_prng_aes_output[3]);
- return _prng_aes_buffer.getBytes();
- };
- prng_aes.increment = function(seed) {
- ++seed[3];
- return seed;
- };
- prng_aes.md = forge.md.sha256;
- function spawnPrng() {
- var ctx = forge.prng.create(prng_aes);
- ctx.getBytes = function(count3, callback) {
- return ctx.generate(count3, callback);
- };
- ctx.getBytesSync = function(count3) {
- return ctx.generate(count3);
- };
- return ctx;
- }
- var _ctx = spawnPrng();
- var getRandomValues = null;
- var globalScope = forge.util.globalScope;
- var _crypto = globalScope.crypto || globalScope.msCrypto;
- if (_crypto && _crypto.getRandomValues) {
- getRandomValues = function(arr) {
- return _crypto.getRandomValues(arr);
- };
- }
- if (forge.options.usePureJavaScript || !forge.util.isNodejs && !getRandomValues) {
- if (typeof window === "undefined" || window.document === undefined) {}
- _ctx.collectInt(+new Date, 32);
- if (typeof navigator !== "undefined") {
- var _navBytes = "";
- for (var key2 in navigator) {
- try {
- if (typeof navigator[key2] == "string") {
- _navBytes += navigator[key2];
- }
- } catch (e4) {}
- }
- _ctx.collect(_navBytes);
- _navBytes = null;
- }
- if (jQuery2) {
- jQuery2().mousemove(function(e4) {
- _ctx.collectInt(e4.clientX, 16);
- _ctx.collectInt(e4.clientY, 16);
- });
- jQuery2().keypress(function(e4) {
- _ctx.collectInt(e4.charCode, 8);
- });
- }
- }
- if (!forge.random) {
- forge.random = _ctx;
- } else {
- for (var key2 in _ctx) {
- forge.random[key2] = _ctx[key2];
- }
- }
- forge.random.createInstance = spawnPrng;
- module.exports = forge.random;
- })(typeof jQuery !== "undefined" ? jQuery : null);
- })();
-});
-
-// node_modules/node-forge/lib/rc2.js
-var require_rc2 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_util3();
- var piTable = [
- 217,
- 120,
- 249,
- 196,
- 25,
- 221,
- 181,
- 237,
- 40,
- 233,
- 253,
- 121,
- 74,
- 160,
- 216,
- 157,
- 198,
- 126,
- 55,
- 131,
- 43,
- 118,
- 83,
- 142,
- 98,
- 76,
- 100,
- 136,
- 68,
- 139,
- 251,
- 162,
- 23,
- 154,
- 89,
- 245,
- 135,
- 179,
- 79,
- 19,
- 97,
- 69,
- 109,
- 141,
- 9,
- 129,
- 125,
- 50,
- 189,
- 143,
- 64,
- 235,
- 134,
- 183,
- 123,
- 11,
- 240,
- 149,
- 33,
- 34,
- 92,
- 107,
- 78,
- 130,
- 84,
- 214,
- 101,
- 147,
- 206,
- 96,
- 178,
- 28,
- 115,
- 86,
- 192,
- 20,
- 167,
- 140,
- 241,
- 220,
- 18,
- 117,
- 202,
- 31,
- 59,
- 190,
- 228,
- 209,
- 66,
- 61,
- 212,
- 48,
- 163,
- 60,
- 182,
- 38,
- 111,
- 191,
- 14,
- 218,
- 70,
- 105,
- 7,
- 87,
- 39,
- 242,
- 29,
- 155,
- 188,
- 148,
- 67,
- 3,
- 248,
- 17,
- 199,
- 246,
- 144,
- 239,
- 62,
- 231,
- 6,
- 195,
- 213,
- 47,
- 200,
- 102,
- 30,
- 215,
- 8,
- 232,
- 234,
- 222,
- 128,
- 82,
- 238,
- 247,
- 132,
- 170,
- 114,
- 172,
- 53,
- 77,
- 106,
- 42,
- 150,
- 26,
- 210,
- 113,
- 90,
- 21,
- 73,
- 116,
- 75,
- 159,
- 208,
- 94,
- 4,
- 24,
- 164,
- 236,
- 194,
- 224,
- 65,
- 110,
- 15,
- 81,
- 203,
- 204,
- 36,
- 145,
- 175,
- 80,
- 161,
- 244,
- 112,
- 57,
- 153,
- 124,
- 58,
- 133,
- 35,
- 184,
- 180,
- 122,
- 252,
- 2,
- 54,
- 91,
- 37,
- 85,
- 151,
- 49,
- 45,
- 93,
- 250,
- 152,
- 227,
- 138,
- 146,
- 174,
- 5,
- 223,
- 41,
- 16,
- 103,
- 108,
- 186,
- 201,
- 211,
- 0,
- 230,
- 207,
- 225,
- 158,
- 168,
- 44,
- 99,
- 22,
- 1,
- 63,
- 88,
- 226,
- 137,
- 169,
- 13,
- 56,
- 52,
- 27,
- 171,
- 51,
- 255,
- 176,
- 187,
- 72,
- 12,
- 95,
- 185,
- 177,
- 205,
- 46,
- 197,
- 243,
- 219,
- 71,
- 229,
- 165,
- 156,
- 119,
- 10,
- 166,
- 32,
- 104,
- 254,
- 127,
- 193,
- 173
- ];
- var s4 = [1, 2, 3, 5];
- var rol = function(word, bits2) {
- return word << bits2 & 65535 | (word & 65535) >> 16 - bits2;
- };
- var ror = function(word, bits2) {
- return (word & 65535) >> bits2 | word << 16 - bits2 & 65535;
- };
- module.exports = forge.rc2 = forge.rc2 || {};
- forge.rc2.expandKey = function(key2, effKeyBits) {
- if (typeof key2 === "string") {
- key2 = forge.util.createBuffer(key2);
- }
- effKeyBits = effKeyBits || 128;
- var L2 = key2;
- var T = key2.length();
- var T1 = effKeyBits;
- var T8 = Math.ceil(T1 / 8);
- var TM = 255 >> (T1 & 7);
- var i6;
- for (i6 = T;i6 < 128; i6++) {
- L2.putByte(piTable[L2.at(i6 - 1) + L2.at(i6 - T) & 255]);
- }
- L2.setAt(128 - T8, piTable[L2.at(128 - T8) & TM]);
- for (i6 = 127 - T8;i6 >= 0; i6--) {
- L2.setAt(i6, piTable[L2.at(i6 + 1) ^ L2.at(i6 + T8)]);
- }
- return L2;
- };
- var createCipher = function(key2, bits2, encrypt) {
- var _finish = false, _input = null, _output = null, _iv = null;
- var mixRound, mashRound;
- var i6, j4, K = [];
- key2 = forge.rc2.expandKey(key2, bits2);
- for (i6 = 0;i6 < 64; i6++) {
- K.push(key2.getInt16Le());
- }
- if (encrypt) {
- mixRound = function(R2) {
- for (i6 = 0;i6 < 4; i6++) {
- R2[i6] += K[j4] + (R2[(i6 + 3) % 4] & R2[(i6 + 2) % 4]) + (~R2[(i6 + 3) % 4] & R2[(i6 + 1) % 4]);
- R2[i6] = rol(R2[i6], s4[i6]);
- j4++;
- }
- };
- mashRound = function(R2) {
- for (i6 = 0;i6 < 4; i6++) {
- R2[i6] += K[R2[(i6 + 3) % 4] & 63];
- }
- };
- } else {
- mixRound = function(R2) {
- for (i6 = 3;i6 >= 0; i6--) {
- R2[i6] = ror(R2[i6], s4[i6]);
- R2[i6] -= K[j4] + (R2[(i6 + 3) % 4] & R2[(i6 + 2) % 4]) + (~R2[(i6 + 3) % 4] & R2[(i6 + 1) % 4]);
- j4--;
- }
- };
- mashRound = function(R2) {
- for (i6 = 3;i6 >= 0; i6--) {
- R2[i6] -= K[R2[(i6 + 3) % 4] & 63];
- }
- };
- }
- var runPlan = function(plan) {
- var R2 = [];
- for (i6 = 0;i6 < 4; i6++) {
- var val = _input.getInt16Le();
- if (_iv !== null) {
- if (encrypt) {
- val ^= _iv.getInt16Le();
- } else {
- _iv.putInt16Le(val);
- }
- }
- R2.push(val & 65535);
- }
- j4 = encrypt ? 0 : 63;
- for (var ptr = 0;ptr < plan.length; ptr++) {
- for (var ctr = 0;ctr < plan[ptr][0]; ctr++) {
- plan[ptr][1](R2);
- }
- }
- for (i6 = 0;i6 < 4; i6++) {
- if (_iv !== null) {
- if (encrypt) {
- _iv.putInt16Le(R2[i6]);
- } else {
- R2[i6] ^= _iv.getInt16Le();
- }
- }
- _output.putInt16Le(R2[i6]);
- }
- };
- var cipher = null;
- cipher = {
- start: function(iv, output) {
- if (iv) {
- if (typeof iv === "string") {
- iv = forge.util.createBuffer(iv);
- }
- }
- _finish = false;
- _input = forge.util.createBuffer();
- _output = output || new forge.util.createBuffer;
- _iv = iv;
- cipher.output = _output;
- },
- update: function(input) {
- if (!_finish) {
- _input.putBuffer(input);
- }
- while (_input.length() >= 8) {
- runPlan([
- [5, mixRound],
- [1, mashRound],
- [6, mixRound],
- [1, mashRound],
- [5, mixRound]
- ]);
- }
- },
- finish: function(pad) {
- var rval = true;
- if (encrypt) {
- if (pad) {
- rval = pad(8, _input, !encrypt);
- } else {
- var padding = _input.length() === 8 ? 8 : 8 - _input.length();
- _input.fillWithByte(padding, padding);
- }
- }
- if (rval) {
- _finish = true;
- cipher.update();
- }
- if (!encrypt) {
- rval = _input.length() === 0;
- if (rval) {
- if (pad) {
- rval = pad(8, _output, !encrypt);
- } else {
- var len = _output.length();
- var count3 = _output.at(len - 1);
- if (count3 > len) {
- rval = false;
- } else {
- _output.truncate(count3);
- }
- }
- }
- }
- return rval;
- }
- };
- return cipher;
- };
- forge.rc2.startEncrypting = function(key2, iv, output) {
- var cipher = forge.rc2.createEncryptionCipher(key2, 128);
- cipher.start(iv, output);
- return cipher;
- };
- forge.rc2.createEncryptionCipher = function(key2, bits2) {
- return createCipher(key2, bits2, true);
- };
- forge.rc2.startDecrypting = function(key2, iv, output) {
- var cipher = forge.rc2.createDecryptionCipher(key2, 128);
- cipher.start(iv, output);
- return cipher;
- };
- forge.rc2.createDecryptionCipher = function(key2, bits2) {
- return createCipher(key2, bits2, false);
- };
-});
-
-// node_modules/node-forge/lib/jsbn.js
-var require_jsbn = __commonJS((exports, module) => {
- var forge = require_forge();
- module.exports = forge.jsbn = forge.jsbn || {};
- var dbits;
- var canary = 244837814094590;
- var j_lm = (canary & 16777215) == 15715070;
- function BigInteger(a5, b5, c8) {
- this.data = [];
- if (a5 != null)
- if (typeof a5 == "number")
- this.fromNumber(a5, b5, c8);
- else if (b5 == null && typeof a5 != "string")
- this.fromString(a5, 256);
- else
- this.fromString(a5, b5);
- }
- forge.jsbn.BigInteger = BigInteger;
- function nbi() {
- return new BigInteger(null);
- }
- function am1(i6, x4, w2, j4, c8, n5) {
- while (--n5 >= 0) {
- var v6 = x4 * this.data[i6++] + w2.data[j4] + c8;
- c8 = Math.floor(v6 / 67108864);
- w2.data[j4++] = v6 & 67108863;
- }
- return c8;
- }
- function am2(i6, x4, w2, j4, c8, n5) {
- var xl = x4 & 32767, xh = x4 >> 15;
- while (--n5 >= 0) {
- var l4 = this.data[i6] & 32767;
- var h5 = this.data[i6++] >> 15;
- var m4 = xh * l4 + h5 * xl;
- l4 = xl * l4 + ((m4 & 32767) << 15) + w2.data[j4] + (c8 & 1073741823);
- c8 = (l4 >>> 30) + (m4 >>> 15) + xh * h5 + (c8 >>> 30);
- w2.data[j4++] = l4 & 1073741823;
- }
- return c8;
- }
- function am3(i6, x4, w2, j4, c8, n5) {
- var xl = x4 & 16383, xh = x4 >> 14;
- while (--n5 >= 0) {
- var l4 = this.data[i6] & 16383;
- var h5 = this.data[i6++] >> 14;
- var m4 = xh * l4 + h5 * xl;
- l4 = xl * l4 + ((m4 & 16383) << 14) + w2.data[j4] + c8;
- c8 = (l4 >> 28) + (m4 >> 14) + xh * h5;
- w2.data[j4++] = l4 & 268435455;
- }
- return c8;
- }
- if (typeof navigator === "undefined") {
- BigInteger.prototype.am = am3;
- dbits = 28;
- } else if (j_lm && navigator.appName == "Microsoft Internet Explorer") {
- BigInteger.prototype.am = am2;
- dbits = 30;
- } else if (j_lm && navigator.appName != "Netscape") {
- BigInteger.prototype.am = am1;
- dbits = 26;
- } else {
- BigInteger.prototype.am = am3;
- dbits = 28;
- }
- BigInteger.prototype.DB = dbits;
- BigInteger.prototype.DM = (1 << dbits) - 1;
- BigInteger.prototype.DV = 1 << dbits;
- var BI_FP = 52;
- BigInteger.prototype.FV = Math.pow(2, BI_FP);
- BigInteger.prototype.F1 = BI_FP - dbits;
- BigInteger.prototype.F2 = 2 * dbits - BI_FP;
- var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
- var BI_RC = new Array;
- var rr;
- var vv;
- rr = 48;
- for (vv = 0;vv <= 9; ++vv)
- BI_RC[rr++] = vv;
- rr = 97;
- for (vv = 10;vv < 36; ++vv)
- BI_RC[rr++] = vv;
- rr = 65;
- for (vv = 10;vv < 36; ++vv)
- BI_RC[rr++] = vv;
- function int2char(n5) {
- return BI_RM.charAt(n5);
- }
- function intAt(s4, i6) {
- var c8 = BI_RC[s4.charCodeAt(i6)];
- return c8 == null ? -1 : c8;
- }
- function bnpCopyTo(r4) {
- for (var i6 = this.t - 1;i6 >= 0; --i6)
- r4.data[i6] = this.data[i6];
- r4.t = this.t;
- r4.s = this.s;
- }
- function bnpFromInt(x4) {
- this.t = 1;
- this.s = x4 < 0 ? -1 : 0;
- if (x4 > 0)
- this.data[0] = x4;
- else if (x4 < -1)
- this.data[0] = x4 + this.DV;
- else
- this.t = 0;
- }
- function nbv(i6) {
- var r4 = nbi();
- r4.fromInt(i6);
- return r4;
- }
- function bnpFromString(s4, b5) {
- var k4;
- if (b5 == 16)
- k4 = 4;
- else if (b5 == 8)
- k4 = 3;
- else if (b5 == 256)
- k4 = 8;
- else if (b5 == 2)
- k4 = 1;
- else if (b5 == 32)
- k4 = 5;
- else if (b5 == 4)
- k4 = 2;
- else {
- this.fromRadix(s4, b5);
- return;
- }
- this.t = 0;
- this.s = 0;
- var i6 = s4.length, mi = false, sh = 0;
- while (--i6 >= 0) {
- var x4 = k4 == 8 ? s4[i6] & 255 : intAt(s4, i6);
- if (x4 < 0) {
- if (s4.charAt(i6) == "-")
- mi = true;
- continue;
- }
- mi = false;
- if (sh == 0)
- this.data[this.t++] = x4;
- else if (sh + k4 > this.DB) {
- this.data[this.t - 1] |= (x4 & (1 << this.DB - sh) - 1) << sh;
- this.data[this.t++] = x4 >> this.DB - sh;
- } else
- this.data[this.t - 1] |= x4 << sh;
- sh += k4;
- if (sh >= this.DB)
- sh -= this.DB;
- }
- if (k4 == 8 && (s4[0] & 128) != 0) {
- this.s = -1;
- if (sh > 0)
- this.data[this.t - 1] |= (1 << this.DB - sh) - 1 << sh;
- }
- this.clamp();
- if (mi)
- BigInteger.ZERO.subTo(this, this);
- }
- function bnpClamp() {
- var c8 = this.s & this.DM;
- while (this.t > 0 && this.data[this.t - 1] == c8)
- --this.t;
- }
- function bnToString(b5) {
- if (this.s < 0)
- return "-" + this.negate().toString(b5);
- var k4;
- if (b5 == 16)
- k4 = 4;
- else if (b5 == 8)
- k4 = 3;
- else if (b5 == 2)
- k4 = 1;
- else if (b5 == 32)
- k4 = 5;
- else if (b5 == 4)
- k4 = 2;
- else
- return this.toRadix(b5);
- var km = (1 << k4) - 1, d4, m4 = false, r4 = "", i6 = this.t;
- var p4 = this.DB - i6 * this.DB % k4;
- if (i6-- > 0) {
- if (p4 < this.DB && (d4 = this.data[i6] >> p4) > 0) {
- m4 = true;
- r4 = int2char(d4);
- }
- while (i6 >= 0) {
- if (p4 < k4) {
- d4 = (this.data[i6] & (1 << p4) - 1) << k4 - p4;
- d4 |= this.data[--i6] >> (p4 += this.DB - k4);
- } else {
- d4 = this.data[i6] >> (p4 -= k4) & km;
- if (p4 <= 0) {
- p4 += this.DB;
- --i6;
- }
- }
- if (d4 > 0)
- m4 = true;
- if (m4)
- r4 += int2char(d4);
- }
- }
- return m4 ? r4 : "0";
- }
- function bnNegate() {
- var r4 = nbi();
- BigInteger.ZERO.subTo(this, r4);
- return r4;
- }
- function bnAbs() {
- return this.s < 0 ? this.negate() : this;
- }
- function bnCompareTo(a5) {
- var r4 = this.s - a5.s;
- if (r4 != 0)
- return r4;
- var i6 = this.t;
- r4 = i6 - a5.t;
- if (r4 != 0)
- return this.s < 0 ? -r4 : r4;
- while (--i6 >= 0)
- if ((r4 = this.data[i6] - a5.data[i6]) != 0)
- return r4;
- return 0;
- }
- function nbits(x4) {
- var r4 = 1, t4;
- if ((t4 = x4 >>> 16) != 0) {
- x4 = t4;
- r4 += 16;
- }
- if ((t4 = x4 >> 8) != 0) {
- x4 = t4;
- r4 += 8;
- }
- if ((t4 = x4 >> 4) != 0) {
- x4 = t4;
- r4 += 4;
- }
- if ((t4 = x4 >> 2) != 0) {
- x4 = t4;
- r4 += 2;
- }
- if ((t4 = x4 >> 1) != 0) {
- x4 = t4;
- r4 += 1;
- }
- return r4;
- }
- function bnBitLength() {
- if (this.t <= 0)
- return 0;
- return this.DB * (this.t - 1) + nbits(this.data[this.t - 1] ^ this.s & this.DM);
- }
- function bnpDLShiftTo(n5, r4) {
- var i6;
- for (i6 = this.t - 1;i6 >= 0; --i6)
- r4.data[i6 + n5] = this.data[i6];
- for (i6 = n5 - 1;i6 >= 0; --i6)
- r4.data[i6] = 0;
- r4.t = this.t + n5;
- r4.s = this.s;
- }
- function bnpDRShiftTo(n5, r4) {
- for (var i6 = n5;i6 < this.t; ++i6)
- r4.data[i6 - n5] = this.data[i6];
- r4.t = Math.max(this.t - n5, 0);
- r4.s = this.s;
- }
- function bnpLShiftTo(n5, r4) {
- var bs = n5 % this.DB;
- var cbs = this.DB - bs;
- var bm = (1 << cbs) - 1;
- var ds = Math.floor(n5 / this.DB), c8 = this.s << bs & this.DM, i6;
- for (i6 = this.t - 1;i6 >= 0; --i6) {
- r4.data[i6 + ds + 1] = this.data[i6] >> cbs | c8;
- c8 = (this.data[i6] & bm) << bs;
- }
- for (i6 = ds - 1;i6 >= 0; --i6)
- r4.data[i6] = 0;
- r4.data[ds] = c8;
- r4.t = this.t + ds + 1;
- r4.s = this.s;
- r4.clamp();
- }
- function bnpRShiftTo(n5, r4) {
- r4.s = this.s;
- var ds = Math.floor(n5 / this.DB);
- if (ds >= this.t) {
- r4.t = 0;
- return;
- }
- var bs = n5 % this.DB;
- var cbs = this.DB - bs;
- var bm = (1 << bs) - 1;
- r4.data[0] = this.data[ds] >> bs;
- for (var i6 = ds + 1;i6 < this.t; ++i6) {
- r4.data[i6 - ds - 1] |= (this.data[i6] & bm) << cbs;
- r4.data[i6 - ds] = this.data[i6] >> bs;
- }
- if (bs > 0)
- r4.data[this.t - ds - 1] |= (this.s & bm) << cbs;
- r4.t = this.t - ds;
- r4.clamp();
- }
- function bnpSubTo(a5, r4) {
- var i6 = 0, c8 = 0, m4 = Math.min(a5.t, this.t);
- while (i6 < m4) {
- c8 += this.data[i6] - a5.data[i6];
- r4.data[i6++] = c8 & this.DM;
- c8 >>= this.DB;
- }
- if (a5.t < this.t) {
- c8 -= a5.s;
- while (i6 < this.t) {
- c8 += this.data[i6];
- r4.data[i6++] = c8 & this.DM;
- c8 >>= this.DB;
- }
- c8 += this.s;
- } else {
- c8 += this.s;
- while (i6 < a5.t) {
- c8 -= a5.data[i6];
- r4.data[i6++] = c8 & this.DM;
- c8 >>= this.DB;
- }
- c8 -= a5.s;
- }
- r4.s = c8 < 0 ? -1 : 0;
- if (c8 < -1)
- r4.data[i6++] = this.DV + c8;
- else if (c8 > 0)
- r4.data[i6++] = c8;
- r4.t = i6;
- r4.clamp();
- }
- function bnpMultiplyTo(a5, r4) {
- var x4 = this.abs(), y3 = a5.abs();
- var i6 = x4.t;
- r4.t = i6 + y3.t;
- while (--i6 >= 0)
- r4.data[i6] = 0;
- for (i6 = 0;i6 < y3.t; ++i6)
- r4.data[i6 + x4.t] = x4.am(0, y3.data[i6], r4, i6, 0, x4.t);
- r4.s = 0;
- r4.clamp();
- if (this.s != a5.s)
- BigInteger.ZERO.subTo(r4, r4);
- }
- function bnpSquareTo(r4) {
- var x4 = this.abs();
- var i6 = r4.t = 2 * x4.t;
- while (--i6 >= 0)
- r4.data[i6] = 0;
- for (i6 = 0;i6 < x4.t - 1; ++i6) {
- var c8 = x4.am(i6, x4.data[i6], r4, 2 * i6, 0, 1);
- if ((r4.data[i6 + x4.t] += x4.am(i6 + 1, 2 * x4.data[i6], r4, 2 * i6 + 1, c8, x4.t - i6 - 1)) >= x4.DV) {
- r4.data[i6 + x4.t] -= x4.DV;
- r4.data[i6 + x4.t + 1] = 1;
- }
- }
- if (r4.t > 0)
- r4.data[r4.t - 1] += x4.am(i6, x4.data[i6], r4, 2 * i6, 0, 1);
- r4.s = 0;
- r4.clamp();
- }
- function bnpDivRemTo(m4, q4, r4) {
- var pm = m4.abs();
- if (pm.t <= 0)
- return;
- var pt = this.abs();
- if (pt.t < pm.t) {
- if (q4 != null)
- q4.fromInt(0);
- if (r4 != null)
- this.copyTo(r4);
- return;
- }
- if (r4 == null)
- r4 = nbi();
- var y3 = nbi(), ts = this.s, ms = m4.s;
- var nsh = this.DB - nbits(pm.data[pm.t - 1]);
- if (nsh > 0) {
- pm.lShiftTo(nsh, y3);
- pt.lShiftTo(nsh, r4);
- } else {
- pm.copyTo(y3);
- pt.copyTo(r4);
- }
- var ys = y3.t;
- var y0 = y3.data[ys - 1];
- if (y0 == 0)
- return;
- var yt = y0 * (1 << this.F1) + (ys > 1 ? y3.data[ys - 2] >> this.F2 : 0);
- var d1 = this.FV / yt, d22 = (1 << this.F1) / yt, e4 = 1 << this.F2;
- var i6 = r4.t, j4 = i6 - ys, t4 = q4 == null ? nbi() : q4;
- y3.dlShiftTo(j4, t4);
- if (r4.compareTo(t4) >= 0) {
- r4.data[r4.t++] = 1;
- r4.subTo(t4, r4);
- }
- BigInteger.ONE.dlShiftTo(ys, t4);
- t4.subTo(y3, y3);
- while (y3.t < ys)
- y3.data[y3.t++] = 0;
- while (--j4 >= 0) {
- var qd = r4.data[--i6] == y0 ? this.DM : Math.floor(r4.data[i6] * d1 + (r4.data[i6 - 1] + e4) * d22);
- if ((r4.data[i6] += y3.am(0, qd, r4, j4, 0, ys)) < qd) {
- y3.dlShiftTo(j4, t4);
- r4.subTo(t4, r4);
- while (r4.data[i6] < --qd)
- r4.subTo(t4, r4);
- }
- }
- if (q4 != null) {
- r4.drShiftTo(ys, q4);
- if (ts != ms)
- BigInteger.ZERO.subTo(q4, q4);
- }
- r4.t = ys;
- r4.clamp();
- if (nsh > 0)
- r4.rShiftTo(nsh, r4);
- if (ts < 0)
- BigInteger.ZERO.subTo(r4, r4);
- }
- function bnMod(a5) {
- var r4 = nbi();
- this.abs().divRemTo(a5, null, r4);
- if (this.s < 0 && r4.compareTo(BigInteger.ZERO) > 0)
- a5.subTo(r4, r4);
- return r4;
- }
- function Classic(m4) {
- this.m = m4;
- }
- function cConvert(x4) {
- if (x4.s < 0 || x4.compareTo(this.m) >= 0)
- return x4.mod(this.m);
- else
- return x4;
- }
- function cRevert(x4) {
- return x4;
- }
- function cReduce(x4) {
- x4.divRemTo(this.m, null, x4);
- }
- function cMulTo(x4, y3, r4) {
- x4.multiplyTo(y3, r4);
- this.reduce(r4);
- }
- function cSqrTo(x4, r4) {
- x4.squareTo(r4);
- this.reduce(r4);
- }
- Classic.prototype.convert = cConvert;
- Classic.prototype.revert = cRevert;
- Classic.prototype.reduce = cReduce;
- Classic.prototype.mulTo = cMulTo;
- Classic.prototype.sqrTo = cSqrTo;
- function bnpInvDigit() {
- if (this.t < 1)
- return 0;
- var x4 = this.data[0];
- if ((x4 & 1) == 0)
- return 0;
- var y3 = x4 & 3;
- y3 = y3 * (2 - (x4 & 15) * y3) & 15;
- y3 = y3 * (2 - (x4 & 255) * y3) & 255;
- y3 = y3 * (2 - ((x4 & 65535) * y3 & 65535)) & 65535;
- y3 = y3 * (2 - x4 * y3 % this.DV) % this.DV;
- return y3 > 0 ? this.DV - y3 : -y3;
- }
- function Montgomery(m4) {
- this.m = m4;
- this.mp = m4.invDigit();
- this.mpl = this.mp & 32767;
- this.mph = this.mp >> 15;
- this.um = (1 << m4.DB - 15) - 1;
- this.mt2 = 2 * m4.t;
- }
- function montConvert(x4) {
- var r4 = nbi();
- x4.abs().dlShiftTo(this.m.t, r4);
- r4.divRemTo(this.m, null, r4);
- if (x4.s < 0 && r4.compareTo(BigInteger.ZERO) > 0)
- this.m.subTo(r4, r4);
- return r4;
- }
- function montRevert(x4) {
- var r4 = nbi();
- x4.copyTo(r4);
- this.reduce(r4);
- return r4;
- }
- function montReduce(x4) {
- while (x4.t <= this.mt2)
- x4.data[x4.t++] = 0;
- for (var i6 = 0;i6 < this.m.t; ++i6) {
- var j4 = x4.data[i6] & 32767;
- var u0 = j4 * this.mpl + ((j4 * this.mph + (x4.data[i6] >> 15) * this.mpl & this.um) << 15) & x4.DM;
- j4 = i6 + this.m.t;
- x4.data[j4] += this.m.am(0, u0, x4, i6, 0, this.m.t);
- while (x4.data[j4] >= x4.DV) {
- x4.data[j4] -= x4.DV;
- x4.data[++j4]++;
- }
- }
- x4.clamp();
- x4.drShiftTo(this.m.t, x4);
- if (x4.compareTo(this.m) >= 0)
- x4.subTo(this.m, x4);
- }
- function montSqrTo(x4, r4) {
- x4.squareTo(r4);
- this.reduce(r4);
- }
- function montMulTo(x4, y3, r4) {
- x4.multiplyTo(y3, r4);
- this.reduce(r4);
- }
- Montgomery.prototype.convert = montConvert;
- Montgomery.prototype.revert = montRevert;
- Montgomery.prototype.reduce = montReduce;
- Montgomery.prototype.mulTo = montMulTo;
- Montgomery.prototype.sqrTo = montSqrTo;
- function bnpIsEven() {
- return (this.t > 0 ? this.data[0] & 1 : this.s) == 0;
- }
- function bnpExp(e4, z3) {
- if (e4 > 4294967295 || e4 < 1)
- return BigInteger.ONE;
- var r4 = nbi(), r22 = nbi(), g4 = z3.convert(this), i6 = nbits(e4) - 1;
- g4.copyTo(r4);
- while (--i6 >= 0) {
- z3.sqrTo(r4, r22);
- if ((e4 & 1 << i6) > 0)
- z3.mulTo(r22, g4, r4);
- else {
- var t4 = r4;
- r4 = r22;
- r22 = t4;
- }
- }
- return z3.revert(r4);
- }
- function bnModPowInt(e4, m4) {
- var z3;
- if (e4 < 256 || m4.isEven())
- z3 = new Classic(m4);
- else
- z3 = new Montgomery(m4);
- return this.exp(e4, z3);
- }
- BigInteger.prototype.copyTo = bnpCopyTo;
- BigInteger.prototype.fromInt = bnpFromInt;
- BigInteger.prototype.fromString = bnpFromString;
- BigInteger.prototype.clamp = bnpClamp;
- BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
- BigInteger.prototype.drShiftTo = bnpDRShiftTo;
- BigInteger.prototype.lShiftTo = bnpLShiftTo;
- BigInteger.prototype.rShiftTo = bnpRShiftTo;
- BigInteger.prototype.subTo = bnpSubTo;
- BigInteger.prototype.multiplyTo = bnpMultiplyTo;
- BigInteger.prototype.squareTo = bnpSquareTo;
- BigInteger.prototype.divRemTo = bnpDivRemTo;
- BigInteger.prototype.invDigit = bnpInvDigit;
- BigInteger.prototype.isEven = bnpIsEven;
- BigInteger.prototype.exp = bnpExp;
- BigInteger.prototype.toString = bnToString;
- BigInteger.prototype.negate = bnNegate;
- BigInteger.prototype.abs = bnAbs;
- BigInteger.prototype.compareTo = bnCompareTo;
- BigInteger.prototype.bitLength = bnBitLength;
- BigInteger.prototype.mod = bnMod;
- BigInteger.prototype.modPowInt = bnModPowInt;
- BigInteger.ZERO = nbv(0);
- BigInteger.ONE = nbv(1);
- function bnClone() {
- var r4 = nbi();
- this.copyTo(r4);
- return r4;
- }
- function bnIntValue() {
- if (this.s < 0) {
- if (this.t == 1)
- return this.data[0] - this.DV;
- else if (this.t == 0)
- return -1;
- } else if (this.t == 1)
- return this.data[0];
- else if (this.t == 0)
- return 0;
- return (this.data[1] & (1 << 32 - this.DB) - 1) << this.DB | this.data[0];
- }
- function bnByteValue() {
- return this.t == 0 ? this.s : this.data[0] << 24 >> 24;
- }
- function bnShortValue() {
- return this.t == 0 ? this.s : this.data[0] << 16 >> 16;
- }
- function bnpChunkSize(r4) {
- return Math.floor(Math.LN2 * this.DB / Math.log(r4));
- }
- function bnSigNum() {
- if (this.s < 0)
- return -1;
- else if (this.t <= 0 || this.t == 1 && this.data[0] <= 0)
- return 0;
- else
- return 1;
- }
- function bnpToRadix(b5) {
- if (b5 == null)
- b5 = 10;
- if (this.signum() == 0 || b5 < 2 || b5 > 36)
- return "0";
- var cs = this.chunkSize(b5);
- var a5 = Math.pow(b5, cs);
- var d4 = nbv(a5), y3 = nbi(), z3 = nbi(), r4 = "";
- this.divRemTo(d4, y3, z3);
- while (y3.signum() > 0) {
- r4 = (a5 + z3.intValue()).toString(b5).substr(1) + r4;
- y3.divRemTo(d4, y3, z3);
- }
- return z3.intValue().toString(b5) + r4;
- }
- function bnpFromRadix(s4, b5) {
- this.fromInt(0);
- if (b5 == null)
- b5 = 10;
- var cs = this.chunkSize(b5);
- var d4 = Math.pow(b5, cs), mi = false, j4 = 0, w2 = 0;
- for (var i6 = 0;i6 < s4.length; ++i6) {
- var x4 = intAt(s4, i6);
- if (x4 < 0) {
- if (s4.charAt(i6) == "-" && this.signum() == 0)
- mi = true;
- continue;
- }
- w2 = b5 * w2 + x4;
- if (++j4 >= cs) {
- this.dMultiply(d4);
- this.dAddOffset(w2, 0);
- j4 = 0;
- w2 = 0;
- }
- }
- if (j4 > 0) {
- this.dMultiply(Math.pow(b5, j4));
- this.dAddOffset(w2, 0);
- }
- if (mi)
- BigInteger.ZERO.subTo(this, this);
- }
- function bnpFromNumber(a5, b5, c8) {
- if (typeof b5 == "number") {
- if (a5 < 2)
- this.fromInt(1);
- else {
- this.fromNumber(a5, c8);
- if (!this.testBit(a5 - 1))
- this.bitwiseTo(BigInteger.ONE.shiftLeft(a5 - 1), op_or, this);
- if (this.isEven())
- this.dAddOffset(1, 0);
- while (!this.isProbablePrime(b5)) {
- this.dAddOffset(2, 0);
- if (this.bitLength() > a5)
- this.subTo(BigInteger.ONE.shiftLeft(a5 - 1), this);
- }
- }
- } else {
- var x4 = new Array, t4 = a5 & 7;
- x4.length = (a5 >> 3) + 1;
- b5.nextBytes(x4);
- if (t4 > 0)
- x4[0] &= (1 << t4) - 1;
- else
- x4[0] = 0;
- this.fromString(x4, 256);
- }
- }
- function bnToByteArray() {
- var i6 = this.t, r4 = new Array;
- r4[0] = this.s;
- var p4 = this.DB - i6 * this.DB % 8, d4, k4 = 0;
- if (i6-- > 0) {
- if (p4 < this.DB && (d4 = this.data[i6] >> p4) != (this.s & this.DM) >> p4)
- r4[k4++] = d4 | this.s << this.DB - p4;
- while (i6 >= 0) {
- if (p4 < 8) {
- d4 = (this.data[i6] & (1 << p4) - 1) << 8 - p4;
- d4 |= this.data[--i6] >> (p4 += this.DB - 8);
- } else {
- d4 = this.data[i6] >> (p4 -= 8) & 255;
- if (p4 <= 0) {
- p4 += this.DB;
- --i6;
- }
- }
- if ((d4 & 128) != 0)
- d4 |= -256;
- if (k4 == 0 && (this.s & 128) != (d4 & 128))
- ++k4;
- if (k4 > 0 || d4 != this.s)
- r4[k4++] = d4;
- }
- }
- return r4;
- }
- function bnEquals(a5) {
- return this.compareTo(a5) == 0;
- }
- function bnMin(a5) {
- return this.compareTo(a5) < 0 ? this : a5;
- }
- function bnMax(a5) {
- return this.compareTo(a5) > 0 ? this : a5;
- }
- function bnpBitwiseTo(a5, op, r4) {
- var i6, f4, m4 = Math.min(a5.t, this.t);
- for (i6 = 0;i6 < m4; ++i6)
- r4.data[i6] = op(this.data[i6], a5.data[i6]);
- if (a5.t < this.t) {
- f4 = a5.s & this.DM;
- for (i6 = m4;i6 < this.t; ++i6)
- r4.data[i6] = op(this.data[i6], f4);
- r4.t = this.t;
- } else {
- f4 = this.s & this.DM;
- for (i6 = m4;i6 < a5.t; ++i6)
- r4.data[i6] = op(f4, a5.data[i6]);
- r4.t = a5.t;
- }
- r4.s = op(this.s, a5.s);
- r4.clamp();
- }
- function op_and(x4, y3) {
- return x4 & y3;
- }
- function bnAnd(a5) {
- var r4 = nbi();
- this.bitwiseTo(a5, op_and, r4);
- return r4;
- }
- function op_or(x4, y3) {
- return x4 | y3;
- }
- function bnOr(a5) {
- var r4 = nbi();
- this.bitwiseTo(a5, op_or, r4);
- return r4;
- }
- function op_xor(x4, y3) {
- return x4 ^ y3;
- }
- function bnXor(a5) {
- var r4 = nbi();
- this.bitwiseTo(a5, op_xor, r4);
- return r4;
- }
- function op_andnot(x4, y3) {
- return x4 & ~y3;
- }
- function bnAndNot(a5) {
- var r4 = nbi();
- this.bitwiseTo(a5, op_andnot, r4);
- return r4;
- }
- function bnNot() {
- var r4 = nbi();
- for (var i6 = 0;i6 < this.t; ++i6)
- r4.data[i6] = this.DM & ~this.data[i6];
- r4.t = this.t;
- r4.s = ~this.s;
- return r4;
- }
- function bnShiftLeft(n5) {
- var r4 = nbi();
- if (n5 < 0)
- this.rShiftTo(-n5, r4);
- else
- this.lShiftTo(n5, r4);
- return r4;
- }
- function bnShiftRight(n5) {
- var r4 = nbi();
- if (n5 < 0)
- this.lShiftTo(-n5, r4);
- else
- this.rShiftTo(n5, r4);
- return r4;
- }
- function lbit(x4) {
- if (x4 == 0)
- return -1;
- var r4 = 0;
- if ((x4 & 65535) == 0) {
- x4 >>= 16;
- r4 += 16;
- }
- if ((x4 & 255) == 0) {
- x4 >>= 8;
- r4 += 8;
- }
- if ((x4 & 15) == 0) {
- x4 >>= 4;
- r4 += 4;
- }
- if ((x4 & 3) == 0) {
- x4 >>= 2;
- r4 += 2;
- }
- if ((x4 & 1) == 0)
- ++r4;
- return r4;
- }
- function bnGetLowestSetBit() {
- for (var i6 = 0;i6 < this.t; ++i6)
- if (this.data[i6] != 0)
- return i6 * this.DB + lbit(this.data[i6]);
- if (this.s < 0)
- return this.t * this.DB;
- return -1;
- }
- function cbit(x4) {
- var r4 = 0;
- while (x4 != 0) {
- x4 &= x4 - 1;
- ++r4;
- }
- return r4;
- }
- function bnBitCount() {
- var r4 = 0, x4 = this.s & this.DM;
- for (var i6 = 0;i6 < this.t; ++i6)
- r4 += cbit(this.data[i6] ^ x4);
- return r4;
- }
- function bnTestBit(n5) {
- var j4 = Math.floor(n5 / this.DB);
- if (j4 >= this.t)
- return this.s != 0;
- return (this.data[j4] & 1 << n5 % this.DB) != 0;
- }
- function bnpChangeBit(n5, op) {
- var r4 = BigInteger.ONE.shiftLeft(n5);
- this.bitwiseTo(r4, op, r4);
- return r4;
- }
- function bnSetBit(n5) {
- return this.changeBit(n5, op_or);
- }
- function bnClearBit(n5) {
- return this.changeBit(n5, op_andnot);
- }
- function bnFlipBit(n5) {
- return this.changeBit(n5, op_xor);
- }
- function bnpAddTo(a5, r4) {
- var i6 = 0, c8 = 0, m4 = Math.min(a5.t, this.t);
- while (i6 < m4) {
- c8 += this.data[i6] + a5.data[i6];
- r4.data[i6++] = c8 & this.DM;
- c8 >>= this.DB;
- }
- if (a5.t < this.t) {
- c8 += a5.s;
- while (i6 < this.t) {
- c8 += this.data[i6];
- r4.data[i6++] = c8 & this.DM;
- c8 >>= this.DB;
- }
- c8 += this.s;
- } else {
- c8 += this.s;
- while (i6 < a5.t) {
- c8 += a5.data[i6];
- r4.data[i6++] = c8 & this.DM;
- c8 >>= this.DB;
- }
- c8 += a5.s;
- }
- r4.s = c8 < 0 ? -1 : 0;
- if (c8 > 0)
- r4.data[i6++] = c8;
- else if (c8 < -1)
- r4.data[i6++] = this.DV + c8;
- r4.t = i6;
- r4.clamp();
- }
- function bnAdd(a5) {
- var r4 = nbi();
- this.addTo(a5, r4);
- return r4;
- }
- function bnSubtract(a5) {
- var r4 = nbi();
- this.subTo(a5, r4);
- return r4;
- }
- function bnMultiply(a5) {
- var r4 = nbi();
- this.multiplyTo(a5, r4);
- return r4;
- }
- function bnSquare() {
- var r4 = nbi();
- this.squareTo(r4);
- return r4;
- }
- function bnDivide(a5) {
- var r4 = nbi();
- this.divRemTo(a5, r4, null);
- return r4;
- }
- function bnRemainder(a5) {
- var r4 = nbi();
- this.divRemTo(a5, null, r4);
- return r4;
- }
- function bnDivideAndRemainder(a5) {
- var q4 = nbi(), r4 = nbi();
- this.divRemTo(a5, q4, r4);
- return new Array(q4, r4);
- }
- function bnpDMultiply(n5) {
- this.data[this.t] = this.am(0, n5 - 1, this, 0, 0, this.t);
- ++this.t;
- this.clamp();
- }
- function bnpDAddOffset(n5, w2) {
- if (n5 == 0)
- return;
- while (this.t <= w2)
- this.data[this.t++] = 0;
- this.data[w2] += n5;
- while (this.data[w2] >= this.DV) {
- this.data[w2] -= this.DV;
- if (++w2 >= this.t)
- this.data[this.t++] = 0;
- ++this.data[w2];
- }
- }
- function NullExp() {}
- function nNop(x4) {
- return x4;
- }
- function nMulTo(x4, y3, r4) {
- x4.multiplyTo(y3, r4);
- }
- function nSqrTo(x4, r4) {
- x4.squareTo(r4);
- }
- NullExp.prototype.convert = nNop;
- NullExp.prototype.revert = nNop;
- NullExp.prototype.mulTo = nMulTo;
- NullExp.prototype.sqrTo = nSqrTo;
- function bnPow(e4) {
- return this.exp(e4, new NullExp);
- }
- function bnpMultiplyLowerTo(a5, n5, r4) {
- var i6 = Math.min(this.t + a5.t, n5);
- r4.s = 0;
- r4.t = i6;
- while (i6 > 0)
- r4.data[--i6] = 0;
- var j4;
- for (j4 = r4.t - this.t;i6 < j4; ++i6)
- r4.data[i6 + this.t] = this.am(0, a5.data[i6], r4, i6, 0, this.t);
- for (j4 = Math.min(a5.t, n5);i6 < j4; ++i6)
- this.am(0, a5.data[i6], r4, i6, 0, n5 - i6);
- r4.clamp();
- }
- function bnpMultiplyUpperTo(a5, n5, r4) {
- --n5;
- var i6 = r4.t = this.t + a5.t - n5;
- r4.s = 0;
- while (--i6 >= 0)
- r4.data[i6] = 0;
- for (i6 = Math.max(n5 - this.t, 0);i6 < a5.t; ++i6)
- r4.data[this.t + i6 - n5] = this.am(n5 - i6, a5.data[i6], r4, 0, 0, this.t + i6 - n5);
- r4.clamp();
- r4.drShiftTo(1, r4);
- }
- function Barrett(m4) {
- this.r2 = nbi();
- this.q3 = nbi();
- BigInteger.ONE.dlShiftTo(2 * m4.t, this.r2);
- this.mu = this.r2.divide(m4);
- this.m = m4;
- }
- function barrettConvert(x4) {
- if (x4.s < 0 || x4.t > 2 * this.m.t)
- return x4.mod(this.m);
- else if (x4.compareTo(this.m) < 0)
- return x4;
- else {
- var r4 = nbi();
- x4.copyTo(r4);
- this.reduce(r4);
- return r4;
- }
- }
- function barrettRevert(x4) {
- return x4;
- }
- function barrettReduce(x4) {
- x4.drShiftTo(this.m.t - 1, this.r2);
- if (x4.t > this.m.t + 1) {
- x4.t = this.m.t + 1;
- x4.clamp();
- }
- this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
- this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
- while (x4.compareTo(this.r2) < 0)
- x4.dAddOffset(1, this.m.t + 1);
- x4.subTo(this.r2, x4);
- while (x4.compareTo(this.m) >= 0)
- x4.subTo(this.m, x4);
- }
- function barrettSqrTo(x4, r4) {
- x4.squareTo(r4);
- this.reduce(r4);
- }
- function barrettMulTo(x4, y3, r4) {
- x4.multiplyTo(y3, r4);
- this.reduce(r4);
- }
- Barrett.prototype.convert = barrettConvert;
- Barrett.prototype.revert = barrettRevert;
- Barrett.prototype.reduce = barrettReduce;
- Barrett.prototype.mulTo = barrettMulTo;
- Barrett.prototype.sqrTo = barrettSqrTo;
- function bnModPow(e4, m4) {
- var i6 = e4.bitLength(), k4, r4 = nbv(1), z3;
- if (i6 <= 0)
- return r4;
- else if (i6 < 18)
- k4 = 1;
- else if (i6 < 48)
- k4 = 3;
- else if (i6 < 144)
- k4 = 4;
- else if (i6 < 768)
- k4 = 5;
- else
- k4 = 6;
- if (i6 < 8)
- z3 = new Classic(m4);
- else if (m4.isEven())
- z3 = new Barrett(m4);
- else
- z3 = new Montgomery(m4);
- var g4 = new Array, n5 = 3, k1 = k4 - 1, km = (1 << k4) - 1;
- g4[1] = z3.convert(this);
- if (k4 > 1) {
- var g22 = nbi();
- z3.sqrTo(g4[1], g22);
- while (n5 <= km) {
- g4[n5] = nbi();
- z3.mulTo(g22, g4[n5 - 2], g4[n5]);
- n5 += 2;
- }
- }
- var j4 = e4.t - 1, w2, is1 = true, r22 = nbi(), t4;
- i6 = nbits(e4.data[j4]) - 1;
- while (j4 >= 0) {
- if (i6 >= k1)
- w2 = e4.data[j4] >> i6 - k1 & km;
- else {
- w2 = (e4.data[j4] & (1 << i6 + 1) - 1) << k1 - i6;
- if (j4 > 0)
- w2 |= e4.data[j4 - 1] >> this.DB + i6 - k1;
- }
- n5 = k4;
- while ((w2 & 1) == 0) {
- w2 >>= 1;
- --n5;
- }
- if ((i6 -= n5) < 0) {
- i6 += this.DB;
- --j4;
- }
- if (is1) {
- g4[w2].copyTo(r4);
- is1 = false;
- } else {
- while (n5 > 1) {
- z3.sqrTo(r4, r22);
- z3.sqrTo(r22, r4);
- n5 -= 2;
- }
- if (n5 > 0)
- z3.sqrTo(r4, r22);
- else {
- t4 = r4;
- r4 = r22;
- r22 = t4;
- }
- z3.mulTo(r22, g4[w2], r4);
- }
- while (j4 >= 0 && (e4.data[j4] & 1 << i6) == 0) {
- z3.sqrTo(r4, r22);
- t4 = r4;
- r4 = r22;
- r22 = t4;
- if (--i6 < 0) {
- i6 = this.DB - 1;
- --j4;
- }
- }
- }
- return z3.revert(r4);
- }
- function bnGCD(a5) {
- var x4 = this.s < 0 ? this.negate() : this.clone();
- var y3 = a5.s < 0 ? a5.negate() : a5.clone();
- if (x4.compareTo(y3) < 0) {
- var t4 = x4;
- x4 = y3;
- y3 = t4;
- }
- var i6 = x4.getLowestSetBit(), g4 = y3.getLowestSetBit();
- if (g4 < 0)
- return x4;
- if (i6 < g4)
- g4 = i6;
- if (g4 > 0) {
- x4.rShiftTo(g4, x4);
- y3.rShiftTo(g4, y3);
- }
- while (x4.signum() > 0) {
- if ((i6 = x4.getLowestSetBit()) > 0)
- x4.rShiftTo(i6, x4);
- if ((i6 = y3.getLowestSetBit()) > 0)
- y3.rShiftTo(i6, y3);
- if (x4.compareTo(y3) >= 0) {
- x4.subTo(y3, x4);
- x4.rShiftTo(1, x4);
- } else {
- y3.subTo(x4, y3);
- y3.rShiftTo(1, y3);
- }
- }
- if (g4 > 0)
- y3.lShiftTo(g4, y3);
- return y3;
- }
- function bnpModInt(n5) {
- if (n5 <= 0)
- return 0;
- var d4 = this.DV % n5, r4 = this.s < 0 ? n5 - 1 : 0;
- if (this.t > 0)
- if (d4 == 0)
- r4 = this.data[0] % n5;
- else
- for (var i6 = this.t - 1;i6 >= 0; --i6)
- r4 = (d4 * r4 + this.data[i6]) % n5;
- return r4;
- }
- function bnModInverse(m4) {
- if (this.signum() == 0) {
- return BigInteger.ZERO;
- }
- var ac = m4.isEven();
- if (this.isEven() && ac || m4.signum() == 0)
- return BigInteger.ZERO;
- var u5 = m4.clone(), v6 = this.clone();
- var a5 = nbv(1), b5 = nbv(0), c8 = nbv(0), d4 = nbv(1);
- while (u5.signum() != 0) {
- while (u5.isEven()) {
- u5.rShiftTo(1, u5);
- if (ac) {
- if (!a5.isEven() || !b5.isEven()) {
- a5.addTo(this, a5);
- b5.subTo(m4, b5);
- }
- a5.rShiftTo(1, a5);
- } else if (!b5.isEven())
- b5.subTo(m4, b5);
- b5.rShiftTo(1, b5);
- }
- while (v6.isEven()) {
- v6.rShiftTo(1, v6);
- if (ac) {
- if (!c8.isEven() || !d4.isEven()) {
- c8.addTo(this, c8);
- d4.subTo(m4, d4);
- }
- c8.rShiftTo(1, c8);
- } else if (!d4.isEven())
- d4.subTo(m4, d4);
- d4.rShiftTo(1, d4);
- }
- if (u5.compareTo(v6) >= 0) {
- u5.subTo(v6, u5);
- if (ac)
- a5.subTo(c8, a5);
- b5.subTo(d4, b5);
- } else {
- v6.subTo(u5, v6);
- if (ac)
- c8.subTo(a5, c8);
- d4.subTo(b5, d4);
- }
- }
- if (v6.compareTo(BigInteger.ONE) != 0)
- return BigInteger.ZERO;
- if (d4.compareTo(m4) >= 0)
- return d4.subtract(m4);
- if (d4.signum() < 0)
- d4.addTo(m4, d4);
- else
- return d4;
- if (d4.signum() < 0)
- return d4.add(m4);
- else
- return d4;
- }
- var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
- var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
- function bnIsProbablePrime(t4) {
- var i6, x4 = this.abs();
- if (x4.t == 1 && x4.data[0] <= lowprimes[lowprimes.length - 1]) {
- for (i6 = 0;i6 < lowprimes.length; ++i6)
- if (x4.data[0] == lowprimes[i6])
- return true;
- return false;
- }
- if (x4.isEven())
- return false;
- i6 = 1;
- while (i6 < lowprimes.length) {
- var m4 = lowprimes[i6], j4 = i6 + 1;
- while (j4 < lowprimes.length && m4 < lplim)
- m4 *= lowprimes[j4++];
- m4 = x4.modInt(m4);
- while (i6 < j4)
- if (m4 % lowprimes[i6++] == 0)
- return false;
- }
- return x4.millerRabin(t4);
- }
- function bnpMillerRabin(t4) {
- var n1 = this.subtract(BigInteger.ONE);
- var k4 = n1.getLowestSetBit();
- if (k4 <= 0)
- return false;
- var r4 = n1.shiftRight(k4);
- var prng = bnGetPrng();
- var a5;
- for (var i6 = 0;i6 < t4; ++i6) {
- do {
- a5 = new BigInteger(this.bitLength(), prng);
- } while (a5.compareTo(BigInteger.ONE) <= 0 || a5.compareTo(n1) >= 0);
- var y3 = a5.modPow(r4, this);
- if (y3.compareTo(BigInteger.ONE) != 0 && y3.compareTo(n1) != 0) {
- var j4 = 1;
- while (j4++ < k4 && y3.compareTo(n1) != 0) {
- y3 = y3.modPowInt(2, this);
- if (y3.compareTo(BigInteger.ONE) == 0)
- return false;
- }
- if (y3.compareTo(n1) != 0)
- return false;
- }
- }
- return true;
- }
- function bnGetPrng() {
- return {
- nextBytes: function(x4) {
- for (var i6 = 0;i6 < x4.length; ++i6) {
- x4[i6] = Math.floor(Math.random() * 256);
- }
- }
- };
- }
- BigInteger.prototype.chunkSize = bnpChunkSize;
- BigInteger.prototype.toRadix = bnpToRadix;
- BigInteger.prototype.fromRadix = bnpFromRadix;
- BigInteger.prototype.fromNumber = bnpFromNumber;
- BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
- BigInteger.prototype.changeBit = bnpChangeBit;
- BigInteger.prototype.addTo = bnpAddTo;
- BigInteger.prototype.dMultiply = bnpDMultiply;
- BigInteger.prototype.dAddOffset = bnpDAddOffset;
- BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
- BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
- BigInteger.prototype.modInt = bnpModInt;
- BigInteger.prototype.millerRabin = bnpMillerRabin;
- BigInteger.prototype.clone = bnClone;
- BigInteger.prototype.intValue = bnIntValue;
- BigInteger.prototype.byteValue = bnByteValue;
- BigInteger.prototype.shortValue = bnShortValue;
- BigInteger.prototype.signum = bnSigNum;
- BigInteger.prototype.toByteArray = bnToByteArray;
- BigInteger.prototype.equals = bnEquals;
- BigInteger.prototype.min = bnMin;
- BigInteger.prototype.max = bnMax;
- BigInteger.prototype.and = bnAnd;
- BigInteger.prototype.or = bnOr;
- BigInteger.prototype.xor = bnXor;
- BigInteger.prototype.andNot = bnAndNot;
- BigInteger.prototype.not = bnNot;
- BigInteger.prototype.shiftLeft = bnShiftLeft;
- BigInteger.prototype.shiftRight = bnShiftRight;
- BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
- BigInteger.prototype.bitCount = bnBitCount;
- BigInteger.prototype.testBit = bnTestBit;
- BigInteger.prototype.setBit = bnSetBit;
- BigInteger.prototype.clearBit = bnClearBit;
- BigInteger.prototype.flipBit = bnFlipBit;
- BigInteger.prototype.add = bnAdd;
- BigInteger.prototype.subtract = bnSubtract;
- BigInteger.prototype.multiply = bnMultiply;
- BigInteger.prototype.divide = bnDivide;
- BigInteger.prototype.remainder = bnRemainder;
- BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
- BigInteger.prototype.modPow = bnModPow;
- BigInteger.prototype.modInverse = bnModInverse;
- BigInteger.prototype.pow = bnPow;
- BigInteger.prototype.gcd = bnGCD;
- BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
- BigInteger.prototype.square = bnSquare;
-});
-
-// node_modules/node-forge/lib/sha1.js
-var require_sha13 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_md();
- require_util3();
- var sha1 = module.exports = forge.sha1 = forge.sha1 || {};
- forge.md.sha1 = forge.md.algorithms.sha1 = sha1;
- sha1.create = function() {
- if (!_initialized) {
- _init();
- }
- var _state = null;
- var _input = forge.util.createBuffer();
- var _w3 = new Array(80);
- var md = {
- algorithm: "sha1",
- blockLength: 64,
- digestLength: 20,
- messageLength: 0,
- fullMessageLength: null,
- messageLengthSize: 8
- };
- md.start = function() {
- md.messageLength = 0;
- md.fullMessageLength = md.messageLength64 = [];
- var int32s = md.messageLengthSize / 4;
- for (var i6 = 0;i6 < int32s; ++i6) {
- md.fullMessageLength.push(0);
- }
- _input = forge.util.createBuffer();
- _state = {
- h0: 1732584193,
- h1: 4023233417,
- h2: 2562383102,
- h3: 271733878,
- h4: 3285377520
- };
- return md;
- };
- md.start();
- md.update = function(msg, encoding) {
- if (encoding === "utf8") {
- msg = forge.util.encodeUtf8(msg);
- }
- var len = msg.length;
- md.messageLength += len;
- len = [len / 4294967296 >>> 0, len >>> 0];
- for (var i6 = md.fullMessageLength.length - 1;i6 >= 0; --i6) {
- md.fullMessageLength[i6] += len[1];
- len[1] = len[0] + (md.fullMessageLength[i6] / 4294967296 >>> 0);
- md.fullMessageLength[i6] = md.fullMessageLength[i6] >>> 0;
- len[0] = len[1] / 4294967296 >>> 0;
- }
- _input.putBytes(msg);
- _update(_state, _w3, _input);
- if (_input.read > 2048 || _input.length() === 0) {
- _input.compact();
- }
- return md;
- };
- md.digest = function() {
- var finalBlock = forge.util.createBuffer();
- finalBlock.putBytes(_input.bytes());
- var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize;
- var overflow = remaining & md.blockLength - 1;
- finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
- var next, carry;
- var bits2 = md.fullMessageLength[0] * 8;
- for (var i6 = 0;i6 < md.fullMessageLength.length - 1; ++i6) {
- next = md.fullMessageLength[i6 + 1] * 8;
- carry = next / 4294967296 >>> 0;
- bits2 += carry;
- finalBlock.putInt32(bits2 >>> 0);
- bits2 = next >>> 0;
- }
- finalBlock.putInt32(bits2);
- var s22 = {
- h0: _state.h0,
- h1: _state.h1,
- h2: _state.h2,
- h3: _state.h3,
- h4: _state.h4
- };
- _update(s22, _w3, finalBlock);
- var rval = forge.util.createBuffer();
- rval.putInt32(s22.h0);
- rval.putInt32(s22.h1);
- rval.putInt32(s22.h2);
- rval.putInt32(s22.h3);
- rval.putInt32(s22.h4);
- return rval;
- };
- return md;
- };
- var _padding = null;
- var _initialized = false;
- function _init() {
- _padding = String.fromCharCode(128);
- _padding += forge.util.fillString(String.fromCharCode(0), 64);
- _initialized = true;
- }
- function _update(s4, w2, bytes) {
- var t4, a5, b5, c8, d4, e4, f4, i6;
- var len = bytes.length();
- while (len >= 64) {
- a5 = s4.h0;
- b5 = s4.h1;
- c8 = s4.h2;
- d4 = s4.h3;
- e4 = s4.h4;
- for (i6 = 0;i6 < 16; ++i6) {
- t4 = bytes.getInt32();
- w2[i6] = t4;
- f4 = d4 ^ b5 & (c8 ^ d4);
- t4 = (a5 << 5 | a5 >>> 27) + f4 + e4 + 1518500249 + t4;
- e4 = d4;
- d4 = c8;
- c8 = (b5 << 30 | b5 >>> 2) >>> 0;
- b5 = a5;
- a5 = t4;
- }
- for (;i6 < 20; ++i6) {
- t4 = w2[i6 - 3] ^ w2[i6 - 8] ^ w2[i6 - 14] ^ w2[i6 - 16];
- t4 = t4 << 1 | t4 >>> 31;
- w2[i6] = t4;
- f4 = d4 ^ b5 & (c8 ^ d4);
- t4 = (a5 << 5 | a5 >>> 27) + f4 + e4 + 1518500249 + t4;
- e4 = d4;
- d4 = c8;
- c8 = (b5 << 30 | b5 >>> 2) >>> 0;
- b5 = a5;
- a5 = t4;
- }
- for (;i6 < 32; ++i6) {
- t4 = w2[i6 - 3] ^ w2[i6 - 8] ^ w2[i6 - 14] ^ w2[i6 - 16];
- t4 = t4 << 1 | t4 >>> 31;
- w2[i6] = t4;
- f4 = b5 ^ c8 ^ d4;
- t4 = (a5 << 5 | a5 >>> 27) + f4 + e4 + 1859775393 + t4;
- e4 = d4;
- d4 = c8;
- c8 = (b5 << 30 | b5 >>> 2) >>> 0;
- b5 = a5;
- a5 = t4;
- }
- for (;i6 < 40; ++i6) {
- t4 = w2[i6 - 6] ^ w2[i6 - 16] ^ w2[i6 - 28] ^ w2[i6 - 32];
- t4 = t4 << 2 | t4 >>> 30;
- w2[i6] = t4;
- f4 = b5 ^ c8 ^ d4;
- t4 = (a5 << 5 | a5 >>> 27) + f4 + e4 + 1859775393 + t4;
- e4 = d4;
- d4 = c8;
- c8 = (b5 << 30 | b5 >>> 2) >>> 0;
- b5 = a5;
- a5 = t4;
- }
- for (;i6 < 60; ++i6) {
- t4 = w2[i6 - 6] ^ w2[i6 - 16] ^ w2[i6 - 28] ^ w2[i6 - 32];
- t4 = t4 << 2 | t4 >>> 30;
- w2[i6] = t4;
- f4 = b5 & c8 | d4 & (b5 ^ c8);
- t4 = (a5 << 5 | a5 >>> 27) + f4 + e4 + 2400959708 + t4;
- e4 = d4;
- d4 = c8;
- c8 = (b5 << 30 | b5 >>> 2) >>> 0;
- b5 = a5;
- a5 = t4;
- }
- for (;i6 < 80; ++i6) {
- t4 = w2[i6 - 6] ^ w2[i6 - 16] ^ w2[i6 - 28] ^ w2[i6 - 32];
- t4 = t4 << 2 | t4 >>> 30;
- w2[i6] = t4;
- f4 = b5 ^ c8 ^ d4;
- t4 = (a5 << 5 | a5 >>> 27) + f4 + e4 + 3395469782 + t4;
- e4 = d4;
- d4 = c8;
- c8 = (b5 << 30 | b5 >>> 2) >>> 0;
- b5 = a5;
- a5 = t4;
- }
- s4.h0 = s4.h0 + a5 | 0;
- s4.h1 = s4.h1 + b5 | 0;
- s4.h2 = s4.h2 + c8 | 0;
- s4.h3 = s4.h3 + d4 | 0;
- s4.h4 = s4.h4 + e4 | 0;
- len -= 64;
- }
- }
-});
-
-// node_modules/node-forge/lib/pkcs1.js
-var require_pkcs1 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_util3();
- require_random();
- require_sha13();
- var pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {};
- pkcs1.encode_rsa_oaep = function(key2, message, options2) {
- var label;
- var seed;
- var md;
- var mgf1Md;
- if (typeof options2 === "string") {
- label = options2;
- seed = arguments[3] || undefined;
- md = arguments[4] || undefined;
- } else if (options2) {
- label = options2.label || undefined;
- seed = options2.seed || undefined;
- md = options2.md || undefined;
- if (options2.mgf1 && options2.mgf1.md) {
- mgf1Md = options2.mgf1.md;
- }
- }
- if (!md) {
- md = forge.md.sha1.create();
- } else {
- md.start();
- }
- if (!mgf1Md) {
- mgf1Md = md;
- }
- var keyLength = Math.ceil(key2.n.bitLength() / 8);
- var maxLength = keyLength - 2 * md.digestLength - 2;
- if (message.length > maxLength) {
- var error46 = new Error("RSAES-OAEP input message length is too long.");
- error46.length = message.length;
- error46.maxLength = maxLength;
- throw error46;
- }
- if (!label) {
- label = "";
- }
- md.update(label, "raw");
- var lHash = md.digest();
- var PS = "";
- var PS_length = maxLength - message.length;
- for (var i6 = 0;i6 < PS_length; i6++) {
- PS += "\x00";
- }
- var DB = lHash.getBytes() + PS + "\x01" + message;
- if (!seed) {
- seed = forge.random.getBytes(md.digestLength);
- } else if (seed.length !== md.digestLength) {
- var error46 = new Error("Invalid RSAES-OAEP seed. The seed length must " + "match the digest length.");
- error46.seedLength = seed.length;
- error46.digestLength = md.digestLength;
- throw error46;
- }
- var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);
- var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length);
- var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);
- var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length);
- return "\x00" + maskedSeed + maskedDB;
- };
- pkcs1.decode_rsa_oaep = function(key2, em, options2) {
- var label;
- var md;
- var mgf1Md;
- if (typeof options2 === "string") {
- label = options2;
- md = arguments[3] || undefined;
- } else if (options2) {
- label = options2.label || undefined;
- md = options2.md || undefined;
- if (options2.mgf1 && options2.mgf1.md) {
- mgf1Md = options2.mgf1.md;
- }
- }
- var keyLength = Math.ceil(key2.n.bitLength() / 8);
- if (em.length !== keyLength) {
- var error46 = new Error("RSAES-OAEP encoded message length is invalid.");
- error46.length = em.length;
- error46.expectedLength = keyLength;
- throw error46;
- }
- if (md === undefined) {
- md = forge.md.sha1.create();
- } else {
- md.start();
- }
- if (!mgf1Md) {
- mgf1Md = md;
- }
- if (keyLength < 2 * md.digestLength + 2) {
- throw new Error("RSAES-OAEP key is too short for the hash function.");
- }
- if (!label) {
- label = "";
- }
- md.update(label, "raw");
- var lHash = md.digest().getBytes();
- var y3 = em.charAt(0);
- var maskedSeed = em.substring(1, md.digestLength + 1);
- var maskedDB = em.substring(1 + md.digestLength);
- var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);
- var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);
- var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);
- var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);
- var lHashPrime = db.substring(0, md.digestLength);
- var error46 = y3 !== "\x00";
- for (var i6 = 0;i6 < md.digestLength; ++i6) {
- error46 |= lHash.charAt(i6) !== lHashPrime.charAt(i6);
- }
- var in_ps = 1;
- var index2 = md.digestLength;
- for (var j4 = md.digestLength;j4 < db.length; j4++) {
- var code = db.charCodeAt(j4);
- var is_0 = code & 1 ^ 1;
- var error_mask = in_ps ? 65534 : 0;
- error46 |= code & error_mask;
- in_ps = in_ps & is_0;
- index2 += in_ps;
- }
- if (error46 || db.charCodeAt(index2) !== 1) {
- throw new Error("Invalid RSAES-OAEP padding.");
- }
- return db.substring(index2 + 1);
- };
- function rsa_mgf1(seed, maskLength, hash2) {
- if (!hash2) {
- hash2 = forge.md.sha1.create();
- }
- var t4 = "";
- var count3 = Math.ceil(maskLength / hash2.digestLength);
- for (var i6 = 0;i6 < count3; ++i6) {
- var c8 = String.fromCharCode(i6 >> 24 & 255, i6 >> 16 & 255, i6 >> 8 & 255, i6 & 255);
- hash2.start();
- hash2.update(seed + c8);
- t4 += hash2.digest().getBytes();
- }
- return t4.substring(0, maskLength);
- }
-});
-
-// node_modules/node-forge/lib/prime.js
-var require_prime = __commonJS((exports, module) => {
- var forge = require_forge();
- require_util3();
- require_jsbn();
- require_random();
- (function() {
- if (forge.prime) {
- module.exports = forge.prime;
- return;
- }
- var prime = module.exports = forge.prime = forge.prime || {};
- var BigInteger = forge.jsbn.BigInteger;
- var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
- var THIRTY = new BigInteger(null);
- THIRTY.fromInt(30);
- var op_or = function(x4, y3) {
- return x4 | y3;
- };
- prime.generateProbablePrime = function(bits2, options2, callback) {
- if (typeof options2 === "function") {
- callback = options2;
- options2 = {};
- }
- options2 = options2 || {};
- var algorithm = options2.algorithm || "PRIMEINC";
- if (typeof algorithm === "string") {
- algorithm = { name: algorithm };
- }
- algorithm.options = algorithm.options || {};
- var prng = options2.prng || forge.random;
- var rng = {
- nextBytes: function(x4) {
- var b5 = prng.getBytesSync(x4.length);
- for (var i6 = 0;i6 < x4.length; ++i6) {
- x4[i6] = b5.charCodeAt(i6);
- }
- }
- };
- if (algorithm.name === "PRIMEINC") {
- return primeincFindPrime(bits2, rng, algorithm.options, callback);
- }
- throw new Error("Invalid prime generation algorithm: " + algorithm.name);
- };
- function primeincFindPrime(bits2, rng, options2, callback) {
- if ("workers" in options2) {
- return primeincFindPrimeWithWorkers(bits2, rng, options2, callback);
- }
- return primeincFindPrimeWithoutWorkers(bits2, rng, options2, callback);
- }
- function primeincFindPrimeWithoutWorkers(bits2, rng, options2, callback) {
- var num = generateRandom(bits2, rng);
- var deltaIdx = 0;
- var mrTests = getMillerRabinTests(num.bitLength());
- if ("millerRabinTests" in options2) {
- mrTests = options2.millerRabinTests;
- }
- var maxBlockTime = 10;
- if ("maxBlockTime" in options2) {
- maxBlockTime = options2.maxBlockTime;
- }
- _primeinc(num, bits2, rng, deltaIdx, mrTests, maxBlockTime, callback);
- }
- function _primeinc(num, bits2, rng, deltaIdx, mrTests, maxBlockTime, callback) {
- var start = +new Date;
- do {
- if (num.bitLength() > bits2) {
- num = generateRandom(bits2, rng);
- }
- if (num.isProbablePrime(mrTests)) {
- return callback(null, num);
- }
- num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
- } while (maxBlockTime < 0 || +new Date - start < maxBlockTime);
- forge.util.setImmediate(function() {
- _primeinc(num, bits2, rng, deltaIdx, mrTests, maxBlockTime, callback);
- });
- }
- function primeincFindPrimeWithWorkers(bits2, rng, options2, callback) {
- if (typeof Worker === "undefined") {
- return primeincFindPrimeWithoutWorkers(bits2, rng, options2, callback);
- }
- var num = generateRandom(bits2, rng);
- var numWorkers = options2.workers;
- var workLoad = options2.workLoad || 100;
- var range = workLoad * 30 / 8;
- var workerScript = options2.workerScript || "forge/prime.worker.js";
- if (numWorkers === -1) {
- return forge.util.estimateCores(function(err2, cores) {
- if (err2) {
- cores = 2;
- }
- numWorkers = cores - 1;
- generate5();
- });
- }
- generate5();
- function generate5() {
- numWorkers = Math.max(1, numWorkers);
- var workers = [];
- for (var i6 = 0;i6 < numWorkers; ++i6) {
- workers[i6] = new Worker(workerScript);
- }
- var running = numWorkers;
- for (var i6 = 0;i6 < numWorkers; ++i6) {
- workers[i6].addEventListener("message", workerMessage);
- }
- var found = false;
- function workerMessage(e4) {
- if (found) {
- return;
- }
- --running;
- var data = e4.data;
- if (data.found) {
- for (var i7 = 0;i7 < workers.length; ++i7) {
- workers[i7].terminate();
- }
- found = true;
- return callback(null, new BigInteger(data.prime, 16));
- }
- if (num.bitLength() > bits2) {
- num = generateRandom(bits2, rng);
- }
- var hex = num.toString(16);
- e4.target.postMessage({
- hex,
- workLoad
- });
- num.dAddOffset(range, 0);
- }
- }
- }
- function generateRandom(bits2, rng) {
- var num = new BigInteger(bits2, rng);
- var bits1 = bits2 - 1;
- if (!num.testBit(bits1)) {
- num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);
- }
- num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);
- return num;
- }
- function getMillerRabinTests(bits2) {
- if (bits2 <= 100)
- return 27;
- if (bits2 <= 150)
- return 18;
- if (bits2 <= 200)
- return 15;
- if (bits2 <= 250)
- return 12;
- if (bits2 <= 300)
- return 9;
- if (bits2 <= 350)
- return 8;
- if (bits2 <= 400)
- return 7;
- if (bits2 <= 500)
- return 6;
- if (bits2 <= 600)
- return 5;
- if (bits2 <= 800)
- return 4;
- if (bits2 <= 1250)
- return 3;
- return 2;
- }
- })();
-});
-
-// node_modules/node-forge/lib/rsa.js
-var require_rsa = __commonJS((exports, module) => {
- var forge = require_forge();
- require_asn1();
- require_jsbn();
- require_oids();
- require_pkcs1();
- require_prime();
- require_random();
- require_util3();
- if (typeof BigInteger === "undefined") {
- BigInteger = forge.jsbn.BigInteger;
- }
- var BigInteger;
- var _crypto = forge.util.isNodejs ? __require("crypto") : null;
- var asn1 = forge.asn1;
- var util12 = forge.util;
- forge.pki = forge.pki || {};
- module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};
- var pki = forge.pki;
- var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
- var privateKeyValidator = {
- name: "PrivateKeyInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "PrivateKeyInfo.version",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "privateKeyVersion"
- }, {
- name: "PrivateKeyInfo.privateKeyAlgorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "AlgorithmIdentifier.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "privateKeyOid"
- }]
- }, {
- name: "PrivateKeyInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: "privateKey"
- }]
- };
- var rsaPrivateKeyValidator = {
- name: "RSAPrivateKey",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "RSAPrivateKey.version",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "privateKeyVersion"
- }, {
- name: "RSAPrivateKey.modulus",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "privateKeyModulus"
- }, {
- name: "RSAPrivateKey.publicExponent",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "privateKeyPublicExponent"
- }, {
- name: "RSAPrivateKey.privateExponent",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "privateKeyPrivateExponent"
- }, {
- name: "RSAPrivateKey.prime1",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "privateKeyPrime1"
- }, {
- name: "RSAPrivateKey.prime2",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "privateKeyPrime2"
- }, {
- name: "RSAPrivateKey.exponent1",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "privateKeyExponent1"
- }, {
- name: "RSAPrivateKey.exponent2",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "privateKeyExponent2"
- }, {
- name: "RSAPrivateKey.coefficient",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "privateKeyCoefficient"
- }]
- };
- var rsaPublicKeyValidator = {
- name: "RSAPublicKey",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "RSAPublicKey.modulus",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "publicKeyModulus"
- }, {
- name: "RSAPublicKey.exponent",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "publicKeyExponent"
- }]
- };
- var publicKeyValidator = forge.pki.rsa.publicKeyValidator = {
- name: "SubjectPublicKeyInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: "subjectPublicKeyInfo",
- value: [{
- name: "SubjectPublicKeyInfo.AlgorithmIdentifier",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "AlgorithmIdentifier.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "publicKeyOid"
- }]
- }, {
- name: "SubjectPublicKeyInfo.subjectPublicKey",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.BITSTRING,
- constructed: false,
- value: [{
- name: "SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- optional: true,
- captureAsn1: "rsaPublicKey"
- }]
- }]
- };
- var digestInfoValidator = {
- name: "DigestInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "DigestInfo.DigestAlgorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "DigestInfo.DigestAlgorithm.algorithmIdentifier",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "algorithmIdentifier"
- }, {
- name: "DigestInfo.DigestAlgorithm.parameters",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.NULL,
- capture: "parameters",
- optional: true,
- constructed: false
- }]
- }, {
- name: "DigestInfo.digest",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: "digest"
- }]
- };
- var emsaPkcs1v15encode = function(md) {
- var oid;
- if (md.algorithm in pki.oids) {
- oid = pki.oids[md.algorithm];
- } else {
- var error46 = new Error("Unknown message digest algorithm.");
- error46.algorithm = md.algorithm;
- throw error46;
- }
- var oidBytes = asn1.oidToDer(oid).getBytes();
- var digestInfo = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- var digestAlgorithm = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));
- digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ""));
- var digest = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, md.digest().getBytes());
- digestInfo.value.push(digestAlgorithm);
- digestInfo.value.push(digest);
- return asn1.toDer(digestInfo).getBytes();
- };
- var _modPow = function(x4, key2, pub) {
- if (pub) {
- return x4.modPow(key2.e, key2.n);
- }
- if (!key2.p || !key2.q) {
- return x4.modPow(key2.d, key2.n);
- }
- if (!key2.dP) {
- key2.dP = key2.d.mod(key2.p.subtract(BigInteger.ONE));
- }
- if (!key2.dQ) {
- key2.dQ = key2.d.mod(key2.q.subtract(BigInteger.ONE));
- }
- if (!key2.qInv) {
- key2.qInv = key2.q.modInverse(key2.p);
- }
- var r4;
- do {
- r4 = new BigInteger(forge.util.bytesToHex(forge.random.getBytes(key2.n.bitLength() / 8)), 16);
- } while (r4.compareTo(key2.n) >= 0 || !r4.gcd(key2.n).equals(BigInteger.ONE));
- x4 = x4.multiply(r4.modPow(key2.e, key2.n)).mod(key2.n);
- var xp = x4.mod(key2.p).modPow(key2.dP, key2.p);
- var xq = x4.mod(key2.q).modPow(key2.dQ, key2.q);
- while (xp.compareTo(xq) < 0) {
- xp = xp.add(key2.p);
- }
- var y3 = xp.subtract(xq).multiply(key2.qInv).mod(key2.p).multiply(key2.q).add(xq);
- y3 = y3.multiply(r4.modInverse(key2.n)).mod(key2.n);
- return y3;
- };
- pki.rsa.encrypt = function(m4, key2, bt) {
- var pub = bt;
- var eb;
- var k4 = Math.ceil(key2.n.bitLength() / 8);
- if (bt !== false && bt !== true) {
- pub = bt === 2;
- eb = _encodePkcs1_v1_5(m4, key2, bt);
- } else {
- eb = forge.util.createBuffer();
- eb.putBytes(m4);
- }
- var x4 = new BigInteger(eb.toHex(), 16);
- var y3 = _modPow(x4, key2, pub);
- var yhex = y3.toString(16);
- var ed = forge.util.createBuffer();
- var zeros = k4 - Math.ceil(yhex.length / 2);
- while (zeros > 0) {
- ed.putByte(0);
- --zeros;
- }
- ed.putBytes(forge.util.hexToBytes(yhex));
- return ed.getBytes();
- };
- pki.rsa.decrypt = function(ed, key2, pub, ml) {
- var k4 = Math.ceil(key2.n.bitLength() / 8);
- if (ed.length !== k4) {
- var error46 = new Error("Encrypted message length is invalid.");
- error46.length = ed.length;
- error46.expected = k4;
- throw error46;
- }
- var y3 = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);
- if (y3.compareTo(key2.n) >= 0) {
- throw new Error("Encrypted message is invalid.");
- }
- var x4 = _modPow(y3, key2, pub);
- var xhex = x4.toString(16);
- var eb = forge.util.createBuffer();
- var zeros = k4 - Math.ceil(xhex.length / 2);
- while (zeros > 0) {
- eb.putByte(0);
- --zeros;
- }
- eb.putBytes(forge.util.hexToBytes(xhex));
- if (ml !== false) {
- return _decodePkcs1_v1_5(eb.getBytes(), key2, pub);
- }
- return eb.getBytes();
- };
- pki.rsa.createKeyPairGenerationState = function(bits2, e4, options2) {
- if (typeof bits2 === "string") {
- bits2 = parseInt(bits2, 10);
- }
- bits2 = bits2 || 2048;
- options2 = options2 || {};
- var prng = options2.prng || forge.random;
- var rng = {
- nextBytes: function(x4) {
- var b5 = prng.getBytesSync(x4.length);
- for (var i6 = 0;i6 < x4.length; ++i6) {
- x4[i6] = b5.charCodeAt(i6);
- }
- }
- };
- var algorithm = options2.algorithm || "PRIMEINC";
- var rval;
- if (algorithm === "PRIMEINC") {
- rval = {
- algorithm,
- state: 0,
- bits: bits2,
- rng,
- eInt: e4 || 65537,
- e: new BigInteger(null),
- p: null,
- q: null,
- qBits: bits2 >> 1,
- pBits: bits2 - (bits2 >> 1),
- pqState: 0,
- num: null,
- keys: null
- };
- rval.e.fromInt(rval.eInt);
- } else {
- throw new Error("Invalid key generation algorithm: " + algorithm);
- }
- return rval;
- };
- pki.rsa.stepKeyPairGenerationState = function(state3, n5) {
- if (!("algorithm" in state3)) {
- state3.algorithm = "PRIMEINC";
- }
- var THIRTY = new BigInteger(null);
- THIRTY.fromInt(30);
- var deltaIdx = 0;
- var op_or = function(x4, y3) {
- return x4 | y3;
- };
- var t1 = +new Date;
- var t22;
- var total = 0;
- while (state3.keys === null && (n5 <= 0 || total < n5)) {
- if (state3.state === 0) {
- var bits2 = state3.p === null ? state3.pBits : state3.qBits;
- var bits1 = bits2 - 1;
- if (state3.pqState === 0) {
- state3.num = new BigInteger(bits2, state3.rng);
- if (!state3.num.testBit(bits1)) {
- state3.num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, state3.num);
- }
- state3.num.dAddOffset(31 - state3.num.mod(THIRTY).byteValue(), 0);
- deltaIdx = 0;
- ++state3.pqState;
- } else if (state3.pqState === 1) {
- if (state3.num.bitLength() > bits2) {
- state3.pqState = 0;
- } else if (state3.num.isProbablePrime(_getMillerRabinTests(state3.num.bitLength()))) {
- ++state3.pqState;
- } else {
- state3.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
- }
- } else if (state3.pqState === 2) {
- state3.pqState = state3.num.subtract(BigInteger.ONE).gcd(state3.e).compareTo(BigInteger.ONE) === 0 ? 3 : 0;
- } else if (state3.pqState === 3) {
- state3.pqState = 0;
- if (state3.p === null) {
- state3.p = state3.num;
- } else {
- state3.q = state3.num;
- }
- if (state3.p !== null && state3.q !== null) {
- ++state3.state;
- }
- state3.num = null;
- }
- } else if (state3.state === 1) {
- if (state3.p.compareTo(state3.q) < 0) {
- state3.num = state3.p;
- state3.p = state3.q;
- state3.q = state3.num;
- }
- ++state3.state;
- } else if (state3.state === 2) {
- state3.p1 = state3.p.subtract(BigInteger.ONE);
- state3.q1 = state3.q.subtract(BigInteger.ONE);
- state3.phi = state3.p1.multiply(state3.q1);
- ++state3.state;
- } else if (state3.state === 3) {
- if (state3.phi.gcd(state3.e).compareTo(BigInteger.ONE) === 0) {
- ++state3.state;
- } else {
- state3.p = null;
- state3.q = null;
- state3.state = 0;
- }
- } else if (state3.state === 4) {
- state3.n = state3.p.multiply(state3.q);
- if (state3.n.bitLength() === state3.bits) {
- ++state3.state;
- } else {
- state3.q = null;
- state3.state = 0;
- }
- } else if (state3.state === 5) {
- var d4 = state3.e.modInverse(state3.phi);
- state3.keys = {
- privateKey: pki.rsa.setPrivateKey(state3.n, state3.e, d4, state3.p, state3.q, d4.mod(state3.p1), d4.mod(state3.q1), state3.q.modInverse(state3.p)),
- publicKey: pki.rsa.setPublicKey(state3.n, state3.e)
- };
- }
- t22 = +new Date;
- total += t22 - t1;
- t1 = t22;
- }
- return state3.keys !== null;
- };
- pki.rsa.generateKeyPair = function(bits2, e4, options2, callback) {
- if (arguments.length === 1) {
- if (typeof bits2 === "object") {
- options2 = bits2;
- bits2 = undefined;
- } else if (typeof bits2 === "function") {
- callback = bits2;
- bits2 = undefined;
- }
- } else if (arguments.length === 2) {
- if (typeof bits2 === "number") {
- if (typeof e4 === "function") {
- callback = e4;
- e4 = undefined;
- } else if (typeof e4 !== "number") {
- options2 = e4;
- e4 = undefined;
- }
- } else {
- options2 = bits2;
- callback = e4;
- bits2 = undefined;
- e4 = undefined;
- }
- } else if (arguments.length === 3) {
- if (typeof e4 === "number") {
- if (typeof options2 === "function") {
- callback = options2;
- options2 = undefined;
- }
- } else {
- callback = options2;
- options2 = e4;
- e4 = undefined;
- }
- }
- options2 = options2 || {};
- if (bits2 === undefined) {
- bits2 = options2.bits || 2048;
- }
- if (e4 === undefined) {
- e4 = options2.e || 65537;
- }
- if (!forge.options.usePureJavaScript && !options2.prng && bits2 >= 256 && bits2 <= 16384 && (e4 === 65537 || e4 === 3)) {
- if (callback) {
- if (_detectNodeCrypto("generateKeyPair")) {
- return _crypto.generateKeyPair("rsa", {
- modulusLength: bits2,
- publicExponent: e4,
- publicKeyEncoding: {
- type: "spki",
- format: "pem"
- },
- privateKeyEncoding: {
- type: "pkcs8",
- format: "pem"
- }
- }, function(err2, pub, priv) {
- if (err2) {
- return callback(err2);
- }
- callback(null, {
- privateKey: pki.privateKeyFromPem(priv),
- publicKey: pki.publicKeyFromPem(pub)
- });
- });
- }
- if (_detectSubtleCrypto("generateKey") && _detectSubtleCrypto("exportKey")) {
- return util12.globalScope.crypto.subtle.generateKey({
- name: "RSASSA-PKCS1-v1_5",
- modulusLength: bits2,
- publicExponent: _intToUint8Array(e4),
- hash: { name: "SHA-256" }
- }, true, ["sign", "verify"]).then(function(pair) {
- return util12.globalScope.crypto.subtle.exportKey("pkcs8", pair.privateKey);
- }).then(undefined, function(err2) {
- callback(err2);
- }).then(function(pkcs8) {
- if (pkcs8) {
- var privateKey = pki.privateKeyFromAsn1(asn1.fromDer(forge.util.createBuffer(pkcs8)));
- callback(null, {
- privateKey,
- publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)
- });
- }
- });
- }
- if (_detectSubtleMsCrypto("generateKey") && _detectSubtleMsCrypto("exportKey")) {
- var genOp = util12.globalScope.msCrypto.subtle.generateKey({
- name: "RSASSA-PKCS1-v1_5",
- modulusLength: bits2,
- publicExponent: _intToUint8Array(e4),
- hash: { name: "SHA-256" }
- }, true, ["sign", "verify"]);
- genOp.oncomplete = function(e5) {
- var pair = e5.target.result;
- var exportOp = util12.globalScope.msCrypto.subtle.exportKey("pkcs8", pair.privateKey);
- exportOp.oncomplete = function(e6) {
- var pkcs8 = e6.target.result;
- var privateKey = pki.privateKeyFromAsn1(asn1.fromDer(forge.util.createBuffer(pkcs8)));
- callback(null, {
- privateKey,
- publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)
- });
- };
- exportOp.onerror = function(err2) {
- callback(err2);
- };
- };
- genOp.onerror = function(err2) {
- callback(err2);
- };
- return;
- }
- } else {
- if (_detectNodeCrypto("generateKeyPairSync")) {
- var keypair = _crypto.generateKeyPairSync("rsa", {
- modulusLength: bits2,
- publicExponent: e4,
- publicKeyEncoding: {
- type: "spki",
- format: "pem"
- },
- privateKeyEncoding: {
- type: "pkcs8",
- format: "pem"
- }
- });
- return {
- privateKey: pki.privateKeyFromPem(keypair.privateKey),
- publicKey: pki.publicKeyFromPem(keypair.publicKey)
- };
- }
- }
- }
- var state3 = pki.rsa.createKeyPairGenerationState(bits2, e4, options2);
- if (!callback) {
- pki.rsa.stepKeyPairGenerationState(state3, 0);
- return state3.keys;
- }
- _generateKeyPair(state3, options2, callback);
- };
- pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n5, e4) {
- var key2 = {
- n: n5,
- e: e4
- };
- key2.encrypt = function(data, scheme, schemeOptions) {
- if (typeof scheme === "string") {
- scheme = scheme.toUpperCase();
- } else if (scheme === undefined) {
- scheme = "RSAES-PKCS1-V1_5";
- }
- if (scheme === "RSAES-PKCS1-V1_5") {
- scheme = {
- encode: function(m4, key3, pub) {
- return _encodePkcs1_v1_5(m4, key3, 2).getBytes();
- }
- };
- } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") {
- scheme = {
- encode: function(m4, key3) {
- return forge.pkcs1.encode_rsa_oaep(key3, m4, schemeOptions);
- }
- };
- } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) {
- scheme = { encode: function(e6) {
- return e6;
- } };
- } else if (typeof scheme === "string") {
- throw new Error('Unsupported encryption scheme: "' + scheme + '".');
- }
- var e5 = scheme.encode(data, key2, true);
- return pki.rsa.encrypt(e5, key2, true);
- };
- key2.verify = function(digest, signature7, scheme, options2) {
- if (typeof scheme === "string") {
- scheme = scheme.toUpperCase();
- } else if (scheme === undefined) {
- scheme = "RSASSA-PKCS1-V1_5";
- }
- if (options2 === undefined) {
- options2 = {
- _parseAllDigestBytes: true,
- _skipPaddingChecks: false
- };
- }
- if (!("_parseAllDigestBytes" in options2)) {
- options2._parseAllDigestBytes = true;
- }
- if (!("_skipPaddingChecks" in options2)) {
- options2._skipPaddingChecks = false;
- }
- if (scheme === "RSASSA-PKCS1-V1_5") {
- scheme = {
- verify: function(digest2, d5) {
- d5 = _decodePkcs1_v1_5(d5, key2, true, undefined, options2);
- var obj = asn1.fromDer(d5, {
- parseAllBytes: options2._parseAllDigestBytes
- });
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(obj, digestInfoValidator, capture, errors8) || obj.value.length !== 2) {
- var error46 = new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 " + "DigestInfo value.");
- error46.errors = errors8;
- throw error46;
- }
- var oid = asn1.derToOid(capture.algorithmIdentifier);
- if (!(oid === forge.oids.md2 || oid === forge.oids.md5 || oid === forge.oids.sha1 || oid === forge.oids.sha224 || oid === forge.oids.sha256 || oid === forge.oids.sha384 || oid === forge.oids.sha512 || oid === forge.oids["sha512-224"] || oid === forge.oids["sha512-256"])) {
- var error46 = new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");
- error46.oid = oid;
- throw error46;
- }
- if (oid === forge.oids.md2 || oid === forge.oids.md5) {
- if (!("parameters" in capture)) {
- throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 " + "DigestInfo value. " + "Missing algorithm identifier NULL parameters.");
- }
- }
- return digest2 === capture.digest;
- }
- };
- } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) {
- scheme = {
- verify: function(digest2, d5) {
- d5 = _decodePkcs1_v1_5(d5, key2, true, undefined, options2);
- return digest2 === d5;
- }
- };
- }
- var d4 = pki.rsa.decrypt(signature7, key2, true, false);
- return scheme.verify(digest, d4, key2.n.bitLength());
- };
- return key2;
- };
- pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(n5, e4, d4, p4, q4, dP, dQ, qInv) {
- var key2 = {
- n: n5,
- e: e4,
- d: d4,
- p: p4,
- q: q4,
- dP,
- dQ,
- qInv
- };
- key2.decrypt = function(data, scheme, schemeOptions) {
- if (typeof scheme === "string") {
- scheme = scheme.toUpperCase();
- } else if (scheme === undefined) {
- scheme = "RSAES-PKCS1-V1_5";
- }
- var d5 = pki.rsa.decrypt(data, key2, false, false);
- if (scheme === "RSAES-PKCS1-V1_5") {
- scheme = { decode: _decodePkcs1_v1_5 };
- } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") {
- scheme = {
- decode: function(d6, key3) {
- return forge.pkcs1.decode_rsa_oaep(key3, d6, schemeOptions);
- }
- };
- } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) {
- scheme = { decode: function(d6) {
- return d6;
- } };
- } else {
- throw new Error('Unsupported encryption scheme: "' + scheme + '".');
- }
- return scheme.decode(d5, key2, false);
- };
- key2.sign = function(md, scheme) {
- var bt = false;
- if (typeof scheme === "string") {
- scheme = scheme.toUpperCase();
- }
- if (scheme === undefined || scheme === "RSASSA-PKCS1-V1_5") {
- scheme = { encode: emsaPkcs1v15encode };
- bt = 1;
- } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) {
- scheme = { encode: function() {
- return md;
- } };
- bt = 1;
- }
- var d5 = scheme.encode(md, key2.n.bitLength());
- return pki.rsa.encrypt(d5, key2, bt);
- };
- return key2;
- };
- pki.wrapRsaPrivateKey = function(rsaKey) {
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(0).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
- ]),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(rsaKey).getBytes())
- ]);
- };
- pki.privateKeyFromAsn1 = function(obj) {
- var capture = {};
- var errors8 = [];
- if (asn1.validate(obj, privateKeyValidator, capture, errors8)) {
- obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));
- }
- capture = {};
- errors8 = [];
- if (!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors8)) {
- var error46 = new Error("Cannot read private key. " + "ASN.1 object does not contain an RSAPrivateKey.");
- error46.errors = errors8;
- throw error46;
- }
- var n5, e4, d4, p4, q4, dP, dQ, qInv;
- n5 = forge.util.createBuffer(capture.privateKeyModulus).toHex();
- e4 = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();
- d4 = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();
- p4 = forge.util.createBuffer(capture.privateKeyPrime1).toHex();
- q4 = forge.util.createBuffer(capture.privateKeyPrime2).toHex();
- dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();
- dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();
- qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();
- return pki.setRsaPrivateKey(new BigInteger(n5, 16), new BigInteger(e4, 16), new BigInteger(d4, 16), new BigInteger(p4, 16), new BigInteger(q4, 16), new BigInteger(dP, 16), new BigInteger(dQ, 16), new BigInteger(qInv, 16));
- };
- pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key2) {
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(0).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key2.n)),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key2.e)),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key2.d)),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key2.p)),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key2.q)),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key2.dP)),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key2.dQ)),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key2.qInv))
- ]);
- };
- pki.publicKeyFromAsn1 = function(obj) {
- var capture = {};
- var errors8 = [];
- if (asn1.validate(obj, publicKeyValidator, capture, errors8)) {
- var oid = asn1.derToOid(capture.publicKeyOid);
- if (oid !== pki.oids.rsaEncryption) {
- var error46 = new Error("Cannot read public key. Unknown OID.");
- error46.oid = oid;
- throw error46;
- }
- obj = capture.rsaPublicKey;
- }
- errors8 = [];
- if (!asn1.validate(obj, rsaPublicKeyValidator, capture, errors8)) {
- var error46 = new Error("Cannot read public key. " + "ASN.1 object does not contain an RSAPublicKey.");
- error46.errors = errors8;
- throw error46;
- }
- var n5 = forge.util.createBuffer(capture.publicKeyModulus).toHex();
- var e4 = forge.util.createBuffer(capture.publicKeyExponent).toHex();
- return pki.setRsaPublicKey(new BigInteger(n5, 16), new BigInteger(e4, 16));
- };
- pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key2) {
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
- ]),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [
- pki.publicKeyToRSAPublicKey(key2)
- ])
- ]);
- };
- pki.publicKeyToRSAPublicKey = function(key2) {
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key2.n)),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key2.e))
- ]);
- };
- function _encodePkcs1_v1_5(m4, key2, bt) {
- var eb = forge.util.createBuffer();
- var k4 = Math.ceil(key2.n.bitLength() / 8);
- if (m4.length > k4 - 11) {
- var error46 = new Error("Message is too long for PKCS#1 v1.5 padding.");
- error46.length = m4.length;
- error46.max = k4 - 11;
- throw error46;
- }
- eb.putByte(0);
- eb.putByte(bt);
- var padNum = k4 - 3 - m4.length;
- var padByte;
- if (bt === 0 || bt === 1) {
- padByte = bt === 0 ? 0 : 255;
- for (var i6 = 0;i6 < padNum; ++i6) {
- eb.putByte(padByte);
- }
- } else {
- while (padNum > 0) {
- var numZeros = 0;
- var padBytes = forge.random.getBytes(padNum);
- for (var i6 = 0;i6 < padNum; ++i6) {
- padByte = padBytes.charCodeAt(i6);
- if (padByte === 0) {
- ++numZeros;
- } else {
- eb.putByte(padByte);
- }
- }
- padNum = numZeros;
- }
- }
- eb.putByte(0);
- eb.putBytes(m4);
- return eb;
- }
- function _decodePkcs1_v1_5(em, key2, pub, ml, options2) {
- var k4 = Math.ceil(key2.n.bitLength() / 8);
- var eb = forge.util.createBuffer(em);
- var first = eb.getByte();
- var bt = eb.getByte();
- if (first !== 0 || pub && bt !== 0 && bt !== 1 || !pub && bt !== 2 || pub && bt === 0 && typeof ml === "undefined") {
- throw new Error("Encryption block is invalid.");
- }
- var padNum = 0;
- if (bt === 0) {
- padNum = k4 - 3 - ml;
- for (var i6 = 0;i6 < padNum; ++i6) {
- if (eb.getByte() !== 0) {
- throw new Error("Encryption block is invalid.");
- }
- }
- } else if (bt === 1) {
- padNum = 0;
- while (eb.length() > 1) {
- if (eb.getByte() !== 255) {
- --eb.read;
- break;
- }
- ++padNum;
- }
- if (padNum < 8 && !(options2 ? options2._skipPaddingChecks : false)) {
- throw new Error("Encryption block is invalid.");
- }
- } else if (bt === 2) {
- padNum = 0;
- while (eb.length() > 1) {
- if (eb.getByte() === 0) {
- --eb.read;
- break;
- }
- ++padNum;
- }
- if (padNum < 8 && !(options2 ? options2._skipPaddingChecks : false)) {
- throw new Error("Encryption block is invalid.");
- }
- }
- var zero = eb.getByte();
- if (zero !== 0 || padNum !== k4 - 3 - eb.length()) {
- throw new Error("Encryption block is invalid.");
- }
- return eb.getBytes();
- }
- function _generateKeyPair(state3, options2, callback) {
- if (typeof options2 === "function") {
- callback = options2;
- options2 = {};
- }
- options2 = options2 || {};
- var opts = {
- algorithm: {
- name: options2.algorithm || "PRIMEINC",
- options: {
- workers: options2.workers || 2,
- workLoad: options2.workLoad || 100,
- workerScript: options2.workerScript
- }
- }
- };
- if ("prng" in options2) {
- opts.prng = options2.prng;
- }
- generate5();
- function generate5() {
- getPrime(state3.pBits, function(err2, num) {
- if (err2) {
- return callback(err2);
- }
- state3.p = num;
- if (state3.q !== null) {
- return finish(err2, state3.q);
- }
- getPrime(state3.qBits, finish);
- });
- }
- function getPrime(bits2, callback2) {
- forge.prime.generateProbablePrime(bits2, opts, callback2);
- }
- function finish(err2, num) {
- if (err2) {
- return callback(err2);
- }
- state3.q = num;
- if (state3.p.compareTo(state3.q) < 0) {
- var tmp = state3.p;
- state3.p = state3.q;
- state3.q = tmp;
- }
- if (state3.p.subtract(BigInteger.ONE).gcd(state3.e).compareTo(BigInteger.ONE) !== 0) {
- state3.p = null;
- generate5();
- return;
- }
- if (state3.q.subtract(BigInteger.ONE).gcd(state3.e).compareTo(BigInteger.ONE) !== 0) {
- state3.q = null;
- getPrime(state3.qBits, finish);
- return;
- }
- state3.p1 = state3.p.subtract(BigInteger.ONE);
- state3.q1 = state3.q.subtract(BigInteger.ONE);
- state3.phi = state3.p1.multiply(state3.q1);
- if (state3.phi.gcd(state3.e).compareTo(BigInteger.ONE) !== 0) {
- state3.p = state3.q = null;
- generate5();
- return;
- }
- state3.n = state3.p.multiply(state3.q);
- if (state3.n.bitLength() !== state3.bits) {
- state3.q = null;
- getPrime(state3.qBits, finish);
- return;
- }
- var d4 = state3.e.modInverse(state3.phi);
- state3.keys = {
- privateKey: pki.rsa.setPrivateKey(state3.n, state3.e, d4, state3.p, state3.q, d4.mod(state3.p1), d4.mod(state3.q1), state3.q.modInverse(state3.p)),
- publicKey: pki.rsa.setPublicKey(state3.n, state3.e)
- };
- callback(null, state3.keys);
- }
- }
- function _bnToBytes(b5) {
- var hex = b5.toString(16);
- if (hex[0] >= "8") {
- hex = "00" + hex;
- }
- var bytes = forge.util.hexToBytes(hex);
- if (bytes.length > 1 && (bytes.charCodeAt(0) === 0 && (bytes.charCodeAt(1) & 128) === 0 || bytes.charCodeAt(0) === 255 && (bytes.charCodeAt(1) & 128) === 128)) {
- return bytes.substr(1);
- }
- return bytes;
- }
- function _getMillerRabinTests(bits2) {
- if (bits2 <= 100)
- return 27;
- if (bits2 <= 150)
- return 18;
- if (bits2 <= 200)
- return 15;
- if (bits2 <= 250)
- return 12;
- if (bits2 <= 300)
- return 9;
- if (bits2 <= 350)
- return 8;
- if (bits2 <= 400)
- return 7;
- if (bits2 <= 500)
- return 6;
- if (bits2 <= 600)
- return 5;
- if (bits2 <= 800)
- return 4;
- if (bits2 <= 1250)
- return 3;
- return 2;
- }
- function _detectNodeCrypto(fn) {
- return forge.util.isNodejs && typeof _crypto[fn] === "function";
- }
- function _detectSubtleCrypto(fn) {
- return typeof util12.globalScope !== "undefined" && typeof util12.globalScope.crypto === "object" && typeof util12.globalScope.crypto.subtle === "object" && typeof util12.globalScope.crypto.subtle[fn] === "function";
- }
- function _detectSubtleMsCrypto(fn) {
- return typeof util12.globalScope !== "undefined" && typeof util12.globalScope.msCrypto === "object" && typeof util12.globalScope.msCrypto.subtle === "object" && typeof util12.globalScope.msCrypto.subtle[fn] === "function";
- }
- function _intToUint8Array(x4) {
- var bytes = forge.util.hexToBytes(x4.toString(16));
- var buffer = new Uint8Array(bytes.length);
- for (var i6 = 0;i6 < bytes.length; ++i6) {
- buffer[i6] = bytes.charCodeAt(i6);
- }
- return buffer;
- }
-});
-
-// node_modules/node-forge/lib/pbe.js
-var require_pbe = __commonJS((exports, module) => {
- var forge = require_forge();
- require_aes();
- require_asn1();
- require_des();
- require_md();
- require_oids();
- require_pbkdf2();
- require_pem();
- require_random();
- require_rc2();
- require_rsa();
- require_util3();
- if (typeof BigInteger === "undefined") {
- BigInteger = forge.jsbn.BigInteger;
- }
- var BigInteger;
- var asn1 = forge.asn1;
- var pki = forge.pki = forge.pki || {};
- module.exports = pki.pbe = forge.pbe = forge.pbe || {};
- var oids = pki.oids;
- var encryptedPrivateKeyValidator = {
- name: "EncryptedPrivateKeyInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "EncryptedPrivateKeyInfo.encryptionAlgorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "AlgorithmIdentifier.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "encryptionOid"
- }, {
- name: "AlgorithmIdentifier.parameters",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: "encryptionParams"
- }]
- }, {
- name: "EncryptedPrivateKeyInfo.encryptedData",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: "encryptedData"
- }]
- };
- var PBES2AlgorithmsValidator = {
- name: "PBES2Algorithms",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "PBES2Algorithms.keyDerivationFunc",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "PBES2Algorithms.keyDerivationFunc.oid",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "kdfOid"
- }, {
- name: "PBES2Algorithms.params",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "PBES2Algorithms.params.salt",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: "kdfSalt"
- }, {
- name: "PBES2Algorithms.params.iterationCount",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "kdfIterationCount"
- }, {
- name: "PBES2Algorithms.params.keyLength",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- optional: true,
- capture: "keyLength"
- }, {
- name: "PBES2Algorithms.params.prf",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- optional: true,
- value: [{
- name: "PBES2Algorithms.params.prf.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "prfOid"
- }]
- }]
- }]
- }, {
- name: "PBES2Algorithms.encryptionScheme",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "PBES2Algorithms.encryptionScheme.oid",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "encOid"
- }, {
- name: "PBES2Algorithms.encryptionScheme.iv",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: "encIv"
- }]
- }]
- };
- var pkcs12PbeParamsValidator = {
- name: "pkcs-12PbeParams",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "pkcs-12PbeParams.salt",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: "salt"
- }, {
- name: "pkcs-12PbeParams.iterations",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "iterations"
- }]
- };
- pki.encryptPrivateKeyInfo = function(obj, password, options2) {
- options2 = options2 || {};
- options2.saltSize = options2.saltSize || 8;
- options2.count = options2.count || 2048;
- options2.algorithm = options2.algorithm || "aes128";
- options2.prfAlgorithm = options2.prfAlgorithm || "sha1";
- var salt = forge.random.getBytesSync(options2.saltSize);
- var count3 = options2.count;
- var countBytes = asn1.integerToDer(count3);
- var dkLen;
- var encryptionAlgorithm;
- var encryptedData;
- if (options2.algorithm.indexOf("aes") === 0 || options2.algorithm === "des") {
- var ivLen, encOid, cipherFn;
- switch (options2.algorithm) {
- case "aes128":
- dkLen = 16;
- ivLen = 16;
- encOid = oids["aes128-CBC"];
- cipherFn = forge.aes.createEncryptionCipher;
- break;
- case "aes192":
- dkLen = 24;
- ivLen = 16;
- encOid = oids["aes192-CBC"];
- cipherFn = forge.aes.createEncryptionCipher;
- break;
- case "aes256":
- dkLen = 32;
- ivLen = 16;
- encOid = oids["aes256-CBC"];
- cipherFn = forge.aes.createEncryptionCipher;
- break;
- case "des":
- dkLen = 8;
- ivLen = 8;
- encOid = oids["desCBC"];
- cipherFn = forge.des.createEncryptionCipher;
- break;
- default:
- var error46 = new Error("Cannot encrypt private key. Unknown encryption algorithm.");
- error46.algorithm = options2.algorithm;
- throw error46;
- }
- var prfAlgorithm = "hmacWith" + options2.prfAlgorithm.toUpperCase();
- var md = prfAlgorithmToMessageDigest(prfAlgorithm);
- var dk = forge.pkcs5.pbkdf2(password, salt, count3, dkLen, md);
- var iv = forge.random.getBytesSync(ivLen);
- var cipher = cipherFn(dk);
- cipher.start(iv);
- cipher.update(asn1.toDer(obj));
- cipher.finish();
- encryptedData = cipher.output.getBytes();
- var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);
- encryptionAlgorithm = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids["pkcs5PBES2"]).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids["pkcs5PBKDF2"]).getBytes()),
- params
- ]),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(encOid).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)
- ])
- ])
- ]);
- } else if (options2.algorithm === "3des") {
- dkLen = 24;
- var saltBytes = new forge.util.ByteBuffer(salt);
- var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count3, dkLen);
- var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count3, dkLen);
- var cipher = forge.des.createEncryptionCipher(dk);
- cipher.start(iv);
- cipher.update(asn1.toDer(obj));
- cipher.finish();
- encryptedData = cipher.output.getBytes();
- encryptionAlgorithm = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, countBytes.getBytes())
- ])
- ]);
- } else {
- var error46 = new Error("Cannot encrypt private key. Unknown encryption algorithm.");
- error46.algorithm = options2.algorithm;
- throw error46;
- }
- var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- encryptionAlgorithm,
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)
- ]);
- return rval;
- };
- pki.decryptPrivateKeyInfo = function(obj, password) {
- var rval = null;
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors8)) {
- var error46 = new Error("Cannot read encrypted private key. " + "ASN.1 object is not a supported EncryptedPrivateKeyInfo.");
- error46.errors = errors8;
- throw error46;
- }
- var oid = asn1.derToOid(capture.encryptionOid);
- var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);
- var encrypted = forge.util.createBuffer(capture.encryptedData);
- cipher.update(encrypted);
- if (cipher.finish()) {
- rval = asn1.fromDer(cipher.output);
- }
- return rval;
- };
- pki.encryptedPrivateKeyToPem = function(epki, maxline) {
- var msg = {
- type: "ENCRYPTED PRIVATE KEY",
- body: asn1.toDer(epki).getBytes()
- };
- return forge.pem.encode(msg, { maxline });
- };
- pki.encryptedPrivateKeyFromPem = function(pem) {
- var msg = forge.pem.decode(pem)[0];
- if (msg.type !== "ENCRYPTED PRIVATE KEY") {
- var error46 = new Error("Could not convert encrypted private key from PEM; " + 'PEM header type is "ENCRYPTED PRIVATE KEY".');
- error46.headerType = msg.type;
- throw error46;
- }
- if (msg.procType && msg.procType.type === "ENCRYPTED") {
- throw new Error("Could not convert encrypted private key from PEM; " + "PEM is encrypted.");
- }
- return asn1.fromDer(msg.body);
- };
- pki.encryptRsaPrivateKey = function(rsaKey, password, options2) {
- options2 = options2 || {};
- if (!options2.legacy) {
- var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));
- rval = pki.encryptPrivateKeyInfo(rval, password, options2);
- return pki.encryptedPrivateKeyToPem(rval);
- }
- var algorithm;
- var iv;
- var dkLen;
- var cipherFn;
- switch (options2.algorithm) {
- case "aes128":
- algorithm = "AES-128-CBC";
- dkLen = 16;
- iv = forge.random.getBytesSync(16);
- cipherFn = forge.aes.createEncryptionCipher;
- break;
- case "aes192":
- algorithm = "AES-192-CBC";
- dkLen = 24;
- iv = forge.random.getBytesSync(16);
- cipherFn = forge.aes.createEncryptionCipher;
- break;
- case "aes256":
- algorithm = "AES-256-CBC";
- dkLen = 32;
- iv = forge.random.getBytesSync(16);
- cipherFn = forge.aes.createEncryptionCipher;
- break;
- case "3des":
- algorithm = "DES-EDE3-CBC";
- dkLen = 24;
- iv = forge.random.getBytesSync(8);
- cipherFn = forge.des.createEncryptionCipher;
- break;
- case "des":
- algorithm = "DES-CBC";
- dkLen = 8;
- iv = forge.random.getBytesSync(8);
- cipherFn = forge.des.createEncryptionCipher;
- break;
- default:
- var error46 = new Error("Could not encrypt RSA private key; unsupported " + 'encryption algorithm "' + options2.algorithm + '".');
- error46.algorithm = options2.algorithm;
- throw error46;
- }
- var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);
- var cipher = cipherFn(dk);
- cipher.start(iv);
- cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));
- cipher.finish();
- var msg = {
- type: "RSA PRIVATE KEY",
- procType: {
- version: "4",
- type: "ENCRYPTED"
- },
- dekInfo: {
- algorithm,
- parameters: forge.util.bytesToHex(iv).toUpperCase()
- },
- body: cipher.output.getBytes()
- };
- return forge.pem.encode(msg);
- };
- pki.decryptRsaPrivateKey = function(pem, password) {
- var rval = null;
- var msg = forge.pem.decode(pem)[0];
- if (msg.type !== "ENCRYPTED PRIVATE KEY" && msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") {
- var error46 = new Error("Could not convert private key from PEM; PEM header type " + 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');
- error46.headerType = error46;
- throw error46;
- }
- if (msg.procType && msg.procType.type === "ENCRYPTED") {
- var dkLen;
- var cipherFn;
- switch (msg.dekInfo.algorithm) {
- case "DES-CBC":
- dkLen = 8;
- cipherFn = forge.des.createDecryptionCipher;
- break;
- case "DES-EDE3-CBC":
- dkLen = 24;
- cipherFn = forge.des.createDecryptionCipher;
- break;
- case "AES-128-CBC":
- dkLen = 16;
- cipherFn = forge.aes.createDecryptionCipher;
- break;
- case "AES-192-CBC":
- dkLen = 24;
- cipherFn = forge.aes.createDecryptionCipher;
- break;
- case "AES-256-CBC":
- dkLen = 32;
- cipherFn = forge.aes.createDecryptionCipher;
- break;
- case "RC2-40-CBC":
- dkLen = 5;
- cipherFn = function(key2) {
- return forge.rc2.createDecryptionCipher(key2, 40);
- };
- break;
- case "RC2-64-CBC":
- dkLen = 8;
- cipherFn = function(key2) {
- return forge.rc2.createDecryptionCipher(key2, 64);
- };
- break;
- case "RC2-128-CBC":
- dkLen = 16;
- cipherFn = function(key2) {
- return forge.rc2.createDecryptionCipher(key2, 128);
- };
- break;
- default:
- var error46 = new Error("Could not decrypt private key; unsupported " + 'encryption algorithm "' + msg.dekInfo.algorithm + '".');
- error46.algorithm = msg.dekInfo.algorithm;
- throw error46;
- }
- var iv = forge.util.hexToBytes(msg.dekInfo.parameters);
- var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);
- var cipher = cipherFn(dk);
- cipher.start(iv);
- cipher.update(forge.util.createBuffer(msg.body));
- if (cipher.finish()) {
- rval = cipher.output.getBytes();
- } else {
- return rval;
- }
- } else {
- rval = msg.body;
- }
- if (msg.type === "ENCRYPTED PRIVATE KEY") {
- rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);
- } else {
- rval = asn1.fromDer(rval);
- }
- if (rval !== null) {
- rval = pki.privateKeyFromAsn1(rval);
- }
- return rval;
- };
- pki.pbe.generatePkcs12Key = function(password, salt, id, iter, n5, md) {
- var j4, l4;
- if (typeof md === "undefined" || md === null) {
- if (!("sha1" in forge.md)) {
- throw new Error('"sha1" hash algorithm unavailable.');
- }
- md = forge.md.sha1.create();
- }
- var u5 = md.digestLength;
- var v6 = md.blockLength;
- var result = new forge.util.ByteBuffer;
- var passBuf = new forge.util.ByteBuffer;
- if (password !== null && password !== undefined) {
- for (l4 = 0;l4 < password.length; l4++) {
- passBuf.putInt16(password.charCodeAt(l4));
- }
- passBuf.putInt16(0);
- }
- var p4 = passBuf.length();
- var s4 = salt.length();
- var D3 = new forge.util.ByteBuffer;
- D3.fillWithByte(id, v6);
- var Slen = v6 * Math.ceil(s4 / v6);
- var S = new forge.util.ByteBuffer;
- for (l4 = 0;l4 < Slen; l4++) {
- S.putByte(salt.at(l4 % s4));
- }
- var Plen = v6 * Math.ceil(p4 / v6);
- var P = new forge.util.ByteBuffer;
- for (l4 = 0;l4 < Plen; l4++) {
- P.putByte(passBuf.at(l4 % p4));
- }
- var I3 = S;
- I3.putBuffer(P);
- var c8 = Math.ceil(n5 / u5);
- for (var i6 = 1;i6 <= c8; i6++) {
- var buf = new forge.util.ByteBuffer;
- buf.putBytes(D3.bytes());
- buf.putBytes(I3.bytes());
- for (var round = 0;round < iter; round++) {
- md.start();
- md.update(buf.getBytes());
- buf = md.digest();
- }
- var B2 = new forge.util.ByteBuffer;
- for (l4 = 0;l4 < v6; l4++) {
- B2.putByte(buf.at(l4 % u5));
- }
- var k4 = Math.ceil(s4 / v6) + Math.ceil(p4 / v6);
- var Inew = new forge.util.ByteBuffer;
- for (j4 = 0;j4 < k4; j4++) {
- var chunk = new forge.util.ByteBuffer(I3.getBytes(v6));
- var x4 = 511;
- for (l4 = B2.length() - 1;l4 >= 0; l4--) {
- x4 = x4 >> 8;
- x4 += B2.at(l4) + chunk.at(l4);
- chunk.setAt(l4, x4 & 255);
- }
- Inew.putBuffer(chunk);
- }
- I3 = Inew;
- result.putBuffer(buf);
- }
- result.truncate(result.length() - n5);
- return result;
- };
- pki.pbe.getCipher = function(oid, params, password) {
- switch (oid) {
- case pki.oids["pkcs5PBES2"]:
- return pki.pbe.getCipherForPBES2(oid, params, password);
- case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:
- case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:
- return pki.pbe.getCipherForPKCS12PBE(oid, params, password);
- default:
- var error46 = new Error("Cannot read encrypted PBE data block. Unsupported OID.");
- error46.oid = oid;
- error46.supportedOids = [
- "pkcs5PBES2",
- "pbeWithSHAAnd3-KeyTripleDES-CBC",
- "pbewithSHAAnd40BitRC2-CBC"
- ];
- throw error46;
- }
- };
- pki.pbe.getCipherForPBES2 = function(oid, params, password) {
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors8)) {
- var error46 = new Error("Cannot read password-based-encryption algorithm " + "parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");
- error46.errors = errors8;
- throw error46;
- }
- oid = asn1.derToOid(capture.kdfOid);
- if (oid !== pki.oids["pkcs5PBKDF2"]) {
- var error46 = new Error("Cannot read encrypted private key. " + "Unsupported key derivation function OID.");
- error46.oid = oid;
- error46.supportedOids = ["pkcs5PBKDF2"];
- throw error46;
- }
- oid = asn1.derToOid(capture.encOid);
- if (oid !== pki.oids["aes128-CBC"] && oid !== pki.oids["aes192-CBC"] && oid !== pki.oids["aes256-CBC"] && oid !== pki.oids["des-EDE3-CBC"] && oid !== pki.oids["desCBC"]) {
- var error46 = new Error("Cannot read encrypted private key. " + "Unsupported encryption scheme OID.");
- error46.oid = oid;
- error46.supportedOids = [
- "aes128-CBC",
- "aes192-CBC",
- "aes256-CBC",
- "des-EDE3-CBC",
- "desCBC"
- ];
- throw error46;
- }
- var salt = capture.kdfSalt;
- var count3 = forge.util.createBuffer(capture.kdfIterationCount);
- count3 = count3.getInt(count3.length() << 3);
- var dkLen;
- var cipherFn;
- switch (pki.oids[oid]) {
- case "aes128-CBC":
- dkLen = 16;
- cipherFn = forge.aes.createDecryptionCipher;
- break;
- case "aes192-CBC":
- dkLen = 24;
- cipherFn = forge.aes.createDecryptionCipher;
- break;
- case "aes256-CBC":
- dkLen = 32;
- cipherFn = forge.aes.createDecryptionCipher;
- break;
- case "des-EDE3-CBC":
- dkLen = 24;
- cipherFn = forge.des.createDecryptionCipher;
- break;
- case "desCBC":
- dkLen = 8;
- cipherFn = forge.des.createDecryptionCipher;
- break;
- }
- var md = prfOidToMessageDigest(capture.prfOid);
- var dk = forge.pkcs5.pbkdf2(password, salt, count3, dkLen, md);
- var iv = capture.encIv;
- var cipher = cipherFn(dk);
- cipher.start(iv);
- return cipher;
- };
- pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors8)) {
- var error46 = new Error("Cannot read password-based-encryption algorithm " + "parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");
- error46.errors = errors8;
- throw error46;
- }
- var salt = forge.util.createBuffer(capture.salt);
- var count3 = forge.util.createBuffer(capture.iterations);
- count3 = count3.getInt(count3.length() << 3);
- var dkLen, dIvLen, cipherFn;
- switch (oid) {
- case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:
- dkLen = 24;
- dIvLen = 8;
- cipherFn = forge.des.startDecrypting;
- break;
- case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:
- dkLen = 5;
- dIvLen = 8;
- cipherFn = function(key3, iv2) {
- var cipher = forge.rc2.createDecryptionCipher(key3, 40);
- cipher.start(iv2, null);
- return cipher;
- };
- break;
- default:
- var error46 = new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");
- error46.oid = oid;
- throw error46;
- }
- var md = prfOidToMessageDigest(capture.prfOid);
- var key2 = pki.pbe.generatePkcs12Key(password, salt, 1, count3, dkLen, md);
- md.start();
- var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count3, dIvLen, md);
- return cipherFn(key2, iv);
- };
- pki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {
- if (typeof md === "undefined" || md === null) {
- if (!("md5" in forge.md)) {
- throw new Error('"md5" hash algorithm unavailable.');
- }
- md = forge.md.md5.create();
- }
- if (salt === null) {
- salt = "";
- }
- var digests = [hash2(md, password + salt)];
- for (var length = 16, i6 = 1;length < dkLen; ++i6, length += 16) {
- digests.push(hash2(md, digests[i6 - 1] + password + salt));
- }
- return digests.join("").substr(0, dkLen);
- };
- function hash2(md, bytes) {
- return md.start().update(bytes).digest().getBytes();
- }
- function prfOidToMessageDigest(prfOid) {
- var prfAlgorithm;
- if (!prfOid) {
- prfAlgorithm = "hmacWithSHA1";
- } else {
- prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];
- if (!prfAlgorithm) {
- var error46 = new Error("Unsupported PRF OID.");
- error46.oid = prfOid;
- error46.supported = [
- "hmacWithSHA1",
- "hmacWithSHA224",
- "hmacWithSHA256",
- "hmacWithSHA384",
- "hmacWithSHA512"
- ];
- throw error46;
- }
- }
- return prfAlgorithmToMessageDigest(prfAlgorithm);
- }
- function prfAlgorithmToMessageDigest(prfAlgorithm) {
- var factory2 = forge.md;
- switch (prfAlgorithm) {
- case "hmacWithSHA224":
- factory2 = forge.md.sha512;
- case "hmacWithSHA1":
- case "hmacWithSHA256":
- case "hmacWithSHA384":
- case "hmacWithSHA512":
- prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();
- break;
- default:
- var error46 = new Error("Unsupported PRF algorithm.");
- error46.algorithm = prfAlgorithm;
- error46.supported = [
- "hmacWithSHA1",
- "hmacWithSHA224",
- "hmacWithSHA256",
- "hmacWithSHA384",
- "hmacWithSHA512"
- ];
- throw error46;
- }
- if (!factory2 || !(prfAlgorithm in factory2)) {
- throw new Error("Unknown hash algorithm: " + prfAlgorithm);
- }
- return factory2[prfAlgorithm].create();
- }
- function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {
- var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, countBytes.getBytes())
- ]);
- if (prfAlgorithm !== "hmacWithSHA1") {
- params.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(dkLen.toString(16))), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
- ]));
- }
- return params;
- }
-});
-
-// node_modules/node-forge/lib/pkcs7asn1.js
-var require_pkcs7asn1 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_asn1();
- require_util3();
- var asn1 = forge.asn1;
- var p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {};
- forge.pkcs7 = forge.pkcs7 || {};
- forge.pkcs7.asn1 = p7v;
- var contentInfoValidator = {
- name: "ContentInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "ContentInfo.ContentType",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "contentType"
- }, {
- name: "ContentInfo.content",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 0,
- constructed: true,
- optional: true,
- captureAsn1: "content"
- }]
- };
- p7v.contentInfoValidator = contentInfoValidator;
- var encryptedContentInfoValidator = {
- name: "EncryptedContentInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "EncryptedContentInfo.contentType",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "contentType"
- }, {
- name: "EncryptedContentInfo.contentEncryptionAlgorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "encAlgorithm"
- }, {
- name: "EncryptedContentInfo.contentEncryptionAlgorithm.parameter",
- tagClass: asn1.Class.UNIVERSAL,
- captureAsn1: "encParameter"
- }]
- }, {
- name: "EncryptedContentInfo.encryptedContent",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 0,
- capture: "encryptedContent",
- captureAsn1: "encryptedContentAsn1"
- }]
- };
- p7v.envelopedDataValidator = {
- name: "EnvelopedData",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "EnvelopedData.Version",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "version"
- }, {
- name: "EnvelopedData.RecipientInfos",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SET,
- constructed: true,
- captureAsn1: "recipientInfos"
- }].concat(encryptedContentInfoValidator)
- };
- p7v.encryptedDataValidator = {
- name: "EncryptedData",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "EncryptedData.Version",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "version"
- }].concat(encryptedContentInfoValidator)
- };
- var signerValidator = {
- name: "SignerInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "SignerInfo.version",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false
- }, {
- name: "SignerInfo.issuerAndSerialNumber",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "SignerInfo.issuerAndSerialNumber.issuer",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: "issuer"
- }, {
- name: "SignerInfo.issuerAndSerialNumber.serialNumber",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "serial"
- }]
- }, {
- name: "SignerInfo.digestAlgorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "SignerInfo.digestAlgorithm.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "digestAlgorithm"
- }, {
- name: "SignerInfo.digestAlgorithm.parameter",
- tagClass: asn1.Class.UNIVERSAL,
- constructed: false,
- captureAsn1: "digestParameter",
- optional: true
- }]
- }, {
- name: "SignerInfo.authenticatedAttributes",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 0,
- constructed: true,
- optional: true,
- capture: "authenticatedAttributes"
- }, {
- name: "SignerInfo.digestEncryptionAlgorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- capture: "signatureAlgorithm"
- }, {
- name: "SignerInfo.encryptedDigest",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: "signature"
- }, {
- name: "SignerInfo.unauthenticatedAttributes",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 1,
- constructed: true,
- optional: true,
- capture: "unauthenticatedAttributes"
- }]
- };
- p7v.signedDataValidator = {
- name: "SignedData",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [
- {
- name: "SignedData.Version",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "version"
- },
- {
- name: "SignedData.DigestAlgorithms",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SET,
- constructed: true,
- captureAsn1: "digestAlgorithms"
- },
- contentInfoValidator,
- {
- name: "SignedData.Certificates",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 0,
- optional: true,
- captureAsn1: "certificates"
- },
- {
- name: "SignedData.CertificateRevocationLists",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 1,
- optional: true,
- captureAsn1: "crls"
- },
- {
- name: "SignedData.SignerInfos",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SET,
- capture: "signerInfos",
- optional: true,
- value: [signerValidator]
- }
- ]
- };
- p7v.recipientInfoValidator = {
- name: "RecipientInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "RecipientInfo.version",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "version"
- }, {
- name: "RecipientInfo.issuerAndSerial",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "RecipientInfo.issuerAndSerial.issuer",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: "issuer"
- }, {
- name: "RecipientInfo.issuerAndSerial.serialNumber",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "serial"
- }]
- }, {
- name: "RecipientInfo.keyEncryptionAlgorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "RecipientInfo.keyEncryptionAlgorithm.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "encAlgorithm"
- }, {
- name: "RecipientInfo.keyEncryptionAlgorithm.parameter",
- tagClass: asn1.Class.UNIVERSAL,
- constructed: false,
- captureAsn1: "encParameter",
- optional: true
- }]
- }, {
- name: "RecipientInfo.encryptedKey",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: "encKey"
- }]
- };
-});
-
-// node_modules/node-forge/lib/mgf1.js
-var require_mgf1 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_util3();
- forge.mgf = forge.mgf || {};
- var mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {};
- mgf1.create = function(md) {
- var mgf = {
- generate: function(seed, maskLen) {
- var t4 = new forge.util.ByteBuffer;
- var len = Math.ceil(maskLen / md.digestLength);
- for (var i6 = 0;i6 < len; i6++) {
- var c8 = new forge.util.ByteBuffer;
- c8.putInt32(i6);
- md.start();
- md.update(seed + c8.getBytes());
- t4.putBuffer(md.digest());
- }
- t4.truncate(t4.length() - maskLen);
- return t4.getBytes();
- }
- };
- return mgf;
- };
-});
-
-// node_modules/node-forge/lib/mgf.js
-var require_mgf = __commonJS((exports, module) => {
- var forge = require_forge();
- require_mgf1();
- module.exports = forge.mgf = forge.mgf || {};
- forge.mgf.mgf1 = forge.mgf1;
-});
-
-// node_modules/node-forge/lib/pss.js
-var require_pss = __commonJS((exports, module) => {
- var forge = require_forge();
- require_random();
- require_util3();
- var pss = module.exports = forge.pss = forge.pss || {};
- pss.create = function(options2) {
- if (arguments.length === 3) {
- options2 = {
- md: arguments[0],
- mgf: arguments[1],
- saltLength: arguments[2]
- };
- }
- var hash2 = options2.md;
- var mgf = options2.mgf;
- var hLen = hash2.digestLength;
- var salt_ = options2.salt || null;
- if (typeof salt_ === "string") {
- salt_ = forge.util.createBuffer(salt_);
- }
- var sLen;
- if ("saltLength" in options2) {
- sLen = options2.saltLength;
- } else if (salt_ !== null) {
- sLen = salt_.length();
- } else {
- throw new Error("Salt length not specified or specific salt not given.");
- }
- if (salt_ !== null && salt_.length() !== sLen) {
- throw new Error("Given salt length does not match length of given salt.");
- }
- var prng = options2.prng || forge.random;
- var pssobj = {};
- pssobj.encode = function(md, modBits) {
- var i6;
- var emBits = modBits - 1;
- var emLen = Math.ceil(emBits / 8);
- var mHash = md.digest().getBytes();
- if (emLen < hLen + sLen + 2) {
- throw new Error("Message is too long to encrypt.");
- }
- var salt;
- if (salt_ === null) {
- salt = prng.getBytesSync(sLen);
- } else {
- salt = salt_.bytes();
- }
- var m_ = new forge.util.ByteBuffer;
- m_.fillWithByte(0, 8);
- m_.putBytes(mHash);
- m_.putBytes(salt);
- hash2.start();
- hash2.update(m_.getBytes());
- var h5 = hash2.digest().getBytes();
- var ps = new forge.util.ByteBuffer;
- ps.fillWithByte(0, emLen - sLen - hLen - 2);
- ps.putByte(1);
- ps.putBytes(salt);
- var db = ps.getBytes();
- var maskLen = emLen - hLen - 1;
- var dbMask = mgf.generate(h5, maskLen);
- var maskedDB = "";
- for (i6 = 0;i6 < maskLen; i6++) {
- maskedDB += String.fromCharCode(db.charCodeAt(i6) ^ dbMask.charCodeAt(i6));
- }
- var mask = 65280 >> 8 * emLen - emBits & 255;
- maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1);
- return maskedDB + h5 + String.fromCharCode(188);
- };
- pssobj.verify = function(mHash, em, modBits) {
- var i6;
- var emBits = modBits - 1;
- var emLen = Math.ceil(emBits / 8);
- em = em.substr(-emLen);
- if (emLen < hLen + sLen + 2) {
- throw new Error("Inconsistent parameters to PSS signature verification.");
- }
- if (em.charCodeAt(emLen - 1) !== 188) {
- throw new Error("Encoded message does not end in 0xBC.");
- }
- var maskLen = emLen - hLen - 1;
- var maskedDB = em.substr(0, maskLen);
- var h5 = em.substr(maskLen, hLen);
- var mask = 65280 >> 8 * emLen - emBits & 255;
- if ((maskedDB.charCodeAt(0) & mask) !== 0) {
- throw new Error("Bits beyond keysize not zero as expected.");
- }
- var dbMask = mgf.generate(h5, maskLen);
- var db = "";
- for (i6 = 0;i6 < maskLen; i6++) {
- db += String.fromCharCode(maskedDB.charCodeAt(i6) ^ dbMask.charCodeAt(i6));
- }
- db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);
- var checkLen = emLen - hLen - sLen - 2;
- for (i6 = 0;i6 < checkLen; i6++) {
- if (db.charCodeAt(i6) !== 0) {
- throw new Error("Leftmost octets not zero as expected");
- }
- }
- if (db.charCodeAt(checkLen) !== 1) {
- throw new Error("Inconsistent PSS signature, 0x01 marker not found");
- }
- var salt = db.substr(-sLen);
- var m_ = new forge.util.ByteBuffer;
- m_.fillWithByte(0, 8);
- m_.putBytes(mHash);
- m_.putBytes(salt);
- hash2.start();
- hash2.update(m_.getBytes());
- var h_ = hash2.digest().getBytes();
- return h5 === h_;
- };
- return pssobj;
- };
-});
-
-// node_modules/node-forge/lib/x509.js
-var require_x509 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_aes();
- require_asn1();
- require_des();
- require_md();
- require_mgf();
- require_oids();
- require_pem();
- require_pss();
- require_rsa();
- require_util3();
- var asn1 = forge.asn1;
- var pki = module.exports = forge.pki = forge.pki || {};
- var oids = pki.oids;
- var _shortNames = {};
- _shortNames["CN"] = oids["commonName"];
- _shortNames["commonName"] = "CN";
- _shortNames["C"] = oids["countryName"];
- _shortNames["countryName"] = "C";
- _shortNames["L"] = oids["localityName"];
- _shortNames["localityName"] = "L";
- _shortNames["ST"] = oids["stateOrProvinceName"];
- _shortNames["stateOrProvinceName"] = "ST";
- _shortNames["O"] = oids["organizationName"];
- _shortNames["organizationName"] = "O";
- _shortNames["OU"] = oids["organizationalUnitName"];
- _shortNames["organizationalUnitName"] = "OU";
- _shortNames["E"] = oids["emailAddress"];
- _shortNames["emailAddress"] = "E";
- var publicKeyValidator = forge.pki.rsa.publicKeyValidator;
- var x509CertificateValidator = {
- name: "Certificate",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "Certificate.TBSCertificate",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: "tbsCertificate",
- value: [
- {
- name: "Certificate.TBSCertificate.version",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 0,
- constructed: true,
- optional: true,
- value: [{
- name: "Certificate.TBSCertificate.version.integer",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "certVersion"
- }]
- },
- {
- name: "Certificate.TBSCertificate.serialNumber",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "certSerialNumber"
- },
- {
- name: "Certificate.TBSCertificate.signature",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "Certificate.TBSCertificate.signature.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "certinfoSignatureOid"
- }, {
- name: "Certificate.TBSCertificate.signature.parameters",
- tagClass: asn1.Class.UNIVERSAL,
- optional: true,
- captureAsn1: "certinfoSignatureParams"
- }]
- },
- {
- name: "Certificate.TBSCertificate.issuer",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: "certIssuer"
- },
- {
- name: "Certificate.TBSCertificate.validity",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "Certificate.TBSCertificate.validity.notBefore (utc)",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.UTCTIME,
- constructed: false,
- optional: true,
- capture: "certValidity1UTCTime"
- }, {
- name: "Certificate.TBSCertificate.validity.notBefore (generalized)",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.GENERALIZEDTIME,
- constructed: false,
- optional: true,
- capture: "certValidity2GeneralizedTime"
- }, {
- name: "Certificate.TBSCertificate.validity.notAfter (utc)",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.UTCTIME,
- constructed: false,
- optional: true,
- capture: "certValidity3UTCTime"
- }, {
- name: "Certificate.TBSCertificate.validity.notAfter (generalized)",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.GENERALIZEDTIME,
- constructed: false,
- optional: true,
- capture: "certValidity4GeneralizedTime"
- }]
- },
- {
- name: "Certificate.TBSCertificate.subject",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: "certSubject"
- },
- publicKeyValidator,
- {
- name: "Certificate.TBSCertificate.issuerUniqueID",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 1,
- constructed: true,
- optional: true,
- value: [{
- name: "Certificate.TBSCertificate.issuerUniqueID.id",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.BITSTRING,
- constructed: false,
- captureBitStringValue: "certIssuerUniqueId"
- }]
- },
- {
- name: "Certificate.TBSCertificate.subjectUniqueID",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 2,
- constructed: true,
- optional: true,
- value: [{
- name: "Certificate.TBSCertificate.subjectUniqueID.id",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.BITSTRING,
- constructed: false,
- captureBitStringValue: "certSubjectUniqueId"
- }]
- },
- {
- name: "Certificate.TBSCertificate.extensions",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 3,
- constructed: true,
- captureAsn1: "certExtensions",
- optional: true
- }
- ]
- }, {
- name: "Certificate.signatureAlgorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "Certificate.signatureAlgorithm.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "certSignatureOid"
- }, {
- name: "Certificate.TBSCertificate.signature.parameters",
- tagClass: asn1.Class.UNIVERSAL,
- optional: true,
- captureAsn1: "certSignatureParams"
- }]
- }, {
- name: "Certificate.signatureValue",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.BITSTRING,
- constructed: false,
- captureBitStringValue: "certSignature"
- }]
- };
- var rsassaPssParameterValidator = {
- name: "rsapss",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "rsapss.hashAlgorithm",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 0,
- constructed: true,
- value: [{
- name: "rsapss.hashAlgorithm.AlgorithmIdentifier",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Class.SEQUENCE,
- constructed: true,
- optional: true,
- value: [{
- name: "rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "hashOid"
- }]
- }]
- }, {
- name: "rsapss.maskGenAlgorithm",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 1,
- constructed: true,
- value: [{
- name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Class.SEQUENCE,
- constructed: true,
- optional: true,
- value: [{
- name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "maskGenOid"
- }, {
- name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "maskGenHashOid"
- }]
- }]
- }]
- }, {
- name: "rsapss.saltLength",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 2,
- optional: true,
- value: [{
- name: "rsapss.saltLength.saltLength",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Class.INTEGER,
- constructed: false,
- capture: "saltLength"
- }]
- }, {
- name: "rsapss.trailerField",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 3,
- optional: true,
- value: [{
- name: "rsapss.trailer.trailer",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Class.INTEGER,
- constructed: false,
- capture: "trailer"
- }]
- }]
- };
- var certificationRequestInfoValidator = {
- name: "CertificationRequestInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: "certificationRequestInfo",
- value: [
- {
- name: "CertificationRequestInfo.integer",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "certificationRequestInfoVersion"
- },
- {
- name: "CertificationRequestInfo.subject",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: "certificationRequestInfoSubject"
- },
- publicKeyValidator,
- {
- name: "CertificationRequestInfo.attributes",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- type: 0,
- constructed: true,
- optional: true,
- capture: "certificationRequestInfoAttributes",
- value: [{
- name: "CertificationRequestInfo.attributes",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "CertificationRequestInfo.attributes.type",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false
- }, {
- name: "CertificationRequestInfo.attributes.value",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SET,
- constructed: true
- }]
- }]
- }
- ]
- };
- var certificationRequestValidator = {
- name: "CertificationRequest",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: "csr",
- value: [
- certificationRequestInfoValidator,
- {
- name: "CertificationRequest.signatureAlgorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "CertificationRequest.signatureAlgorithm.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "csrSignatureOid"
- }, {
- name: "CertificationRequest.signatureAlgorithm.parameters",
- tagClass: asn1.Class.UNIVERSAL,
- optional: true,
- captureAsn1: "csrSignatureParams"
- }]
- },
- {
- name: "CertificationRequest.signature",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.BITSTRING,
- constructed: false,
- captureBitStringValue: "csrSignature"
- }
- ]
- };
- pki.RDNAttributesAsArray = function(rdn, md) {
- var rval = [];
- var set2, attr, obj;
- for (var si = 0;si < rdn.value.length; ++si) {
- set2 = rdn.value[si];
- for (var i6 = 0;i6 < set2.value.length; ++i6) {
- obj = {};
- attr = set2.value[i6];
- obj.type = asn1.derToOid(attr.value[0].value);
- obj.value = attr.value[1].value;
- obj.valueTagClass = attr.value[1].type;
- if (obj.type in oids) {
- obj.name = oids[obj.type];
- if (obj.name in _shortNames) {
- obj.shortName = _shortNames[obj.name];
- }
- }
- if (md) {
- md.update(obj.type);
- md.update(obj.value);
- }
- rval.push(obj);
- }
- }
- return rval;
- };
- pki.CRIAttributesAsArray = function(attributes) {
- var rval = [];
- for (var si = 0;si < attributes.length; ++si) {
- var seq = attributes[si];
- var type = asn1.derToOid(seq.value[0].value);
- var values2 = seq.value[1].value;
- for (var vi = 0;vi < values2.length; ++vi) {
- var obj = {};
- obj.type = type;
- obj.value = values2[vi].value;
- obj.valueTagClass = values2[vi].type;
- if (obj.type in oids) {
- obj.name = oids[obj.type];
- if (obj.name in _shortNames) {
- obj.shortName = _shortNames[obj.name];
- }
- }
- if (obj.type === oids.extensionRequest) {
- obj.extensions = [];
- for (var ei = 0;ei < obj.value.length; ++ei) {
- obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));
- }
- }
- rval.push(obj);
- }
- }
- return rval;
- };
- function _getAttribute(obj, options2) {
- if (typeof options2 === "string") {
- options2 = { shortName: options2 };
- }
- var rval = null;
- var attr;
- for (var i6 = 0;rval === null && i6 < obj.attributes.length; ++i6) {
- attr = obj.attributes[i6];
- if (options2.type && options2.type === attr.type) {
- rval = attr;
- } else if (options2.name && options2.name === attr.name) {
- rval = attr;
- } else if (options2.shortName && options2.shortName === attr.shortName) {
- rval = attr;
- }
- }
- return rval;
- }
- var _readSignatureParameters = function(oid, obj, fillDefaults) {
- var params = {};
- if (oid !== oids["RSASSA-PSS"]) {
- return params;
- }
- if (fillDefaults) {
- params = {
- hash: {
- algorithmOid: oids["sha1"]
- },
- mgf: {
- algorithmOid: oids["mgf1"],
- hash: {
- algorithmOid: oids["sha1"]
- }
- },
- saltLength: 20
- };
- }
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(obj, rsassaPssParameterValidator, capture, errors8)) {
- var error46 = new Error("Cannot read RSASSA-PSS parameter block.");
- error46.errors = errors8;
- throw error46;
- }
- if (capture.hashOid !== undefined) {
- params.hash = params.hash || {};
- params.hash.algorithmOid = asn1.derToOid(capture.hashOid);
- }
- if (capture.maskGenOid !== undefined) {
- params.mgf = params.mgf || {};
- params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);
- params.mgf.hash = params.mgf.hash || {};
- params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);
- }
- if (capture.saltLength !== undefined) {
- params.saltLength = capture.saltLength.charCodeAt(0);
- }
- return params;
- };
- var _createSignatureDigest = function(options2) {
- switch (oids[options2.signatureOid]) {
- case "sha1WithRSAEncryption":
- case "sha1WithRSASignature":
- return forge.md.sha1.create();
- case "md5WithRSAEncryption":
- return forge.md.md5.create();
- case "sha256WithRSAEncryption":
- return forge.md.sha256.create();
- case "sha384WithRSAEncryption":
- return forge.md.sha384.create();
- case "sha512WithRSAEncryption":
- return forge.md.sha512.create();
- case "RSASSA-PSS":
- return forge.md.sha256.create();
- default:
- var error46 = new Error("Could not compute " + options2.type + " digest. " + "Unknown signature OID.");
- error46.signatureOid = options2.signatureOid;
- throw error46;
- }
- };
- var _verifySignature = function(options2) {
- var cert = options2.certificate;
- var scheme;
- switch (cert.signatureOid) {
- case oids.sha1WithRSAEncryption:
- case oids.sha1WithRSASignature:
- break;
- case oids["RSASSA-PSS"]:
- var hash2, mgf;
- hash2 = oids[cert.signatureParameters.mgf.hash.algorithmOid];
- if (hash2 === undefined || forge.md[hash2] === undefined) {
- var error46 = new Error("Unsupported MGF hash function.");
- error46.oid = cert.signatureParameters.mgf.hash.algorithmOid;
- error46.name = hash2;
- throw error46;
- }
- mgf = oids[cert.signatureParameters.mgf.algorithmOid];
- if (mgf === undefined || forge.mgf[mgf] === undefined) {
- var error46 = new Error("Unsupported MGF function.");
- error46.oid = cert.signatureParameters.mgf.algorithmOid;
- error46.name = mgf;
- throw error46;
- }
- mgf = forge.mgf[mgf].create(forge.md[hash2].create());
- hash2 = oids[cert.signatureParameters.hash.algorithmOid];
- if (hash2 === undefined || forge.md[hash2] === undefined) {
- var error46 = new Error("Unsupported RSASSA-PSS hash function.");
- error46.oid = cert.signatureParameters.hash.algorithmOid;
- error46.name = hash2;
- throw error46;
- }
- scheme = forge.pss.create(forge.md[hash2].create(), mgf, cert.signatureParameters.saltLength);
- break;
- }
- return cert.publicKey.verify(options2.md.digest().getBytes(), options2.signature, scheme);
- };
- pki.certificateFromPem = function(pem, computeHash, strict) {
- var msg = forge.pem.decode(pem)[0];
- if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") {
- var error46 = new Error("Could not convert certificate from PEM; PEM header type " + 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');
- error46.headerType = msg.type;
- throw error46;
- }
- if (msg.procType && msg.procType.type === "ENCRYPTED") {
- throw new Error("Could not convert certificate from PEM; PEM is encrypted.");
- }
- var obj = asn1.fromDer(msg.body, strict);
- return pki.certificateFromAsn1(obj, computeHash);
- };
- pki.certificateToPem = function(cert, maxline) {
- var msg = {
- type: "CERTIFICATE",
- body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()
- };
- return forge.pem.encode(msg, { maxline });
- };
- pki.publicKeyFromPem = function(pem) {
- var msg = forge.pem.decode(pem)[0];
- if (msg.type !== "PUBLIC KEY" && msg.type !== "RSA PUBLIC KEY") {
- var error46 = new Error("Could not convert public key from PEM; PEM header " + 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');
- error46.headerType = msg.type;
- throw error46;
- }
- if (msg.procType && msg.procType.type === "ENCRYPTED") {
- throw new Error("Could not convert public key from PEM; PEM is encrypted.");
- }
- var obj = asn1.fromDer(msg.body);
- return pki.publicKeyFromAsn1(obj);
- };
- pki.publicKeyToPem = function(key2, maxline) {
- var msg = {
- type: "PUBLIC KEY",
- body: asn1.toDer(pki.publicKeyToAsn1(key2)).getBytes()
- };
- return forge.pem.encode(msg, { maxline });
- };
- pki.publicKeyToRSAPublicKeyPem = function(key2, maxline) {
- var msg = {
- type: "RSA PUBLIC KEY",
- body: asn1.toDer(pki.publicKeyToRSAPublicKey(key2)).getBytes()
- };
- return forge.pem.encode(msg, { maxline });
- };
- pki.getPublicKeyFingerprint = function(key2, options2) {
- options2 = options2 || {};
- var md = options2.md || forge.md.sha1.create();
- var type = options2.type || "RSAPublicKey";
- var bytes;
- switch (type) {
- case "RSAPublicKey":
- bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key2)).getBytes();
- break;
- case "SubjectPublicKeyInfo":
- bytes = asn1.toDer(pki.publicKeyToAsn1(key2)).getBytes();
- break;
- default:
- throw new Error('Unknown fingerprint type "' + options2.type + '".');
- }
- md.start();
- md.update(bytes);
- var digest = md.digest();
- if (options2.encoding === "hex") {
- var hex = digest.toHex();
- if (options2.delimiter) {
- return hex.match(/.{2}/g).join(options2.delimiter);
- }
- return hex;
- } else if (options2.encoding === "binary") {
- return digest.getBytes();
- } else if (options2.encoding) {
- throw new Error('Unknown encoding "' + options2.encoding + '".');
- }
- return digest;
- };
- pki.certificationRequestFromPem = function(pem, computeHash, strict) {
- var msg = forge.pem.decode(pem)[0];
- if (msg.type !== "CERTIFICATE REQUEST") {
- var error46 = new Error("Could not convert certification request from PEM; " + 'PEM header type is not "CERTIFICATE REQUEST".');
- error46.headerType = msg.type;
- throw error46;
- }
- if (msg.procType && msg.procType.type === "ENCRYPTED") {
- throw new Error("Could not convert certification request from PEM; " + "PEM is encrypted.");
- }
- var obj = asn1.fromDer(msg.body, strict);
- return pki.certificationRequestFromAsn1(obj, computeHash);
- };
- pki.certificationRequestToPem = function(csr, maxline) {
- var msg = {
- type: "CERTIFICATE REQUEST",
- body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()
- };
- return forge.pem.encode(msg, { maxline });
- };
- pki.createCertificate = function() {
- var cert = {};
- cert.version = 2;
- cert.serialNumber = "00";
- cert.signatureOid = null;
- cert.signature = null;
- cert.siginfo = {};
- cert.siginfo.algorithmOid = null;
- cert.validity = {};
- cert.validity.notBefore = new Date;
- cert.validity.notAfter = new Date;
- cert.issuer = {};
- cert.issuer.getField = function(sn) {
- return _getAttribute(cert.issuer, sn);
- };
- cert.issuer.addField = function(attr) {
- _fillMissingFields([attr]);
- cert.issuer.attributes.push(attr);
- };
- cert.issuer.attributes = [];
- cert.issuer.hash = null;
- cert.subject = {};
- cert.subject.getField = function(sn) {
- return _getAttribute(cert.subject, sn);
- };
- cert.subject.addField = function(attr) {
- _fillMissingFields([attr]);
- cert.subject.attributes.push(attr);
- };
- cert.subject.attributes = [];
- cert.subject.hash = null;
- cert.extensions = [];
- cert.publicKey = null;
- cert.md = null;
- cert.setSubject = function(attrs, uniqueId) {
- _fillMissingFields(attrs);
- cert.subject.attributes = attrs;
- delete cert.subject.uniqueId;
- if (uniqueId) {
- cert.subject.uniqueId = uniqueId;
- }
- cert.subject.hash = null;
- };
- cert.setIssuer = function(attrs, uniqueId) {
- _fillMissingFields(attrs);
- cert.issuer.attributes = attrs;
- delete cert.issuer.uniqueId;
- if (uniqueId) {
- cert.issuer.uniqueId = uniqueId;
- }
- cert.issuer.hash = null;
- };
- cert.setExtensions = function(exts) {
- for (var i6 = 0;i6 < exts.length; ++i6) {
- _fillMissingExtensionFields(exts[i6], { cert });
- }
- cert.extensions = exts;
- };
- cert.getExtension = function(options2) {
- if (typeof options2 === "string") {
- options2 = { name: options2 };
- }
- var rval = null;
- var ext;
- for (var i6 = 0;rval === null && i6 < cert.extensions.length; ++i6) {
- ext = cert.extensions[i6];
- if (options2.id && ext.id === options2.id) {
- rval = ext;
- } else if (options2.name && ext.name === options2.name) {
- rval = ext;
- }
- }
- return rval;
- };
- cert.sign = function(key2, md) {
- cert.md = md || forge.md.sha1.create();
- var algorithmOid = oids[cert.md.algorithm + "WithRSAEncryption"];
- if (!algorithmOid) {
- var error46 = new Error("Could not compute certificate digest. " + "Unknown message digest algorithm OID.");
- error46.algorithm = cert.md.algorithm;
- throw error46;
- }
- cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;
- cert.tbsCertificate = pki.getTBSCertificate(cert);
- var bytes = asn1.toDer(cert.tbsCertificate);
- cert.md.update(bytes.getBytes());
- cert.signature = key2.sign(cert.md);
- };
- cert.verify = function(child) {
- var rval = false;
- if (!cert.issued(child)) {
- var issuer = child.issuer;
- var subject = cert.subject;
- var error46 = new Error("The parent certificate did not issue the given child " + "certificate; the child certificate's issuer does not match the " + "parent's subject.");
- error46.expectedIssuer = subject.attributes;
- error46.actualIssuer = issuer.attributes;
- throw error46;
- }
- var md = child.md;
- if (md === null) {
- md = _createSignatureDigest({
- signatureOid: child.signatureOid,
- type: "certificate"
- });
- var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);
- var bytes = asn1.toDer(tbsCertificate);
- md.update(bytes.getBytes());
- }
- if (md !== null) {
- rval = _verifySignature({
- certificate: cert,
- md,
- signature: child.signature
- });
- }
- return rval;
- };
- cert.isIssuer = function(parent) {
- var rval = false;
- var i6 = cert.issuer;
- var s4 = parent.subject;
- if (i6.hash && s4.hash) {
- rval = i6.hash === s4.hash;
- } else if (i6.attributes.length === s4.attributes.length) {
- rval = true;
- var iattr, sattr;
- for (var n5 = 0;rval && n5 < i6.attributes.length; ++n5) {
- iattr = i6.attributes[n5];
- sattr = s4.attributes[n5];
- if (iattr.type !== sattr.type || iattr.value !== sattr.value) {
- rval = false;
- }
- }
- }
- return rval;
- };
- cert.issued = function(child) {
- return child.isIssuer(cert);
- };
- cert.generateSubjectKeyIdentifier = function() {
- return pki.getPublicKeyFingerprint(cert.publicKey, { type: "RSAPublicKey" });
- };
- cert.verifySubjectKeyIdentifier = function() {
- var oid = oids["subjectKeyIdentifier"];
- for (var i6 = 0;i6 < cert.extensions.length; ++i6) {
- var ext = cert.extensions[i6];
- if (ext.id === oid) {
- var ski = cert.generateSubjectKeyIdentifier().getBytes();
- return forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski;
- }
- }
- return false;
- };
- return cert;
- };
- pki.certificateFromAsn1 = function(obj, computeHash) {
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(obj, x509CertificateValidator, capture, errors8)) {
- var error46 = new Error("Cannot read X.509 certificate. " + "ASN.1 object is not an X509v3 Certificate.");
- error46.errors = errors8;
- throw error46;
- }
- var oid = asn1.derToOid(capture.publicKeyOid);
- if (oid !== pki.oids.rsaEncryption) {
- throw new Error("Cannot read public key. OID is not RSA.");
- }
- var cert = pki.createCertificate();
- cert.version = capture.certVersion ? capture.certVersion.charCodeAt(0) : 0;
- var serial = forge.util.createBuffer(capture.certSerialNumber);
- cert.serialNumber = serial.toHex();
- cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);
- cert.signatureParameters = _readSignatureParameters(cert.signatureOid, capture.certSignatureParams, true);
- cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);
- cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid, capture.certinfoSignatureParams, false);
- cert.signature = capture.certSignature;
- var validity = [];
- if (capture.certValidity1UTCTime !== undefined) {
- validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));
- }
- if (capture.certValidity2GeneralizedTime !== undefined) {
- validity.push(asn1.generalizedTimeToDate(capture.certValidity2GeneralizedTime));
- }
- if (capture.certValidity3UTCTime !== undefined) {
- validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));
- }
- if (capture.certValidity4GeneralizedTime !== undefined) {
- validity.push(asn1.generalizedTimeToDate(capture.certValidity4GeneralizedTime));
- }
- if (validity.length > 2) {
- throw new Error("Cannot read notBefore/notAfter validity times; more " + "than two times were provided in the certificate.");
- }
- if (validity.length < 2) {
- throw new Error("Cannot read notBefore/notAfter validity times; they " + "were not provided as either UTCTime or GeneralizedTime.");
- }
- cert.validity.notBefore = validity[0];
- cert.validity.notAfter = validity[1];
- cert.tbsCertificate = capture.tbsCertificate;
- if (computeHash) {
- cert.md = _createSignatureDigest({
- signatureOid: cert.signatureOid,
- type: "certificate"
- });
- var bytes = asn1.toDer(cert.tbsCertificate);
- cert.md.update(bytes.getBytes());
- }
- var imd = forge.md.sha1.create();
- var ibytes = asn1.toDer(capture.certIssuer);
- imd.update(ibytes.getBytes());
- cert.issuer.getField = function(sn) {
- return _getAttribute(cert.issuer, sn);
- };
- cert.issuer.addField = function(attr) {
- _fillMissingFields([attr]);
- cert.issuer.attributes.push(attr);
- };
- cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer);
- if (capture.certIssuerUniqueId) {
- cert.issuer.uniqueId = capture.certIssuerUniqueId;
- }
- cert.issuer.hash = imd.digest().toHex();
- var smd = forge.md.sha1.create();
- var sbytes = asn1.toDer(capture.certSubject);
- smd.update(sbytes.getBytes());
- cert.subject.getField = function(sn) {
- return _getAttribute(cert.subject, sn);
- };
- cert.subject.addField = function(attr) {
- _fillMissingFields([attr]);
- cert.subject.attributes.push(attr);
- };
- cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject);
- if (capture.certSubjectUniqueId) {
- cert.subject.uniqueId = capture.certSubjectUniqueId;
- }
- cert.subject.hash = smd.digest().toHex();
- if (capture.certExtensions) {
- cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);
- } else {
- cert.extensions = [];
- }
- cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
- return cert;
- };
- pki.certificateExtensionsFromAsn1 = function(exts) {
- var rval = [];
- for (var i6 = 0;i6 < exts.value.length; ++i6) {
- var extseq = exts.value[i6];
- for (var ei = 0;ei < extseq.value.length; ++ei) {
- rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));
- }
- }
- return rval;
- };
- pki.certificateExtensionFromAsn1 = function(ext) {
- var e4 = {};
- e4.id = asn1.derToOid(ext.value[0].value);
- e4.critical = false;
- if (ext.value[1].type === asn1.Type.BOOLEAN) {
- e4.critical = ext.value[1].value.charCodeAt(0) !== 0;
- e4.value = ext.value[2].value;
- } else {
- e4.value = ext.value[1].value;
- }
- if (e4.id in oids) {
- e4.name = oids[e4.id];
- if (e4.name === "keyUsage") {
- var ev = asn1.fromDer(e4.value);
- var b23 = 0;
- var b32 = 0;
- if (ev.value.length > 1) {
- b23 = ev.value.charCodeAt(1);
- b32 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;
- }
- e4.digitalSignature = (b23 & 128) === 128;
- e4.nonRepudiation = (b23 & 64) === 64;
- e4.keyEncipherment = (b23 & 32) === 32;
- e4.dataEncipherment = (b23 & 16) === 16;
- e4.keyAgreement = (b23 & 8) === 8;
- e4.keyCertSign = (b23 & 4) === 4;
- e4.cRLSign = (b23 & 2) === 2;
- e4.encipherOnly = (b23 & 1) === 1;
- e4.decipherOnly = (b32 & 128) === 128;
- } else if (e4.name === "basicConstraints") {
- var ev = asn1.fromDer(e4.value);
- if (ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {
- e4.cA = ev.value[0].value.charCodeAt(0) !== 0;
- } else {
- e4.cA = false;
- }
- var value = null;
- if (ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {
- value = ev.value[0].value;
- } else if (ev.value.length > 1) {
- value = ev.value[1].value;
- }
- if (value !== null) {
- e4.pathLenConstraint = asn1.derToInteger(value);
- }
- } else if (e4.name === "extKeyUsage") {
- var ev = asn1.fromDer(e4.value);
- for (var vi = 0;vi < ev.value.length; ++vi) {
- var oid = asn1.derToOid(ev.value[vi].value);
- if (oid in oids) {
- e4[oids[oid]] = true;
- } else {
- e4[oid] = true;
- }
- }
- } else if (e4.name === "nsCertType") {
- var ev = asn1.fromDer(e4.value);
- var b23 = 0;
- if (ev.value.length > 1) {
- b23 = ev.value.charCodeAt(1);
- }
- e4.client = (b23 & 128) === 128;
- e4.server = (b23 & 64) === 64;
- e4.email = (b23 & 32) === 32;
- e4.objsign = (b23 & 16) === 16;
- e4.reserved = (b23 & 8) === 8;
- e4.sslCA = (b23 & 4) === 4;
- e4.emailCA = (b23 & 2) === 2;
- e4.objCA = (b23 & 1) === 1;
- } else if (e4.name === "subjectAltName" || e4.name === "issuerAltName") {
- e4.altNames = [];
- var gn;
- var ev = asn1.fromDer(e4.value);
- for (var n5 = 0;n5 < ev.value.length; ++n5) {
- gn = ev.value[n5];
- var altName = {
- type: gn.type,
- value: gn.value
- };
- e4.altNames.push(altName);
- switch (gn.type) {
- case 1:
- case 2:
- case 6:
- break;
- case 7:
- altName.ip = forge.util.bytesToIP(gn.value);
- break;
- case 8:
- altName.oid = asn1.derToOid(gn.value);
- break;
- default:
- }
- }
- } else if (e4.name === "subjectKeyIdentifier") {
- var ev = asn1.fromDer(e4.value);
- e4.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);
- }
- }
- return e4;
- };
- pki.certificationRequestFromAsn1 = function(obj, computeHash) {
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(obj, certificationRequestValidator, capture, errors8)) {
- var error46 = new Error("Cannot read PKCS#10 certificate request. " + "ASN.1 object is not a PKCS#10 CertificationRequest.");
- error46.errors = errors8;
- throw error46;
- }
- var oid = asn1.derToOid(capture.publicKeyOid);
- if (oid !== pki.oids.rsaEncryption) {
- throw new Error("Cannot read public key. OID is not RSA.");
- }
- var csr = pki.createCertificationRequest();
- csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;
- csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);
- csr.signatureParameters = _readSignatureParameters(csr.signatureOid, capture.csrSignatureParams, true);
- csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);
- csr.siginfo.parameters = _readSignatureParameters(csr.siginfo.algorithmOid, capture.csrSignatureParams, false);
- csr.signature = capture.csrSignature;
- csr.certificationRequestInfo = capture.certificationRequestInfo;
- if (computeHash) {
- csr.md = _createSignatureDigest({
- signatureOid: csr.signatureOid,
- type: "certification request"
- });
- var bytes = asn1.toDer(csr.certificationRequestInfo);
- csr.md.update(bytes.getBytes());
- }
- var smd = forge.md.sha1.create();
- csr.subject.getField = function(sn) {
- return _getAttribute(csr.subject, sn);
- };
- csr.subject.addField = function(attr) {
- _fillMissingFields([attr]);
- csr.subject.attributes.push(attr);
- };
- csr.subject.attributes = pki.RDNAttributesAsArray(capture.certificationRequestInfoSubject, smd);
- csr.subject.hash = smd.digest().toHex();
- csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
- csr.getAttribute = function(sn) {
- return _getAttribute(csr, sn);
- };
- csr.addAttribute = function(attr) {
- _fillMissingFields([attr]);
- csr.attributes.push(attr);
- };
- csr.attributes = pki.CRIAttributesAsArray(capture.certificationRequestInfoAttributes || []);
- return csr;
- };
- pki.createCertificationRequest = function() {
- var csr = {};
- csr.version = 0;
- csr.signatureOid = null;
- csr.signature = null;
- csr.siginfo = {};
- csr.siginfo.algorithmOid = null;
- csr.subject = {};
- csr.subject.getField = function(sn) {
- return _getAttribute(csr.subject, sn);
- };
- csr.subject.addField = function(attr) {
- _fillMissingFields([attr]);
- csr.subject.attributes.push(attr);
- };
- csr.subject.attributes = [];
- csr.subject.hash = null;
- csr.publicKey = null;
- csr.attributes = [];
- csr.getAttribute = function(sn) {
- return _getAttribute(csr, sn);
- };
- csr.addAttribute = function(attr) {
- _fillMissingFields([attr]);
- csr.attributes.push(attr);
- };
- csr.md = null;
- csr.setSubject = function(attrs) {
- _fillMissingFields(attrs);
- csr.subject.attributes = attrs;
- csr.subject.hash = null;
- };
- csr.setAttributes = function(attrs) {
- _fillMissingFields(attrs);
- csr.attributes = attrs;
- };
- csr.sign = function(key2, md) {
- csr.md = md || forge.md.sha1.create();
- var algorithmOid = oids[csr.md.algorithm + "WithRSAEncryption"];
- if (!algorithmOid) {
- var error46 = new Error("Could not compute certification request digest. " + "Unknown message digest algorithm OID.");
- error46.algorithm = csr.md.algorithm;
- throw error46;
- }
- csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;
- csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);
- var bytes = asn1.toDer(csr.certificationRequestInfo);
- csr.md.update(bytes.getBytes());
- csr.signature = key2.sign(csr.md);
- };
- csr.verify = function() {
- var rval = false;
- var md = csr.md;
- if (md === null) {
- md = _createSignatureDigest({
- signatureOid: csr.signatureOid,
- type: "certification request"
- });
- var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr);
- var bytes = asn1.toDer(cri);
- md.update(bytes.getBytes());
- }
- if (md !== null) {
- rval = _verifySignature({
- certificate: csr,
- md,
- signature: csr.signature
- });
- }
- return rval;
- };
- return csr;
- };
- function _dnToAsn1(obj) {
- var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- var attr, set2;
- var attrs = obj.attributes;
- for (var i6 = 0;i6 < attrs.length; ++i6) {
- attr = attrs[i6];
- var value = attr.value;
- var valueTagClass = asn1.Type.PRINTABLESTRING;
- if ("valueTagClass" in attr) {
- valueTagClass = attr.valueTagClass;
- if (valueTagClass === asn1.Type.UTF8) {
- value = forge.util.encodeUtf8(value);
- }
- }
- set2 = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.type).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)
- ])
- ]);
- rval.value.push(set2);
- }
- return rval;
- }
- function _fillMissingFields(attrs) {
- var attr;
- for (var i6 = 0;i6 < attrs.length; ++i6) {
- attr = attrs[i6];
- if (typeof attr.name === "undefined") {
- if (attr.type && attr.type in pki.oids) {
- attr.name = pki.oids[attr.type];
- } else if (attr.shortName && attr.shortName in _shortNames) {
- attr.name = pki.oids[_shortNames[attr.shortName]];
- }
- }
- if (typeof attr.type === "undefined") {
- if (attr.name && attr.name in pki.oids) {
- attr.type = pki.oids[attr.name];
- } else {
- var error46 = new Error("Attribute type not specified.");
- error46.attribute = attr;
- throw error46;
- }
- }
- if (typeof attr.shortName === "undefined") {
- if (attr.name && attr.name in _shortNames) {
- attr.shortName = _shortNames[attr.name];
- }
- }
- if (attr.type === oids.extensionRequest) {
- attr.valueConstructed = true;
- attr.valueTagClass = asn1.Type.SEQUENCE;
- if (!attr.value && attr.extensions) {
- attr.value = [];
- for (var ei = 0;ei < attr.extensions.length; ++ei) {
- attr.value.push(pki.certificateExtensionToAsn1(_fillMissingExtensionFields(attr.extensions[ei])));
- }
- }
- }
- if (typeof attr.value === "undefined") {
- var error46 = new Error("Attribute value not specified.");
- error46.attribute = attr;
- throw error46;
- }
- }
- }
- function _fillMissingExtensionFields(e4, options2) {
- options2 = options2 || {};
- if (typeof e4.name === "undefined") {
- if (e4.id && e4.id in pki.oids) {
- e4.name = pki.oids[e4.id];
- }
- }
- if (typeof e4.id === "undefined") {
- if (e4.name && e4.name in pki.oids) {
- e4.id = pki.oids[e4.name];
- } else {
- var error46 = new Error("Extension ID not specified.");
- error46.extension = e4;
- throw error46;
- }
- }
- if (typeof e4.value !== "undefined") {
- return e4;
- }
- if (e4.name === "keyUsage") {
- var unused = 0;
- var b23 = 0;
- var b32 = 0;
- if (e4.digitalSignature) {
- b23 |= 128;
- unused = 7;
- }
- if (e4.nonRepudiation) {
- b23 |= 64;
- unused = 6;
- }
- if (e4.keyEncipherment) {
- b23 |= 32;
- unused = 5;
- }
- if (e4.dataEncipherment) {
- b23 |= 16;
- unused = 4;
- }
- if (e4.keyAgreement) {
- b23 |= 8;
- unused = 3;
- }
- if (e4.keyCertSign) {
- b23 |= 4;
- unused = 2;
- }
- if (e4.cRLSign) {
- b23 |= 2;
- unused = 1;
- }
- if (e4.encipherOnly) {
- b23 |= 1;
- unused = 0;
- }
- if (e4.decipherOnly) {
- b32 |= 128;
- unused = 7;
- }
- var value = String.fromCharCode(unused);
- if (b32 !== 0) {
- value += String.fromCharCode(b23) + String.fromCharCode(b32);
- } else if (b23 !== 0) {
- value += String.fromCharCode(b23);
- }
- e4.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);
- } else if (e4.name === "basicConstraints") {
- e4.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- if (e4.cA) {
- e4.value.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, String.fromCharCode(255)));
- }
- if ("pathLenConstraint" in e4) {
- e4.value.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(e4.pathLenConstraint).getBytes()));
- }
- } else if (e4.name === "extKeyUsage") {
- e4.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- var seq = e4.value.value;
- for (var key2 in e4) {
- if (e4[key2] !== true) {
- continue;
- }
- if (key2 in oids) {
- seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids[key2]).getBytes()));
- } else if (key2.indexOf(".") !== -1) {
- seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(key2).getBytes()));
- }
- }
- } else if (e4.name === "nsCertType") {
- var unused = 0;
- var b23 = 0;
- if (e4.client) {
- b23 |= 128;
- unused = 7;
- }
- if (e4.server) {
- b23 |= 64;
- unused = 6;
- }
- if (e4.email) {
- b23 |= 32;
- unused = 5;
- }
- if (e4.objsign) {
- b23 |= 16;
- unused = 4;
- }
- if (e4.reserved) {
- b23 |= 8;
- unused = 3;
- }
- if (e4.sslCA) {
- b23 |= 4;
- unused = 2;
- }
- if (e4.emailCA) {
- b23 |= 2;
- unused = 1;
- }
- if (e4.objCA) {
- b23 |= 1;
- unused = 0;
- }
- var value = String.fromCharCode(unused);
- if (b23 !== 0) {
- value += String.fromCharCode(b23);
- }
- e4.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);
- } else if (e4.name === "subjectAltName" || e4.name === "issuerAltName") {
- e4.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- var altName;
- for (var n5 = 0;n5 < e4.altNames.length; ++n5) {
- altName = e4.altNames[n5];
- var value = altName.value;
- if (altName.type === 7 && altName.ip) {
- value = forge.util.bytesFromIP(altName.ip);
- if (value === null) {
- var error46 = new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');
- error46.extension = e4;
- throw error46;
- }
- } else if (altName.type === 8) {
- if (altName.oid) {
- value = asn1.oidToDer(asn1.oidToDer(altName.oid));
- } else {
- value = asn1.oidToDer(value);
- }
- }
- e4.value.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, altName.type, false, value));
- }
- } else if (e4.name === "nsComment" && options2.cert) {
- if (!/^[\x00-\x7F]*$/.test(e4.comment) || e4.comment.length < 1 || e4.comment.length > 128) {
- throw new Error('Invalid "nsComment" content.');
- }
- e4.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e4.comment);
- } else if (e4.name === "subjectKeyIdentifier" && options2.cert) {
- var ski = options2.cert.generateSubjectKeyIdentifier();
- e4.subjectKeyIdentifier = ski.toHex();
- e4.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());
- } else if (e4.name === "authorityKeyIdentifier" && options2.cert) {
- e4.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- var seq = e4.value.value;
- if (e4.keyIdentifier) {
- var keyIdentifier = e4.keyIdentifier === true ? options2.cert.generateSubjectKeyIdentifier().getBytes() : e4.keyIdentifier;
- seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));
- }
- if (e4.authorityCertIssuer) {
- var authorityCertIssuer = [
- asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [
- _dnToAsn1(e4.authorityCertIssuer === true ? options2.cert.issuer : e4.authorityCertIssuer)
- ])
- ];
- seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));
- }
- if (e4.serialNumber) {
- var serialNumber = forge.util.hexToBytes(e4.serialNumber === true ? options2.cert.serialNumber : e4.serialNumber);
- seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));
- }
- } else if (e4.name === "cRLDistributionPoints") {
- e4.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- var seq = e4.value.value;
- var subSeq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- var fullNameGeneralNames = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
- var altName;
- for (var n5 = 0;n5 < e4.altNames.length; ++n5) {
- altName = e4.altNames[n5];
- var value = altName.value;
- if (altName.type === 7 && altName.ip) {
- value = forge.util.bytesFromIP(altName.ip);
- if (value === null) {
- var error46 = new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');
- error46.extension = e4;
- throw error46;
- }
- } else if (altName.type === 8) {
- if (altName.oid) {
- value = asn1.oidToDer(asn1.oidToDer(altName.oid));
- } else {
- value = asn1.oidToDer(value);
- }
- }
- fullNameGeneralNames.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, altName.type, false, value));
- }
- subSeq.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));
- seq.push(subSeq);
- }
- if (typeof e4.value === "undefined") {
- var error46 = new Error("Extension value not specified.");
- error46.extension = e4;
- throw error46;
- }
- return e4;
- }
- function _signatureParametersToAsn1(oid, params) {
- switch (oid) {
- case oids["RSASSA-PSS"]:
- var parts = [];
- if (params.hash.algorithmOid !== undefined) {
- parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.hash.algorithmOid).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
- ])
- ]));
- }
- if (params.mgf.algorithmOid !== undefined) {
- parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.mgf.algorithmOid).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
- ])
- ])
- ]));
- }
- if (params.saltLength !== undefined) {
- parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(params.saltLength).getBytes())
- ]));
- }
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);
- default:
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "");
- }
- }
- function _CRIAttributesToAsn1(csr) {
- var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
- if (csr.attributes.length === 0) {
- return rval;
- }
- var attrs = csr.attributes;
- for (var i6 = 0;i6 < attrs.length; ++i6) {
- var attr = attrs[i6];
- var value = attr.value;
- var valueTagClass = asn1.Type.UTF8;
- if ("valueTagClass" in attr) {
- valueTagClass = attr.valueTagClass;
- }
- if (valueTagClass === asn1.Type.UTF8) {
- value = forge.util.encodeUtf8(value);
- }
- var valueConstructed = false;
- if ("valueConstructed" in attr) {
- valueConstructed = attr.valueConstructed;
- }
- var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.type).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
- asn1.create(asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)
- ])
- ]);
- rval.value.push(seq);
- }
- return rval;
- }
- var jan_1_1950 = new Date("1950-01-01T00:00:00Z");
- var jan_1_2050 = new Date("2050-01-01T00:00:00Z");
- function _dateToAsn1(date5) {
- if (date5 >= jan_1_1950 && date5 < jan_1_2050) {
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, asn1.dateToUtcTime(date5));
- } else {
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, asn1.dateToGeneralizedTime(date5));
- }
- }
- pki.getTBSCertificate = function(cert) {
- var notBefore = _dateToAsn1(cert.validity.notBefore);
- var notAfter = _dateToAsn1(cert.validity.notAfter);
- var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(cert.version).getBytes())
- ]),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(cert.serialNumber)),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),
- _signatureParametersToAsn1(cert.siginfo.algorithmOid, cert.siginfo.parameters)
- ]),
- _dnToAsn1(cert.issuer),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- notBefore,
- notAfter
- ]),
- _dnToAsn1(cert.subject),
- pki.publicKeyToAsn1(cert.publicKey)
- ]);
- if (cert.issuer.uniqueId) {
- tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, String.fromCharCode(0) + cert.issuer.uniqueId)
- ]));
- }
- if (cert.subject.uniqueId) {
- tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, String.fromCharCode(0) + cert.subject.uniqueId)
- ]));
- }
- if (cert.extensions.length > 0) {
- tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));
- }
- return tbs;
- };
- pki.getCertificationRequestInfo = function(csr) {
- var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(csr.version).getBytes()),
- _dnToAsn1(csr.subject),
- pki.publicKeyToAsn1(csr.publicKey),
- _CRIAttributesToAsn1(csr)
- ]);
- return cri;
- };
- pki.distinguishedNameToAsn1 = function(dn) {
- return _dnToAsn1(dn);
- };
- pki.certificateToAsn1 = function(cert) {
- var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- tbsCertificate,
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(cert.signatureOid).getBytes()),
- _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)
- ]),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, String.fromCharCode(0) + cert.signature)
- ]);
- };
- pki.certificateExtensionsToAsn1 = function(exts) {
- var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);
- var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- rval.value.push(seq);
- for (var i6 = 0;i6 < exts.length; ++i6) {
- seq.value.push(pki.certificateExtensionToAsn1(exts[i6]));
- }
- return rval;
- };
- pki.certificateExtensionToAsn1 = function(ext) {
- var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- extseq.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(ext.id).getBytes()));
- if (ext.critical) {
- extseq.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, String.fromCharCode(255)));
- }
- var value = ext.value;
- if (typeof ext.value !== "string") {
- value = asn1.toDer(value).getBytes();
- }
- extseq.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));
- return extseq;
- };
- pki.certificationRequestToAsn1 = function(csr) {
- var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr);
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- cri,
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(csr.signatureOid).getBytes()),
- _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)
- ]),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, String.fromCharCode(0) + csr.signature)
- ]);
- };
- pki.createCaStore = function(certs) {
- var caStore = {
- certs: {}
- };
- caStore.getIssuer = function(cert2) {
- var rval = getBySubject(cert2.issuer);
- return rval;
- };
- caStore.addCertificate = function(cert2) {
- if (typeof cert2 === "string") {
- cert2 = forge.pki.certificateFromPem(cert2);
- }
- ensureSubjectHasHash(cert2.subject);
- if (!caStore.hasCertificate(cert2)) {
- if (cert2.subject.hash in caStore.certs) {
- var tmp = caStore.certs[cert2.subject.hash];
- if (!forge.util.isArray(tmp)) {
- tmp = [tmp];
- }
- tmp.push(cert2);
- caStore.certs[cert2.subject.hash] = tmp;
- } else {
- caStore.certs[cert2.subject.hash] = cert2;
- }
- }
- };
- caStore.hasCertificate = function(cert2) {
- if (typeof cert2 === "string") {
- cert2 = forge.pki.certificateFromPem(cert2);
- }
- var match = getBySubject(cert2.subject);
- if (!match) {
- return false;
- }
- if (!forge.util.isArray(match)) {
- match = [match];
- }
- var der1 = asn1.toDer(pki.certificateToAsn1(cert2)).getBytes();
- for (var i7 = 0;i7 < match.length; ++i7) {
- var der2 = asn1.toDer(pki.certificateToAsn1(match[i7])).getBytes();
- if (der1 === der2) {
- return true;
- }
- }
- return false;
- };
- caStore.listAllCertificates = function() {
- var certList = [];
- for (var hash2 in caStore.certs) {
- if (caStore.certs.hasOwnProperty(hash2)) {
- var value = caStore.certs[hash2];
- if (!forge.util.isArray(value)) {
- certList.push(value);
- } else {
- for (var i7 = 0;i7 < value.length; ++i7) {
- certList.push(value[i7]);
- }
- }
- }
- }
- return certList;
- };
- caStore.removeCertificate = function(cert2) {
- var result;
- if (typeof cert2 === "string") {
- cert2 = forge.pki.certificateFromPem(cert2);
- }
- ensureSubjectHasHash(cert2.subject);
- if (!caStore.hasCertificate(cert2)) {
- return null;
- }
- var match = getBySubject(cert2.subject);
- if (!forge.util.isArray(match)) {
- result = caStore.certs[cert2.subject.hash];
- delete caStore.certs[cert2.subject.hash];
- return result;
- }
- var der1 = asn1.toDer(pki.certificateToAsn1(cert2)).getBytes();
- for (var i7 = 0;i7 < match.length; ++i7) {
- var der2 = asn1.toDer(pki.certificateToAsn1(match[i7])).getBytes();
- if (der1 === der2) {
- result = match[i7];
- match.splice(i7, 1);
- }
- }
- if (match.length === 0) {
- delete caStore.certs[cert2.subject.hash];
- }
- return result;
- };
- function getBySubject(subject) {
- ensureSubjectHasHash(subject);
- return caStore.certs[subject.hash] || null;
- }
- function ensureSubjectHasHash(subject) {
- if (!subject.hash) {
- var md = forge.md.sha1.create();
- subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);
- subject.hash = md.digest().toHex();
- }
- }
- if (certs) {
- for (var i6 = 0;i6 < certs.length; ++i6) {
- var cert = certs[i6];
- caStore.addCertificate(cert);
- }
- }
- return caStore;
- };
- pki.certificateError = {
- bad_certificate: "forge.pki.BadCertificate",
- unsupported_certificate: "forge.pki.UnsupportedCertificate",
- certificate_revoked: "forge.pki.CertificateRevoked",
- certificate_expired: "forge.pki.CertificateExpired",
- certificate_unknown: "forge.pki.CertificateUnknown",
- unknown_ca: "forge.pki.UnknownCertificateAuthority"
- };
- pki.verifyCertificateChain = function(caStore, chain4, options2) {
- if (typeof options2 === "function") {
- options2 = { verify: options2 };
- }
- options2 = options2 || {};
- chain4 = chain4.slice(0);
- var certs = chain4.slice(0);
- var validityCheckDate = options2.validityCheckDate;
- if (typeof validityCheckDate === "undefined") {
- validityCheckDate = new Date;
- }
- var first = true;
- var error46 = null;
- var depth = 0;
- do {
- var cert = chain4.shift();
- var parent = null;
- var selfSigned = false;
- if (validityCheckDate) {
- if (validityCheckDate < cert.validity.notBefore || validityCheckDate > cert.validity.notAfter) {
- error46 = {
- message: "Certificate is not valid yet or has expired.",
- error: pki.certificateError.certificate_expired,
- notBefore: cert.validity.notBefore,
- notAfter: cert.validity.notAfter,
- now: validityCheckDate
- };
- }
- }
- if (error46 === null) {
- parent = chain4[0] || caStore.getIssuer(cert);
- if (parent === null) {
- if (cert.isIssuer(cert)) {
- selfSigned = true;
- parent = cert;
- }
- }
- if (parent) {
- var parents = parent;
- if (!forge.util.isArray(parents)) {
- parents = [parents];
- }
- var verified = false;
- while (!verified && parents.length > 0) {
- parent = parents.shift();
- try {
- verified = parent.verify(cert);
- } catch (ex) {}
- }
- if (!verified) {
- error46 = {
- message: "Certificate signature is invalid.",
- error: pki.certificateError.bad_certificate
- };
- }
- }
- if (error46 === null && (!parent || selfSigned) && !caStore.hasCertificate(cert)) {
- error46 = {
- message: "Certificate is not trusted.",
- error: pki.certificateError.unknown_ca
- };
- }
- }
- if (error46 === null && parent && !cert.isIssuer(parent)) {
- error46 = {
- message: "Certificate issuer is invalid.",
- error: pki.certificateError.bad_certificate
- };
- }
- if (error46 === null) {
- var se = {
- keyUsage: true,
- basicConstraints: true
- };
- for (var i6 = 0;error46 === null && i6 < cert.extensions.length; ++i6) {
- var ext = cert.extensions[i6];
- if (ext.critical && !(ext.name in se)) {
- error46 = {
- message: "Certificate has an unsupported critical extension.",
- error: pki.certificateError.unsupported_certificate
- };
- }
- }
- }
- if (error46 === null && (!first || chain4.length === 0 && (!parent || selfSigned))) {
- var bcExt = cert.getExtension("basicConstraints");
- var keyUsageExt = cert.getExtension("keyUsage");
- if (keyUsageExt !== null) {
- if (!keyUsageExt.keyCertSign || bcExt === null) {
- error46 = {
- message: "Certificate keyUsage or basicConstraints conflict " + "or indicate that the certificate is not a CA. " + "If the certificate is the only one in the chain or " + "isn't the first then the certificate must be a " + "valid CA.",
- error: pki.certificateError.bad_certificate
- };
- }
- }
- if (error46 === null && bcExt === null) {
- error46 = {
- message: "Certificate is missing basicConstraints extension and cannot " + "be used as a CA.",
- error: pki.certificateError.bad_certificate
- };
- }
- if (error46 === null && bcExt !== null && !bcExt.cA) {
- error46 = {
- message: "Certificate basicConstraints indicates the certificate " + "is not a CA.",
- error: pki.certificateError.bad_certificate
- };
- }
- if (error46 === null && keyUsageExt !== null && "pathLenConstraint" in bcExt) {
- var pathLen = depth - 1;
- if (pathLen > bcExt.pathLenConstraint) {
- error46 = {
- message: "Certificate basicConstraints pathLenConstraint violated.",
- error: pki.certificateError.bad_certificate
- };
- }
- }
- }
- var vfd = error46 === null ? true : error46.error;
- var ret = options2.verify ? options2.verify(vfd, depth, certs) : vfd;
- if (ret === true) {
- error46 = null;
- } else {
- if (vfd === true) {
- error46 = {
- message: "The application rejected the certificate.",
- error: pki.certificateError.bad_certificate
- };
- }
- if (ret || ret === 0) {
- if (typeof ret === "object" && !forge.util.isArray(ret)) {
- if (ret.message) {
- error46.message = ret.message;
- }
- if (ret.error) {
- error46.error = ret.error;
- }
- } else if (typeof ret === "string") {
- error46.error = ret;
- }
- }
- throw error46;
- }
- first = false;
- ++depth;
- } while (chain4.length > 0);
- return true;
- };
-});
-
-// node_modules/node-forge/lib/pkcs12.js
-var require_pkcs12 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_asn1();
- require_hmac();
- require_oids();
- require_pkcs7asn1();
- require_pbe();
- require_random();
- require_rsa();
- require_sha13();
- require_util3();
- require_x509();
- var asn1 = forge.asn1;
- var pki = forge.pki;
- var p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {};
- var contentInfoValidator = {
- name: "ContentInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "ContentInfo.contentType",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "contentType"
- }, {
- name: "ContentInfo.content",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- constructed: true,
- captureAsn1: "content"
- }]
- };
- var pfxValidator = {
- name: "PFX",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [
- {
- name: "PFX.version",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "version"
- },
- contentInfoValidator,
- {
- name: "PFX.macData",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- optional: true,
- captureAsn1: "mac",
- value: [{
- name: "PFX.macData.mac",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "PFX.macData.mac.digestAlgorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "PFX.macData.mac.digestAlgorithm.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "macAlgorithm"
- }, {
- name: "PFX.macData.mac.digestAlgorithm.parameters",
- optional: true,
- tagClass: asn1.Class.UNIVERSAL,
- captureAsn1: "macAlgorithmParameters"
- }]
- }, {
- name: "PFX.macData.mac.digest",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: "macDigest"
- }]
- }, {
- name: "PFX.macData.macSalt",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: "macSalt"
- }, {
- name: "PFX.macData.iterations",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- optional: true,
- capture: "macIterations"
- }]
- }
- ]
- };
- var safeBagValidator = {
- name: "SafeBag",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "SafeBag.bagId",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "bagId"
- }, {
- name: "SafeBag.bagValue",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- constructed: true,
- captureAsn1: "bagValue"
- }, {
- name: "SafeBag.bagAttributes",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SET,
- constructed: true,
- optional: true,
- capture: "bagAttributes"
- }]
- };
- var attributeValidator = {
- name: "Attribute",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "Attribute.attrId",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "oid"
- }, {
- name: "Attribute.attrValues",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SET,
- constructed: true,
- capture: "values"
- }]
- };
- var certBagValidator = {
- name: "CertBag",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "CertBag.certId",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "certId"
- }, {
- name: "CertBag.certValue",
- tagClass: asn1.Class.CONTEXT_SPECIFIC,
- constructed: true,
- value: [{
- name: "CertBag.certValue[0]",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Class.OCTETSTRING,
- constructed: false,
- capture: "cert"
- }]
- }]
- };
- function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) {
- var result = [];
- for (var i6 = 0;i6 < safeContents.length; i6++) {
- for (var j4 = 0;j4 < safeContents[i6].safeBags.length; j4++) {
- var bag = safeContents[i6].safeBags[j4];
- if (bagType !== undefined && bag.type !== bagType) {
- continue;
- }
- if (attrName === null) {
- result.push(bag);
- continue;
- }
- if (bag.attributes[attrName] !== undefined && bag.attributes[attrName].indexOf(attrValue) >= 0) {
- result.push(bag);
- }
- }
- }
- return result;
- }
- p12.pkcs12FromAsn1 = function(obj, strict, password) {
- if (typeof strict === "string") {
- password = strict;
- strict = true;
- } else if (strict === undefined) {
- strict = true;
- }
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(obj, pfxValidator, capture, errors8)) {
- var error46 = new Error("Cannot read PKCS#12 PFX. " + "ASN.1 object is not an PKCS#12 PFX.");
- error46.errors = error46;
- throw error46;
- }
- var pfx = {
- version: capture.version.charCodeAt(0),
- safeContents: [],
- getBags: function(filter2) {
- var rval = {};
- var localKeyId;
- if ("localKeyId" in filter2) {
- localKeyId = filter2.localKeyId;
- } else if ("localKeyIdHex" in filter2) {
- localKeyId = forge.util.hexToBytes(filter2.localKeyIdHex);
- }
- if (localKeyId === undefined && !("friendlyName" in filter2) && "bagType" in filter2) {
- rval[filter2.bagType] = _getBagsByAttribute(pfx.safeContents, null, null, filter2.bagType);
- }
- if (localKeyId !== undefined) {
- rval.localKeyId = _getBagsByAttribute(pfx.safeContents, "localKeyId", localKeyId, filter2.bagType);
- }
- if ("friendlyName" in filter2) {
- rval.friendlyName = _getBagsByAttribute(pfx.safeContents, "friendlyName", filter2.friendlyName, filter2.bagType);
- }
- return rval;
- },
- getBagsByFriendlyName: function(friendlyName, bagType) {
- return _getBagsByAttribute(pfx.safeContents, "friendlyName", friendlyName, bagType);
- },
- getBagsByLocalKeyId: function(localKeyId, bagType) {
- return _getBagsByAttribute(pfx.safeContents, "localKeyId", localKeyId, bagType);
- }
- };
- if (capture.version.charCodeAt(0) !== 3) {
- var error46 = new Error("PKCS#12 PFX of version other than 3 not supported.");
- error46.version = capture.version.charCodeAt(0);
- throw error46;
- }
- if (asn1.derToOid(capture.contentType) !== pki.oids.data) {
- var error46 = new Error("Only PKCS#12 PFX in password integrity mode supported.");
- error46.oid = asn1.derToOid(capture.contentType);
- throw error46;
- }
- var data = capture.content.value[0];
- if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) {
- throw new Error("PKCS#12 authSafe content data is not an OCTET STRING.");
- }
- data = _decodePkcs7Data(data);
- if (capture.mac) {
- var md = null;
- var macKeyBytes = 0;
- var macAlgorithm = asn1.derToOid(capture.macAlgorithm);
- switch (macAlgorithm) {
- case pki.oids.sha1:
- md = forge.md.sha1.create();
- macKeyBytes = 20;
- break;
- case pki.oids.sha256:
- md = forge.md.sha256.create();
- macKeyBytes = 32;
- break;
- case pki.oids.sha384:
- md = forge.md.sha384.create();
- macKeyBytes = 48;
- break;
- case pki.oids.sha512:
- md = forge.md.sha512.create();
- macKeyBytes = 64;
- break;
- case pki.oids.md5:
- md = forge.md.md5.create();
- macKeyBytes = 16;
- break;
- }
- if (md === null) {
- throw new Error("PKCS#12 uses unsupported MAC algorithm: " + macAlgorithm);
- }
- var macSalt = new forge.util.ByteBuffer(capture.macSalt);
- var macIterations = "macIterations" in capture ? parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1;
- var macKey = p12.generateKey(password, macSalt, 3, macIterations, macKeyBytes, md);
- var mac = forge.hmac.create();
- mac.start(md, macKey);
- mac.update(data.value);
- var macValue = mac.getMac();
- if (macValue.getBytes() !== capture.macDigest) {
- throw new Error("PKCS#12 MAC could not be verified. Invalid password?");
- }
- } else if (Array.isArray(obj.value) && obj.value.length > 2) {
- throw new Error("Invalid PKCS#12. macData field present but MAC was not validated.");
- }
- _decodeAuthenticatedSafe(pfx, data.value, strict, password);
- return pfx;
- };
- function _decodePkcs7Data(data) {
- if (data.composed || data.constructed) {
- var value = forge.util.createBuffer();
- for (var i6 = 0;i6 < data.value.length; ++i6) {
- value.putBytes(data.value[i6].value);
- }
- data.composed = data.constructed = false;
- data.value = value.getBytes();
- }
- return data;
- }
- function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) {
- authSafe = asn1.fromDer(authSafe, strict);
- if (authSafe.tagClass !== asn1.Class.UNIVERSAL || authSafe.type !== asn1.Type.SEQUENCE || authSafe.constructed !== true) {
- throw new Error("PKCS#12 AuthenticatedSafe expected to be a " + "SEQUENCE OF ContentInfo");
- }
- for (var i6 = 0;i6 < authSafe.value.length; i6++) {
- var contentInfo = authSafe.value[i6];
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(contentInfo, contentInfoValidator, capture, errors8)) {
- var error46 = new Error("Cannot read ContentInfo.");
- error46.errors = errors8;
- throw error46;
- }
- var obj = {
- encrypted: false
- };
- var safeContents = null;
- var data = capture.content.value[0];
- switch (asn1.derToOid(capture.contentType)) {
- case pki.oids.data:
- if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) {
- throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING.");
- }
- safeContents = _decodePkcs7Data(data).value;
- break;
- case pki.oids.encryptedData:
- safeContents = _decryptSafeContents(data, password);
- obj.encrypted = true;
- break;
- default:
- var error46 = new Error("Unsupported PKCS#12 contentType.");
- error46.contentType = asn1.derToOid(capture.contentType);
- throw error46;
- }
- obj.safeBags = _decodeSafeContents(safeContents, strict, password);
- pfx.safeContents.push(obj);
- }
- }
- function _decryptSafeContents(data, password) {
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors8)) {
- var error46 = new Error("Cannot read EncryptedContentInfo.");
- error46.errors = errors8;
- throw error46;
- }
- var oid = asn1.derToOid(capture.contentType);
- if (oid !== pki.oids.data) {
- var error46 = new Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");
- error46.oid = oid;
- throw error46;
- }
- oid = asn1.derToOid(capture.encAlgorithm);
- var cipher = pki.pbe.getCipher(oid, capture.encParameter, password);
- var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1);
- var encrypted = forge.util.createBuffer(encryptedContentAsn1.value);
- cipher.update(encrypted);
- if (!cipher.finish()) {
- throw new Error("Failed to decrypt PKCS#12 SafeContents.");
- }
- return cipher.output.getBytes();
- }
- function _decodeSafeContents(safeContents, strict, password) {
- if (!strict && safeContents.length === 0) {
- return [];
- }
- safeContents = asn1.fromDer(safeContents, strict);
- if (safeContents.tagClass !== asn1.Class.UNIVERSAL || safeContents.type !== asn1.Type.SEQUENCE || safeContents.constructed !== true) {
- throw new Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.");
- }
- var res = [];
- for (var i6 = 0;i6 < safeContents.value.length; i6++) {
- var safeBag = safeContents.value[i6];
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(safeBag, safeBagValidator, capture, errors8)) {
- var error46 = new Error("Cannot read SafeBag.");
- error46.errors = errors8;
- throw error46;
- }
- var bag = {
- type: asn1.derToOid(capture.bagId),
- attributes: _decodeBagAttributes(capture.bagAttributes)
- };
- res.push(bag);
- var validator, decoder;
- var bagAsn1 = capture.bagValue.value[0];
- switch (bag.type) {
- case pki.oids.pkcs8ShroudedKeyBag:
- bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password);
- if (bagAsn1 === null) {
- throw new Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");
- }
- case pki.oids.keyBag:
- try {
- bag.key = pki.privateKeyFromAsn1(bagAsn1);
- } catch (e4) {
- bag.key = null;
- bag.asn1 = bagAsn1;
- }
- continue;
- case pki.oids.certBag:
- validator = certBagValidator;
- decoder = function() {
- if (asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) {
- var error47 = new Error("Unsupported certificate type, only X.509 supported.");
- error47.oid = asn1.derToOid(capture.certId);
- throw error47;
- }
- var certAsn1 = asn1.fromDer(capture.cert, strict);
- try {
- bag.cert = pki.certificateFromAsn1(certAsn1, true);
- } catch (e4) {
- bag.cert = null;
- bag.asn1 = certAsn1;
- }
- };
- break;
- default:
- var error46 = new Error("Unsupported PKCS#12 SafeBag type.");
- error46.oid = bag.type;
- throw error46;
- }
- if (validator !== undefined && !asn1.validate(bagAsn1, validator, capture, errors8)) {
- var error46 = new Error("Cannot read PKCS#12 " + validator.name);
- error46.errors = errors8;
- throw error46;
- }
- decoder();
- }
- return res;
- }
- function _decodeBagAttributes(attributes) {
- var decodedAttrs = {};
- if (attributes !== undefined) {
- for (var i6 = 0;i6 < attributes.length; ++i6) {
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(attributes[i6], attributeValidator, capture, errors8)) {
- var error46 = new Error("Cannot read PKCS#12 BagAttribute.");
- error46.errors = errors8;
- throw error46;
- }
- var oid = asn1.derToOid(capture.oid);
- if (pki.oids[oid] === undefined) {
- continue;
- }
- decodedAttrs[pki.oids[oid]] = [];
- for (var j4 = 0;j4 < capture.values.length; ++j4) {
- decodedAttrs[pki.oids[oid]].push(capture.values[j4].value);
- }
- }
- }
- return decodedAttrs;
- }
- p12.toPkcs12Asn1 = function(key2, cert, password, options2) {
- options2 = options2 || {};
- options2.saltSize = options2.saltSize || 8;
- options2.count = options2.count || 2048;
- options2.algorithm = options2.algorithm || options2.encAlgorithm || "aes128";
- if (!("useMac" in options2)) {
- options2.useMac = true;
- }
- if (!("localKeyId" in options2)) {
- options2.localKeyId = null;
- }
- if (!("generateLocalKeyId" in options2)) {
- options2.generateLocalKeyId = true;
- }
- var localKeyId = options2.localKeyId;
- var bagAttrs;
- if (localKeyId !== null) {
- localKeyId = forge.util.hexToBytes(localKeyId);
- } else if (options2.generateLocalKeyId) {
- if (cert) {
- var pairedCert = forge.util.isArray(cert) ? cert[0] : cert;
- if (typeof pairedCert === "string") {
- pairedCert = pki.certificateFromPem(pairedCert);
- }
- var sha1 = forge.md.sha1.create();
- sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes());
- localKeyId = sha1.digest().getBytes();
- } else {
- localKeyId = forge.random.getBytes(20);
- }
- }
- var attrs = [];
- if (localKeyId !== null) {
- attrs.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.localKeyId).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, localKeyId)
- ])
- ]));
- }
- if ("friendlyName" in options2) {
- attrs.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.friendlyName).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false, options2.friendlyName)
- ])
- ]));
- }
- if (attrs.length > 0) {
- bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs);
- }
- var contents = [];
- var chain4 = [];
- if (cert !== null) {
- if (forge.util.isArray(cert)) {
- chain4 = cert;
- } else {
- chain4 = [cert];
- }
- }
- var certSafeBags = [];
- for (var i6 = 0;i6 < chain4.length; ++i6) {
- cert = chain4[i6];
- if (typeof cert === "string") {
- cert = pki.certificateFromPem(cert);
- }
- var certBagAttrs = i6 === 0 ? bagAttrs : undefined;
- var certAsn1 = pki.certificateToAsn1(cert);
- var certSafeBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.certBag).getBytes()),
- asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.x509Certificate).getBytes()),
- asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(certAsn1).getBytes())
- ])
- ])
- ]),
- certBagAttrs
- ]);
- certSafeBags.push(certSafeBag);
- }
- if (certSafeBags.length > 0) {
- var certSafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags);
- var certCI = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.data).getBytes()),
- asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(certSafeContents).getBytes())
- ])
- ]);
- contents.push(certCI);
- }
- var keyBag = null;
- if (key2 !== null) {
- var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key2));
- if (password === null) {
- keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.keyBag).getBytes()),
- asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- pkAsn1
- ]),
- bagAttrs
- ]);
- } else {
- keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),
- asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- pki.encryptPrivateKeyInfo(pkAsn1, password, options2)
- ]),
- bagAttrs
- ]);
- }
- var keySafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]);
- var keyCI = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.data).getBytes()),
- asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(keySafeContents).getBytes())
- ])
- ]);
- contents.push(keyCI);
- }
- var safe = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents);
- var macData;
- if (options2.useMac) {
- var sha1 = forge.md.sha1.create();
- var macSalt = new forge.util.ByteBuffer(forge.random.getBytes(options2.saltSize));
- var count3 = options2.count;
- var key2 = p12.generateKey(password, macSalt, 3, count3, 20);
- var mac = forge.hmac.create();
- mac.start(sha1, key2);
- mac.update(asn1.toDer(safe).getBytes());
- var macValue = mac.getMac();
- macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.sha1).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
- ]),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macValue.getBytes())
- ]),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(count3).getBytes())
- ]);
- }
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(3).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.data).getBytes()),
- asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(safe).getBytes())
- ])
- ]),
- macData
- ]);
- };
- p12.generateKey = forge.pbe.generatePkcs12Key;
-});
-
-// node_modules/node-forge/lib/pki.js
-var require_pki = __commonJS((exports, module) => {
- var forge = require_forge();
- require_asn1();
- require_oids();
- require_pbe();
- require_pem();
- require_pbkdf2();
- require_pkcs12();
- require_pss();
- require_rsa();
- require_util3();
- require_x509();
- var asn1 = forge.asn1;
- var pki = module.exports = forge.pki = forge.pki || {};
- pki.pemToDer = function(pem) {
- var msg = forge.pem.decode(pem)[0];
- if (msg.procType && msg.procType.type === "ENCRYPTED") {
- throw new Error("Could not convert PEM to DER; PEM is encrypted.");
- }
- return forge.util.createBuffer(msg.body);
- };
- pki.privateKeyFromPem = function(pem) {
- var msg = forge.pem.decode(pem)[0];
- if (msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") {
- var error46 = new Error("Could not convert private key from PEM; PEM " + 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');
- error46.headerType = msg.type;
- throw error46;
- }
- if (msg.procType && msg.procType.type === "ENCRYPTED") {
- throw new Error("Could not convert private key from PEM; PEM is encrypted.");
- }
- var obj = asn1.fromDer(msg.body);
- return pki.privateKeyFromAsn1(obj);
- };
- pki.privateKeyToPem = function(key2, maxline) {
- var msg = {
- type: "RSA PRIVATE KEY",
- body: asn1.toDer(pki.privateKeyToAsn1(key2)).getBytes()
- };
- return forge.pem.encode(msg, { maxline });
- };
- pki.privateKeyInfoToPem = function(pki2, maxline) {
- var msg = {
- type: "PRIVATE KEY",
- body: asn1.toDer(pki2).getBytes()
- };
- return forge.pem.encode(msg, { maxline });
- };
-});
-
-// node_modules/node-forge/lib/tls.js
-var require_tls = __commonJS((exports, module) => {
- var forge = require_forge();
- require_asn1();
- require_hmac();
- require_md53();
- require_pem();
- require_pki();
- require_random();
- require_sha13();
- require_util3();
- var prf_TLS1 = function(secret, label, seed, length) {
- var rval = forge.util.createBuffer();
- var idx = secret.length >> 1;
- var slen = idx + (secret.length & 1);
- var s1 = secret.substr(0, slen);
- var s22 = secret.substr(idx, slen);
- var ai = forge.util.createBuffer();
- var hmac2 = forge.hmac.create();
- seed = label + seed;
- var md5itr = Math.ceil(length / 16);
- var sha1itr = Math.ceil(length / 20);
- hmac2.start("MD5", s1);
- var md5bytes = forge.util.createBuffer();
- ai.putBytes(seed);
- for (var i6 = 0;i6 < md5itr; ++i6) {
- hmac2.start(null, null);
- hmac2.update(ai.getBytes());
- ai.putBuffer(hmac2.digest());
- hmac2.start(null, null);
- hmac2.update(ai.bytes() + seed);
- md5bytes.putBuffer(hmac2.digest());
- }
- hmac2.start("SHA1", s22);
- var sha1bytes = forge.util.createBuffer();
- ai.clear();
- ai.putBytes(seed);
- for (var i6 = 0;i6 < sha1itr; ++i6) {
- hmac2.start(null, null);
- hmac2.update(ai.getBytes());
- ai.putBuffer(hmac2.digest());
- hmac2.start(null, null);
- hmac2.update(ai.bytes() + seed);
- sha1bytes.putBuffer(hmac2.digest());
- }
- rval.putBytes(forge.util.xorBytes(md5bytes.getBytes(), sha1bytes.getBytes(), length));
- return rval;
- };
- var hmac_sha1 = function(key3, seqNum, record2) {
- var hmac2 = forge.hmac.create();
- hmac2.start("SHA1", key3);
- var b5 = forge.util.createBuffer();
- b5.putInt32(seqNum[0]);
- b5.putInt32(seqNum[1]);
- b5.putByte(record2.type);
- b5.putByte(record2.version.major);
- b5.putByte(record2.version.minor);
- b5.putInt16(record2.length);
- b5.putBytes(record2.fragment.bytes());
- hmac2.update(b5.getBytes());
- return hmac2.digest().getBytes();
- };
- var deflate2 = function(c8, record2, s4) {
- var rval = false;
- try {
- var bytes = c8.deflate(record2.fragment.getBytes());
- record2.fragment = forge.util.createBuffer(bytes);
- record2.length = bytes.length;
- rval = true;
- } catch (ex) {}
- return rval;
- };
- var inflate2 = function(c8, record2, s4) {
- var rval = false;
- try {
- var bytes = c8.inflate(record2.fragment.getBytes());
- record2.fragment = forge.util.createBuffer(bytes);
- record2.length = bytes.length;
- rval = true;
- } catch (ex) {}
- return rval;
- };
- var readVector = function(b5, lenBytes) {
- var len = 0;
- switch (lenBytes) {
- case 1:
- len = b5.getByte();
- break;
- case 2:
- len = b5.getInt16();
- break;
- case 3:
- len = b5.getInt24();
- break;
- case 4:
- len = b5.getInt32();
- break;
- }
- return forge.util.createBuffer(b5.getBytes(len));
- };
- var writeVector = function(b5, lenBytes, v6) {
- b5.putInt(v6.length(), lenBytes << 3);
- b5.putBuffer(v6);
- };
- var tls = {};
- tls.Versions = {
- TLS_1_0: { major: 3, minor: 1 },
- TLS_1_1: { major: 3, minor: 2 },
- TLS_1_2: { major: 3, minor: 3 }
- };
- tls.SupportedVersions = [
- tls.Versions.TLS_1_1,
- tls.Versions.TLS_1_0
- ];
- tls.Version = tls.SupportedVersions[0];
- tls.MaxFragment = 16384 - 1024;
- tls.ConnectionEnd = {
- server: 0,
- client: 1
- };
- tls.PRFAlgorithm = {
- tls_prf_sha256: 0
- };
- tls.BulkCipherAlgorithm = {
- none: null,
- rc4: 0,
- des3: 1,
- aes: 2
- };
- tls.CipherType = {
- stream: 0,
- block: 1,
- aead: 2
- };
- tls.MACAlgorithm = {
- none: null,
- hmac_md5: 0,
- hmac_sha1: 1,
- hmac_sha256: 2,
- hmac_sha384: 3,
- hmac_sha512: 4
- };
- tls.CompressionMethod = {
- none: 0,
- deflate: 1
- };
- tls.ContentType = {
- change_cipher_spec: 20,
- alert: 21,
- handshake: 22,
- application_data: 23,
- heartbeat: 24
- };
- tls.HandshakeType = {
- hello_request: 0,
- client_hello: 1,
- server_hello: 2,
- certificate: 11,
- server_key_exchange: 12,
- certificate_request: 13,
- server_hello_done: 14,
- certificate_verify: 15,
- client_key_exchange: 16,
- finished: 20
- };
- tls.Alert = {};
- tls.Alert.Level = {
- warning: 1,
- fatal: 2
- };
- tls.Alert.Description = {
- close_notify: 0,
- unexpected_message: 10,
- bad_record_mac: 20,
- decryption_failed: 21,
- record_overflow: 22,
- decompression_failure: 30,
- handshake_failure: 40,
- bad_certificate: 42,
- unsupported_certificate: 43,
- certificate_revoked: 44,
- certificate_expired: 45,
- certificate_unknown: 46,
- illegal_parameter: 47,
- unknown_ca: 48,
- access_denied: 49,
- decode_error: 50,
- decrypt_error: 51,
- export_restriction: 60,
- protocol_version: 70,
- insufficient_security: 71,
- internal_error: 80,
- user_canceled: 90,
- no_renegotiation: 100
- };
- tls.HeartbeatMessageType = {
- heartbeat_request: 1,
- heartbeat_response: 2
- };
- tls.CipherSuites = {};
- tls.getCipherSuite = function(twoBytes) {
- var rval = null;
- for (var key3 in tls.CipherSuites) {
- var cs = tls.CipherSuites[key3];
- if (cs.id[0] === twoBytes.charCodeAt(0) && cs.id[1] === twoBytes.charCodeAt(1)) {
- rval = cs;
- break;
- }
- }
- return rval;
- };
- tls.handleUnexpected = function(c8, record2) {
- var ignore2 = !c8.open && c8.entity === tls.ConnectionEnd.client;
- if (!ignore2) {
- c8.error(c8, {
- message: "Unexpected message. Received TLS record out of order.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.unexpected_message
- }
- });
- }
- };
- tls.handleHelloRequest = function(c8, record2, length) {
- if (!c8.handshaking && c8.handshakes > 0) {
- tls.queue(c8, tls.createAlert(c8, {
- level: tls.Alert.Level.warning,
- description: tls.Alert.Description.no_renegotiation
- }));
- tls.flush(c8);
- }
- c8.process();
- };
- tls.parseHelloMessage = function(c8, record2, length) {
- var msg = null;
- var client16 = c8.entity === tls.ConnectionEnd.client;
- if (length < 38) {
- c8.error(c8, {
- message: client16 ? "Invalid ServerHello message. Message too short." : "Invalid ClientHello message. Message too short.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.illegal_parameter
- }
- });
- } else {
- var b5 = record2.fragment;
- var remaining = b5.length();
- msg = {
- version: {
- major: b5.getByte(),
- minor: b5.getByte()
- },
- random: forge.util.createBuffer(b5.getBytes(32)),
- session_id: readVector(b5, 1),
- extensions: []
- };
- if (client16) {
- msg.cipher_suite = b5.getBytes(2);
- msg.compression_method = b5.getByte();
- } else {
- msg.cipher_suites = readVector(b5, 2);
- msg.compression_methods = readVector(b5, 1);
- }
- remaining = length - (remaining - b5.length());
- if (remaining > 0) {
- var exts = readVector(b5, 2);
- while (exts.length() > 0) {
- msg.extensions.push({
- type: [exts.getByte(), exts.getByte()],
- data: readVector(exts, 2)
- });
- }
- if (!client16) {
- for (var i6 = 0;i6 < msg.extensions.length; ++i6) {
- var ext = msg.extensions[i6];
- if (ext.type[0] === 0 && ext.type[1] === 0) {
- var snl = readVector(ext.data, 2);
- while (snl.length() > 0) {
- var snType = snl.getByte();
- if (snType !== 0) {
- break;
- }
- c8.session.extensions.server_name.serverNameList.push(readVector(snl, 2).getBytes());
- }
- }
- }
- }
- }
- if (c8.session.version) {
- if (msg.version.major !== c8.session.version.major || msg.version.minor !== c8.session.version.minor) {
- return c8.error(c8, {
- message: "TLS version change is disallowed during renegotiation.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.protocol_version
- }
- });
- }
- }
- if (client16) {
- c8.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite);
- } else {
- var tmp = forge.util.createBuffer(msg.cipher_suites.bytes());
- while (tmp.length() > 0) {
- c8.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2));
- if (c8.session.cipherSuite !== null) {
- break;
- }
- }
- }
- if (c8.session.cipherSuite === null) {
- return c8.error(c8, {
- message: "No cipher suites in common.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.handshake_failure
- },
- cipherSuite: forge.util.bytesToHex(msg.cipher_suite)
- });
- }
- if (client16) {
- c8.session.compressionMethod = msg.compression_method;
- } else {
- c8.session.compressionMethod = tls.CompressionMethod.none;
- }
- }
- return msg;
- };
- tls.createSecurityParameters = function(c8, msg) {
- var client16 = c8.entity === tls.ConnectionEnd.client;
- var msgRandom = msg.random.bytes();
- var cRandom = client16 ? c8.session.sp.client_random : msgRandom;
- var sRandom = client16 ? msgRandom : tls.createRandom().getBytes();
- c8.session.sp = {
- entity: c8.entity,
- prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256,
- bulk_cipher_algorithm: null,
- cipher_type: null,
- enc_key_length: null,
- block_length: null,
- fixed_iv_length: null,
- record_iv_length: null,
- mac_algorithm: null,
- mac_length: null,
- mac_key_length: null,
- compression_algorithm: c8.session.compressionMethod,
- pre_master_secret: null,
- master_secret: null,
- client_random: cRandom,
- server_random: sRandom
- };
- };
- tls.handleServerHello = function(c8, record2, length) {
- var msg = tls.parseHelloMessage(c8, record2, length);
- if (c8.fail) {
- return;
- }
- if (msg.version.minor <= c8.version.minor) {
- c8.version.minor = msg.version.minor;
- } else {
- return c8.error(c8, {
- message: "Incompatible TLS version.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.protocol_version
- }
- });
- }
- c8.session.version = c8.version;
- var sessionId = msg.session_id.bytes();
- if (sessionId.length > 0 && sessionId === c8.session.id) {
- c8.expect = SCC;
- c8.session.resuming = true;
- c8.session.sp.server_random = msg.random.bytes();
- } else {
- c8.expect = SCE;
- c8.session.resuming = false;
- tls.createSecurityParameters(c8, msg);
- }
- c8.session.id = sessionId;
- c8.process();
- };
- tls.handleClientHello = function(c8, record2, length) {
- var msg = tls.parseHelloMessage(c8, record2, length);
- if (c8.fail) {
- return;
- }
- var sessionId = msg.session_id.bytes();
- var session = null;
- if (c8.sessionCache) {
- session = c8.sessionCache.getSession(sessionId);
- if (session === null) {
- sessionId = "";
- } else if (session.version.major !== msg.version.major || session.version.minor > msg.version.minor) {
- session = null;
- sessionId = "";
- }
- }
- if (sessionId.length === 0) {
- sessionId = forge.random.getBytes(32);
- }
- c8.session.id = sessionId;
- c8.session.clientHelloVersion = msg.version;
- c8.session.sp = {};
- if (session) {
- c8.version = c8.session.version = session.version;
- c8.session.sp = session.sp;
- } else {
- var version6;
- for (var i6 = 1;i6 < tls.SupportedVersions.length; ++i6) {
- version6 = tls.SupportedVersions[i6];
- if (version6.minor <= msg.version.minor) {
- break;
- }
- }
- c8.version = { major: version6.major, minor: version6.minor };
- c8.session.version = c8.version;
- }
- if (session !== null) {
- c8.expect = CCC;
- c8.session.resuming = true;
- c8.session.sp.client_random = msg.random.bytes();
- } else {
- c8.expect = c8.verifyClient !== false ? CCE : CKE;
- c8.session.resuming = false;
- tls.createSecurityParameters(c8, msg);
- }
- c8.open = true;
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.handshake,
- data: tls.createServerHello(c8)
- }));
- if (c8.session.resuming) {
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.change_cipher_spec,
- data: tls.createChangeCipherSpec()
- }));
- c8.state.pending = tls.createConnectionState(c8);
- c8.state.current.write = c8.state.pending.write;
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.handshake,
- data: tls.createFinished(c8)
- }));
- } else {
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.handshake,
- data: tls.createCertificate(c8)
- }));
- if (!c8.fail) {
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.handshake,
- data: tls.createServerKeyExchange(c8)
- }));
- if (c8.verifyClient !== false) {
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.handshake,
- data: tls.createCertificateRequest(c8)
- }));
- }
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.handshake,
- data: tls.createServerHelloDone(c8)
- }));
- }
- }
- tls.flush(c8);
- c8.process();
- };
- tls.handleCertificate = function(c8, record2, length) {
- if (length < 3) {
- return c8.error(c8, {
- message: "Invalid Certificate message. Message too short.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.illegal_parameter
- }
- });
- }
- var b5 = record2.fragment;
- var msg = {
- certificate_list: readVector(b5, 3)
- };
- var cert, asn1;
- var certs = [];
- try {
- while (msg.certificate_list.length() > 0) {
- cert = readVector(msg.certificate_list, 3);
- asn1 = forge.asn1.fromDer(cert);
- cert = forge.pki.certificateFromAsn1(asn1, true);
- certs.push(cert);
- }
- } catch (ex) {
- return c8.error(c8, {
- message: "Could not parse certificate list.",
- cause: ex,
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.bad_certificate
- }
- });
- }
- var client16 = c8.entity === tls.ConnectionEnd.client;
- if ((client16 || c8.verifyClient === true) && certs.length === 0) {
- c8.error(c8, {
- message: client16 ? "No server certificate provided." : "No client certificate provided.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.illegal_parameter
- }
- });
- } else if (certs.length === 0) {
- c8.expect = client16 ? SKE : CKE;
- } else {
- if (client16) {
- c8.session.serverCertificate = certs[0];
- } else {
- c8.session.clientCertificate = certs[0];
- }
- if (tls.verifyCertificateChain(c8, certs)) {
- c8.expect = client16 ? SKE : CKE;
- }
- }
- c8.process();
- };
- tls.handleServerKeyExchange = function(c8, record2, length) {
- if (length > 0) {
- return c8.error(c8, {
- message: "Invalid key parameters. Only RSA is supported.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.unsupported_certificate
- }
- });
- }
- c8.expect = SCR;
- c8.process();
- };
- tls.handleClientKeyExchange = function(c8, record2, length) {
- if (length < 48) {
- return c8.error(c8, {
- message: "Invalid key parameters. Only RSA is supported.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.unsupported_certificate
- }
- });
- }
- var b5 = record2.fragment;
- var msg = {
- enc_pre_master_secret: readVector(b5, 2).getBytes()
- };
- var privateKey = null;
- if (c8.getPrivateKey) {
- try {
- privateKey = c8.getPrivateKey(c8, c8.session.serverCertificate);
- privateKey = forge.pki.privateKeyFromPem(privateKey);
- } catch (ex) {
- c8.error(c8, {
- message: "Could not get private key.",
- cause: ex,
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.internal_error
- }
- });
- }
- }
- if (privateKey === null) {
- return c8.error(c8, {
- message: "No private key set.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.internal_error
- }
- });
- }
- try {
- var sp = c8.session.sp;
- sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret);
- var version6 = c8.session.clientHelloVersion;
- if (version6.major !== sp.pre_master_secret.charCodeAt(0) || version6.minor !== sp.pre_master_secret.charCodeAt(1)) {
- throw new Error("TLS version rollback attack detected.");
- }
- } catch (ex) {
- sp.pre_master_secret = forge.random.getBytes(48);
- }
- c8.expect = CCC;
- if (c8.session.clientCertificate !== null) {
- c8.expect = CCV;
- }
- c8.process();
- };
- tls.handleCertificateRequest = function(c8, record2, length) {
- if (length < 3) {
- return c8.error(c8, {
- message: "Invalid CertificateRequest. Message too short.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.illegal_parameter
- }
- });
- }
- var b5 = record2.fragment;
- var msg = {
- certificate_types: readVector(b5, 1),
- certificate_authorities: readVector(b5, 2)
- };
- c8.session.certificateRequest = msg;
- c8.expect = SHD;
- c8.process();
- };
- tls.handleCertificateVerify = function(c8, record2, length) {
- if (length < 2) {
- return c8.error(c8, {
- message: "Invalid CertificateVerify. Message too short.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.illegal_parameter
- }
- });
- }
- var b5 = record2.fragment;
- b5.read -= 4;
- var msgBytes = b5.bytes();
- b5.read += 4;
- var msg = {
- signature: readVector(b5, 2).getBytes()
- };
- var verify = forge.util.createBuffer();
- verify.putBuffer(c8.session.md5.digest());
- verify.putBuffer(c8.session.sha1.digest());
- verify = verify.getBytes();
- try {
- var cert = c8.session.clientCertificate;
- if (!cert.publicKey.verify(verify, msg.signature, "NONE")) {
- throw new Error("CertificateVerify signature does not match.");
- }
- c8.session.md5.update(msgBytes);
- c8.session.sha1.update(msgBytes);
- } catch (ex) {
- return c8.error(c8, {
- message: "Bad signature in CertificateVerify.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.handshake_failure
- }
- });
- }
- c8.expect = CCC;
- c8.process();
- };
- tls.handleServerHelloDone = function(c8, record2, length) {
- if (length > 0) {
- return c8.error(c8, {
- message: "Invalid ServerHelloDone message. Invalid length.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.record_overflow
- }
- });
- }
- if (c8.serverCertificate === null) {
- var error46 = {
- message: "No server certificate provided. Not enough security.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.insufficient_security
- }
- };
- var depth = 0;
- var ret = c8.verify(c8, error46.alert.description, depth, []);
- if (ret !== true) {
- if (ret || ret === 0) {
- if (typeof ret === "object" && !forge.util.isArray(ret)) {
- if (ret.message) {
- error46.message = ret.message;
- }
- if (ret.alert) {
- error46.alert.description = ret.alert;
- }
- } else if (typeof ret === "number") {
- error46.alert.description = ret;
- }
- }
- return c8.error(c8, error46);
- }
- }
- if (c8.session.certificateRequest !== null) {
- record2 = tls.createRecord(c8, {
- type: tls.ContentType.handshake,
- data: tls.createCertificate(c8)
- });
- tls.queue(c8, record2);
- }
- record2 = tls.createRecord(c8, {
- type: tls.ContentType.handshake,
- data: tls.createClientKeyExchange(c8)
- });
- tls.queue(c8, record2);
- c8.expect = SER;
- var callback = function(c9, signature7) {
- if (c9.session.certificateRequest !== null && c9.session.clientCertificate !== null) {
- tls.queue(c9, tls.createRecord(c9, {
- type: tls.ContentType.handshake,
- data: tls.createCertificateVerify(c9, signature7)
- }));
- }
- tls.queue(c9, tls.createRecord(c9, {
- type: tls.ContentType.change_cipher_spec,
- data: tls.createChangeCipherSpec()
- }));
- c9.state.pending = tls.createConnectionState(c9);
- c9.state.current.write = c9.state.pending.write;
- tls.queue(c9, tls.createRecord(c9, {
- type: tls.ContentType.handshake,
- data: tls.createFinished(c9)
- }));
- c9.expect = SCC;
- tls.flush(c9);
- c9.process();
- };
- if (c8.session.certificateRequest === null || c8.session.clientCertificate === null) {
- return callback(c8, null);
- }
- tls.getClientSignature(c8, callback);
- };
- tls.handleChangeCipherSpec = function(c8, record2) {
- if (record2.fragment.getByte() !== 1) {
- return c8.error(c8, {
- message: "Invalid ChangeCipherSpec message received.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.illegal_parameter
- }
- });
- }
- var client16 = c8.entity === tls.ConnectionEnd.client;
- if (c8.session.resuming && client16 || !c8.session.resuming && !client16) {
- c8.state.pending = tls.createConnectionState(c8);
- }
- c8.state.current.read = c8.state.pending.read;
- if (!c8.session.resuming && client16 || c8.session.resuming && !client16) {
- c8.state.pending = null;
- }
- c8.expect = client16 ? SFI : CFI;
- c8.process();
- };
- tls.handleFinished = function(c8, record2, length) {
- var b5 = record2.fragment;
- b5.read -= 4;
- var msgBytes = b5.bytes();
- b5.read += 4;
- var vd = record2.fragment.getBytes();
- b5 = forge.util.createBuffer();
- b5.putBuffer(c8.session.md5.digest());
- b5.putBuffer(c8.session.sha1.digest());
- var client16 = c8.entity === tls.ConnectionEnd.client;
- var label = client16 ? "server finished" : "client finished";
- var sp = c8.session.sp;
- var vdl = 12;
- var prf = prf_TLS1;
- b5 = prf(sp.master_secret, label, b5.getBytes(), vdl);
- if (b5.getBytes() !== vd) {
- return c8.error(c8, {
- message: "Invalid verify_data in Finished message.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.decrypt_error
- }
- });
- }
- c8.session.md5.update(msgBytes);
- c8.session.sha1.update(msgBytes);
- if (c8.session.resuming && client16 || !c8.session.resuming && !client16) {
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.change_cipher_spec,
- data: tls.createChangeCipherSpec()
- }));
- c8.state.current.write = c8.state.pending.write;
- c8.state.pending = null;
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.handshake,
- data: tls.createFinished(c8)
- }));
- }
- c8.expect = client16 ? SAD : CAD;
- c8.handshaking = false;
- ++c8.handshakes;
- c8.peerCertificate = client16 ? c8.session.serverCertificate : c8.session.clientCertificate;
- tls.flush(c8);
- c8.isConnected = true;
- c8.connected(c8);
- c8.process();
- };
- tls.handleAlert = function(c8, record2) {
- var b5 = record2.fragment;
- var alert = {
- level: b5.getByte(),
- description: b5.getByte()
- };
- var msg;
- switch (alert.description) {
- case tls.Alert.Description.close_notify:
- msg = "Connection closed.";
- break;
- case tls.Alert.Description.unexpected_message:
- msg = "Unexpected message.";
- break;
- case tls.Alert.Description.bad_record_mac:
- msg = "Bad record MAC.";
- break;
- case tls.Alert.Description.decryption_failed:
- msg = "Decryption failed.";
- break;
- case tls.Alert.Description.record_overflow:
- msg = "Record overflow.";
- break;
- case tls.Alert.Description.decompression_failure:
- msg = "Decompression failed.";
- break;
- case tls.Alert.Description.handshake_failure:
- msg = "Handshake failure.";
- break;
- case tls.Alert.Description.bad_certificate:
- msg = "Bad certificate.";
- break;
- case tls.Alert.Description.unsupported_certificate:
- msg = "Unsupported certificate.";
- break;
- case tls.Alert.Description.certificate_revoked:
- msg = "Certificate revoked.";
- break;
- case tls.Alert.Description.certificate_expired:
- msg = "Certificate expired.";
- break;
- case tls.Alert.Description.certificate_unknown:
- msg = "Certificate unknown.";
- break;
- case tls.Alert.Description.illegal_parameter:
- msg = "Illegal parameter.";
- break;
- case tls.Alert.Description.unknown_ca:
- msg = "Unknown certificate authority.";
- break;
- case tls.Alert.Description.access_denied:
- msg = "Access denied.";
- break;
- case tls.Alert.Description.decode_error:
- msg = "Decode error.";
- break;
- case tls.Alert.Description.decrypt_error:
- msg = "Decrypt error.";
- break;
- case tls.Alert.Description.export_restriction:
- msg = "Export restriction.";
- break;
- case tls.Alert.Description.protocol_version:
- msg = "Unsupported protocol version.";
- break;
- case tls.Alert.Description.insufficient_security:
- msg = "Insufficient security.";
- break;
- case tls.Alert.Description.internal_error:
- msg = "Internal error.";
- break;
- case tls.Alert.Description.user_canceled:
- msg = "User canceled.";
- break;
- case tls.Alert.Description.no_renegotiation:
- msg = "Renegotiation not supported.";
- break;
- default:
- msg = "Unknown error.";
- break;
- }
- if (alert.description === tls.Alert.Description.close_notify) {
- return c8.close();
- }
- c8.error(c8, {
- message: msg,
- send: false,
- origin: c8.entity === tls.ConnectionEnd.client ? "server" : "client",
- alert
- });
- c8.process();
- };
- tls.handleHandshake = function(c8, record2) {
- var b5 = record2.fragment;
- var type = b5.getByte();
- var length = b5.getInt24();
- if (length > b5.length()) {
- c8.fragmented = record2;
- record2.fragment = forge.util.createBuffer();
- b5.read -= 4;
- return c8.process();
- }
- c8.fragmented = null;
- b5.read -= 4;
- var bytes = b5.bytes(length + 4);
- b5.read += 4;
- if (type in hsTable[c8.entity][c8.expect]) {
- if (c8.entity === tls.ConnectionEnd.server && !c8.open && !c8.fail) {
- c8.handshaking = true;
- c8.session = {
- version: null,
- extensions: {
- server_name: {
- serverNameList: []
- }
- },
- cipherSuite: null,
- compressionMethod: null,
- serverCertificate: null,
- clientCertificate: null,
- md5: forge.md.md5.create(),
- sha1: forge.md.sha1.create()
- };
- }
- if (type !== tls.HandshakeType.hello_request && type !== tls.HandshakeType.certificate_verify && type !== tls.HandshakeType.finished) {
- c8.session.md5.update(bytes);
- c8.session.sha1.update(bytes);
- }
- hsTable[c8.entity][c8.expect][type](c8, record2, length);
- } else {
- tls.handleUnexpected(c8, record2);
- }
- };
- tls.handleApplicationData = function(c8, record2) {
- c8.data.putBuffer(record2.fragment);
- c8.dataReady(c8);
- c8.process();
- };
- tls.handleHeartbeat = function(c8, record2) {
- var b5 = record2.fragment;
- var type = b5.getByte();
- var length = b5.getInt16();
- var payload = b5.getBytes(length);
- if (type === tls.HeartbeatMessageType.heartbeat_request) {
- if (c8.handshaking || length > payload.length) {
- return c8.process();
- }
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.heartbeat,
- data: tls.createHeartbeat(tls.HeartbeatMessageType.heartbeat_response, payload)
- }));
- tls.flush(c8);
- } else if (type === tls.HeartbeatMessageType.heartbeat_response) {
- if (payload !== c8.expectedHeartbeatPayload) {
- return c8.process();
- }
- if (c8.heartbeatReceived) {
- c8.heartbeatReceived(c8, forge.util.createBuffer(payload));
- }
- }
- c8.process();
- };
- var SHE = 0;
- var SCE = 1;
- var SKE = 2;
- var SCR = 3;
- var SHD = 4;
- var SCC = 5;
- var SFI = 6;
- var SAD = 7;
- var SER = 8;
- var CHE = 0;
- var CCE = 1;
- var CKE = 2;
- var CCV = 3;
- var CCC = 4;
- var CFI = 5;
- var CAD = 6;
- var __ = tls.handleUnexpected;
- var R0 = tls.handleChangeCipherSpec;
- var R1 = tls.handleAlert;
- var R2 = tls.handleHandshake;
- var R3 = tls.handleApplicationData;
- var R4 = tls.handleHeartbeat;
- var ctTable = [];
- ctTable[tls.ConnectionEnd.client] = [
- [__, R1, R2, __, R4],
- [__, R1, R2, __, R4],
- [__, R1, R2, __, R4],
- [__, R1, R2, __, R4],
- [__, R1, R2, __, R4],
- [R0, R1, __, __, R4],
- [__, R1, R2, __, R4],
- [__, R1, R2, R3, R4],
- [__, R1, R2, __, R4]
- ];
- ctTable[tls.ConnectionEnd.server] = [
- [__, R1, R2, __, R4],
- [__, R1, R2, __, R4],
- [__, R1, R2, __, R4],
- [__, R1, R2, __, R4],
- [R0, R1, __, __, R4],
- [__, R1, R2, __, R4],
- [__, R1, R2, R3, R4],
- [__, R1, R2, __, R4]
- ];
- var H0 = tls.handleHelloRequest;
- var H1 = tls.handleServerHello;
- var H22 = tls.handleCertificate;
- var H3 = tls.handleServerKeyExchange;
- var H4 = tls.handleCertificateRequest;
- var H5 = tls.handleServerHelloDone;
- var H6 = tls.handleFinished;
- var hsTable = [];
- hsTable[tls.ConnectionEnd.client] = [
- [__, __, H1, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
- [H0, __, __, __, __, __, __, __, __, __, __, H22, H3, H4, H5, __, __, __, __, __, __],
- [H0, __, __, __, __, __, __, __, __, __, __, __, H3, H4, H5, __, __, __, __, __, __],
- [H0, __, __, __, __, __, __, __, __, __, __, __, __, H4, H5, __, __, __, __, __, __],
- [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, H5, __, __, __, __, __, __],
- [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
- [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6],
- [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
- [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __]
- ];
- var H7 = tls.handleClientHello;
- var H8 = tls.handleClientKeyExchange;
- var H9 = tls.handleCertificateVerify;
- hsTable[tls.ConnectionEnd.server] = [
- [__, H7, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
- [__, __, __, __, __, __, __, __, __, __, __, H22, __, __, __, __, __, __, __, __, __],
- [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H8, __, __, __, __],
- [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H9, __, __, __, __, __],
- [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
- [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6],
- [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
- [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __]
- ];
- tls.generateKeys = function(c8, sp) {
- var prf = prf_TLS1;
- var random = sp.client_random + sp.server_random;
- if (!c8.session.resuming) {
- sp.master_secret = prf(sp.pre_master_secret, "master secret", random, 48).bytes();
- sp.pre_master_secret = null;
- }
- random = sp.server_random + sp.client_random;
- var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length;
- var tls10 = c8.version.major === tls.Versions.TLS_1_0.major && c8.version.minor === tls.Versions.TLS_1_0.minor;
- if (tls10) {
- length += 2 * sp.fixed_iv_length;
- }
- var km = prf(sp.master_secret, "key expansion", random, length);
- var rval = {
- client_write_MAC_key: km.getBytes(sp.mac_key_length),
- server_write_MAC_key: km.getBytes(sp.mac_key_length),
- client_write_key: km.getBytes(sp.enc_key_length),
- server_write_key: km.getBytes(sp.enc_key_length)
- };
- if (tls10) {
- rval.client_write_IV = km.getBytes(sp.fixed_iv_length);
- rval.server_write_IV = km.getBytes(sp.fixed_iv_length);
- }
- return rval;
- };
- tls.createConnectionState = function(c8) {
- var client16 = c8.entity === tls.ConnectionEnd.client;
- var createMode = function() {
- var mode = {
- sequenceNumber: [0, 0],
- macKey: null,
- macLength: 0,
- macFunction: null,
- cipherState: null,
- cipherFunction: function(record2) {
- return true;
- },
- compressionState: null,
- compressFunction: function(record2) {
- return true;
- },
- updateSequenceNumber: function() {
- if (mode.sequenceNumber[1] === 4294967295) {
- mode.sequenceNumber[1] = 0;
- ++mode.sequenceNumber[0];
- } else {
- ++mode.sequenceNumber[1];
- }
- }
- };
- return mode;
- };
- var state3 = {
- read: createMode(),
- write: createMode()
- };
- state3.read.update = function(c9, record2) {
- if (!state3.read.cipherFunction(record2, state3.read)) {
- c9.error(c9, {
- message: "Could not decrypt record or bad MAC.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.bad_record_mac
- }
- });
- } else if (!state3.read.compressFunction(c9, record2, state3.read)) {
- c9.error(c9, {
- message: "Could not decompress record.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.decompression_failure
- }
- });
- }
- return !c9.fail;
- };
- state3.write.update = function(c9, record2) {
- if (!state3.write.compressFunction(c9, record2, state3.write)) {
- c9.error(c9, {
- message: "Could not compress record.",
- send: false,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.internal_error
- }
- });
- } else if (!state3.write.cipherFunction(record2, state3.write)) {
- c9.error(c9, {
- message: "Could not encrypt record.",
- send: false,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.internal_error
- }
- });
- }
- return !c9.fail;
- };
- if (c8.session) {
- var sp = c8.session.sp;
- c8.session.cipherSuite.initSecurityParameters(sp);
- sp.keys = tls.generateKeys(c8, sp);
- state3.read.macKey = client16 ? sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key;
- state3.write.macKey = client16 ? sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key;
- c8.session.cipherSuite.initConnectionState(state3, c8, sp);
- switch (sp.compression_algorithm) {
- case tls.CompressionMethod.none:
- break;
- case tls.CompressionMethod.deflate:
- state3.read.compressFunction = inflate2;
- state3.write.compressFunction = deflate2;
- break;
- default:
- throw new Error("Unsupported compression algorithm.");
- }
- }
- return state3;
- };
- tls.createRandom = function() {
- var d4 = new Date;
- var utc = +d4 + d4.getTimezoneOffset() * 60000;
- var rval = forge.util.createBuffer();
- rval.putInt32(utc);
- rval.putBytes(forge.random.getBytes(28));
- return rval;
- };
- tls.createRecord = function(c8, options2) {
- if (!options2.data) {
- return null;
- }
- var record2 = {
- type: options2.type,
- version: {
- major: c8.version.major,
- minor: c8.version.minor
- },
- length: options2.data.length(),
- fragment: options2.data
- };
- return record2;
- };
- tls.createAlert = function(c8, alert) {
- var b5 = forge.util.createBuffer();
- b5.putByte(alert.level);
- b5.putByte(alert.description);
- return tls.createRecord(c8, {
- type: tls.ContentType.alert,
- data: b5
- });
- };
- tls.createClientHello = function(c8) {
- c8.session.clientHelloVersion = {
- major: c8.version.major,
- minor: c8.version.minor
- };
- var cipherSuites = forge.util.createBuffer();
- for (var i6 = 0;i6 < c8.cipherSuites.length; ++i6) {
- var cs = c8.cipherSuites[i6];
- cipherSuites.putByte(cs.id[0]);
- cipherSuites.putByte(cs.id[1]);
- }
- var cSuites = cipherSuites.length();
- var compressionMethods = forge.util.createBuffer();
- compressionMethods.putByte(tls.CompressionMethod.none);
- var cMethods = compressionMethods.length();
- var extensions20 = forge.util.createBuffer();
- if (c8.virtualHost) {
- var ext = forge.util.createBuffer();
- ext.putByte(0);
- ext.putByte(0);
- var serverName = forge.util.createBuffer();
- serverName.putByte(0);
- writeVector(serverName, 2, forge.util.createBuffer(c8.virtualHost));
- var snList = forge.util.createBuffer();
- writeVector(snList, 2, serverName);
- writeVector(ext, 2, snList);
- extensions20.putBuffer(ext);
- }
- var extLength = extensions20.length();
- if (extLength > 0) {
- extLength += 2;
- }
- var sessionId = c8.session.id;
- var length = sessionId.length + 1 + 2 + 4 + 28 + 2 + cSuites + 1 + cMethods + extLength;
- var rval = forge.util.createBuffer();
- rval.putByte(tls.HandshakeType.client_hello);
- rval.putInt24(length);
- rval.putByte(c8.version.major);
- rval.putByte(c8.version.minor);
- rval.putBytes(c8.session.sp.client_random);
- writeVector(rval, 1, forge.util.createBuffer(sessionId));
- writeVector(rval, 2, cipherSuites);
- writeVector(rval, 1, compressionMethods);
- if (extLength > 0) {
- writeVector(rval, 2, extensions20);
- }
- return rval;
- };
- tls.createServerHello = function(c8) {
- var sessionId = c8.session.id;
- var length = sessionId.length + 1 + 2 + 4 + 28 + 2 + 1;
- var rval = forge.util.createBuffer();
- rval.putByte(tls.HandshakeType.server_hello);
- rval.putInt24(length);
- rval.putByte(c8.version.major);
- rval.putByte(c8.version.minor);
- rval.putBytes(c8.session.sp.server_random);
- writeVector(rval, 1, forge.util.createBuffer(sessionId));
- rval.putByte(c8.session.cipherSuite.id[0]);
- rval.putByte(c8.session.cipherSuite.id[1]);
- rval.putByte(c8.session.compressionMethod);
- return rval;
- };
- tls.createCertificate = function(c8) {
- var client16 = c8.entity === tls.ConnectionEnd.client;
- var cert = null;
- if (c8.getCertificate) {
- var hint;
- if (client16) {
- hint = c8.session.certificateRequest;
- } else {
- hint = c8.session.extensions.server_name.serverNameList;
- }
- cert = c8.getCertificate(c8, hint);
- }
- var certList = forge.util.createBuffer();
- if (cert !== null) {
- try {
- if (!forge.util.isArray(cert)) {
- cert = [cert];
- }
- var asn1 = null;
- for (var i6 = 0;i6 < cert.length; ++i6) {
- var msg = forge.pem.decode(cert[i6])[0];
- if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") {
- var error46 = new Error("Could not convert certificate from PEM; PEM " + 'header type is not "CERTIFICATE", "X509 CERTIFICATE", or ' + '"TRUSTED CERTIFICATE".');
- error46.headerType = msg.type;
- throw error46;
- }
- if (msg.procType && msg.procType.type === "ENCRYPTED") {
- throw new Error("Could not convert certificate from PEM; PEM is encrypted.");
- }
- var der = forge.util.createBuffer(msg.body);
- if (asn1 === null) {
- asn1 = forge.asn1.fromDer(der.bytes(), false);
- }
- var certBuffer = forge.util.createBuffer();
- writeVector(certBuffer, 3, der);
- certList.putBuffer(certBuffer);
- }
- cert = forge.pki.certificateFromAsn1(asn1);
- if (client16) {
- c8.session.clientCertificate = cert;
- } else {
- c8.session.serverCertificate = cert;
- }
- } catch (ex) {
- return c8.error(c8, {
- message: "Could not send certificate list.",
- cause: ex,
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.bad_certificate
- }
- });
- }
- }
- var length = 3 + certList.length();
- var rval = forge.util.createBuffer();
- rval.putByte(tls.HandshakeType.certificate);
- rval.putInt24(length);
- writeVector(rval, 3, certList);
- return rval;
- };
- tls.createClientKeyExchange = function(c8) {
- var b5 = forge.util.createBuffer();
- b5.putByte(c8.session.clientHelloVersion.major);
- b5.putByte(c8.session.clientHelloVersion.minor);
- b5.putBytes(forge.random.getBytes(46));
- var sp = c8.session.sp;
- sp.pre_master_secret = b5.getBytes();
- var key3 = c8.session.serverCertificate.publicKey;
- b5 = key3.encrypt(sp.pre_master_secret);
- var length = b5.length + 2;
- var rval = forge.util.createBuffer();
- rval.putByte(tls.HandshakeType.client_key_exchange);
- rval.putInt24(length);
- rval.putInt16(b5.length);
- rval.putBytes(b5);
- return rval;
- };
- tls.createServerKeyExchange = function(c8) {
- var length = 0;
- var rval = forge.util.createBuffer();
- if (length > 0) {
- rval.putByte(tls.HandshakeType.server_key_exchange);
- rval.putInt24(length);
- }
- return rval;
- };
- tls.getClientSignature = function(c8, callback) {
- var b5 = forge.util.createBuffer();
- b5.putBuffer(c8.session.md5.digest());
- b5.putBuffer(c8.session.sha1.digest());
- b5 = b5.getBytes();
- c8.getSignature = c8.getSignature || function(c9, b6, callback2) {
- var privateKey = null;
- if (c9.getPrivateKey) {
- try {
- privateKey = c9.getPrivateKey(c9, c9.session.clientCertificate);
- privateKey = forge.pki.privateKeyFromPem(privateKey);
- } catch (ex) {
- c9.error(c9, {
- message: "Could not get private key.",
- cause: ex,
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.internal_error
- }
- });
- }
- }
- if (privateKey === null) {
- c9.error(c9, {
- message: "No private key set.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.internal_error
- }
- });
- } else {
- b6 = privateKey.sign(b6, null);
- }
- callback2(c9, b6);
- };
- c8.getSignature(c8, b5, callback);
- };
- tls.createCertificateVerify = function(c8, signature7) {
- var length = signature7.length + 2;
- var rval = forge.util.createBuffer();
- rval.putByte(tls.HandshakeType.certificate_verify);
- rval.putInt24(length);
- rval.putInt16(signature7.length);
- rval.putBytes(signature7);
- return rval;
- };
- tls.createCertificateRequest = function(c8) {
- var certTypes = forge.util.createBuffer();
- certTypes.putByte(1);
- var cAs = forge.util.createBuffer();
- for (var key3 in c8.caStore.certs) {
- var cert = c8.caStore.certs[key3];
- var dn = forge.pki.distinguishedNameToAsn1(cert.subject);
- var byteBuffer = forge.asn1.toDer(dn);
- cAs.putInt16(byteBuffer.length());
- cAs.putBuffer(byteBuffer);
- }
- var length = 1 + certTypes.length() + 2 + cAs.length();
- var rval = forge.util.createBuffer();
- rval.putByte(tls.HandshakeType.certificate_request);
- rval.putInt24(length);
- writeVector(rval, 1, certTypes);
- writeVector(rval, 2, cAs);
- return rval;
- };
- tls.createServerHelloDone = function(c8) {
- var rval = forge.util.createBuffer();
- rval.putByte(tls.HandshakeType.server_hello_done);
- rval.putInt24(0);
- return rval;
- };
- tls.createChangeCipherSpec = function() {
- var rval = forge.util.createBuffer();
- rval.putByte(1);
- return rval;
- };
- tls.createFinished = function(c8) {
- var b5 = forge.util.createBuffer();
- b5.putBuffer(c8.session.md5.digest());
- b5.putBuffer(c8.session.sha1.digest());
- var client16 = c8.entity === tls.ConnectionEnd.client;
- var sp = c8.session.sp;
- var vdl = 12;
- var prf = prf_TLS1;
- var label = client16 ? "client finished" : "server finished";
- b5 = prf(sp.master_secret, label, b5.getBytes(), vdl);
- var rval = forge.util.createBuffer();
- rval.putByte(tls.HandshakeType.finished);
- rval.putInt24(b5.length());
- rval.putBuffer(b5);
- return rval;
- };
- tls.createHeartbeat = function(type, payload, payloadLength) {
- if (typeof payloadLength === "undefined") {
- payloadLength = payload.length;
- }
- var rval = forge.util.createBuffer();
- rval.putByte(type);
- rval.putInt16(payloadLength);
- rval.putBytes(payload);
- var plaintextLength = rval.length();
- var paddingLength = Math.max(16, plaintextLength - payloadLength - 3);
- rval.putBytes(forge.random.getBytes(paddingLength));
- return rval;
- };
- tls.queue = function(c8, record2) {
- if (!record2) {
- return;
- }
- if (record2.fragment.length() === 0) {
- if (record2.type === tls.ContentType.handshake || record2.type === tls.ContentType.alert || record2.type === tls.ContentType.change_cipher_spec) {
- return;
- }
- }
- if (record2.type === tls.ContentType.handshake) {
- var bytes = record2.fragment.bytes();
- c8.session.md5.update(bytes);
- c8.session.sha1.update(bytes);
- bytes = null;
- }
- var records;
- if (record2.fragment.length() <= tls.MaxFragment) {
- records = [record2];
- } else {
- records = [];
- var data = record2.fragment.bytes();
- while (data.length > tls.MaxFragment) {
- records.push(tls.createRecord(c8, {
- type: record2.type,
- data: forge.util.createBuffer(data.slice(0, tls.MaxFragment))
- }));
- data = data.slice(tls.MaxFragment);
- }
- if (data.length > 0) {
- records.push(tls.createRecord(c8, {
- type: record2.type,
- data: forge.util.createBuffer(data)
- }));
- }
- }
- for (var i6 = 0;i6 < records.length && !c8.fail; ++i6) {
- var rec = records[i6];
- var s4 = c8.state.current.write;
- if (s4.update(c8, rec)) {
- c8.records.push(rec);
- }
- }
- };
- tls.flush = function(c8) {
- for (var i6 = 0;i6 < c8.records.length; ++i6) {
- var record2 = c8.records[i6];
- c8.tlsData.putByte(record2.type);
- c8.tlsData.putByte(record2.version.major);
- c8.tlsData.putByte(record2.version.minor);
- c8.tlsData.putInt16(record2.fragment.length());
- c8.tlsData.putBuffer(c8.records[i6].fragment);
- }
- c8.records = [];
- return c8.tlsDataReady(c8);
- };
- var _certErrorToAlertDesc = function(error46) {
- switch (error46) {
- case true:
- return true;
- case forge.pki.certificateError.bad_certificate:
- return tls.Alert.Description.bad_certificate;
- case forge.pki.certificateError.unsupported_certificate:
- return tls.Alert.Description.unsupported_certificate;
- case forge.pki.certificateError.certificate_revoked:
- return tls.Alert.Description.certificate_revoked;
- case forge.pki.certificateError.certificate_expired:
- return tls.Alert.Description.certificate_expired;
- case forge.pki.certificateError.certificate_unknown:
- return tls.Alert.Description.certificate_unknown;
- case forge.pki.certificateError.unknown_ca:
- return tls.Alert.Description.unknown_ca;
- default:
- return tls.Alert.Description.bad_certificate;
- }
- };
- var _alertDescToCertError = function(desc) {
- switch (desc) {
- case true:
- return true;
- case tls.Alert.Description.bad_certificate:
- return forge.pki.certificateError.bad_certificate;
- case tls.Alert.Description.unsupported_certificate:
- return forge.pki.certificateError.unsupported_certificate;
- case tls.Alert.Description.certificate_revoked:
- return forge.pki.certificateError.certificate_revoked;
- case tls.Alert.Description.certificate_expired:
- return forge.pki.certificateError.certificate_expired;
- case tls.Alert.Description.certificate_unknown:
- return forge.pki.certificateError.certificate_unknown;
- case tls.Alert.Description.unknown_ca:
- return forge.pki.certificateError.unknown_ca;
- default:
- return forge.pki.certificateError.bad_certificate;
- }
- };
- tls.verifyCertificateChain = function(c8, chain4) {
- try {
- var options2 = {};
- for (var key3 in c8.verifyOptions) {
- options2[key3] = c8.verifyOptions[key3];
- }
- options2.verify = function(vfd, depth, chain5) {
- var desc = _certErrorToAlertDesc(vfd);
- var ret = c8.verify(c8, vfd, depth, chain5);
- if (ret !== true) {
- if (typeof ret === "object" && !forge.util.isArray(ret)) {
- var error46 = new Error("The application rejected the certificate.");
- error46.send = true;
- error46.alert = {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.bad_certificate
- };
- if (ret.message) {
- error46.message = ret.message;
- }
- if (ret.alert) {
- error46.alert.description = ret.alert;
- }
- throw error46;
- }
- if (ret !== vfd) {
- ret = _alertDescToCertError(ret);
- }
- }
- return ret;
- };
- forge.pki.verifyCertificateChain(c8.caStore, chain4, options2);
- } catch (ex) {
- var err2 = ex;
- if (typeof err2 !== "object" || forge.util.isArray(err2)) {
- err2 = {
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: _certErrorToAlertDesc(ex)
- }
- };
- }
- if (!("send" in err2)) {
- err2.send = true;
- }
- if (!("alert" in err2)) {
- err2.alert = {
- level: tls.Alert.Level.fatal,
- description: _certErrorToAlertDesc(err2.error)
- };
- }
- c8.error(c8, err2);
- }
- return !c8.fail;
- };
- tls.createSessionCache = function(cache6, capacity) {
- var rval = null;
- if (cache6 && cache6.getSession && cache6.setSession && cache6.order) {
- rval = cache6;
- } else {
- rval = {};
- rval.cache = cache6 || {};
- rval.capacity = Math.max(capacity || 100, 1);
- rval.order = [];
- for (var key3 in cache6) {
- if (rval.order.length <= capacity) {
- rval.order.push(key3);
- } else {
- delete cache6[key3];
- }
- }
- rval.getSession = function(sessionId) {
- var session = null;
- var key4 = null;
- if (sessionId) {
- key4 = forge.util.bytesToHex(sessionId);
- } else if (rval.order.length > 0) {
- key4 = rval.order[0];
- }
- if (key4 !== null && key4 in rval.cache) {
- session = rval.cache[key4];
- delete rval.cache[key4];
- for (var i6 in rval.order) {
- if (rval.order[i6] === key4) {
- rval.order.splice(i6, 1);
- break;
- }
- }
- }
- return session;
- };
- rval.setSession = function(sessionId, session) {
- if (rval.order.length === rval.capacity) {
- var key4 = rval.order.shift();
- delete rval.cache[key4];
- }
- var key4 = forge.util.bytesToHex(sessionId);
- rval.order.push(key4);
- rval.cache[key4] = session;
- };
- }
- return rval;
- };
- tls.createConnection = function(options2) {
- var caStore = null;
- if (options2.caStore) {
- if (forge.util.isArray(options2.caStore)) {
- caStore = forge.pki.createCaStore(options2.caStore);
- } else {
- caStore = options2.caStore;
- }
- } else {
- caStore = forge.pki.createCaStore();
- }
- var cipherSuites = options2.cipherSuites || null;
- if (cipherSuites === null) {
- cipherSuites = [];
- for (var key3 in tls.CipherSuites) {
- cipherSuites.push(tls.CipherSuites[key3]);
- }
- }
- var entity = options2.server ? tls.ConnectionEnd.server : tls.ConnectionEnd.client;
- var sessionCache2 = options2.sessionCache ? tls.createSessionCache(options2.sessionCache) : null;
- var c8 = {
- version: { major: tls.Version.major, minor: tls.Version.minor },
- entity,
- sessionId: options2.sessionId,
- caStore,
- sessionCache: sessionCache2,
- cipherSuites,
- connected: options2.connected,
- virtualHost: options2.virtualHost || null,
- verifyClient: options2.verifyClient || false,
- verify: options2.verify || function(cn, vfd, dpth, cts) {
- return vfd;
- },
- verifyOptions: options2.verifyOptions || {},
- getCertificate: options2.getCertificate || null,
- getPrivateKey: options2.getPrivateKey || null,
- getSignature: options2.getSignature || null,
- input: forge.util.createBuffer(),
- tlsData: forge.util.createBuffer(),
- data: forge.util.createBuffer(),
- tlsDataReady: options2.tlsDataReady,
- dataReady: options2.dataReady,
- heartbeatReceived: options2.heartbeatReceived,
- closed: options2.closed,
- error: function(c9, ex) {
- ex.origin = ex.origin || (c9.entity === tls.ConnectionEnd.client ? "client" : "server");
- if (ex.send) {
- tls.queue(c9, tls.createAlert(c9, ex.alert));
- tls.flush(c9);
- }
- var fatal = ex.fatal !== false;
- if (fatal) {
- c9.fail = true;
- }
- options2.error(c9, ex);
- if (fatal) {
- c9.close(false);
- }
- },
- deflate: options2.deflate || null,
- inflate: options2.inflate || null
- };
- c8.reset = function(clearFail) {
- c8.version = { major: tls.Version.major, minor: tls.Version.minor };
- c8.record = null;
- c8.session = null;
- c8.peerCertificate = null;
- c8.state = {
- pending: null,
- current: null
- };
- c8.expect = c8.entity === tls.ConnectionEnd.client ? SHE : CHE;
- c8.fragmented = null;
- c8.records = [];
- c8.open = false;
- c8.handshakes = 0;
- c8.handshaking = false;
- c8.isConnected = false;
- c8.fail = !(clearFail || typeof clearFail === "undefined");
- c8.input.clear();
- c8.tlsData.clear();
- c8.data.clear();
- c8.state.current = tls.createConnectionState(c8);
- };
- c8.reset();
- var _update = function(c9, record2) {
- var aligned = record2.type - tls.ContentType.change_cipher_spec;
- var handlers = ctTable[c9.entity][c9.expect];
- if (aligned in handlers) {
- handlers[aligned](c9, record2);
- } else {
- tls.handleUnexpected(c9, record2);
- }
- };
- var _readRecordHeader = function(c9) {
- var rval = 0;
- var b5 = c9.input;
- var len = b5.length();
- if (len < 5) {
- rval = 5 - len;
- } else {
- c9.record = {
- type: b5.getByte(),
- version: {
- major: b5.getByte(),
- minor: b5.getByte()
- },
- length: b5.getInt16(),
- fragment: forge.util.createBuffer(),
- ready: false
- };
- var compatibleVersion = c9.record.version.major === c9.version.major;
- if (compatibleVersion && c9.session && c9.session.version) {
- compatibleVersion = c9.record.version.minor === c9.version.minor;
- }
- if (!compatibleVersion) {
- c9.error(c9, {
- message: "Incompatible TLS version.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.protocol_version
- }
- });
- }
- }
- return rval;
- };
- var _readRecord = function(c9) {
- var rval = 0;
- var b5 = c9.input;
- var len = b5.length();
- if (len < c9.record.length) {
- rval = c9.record.length - len;
- } else {
- c9.record.fragment.putBytes(b5.getBytes(c9.record.length));
- b5.compact();
- var s4 = c9.state.current.read;
- if (s4.update(c9, c9.record)) {
- if (c9.fragmented !== null) {
- if (c9.fragmented.type === c9.record.type) {
- c9.fragmented.fragment.putBuffer(c9.record.fragment);
- c9.record = c9.fragmented;
- } else {
- c9.error(c9, {
- message: "Invalid fragmented record.",
- send: true,
- alert: {
- level: tls.Alert.Level.fatal,
- description: tls.Alert.Description.unexpected_message
- }
- });
- }
- }
- c9.record.ready = true;
- }
- }
- return rval;
- };
- c8.handshake = function(sessionId) {
- if (c8.entity !== tls.ConnectionEnd.client) {
- c8.error(c8, {
- message: "Cannot initiate handshake as a server.",
- fatal: false
- });
- } else if (c8.handshaking) {
- c8.error(c8, {
- message: "Handshake already in progress.",
- fatal: false
- });
- } else {
- if (c8.fail && !c8.open && c8.handshakes === 0) {
- c8.fail = false;
- }
- c8.handshaking = true;
- sessionId = sessionId || "";
- var session = null;
- if (sessionId.length > 0) {
- if (c8.sessionCache) {
- session = c8.sessionCache.getSession(sessionId);
- }
- if (session === null) {
- sessionId = "";
- }
- }
- if (sessionId.length === 0 && c8.sessionCache) {
- session = c8.sessionCache.getSession();
- if (session !== null) {
- sessionId = session.id;
- }
- }
- c8.session = {
- id: sessionId,
- version: null,
- cipherSuite: null,
- compressionMethod: null,
- serverCertificate: null,
- certificateRequest: null,
- clientCertificate: null,
- sp: {},
- md5: forge.md.md5.create(),
- sha1: forge.md.sha1.create()
- };
- if (session) {
- c8.version = session.version;
- c8.session.sp = session.sp;
- }
- c8.session.sp.client_random = tls.createRandom().getBytes();
- c8.open = true;
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.handshake,
- data: tls.createClientHello(c8)
- }));
- tls.flush(c8);
- }
- };
- c8.process = function(data) {
- var rval = 0;
- if (data) {
- c8.input.putBytes(data);
- }
- if (!c8.fail) {
- if (c8.record !== null && c8.record.ready && c8.record.fragment.isEmpty()) {
- c8.record = null;
- }
- if (c8.record === null) {
- rval = _readRecordHeader(c8);
- }
- if (!c8.fail && c8.record !== null && !c8.record.ready) {
- rval = _readRecord(c8);
- }
- if (!c8.fail && c8.record !== null && c8.record.ready) {
- _update(c8, c8.record);
- }
- }
- return rval;
- };
- c8.prepare = function(data) {
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.application_data,
- data: forge.util.createBuffer(data)
- }));
- return tls.flush(c8);
- };
- c8.prepareHeartbeatRequest = function(payload, payloadLength) {
- if (payload instanceof forge.util.ByteBuffer) {
- payload = payload.bytes();
- }
- if (typeof payloadLength === "undefined") {
- payloadLength = payload.length;
- }
- c8.expectedHeartbeatPayload = payload;
- tls.queue(c8, tls.createRecord(c8, {
- type: tls.ContentType.heartbeat,
- data: tls.createHeartbeat(tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength)
- }));
- return tls.flush(c8);
- };
- c8.close = function(clearFail) {
- if (!c8.fail && c8.sessionCache && c8.session) {
- var session = {
- id: c8.session.id,
- version: c8.session.version,
- sp: c8.session.sp
- };
- session.sp.keys = null;
- c8.sessionCache.setSession(session.id, session);
- }
- if (c8.open) {
- c8.open = false;
- c8.input.clear();
- if (c8.isConnected || c8.handshaking) {
- c8.isConnected = c8.handshaking = false;
- tls.queue(c8, tls.createAlert(c8, {
- level: tls.Alert.Level.warning,
- description: tls.Alert.Description.close_notify
- }));
- tls.flush(c8);
- }
- c8.closed(c8);
- }
- c8.reset(clearFail);
- };
- return c8;
- };
- module.exports = forge.tls = forge.tls || {};
- for (key2 in tls) {
- if (typeof tls[key2] !== "function") {
- forge.tls[key2] = tls[key2];
- }
- }
- var key2;
- forge.tls.prf_tls1 = prf_TLS1;
- forge.tls.hmac_sha1 = hmac_sha1;
- forge.tls.createSessionCache = tls.createSessionCache;
- forge.tls.createConnection = tls.createConnection;
-});
-
-// node_modules/node-forge/lib/aesCipherSuites.js
-var require_aesCipherSuites = __commonJS((exports, module) => {
- var forge = require_forge();
- require_aes();
- require_tls();
- var tls = module.exports = forge.tls;
- tls.CipherSuites["TLS_RSA_WITH_AES_128_CBC_SHA"] = {
- id: [0, 47],
- name: "TLS_RSA_WITH_AES_128_CBC_SHA",
- initSecurityParameters: function(sp) {
- sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;
- sp.cipher_type = tls.CipherType.block;
- sp.enc_key_length = 16;
- sp.block_length = 16;
- sp.fixed_iv_length = 16;
- sp.record_iv_length = 16;
- sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;
- sp.mac_length = 20;
- sp.mac_key_length = 20;
- },
- initConnectionState
- };
- tls.CipherSuites["TLS_RSA_WITH_AES_256_CBC_SHA"] = {
- id: [0, 53],
- name: "TLS_RSA_WITH_AES_256_CBC_SHA",
- initSecurityParameters: function(sp) {
- sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;
- sp.cipher_type = tls.CipherType.block;
- sp.enc_key_length = 32;
- sp.block_length = 16;
- sp.fixed_iv_length = 16;
- sp.record_iv_length = 16;
- sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;
- sp.mac_length = 20;
- sp.mac_key_length = 20;
- },
- initConnectionState
- };
- function initConnectionState(state3, c8, sp) {
- var client16 = c8.entity === forge.tls.ConnectionEnd.client;
- state3.read.cipherState = {
- init: false,
- cipher: forge.cipher.createDecipher("AES-CBC", client16 ? sp.keys.server_write_key : sp.keys.client_write_key),
- iv: client16 ? sp.keys.server_write_IV : sp.keys.client_write_IV
- };
- state3.write.cipherState = {
- init: false,
- cipher: forge.cipher.createCipher("AES-CBC", client16 ? sp.keys.client_write_key : sp.keys.server_write_key),
- iv: client16 ? sp.keys.client_write_IV : sp.keys.server_write_IV
- };
- state3.read.cipherFunction = decrypt_aes_cbc_sha1;
- state3.write.cipherFunction = encrypt_aes_cbc_sha1;
- state3.read.macLength = state3.write.macLength = sp.mac_length;
- state3.read.macFunction = state3.write.macFunction = tls.hmac_sha1;
- }
- function encrypt_aes_cbc_sha1(record2, s4) {
- var rval = false;
- var mac = s4.macFunction(s4.macKey, s4.sequenceNumber, record2);
- record2.fragment.putBytes(mac);
- s4.updateSequenceNumber();
- var iv;
- if (record2.version.minor === tls.Versions.TLS_1_0.minor) {
- iv = s4.cipherState.init ? null : s4.cipherState.iv;
- } else {
- iv = forge.random.getBytesSync(16);
- }
- s4.cipherState.init = true;
- var cipher = s4.cipherState.cipher;
- cipher.start({ iv });
- if (record2.version.minor >= tls.Versions.TLS_1_1.minor) {
- cipher.output.putBytes(iv);
- }
- cipher.update(record2.fragment);
- if (cipher.finish(encrypt_aes_cbc_sha1_padding)) {
- record2.fragment = cipher.output;
- record2.length = record2.fragment.length();
- rval = true;
- }
- return rval;
- }
- function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt2) {
- if (!decrypt2) {
- var padding = blockSize - input.length() % blockSize;
- input.fillWithByte(padding - 1, padding);
- }
- return true;
- }
- function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt2) {
- var rval = true;
- if (decrypt2) {
- var len = output.length();
- var paddingLength = output.last();
- for (var i6 = len - 1 - paddingLength;i6 < len - 1; ++i6) {
- rval = rval && output.at(i6) == paddingLength;
- }
- if (rval) {
- output.truncate(paddingLength + 1);
- }
- }
- return rval;
- }
- function decrypt_aes_cbc_sha1(record2, s4) {
- var rval = false;
- var iv;
- if (record2.version.minor === tls.Versions.TLS_1_0.minor) {
- iv = s4.cipherState.init ? null : s4.cipherState.iv;
- } else {
- iv = record2.fragment.getBytes(16);
- }
- s4.cipherState.init = true;
- var cipher = s4.cipherState.cipher;
- cipher.start({ iv });
- cipher.update(record2.fragment);
- rval = cipher.finish(decrypt_aes_cbc_sha1_padding);
- var macLen = s4.macLength;
- var mac = forge.random.getBytesSync(macLen);
- var len = cipher.output.length();
- if (len >= macLen) {
- record2.fragment = cipher.output.getBytes(len - macLen);
- mac = cipher.output.getBytes(macLen);
- } else {
- record2.fragment = cipher.output.getBytes();
- }
- record2.fragment = forge.util.createBuffer(record2.fragment);
- record2.length = record2.fragment.length();
- var mac2 = s4.macFunction(s4.macKey, s4.sequenceNumber, record2);
- s4.updateSequenceNumber();
- rval = compareMacs(s4.macKey, mac, mac2) && rval;
- return rval;
- }
- function compareMacs(key2, mac1, mac2) {
- var hmac2 = forge.hmac.create();
- hmac2.start("SHA1", key2);
- hmac2.update(mac1);
- mac1 = hmac2.digest().getBytes();
- hmac2.start(null, null);
- hmac2.update(mac2);
- mac2 = hmac2.digest().getBytes();
- return mac1 === mac2;
- }
-});
-
-// node_modules/node-forge/lib/sha512.js
-var require_sha512 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_md();
- require_util3();
- var sha512 = module.exports = forge.sha512 = forge.sha512 || {};
- forge.md.sha512 = forge.md.algorithms.sha512 = sha512;
- var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};
- sha384.create = function() {
- return sha512.create("SHA-384");
- };
- forge.md.sha384 = forge.md.algorithms.sha384 = sha384;
- forge.sha512.sha256 = forge.sha512.sha256 || {
- create: function() {
- return sha512.create("SHA-512/256");
- }
- };
- forge.md["sha512/256"] = forge.md.algorithms["sha512/256"] = forge.sha512.sha256;
- forge.sha512.sha224 = forge.sha512.sha224 || {
- create: function() {
- return sha512.create("SHA-512/224");
- }
- };
- forge.md["sha512/224"] = forge.md.algorithms["sha512/224"] = forge.sha512.sha224;
- sha512.create = function(algorithm) {
- if (!_initialized) {
- _init();
- }
- if (typeof algorithm === "undefined") {
- algorithm = "SHA-512";
- }
- if (!(algorithm in _states)) {
- throw new Error("Invalid SHA-512 algorithm: " + algorithm);
- }
- var _state = _states[algorithm];
- var _h3 = null;
- var _input = forge.util.createBuffer();
- var _w3 = new Array(80);
- for (var wi = 0;wi < 80; ++wi) {
- _w3[wi] = new Array(2);
- }
- var digestLength = 64;
- switch (algorithm) {
- case "SHA-384":
- digestLength = 48;
- break;
- case "SHA-512/256":
- digestLength = 32;
- break;
- case "SHA-512/224":
- digestLength = 28;
- break;
- }
- var md = {
- algorithm: algorithm.replace("-", "").toLowerCase(),
- blockLength: 128,
- digestLength,
- messageLength: 0,
- fullMessageLength: null,
- messageLengthSize: 16
- };
- md.start = function() {
- md.messageLength = 0;
- md.fullMessageLength = md.messageLength128 = [];
- var int32s = md.messageLengthSize / 4;
- for (var i6 = 0;i6 < int32s; ++i6) {
- md.fullMessageLength.push(0);
- }
- _input = forge.util.createBuffer();
- _h3 = new Array(_state.length);
- for (var i6 = 0;i6 < _state.length; ++i6) {
- _h3[i6] = _state[i6].slice(0);
- }
- return md;
- };
- md.start();
- md.update = function(msg, encoding) {
- if (encoding === "utf8") {
- msg = forge.util.encodeUtf8(msg);
- }
- var len = msg.length;
- md.messageLength += len;
- len = [len / 4294967296 >>> 0, len >>> 0];
- for (var i6 = md.fullMessageLength.length - 1;i6 >= 0; --i6) {
- md.fullMessageLength[i6] += len[1];
- len[1] = len[0] + (md.fullMessageLength[i6] / 4294967296 >>> 0);
- md.fullMessageLength[i6] = md.fullMessageLength[i6] >>> 0;
- len[0] = len[1] / 4294967296 >>> 0;
- }
- _input.putBytes(msg);
- _update(_h3, _w3, _input);
- if (_input.read > 2048 || _input.length() === 0) {
- _input.compact();
- }
- return md;
- };
- md.digest = function() {
- var finalBlock = forge.util.createBuffer();
- finalBlock.putBytes(_input.bytes());
- var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize;
- var overflow = remaining & md.blockLength - 1;
- finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
- var next, carry;
- var bits2 = md.fullMessageLength[0] * 8;
- for (var i6 = 0;i6 < md.fullMessageLength.length - 1; ++i6) {
- next = md.fullMessageLength[i6 + 1] * 8;
- carry = next / 4294967296 >>> 0;
- bits2 += carry;
- finalBlock.putInt32(bits2 >>> 0);
- bits2 = next >>> 0;
- }
- finalBlock.putInt32(bits2);
- var h5 = new Array(_h3.length);
- for (var i6 = 0;i6 < _h3.length; ++i6) {
- h5[i6] = _h3[i6].slice(0);
- }
- _update(h5, _w3, finalBlock);
- var rval = forge.util.createBuffer();
- var hlen;
- if (algorithm === "SHA-512") {
- hlen = h5.length;
- } else if (algorithm === "SHA-384") {
- hlen = h5.length - 2;
- } else {
- hlen = h5.length - 4;
- }
- for (var i6 = 0;i6 < hlen; ++i6) {
- rval.putInt32(h5[i6][0]);
- if (i6 !== hlen - 1 || algorithm !== "SHA-512/224") {
- rval.putInt32(h5[i6][1]);
- }
- }
- return rval;
- };
- return md;
- };
- var _padding = null;
- var _initialized = false;
- var _k3 = null;
- var _states = null;
- function _init() {
- _padding = String.fromCharCode(128);
- _padding += forge.util.fillString(String.fromCharCode(0), 128);
- _k3 = [
- [1116352408, 3609767458],
- [1899447441, 602891725],
- [3049323471, 3964484399],
- [3921009573, 2173295548],
- [961987163, 4081628472],
- [1508970993, 3053834265],
- [2453635748, 2937671579],
- [2870763221, 3664609560],
- [3624381080, 2734883394],
- [310598401, 1164996542],
- [607225278, 1323610764],
- [1426881987, 3590304994],
- [1925078388, 4068182383],
- [2162078206, 991336113],
- [2614888103, 633803317],
- [3248222580, 3479774868],
- [3835390401, 2666613458],
- [4022224774, 944711139],
- [264347078, 2341262773],
- [604807628, 2007800933],
- [770255983, 1495990901],
- [1249150122, 1856431235],
- [1555081692, 3175218132],
- [1996064986, 2198950837],
- [2554220882, 3999719339],
- [2821834349, 766784016],
- [2952996808, 2566594879],
- [3210313671, 3203337956],
- [3336571891, 1034457026],
- [3584528711, 2466948901],
- [113926993, 3758326383],
- [338241895, 168717936],
- [666307205, 1188179964],
- [773529912, 1546045734],
- [1294757372, 1522805485],
- [1396182291, 2643833823],
- [1695183700, 2343527390],
- [1986661051, 1014477480],
- [2177026350, 1206759142],
- [2456956037, 344077627],
- [2730485921, 1290863460],
- [2820302411, 3158454273],
- [3259730800, 3505952657],
- [3345764771, 106217008],
- [3516065817, 3606008344],
- [3600352804, 1432725776],
- [4094571909, 1467031594],
- [275423344, 851169720],
- [430227734, 3100823752],
- [506948616, 1363258195],
- [659060556, 3750685593],
- [883997877, 3785050280],
- [958139571, 3318307427],
- [1322822218, 3812723403],
- [1537002063, 2003034995],
- [1747873779, 3602036899],
- [1955562222, 1575990012],
- [2024104815, 1125592928],
- [2227730452, 2716904306],
- [2361852424, 442776044],
- [2428436474, 593698344],
- [2756734187, 3733110249],
- [3204031479, 2999351573],
- [3329325298, 3815920427],
- [3391569614, 3928383900],
- [3515267271, 566280711],
- [3940187606, 3454069534],
- [4118630271, 4000239992],
- [116418474, 1914138554],
- [174292421, 2731055270],
- [289380356, 3203993006],
- [460393269, 320620315],
- [685471733, 587496836],
- [852142971, 1086792851],
- [1017036298, 365543100],
- [1126000580, 2618297676],
- [1288033470, 3409855158],
- [1501505948, 4234509866],
- [1607167915, 987167468],
- [1816402316, 1246189591]
- ];
- _states = {};
- _states["SHA-512"] = [
- [1779033703, 4089235720],
- [3144134277, 2227873595],
- [1013904242, 4271175723],
- [2773480762, 1595750129],
- [1359893119, 2917565137],
- [2600822924, 725511199],
- [528734635, 4215389547],
- [1541459225, 327033209]
- ];
- _states["SHA-384"] = [
- [3418070365, 3238371032],
- [1654270250, 914150663],
- [2438529370, 812702999],
- [355462360, 4144912697],
- [1731405415, 4290775857],
- [2394180231, 1750603025],
- [3675008525, 1694076839],
- [1203062813, 3204075428]
- ];
- _states["SHA-512/256"] = [
- [573645204, 4230739756],
- [2673172387, 3360449730],
- [596883563, 1867755857],
- [2520282905, 1497426621],
- [2519219938, 2827943907],
- [3193839141, 1401305490],
- [721525244, 746961066],
- [246885852, 2177182882]
- ];
- _states["SHA-512/224"] = [
- [2352822216, 424955298],
- [1944164710, 2312950998],
- [502970286, 855612546],
- [1738396948, 1479516111],
- [258812777, 2077511080],
- [2011393907, 79989058],
- [1067287976, 1780299464],
- [286451373, 2446758561]
- ];
- _initialized = true;
- }
- function _update(s4, w2, bytes) {
- var t1_hi, t1_lo;
- var t2_hi, t2_lo;
- var s0_hi, s0_lo;
- var s1_hi, s1_lo;
- var ch_hi, ch_lo;
- var maj_hi, maj_lo;
- var a_hi, a_lo;
- var b_hi, b_lo;
- var c_hi, c_lo;
- var d_hi, d_lo;
- var e_hi, e_lo;
- var f_hi, f_lo;
- var g_hi, g_lo;
- var h_hi, h_lo;
- var i6, hi, lo, w22, w7, w15, w16;
- var len = bytes.length();
- while (len >= 128) {
- for (i6 = 0;i6 < 16; ++i6) {
- w2[i6][0] = bytes.getInt32() >>> 0;
- w2[i6][1] = bytes.getInt32() >>> 0;
- }
- for (;i6 < 80; ++i6) {
- w22 = w2[i6 - 2];
- hi = w22[0];
- lo = w22[1];
- t1_hi = ((hi >>> 19 | lo << 13) ^ (lo >>> 29 | hi << 3) ^ hi >>> 6) >>> 0;
- t1_lo = ((hi << 13 | lo >>> 19) ^ (lo << 3 | hi >>> 29) ^ (hi << 26 | lo >>> 6)) >>> 0;
- w15 = w2[i6 - 15];
- hi = w15[0];
- lo = w15[1];
- t2_hi = ((hi >>> 1 | lo << 31) ^ (hi >>> 8 | lo << 24) ^ hi >>> 7) >>> 0;
- t2_lo = ((hi << 31 | lo >>> 1) ^ (hi << 24 | lo >>> 8) ^ (hi << 25 | lo >>> 7)) >>> 0;
- w7 = w2[i6 - 7];
- w16 = w2[i6 - 16];
- lo = t1_lo + w7[1] + t2_lo + w16[1];
- w2[i6][0] = t1_hi + w7[0] + t2_hi + w16[0] + (lo / 4294967296 >>> 0) >>> 0;
- w2[i6][1] = lo >>> 0;
- }
- a_hi = s4[0][0];
- a_lo = s4[0][1];
- b_hi = s4[1][0];
- b_lo = s4[1][1];
- c_hi = s4[2][0];
- c_lo = s4[2][1];
- d_hi = s4[3][0];
- d_lo = s4[3][1];
- e_hi = s4[4][0];
- e_lo = s4[4][1];
- f_hi = s4[5][0];
- f_lo = s4[5][1];
- g_hi = s4[6][0];
- g_lo = s4[6][1];
- h_hi = s4[7][0];
- h_lo = s4[7][1];
- for (i6 = 0;i6 < 80; ++i6) {
- s1_hi = ((e_hi >>> 14 | e_lo << 18) ^ (e_hi >>> 18 | e_lo << 14) ^ (e_lo >>> 9 | e_hi << 23)) >>> 0;
- s1_lo = ((e_hi << 18 | e_lo >>> 14) ^ (e_hi << 14 | e_lo >>> 18) ^ (e_lo << 23 | e_hi >>> 9)) >>> 0;
- ch_hi = (g_hi ^ e_hi & (f_hi ^ g_hi)) >>> 0;
- ch_lo = (g_lo ^ e_lo & (f_lo ^ g_lo)) >>> 0;
- s0_hi = ((a_hi >>> 28 | a_lo << 4) ^ (a_lo >>> 2 | a_hi << 30) ^ (a_lo >>> 7 | a_hi << 25)) >>> 0;
- s0_lo = ((a_hi << 4 | a_lo >>> 28) ^ (a_lo << 30 | a_hi >>> 2) ^ (a_lo << 25 | a_hi >>> 7)) >>> 0;
- maj_hi = (a_hi & b_hi | c_hi & (a_hi ^ b_hi)) >>> 0;
- maj_lo = (a_lo & b_lo | c_lo & (a_lo ^ b_lo)) >>> 0;
- lo = h_lo + s1_lo + ch_lo + _k3[i6][1] + w2[i6][1];
- t1_hi = h_hi + s1_hi + ch_hi + _k3[i6][0] + w2[i6][0] + (lo / 4294967296 >>> 0) >>> 0;
- t1_lo = lo >>> 0;
- lo = s0_lo + maj_lo;
- t2_hi = s0_hi + maj_hi + (lo / 4294967296 >>> 0) >>> 0;
- t2_lo = lo >>> 0;
- h_hi = g_hi;
- h_lo = g_lo;
- g_hi = f_hi;
- g_lo = f_lo;
- f_hi = e_hi;
- f_lo = e_lo;
- lo = d_lo + t1_lo;
- e_hi = d_hi + t1_hi + (lo / 4294967296 >>> 0) >>> 0;
- e_lo = lo >>> 0;
- d_hi = c_hi;
- d_lo = c_lo;
- c_hi = b_hi;
- c_lo = b_lo;
- b_hi = a_hi;
- b_lo = a_lo;
- lo = t1_lo + t2_lo;
- a_hi = t1_hi + t2_hi + (lo / 4294967296 >>> 0) >>> 0;
- a_lo = lo >>> 0;
- }
- lo = s4[0][1] + a_lo;
- s4[0][0] = s4[0][0] + a_hi + (lo / 4294967296 >>> 0) >>> 0;
- s4[0][1] = lo >>> 0;
- lo = s4[1][1] + b_lo;
- s4[1][0] = s4[1][0] + b_hi + (lo / 4294967296 >>> 0) >>> 0;
- s4[1][1] = lo >>> 0;
- lo = s4[2][1] + c_lo;
- s4[2][0] = s4[2][0] + c_hi + (lo / 4294967296 >>> 0) >>> 0;
- s4[2][1] = lo >>> 0;
- lo = s4[3][1] + d_lo;
- s4[3][0] = s4[3][0] + d_hi + (lo / 4294967296 >>> 0) >>> 0;
- s4[3][1] = lo >>> 0;
- lo = s4[4][1] + e_lo;
- s4[4][0] = s4[4][0] + e_hi + (lo / 4294967296 >>> 0) >>> 0;
- s4[4][1] = lo >>> 0;
- lo = s4[5][1] + f_lo;
- s4[5][0] = s4[5][0] + f_hi + (lo / 4294967296 >>> 0) >>> 0;
- s4[5][1] = lo >>> 0;
- lo = s4[6][1] + g_lo;
- s4[6][0] = s4[6][0] + g_hi + (lo / 4294967296 >>> 0) >>> 0;
- s4[6][1] = lo >>> 0;
- lo = s4[7][1] + h_lo;
- s4[7][0] = s4[7][0] + h_hi + (lo / 4294967296 >>> 0) >>> 0;
- s4[7][1] = lo >>> 0;
- len -= 128;
- }
- }
-});
-
-// node_modules/node-forge/lib/asn1-validator.js
-var require_asn1_validator = __commonJS((exports) => {
- var forge = require_forge();
- require_asn1();
- var asn1 = forge.asn1;
- exports.privateKeyValidator = {
- name: "PrivateKeyInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "PrivateKeyInfo.version",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: "privateKeyVersion"
- }, {
- name: "PrivateKeyInfo.privateKeyAlgorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "AlgorithmIdentifier.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "privateKeyOid"
- }]
- }, {
- name: "PrivateKeyInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: "privateKey"
- }]
- };
- exports.publicKeyValidator = {
- name: "SubjectPublicKeyInfo",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: "subjectPublicKeyInfo",
- value: [
- {
- name: "SubjectPublicKeyInfo.AlgorithmIdentifier",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: "AlgorithmIdentifier.algorithm",
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: "publicKeyOid"
- }]
- },
- {
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.BITSTRING,
- constructed: false,
- composed: true,
- captureBitStringValue: "ed25519PublicKey"
- }
- ]
- };
-});
-
-// node_modules/node-forge/lib/ed25519.js
-var require_ed25519 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_jsbn();
- require_random();
- require_sha512();
- require_util3();
- var asn1Validator = require_asn1_validator();
- var publicKeyValidator = asn1Validator.publicKeyValidator;
- var privateKeyValidator = asn1Validator.privateKeyValidator;
- if (typeof BigInteger === "undefined") {
- BigInteger = forge.jsbn.BigInteger;
- }
- var BigInteger;
- var ByteBuffer = forge.util.ByteBuffer;
- var NativeBuffer = typeof Buffer === "undefined" ? Uint8Array : Buffer;
- forge.pki = forge.pki || {};
- module.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {};
- var ed25519 = forge.ed25519;
- ed25519.constants = {};
- ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32;
- ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64;
- ed25519.constants.SEED_BYTE_LENGTH = 32;
- ed25519.constants.SIGN_BYTE_LENGTH = 64;
- ed25519.constants.HASH_BYTE_LENGTH = 64;
- ed25519.generateKeyPair = function(options2) {
- options2 = options2 || {};
- var seed = options2.seed;
- if (seed === undefined) {
- seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH);
- } else if (typeof seed === "string") {
- if (seed.length !== ed25519.constants.SEED_BYTE_LENGTH) {
- throw new TypeError('"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + " bytes in length.");
- }
- } else if (!(seed instanceof Uint8Array)) {
- throw new TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.');
- }
- seed = messageToNativeBuffer({ message: seed, encoding: "binary" });
- var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);
- var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);
- for (var i6 = 0;i6 < 32; ++i6) {
- sk[i6] = seed[i6];
- }
- crypto_sign_keypair(pk, sk);
- return { publicKey: pk, privateKey: sk };
- };
- ed25519.privateKeyFromAsn1 = function(obj) {
- var capture = {};
- var errors8 = [];
- var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors8);
- if (!valid) {
- var error46 = new Error("Invalid Key.");
- error46.errors = errors8;
- throw error46;
- }
- var oid = forge.asn1.derToOid(capture.privateKeyOid);
- var ed25519Oid = forge.oids.EdDSA25519;
- if (oid !== ed25519Oid) {
- throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".');
- }
- var privateKey = capture.privateKey;
- var privateKeyBytes = messageToNativeBuffer({
- message: forge.asn1.fromDer(privateKey).value,
- encoding: "binary"
- });
- return { privateKeyBytes };
- };
- ed25519.publicKeyFromAsn1 = function(obj) {
- var capture = {};
- var errors8 = [];
- var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors8);
- if (!valid) {
- var error46 = new Error("Invalid Key.");
- error46.errors = errors8;
- throw error46;
- }
- var oid = forge.asn1.derToOid(capture.publicKeyOid);
- var ed25519Oid = forge.oids.EdDSA25519;
- if (oid !== ed25519Oid) {
- throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".');
- }
- var publicKeyBytes = capture.ed25519PublicKey;
- if (publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {
- throw new Error("Key length is invalid.");
- }
- return messageToNativeBuffer({
- message: publicKeyBytes,
- encoding: "binary"
- });
- };
- ed25519.publicKeyFromPrivateKey = function(options2) {
- options2 = options2 || {};
- var privateKey = messageToNativeBuffer({
- message: options2.privateKey,
- encoding: "binary"
- });
- if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {
- throw new TypeError('"options.privateKey" must have a byte length of ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);
- }
- var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);
- for (var i6 = 0;i6 < pk.length; ++i6) {
- pk[i6] = privateKey[32 + i6];
- }
- return pk;
- };
- ed25519.sign = function(options2) {
- options2 = options2 || {};
- var msg = messageToNativeBuffer(options2);
- var privateKey = messageToNativeBuffer({
- message: options2.privateKey,
- encoding: "binary"
- });
- if (privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) {
- var keyPair = ed25519.generateKeyPair({ seed: privateKey });
- privateKey = keyPair.privateKey;
- } else if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {
- throw new TypeError('"options.privateKey" must have a byte length of ' + ed25519.constants.SEED_BYTE_LENGTH + " or " + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);
- }
- var signedMsg = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);
- crypto_sign(signedMsg, msg, msg.length, privateKey);
- var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);
- for (var i6 = 0;i6 < sig.length; ++i6) {
- sig[i6] = signedMsg[i6];
- }
- return sig;
- };
- ed25519.verify = function(options2) {
- options2 = options2 || {};
- var msg = messageToNativeBuffer(options2);
- if (options2.signature === undefined) {
- throw new TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' + "ByteBuffer, or a binary string.");
- }
- var sig = messageToNativeBuffer({
- message: options2.signature,
- encoding: "binary"
- });
- if (sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) {
- throw new TypeError('"options.signature" must have a byte length of ' + ed25519.constants.SIGN_BYTE_LENGTH);
- }
- var publicKey = messageToNativeBuffer({
- message: options2.publicKey,
- encoding: "binary"
- });
- if (publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {
- throw new TypeError('"options.publicKey" must have a byte length of ' + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);
- }
- var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);
- var m4 = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);
- var i6;
- for (i6 = 0;i6 < ed25519.constants.SIGN_BYTE_LENGTH; ++i6) {
- sm[i6] = sig[i6];
- }
- for (i6 = 0;i6 < msg.length; ++i6) {
- sm[i6 + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i6];
- }
- return crypto_sign_open(m4, sm, sm.length, publicKey) >= 0;
- };
- function messageToNativeBuffer(options2) {
- var message = options2.message;
- if (message instanceof Uint8Array || message instanceof NativeBuffer) {
- return message;
- }
- var encoding = options2.encoding;
- if (message === undefined) {
- if (options2.md) {
- message = options2.md.digest().getBytes();
- encoding = "binary";
- } else {
- throw new TypeError('"options.message" or "options.md" not specified.');
- }
- }
- if (typeof message === "string" && !encoding) {
- throw new TypeError('"options.encoding" must be "binary" or "utf8".');
- }
- if (typeof message === "string") {
- if (typeof Buffer !== "undefined") {
- return Buffer.from(message, encoding);
- }
- message = new ByteBuffer(message, encoding);
- } else if (!(message instanceof ByteBuffer)) {
- throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ' + 'ByteBuffer, or a string with "options.encoding" specifying its ' + "encoding.");
- }
- var buffer = new NativeBuffer(message.length());
- for (var i6 = 0;i6 < buffer.length; ++i6) {
- buffer[i6] = message.at(i6);
- }
- return buffer;
- }
- var gf0 = gf();
- var gf1 = gf([1]);
- var D3 = gf([
- 30883,
- 4953,
- 19914,
- 30187,
- 55467,
- 16705,
- 2637,
- 112,
- 59544,
- 30585,
- 16505,
- 36039,
- 65139,
- 11119,
- 27886,
- 20995
- ]);
- var D22 = gf([
- 61785,
- 9906,
- 39828,
- 60374,
- 45398,
- 33411,
- 5274,
- 224,
- 53552,
- 61171,
- 33010,
- 6542,
- 64743,
- 22239,
- 55772,
- 9222
- ]);
- var X = gf([
- 54554,
- 36645,
- 11616,
- 51542,
- 42930,
- 38181,
- 51040,
- 26924,
- 56412,
- 64982,
- 57905,
- 49316,
- 21502,
- 52590,
- 14035,
- 8553
- ]);
- var Y = gf([
- 26200,
- 26214,
- 26214,
- 26214,
- 26214,
- 26214,
- 26214,
- 26214,
- 26214,
- 26214,
- 26214,
- 26214,
- 26214,
- 26214,
- 26214,
- 26214
- ]);
- var L2 = new Float64Array([
- 237,
- 211,
- 245,
- 92,
- 26,
- 99,
- 18,
- 88,
- 214,
- 156,
- 247,
- 162,
- 222,
- 249,
- 222,
- 20,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 16
- ]);
- var I3 = gf([
- 41136,
- 18958,
- 6951,
- 50414,
- 58488,
- 44335,
- 6150,
- 12099,
- 55207,
- 15867,
- 153,
- 11085,
- 57099,
- 20417,
- 9344,
- 11139
- ]);
- function sha512(msg, msgLen) {
- var md = forge.md.sha512.create();
- var buffer = new ByteBuffer(msg);
- md.update(buffer.getBytes(msgLen), "binary");
- var hash2 = md.digest().getBytes();
- if (typeof Buffer !== "undefined") {
- return Buffer.from(hash2, "binary");
- }
- var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);
- for (var i6 = 0;i6 < 64; ++i6) {
- out[i6] = hash2.charCodeAt(i6);
- }
- return out;
- }
- function crypto_sign_keypair(pk, sk) {
- var p4 = [gf(), gf(), gf(), gf()];
- var i6;
- var d4 = sha512(sk, 32);
- d4[0] &= 248;
- d4[31] &= 127;
- d4[31] |= 64;
- scalarbase(p4, d4);
- pack(pk, p4);
- for (i6 = 0;i6 < 32; ++i6) {
- sk[i6 + 32] = pk[i6];
- }
- return 0;
- }
- function crypto_sign(sm, m4, n5, sk) {
- var i6, j4, x4 = new Float64Array(64);
- var p4 = [gf(), gf(), gf(), gf()];
- var d4 = sha512(sk, 32);
- d4[0] &= 248;
- d4[31] &= 127;
- d4[31] |= 64;
- var smlen = n5 + 64;
- for (i6 = 0;i6 < n5; ++i6) {
- sm[64 + i6] = m4[i6];
- }
- for (i6 = 0;i6 < 32; ++i6) {
- sm[32 + i6] = d4[32 + i6];
- }
- var r4 = sha512(sm.subarray(32), n5 + 32);
- reduce(r4);
- scalarbase(p4, r4);
- pack(sm, p4);
- for (i6 = 32;i6 < 64; ++i6) {
- sm[i6] = sk[i6];
- }
- var h5 = sha512(sm, n5 + 64);
- reduce(h5);
- for (i6 = 32;i6 < 64; ++i6) {
- x4[i6] = 0;
- }
- for (i6 = 0;i6 < 32; ++i6) {
- x4[i6] = r4[i6];
- }
- for (i6 = 0;i6 < 32; ++i6) {
- for (j4 = 0;j4 < 32; j4++) {
- x4[i6 + j4] += h5[i6] * d4[j4];
- }
- }
- modL(sm.subarray(32), x4);
- return smlen;
- }
- function crypto_sign_open(m4, sm, n5, pk) {
- var i6, mlen;
- var t4 = new NativeBuffer(32);
- var p4 = [gf(), gf(), gf(), gf()], q4 = [gf(), gf(), gf(), gf()];
- mlen = -1;
- if (n5 < 64) {
- return -1;
- }
- if (unpackneg(q4, pk)) {
- return -1;
- }
- if (!_isCanonicalSignatureScalar(sm, 32)) {
- return -1;
- }
- for (i6 = 0;i6 < n5; ++i6) {
- m4[i6] = sm[i6];
- }
- for (i6 = 0;i6 < 32; ++i6) {
- m4[i6 + 32] = pk[i6];
- }
- var h5 = sha512(m4, n5);
- reduce(h5);
- scalarmult(p4, q4, h5);
- scalarbase(q4, sm.subarray(32));
- add(p4, q4);
- pack(t4, p4);
- n5 -= 64;
- if (crypto_verify_32(sm, 0, t4, 0)) {
- for (i6 = 0;i6 < n5; ++i6) {
- m4[i6] = 0;
- }
- return -1;
- }
- for (i6 = 0;i6 < n5; ++i6) {
- m4[i6] = sm[i6 + 64];
- }
- mlen = n5;
- return mlen;
- }
- function _isCanonicalSignatureScalar(bytes, offset) {
- var i6;
- for (i6 = 31;i6 >= 0; --i6) {
- if (bytes[offset + i6] < L2[i6]) {
- return true;
- }
- if (bytes[offset + i6] > L2[i6]) {
- return false;
- }
- }
- return false;
- }
- function modL(r4, x4) {
- var carry, i6, j4, k4;
- for (i6 = 63;i6 >= 32; --i6) {
- carry = 0;
- for (j4 = i6 - 32, k4 = i6 - 12;j4 < k4; ++j4) {
- x4[j4] += carry - 16 * x4[i6] * L2[j4 - (i6 - 32)];
- carry = x4[j4] + 128 >> 8;
- x4[j4] -= carry * 256;
- }
- x4[j4] += carry;
- x4[i6] = 0;
- }
- carry = 0;
- for (j4 = 0;j4 < 32; ++j4) {
- x4[j4] += carry - (x4[31] >> 4) * L2[j4];
- carry = x4[j4] >> 8;
- x4[j4] &= 255;
- }
- for (j4 = 0;j4 < 32; ++j4) {
- x4[j4] -= carry * L2[j4];
- }
- for (i6 = 0;i6 < 32; ++i6) {
- x4[i6 + 1] += x4[i6] >> 8;
- r4[i6] = x4[i6] & 255;
- }
- }
- function reduce(r4) {
- var x4 = new Float64Array(64);
- for (var i6 = 0;i6 < 64; ++i6) {
- x4[i6] = r4[i6];
- r4[i6] = 0;
- }
- modL(r4, x4);
- }
- function add(p4, q4) {
- var a5 = gf(), b5 = gf(), c8 = gf(), d4 = gf(), e4 = gf(), f4 = gf(), g4 = gf(), h5 = gf(), t4 = gf();
- Z(a5, p4[1], p4[0]);
- Z(t4, q4[1], q4[0]);
- M2(a5, a5, t4);
- A2(b5, p4[0], p4[1]);
- A2(t4, q4[0], q4[1]);
- M2(b5, b5, t4);
- M2(c8, p4[3], q4[3]);
- M2(c8, c8, D22);
- M2(d4, p4[2], q4[2]);
- A2(d4, d4, d4);
- Z(e4, b5, a5);
- Z(f4, d4, c8);
- A2(g4, d4, c8);
- A2(h5, b5, a5);
- M2(p4[0], e4, f4);
- M2(p4[1], h5, g4);
- M2(p4[2], g4, f4);
- M2(p4[3], e4, h5);
- }
- function cswap(p4, q4, b5) {
- for (var i6 = 0;i6 < 4; ++i6) {
- sel25519(p4[i6], q4[i6], b5);
- }
- }
- function pack(r4, p4) {
- var tx = gf(), ty = gf(), zi = gf();
- inv25519(zi, p4[2]);
- M2(tx, p4[0], zi);
- M2(ty, p4[1], zi);
- pack25519(r4, ty);
- r4[31] ^= par25519(tx) << 7;
- }
- function pack25519(o5, n5) {
- var i6, j4, b5;
- var m4 = gf(), t4 = gf();
- for (i6 = 0;i6 < 16; ++i6) {
- t4[i6] = n5[i6];
- }
- car25519(t4);
- car25519(t4);
- car25519(t4);
- for (j4 = 0;j4 < 2; ++j4) {
- m4[0] = t4[0] - 65517;
- for (i6 = 1;i6 < 15; ++i6) {
- m4[i6] = t4[i6] - 65535 - (m4[i6 - 1] >> 16 & 1);
- m4[i6 - 1] &= 65535;
- }
- m4[15] = t4[15] - 32767 - (m4[14] >> 16 & 1);
- b5 = m4[15] >> 16 & 1;
- m4[14] &= 65535;
- sel25519(t4, m4, 1 - b5);
- }
- for (i6 = 0;i6 < 16; i6++) {
- o5[2 * i6] = t4[i6] & 255;
- o5[2 * i6 + 1] = t4[i6] >> 8;
- }
- }
- function unpackneg(r4, p4) {
- var t4 = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf();
- set25519(r4[2], gf1);
- unpack25519(r4[1], p4);
- S(num, r4[1]);
- M2(den, num, D3);
- Z(num, num, r4[2]);
- A2(den, r4[2], den);
- S(den2, den);
- S(den4, den2);
- M2(den6, den4, den2);
- M2(t4, den6, num);
- M2(t4, t4, den);
- pow2523(t4, t4);
- M2(t4, t4, num);
- M2(t4, t4, den);
- M2(t4, t4, den);
- M2(r4[0], t4, den);
- S(chk, r4[0]);
- M2(chk, chk, den);
- if (neq25519(chk, num)) {
- M2(r4[0], r4[0], I3);
- }
- S(chk, r4[0]);
- M2(chk, chk, den);
- if (neq25519(chk, num)) {
- return -1;
- }
- if (par25519(r4[0]) === p4[31] >> 7) {
- Z(r4[0], gf0, r4[0]);
- }
- M2(r4[3], r4[0], r4[1]);
- return 0;
- }
- function unpack25519(o5, n5) {
- var i6;
- for (i6 = 0;i6 < 16; ++i6) {
- o5[i6] = n5[2 * i6] + (n5[2 * i6 + 1] << 8);
- }
- o5[15] &= 32767;
- }
- function pow2523(o5, i6) {
- var c8 = gf();
- var a5;
- for (a5 = 0;a5 < 16; ++a5) {
- c8[a5] = i6[a5];
- }
- for (a5 = 250;a5 >= 0; --a5) {
- S(c8, c8);
- if (a5 !== 1) {
- M2(c8, c8, i6);
- }
- }
- for (a5 = 0;a5 < 16; ++a5) {
- o5[a5] = c8[a5];
- }
- }
- function neq25519(a5, b5) {
- var c8 = new NativeBuffer(32);
- var d4 = new NativeBuffer(32);
- pack25519(c8, a5);
- pack25519(d4, b5);
- return crypto_verify_32(c8, 0, d4, 0);
- }
- function crypto_verify_32(x4, xi, y3, yi) {
- return vn(x4, xi, y3, yi, 32);
- }
- function vn(x4, xi, y3, yi, n5) {
- var i6, d4 = 0;
- for (i6 = 0;i6 < n5; ++i6) {
- d4 |= x4[xi + i6] ^ y3[yi + i6];
- }
- return (1 & d4 - 1 >>> 8) - 1;
- }
- function par25519(a5) {
- var d4 = new NativeBuffer(32);
- pack25519(d4, a5);
- return d4[0] & 1;
- }
- function scalarmult(p4, q4, s4) {
- var b5, i6;
- set25519(p4[0], gf0);
- set25519(p4[1], gf1);
- set25519(p4[2], gf1);
- set25519(p4[3], gf0);
- for (i6 = 255;i6 >= 0; --i6) {
- b5 = s4[i6 / 8 | 0] >> (i6 & 7) & 1;
- cswap(p4, q4, b5);
- add(q4, p4);
- add(p4, p4);
- cswap(p4, q4, b5);
- }
- }
- function scalarbase(p4, s4) {
- var q4 = [gf(), gf(), gf(), gf()];
- set25519(q4[0], X);
- set25519(q4[1], Y);
- set25519(q4[2], gf1);
- M2(q4[3], X, Y);
- scalarmult(p4, q4, s4);
- }
- function set25519(r4, a5) {
- var i6;
- for (i6 = 0;i6 < 16; i6++) {
- r4[i6] = a5[i6] | 0;
- }
- }
- function inv25519(o5, i6) {
- var c8 = gf();
- var a5;
- for (a5 = 0;a5 < 16; ++a5) {
- c8[a5] = i6[a5];
- }
- for (a5 = 253;a5 >= 0; --a5) {
- S(c8, c8);
- if (a5 !== 2 && a5 !== 4) {
- M2(c8, c8, i6);
- }
- }
- for (a5 = 0;a5 < 16; ++a5) {
- o5[a5] = c8[a5];
- }
- }
- function car25519(o5) {
- var i6, v6, c8 = 1;
- for (i6 = 0;i6 < 16; ++i6) {
- v6 = o5[i6] + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- o5[i6] = v6 - c8 * 65536;
- }
- o5[0] += c8 - 1 + 37 * (c8 - 1);
- }
- function sel25519(p4, q4, b5) {
- var t4, c8 = ~(b5 - 1);
- for (var i6 = 0;i6 < 16; ++i6) {
- t4 = c8 & (p4[i6] ^ q4[i6]);
- p4[i6] ^= t4;
- q4[i6] ^= t4;
- }
- }
- function gf(init) {
- var i6, r4 = new Float64Array(16);
- if (init) {
- for (i6 = 0;i6 < init.length; ++i6) {
- r4[i6] = init[i6];
- }
- }
- return r4;
- }
- function A2(o5, a5, b5) {
- for (var i6 = 0;i6 < 16; ++i6) {
- o5[i6] = a5[i6] + b5[i6];
- }
- }
- function Z(o5, a5, b5) {
- for (var i6 = 0;i6 < 16; ++i6) {
- o5[i6] = a5[i6] - b5[i6];
- }
- }
- function S(o5, a5) {
- M2(o5, a5, a5);
- }
- function M2(o5, a5, b5) {
- var v6, c8, t0 = 0, t1 = 0, t22 = 0, t32 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t222 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b5[0], b1 = b5[1], b23 = b5[2], b32 = b5[3], b42 = b5[4], b52 = b5[5], b6 = b5[6], b7 = b5[7], b82 = b5[8], b9 = b5[9], b10 = b5[10], b11 = b5[11], b12 = b5[12], b13 = b5[13], b14 = b5[14], b15 = b5[15];
- v6 = a5[0];
- t0 += v6 * b0;
- t1 += v6 * b1;
- t22 += v6 * b23;
- t32 += v6 * b32;
- t4 += v6 * b42;
- t5 += v6 * b52;
- t6 += v6 * b6;
- t7 += v6 * b7;
- t8 += v6 * b82;
- t9 += v6 * b9;
- t10 += v6 * b10;
- t11 += v6 * b11;
- t12 += v6 * b12;
- t13 += v6 * b13;
- t14 += v6 * b14;
- t15 += v6 * b15;
- v6 = a5[1];
- t1 += v6 * b0;
- t22 += v6 * b1;
- t32 += v6 * b23;
- t4 += v6 * b32;
- t5 += v6 * b42;
- t6 += v6 * b52;
- t7 += v6 * b6;
- t8 += v6 * b7;
- t9 += v6 * b82;
- t10 += v6 * b9;
- t11 += v6 * b10;
- t12 += v6 * b11;
- t13 += v6 * b12;
- t14 += v6 * b13;
- t15 += v6 * b14;
- t16 += v6 * b15;
- v6 = a5[2];
- t22 += v6 * b0;
- t32 += v6 * b1;
- t4 += v6 * b23;
- t5 += v6 * b32;
- t6 += v6 * b42;
- t7 += v6 * b52;
- t8 += v6 * b6;
- t9 += v6 * b7;
- t10 += v6 * b82;
- t11 += v6 * b9;
- t12 += v6 * b10;
- t13 += v6 * b11;
- t14 += v6 * b12;
- t15 += v6 * b13;
- t16 += v6 * b14;
- t17 += v6 * b15;
- v6 = a5[3];
- t32 += v6 * b0;
- t4 += v6 * b1;
- t5 += v6 * b23;
- t6 += v6 * b32;
- t7 += v6 * b42;
- t8 += v6 * b52;
- t9 += v6 * b6;
- t10 += v6 * b7;
- t11 += v6 * b82;
- t12 += v6 * b9;
- t13 += v6 * b10;
- t14 += v6 * b11;
- t15 += v6 * b12;
- t16 += v6 * b13;
- t17 += v6 * b14;
- t18 += v6 * b15;
- v6 = a5[4];
- t4 += v6 * b0;
- t5 += v6 * b1;
- t6 += v6 * b23;
- t7 += v6 * b32;
- t8 += v6 * b42;
- t9 += v6 * b52;
- t10 += v6 * b6;
- t11 += v6 * b7;
- t12 += v6 * b82;
- t13 += v6 * b9;
- t14 += v6 * b10;
- t15 += v6 * b11;
- t16 += v6 * b12;
- t17 += v6 * b13;
- t18 += v6 * b14;
- t19 += v6 * b15;
- v6 = a5[5];
- t5 += v6 * b0;
- t6 += v6 * b1;
- t7 += v6 * b23;
- t8 += v6 * b32;
- t9 += v6 * b42;
- t10 += v6 * b52;
- t11 += v6 * b6;
- t12 += v6 * b7;
- t13 += v6 * b82;
- t14 += v6 * b9;
- t15 += v6 * b10;
- t16 += v6 * b11;
- t17 += v6 * b12;
- t18 += v6 * b13;
- t19 += v6 * b14;
- t20 += v6 * b15;
- v6 = a5[6];
- t6 += v6 * b0;
- t7 += v6 * b1;
- t8 += v6 * b23;
- t9 += v6 * b32;
- t10 += v6 * b42;
- t11 += v6 * b52;
- t12 += v6 * b6;
- t13 += v6 * b7;
- t14 += v6 * b82;
- t15 += v6 * b9;
- t16 += v6 * b10;
- t17 += v6 * b11;
- t18 += v6 * b12;
- t19 += v6 * b13;
- t20 += v6 * b14;
- t21 += v6 * b15;
- v6 = a5[7];
- t7 += v6 * b0;
- t8 += v6 * b1;
- t9 += v6 * b23;
- t10 += v6 * b32;
- t11 += v6 * b42;
- t12 += v6 * b52;
- t13 += v6 * b6;
- t14 += v6 * b7;
- t15 += v6 * b82;
- t16 += v6 * b9;
- t17 += v6 * b10;
- t18 += v6 * b11;
- t19 += v6 * b12;
- t20 += v6 * b13;
- t21 += v6 * b14;
- t222 += v6 * b15;
- v6 = a5[8];
- t8 += v6 * b0;
- t9 += v6 * b1;
- t10 += v6 * b23;
- t11 += v6 * b32;
- t12 += v6 * b42;
- t13 += v6 * b52;
- t14 += v6 * b6;
- t15 += v6 * b7;
- t16 += v6 * b82;
- t17 += v6 * b9;
- t18 += v6 * b10;
- t19 += v6 * b11;
- t20 += v6 * b12;
- t21 += v6 * b13;
- t222 += v6 * b14;
- t23 += v6 * b15;
- v6 = a5[9];
- t9 += v6 * b0;
- t10 += v6 * b1;
- t11 += v6 * b23;
- t12 += v6 * b32;
- t13 += v6 * b42;
- t14 += v6 * b52;
- t15 += v6 * b6;
- t16 += v6 * b7;
- t17 += v6 * b82;
- t18 += v6 * b9;
- t19 += v6 * b10;
- t20 += v6 * b11;
- t21 += v6 * b12;
- t222 += v6 * b13;
- t23 += v6 * b14;
- t24 += v6 * b15;
- v6 = a5[10];
- t10 += v6 * b0;
- t11 += v6 * b1;
- t12 += v6 * b23;
- t13 += v6 * b32;
- t14 += v6 * b42;
- t15 += v6 * b52;
- t16 += v6 * b6;
- t17 += v6 * b7;
- t18 += v6 * b82;
- t19 += v6 * b9;
- t20 += v6 * b10;
- t21 += v6 * b11;
- t222 += v6 * b12;
- t23 += v6 * b13;
- t24 += v6 * b14;
- t25 += v6 * b15;
- v6 = a5[11];
- t11 += v6 * b0;
- t12 += v6 * b1;
- t13 += v6 * b23;
- t14 += v6 * b32;
- t15 += v6 * b42;
- t16 += v6 * b52;
- t17 += v6 * b6;
- t18 += v6 * b7;
- t19 += v6 * b82;
- t20 += v6 * b9;
- t21 += v6 * b10;
- t222 += v6 * b11;
- t23 += v6 * b12;
- t24 += v6 * b13;
- t25 += v6 * b14;
- t26 += v6 * b15;
- v6 = a5[12];
- t12 += v6 * b0;
- t13 += v6 * b1;
- t14 += v6 * b23;
- t15 += v6 * b32;
- t16 += v6 * b42;
- t17 += v6 * b52;
- t18 += v6 * b6;
- t19 += v6 * b7;
- t20 += v6 * b82;
- t21 += v6 * b9;
- t222 += v6 * b10;
- t23 += v6 * b11;
- t24 += v6 * b12;
- t25 += v6 * b13;
- t26 += v6 * b14;
- t27 += v6 * b15;
- v6 = a5[13];
- t13 += v6 * b0;
- t14 += v6 * b1;
- t15 += v6 * b23;
- t16 += v6 * b32;
- t17 += v6 * b42;
- t18 += v6 * b52;
- t19 += v6 * b6;
- t20 += v6 * b7;
- t21 += v6 * b82;
- t222 += v6 * b9;
- t23 += v6 * b10;
- t24 += v6 * b11;
- t25 += v6 * b12;
- t26 += v6 * b13;
- t27 += v6 * b14;
- t28 += v6 * b15;
- v6 = a5[14];
- t14 += v6 * b0;
- t15 += v6 * b1;
- t16 += v6 * b23;
- t17 += v6 * b32;
- t18 += v6 * b42;
- t19 += v6 * b52;
- t20 += v6 * b6;
- t21 += v6 * b7;
- t222 += v6 * b82;
- t23 += v6 * b9;
- t24 += v6 * b10;
- t25 += v6 * b11;
- t26 += v6 * b12;
- t27 += v6 * b13;
- t28 += v6 * b14;
- t29 += v6 * b15;
- v6 = a5[15];
- t15 += v6 * b0;
- t16 += v6 * b1;
- t17 += v6 * b23;
- t18 += v6 * b32;
- t19 += v6 * b42;
- t20 += v6 * b52;
- t21 += v6 * b6;
- t222 += v6 * b7;
- t23 += v6 * b82;
- t24 += v6 * b9;
- t25 += v6 * b10;
- t26 += v6 * b11;
- t27 += v6 * b12;
- t28 += v6 * b13;
- t29 += v6 * b14;
- t30 += v6 * b15;
- t0 += 38 * t16;
- t1 += 38 * t17;
- t22 += 38 * t18;
- t32 += 38 * t19;
- t4 += 38 * t20;
- t5 += 38 * t21;
- t6 += 38 * t222;
- t7 += 38 * t23;
- t8 += 38 * t24;
- t9 += 38 * t25;
- t10 += 38 * t26;
- t11 += 38 * t27;
- t12 += 38 * t28;
- t13 += 38 * t29;
- t14 += 38 * t30;
- c8 = 1;
- v6 = t0 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t0 = v6 - c8 * 65536;
- v6 = t1 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t1 = v6 - c8 * 65536;
- v6 = t22 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t22 = v6 - c8 * 65536;
- v6 = t32 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t32 = v6 - c8 * 65536;
- v6 = t4 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t4 = v6 - c8 * 65536;
- v6 = t5 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t5 = v6 - c8 * 65536;
- v6 = t6 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t6 = v6 - c8 * 65536;
- v6 = t7 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t7 = v6 - c8 * 65536;
- v6 = t8 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t8 = v6 - c8 * 65536;
- v6 = t9 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t9 = v6 - c8 * 65536;
- v6 = t10 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t10 = v6 - c8 * 65536;
- v6 = t11 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t11 = v6 - c8 * 65536;
- v6 = t12 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t12 = v6 - c8 * 65536;
- v6 = t13 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t13 = v6 - c8 * 65536;
- v6 = t14 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t14 = v6 - c8 * 65536;
- v6 = t15 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t15 = v6 - c8 * 65536;
- t0 += c8 - 1 + 37 * (c8 - 1);
- c8 = 1;
- v6 = t0 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t0 = v6 - c8 * 65536;
- v6 = t1 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t1 = v6 - c8 * 65536;
- v6 = t22 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t22 = v6 - c8 * 65536;
- v6 = t32 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t32 = v6 - c8 * 65536;
- v6 = t4 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t4 = v6 - c8 * 65536;
- v6 = t5 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t5 = v6 - c8 * 65536;
- v6 = t6 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t6 = v6 - c8 * 65536;
- v6 = t7 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t7 = v6 - c8 * 65536;
- v6 = t8 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t8 = v6 - c8 * 65536;
- v6 = t9 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t9 = v6 - c8 * 65536;
- v6 = t10 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t10 = v6 - c8 * 65536;
- v6 = t11 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t11 = v6 - c8 * 65536;
- v6 = t12 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t12 = v6 - c8 * 65536;
- v6 = t13 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t13 = v6 - c8 * 65536;
- v6 = t14 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t14 = v6 - c8 * 65536;
- v6 = t15 + c8 + 65535;
- c8 = Math.floor(v6 / 65536);
- t15 = v6 - c8 * 65536;
- t0 += c8 - 1 + 37 * (c8 - 1);
- o5[0] = t0;
- o5[1] = t1;
- o5[2] = t22;
- o5[3] = t32;
- o5[4] = t4;
- o5[5] = t5;
- o5[6] = t6;
- o5[7] = t7;
- o5[8] = t8;
- o5[9] = t9;
- o5[10] = t10;
- o5[11] = t11;
- o5[12] = t12;
- o5[13] = t13;
- o5[14] = t14;
- o5[15] = t15;
- }
-});
-
-// node_modules/node-forge/lib/kem.js
-var require_kem = __commonJS((exports, module) => {
- var forge = require_forge();
- require_util3();
- require_random();
- require_jsbn();
- module.exports = forge.kem = forge.kem || {};
- var BigInteger = forge.jsbn.BigInteger;
- forge.kem.rsa = {};
- forge.kem.rsa.create = function(kdf, options2) {
- options2 = options2 || {};
- var prng = options2.prng || forge.random;
- var kem = {};
- kem.encrypt = function(publicKey, keyLength) {
- var byteLength = Math.ceil(publicKey.n.bitLength() / 8);
- var r4;
- do {
- r4 = new BigInteger(forge.util.bytesToHex(prng.getBytesSync(byteLength)), 16).mod(publicKey.n);
- } while (r4.compareTo(BigInteger.ONE) <= 0);
- r4 = forge.util.hexToBytes(r4.toString(16));
- var zeros = byteLength - r4.length;
- if (zeros > 0) {
- r4 = forge.util.fillString(String.fromCharCode(0), zeros) + r4;
- }
- var encapsulation = publicKey.encrypt(r4, "NONE");
- var key2 = kdf.generate(r4, keyLength);
- return { encapsulation, key: key2 };
- };
- kem.decrypt = function(privateKey, encapsulation, keyLength) {
- var r4 = privateKey.decrypt(encapsulation, "NONE");
- return kdf.generate(r4, keyLength);
- };
- return kem;
- };
- forge.kem.kdf1 = function(md, digestLength) {
- _createKDF(this, md, 0, digestLength || md.digestLength);
- };
- forge.kem.kdf2 = function(md, digestLength) {
- _createKDF(this, md, 1, digestLength || md.digestLength);
- };
- function _createKDF(kdf, md, counterStart, digestLength) {
- kdf.generate = function(x4, length) {
- var key2 = new forge.util.ByteBuffer;
- var k4 = Math.ceil(length / digestLength) + counterStart;
- var c8 = new forge.util.ByteBuffer;
- for (var i6 = counterStart;i6 < k4; ++i6) {
- c8.putInt32(i6);
- md.start();
- md.update(x4 + c8.getBytes());
- var hash2 = md.digest();
- key2.putBytes(hash2.getBytes(digestLength));
- }
- key2.truncate(key2.length() - length);
- return key2.getBytes();
- };
- }
-});
-
-// node_modules/node-forge/lib/log.js
-var require_log = __commonJS((exports, module) => {
- var forge = require_forge();
- require_util3();
- module.exports = forge.log = forge.log || {};
- forge.log.levels = [
- "none",
- "error",
- "warning",
- "info",
- "debug",
- "verbose",
- "max"
- ];
- var sLevelInfo = {};
- var sLoggers = [];
- var sConsoleLogger = null;
- forge.log.LEVEL_LOCKED = 1 << 1;
- forge.log.NO_LEVEL_CHECK = 1 << 2;
- forge.log.INTERPOLATE = 1 << 3;
- for (i6 = 0;i6 < forge.log.levels.length; ++i6) {
- level = forge.log.levels[i6];
- sLevelInfo[level] = {
- index: i6,
- name: level.toUpperCase()
- };
- }
- var level;
- var i6;
- forge.log.logMessage = function(message) {
- var messageLevelIndex = sLevelInfo[message.level].index;
- for (var i7 = 0;i7 < sLoggers.length; ++i7) {
- var logger35 = sLoggers[i7];
- if (logger35.flags & forge.log.NO_LEVEL_CHECK) {
- logger35.f(message);
- } else {
- var loggerLevelIndex = sLevelInfo[logger35.level].index;
- if (messageLevelIndex <= loggerLevelIndex) {
- logger35.f(logger35, message);
- }
- }
- }
- };
- forge.log.prepareStandard = function(message) {
- if (!("standard" in message)) {
- message.standard = sLevelInfo[message.level].name + " [" + message.category + "] " + message.message;
- }
- };
- forge.log.prepareFull = function(message) {
- if (!("full" in message)) {
- var args = [message.message];
- args = args.concat([]);
- message.full = forge.util.format.apply(this, args);
- }
- };
- forge.log.prepareStandardFull = function(message) {
- if (!("standardFull" in message)) {
- forge.log.prepareStandard(message);
- message.standardFull = message.standard;
- }
- };
- if (true) {
- levels = ["error", "warning", "info", "debug", "verbose"];
- for (i6 = 0;i6 < levels.length; ++i6) {
- (function(level2) {
- forge.log[level2] = function(category, message) {
- var args = Array.prototype.slice.call(arguments).slice(2);
- var msg = {
- timestamp: new Date,
- level: level2,
- category,
- message,
- arguments: args
- };
- forge.log.logMessage(msg);
- };
- })(levels[i6]);
- }
- }
- var levels;
- var i6;
- forge.log.makeLogger = function(logFunction) {
- var logger35 = {
- flags: 0,
- f: logFunction
- };
- forge.log.setLevel(logger35, "none");
- return logger35;
- };
- forge.log.setLevel = function(logger35, level2) {
- var rval = false;
- if (logger35 && !(logger35.flags & forge.log.LEVEL_LOCKED)) {
- for (var i7 = 0;i7 < forge.log.levels.length; ++i7) {
- var aValidLevel = forge.log.levels[i7];
- if (level2 == aValidLevel) {
- logger35.level = level2;
- rval = true;
- break;
- }
- }
- }
- return rval;
- };
- forge.log.lock = function(logger35, lock3) {
- if (typeof lock3 === "undefined" || lock3) {
- logger35.flags |= forge.log.LEVEL_LOCKED;
- } else {
- logger35.flags &= ~forge.log.LEVEL_LOCKED;
- }
- };
- forge.log.addLogger = function(logger35) {
- sLoggers.push(logger35);
- };
- if (typeof console !== "undefined" && "log" in console) {
- if (console.error && console.warn && console.info && console.debug) {
- levelHandlers = {
- error: console.error,
- warning: console.warn,
- info: console.info,
- debug: console.debug,
- verbose: console.debug
- };
- f4 = function(logger35, message) {
- forge.log.prepareStandard(message);
- var handler = levelHandlers[message.level];
- var args = [message.standard];
- args = args.concat(message["arguments"].slice());
- handler.apply(console, args);
- };
- logger34 = forge.log.makeLogger(f4);
- } else {
- f4 = function(logger35, message) {
- forge.log.prepareStandardFull(message);
- console.log(message.standardFull);
- };
- logger34 = forge.log.makeLogger(f4);
- }
- forge.log.setLevel(logger34, "debug");
- forge.log.addLogger(logger34);
- sConsoleLogger = logger34;
- } else {
- console = {
- log: function() {}
- };
- }
- var logger34;
- var levelHandlers;
- var f4;
- if (sConsoleLogger !== null && typeof window !== "undefined" && window.location) {
- query = new URL(window.location.href).searchParams;
- if (query.has("console.level")) {
- forge.log.setLevel(sConsoleLogger, query.get("console.level").slice(-1)[0]);
- }
- if (query.has("console.lock")) {
- lock2 = query.get("console.lock").slice(-1)[0];
- if (lock2 == "true") {
- forge.log.lock(sConsoleLogger);
- }
- }
- }
- var query;
- var lock2;
- forge.log.consoleLogger = sConsoleLogger;
-});
-
-// node_modules/node-forge/lib/md.all.js
-var require_md_all = __commonJS((exports, module) => {
- module.exports = require_md();
- require_md53();
- require_sha13();
- require_sha256();
- require_sha512();
-});
-
-// node_modules/node-forge/lib/pkcs7.js
-var require_pkcs7 = __commonJS((exports, module) => {
- var forge = require_forge();
- require_aes();
- require_asn1();
- require_des();
- require_oids();
- require_pem();
- require_pkcs7asn1();
- require_random();
- require_util3();
- require_x509();
- var asn1 = forge.asn1;
- var p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};
- p7.messageFromPem = function(pem) {
- var msg = forge.pem.decode(pem)[0];
- if (msg.type !== "PKCS7") {
- var error46 = new Error("Could not convert PKCS#7 message from PEM; PEM " + 'header type is not "PKCS#7".');
- error46.headerType = msg.type;
- throw error46;
- }
- if (msg.procType && msg.procType.type === "ENCRYPTED") {
- throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");
- }
- var obj = asn1.fromDer(msg.body);
- return p7.messageFromAsn1(obj);
- };
- p7.messageToPem = function(msg, maxline) {
- var pemObj = {
- type: "PKCS7",
- body: asn1.toDer(msg.toAsn1()).getBytes()
- };
- return forge.pem.encode(pemObj, { maxline });
- };
- p7.messageFromAsn1 = function(obj) {
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors8)) {
- var error46 = new Error("Cannot read PKCS#7 message. " + "ASN.1 object is not an PKCS#7 ContentInfo.");
- error46.errors = errors8;
- throw error46;
- }
- var contentType = asn1.derToOid(capture.contentType);
- var msg;
- switch (contentType) {
- case forge.pki.oids.envelopedData:
- msg = p7.createEnvelopedData();
- break;
- case forge.pki.oids.encryptedData:
- msg = p7.createEncryptedData();
- break;
- case forge.pki.oids.signedData:
- msg = p7.createSignedData();
- break;
- default:
- throw new Error("Cannot read PKCS#7 message. ContentType with OID " + contentType + " is not (yet) supported.");
- }
- msg.fromAsn1(capture.content.value[0]);
- return msg;
- };
- p7.createSignedData = function() {
- var msg = null;
- msg = {
- type: forge.pki.oids.signedData,
- version: 1,
- certificates: [],
- crls: [],
- signers: [],
- digestAlgorithmIdentifiers: [],
- contentInfo: null,
- signerInfos: [],
- fromAsn1: function(obj) {
- _fromAsn1(msg, obj, p7.asn1.signedDataValidator);
- msg.certificates = [];
- msg.crls = [];
- msg.digestAlgorithmIdentifiers = [];
- msg.contentInfo = null;
- msg.signerInfos = [];
- if (msg.rawCapture.certificates) {
- var certs = msg.rawCapture.certificates.value;
- for (var i6 = 0;i6 < certs.length; ++i6) {
- msg.certificates.push(forge.pki.certificateFromAsn1(certs[i6]));
- }
- }
- },
- toAsn1: function() {
- if (!msg.contentInfo) {
- msg.sign();
- }
- var certs = [];
- for (var i6 = 0;i6 < msg.certificates.length; ++i6) {
- certs.push(forge.pki.certificateToAsn1(msg.certificates[i6]));
- }
- var crls = [];
- var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(msg.version).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, msg.digestAlgorithmIdentifiers),
- msg.contentInfo
- ])
- ]);
- if (certs.length > 0) {
- signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));
- }
- if (crls.length > 0) {
- signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));
- }
- signedData.value[0].value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, msg.signerInfos));
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(msg.type).getBytes()),
- signedData
- ]);
- },
- addSigner: function(signer) {
- var issuer = signer.issuer;
- var serialNumber = signer.serialNumber;
- if (signer.certificate) {
- var cert = signer.certificate;
- if (typeof cert === "string") {
- cert = forge.pki.certificateFromPem(cert);
- }
- issuer = cert.issuer.attributes;
- serialNumber = cert.serialNumber;
- }
- var key2 = signer.key;
- if (!key2) {
- throw new Error("Could not add PKCS#7 signer; no private key specified.");
- }
- if (typeof key2 === "string") {
- key2 = forge.pki.privateKeyFromPem(key2);
- }
- var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;
- switch (digestAlgorithm) {
- case forge.pki.oids.sha1:
- case forge.pki.oids.sha256:
- case forge.pki.oids.sha384:
- case forge.pki.oids.sha512:
- case forge.pki.oids.md5:
- break;
- default:
- throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: " + digestAlgorithm);
- }
- var authenticatedAttributes = signer.authenticatedAttributes || [];
- if (authenticatedAttributes.length > 0) {
- var contentType = false;
- var messageDigest = false;
- for (var i6 = 0;i6 < authenticatedAttributes.length; ++i6) {
- var attr = authenticatedAttributes[i6];
- if (!contentType && attr.type === forge.pki.oids.contentType) {
- contentType = true;
- if (messageDigest) {
- break;
- }
- continue;
- }
- if (!messageDigest && attr.type === forge.pki.oids.messageDigest) {
- messageDigest = true;
- if (contentType) {
- break;
- }
- continue;
- }
- }
- if (!contentType || !messageDigest) {
- throw new Error("Invalid signer.authenticatedAttributes. If " + "signer.authenticatedAttributes is specified, then it must " + "contain at least two attributes, PKCS #9 content-type and " + "PKCS #9 message-digest.");
- }
- }
- msg.signers.push({
- key: key2,
- version: 1,
- issuer,
- serialNumber,
- digestAlgorithm,
- signatureAlgorithm: forge.pki.oids.rsaEncryption,
- signature: null,
- authenticatedAttributes,
- unauthenticatedAttributes: []
- });
- },
- sign: function(options2) {
- options2 = options2 || {};
- if (typeof msg.content !== "object" || msg.contentInfo === null) {
- msg.contentInfo = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(forge.pki.oids.data).getBytes())
- ]);
- if ("content" in msg) {
- var content;
- if (msg.content instanceof forge.util.ByteBuffer) {
- content = msg.content.bytes();
- } else if (typeof msg.content === "string") {
- content = forge.util.encodeUtf8(msg.content);
- }
- if (options2.detached) {
- msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);
- } else {
- msg.contentInfo.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content)
- ]));
- }
- }
- }
- if (msg.signers.length === 0) {
- return;
- }
- var mds = addDigestAlgorithmIds();
- addSignerInfos(mds);
- },
- verify: function() {
- throw new Error("PKCS#7 signature verification not yet implemented.");
- },
- addCertificate: function(cert) {
- if (typeof cert === "string") {
- cert = forge.pki.certificateFromPem(cert);
- }
- msg.certificates.push(cert);
- },
- addCertificateRevokationList: function(crl) {
- throw new Error("PKCS#7 CRL support not yet implemented.");
- }
- };
- return msg;
- function addDigestAlgorithmIds() {
- var mds = {};
- for (var i6 = 0;i6 < msg.signers.length; ++i6) {
- var signer = msg.signers[i6];
- var oid = signer.digestAlgorithm;
- if (!(oid in mds)) {
- mds[oid] = forge.md[forge.pki.oids[oid]].create();
- }
- if (signer.authenticatedAttributes.length === 0) {
- signer.md = mds[oid];
- } else {
- signer.md = forge.md[forge.pki.oids[oid]].create();
- }
- }
- msg.digestAlgorithmIdentifiers = [];
- for (var oid in mds) {
- msg.digestAlgorithmIdentifiers.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oid).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
- ]));
- }
- return mds;
- }
- function addSignerInfos(mds) {
- var content;
- if (msg.detachedContent) {
- content = msg.detachedContent;
- } else {
- content = msg.contentInfo.value[1];
- content = content.value[0];
- }
- if (!content) {
- throw new Error("Could not sign PKCS#7 message; there is no content to sign.");
- }
- var contentType = asn1.derToOid(msg.contentInfo.value[0].value);
- var bytes = asn1.toDer(content);
- bytes.getByte();
- asn1.getBerValueLength(bytes);
- bytes = bytes.getBytes();
- for (var oid in mds) {
- mds[oid].start().update(bytes);
- }
- var signingTime = new Date;
- for (var i6 = 0;i6 < msg.signers.length; ++i6) {
- var signer = msg.signers[i6];
- if (signer.authenticatedAttributes.length === 0) {
- if (contentType !== forge.pki.oids.data) {
- throw new Error("Invalid signer; authenticatedAttributes must be present " + "when the ContentInfo content type is not PKCS#7 Data.");
- }
- } else {
- signer.authenticatedAttributesAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
- var attrsAsn1 = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);
- for (var ai = 0;ai < signer.authenticatedAttributes.length; ++ai) {
- var attr = signer.authenticatedAttributes[ai];
- if (attr.type === forge.pki.oids.messageDigest) {
- attr.value = mds[signer.digestAlgorithm].digest();
- } else if (attr.type === forge.pki.oids.signingTime) {
- if (!attr.value) {
- attr.value = signingTime;
- }
- }
- attrsAsn1.value.push(_attributeToAsn1(attr));
- signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));
- }
- bytes = asn1.toDer(attrsAsn1).getBytes();
- signer.md.start().update(bytes);
- }
- signer.signature = signer.key.sign(signer.md, "RSASSA-PKCS1-V1_5");
- }
- msg.signerInfos = _signersToAsn1(msg.signers);
- }
- };
- p7.createEncryptedData = function() {
- var msg = null;
- msg = {
- type: forge.pki.oids.encryptedData,
- version: 0,
- encryptedContent: {
- algorithm: forge.pki.oids["aes256-CBC"]
- },
- fromAsn1: function(obj) {
- _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);
- },
- decrypt: function(key2) {
- if (key2 !== undefined) {
- msg.encryptedContent.key = key2;
- }
- _decryptContent(msg);
- }
- };
- return msg;
- };
- p7.createEnvelopedData = function() {
- var msg = null;
- msg = {
- type: forge.pki.oids.envelopedData,
- version: 0,
- recipients: [],
- encryptedContent: {
- algorithm: forge.pki.oids["aes256-CBC"]
- },
- fromAsn1: function(obj) {
- var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);
- msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);
- },
- toAsn1: function() {
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(msg.type).getBytes()),
- asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(msg.version).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, _recipientsToAsn1(msg.recipients)),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, _encryptedContentToAsn1(msg.encryptedContent))
- ])
- ])
- ]);
- },
- findRecipient: function(cert) {
- var sAttr = cert.issuer.attributes;
- for (var i6 = 0;i6 < msg.recipients.length; ++i6) {
- var r4 = msg.recipients[i6];
- var rAttr = r4.issuer;
- if (r4.serialNumber !== cert.serialNumber) {
- continue;
- }
- if (rAttr.length !== sAttr.length) {
- continue;
- }
- var match = true;
- for (var j4 = 0;j4 < sAttr.length; ++j4) {
- if (rAttr[j4].type !== sAttr[j4].type || rAttr[j4].value !== sAttr[j4].value) {
- match = false;
- break;
- }
- }
- if (match) {
- return r4;
- }
- }
- return null;
- },
- decrypt: function(recipient, privKey) {
- if (msg.encryptedContent.key === undefined && recipient !== undefined && privKey !== undefined) {
- switch (recipient.encryptedContent.algorithm) {
- case forge.pki.oids.rsaEncryption:
- case forge.pki.oids.desCBC:
- var key2 = privKey.decrypt(recipient.encryptedContent.content);
- msg.encryptedContent.key = forge.util.createBuffer(key2);
- break;
- default:
- throw new Error("Unsupported asymmetric cipher, " + "OID " + recipient.encryptedContent.algorithm);
- }
- }
- _decryptContent(msg);
- },
- addRecipient: function(cert) {
- msg.recipients.push({
- version: 0,
- issuer: cert.issuer.attributes,
- serialNumber: cert.serialNumber,
- encryptedContent: {
- algorithm: forge.pki.oids.rsaEncryption,
- key: cert.publicKey
- }
- });
- },
- encrypt: function(key2, cipher) {
- if (msg.encryptedContent.content === undefined) {
- cipher = cipher || msg.encryptedContent.algorithm;
- key2 = key2 || msg.encryptedContent.key;
- var keyLen, ivLen, ciphFn;
- switch (cipher) {
- case forge.pki.oids["aes128-CBC"]:
- keyLen = 16;
- ivLen = 16;
- ciphFn = forge.aes.createEncryptionCipher;
- break;
- case forge.pki.oids["aes192-CBC"]:
- keyLen = 24;
- ivLen = 16;
- ciphFn = forge.aes.createEncryptionCipher;
- break;
- case forge.pki.oids["aes256-CBC"]:
- keyLen = 32;
- ivLen = 16;
- ciphFn = forge.aes.createEncryptionCipher;
- break;
- case forge.pki.oids["des-EDE3-CBC"]:
- keyLen = 24;
- ivLen = 8;
- ciphFn = forge.des.createEncryptionCipher;
- break;
- default:
- throw new Error("Unsupported symmetric cipher, OID " + cipher);
- }
- if (key2 === undefined) {
- key2 = forge.util.createBuffer(forge.random.getBytes(keyLen));
- } else if (key2.length() != keyLen) {
- throw new Error("Symmetric key has wrong length; " + "got " + key2.length() + " bytes, expected " + keyLen + ".");
- }
- msg.encryptedContent.algorithm = cipher;
- msg.encryptedContent.key = key2;
- msg.encryptedContent.parameter = forge.util.createBuffer(forge.random.getBytes(ivLen));
- var ciph = ciphFn(key2);
- ciph.start(msg.encryptedContent.parameter.copy());
- ciph.update(msg.content);
- if (!ciph.finish()) {
- throw new Error("Symmetric encryption failed.");
- }
- msg.encryptedContent.content = ciph.output;
- }
- for (var i6 = 0;i6 < msg.recipients.length; ++i6) {
- var recipient = msg.recipients[i6];
- if (recipient.encryptedContent.content !== undefined) {
- continue;
- }
- switch (recipient.encryptedContent.algorithm) {
- case forge.pki.oids.rsaEncryption:
- recipient.encryptedContent.content = recipient.encryptedContent.key.encrypt(msg.encryptedContent.key.data);
- break;
- default:
- throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm);
- }
- }
- }
- };
- return msg;
- };
- function _recipientFromAsn1(obj) {
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors8)) {
- var error46 = new Error("Cannot read PKCS#7 RecipientInfo. " + "ASN.1 object is not an PKCS#7 RecipientInfo.");
- error46.errors = errors8;
- throw error46;
- }
- return {
- version: capture.version.charCodeAt(0),
- issuer: forge.pki.RDNAttributesAsArray(capture.issuer),
- serialNumber: forge.util.createBuffer(capture.serial).toHex(),
- encryptedContent: {
- algorithm: asn1.derToOid(capture.encAlgorithm),
- parameter: capture.encParameter ? capture.encParameter.value : undefined,
- content: capture.encKey
- }
- };
- }
- function _recipientToAsn1(obj) {
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(obj.version).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(obj.serialNumber))
- ]),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
- ]),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.encryptedContent.content)
- ]);
- }
- function _recipientsFromAsn1(infos) {
- var ret = [];
- for (var i6 = 0;i6 < infos.length; ++i6) {
- ret.push(_recipientFromAsn1(infos[i6]));
- }
- return ret;
- }
- function _recipientsToAsn1(recipients) {
- var ret = [];
- for (var i6 = 0;i6 < recipients.length; ++i6) {
- ret.push(_recipientToAsn1(recipients[i6]));
- }
- return ret;
- }
- function _signerToAsn1(obj) {
- var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(obj.version).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(obj.serialNumber))
- ]),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.digestAlgorithm).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
- ])
- ]);
- if (obj.authenticatedAttributesAsn1) {
- rval.value.push(obj.authenticatedAttributesAsn1);
- }
- rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.signatureAlgorithm).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
- ]));
- rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));
- if (obj.unauthenticatedAttributes.length > 0) {
- var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);
- for (var i6 = 0;i6 < obj.unauthenticatedAttributes.length; ++i6) {
- var attr = obj.unauthenticatedAttributes[i6];
- attrsAsn1.values.push(_attributeToAsn1(attr));
- }
- rval.value.push(attrsAsn1);
- }
- return rval;
- }
- function _signersToAsn1(signers) {
- var ret = [];
- for (var i6 = 0;i6 < signers.length; ++i6) {
- ret.push(_signerToAsn1(signers[i6]));
- }
- return ret;
- }
- function _attributeToAsn1(attr) {
- var value;
- if (attr.type === forge.pki.oids.contentType) {
- value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.value).getBytes());
- } else if (attr.type === forge.pki.oids.messageDigest) {
- value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, attr.value.bytes());
- } else if (attr.type === forge.pki.oids.signingTime) {
- var jan_1_1950 = new Date("1950-01-01T00:00:00Z");
- var jan_1_2050 = new Date("2050-01-01T00:00:00Z");
- var date5 = attr.value;
- if (typeof date5 === "string") {
- var timestamp = Date.parse(date5);
- if (!isNaN(timestamp)) {
- date5 = new Date(timestamp);
- } else if (date5.length === 13) {
- date5 = asn1.utcTimeToDate(date5);
- } else {
- date5 = asn1.generalizedTimeToDate(date5);
- }
- }
- if (date5 >= jan_1_1950 && date5 < jan_1_2050) {
- value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, asn1.dateToUtcTime(date5));
- } else {
- value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, asn1.dateToGeneralizedTime(date5));
- }
- }
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.type).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
- value
- ])
- ]);
- }
- function _encryptedContentToAsn1(ec2) {
- return [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(forge.pki.oids.data).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(ec2.algorithm).getBytes()),
- !ec2.parameter ? undefined : asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ec2.parameter.getBytes())
- ]),
- asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ec2.content.getBytes())
- ])
- ];
- }
- function _fromAsn1(msg, obj, validator) {
- var capture = {};
- var errors8 = [];
- if (!asn1.validate(obj, validator, capture, errors8)) {
- var error46 = new Error("Cannot read PKCS#7 message. " + "ASN.1 object is not a supported PKCS#7 message.");
- error46.errors = error46;
- throw error46;
- }
- var contentType = asn1.derToOid(capture.contentType);
- if (contentType !== forge.pki.oids.data) {
- throw new Error("Unsupported PKCS#7 message. " + "Only wrapped ContentType Data supported.");
- }
- if (capture.encryptedContent) {
- var content = "";
- if (forge.util.isArray(capture.encryptedContent)) {
- for (var i6 = 0;i6 < capture.encryptedContent.length; ++i6) {
- if (capture.encryptedContent[i6].type !== asn1.Type.OCTETSTRING) {
- throw new Error("Malformed PKCS#7 message, expecting encrypted " + "content constructed of only OCTET STRING objects.");
- }
- content += capture.encryptedContent[i6].value;
- }
- } else {
- content = capture.encryptedContent;
- }
- msg.encryptedContent = {
- algorithm: asn1.derToOid(capture.encAlgorithm),
- parameter: forge.util.createBuffer(capture.encParameter.value),
- content: forge.util.createBuffer(content)
- };
- }
- if (capture.content) {
- var content = "";
- if (forge.util.isArray(capture.content)) {
- for (var i6 = 0;i6 < capture.content.length; ++i6) {
- if (capture.content[i6].type !== asn1.Type.OCTETSTRING) {
- throw new Error("Malformed PKCS#7 message, expecting " + "content constructed of only OCTET STRING objects.");
- }
- content += capture.content[i6].value;
- }
- } else {
- content = capture.content;
- }
- msg.content = forge.util.createBuffer(content);
- }
- msg.version = capture.version.charCodeAt(0);
- msg.rawCapture = capture;
- return capture;
- }
- function _decryptContent(msg) {
- if (msg.encryptedContent.key === undefined) {
- throw new Error("Symmetric key not available.");
- }
- if (msg.content === undefined) {
- var ciph;
- switch (msg.encryptedContent.algorithm) {
- case forge.pki.oids["aes128-CBC"]:
- case forge.pki.oids["aes192-CBC"]:
- case forge.pki.oids["aes256-CBC"]:
- ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);
- break;
- case forge.pki.oids["desCBC"]:
- case forge.pki.oids["des-EDE3-CBC"]:
- ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);
- break;
- default:
- throw new Error("Unsupported symmetric cipher, OID " + msg.encryptedContent.algorithm);
- }
- ciph.start(msg.encryptedContent.parameter);
- ciph.update(msg.encryptedContent.content);
- if (!ciph.finish()) {
- throw new Error("Symmetric decryption failed.");
- }
- msg.content = ciph.output;
- }
- }
-});
-
-// node_modules/node-forge/lib/ssh.js
-var require_ssh = __commonJS((exports, module) => {
- var forge = require_forge();
- require_aes();
- require_hmac();
- require_md53();
- require_sha13();
- require_util3();
- var ssh = module.exports = forge.ssh = forge.ssh || {};
- ssh.privateKeyToPutty = function(privateKey, passphrase, comment) {
- comment = comment || "";
- passphrase = passphrase || "";
- var algorithm = "ssh-rsa";
- var encryptionAlgorithm = passphrase === "" ? "none" : "aes256-cbc";
- var ppk = "PuTTY-User-Key-File-2: " + algorithm + `\r
-`;
- ppk += "Encryption: " + encryptionAlgorithm + `\r
-`;
- ppk += "Comment: " + comment + `\r
-`;
- var pubbuffer = forge.util.createBuffer();
- _addStringToBuffer(pubbuffer, algorithm);
- _addBigIntegerToBuffer(pubbuffer, privateKey.e);
- _addBigIntegerToBuffer(pubbuffer, privateKey.n);
- var pub = forge.util.encode64(pubbuffer.bytes(), 64);
- var length = Math.floor(pub.length / 66) + 1;
- ppk += "Public-Lines: " + length + `\r
-`;
- ppk += pub;
- var privbuffer = forge.util.createBuffer();
- _addBigIntegerToBuffer(privbuffer, privateKey.d);
- _addBigIntegerToBuffer(privbuffer, privateKey.p);
- _addBigIntegerToBuffer(privbuffer, privateKey.q);
- _addBigIntegerToBuffer(privbuffer, privateKey.qInv);
- var priv;
- if (!passphrase) {
- priv = forge.util.encode64(privbuffer.bytes(), 64);
- } else {
- var encLen = privbuffer.length() + 16 - 1;
- encLen -= encLen % 16;
- var padding = _sha1(privbuffer.bytes());
- padding.truncate(padding.length() - encLen + privbuffer.length());
- privbuffer.putBuffer(padding);
- var aeskey = forge.util.createBuffer();
- aeskey.putBuffer(_sha1("\x00\x00\x00\x00", passphrase));
- aeskey.putBuffer(_sha1("\x00\x00\x00\x01", passphrase));
- var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), "CBC");
- cipher.start(forge.util.createBuffer().fillWithByte(0, 16));
- cipher.update(privbuffer.copy());
- cipher.finish();
- var encrypted = cipher.output;
- encrypted.truncate(16);
- priv = forge.util.encode64(encrypted.bytes(), 64);
- }
- length = Math.floor(priv.length / 66) + 1;
- ppk += `\r
-Private-Lines: ` + length + `\r
-`;
- ppk += priv;
- var mackey = _sha1("putty-private-key-file-mac-key", passphrase);
- var macbuffer = forge.util.createBuffer();
- _addStringToBuffer(macbuffer, algorithm);
- _addStringToBuffer(macbuffer, encryptionAlgorithm);
- _addStringToBuffer(macbuffer, comment);
- macbuffer.putInt32(pubbuffer.length());
- macbuffer.putBuffer(pubbuffer);
- macbuffer.putInt32(privbuffer.length());
- macbuffer.putBuffer(privbuffer);
- var hmac2 = forge.hmac.create();
- hmac2.start("sha1", mackey);
- hmac2.update(macbuffer.bytes());
- ppk += `\r
-Private-MAC: ` + hmac2.digest().toHex() + `\r
-`;
- return ppk;
- };
- ssh.publicKeyToOpenSSH = function(key2, comment) {
- var type = "ssh-rsa";
- comment = comment || "";
- var buffer = forge.util.createBuffer();
- _addStringToBuffer(buffer, type);
- _addBigIntegerToBuffer(buffer, key2.e);
- _addBigIntegerToBuffer(buffer, key2.n);
- return type + " " + forge.util.encode64(buffer.bytes()) + " " + comment;
- };
- ssh.privateKeyToOpenSSH = function(privateKey, passphrase) {
- if (!passphrase) {
- return forge.pki.privateKeyToPem(privateKey);
- }
- return forge.pki.encryptRsaPrivateKey(privateKey, passphrase, { legacy: true, algorithm: "aes128" });
- };
- ssh.getPublicKeyFingerprint = function(key2, options2) {
- options2 = options2 || {};
- var md = options2.md || forge.md.md5.create();
- var type = "ssh-rsa";
- var buffer = forge.util.createBuffer();
- _addStringToBuffer(buffer, type);
- _addBigIntegerToBuffer(buffer, key2.e);
- _addBigIntegerToBuffer(buffer, key2.n);
- md.start();
- md.update(buffer.getBytes());
- var digest = md.digest();
- if (options2.encoding === "hex") {
- var hex = digest.toHex();
- if (options2.delimiter) {
- return hex.match(/.{2}/g).join(options2.delimiter);
- }
- return hex;
- } else if (options2.encoding === "binary") {
- return digest.getBytes();
- } else if (options2.encoding) {
- throw new Error('Unknown encoding "' + options2.encoding + '".');
- }
- return digest;
- };
- function _addBigIntegerToBuffer(buffer, val) {
- var hexVal = val.toString(16);
- if (hexVal[0] >= "8") {
- hexVal = "00" + hexVal;
- }
- var bytes = forge.util.hexToBytes(hexVal);
- buffer.putInt32(bytes.length);
- buffer.putBytes(bytes);
- }
- function _addStringToBuffer(buffer, val) {
- buffer.putInt32(val.length);
- buffer.putString(val);
- }
- function _sha1() {
- var sha = forge.md.sha1.create();
- var num = arguments.length;
- for (var i6 = 0;i6 < num; ++i6) {
- sha.update(arguments[i6]);
- }
- return sha.digest();
- }
-});
-
-// node_modules/node-forge/lib/index.js
-var require_lib5 = __commonJS((exports, module) => {
- module.exports = require_forge();
- require_aes();
- require_aesCipherSuites();
- require_asn1();
- require_cipher();
- require_des();
- require_ed25519();
- require_hmac();
- require_kem();
- require_log();
- require_md_all();
- require_mgf1();
- require_pbkdf2();
- require_pem();
- require_pkcs1();
- require_pkcs12();
- require_pkcs7();
- require_pki();
- require_prime();
- require_prng();
- require_pss();
- require_random();
- require_rc2();
- require_ssh();
- require_tls();
- require_util3();
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/node/sign.js
-import { execFile as execFile8 } from "child_process";
-import { readFileSync as readFileSync12, writeFileSync as writeFileSync4 } from "fs";
-import { mkdtemp, rm, writeFile as writeFile8 } from "fs/promises";
-import { tmpdir as tmpdir3 } from "os";
-import { join as join35 } from "path";
-import { promisify as promisify10 } from "util";
-function signMcpbFile(mcpbPath, certPath, keyPath, intermediates) {
- const mcpbContent = readFileSync12(mcpbPath);
- const certificatePem = readFileSync12(certPath, "utf-8");
- const privateKeyPem = readFileSync12(keyPath, "utf-8");
- const intermediatePems = intermediates?.map((path15) => readFileSync12(path15, "utf-8"));
- const p7 = import_node_forge.default.pkcs7.createSignedData();
- p7.content = import_node_forge.default.util.createBuffer(mcpbContent);
- const signingCert = import_node_forge.default.pki.certificateFromPem(certificatePem);
- const privateKey = import_node_forge.default.pki.privateKeyFromPem(privateKeyPem);
- p7.addCertificate(signingCert);
- if (intermediatePems) {
- for (const pem of intermediatePems) {
- p7.addCertificate(import_node_forge.default.pki.certificateFromPem(pem));
- }
- }
- p7.addSigner({
- key: privateKey,
- certificate: signingCert,
- digestAlgorithm: import_node_forge.default.pki.oids.sha256,
- authenticatedAttributes: [
- {
- type: import_node_forge.default.pki.oids.contentType,
- value: import_node_forge.default.pki.oids.data
- },
- {
- type: import_node_forge.default.pki.oids.messageDigest
- },
- {
- type: import_node_forge.default.pki.oids.signingTime
- }
- ]
- });
- p7.sign({ detached: true });
- const asn1 = import_node_forge.default.asn1.toDer(p7.toAsn1());
- const pkcs7Signature = Buffer.from(asn1.getBytes(), "binary");
- const signatureBlock = createSignatureBlock(pkcs7Signature);
- const signedContent = Buffer.concat([mcpbContent, signatureBlock]);
- writeFileSync4(mcpbPath, signedContent);
-}
-async function verifyMcpbFile(mcpbPath) {
- try {
- const fileContent = readFileSync12(mcpbPath);
- const { originalContent, pkcs7Signature } = extractSignatureBlock(fileContent);
- if (!pkcs7Signature) {
- return { status: "unsigned" };
- }
- const asn1 = import_node_forge.default.asn1.fromDer(pkcs7Signature.toString("binary"));
- const p7Message = import_node_forge.default.pkcs7.messageFromAsn1(asn1);
- if (!("type" in p7Message) || p7Message.type !== import_node_forge.default.pki.oids.signedData) {
- return { status: "unsigned" };
- }
- const p7 = p7Message;
- const certificates = p7.certificates || [];
- if (certificates.length === 0) {
- return { status: "unsigned" };
- }
- const signingCert = certificates[0];
- const contentBuf = import_node_forge.default.util.createBuffer(originalContent);
- try {
- p7.verify({ authenticatedAttributes: true });
- const signerInfos = p7.signerInfos;
- const signerInfo = signerInfos?.[0];
- if (signerInfo) {
- const md = import_node_forge.default.md.sha256.create();
- md.update(contentBuf.getBytes());
- const digest = md.digest().getBytes();
- let messageDigest = null;
- for (const attr of signerInfo.authenticatedAttributes) {
- if (attr.type === import_node_forge.default.pki.oids.messageDigest) {
- messageDigest = attr.value;
- break;
- }
- }
- if (!messageDigest || messageDigest !== digest) {
- return { status: "unsigned" };
- }
- }
- } catch (error46) {
- return { status: "unsigned" };
- }
- const certPem = import_node_forge.default.pki.certificateToPem(signingCert);
- const intermediatePems = certificates.slice(1).map((cert) => Buffer.from(import_node_forge.default.pki.certificateToPem(cert)));
- const chainValid = await verifyCertificateChain(Buffer.from(certPem), intermediatePems);
- if (!chainValid) {
- return { status: "unsigned" };
- }
- const isSelfSigned = signingCert.issuer.getField("CN")?.value === signingCert.subject.getField("CN")?.value;
- return {
- status: isSelfSigned ? "self-signed" : "signed",
- publisher: signingCert.subject.getField("CN")?.value || "Unknown",
- issuer: signingCert.issuer.getField("CN")?.value || "Unknown",
- valid_from: signingCert.validity.notBefore.toISOString(),
- valid_to: signingCert.validity.notAfter.toISOString(),
- fingerprint: import_node_forge.default.md.sha256.create().update(import_node_forge.default.asn1.toDer(import_node_forge.default.pki.certificateToAsn1(signingCert)).getBytes()).digest().toHex()
- };
- } catch (error46) {
- throw new Error(`Failed to verify MCPB file: ${error46}`);
- }
-}
-function createSignatureBlock(pkcs7Signature) {
- const parts = [];
- parts.push(Buffer.from(SIGNATURE_HEADER2, "utf-8"));
- const sigLengthBuffer = Buffer.alloc(4);
- sigLengthBuffer.writeUInt32LE(pkcs7Signature.length, 0);
- parts.push(sigLengthBuffer);
- parts.push(pkcs7Signature);
- parts.push(Buffer.from(SIGNATURE_FOOTER, "utf-8"));
- return Buffer.concat(parts);
-}
-function extractSignatureBlock(fileContent) {
- const footerBytes = Buffer.from(SIGNATURE_FOOTER, "utf-8");
- const footerIndex = fileContent.lastIndexOf(footerBytes);
- if (footerIndex === -1) {
- return { originalContent: fileContent };
- }
- const headerBytes = Buffer.from(SIGNATURE_HEADER2, "utf-8");
- let headerIndex = -1;
- for (let i6 = footerIndex - 1;i6 >= 0; i6--) {
- if (fileContent.slice(i6, i6 + headerBytes.length).equals(headerBytes)) {
- headerIndex = i6;
- break;
- }
- }
- if (headerIndex === -1) {
- return { originalContent: fileContent };
- }
- const originalContent = fileContent.slice(0, headerIndex);
- let offset = headerIndex + headerBytes.length;
- try {
- const sigLength = fileContent.readUInt32LE(offset);
- offset += 4;
- const pkcs7Signature = fileContent.slice(offset, offset + sigLength);
- return {
- originalContent,
- pkcs7Signature
- };
- } catch {
- return { originalContent: fileContent };
- }
-}
-async function verifyCertificateChain(certificate, intermediates) {
- let tempDir = null;
- try {
- tempDir = await mkdtemp(join35(tmpdir3(), "mcpb-verify-"));
- const certChainPath = join35(tempDir, "chain.pem");
- const certChain = [certificate, ...intermediates || []].join(`
-`);
- await writeFile8(certChainPath, certChain);
- if (process.platform === "darwin") {
- try {
- await execFileAsync6("security", [
- "verify-cert",
- "-c",
- certChainPath,
- "-p",
- "codeSign"
- ]);
- return true;
- } catch (error46) {
- return false;
- }
- } else if (process.platform === "win32") {
- const psCommand = `
- $ErrorActionPreference = 'Stop'
- $certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
- $certCollection.Import('${certChainPath}')
-
- if ($certCollection.Count -eq 0) {
- Write-Error 'No certificates found'
- exit 1
- }
-
- $leafCert = $certCollection[0]
- $chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
-
- # Enable revocation checking
- $chain.ChainPolicy.RevocationMode = 'Online'
- $chain.ChainPolicy.RevocationFlag = 'EntireChain'
- $chain.ChainPolicy.UrlRetrievalTimeout = New-TimeSpan -Seconds 30
-
- # Add code signing application policy
- $codeSignOid = New-Object System.Security.Cryptography.Oid '1.3.6.1.5.5.7.3.3'
- $chain.ChainPolicy.ApplicationPolicy.Add($codeSignOid)
-
- # Add intermediate certificates to extra store
- for ($i = 1; $i -lt $certCollection.Count; $i++) {
- [void]$chain.ChainPolicy.ExtraStore.Add($certCollection[$i])
- }
-
- # Build and validate chain
- $result = $chain.Build($leafCert)
-
- if ($result) {
- 'Valid'
- } else {
- $chain.ChainStatus | ForEach-Object {
- Write-Error "$($_.Status): $($_.StatusInformation)"
- }
- exit 1
- }
- `.trim();
- const { stdout } = await execFileAsync6("powershell.exe", [
- "-NoProfile",
- "-NonInteractive",
- "-Command",
- psCommand
- ]);
- return stdout.includes("Valid");
- } else {
- try {
- await execFileAsync6("openssl", [
- "verify",
- "-purpose",
- "codesigning",
- "-CApath",
- "/etc/ssl/certs",
- certChainPath
- ]);
- return true;
- } catch (error46) {
- return false;
- }
- }
- } catch (error46) {
- return false;
- } finally {
- if (tempDir) {
- try {
- await rm(tempDir, { recursive: true, force: true });
- } catch {}
- }
- }
-}
-function unsignMcpbFile(mcpbPath) {
- const fileContent = readFileSync12(mcpbPath);
- const { originalContent } = extractSignatureBlock(fileContent);
- writeFileSync4(mcpbPath, originalContent);
-}
-var import_node_forge, SIGNATURE_HEADER2 = "MCPB_SIG_V1", SIGNATURE_FOOTER = "MCPB_SIG_END", execFileAsync6;
-var init_sign = __esm(() => {
- import_node_forge = __toESM(require_lib5(), 1);
- execFileAsync6 = promisify10(execFile8);
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/shared/log.js
-function getLogger({ silent = false } = {}) {
- return {
- log: (...args) => {
- if (!silent) {
- console.log(...args);
- }
- },
- error: (...args) => {
- if (!silent) {
- console.error(...args);
- }
- },
- warn: (...args) => {
- if (!silent) {
- console.warn(...args);
- }
- },
- info: (...args) => {
- if (!silent) {
- console.info(...args);
- }
- },
- debug: (...args) => {
- if (!silent) {
- console.debug(...args);
- }
- }
- };
-}
-
-// node_modules/@anthropic-ai/mcpb/dist/cli/unpack.js
-import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync5 } from "fs";
-import { join as join36, resolve as resolve11, sep as sep8 } from "path";
-async function unpackExtension({ mcpbPath, outputDir, silent }) {
- const logger34 = getLogger({ silent });
- const resolvedMcpbPath = resolve11(mcpbPath);
- if (!existsSync5(resolvedMcpbPath)) {
- logger34.error(`ERROR: MCPB file not found: ${mcpbPath}`);
- return false;
- }
- const finalOutputDir = outputDir ? resolve11(outputDir) : process.cwd();
- if (!existsSync5(finalOutputDir)) {
- mkdirSync3(finalOutputDir, { recursive: true });
- }
- try {
- const fileContent = readFileSync13(resolvedMcpbPath);
- const { originalContent } = extractSignatureBlock(fileContent);
- const fileAttributes = new Map;
- const isUnix = process.platform !== "win32";
- if (isUnix) {
- const zipBuffer = originalContent;
- let eocdOffset = -1;
- for (let i6 = zipBuffer.length - 22;i6 >= 0; i6--) {
- if (zipBuffer.readUInt32LE(i6) === 101010256) {
- eocdOffset = i6;
- break;
- }
- }
- if (eocdOffset !== -1) {
- const centralDirOffset = zipBuffer.readUInt32LE(eocdOffset + 16);
- const centralDirEntries = zipBuffer.readUInt16LE(eocdOffset + 8);
- let offset = centralDirOffset;
- for (let i6 = 0;i6 < centralDirEntries; i6++) {
- if (zipBuffer.readUInt32LE(offset) === 33639248) {
- const externalAttrs = zipBuffer.readUInt32LE(offset + 38);
- const filenameLength = zipBuffer.readUInt16LE(offset + 28);
- const filename = zipBuffer.toString("utf8", offset + 46, offset + 46 + filenameLength);
- const mode = externalAttrs >> 16 & 511;
- if (mode > 0) {
- fileAttributes.set(filename, mode);
- }
- const extraFieldLength = zipBuffer.readUInt16LE(offset + 30);
- const commentLength = zipBuffer.readUInt16LE(offset + 32);
- offset += 46 + filenameLength + extraFieldLength + commentLength;
- } else {
- break;
- }
- }
- }
- }
- const decompressed = unzipSync(originalContent);
- for (const relativePath in decompressed) {
- if (Object.prototype.hasOwnProperty.call(decompressed, relativePath)) {
- const data = decompressed[relativePath];
- const fullPath = join36(finalOutputDir, relativePath);
- const normalizedPath = resolve11(fullPath);
- const normalizedOutputDir = resolve11(finalOutputDir);
- if (!normalizedPath.startsWith(normalizedOutputDir + sep8) && normalizedPath !== normalizedOutputDir) {
- throw new Error(`Path traversal attempt detected: ${relativePath}`);
- }
- const dir = join36(fullPath, "..");
- if (!existsSync5(dir)) {
- mkdirSync3(dir, { recursive: true });
- }
- writeFileSync5(fullPath, data);
- if (isUnix && fileAttributes.has(relativePath)) {
- try {
- const mode = fileAttributes.get(relativePath);
- if (mode !== undefined) {
- chmodSync3(fullPath, mode);
- }
- } catch (error46) {}
- }
- }
- }
- logger34.log(`Extension unpacked successfully to ${finalOutputDir}`);
- return true;
- } catch (error46) {
- if (error46 instanceof Error) {
- logger34.error(`ERROR: Failed to unpack extension: ${error46.message}`);
- } else {
- logger34.error("ERROR: An unknown error occurred during unpacking.");
- }
- return false;
- }
-}
-var init_unpack = __esm(() => {
- init_esm18();
- init_sign();
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/shared/manifestVersionResolve.js
-function getManifestVersionFromRawData(manifestData) {
- let manifestVersion = null;
- if (typeof manifestData === "object" && manifestData && "manifest_version" in manifestData && typeof manifestData.manifest_version === "string" && Object.keys(MANIFEST_SCHEMAS).includes(manifestData.manifest_version)) {
- manifestVersion = manifestData.manifest_version;
- } else if (typeof manifestData === "object" && manifestData && "dxt_version" in manifestData && typeof manifestData.dxt_version === "string" && Object.keys(MANIFEST_SCHEMAS).includes(manifestData.dxt_version)) {
- manifestVersion = manifestData.dxt_version;
- }
- return manifestVersion;
-}
-var init_manifestVersionResolve = __esm(() => {
- init_constants12();
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/node/validate.js
-import { existsSync as existsSync6, readFileSync as readFileSync14, statSync as statSync6 } from "fs";
-import * as fs9 from "fs/promises";
-import * as os5 from "os";
-import { dirname as dirname13, isAbsolute as isAbsolute5, join as join37, resolve as resolve12 } from "path";
-function isPNG(buffer) {
- return buffer.length >= 8 && buffer[0] === 137 && buffer[1] === 80 && buffer[2] === 78 && buffer[3] === 71 && buffer[4] === 13 && buffer[5] === 10 && buffer[6] === 26 && buffer[7] === 10;
-}
-function validateIcon(iconPath, baseDir) {
- const errors8 = [];
- const warnings = [];
- const isRemoteUrl = iconPath.startsWith("http://") || iconPath.startsWith("https://");
- const hasVariableSubstitution = iconPath.includes("${__dirname}");
- const isAbsolutePath = isAbsolute5(iconPath);
- if (isRemoteUrl) {
- warnings.push("Icon path uses a remote URL. " + 'Best practice for local MCP servers: Use local files like "icon": "icon.png" for maximum compatibility. ' + "Claude Desktop currently only supports local icon files in bundles.");
- }
- if (hasVariableSubstitution) {
- errors8.push("Icon path should not use ${__dirname} variable substitution. " + 'Use a simple relative path like "icon.png" instead of "${__dirname}/icon.png".');
- }
- if (isAbsolutePath) {
- errors8.push("Icon path must be relative to the bundle root, not an absolute path. " + `Found: "${iconPath}"`);
- }
- if (!isRemoteUrl && !isAbsolutePath && !hasVariableSubstitution) {
- const fullIconPath = join37(baseDir, iconPath);
- if (!existsSync6(fullIconPath)) {
- errors8.push(`Icon file not found at path: ${iconPath}`);
- } else {
- try {
- const buffer = readFileSync14(fullIconPath);
- if (!isPNG(buffer)) {
- errors8.push(`Icon file must be PNG format. The file at "${iconPath}" does not appear to be a valid PNG file.`);
- } else {
- warnings.push("Icon validation passed. Recommended size is 512\xD7512 pixels for best display in Claude Desktop.");
- }
- } catch (error46) {
- errors8.push(`Unable to read icon file at "${iconPath}": ${error46 instanceof Error ? error46.message : "Unknown error"}`);
- }
- }
- }
- return {
- valid: errors8.length === 0,
- errors: errors8,
- warnings
- };
-}
-function validateManifest(inputPath) {
- try {
- const resolvedPath5 = resolve12(inputPath);
- let manifestPath = resolvedPath5;
- if (existsSync6(resolvedPath5) && statSync6(resolvedPath5).isDirectory()) {
- manifestPath = join37(resolvedPath5, "manifest.json");
- }
- const manifestContent = readFileSync14(manifestPath, "utf-8");
- const manifestData = JSON.parse(manifestContent);
- const manifestVersion = getManifestVersionFromRawData(manifestData);
- if (!manifestVersion) {
- console.log("Unrecognized or unsupported manifest version");
- return false;
- }
- const result = MANIFEST_SCHEMAS[manifestVersion].safeParse(manifestData);
- if (result.success) {
- console.log("Manifest schema validation passes!");
- if (manifestData.icon) {
- const baseDir = dirname13(manifestPath);
- const iconValidation = validateIcon(manifestData.icon, baseDir);
- if (iconValidation.errors.length > 0) {
- console.log(`
-ERROR: Icon validation failed:
-`);
- iconValidation.errors.forEach((error46) => {
- console.log(` - ${error46}`);
- });
- return false;
- }
- if (iconValidation.warnings.length > 0) {
- console.log(`
-Icon validation warnings:
-`);
- iconValidation.warnings.forEach((warning) => {
- console.log(` - ${warning}`);
- });
- }
- }
- return true;
- } else {
- console.log(`ERROR: Manifest validation failed:
-`);
- result.error.issues.forEach((issue2) => {
- const path15 = issue2.path.join(".");
- console.log(` - ${path15 ? `${path15}: ` : ""}${issue2.message}`);
- });
- return false;
- }
- } catch (error46) {
- if (error46 instanceof Error) {
- if (error46.message.includes("ENOENT")) {
- console.error(`ERROR: File not found: ${inputPath}`);
- if (existsSync6(resolve12(inputPath)) && statSync6(resolve12(inputPath)).isDirectory()) {
- console.error(` (No manifest.json found in directory)`);
- }
- } else if (error46.message.includes("JSON")) {
- console.error(`ERROR: Invalid JSON in manifest file: ${error46.message}`);
- } else {
- console.error(`ERROR: Error reading manifest: ${error46.message}`);
- }
- } else {
- console.error("ERROR: Unknown error occurred");
- }
- return false;
- }
-}
-async function cleanMcpb(inputPath) {
- const tmpDir = await fs9.mkdtemp(resolve12(os5.tmpdir(), "mcpb-clean-"));
- const mcpbPath = resolve12(tmpDir, "in.mcpb");
- const unpackPath = resolve12(tmpDir, "out");
- console.log(" -- Cleaning MCPB...");
- try {
- await fs9.copyFile(inputPath, mcpbPath);
- console.log(" -- Unpacking MCPB...");
- await unpackExtension({ mcpbPath, silent: true, outputDir: unpackPath });
- const manifestPath = resolve12(unpackPath, "manifest.json");
- const originalManifest = await fs9.readFile(manifestPath, "utf-8");
- const manifestData = JSON.parse(originalManifest);
- const manifestVersion = getManifestVersionFromRawData(manifestData);
- if (!manifestVersion) {
- throw new Error("Unrecognized or unsupported manifest version");
- }
- const result = MANIFEST_SCHEMAS_LOOSE[manifestVersion].safeParse(manifestData);
- if (!result.success) {
- throw new Error(`Unrecoverable manifest issues, please run "mcpb validate"`);
- }
- await fs9.writeFile(manifestPath, JSON.stringify(result.data, null, 2));
- if (originalManifest.trim() !== (await fs9.readFile(manifestPath, "utf8")).trim()) {
- console.log(" -- Update manifest to be valid per MCPB schema");
- } else {
- console.log(" -- Manifest already valid per MCPB schema");
- }
- const nodeModulesPath = resolve12(unpackPath, "node_modules");
- if (existsSync6(nodeModulesPath)) {
- console.log(" -- node_modules found, deleting development dependencies");
- const destroyer = new import_galactus.DestroyerOfModules({
- rootDirectory: unpackPath
- });
- try {
- await destroyer.destroy();
- } catch (error46) {
- if (error46 instanceof Error && error46.message.includes("Failed to locate module")) {
- console.log(" -- Some modules already removed, skipping remaining cleanup");
- } else {
- throw error46;
- }
- }
- console.log(" -- Removed development dependencies from node_modules");
- } else {
- console.log(" -- No node_modules, not pruning");
- }
- const before = await fs9.stat(inputPath);
- const { packExtension } = await Promise.resolve().then(() => (init_pack(), exports_pack));
- await packExtension({
- extensionPath: unpackPath,
- outputPath: inputPath,
- silent: true
- });
- const after = await fs9.stat(inputPath);
- console.log(`
-Clean Complete:`);
- console.log("Before:", import_pretty_bytes.default(before.size));
- console.log("After:", import_pretty_bytes.default(after.size));
- } finally {
- await fs9.rm(tmpDir, {
- recursive: true,
- force: true
- });
- }
-}
-var import_galactus, import_pretty_bytes;
-var init_validate2 = __esm(() => {
- init_unpack();
- init_constants12();
- init_manifestVersionResolve();
- import_galactus = __toESM(require_lib4(), 1);
- import_pretty_bytes = __toESM(require_pretty_bytes(), 1);
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/cli/pack.js
-var exports_pack = {};
-__export(exports_pack, {
- packExtension: () => packExtension
-});
-import { createHash as createHash6 } from "crypto";
-import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync15, statSync as statSync7, writeFileSync as writeFileSync6 } from "fs";
-import { basename as basename6, join as join38, relative as relative4, resolve as resolve13, sep as sep9 } from "path";
-function formatFileSize2(bytes) {
- if (bytes < 1024) {
- return `${bytes}B`;
- } else if (bytes < 1024 * 1024) {
- return `${(bytes / 1024).toFixed(1)}kB`;
- } else {
- return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
- }
-}
-function sanitizeNameForFilename(name3) {
- return name3.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-_.]/g, "").replace(/-+/g, "-").replace(/^-+|-+$/g, "").substring(0, 100);
-}
-async function packExtension({ extensionPath, outputPath, silent }) {
- const resolvedPath5 = resolve13(extensionPath);
- const logger34 = getLogger({ silent });
- if (!existsSync7(resolvedPath5) || !statSync7(resolvedPath5).isDirectory()) {
- logger34.error(`ERROR: Directory not found: ${extensionPath}`);
- return false;
- }
- const manifestPath = join38(resolvedPath5, "manifest.json");
- if (!existsSync7(manifestPath)) {
- logger34.log(`No manifest.json found in ${extensionPath}`);
- const shouldInit = await esm_default2({
- message: "Would you like to create a manifest.json file?",
- default: true
- });
- if (shouldInit) {
- const success2 = await initExtension(extensionPath);
- if (!success2) {
- logger34.error("ERROR: Failed to create manifest");
- return false;
- }
- } else {
- logger34.error("ERROR: Cannot pack extension without manifest.json");
- return false;
- }
- }
- logger34.log("Validating manifest...");
- if (!validateManifest(manifestPath)) {
- logger34.error("ERROR: Cannot pack extension with invalid manifest");
- return false;
- }
- let manifest;
- try {
- const manifestContent = readFileSync15(manifestPath, "utf-8");
- const manifestData = JSON.parse(manifestContent);
- const manifestVersion = getManifestVersionFromRawData(manifestData);
- if (!manifestVersion) {
- logger34.error(`ERROR: Manifest version mismatch. Expected "${Object.keys(MANIFEST_SCHEMAS).join(" or ")}", found "${manifestVersion}"`);
- logger34.error(` Please update the manifest_version in your manifest.json to a supported version`);
- return false;
- }
- manifest = MANIFEST_SCHEMAS[manifestVersion].parse(manifestData);
- } catch (error46) {
- logger34.error("ERROR: Failed to parse manifest.json");
- if (error46 instanceof Error) {
- logger34.error(` ${error46.message}`);
- }
- return false;
- }
- const extensionName = basename6(resolvedPath5);
- const finalOutputPath = outputPath ? resolve13(outputPath) : resolve13(`${extensionName}.mcpb`);
- const outputDir = join38(finalOutputPath, "..");
- mkdirSync4(outputDir, { recursive: true });
- try {
- const mcpbIgnorePatterns = readMcpbIgnorePatterns(resolvedPath5);
- const { files, ignoredCount } = getAllFilesWithCount(resolvedPath5, resolvedPath5, {}, mcpbIgnorePatterns);
- logger34.log(`
-\uD83D\uDCE6 ${manifest.name}@${manifest.version}`);
- logger34.log("Archive Contents");
- const fileEntries = Object.entries(files);
- let totalUnpackedSize = 0;
- fileEntries.sort(([a5], [b5]) => a5.localeCompare(b5));
- const directoryGroups = new Map;
- const shallowFiles = [];
- for (const [filePath, fileData] of fileEntries) {
- const relPath = relative4(resolvedPath5, filePath);
- const content = fileData.data;
- const size = typeof content === "string" ? Buffer.byteLength(content, "utf8") : content.length;
- totalUnpackedSize += size;
- const parts = relPath.split(sep9);
- if (parts.length > 3) {
- const groupKey = parts.slice(0, 3).join("/");
- if (!directoryGroups.has(groupKey)) {
- directoryGroups.set(groupKey, { files: [], totalSize: 0 });
- }
- const group = directoryGroups.get(groupKey);
- group.files.push(relPath);
- group.totalSize += size;
- } else {
- shallowFiles.push({ path: relPath, size });
- }
- }
- for (const { path: path15, size } of shallowFiles) {
- logger34.log(`${formatFileSize2(size).padStart(8)} ${path15}`);
- }
- for (const [dir, { files: files2, totalSize }] of directoryGroups) {
- if (files2.length === 1) {
- const filePath = files2[0];
- const fileSize = totalSize;
- logger34.log(`${formatFileSize2(fileSize).padStart(8)} ${filePath}`);
- } else {
- logger34.log(`${formatFileSize2(totalSize).padStart(8)} ${dir}/ [and ${files2.length} more files]`);
- }
- }
- const zipFiles = {};
- const isUnix = process.platform !== "win32";
- for (const [filePath, fileData] of Object.entries(files)) {
- if (isUnix) {
- zipFiles[filePath] = [
- fileData.data,
- { os: 3, attrs: (fileData.mode & 511) << 16 }
- ];
- } else {
- zipFiles[filePath] = fileData.data;
- }
- }
- const zipData = zipSync(zipFiles, {
- level: 9,
- mtime: new Date
- });
- writeFileSync6(finalOutputPath, zipData);
- const shasum = createHash6("sha1").update(zipData).digest("hex");
- const sanitizedName = sanitizeNameForFilename(manifest.name);
- const archiveName = `${sanitizedName}-${manifest.version}.mcpb`;
- logger34.log(`
-Archive Details`);
- logger34.log(`name: ${manifest.name}`);
- logger34.log(`version: ${manifest.version}`);
- logger34.log(`filename: ${archiveName}`);
- logger34.log(`package size: ${formatFileSize2(zipData.length)}`);
- logger34.log(`unpacked size: ${formatFileSize2(totalUnpackedSize)}`);
- logger34.log(`shasum: ${shasum}`);
- logger34.log(`total files: ${fileEntries.length}`);
- logger34.log(`ignored (.mcpbignore) files: ${ignoredCount}`);
- logger34.log(`
-Output: ${finalOutputPath}`);
- return true;
- } catch (error46) {
- if (error46 instanceof Error) {
- logger34.error(`ERROR: Archive error: ${error46.message}`);
- } else {
- logger34.error("ERROR: Unknown archive error occurred");
- }
- return false;
- }
-}
-var init_pack = __esm(() => {
- init_esm17();
- init_esm18();
- init_files5();
- init_validate2();
- init_constants12();
- init_manifestVersionResolve();
- init_init();
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/schemas/any.js
-var exports_any = {};
-__export(exports_any, {
- McpbManifestSchema: () => McpbManifestSchema9
-});
-var McpbManifestSchema9;
-var init_any = __esm(() => {
- init_zod();
- init_0_1();
- init_0_2();
- init_0_3();
- init_0_4();
- McpbManifestSchema9 = unionType([
- McpbManifestSchema,
- McpbManifestSchema2,
- McpbManifestSchema3,
- McpbManifestSchema4
- ]);
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/schemas/index.js
-var VERSIONED_MANIFEST_SCHEMAS;
-var init_schemas4 = __esm(() => {
- init_0_1();
- init_0_2();
- init_0_3();
- init_0_4();
- init_0_1();
- init_0_2();
- init_0_3();
- init_0_4();
- init_any();
- VERSIONED_MANIFEST_SCHEMAS = {
- "0.1": McpbManifestSchema,
- "0.2": McpbManifestSchema2,
- "0.3": McpbManifestSchema3,
- "0.4": McpbManifestSchema4
- };
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/shared/common.js
-var McpbUserConfigValuesSchema, McpbSignatureInfoSchema;
-var init_common2 = __esm(() => {
- init_zod();
- McpbUserConfigValuesSchema = exports_external2.record(exports_external2.string(), exports_external2.union([exports_external2.string(), exports_external2.number(), exports_external2.boolean(), exports_external2.array(exports_external2.string())]));
- McpbSignatureInfoSchema = exports_external2.strictObject({
- status: exports_external2.enum(["signed", "unsigned", "self-signed"]),
- publisher: exports_external2.string().optional(),
- issuer: exports_external2.string().optional(),
- valid_from: exports_external2.string().optional(),
- valid_to: exports_external2.string().optional(),
- fingerprint: exports_external2.string().optional()
- });
-});
-
-// node_modules/@anthropic-ai/mcpb/dist/shared/config.js
-function replaceVariables(value, variables) {
- if (typeof value === "string") {
- let result = value;
- for (const [key2, replacement] of Object.entries(variables)) {
- const pattern = new RegExp(`\\$\\{${key2}\\}`, "g");
- if (result.match(pattern)) {
- if (Array.isArray(replacement)) {
- console.warn(`Cannot replace ${key2} with array value in string context: "${value}"`, { key: key2, replacement });
- } else {
- result = result.replace(pattern, replacement);
- }
- }
- }
- return result;
- } else if (Array.isArray(value)) {
- const result = [];
- for (const item of value) {
- if (typeof item === "string" && item.match(/^\$\{user_config\.[^}]+\}$/)) {
- const varName = item.match(/^\$\{([^}]+)\}$/)?.[1];
- if (varName && variables[varName]) {
- const replacement = variables[varName];
- if (Array.isArray(replacement)) {
- result.push(...replacement);
- } else {
- result.push(replacement);
- }
- } else {
- result.push(item);
- }
- } else {
- result.push(replaceVariables(item, variables));
- }
- }
- return result;
- } else if (value && typeof value === "object") {
- const result = {};
- for (const [key2, val] of Object.entries(value)) {
- result[key2] = replaceVariables(val, variables);
- }
- return result;
- }
- return value;
-}
-async function getMcpConfigForManifest(options2) {
- const { manifest, extensionPath, systemDirs, userConfig, pathSeparator, logger: logger34 } = options2;
- const baseConfig = manifest.server?.mcp_config;
- if (!baseConfig) {
- return;
- }
- let result = {
- ...baseConfig
- };
- if (baseConfig.platform_overrides) {
- if (process.platform in baseConfig.platform_overrides) {
- const platformConfig = baseConfig.platform_overrides[process.platform];
- result.command = platformConfig.command || result.command;
- result.args = platformConfig.args || result.args;
- result.env = platformConfig.env || result.env;
- }
- }
- if (hasRequiredConfigMissing({ manifest, userConfig })) {
- logger34?.warn(`Extension ${manifest.name} has missing required configuration, skipping MCP config`);
- return;
- }
- const variables = {
- __dirname: extensionPath,
- pathSeparator,
- "/": pathSeparator,
- ...systemDirs
- };
- const mergedConfig = {};
- if (manifest.user_config) {
- for (const [key2, configOption] of Object.entries(manifest.user_config)) {
- if (configOption.default !== undefined) {
- mergedConfig[key2] = configOption.default;
- }
- }
- }
- if (userConfig) {
- Object.assign(mergedConfig, userConfig);
- }
- for (const [key2, value] of Object.entries(mergedConfig)) {
- const userConfigKey = `user_config.${key2}`;
- if (Array.isArray(value)) {
- variables[userConfigKey] = value.map(String);
- } else if (typeof value === "boolean") {
- variables[userConfigKey] = value ? "true" : "false";
- } else {
- variables[userConfigKey] = String(value);
- }
- }
- result = replaceVariables(result, variables);
- return result;
-}
-function isInvalidSingleValue(value) {
- return value === undefined || value === null || value === "";
-}
-function hasRequiredConfigMissing({ manifest, userConfig }) {
- if (!manifest.user_config) {
- return false;
- }
- const config8 = userConfig || {};
- for (const [key2, configOption] of Object.entries(manifest.user_config)) {
- if (configOption.required) {
- const value = config8[key2];
- if (isInvalidSingleValue(value) || Array.isArray(value) && (value.length === 0 || value.some(isInvalidSingleValue))) {
- return true;
- }
- }
- }
- return false;
-}
-
-// node_modules/@anthropic-ai/mcpb/dist/types.js
-var init_types15 = () => {};
-
-// node_modules/@anthropic-ai/mcpb/dist/index.js
-var exports_dist2 = {};
-__export(exports_dist2, {
- verifyMcpbFile: () => verifyMcpbFile,
- verifyCertificateChain: () => verifyCertificateChain,
- validateManifest: () => validateManifest,
- vAny: () => exports_any,
- v0_4: () => exports_0_4,
- v0_3: () => exports_0_3,
- v0_2: () => exports_0_2,
- v0_1: () => exports_0_1,
- unsignMcpbFile: () => unsignMcpbFile,
- unpackExtension: () => unpackExtension,
- signMcpbFile: () => signMcpbFile,
- shouldExclude: () => shouldExclude,
- replaceVariables: () => replaceVariables,
- readPackageJson: () => readPackageJson,
- readMcpbIgnorePatterns: () => readMcpbIgnorePatterns,
- promptVisualAssets: () => promptVisualAssets,
- promptUserConfig: () => promptUserConfig,
- promptUrls: () => promptUrls,
- promptTools: () => promptTools,
- promptServerConfig: () => promptServerConfig,
- promptPrompts: () => promptPrompts,
- promptOptionalFields: () => promptOptionalFields,
- promptLongDescription: () => promptLongDescription,
- promptLocalization: () => promptLocalization,
- promptCompatibility: () => promptCompatibility,
- promptBasicInfo: () => promptBasicInfo,
- promptAuthorInfo: () => promptAuthorInfo,
- printNextSteps: () => printNextSteps,
- packExtension: () => packExtension,
- initExtension: () => initExtension,
- hasRequiredConfigMissing: () => hasRequiredConfigMissing,
- getMcpConfigForManifest: () => getMcpConfigForManifest,
- getDefaultServerConfig: () => getDefaultServerConfig,
- getDefaultRepositoryUrl: () => getDefaultRepositoryUrl,
- getDefaultOptionalFields: () => getDefaultOptionalFields,
- getDefaultEntryPoint: () => getDefaultEntryPoint,
- getDefaultBasicInfo: () => getDefaultBasicInfo,
- getDefaultAuthorUrl: () => getDefaultAuthorUrl,
- getDefaultAuthorName: () => getDefaultAuthorName,
- getDefaultAuthorInfo: () => getDefaultAuthorInfo,
- getDefaultAuthorEmail: () => getDefaultAuthorEmail,
- getAllFilesWithCount: () => getAllFilesWithCount,
- getAllFiles: () => getAllFiles,
- extractSignatureBlock: () => extractSignatureBlock,
- createMcpConfig: () => createMcpConfig,
- cleanMcpb: () => cleanMcpb,
- buildManifest: () => buildManifest,
- VERSIONED_MANIFEST_SCHEMAS: () => VERSIONED_MANIFEST_SCHEMAS,
- McpbUserConfigValuesSchema: () => McpbUserConfigValuesSchema,
- McpbSignatureInfoSchema: () => McpbSignatureInfoSchema,
- MANIFEST_SCHEMAS_LOOSE: () => MANIFEST_SCHEMAS_LOOSE,
- MANIFEST_SCHEMAS: () => MANIFEST_SCHEMAS,
- LATEST_MANIFEST_VERSION: () => LATEST_MANIFEST_VERSION,
- EXCLUDE_PATTERNS: () => EXCLUDE_PATTERNS,
- DEFAULT_MANIFEST_VERSION: () => DEFAULT_MANIFEST_VERSION
-});
-var init_dist5 = __esm(() => {
- init_init();
- init_pack();
- init_unpack();
- init_files5();
- init_sign();
- init_validate2();
- init_schemas4();
- init_common2();
- init_constants12();
- init_types15();
-});
-
-// src/utils/dxt/helpers.ts
-async function validateManifest2(manifestJson) {
- const { McpbManifestSchema: McpbManifestSchema10 } = await Promise.resolve().then(() => (init_dist5(), exports_dist2));
- const parseResult = McpbManifestSchema10.safeParse(manifestJson);
- if (!parseResult.success) {
- const errors8 = parseResult.error.flatten();
- const errorMessages = [
- ...Object.entries(errors8.fieldErrors).map(([field, errs]) => `${field}: ${errs?.join(", ")}`),
- ...errors8.formErrors || []
- ].filter(Boolean).join("; ");
- throw new Error(`Invalid manifest: ${errorMessages}`);
- }
- return parseResult.data;
-}
-async function parseAndValidateManifestFromText(manifestText) {
- let manifestJson;
- try {
- manifestJson = jsonParse(manifestText);
- } catch (error46) {
- throw new Error(`Invalid JSON in manifest.json: ${errorMessage(error46)}`);
- }
- return validateManifest2(manifestJson);
-}
-async function parseAndValidateManifestFromBytes(manifestData) {
- const manifestText = new TextDecoder().decode(manifestData);
- return parseAndValidateManifestFromText(manifestText);
-}
-var init_helpers2 = __esm(() => {
- init_errors();
- init_slowOperations();
-});
-
-// src/utils/dxt/zip.ts
-import { isAbsolute as isAbsolute6, normalize as normalize5 } from "path";
-function isPathSafe(filePath) {
- if (containsPathTraversal(filePath)) {
- return false;
- }
- const normalized = normalize5(filePath);
- if (isAbsolute6(normalized)) {
- return false;
- }
- return true;
-}
-function validateZipFile(file2, state3) {
- state3.fileCount++;
- let error46;
- if (state3.fileCount > LIMITS.MAX_FILE_COUNT) {
- error46 = `Archive contains too many files: ${state3.fileCount} (max: ${LIMITS.MAX_FILE_COUNT})`;
- }
- if (!isPathSafe(file2.name)) {
- error46 = `Unsafe file path detected: "${file2.name}". Path traversal or absolute paths are not allowed.`;
- }
- const fileSize = file2.originalSize || 0;
- if (fileSize > LIMITS.MAX_FILE_SIZE) {
- error46 = `File "${file2.name}" is too large: ${Math.round(fileSize / 1024 / 1024)}MB (max: ${Math.round(LIMITS.MAX_FILE_SIZE / 1024 / 1024)}MB)`;
- }
- state3.totalUncompressedSize += fileSize;
- if (state3.totalUncompressedSize > LIMITS.MAX_TOTAL_SIZE) {
- error46 = `Archive total size is too large: ${Math.round(state3.totalUncompressedSize / 1024 / 1024)}MB (max: ${Math.round(LIMITS.MAX_TOTAL_SIZE / 1024 / 1024)}MB)`;
- }
- const currentRatio = state3.totalUncompressedSize / state3.compressedSize;
- if (currentRatio > LIMITS.MAX_COMPRESSION_RATIO) {
- error46 = `Suspicious compression ratio detected: ${currentRatio.toFixed(1)}:1 (max: ${LIMITS.MAX_COMPRESSION_RATIO}:1). This may be a zip bomb.`;
- }
- return error46 ? { isValid: false, error: error46 } : { isValid: true };
-}
-async function unzipFile(zipData) {
- const { unzipSync: unzipSync2 } = await Promise.resolve().then(() => (init_esm18(), exports_esm2));
- const compressedSize = zipData.length;
- const state3 = {
- fileCount: 0,
- totalUncompressedSize: 0,
- compressedSize,
- errors: []
- };
- const result = unzipSync2(new Uint8Array(zipData), {
- filter: (file2) => {
- const validationResult = validateZipFile(file2, state3);
- if (!validationResult.isValid) {
- throw new Error(validationResult.error);
- }
- return true;
- }
- });
- logForDebugging(`Zip extraction completed: ${state3.fileCount} files, ${Math.round(state3.totalUncompressedSize / 1024)}KB uncompressed`);
- return result;
-}
-function parseZipModes(data) {
- const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
- const modes = {};
- const minEocd = Math.max(0, buf.length - 22 - 65535);
- let eocd = -1;
- for (let i6 = buf.length - 22;i6 >= minEocd; i6--) {
- if (buf.readUInt32LE(i6) === 101010256) {
- eocd = i6;
- break;
- }
- }
- if (eocd < 0)
- return modes;
- const entryCount = buf.readUInt16LE(eocd + 10);
- let off = buf.readUInt32LE(eocd + 16);
- for (let i6 = 0;i6 < entryCount; i6++) {
- if (off + 46 > buf.length || buf.readUInt32LE(off) !== 33639248)
- break;
- const versionMadeBy = buf.readUInt16LE(off + 4);
- const nameLen = buf.readUInt16LE(off + 28);
- const extraLen = buf.readUInt16LE(off + 30);
- const commentLen = buf.readUInt16LE(off + 32);
- const externalAttr = buf.readUInt32LE(off + 38);
- const name3 = buf.toString("utf8", off + 46, off + 46 + nameLen);
- if (versionMadeBy >> 8 === 3) {
- const mode = externalAttr >>> 16 & 65535;
- if (mode)
- modes[name3] = mode;
- }
- off += 46 + nameLen + extraLen + commentLen;
- }
- return modes;
-}
-var LIMITS;
-var init_zip = __esm(() => {
- init_debug();
- init_errors();
- init_fsOperations();
- init_path();
- LIMITS = {
- MAX_FILE_SIZE: 512 * 1024 * 1024,
- MAX_TOTAL_SIZE: 1024 * 1024 * 1024,
- MAX_FILE_COUNT: 1e5,
- MAX_COMPRESSION_RATIO: 50,
- MIN_COMPRESSION_RATIO: 0.5
- };
-});
-
-// src/utils/systemDirectories.ts
-import { homedir as homedir11 } from "os";
-import { join as join39 } from "path";
-function getSystemDirectories(options2) {
- const platform3 = options2?.platform ?? getPlatform();
- const homeDir = options2?.homedir ?? homedir11();
- const env5 = options2?.env ?? process.env;
- const defaults2 = {
- HOME: homeDir,
- DESKTOP: join39(homeDir, "Desktop"),
- DOCUMENTS: join39(homeDir, "Documents"),
- DOWNLOADS: join39(homeDir, "Downloads")
- };
- switch (platform3) {
- case "windows": {
- const userProfile = env5.USERPROFILE || homeDir;
- return {
- HOME: homeDir,
- DESKTOP: join39(userProfile, "Desktop"),
- DOCUMENTS: join39(userProfile, "Documents"),
- DOWNLOADS: join39(userProfile, "Downloads")
- };
- }
- case "linux":
- case "wsl": {
- return {
- HOME: homeDir,
- DESKTOP: env5.XDG_DESKTOP_DIR || defaults2.DESKTOP,
- DOCUMENTS: env5.XDG_DOCUMENTS_DIR || defaults2.DOCUMENTS,
- DOWNLOADS: env5.XDG_DOWNLOAD_DIR || defaults2.DOWNLOADS
- };
- }
- case "macos":
- default: {
- if (platform3 === "unknown") {
- logForDebugging(`Unknown platform detected, using default paths`);
- }
- return defaults2;
- }
- }
-}
-var init_systemDirectories = __esm(() => {
- init_debug();
- init_platform2();
-});
-
-// src/utils/plugins/officialMarketplace.ts
-var OFFICIAL_MARKETPLACE_SOURCE, OFFICIAL_MARKETPLACE_NAME = "claude-plugins-official";
-var init_officialMarketplace = __esm(() => {
- OFFICIAL_MARKETPLACE_SOURCE = {
- source: "github",
- repo: "anthropics/claude-plugins-official"
- };
-});
-
-// src/utils/plugins/fetchTelemetry.ts
-function extractHost(urlOrSpec) {
- let host;
- const scpMatch = /^[^@/]+@([^:/]+):/.exec(urlOrSpec);
- if (scpMatch) {
- host = scpMatch[1];
- } else {
- try {
- host = new URL(urlOrSpec).hostname;
- } catch {
- return "unknown";
- }
- }
- const normalized = host.toLowerCase();
- return KNOWN_PUBLIC_HOSTS.has(normalized) ? normalized : "other";
-}
-function isOfficialRepo(urlOrSpec) {
- return urlOrSpec.includes(`anthropics/${OFFICIAL_MARKETPLACE_NAME}`);
-}
-function logPluginFetch(source, urlOrSpec, outcome, durationMs, errorKind) {
- logEvent("tengu_plugin_remote_fetch", {
- source,
- host: urlOrSpec ? extractHost(urlOrSpec) : "unknown",
- is_official: urlOrSpec ? isOfficialRepo(urlOrSpec) : false,
- outcome,
- duration_ms: Math.round(durationMs),
- ...errorKind && { error_kind: errorKind }
- });
-}
-function classifyFetchError(error46) {
- const msg = String(error46?.message ?? error46);
- if (/ENOTFOUND|ECONNREFUSED|EAI_AGAIN|Could not resolve host|Connection refused/i.test(msg)) {
- return "dns_or_refused";
- }
- if (/ETIMEDOUT|timed out|timeout/i.test(msg))
- return "timeout";
- if (/ECONNRESET|socket hang up|Connection reset by peer|remote end hung up/i.test(msg)) {
- return "conn_reset";
- }
- if (/403|401|authentication|permission denied/i.test(msg))
- return "auth";
- if (/404|not found|repository not found/i.test(msg))
- return "not_found";
- if (/certificate|SSL|TLS|unable to get local issuer/i.test(msg))
- return "tls";
- if (/Invalid response format|Invalid marketplace schema/i.test(msg)) {
- return "invalid_schema";
- }
- return "other";
-}
-var KNOWN_PUBLIC_HOSTS;
-var init_fetchTelemetry = __esm(() => {
- init_analytics();
- init_officialMarketplace();
- KNOWN_PUBLIC_HOSTS = new Set([
- "github.com",
- "raw.githubusercontent.com",
- "objects.githubusercontent.com",
- "gist.githubusercontent.com",
- "gitlab.com",
- "bitbucket.org",
- "codeberg.org",
- "dev.azure.com",
- "ssh.dev.azure.com",
- "storage.googleapis.com"
- ]);
-});
-
-// src/utils/plugins/mcpbHandler.ts
-import { createHash as createHash7 } from "crypto";
-import { chmod, writeFile as writeFile10 } from "fs/promises";
-import { dirname as dirname14, join as join40 } from "path";
-function isMcpbSource(source) {
- return source.endsWith(".mcpb") || source.endsWith(".dxt");
-}
-function isUrl2(source) {
- return source.startsWith("http://") || source.startsWith("https://");
-}
-function generateContentHash(data) {
- return createHash7("sha256").update(data).digest("hex").substring(0, 16);
-}
-function getMcpbCacheDir(pluginPath) {
- return join40(pluginPath, ".mcpb-cache");
-}
-function getMetadataPath(cacheDir, source) {
- const sourceHash = createHash7("md5").update(source).digest("hex").substring(0, 8);
- return join40(cacheDir, `${sourceHash}.metadata.json`);
-}
-function serverSecretsKey(pluginId, serverName) {
- return `${pluginId}/${serverName}`;
-}
-function loadMcpServerUserConfig(pluginId, serverName) {
- try {
- const settings = getSettings_DEPRECATED();
- const nonSensitive = settings.pluginConfigs?.[pluginId]?.mcpServers?.[serverName];
- const sensitive = getSecureStorage().read()?.pluginSecrets?.[serverSecretsKey(pluginId, serverName)];
- if (!nonSensitive && !sensitive) {
- return null;
- }
- logForDebugging(`Loaded user config for ${pluginId}/${serverName} (settings + secureStorage)`);
- return { ...nonSensitive, ...sensitive };
- } catch (error46) {
- const errorObj = toError(error46);
- logError2(errorObj);
- logForDebugging(`Failed to load user config for ${pluginId}/${serverName}: ${error46}`, { level: "error" });
- return null;
- }
-}
-function saveMcpServerUserConfig(pluginId, serverName, config9, schema5) {
- try {
- const nonSensitive = {};
- const sensitive = {};
- for (const [key2, value] of Object.entries(config9)) {
- if (schema5[key2]?.sensitive === true) {
- sensitive[key2] = String(value);
- } else {
- nonSensitive[key2] = value;
- }
- }
- const sensitiveKeysInThisSave = new Set(Object.keys(sensitive));
- const nonSensitiveKeysInThisSave = new Set(Object.keys(nonSensitive));
- const storage = getSecureStorage();
- const k4 = serverSecretsKey(pluginId, serverName);
- const existingInSecureStorage = storage.read()?.pluginSecrets?.[k4] ?? undefined;
- const secureScrubbed = existingInSecureStorage ? Object.fromEntries(Object.entries(existingInSecureStorage).filter(([key2]) => !nonSensitiveKeysInThisSave.has(key2))) : undefined;
- const needSecureScrub = secureScrubbed && existingInSecureStorage && Object.keys(secureScrubbed).length !== Object.keys(existingInSecureStorage).length;
- if (Object.keys(sensitive).length > 0 || needSecureScrub) {
- const existing = storage.read() ?? {};
- if (!existing.pluginSecrets) {
- existing.pluginSecrets = {};
- }
- existing.pluginSecrets[k4] = {
- ...secureScrubbed,
- ...sensitive
- };
- const result = storage.update(existing);
- if (!result.success) {
- throw new Error(`Failed to save sensitive config to secure storage for ${k4}`);
- }
- if (result.warning) {
- logForDebugging(`Server secrets save warning: ${result.warning}`, {
- level: "warn"
- });
- }
- if (needSecureScrub) {
- logForDebugging(`saveMcpServerUserConfig: scrubbed ${Object.keys(existingInSecureStorage).length - Object.keys(secureScrubbed).length} stale non-sensitive key(s) from secureStorage for ${k4}`);
- }
- }
- const settings = getSettings_DEPRECATED();
- const existingInSettings = settings.pluginConfigs?.[pluginId]?.mcpServers?.[serverName] ?? {};
- const keysToScrubFromSettings = Object.keys(existingInSettings).filter((k5) => sensitiveKeysInThisSave.has(k5));
- if (Object.keys(nonSensitive).length > 0 || keysToScrubFromSettings.length > 0) {
- if (!settings.pluginConfigs) {
- settings.pluginConfigs = {};
- }
- if (!settings.pluginConfigs[pluginId]) {
- settings.pluginConfigs[pluginId] = {};
- }
- if (!settings.pluginConfigs[pluginId].mcpServers) {
- settings.pluginConfigs[pluginId].mcpServers = {};
- }
- const scrubbed = Object.fromEntries(keysToScrubFromSettings.map((k5) => [k5, undefined]));
- settings.pluginConfigs[pluginId].mcpServers[serverName] = {
- ...nonSensitive,
- ...scrubbed
- };
- const result = updateSettingsForSource("userSettings", settings);
- if (result.error) {
- throw result.error;
- }
- if (keysToScrubFromSettings.length > 0) {
- logForDebugging(`saveMcpServerUserConfig: scrubbed ${keysToScrubFromSettings.length} plaintext sensitive key(s) from settings.json for ${pluginId}/${serverName}`);
- }
- }
- logForDebugging(`Saved user config for ${pluginId}/${serverName} (${Object.keys(nonSensitive).length} non-sensitive, ${Object.keys(sensitive).length} sensitive)`);
- } catch (error46) {
- const errorObj = toError(error46);
- logError2(errorObj);
- throw new Error(`Failed to save user configuration for ${pluginId}/${serverName}: ${errorObj.message}`);
- }
-}
-function validateUserConfig(values2, schema5) {
- const errors8 = [];
- for (const [key2, fieldSchema] of Object.entries(schema5)) {
- const value = values2[key2];
- if (fieldSchema.required && (value === undefined || value === "")) {
- errors8.push(`${fieldSchema.title || key2} is required but not provided`);
- continue;
- }
- if (value === undefined || value === "") {
- continue;
- }
- if (fieldSchema.type === "string") {
- if (Array.isArray(value)) {
- if (!fieldSchema.multiple) {
- errors8.push(`${fieldSchema.title || key2} must be a string, not an array`);
- } else if (!value.every((v6) => typeof v6 === "string")) {
- errors8.push(`${fieldSchema.title || key2} must be an array of strings`);
- }
- } else if (typeof value !== "string") {
- errors8.push(`${fieldSchema.title || key2} must be a string`);
- }
- } else if (fieldSchema.type === "number" && typeof value !== "number") {
- errors8.push(`${fieldSchema.title || key2} must be a number`);
- } else if (fieldSchema.type === "boolean" && typeof value !== "boolean") {
- errors8.push(`${fieldSchema.title || key2} must be a boolean`);
- } else if ((fieldSchema.type === "file" || fieldSchema.type === "directory") && typeof value !== "string") {
- errors8.push(`${fieldSchema.title || key2} must be a path string`);
- }
- if (fieldSchema.type === "number" && typeof value === "number") {
- if (fieldSchema.min !== undefined && value < fieldSchema.min) {
- errors8.push(`${fieldSchema.title || key2} must be at least ${fieldSchema.min}`);
- }
- if (fieldSchema.max !== undefined && value > fieldSchema.max) {
- errors8.push(`${fieldSchema.title || key2} must be at most ${fieldSchema.max}`);
- }
- }
- }
- return { valid: errors8.length === 0, errors: errors8 };
-}
-async function generateMcpConfig(manifest, extractedPath, userConfig = {}) {
- const { getMcpConfigForManifest: getMcpConfigForManifest2 } = await Promise.resolve().then(() => (init_dist5(), exports_dist2));
- const mcpConfig = await getMcpConfigForManifest2({
- manifest,
- extensionPath: extractedPath,
- systemDirs: getSystemDirectories(),
- userConfig,
- pathSeparator: "/"
- });
- if (!mcpConfig) {
- const error46 = new Error(`Failed to generate MCP server configuration from manifest "${manifest.name}"`);
- logError2(error46);
- throw error46;
- }
- return mcpConfig;
-}
-async function loadCacheMetadata(cacheDir, source) {
- const fs10 = getFsImplementation();
- const metadataPath = getMetadataPath(cacheDir, source);
- try {
- const content = await fs10.readFile(metadataPath, { encoding: "utf-8" });
- return jsonParse(content);
- } catch (error46) {
- const code = getErrnoCode(error46);
- if (code === "ENOENT")
- return null;
- const errorObj = toError(error46);
- logError2(errorObj);
- logForDebugging(`Failed to load MCPB cache metadata: ${error46}`, {
- level: "error"
- });
- return null;
- }
-}
-async function saveCacheMetadata(cacheDir, source, metadata) {
- const metadataPath = getMetadataPath(cacheDir, source);
- await getFsImplementation().mkdir(cacheDir);
- await writeFile10(metadataPath, jsonStringify(metadata, null, 2), "utf-8");
-}
-async function downloadMcpb(url3, destPath, onProgress) {
- logForDebugging(`Downloading MCPB from ${url3}`);
- if (onProgress) {
- onProgress(`Downloading ${url3}...`);
- }
- const started = performance.now();
- let fetchTelemetryFired = false;
- try {
- const response7 = await axios_default.get(url3, {
- timeout: 120000,
- responseType: "arraybuffer",
- maxRedirects: 5,
- onDownloadProgress: (progressEvent) => {
- if (progressEvent.total && onProgress) {
- const percent = Math.round(progressEvent.loaded / progressEvent.total * 100);
- onProgress(`Downloading... ${percent}%`);
- }
- }
- });
- const data = new Uint8Array(response7.data);
- logPluginFetch("mcpb", url3, "success", performance.now() - started);
- fetchTelemetryFired = true;
- await writeFile10(destPath, Buffer.from(data));
- logForDebugging(`Downloaded ${data.length} bytes to ${destPath}`);
- if (onProgress) {
- onProgress("Download complete");
- }
- return data;
- } catch (error46) {
- if (!fetchTelemetryFired) {
- logPluginFetch("mcpb", url3, "failure", performance.now() - started, classifyFetchError(error46));
- }
- const errorMsg = errorMessage(error46);
- const fullError = new Error(`Failed to download MCPB file from ${url3}: ${errorMsg}`);
- logError2(fullError);
- throw fullError;
- }
-}
-async function extractMcpbContents(unzipped, extractPath, modes, onProgress) {
- if (onProgress) {
- onProgress("Extracting files...");
- }
- await getFsImplementation().mkdir(extractPath);
- let filesWritten = 0;
- const entries = Object.entries(unzipped).filter(([k4]) => !k4.endsWith("/"));
- const totalFiles = entries.length;
- for (const [filePath, fileData] of entries) {
- const fullPath = join40(extractPath, filePath);
- const dir = dirname14(fullPath);
- if (dir !== extractPath) {
- await getFsImplementation().mkdir(dir);
- }
- const isTextFile = filePath.endsWith(".json") || filePath.endsWith(".js") || filePath.endsWith(".ts") || filePath.endsWith(".txt") || filePath.endsWith(".md") || filePath.endsWith(".yml") || filePath.endsWith(".yaml");
- if (isTextFile) {
- const content = new TextDecoder().decode(fileData);
- await writeFile10(fullPath, content, "utf-8");
- } else {
- await writeFile10(fullPath, Buffer.from(fileData));
- }
- const mode = modes[filePath];
- if (mode && mode & 73) {
- await chmod(fullPath, mode & 511).catch(() => {});
- }
- filesWritten++;
- if (onProgress && filesWritten % 10 === 0) {
- onProgress(`Extracted ${filesWritten}/${totalFiles} files`);
- }
- }
- logForDebugging(`Extracted ${filesWritten} files to ${extractPath}`);
- if (onProgress) {
- onProgress(`Extraction complete (${filesWritten} files)`);
- }
-}
-async function checkMcpbChanged(source, pluginPath) {
- const fs10 = getFsImplementation();
- const cacheDir = getMcpbCacheDir(pluginPath);
- const metadata = await loadCacheMetadata(cacheDir, source);
- if (!metadata) {
- return true;
- }
- try {
- await fs10.stat(metadata.extractedPath);
- } catch (error46) {
- const code = getErrnoCode(error46);
- if (code === "ENOENT") {
- logForDebugging(`MCPB extraction path missing: ${metadata.extractedPath}`);
- } else {
- logForDebugging(`MCPB extraction path inaccessible: ${metadata.extractedPath}: ${error46}`, { level: "error" });
- }
- return true;
- }
- if (!isUrl2(source)) {
- const localPath = join40(pluginPath, source);
- let stats;
- try {
- stats = await fs10.stat(localPath);
- } catch (error46) {
- const code = getErrnoCode(error46);
- if (code === "ENOENT") {
- logForDebugging(`MCPB source file missing: ${localPath}`);
- } else {
- logForDebugging(`MCPB source file inaccessible: ${localPath}: ${error46}`, { level: "error" });
- }
- return true;
- }
- const cachedTime = new Date(metadata.cachedAt).getTime();
- const fileTime = Math.floor(stats.mtimeMs);
- if (fileTime > cachedTime) {
- logForDebugging(`MCPB file modified: ${new Date(fileTime)} > ${new Date(cachedTime)}`);
- return true;
- }
- }
- return false;
-}
-async function loadMcpbFile(source, pluginPath, pluginId, onProgress, providedUserConfig, forceConfigDialog) {
- const fs10 = getFsImplementation();
- const cacheDir = getMcpbCacheDir(pluginPath);
- await fs10.mkdir(cacheDir);
- logForDebugging(`Loading MCPB from source: ${source}`);
- const metadata = await loadCacheMetadata(cacheDir, source);
- if (metadata && !await checkMcpbChanged(source, pluginPath)) {
- logForDebugging(`Using cached MCPB from ${metadata.extractedPath} (hash: ${metadata.contentHash})`);
- const manifestPath = join40(metadata.extractedPath, "manifest.json");
- let manifestContent;
- try {
- manifestContent = await fs10.readFile(manifestPath, { encoding: "utf-8" });
- } catch (error46) {
- if (isENOENT(error46)) {
- const err2 = new Error(`Cached manifest not found: ${manifestPath}`);
- logError2(err2);
- throw err2;
- }
- throw error46;
- }
- const manifestData2 = new TextEncoder().encode(manifestContent);
- const manifest2 = await parseAndValidateManifestFromBytes(manifestData2);
- if (manifest2.user_config && Object.keys(manifest2.user_config).length > 0) {
- const serverName = manifest2.name;
- const savedConfig = loadMcpServerUserConfig(pluginId, serverName);
- const userConfig = providedUserConfig || savedConfig || {};
- const validation = validateUserConfig(userConfig, manifest2.user_config);
- if (forceConfigDialog || !validation.valid) {
- return {
- status: "needs-config",
- manifest: manifest2,
- extractedPath: metadata.extractedPath,
- contentHash: metadata.contentHash,
- configSchema: manifest2.user_config,
- existingConfig: savedConfig || {},
- validationErrors: validation.valid ? [] : validation.errors
- };
- }
- if (providedUserConfig) {
- saveMcpServerUserConfig(pluginId, serverName, providedUserConfig, manifest2.user_config ?? {});
- }
- const mcpConfig3 = await generateMcpConfig(manifest2, metadata.extractedPath, userConfig);
- return {
- manifest: manifest2,
- mcpConfig: mcpConfig3,
- extractedPath: metadata.extractedPath,
- contentHash: metadata.contentHash
- };
- }
- const mcpConfig2 = await generateMcpConfig(manifest2, metadata.extractedPath);
- return {
- manifest: manifest2,
- mcpConfig: mcpConfig2,
- extractedPath: metadata.extractedPath,
- contentHash: metadata.contentHash
- };
- }
- let mcpbData;
- let mcpbFilePath;
- if (isUrl2(source)) {
- const sourceHash = createHash7("md5").update(source).digest("hex").substring(0, 8);
- mcpbFilePath = join40(cacheDir, `${sourceHash}.mcpb`);
- mcpbData = await downloadMcpb(source, mcpbFilePath, onProgress);
- } else {
- const localPath = join40(pluginPath, source);
- if (onProgress) {
- onProgress(`Loading ${source}...`);
- }
- try {
- mcpbData = await fs10.readFileBytes(localPath);
- mcpbFilePath = localPath;
- } catch (error46) {
- if (isENOENT(error46)) {
- const err2 = new Error(`MCPB file not found: ${localPath}`);
- logError2(err2);
- throw err2;
- }
- throw error46;
- }
- }
- const contentHash = generateContentHash(mcpbData);
- logForDebugging(`MCPB content hash: ${contentHash}`);
- if (onProgress) {
- onProgress("Extracting MCPB archive...");
- }
- const unzipped = await unzipFile(Buffer.from(mcpbData));
- const modes = parseZipModes(mcpbData);
- const manifestData = unzipped["manifest.json"];
- if (!manifestData) {
- const error46 = new Error("No manifest.json found in MCPB file");
- logError2(error46);
- throw error46;
- }
- const manifest = await parseAndValidateManifestFromBytes(manifestData);
- logForDebugging(`MCPB manifest: ${manifest.name} v${manifest.version} by ${manifest.author.name}`);
- if (!manifest.server) {
- const error46 = new Error(`MCPB manifest for "${manifest.name}" does not define a server configuration`);
- logError2(error46);
- throw error46;
- }
- const extractPath = join40(cacheDir, contentHash);
- await extractMcpbContents(unzipped, extractPath, modes, onProgress);
- if (manifest.user_config && Object.keys(manifest.user_config).length > 0) {
- const serverName = manifest.name;
- const savedConfig = loadMcpServerUserConfig(pluginId, serverName);
- const userConfig = providedUserConfig || savedConfig || {};
- const validation = validateUserConfig(userConfig, manifest.user_config);
- if (!validation.valid) {
- const newMetadata3 = {
- source,
- contentHash,
- extractedPath: extractPath,
- cachedAt: new Date().toISOString(),
- lastChecked: new Date().toISOString()
- };
- await saveCacheMetadata(cacheDir, source, newMetadata3);
- return {
- status: "needs-config",
- manifest,
- extractedPath: extractPath,
- contentHash,
- configSchema: manifest.user_config,
- existingConfig: savedConfig || {},
- validationErrors: validation.errors
- };
- }
- if (providedUserConfig) {
- saveMcpServerUserConfig(pluginId, serverName, providedUserConfig, manifest.user_config ?? {});
- }
- if (onProgress) {
- onProgress("Generating MCP server configuration...");
- }
- const mcpConfig2 = await generateMcpConfig(manifest, extractPath, userConfig);
- const newMetadata2 = {
- source,
- contentHash,
- extractedPath: extractPath,
- cachedAt: new Date().toISOString(),
- lastChecked: new Date().toISOString()
- };
- await saveCacheMetadata(cacheDir, source, newMetadata2);
- return {
- manifest,
- mcpConfig: mcpConfig2,
- extractedPath: extractPath,
- contentHash
- };
- }
- if (onProgress) {
- onProgress("Generating MCP server configuration...");
- }
- const mcpConfig = await generateMcpConfig(manifest, extractPath);
- const newMetadata = {
- source,
- contentHash,
- extractedPath: extractPath,
- cachedAt: new Date().toISOString(),
- lastChecked: new Date().toISOString()
- };
- await saveCacheMetadata(cacheDir, source, newMetadata);
- logForDebugging(`Successfully loaded MCPB: ${manifest.name} (extracted to ${extractPath})`);
- return {
- manifest,
- mcpConfig,
- extractedPath: extractPath,
- contentHash
- };
-}
-var init_mcpbHandler = __esm(() => {
- init_axios2();
- init_debug();
- init_helpers2();
- init_zip();
- init_errors();
- init_fsOperations();
- init_log2();
- init_secureStorage();
- init_settings2();
- init_slowOperations();
- init_systemDirectories();
- init_fetchTelemetry();
-});
-
-// node_modules/@anthropic-ai/sandbox-runtime/index.js
-var require_sandbox_runtime = __commonJS((exports, module) => {
- module.exports = {};
-});
-
-// node_modules/readdirp/esm/index.js
-import { stat as stat12, lstat, readdir as readdir6, realpath as realpath5 } from "fs/promises";
-import { Readable as Readable9 } from "stream";
-import { resolve as presolve, relative as prelative, join as pjoin, sep as psep } from "path";
-function readdirp(root2, options2 = {}) {
- let type = options2.entryType || options2.type;
- if (type === "both")
- type = EntryTypes.FILE_DIR_TYPE;
- if (type)
- options2.type = type;
- if (!root2) {
- throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
- } else if (typeof root2 !== "string") {
- throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
- } else if (type && !ALL_TYPES.includes(type)) {
- throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
- }
- options2.root = root2;
- return new ReaddirpStream(options2);
-}
-var EntryTypes, defaultOptions, RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR", NORMAL_FLOW_ERRORS, ALL_TYPES, DIR_TYPES, FILE_TYPES2, isNormalFlowError = (error46) => NORMAL_FLOW_ERRORS.has(error46.code), wantBigintFsStats, emptyFn = (_entryInfo) => true, normalizeFilter = (filter2) => {
- if (filter2 === undefined)
- return emptyFn;
- if (typeof filter2 === "function")
- return filter2;
- if (typeof filter2 === "string") {
- const fl2 = filter2.trim();
- return (entry) => entry.basename === fl2;
- }
- if (Array.isArray(filter2)) {
- const trItems = filter2.map((item) => item.trim());
- return (entry) => trItems.some((f4) => entry.basename === f4);
- }
- return emptyFn;
-}, ReaddirpStream;
-var init_esm19 = __esm(() => {
- EntryTypes = {
- FILE_TYPE: "files",
- DIR_TYPE: "directories",
- FILE_DIR_TYPE: "files_directories",
- EVERYTHING_TYPE: "all"
- };
- defaultOptions = {
- root: ".",
- fileFilter: (_entryInfo) => true,
- directoryFilter: (_entryInfo) => true,
- type: EntryTypes.FILE_TYPE,
- lstat: false,
- depth: 2147483648,
- alwaysStat: false,
- highWaterMark: 4096
- };
- Object.freeze(defaultOptions);
- NORMAL_FLOW_ERRORS = new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
- ALL_TYPES = [
- EntryTypes.DIR_TYPE,
- EntryTypes.EVERYTHING_TYPE,
- EntryTypes.FILE_DIR_TYPE,
- EntryTypes.FILE_TYPE
- ];
- DIR_TYPES = new Set([
- EntryTypes.DIR_TYPE,
- EntryTypes.EVERYTHING_TYPE,
- EntryTypes.FILE_DIR_TYPE
- ]);
- FILE_TYPES2 = new Set([
- EntryTypes.EVERYTHING_TYPE,
- EntryTypes.FILE_DIR_TYPE,
- EntryTypes.FILE_TYPE
- ]);
- wantBigintFsStats = process.platform === "win32";
- ReaddirpStream = class ReaddirpStream extends Readable9 {
- constructor(options2 = {}) {
- super({
- objectMode: true,
- autoDestroy: true,
- highWaterMark: options2.highWaterMark
- });
- const opts = { ...defaultOptions, ...options2 };
- const { root: root2, type } = opts;
- this._fileFilter = normalizeFilter(opts.fileFilter);
- this._directoryFilter = normalizeFilter(opts.directoryFilter);
- const statMethod = opts.lstat ? lstat : stat12;
- if (wantBigintFsStats) {
- this._stat = (path15) => statMethod(path15, { bigint: true });
- } else {
- this._stat = statMethod;
- }
- this._maxDepth = opts.depth ?? defaultOptions.depth;
- this._wantsDir = type ? DIR_TYPES.has(type) : false;
- this._wantsFile = type ? FILE_TYPES2.has(type) : false;
- this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
- this._root = presolve(root2);
- this._isDirent = !opts.alwaysStat;
- this._statsProp = this._isDirent ? "dirent" : "stats";
- this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
- this.parents = [this._exploreDir(root2, 1)];
- this.reading = false;
- this.parent = undefined;
- }
- async _read(batch) {
- if (this.reading)
- return;
- this.reading = true;
- try {
- while (!this.destroyed && batch > 0) {
- const par = this.parent;
- const fil = par && par.files;
- if (fil && fil.length > 0) {
- const { path: path15, depth } = par;
- const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path15));
- const awaited = await Promise.all(slice);
- for (const entry of awaited) {
- if (!entry)
- continue;
- if (this.destroyed)
- return;
- const entryType = await this._getEntryType(entry);
- if (entryType === "directory" && this._directoryFilter(entry)) {
- if (depth <= this._maxDepth) {
- this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
- }
- if (this._wantsDir) {
- this.push(entry);
- batch--;
- }
- } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
- if (this._wantsFile) {
- this.push(entry);
- batch--;
- }
- }
- }
- } else {
- const parent = this.parents.pop();
- if (!parent) {
- this.push(null);
- break;
- }
- this.parent = await parent;
- if (this.destroyed)
- return;
- }
- }
- } catch (error46) {
- this.destroy(error46);
- } finally {
- this.reading = false;
- }
- }
- async _exploreDir(path15, depth) {
- let files2;
- try {
- files2 = await readdir6(path15, this._rdOptions);
- } catch (error46) {
- this._onError(error46);
- }
- return { files: files2, depth, path: path15 };
- }
- async _formatEntry(dirent, path15) {
- let entry;
- const basename7 = this._isDirent ? dirent.name : dirent;
- try {
- const fullPath = presolve(pjoin(path15, basename7));
- entry = { path: prelative(this._root, fullPath), fullPath, basename: basename7 };
- entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
- } catch (err2) {
- this._onError(err2);
- return;
- }
- return entry;
- }
- _onError(err2) {
- if (isNormalFlowError(err2) && !this.destroyed) {
- this.emit("warn", err2);
- } else {
- this.destroy(err2);
- }
- }
- async _getEntryType(entry) {
- if (!entry && this._statsProp in entry) {
- return "";
- }
- const stats = entry[this._statsProp];
- if (stats.isFile())
- return "file";
- if (stats.isDirectory())
- return "directory";
- if (stats && stats.isSymbolicLink()) {
- const full = entry.fullPath;
- try {
- const entryRealPath = await realpath5(full);
- const entryRealPathStats = await lstat(entryRealPath);
- if (entryRealPathStats.isFile()) {
- return "file";
- }
- if (entryRealPathStats.isDirectory()) {
- const len = entryRealPath.length;
- if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {
- const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
- recursiveError.code = RECURSIVE_ERROR_CODE;
- return this._onError(recursiveError);
- }
- return "directory";
- }
- } catch (error46) {
- this._onError(error46);
- return "";
- }
- }
- }
- _includeAsFile(entry) {
- const stats = entry && entry[this._statsProp];
- return stats && this._wantsEverything && !stats.isDirectory();
- }
- };
-});
-
-// node_modules/chokidar/esm/handler.js
-import { watchFile as watchFile3, unwatchFile as unwatchFile3, watch as fs_watch } from "fs";
-import { open as open6, stat as stat13, lstat as lstat2, realpath as fsrealpath } from "fs/promises";
-import * as sysPath from "path";
-import { type as osType } from "os";
-function createFsWatchInstance(path15, options2, listener, errHandler, emitRaw) {
- const handleEvent = (rawEvent, evPath) => {
- listener(path15);
- emitRaw(rawEvent, evPath, { watchedPath: path15 });
- if (evPath && path15 !== evPath) {
- fsWatchBroadcast(sysPath.resolve(path15, evPath), KEY_LISTENERS, sysPath.join(path15, evPath));
- }
- };
- try {
- return fs_watch(path15, {
- persistent: options2.persistent
- }, handleEvent);
- } catch (error46) {
- errHandler(error46);
- return;
- }
-}
-
-class NodeFsHandler {
- constructor(fsW) {
- this.fsw = fsW;
- this._boundHandleError = (error46) => fsW._handleError(error46);
- }
- _watchWithNodeFs(path15, listener) {
- const opts = this.fsw.options;
- const directory = sysPath.dirname(path15);
- const basename8 = sysPath.basename(path15);
- const parent = this.fsw._getWatchedDir(directory);
- parent.add(basename8);
- const absolutePath = sysPath.resolve(path15);
- const options2 = {
- persistent: opts.persistent
- };
- if (!listener)
- listener = EMPTY_FN;
- let closer;
- if (opts.usePolling) {
- const enableBin = opts.interval !== opts.binaryInterval;
- options2.interval = enableBin && isBinaryPath(basename8) ? opts.binaryInterval : opts.interval;
- closer = setFsWatchFileListener(path15, absolutePath, options2, {
- listener,
- rawEmitter: this.fsw._emitRaw
- });
- } else {
- closer = setFsWatchListener(path15, absolutePath, options2, {
- listener,
- errHandler: this._boundHandleError,
- rawEmitter: this.fsw._emitRaw
- });
- }
- return closer;
- }
- _handleFile(file2, stats, initialAdd) {
- if (this.fsw.closed) {
- return;
- }
- const dirname16 = sysPath.dirname(file2);
- const basename8 = sysPath.basename(file2);
- const parent = this.fsw._getWatchedDir(dirname16);
- let prevStats = stats;
- if (parent.has(basename8))
- return;
- const listener = async (path15, newStats) => {
- if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
- return;
- if (!newStats || newStats.mtimeMs === 0) {
- try {
- const newStats2 = await stat13(file2);
- if (this.fsw.closed)
- return;
- const at = newStats2.atimeMs;
- const mt2 = newStats2.mtimeMs;
- if (!at || at <= mt2 || mt2 !== prevStats.mtimeMs) {
- this.fsw._emit(EV.CHANGE, file2, newStats2);
- }
- if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
- this.fsw._closeFile(path15);
- prevStats = newStats2;
- const closer2 = this._watchWithNodeFs(file2, listener);
- if (closer2)
- this.fsw._addPathCloser(path15, closer2);
- } else {
- prevStats = newStats2;
- }
- } catch (error46) {
- this.fsw._remove(dirname16, basename8);
- }
- } else if (parent.has(basename8)) {
- const at = newStats.atimeMs;
- const mt2 = newStats.mtimeMs;
- if (!at || at <= mt2 || mt2 !== prevStats.mtimeMs) {
- this.fsw._emit(EV.CHANGE, file2, newStats);
- }
- prevStats = newStats;
- }
- };
- const closer = this._watchWithNodeFs(file2, listener);
- if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file2)) {
- if (!this.fsw._throttle(EV.ADD, file2, 0))
- return;
- this.fsw._emit(EV.ADD, file2, stats);
- }
- return closer;
- }
- async _handleSymlink(entry, directory, path15, item) {
- if (this.fsw.closed) {
- return;
- }
- const full = entry.fullPath;
- const dir = this.fsw._getWatchedDir(directory);
- if (!this.fsw.options.followSymlinks) {
- this.fsw._incrReadyCount();
- let linkPath;
- try {
- linkPath = await fsrealpath(path15);
- } catch (e4) {
- this.fsw._emitReady();
- return true;
- }
- if (this.fsw.closed)
- return;
- if (dir.has(item)) {
- if (this.fsw._symlinkPaths.get(full) !== linkPath) {
- this.fsw._symlinkPaths.set(full, linkPath);
- this.fsw._emit(EV.CHANGE, path15, entry.stats);
- }
- } else {
- dir.add(item);
- this.fsw._symlinkPaths.set(full, linkPath);
- this.fsw._emit(EV.ADD, path15, entry.stats);
- }
- this.fsw._emitReady();
- return true;
- }
- if (this.fsw._symlinkPaths.has(full)) {
- return true;
- }
- this.fsw._symlinkPaths.set(full, true);
- }
- _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
- directory = sysPath.join(directory, "");
- throttler = this.fsw._throttle("readdir", directory, 1000);
- if (!throttler)
- return;
- const previous = this.fsw._getWatchedDir(wh.path);
- const current = new Set;
- let stream10 = this.fsw._readdirp(directory, {
- fileFilter: (entry) => wh.filterPath(entry),
- directoryFilter: (entry) => wh.filterDir(entry)
- });
- if (!stream10)
- return;
- stream10.on(STR_DATA, async (entry) => {
- if (this.fsw.closed) {
- stream10 = undefined;
- return;
- }
- const item = entry.path;
- let path15 = sysPath.join(directory, item);
- current.add(item);
- if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path15, item)) {
- return;
- }
- if (this.fsw.closed) {
- stream10 = undefined;
- return;
- }
- if (item === target || !target && !previous.has(item)) {
- this.fsw._incrReadyCount();
- path15 = sysPath.join(dir, sysPath.relative(dir, path15));
- this._addToNodeFs(path15, initialAdd, wh, depth + 1);
- }
- }).on(EV.ERROR, this._boundHandleError);
- return new Promise((resolve15, reject) => {
- if (!stream10)
- return reject();
- stream10.once(STR_END, () => {
- if (this.fsw.closed) {
- stream10 = undefined;
- return;
- }
- const wasThrottled = throttler ? throttler.clear() : false;
- resolve15(undefined);
- previous.getChildren().filter((item) => {
- return item !== directory && !current.has(item);
- }).forEach((item) => {
- this.fsw._remove(directory, item);
- });
- stream10 = undefined;
- if (wasThrottled)
- this._handleRead(directory, false, wh, target, dir, depth, throttler);
- });
- });
- }
- async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath6) {
- const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
- const tracked = parentDir.has(sysPath.basename(dir));
- if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
- this.fsw._emit(EV.ADD_DIR, dir, stats);
- }
- parentDir.add(sysPath.basename(dir));
- this.fsw._getWatchedDir(dir);
- let throttler;
- let closer;
- const oDepth = this.fsw.options.depth;
- if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath6)) {
- if (!target) {
- await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
- if (this.fsw.closed)
- return;
- }
- closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
- if (stats2 && stats2.mtimeMs === 0)
- return;
- this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
- });
- }
- return closer;
- }
- async _addToNodeFs(path15, initialAdd, priorWh, depth, target) {
- const ready = this.fsw._emitReady;
- if (this.fsw._isIgnored(path15) || this.fsw.closed) {
- ready();
- return false;
- }
- const wh = this.fsw._getWatchHelpers(path15);
- if (priorWh) {
- wh.filterPath = (entry) => priorWh.filterPath(entry);
- wh.filterDir = (entry) => priorWh.filterDir(entry);
- }
- try {
- const stats = await statMethods[wh.statMethod](wh.watchPath);
- if (this.fsw.closed)
- return;
- if (this.fsw._isIgnored(wh.watchPath, stats)) {
- ready();
- return false;
- }
- const follow = this.fsw.options.followSymlinks;
- let closer;
- if (stats.isDirectory()) {
- const absPath = sysPath.resolve(path15);
- const targetPath = follow ? await fsrealpath(path15) : path15;
- if (this.fsw.closed)
- return;
- closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
- if (this.fsw.closed)
- return;
- if (absPath !== targetPath && targetPath !== undefined) {
- this.fsw._symlinkPaths.set(absPath, targetPath);
- }
- } else if (stats.isSymbolicLink()) {
- const targetPath = follow ? await fsrealpath(path15) : path15;
- if (this.fsw.closed)
- return;
- const parent = sysPath.dirname(wh.watchPath);
- this.fsw._getWatchedDir(parent).add(wh.watchPath);
- this.fsw._emit(EV.ADD, wh.watchPath, stats);
- closer = await this._handleDir(parent, stats, initialAdd, depth, path15, wh, targetPath);
- if (this.fsw.closed)
- return;
- if (targetPath !== undefined) {
- this.fsw._symlinkPaths.set(sysPath.resolve(path15), targetPath);
- }
- } else {
- closer = this._handleFile(wh.watchPath, stats, initialAdd);
- }
- ready();
- if (closer)
- this.fsw._addPathCloser(path15, closer);
- return false;
- } catch (error46) {
- if (this.fsw._handleError(error46)) {
- ready();
- return path15;
- }
- }
- }
-}
-var STR_DATA = "data", STR_END = "end", STR_CLOSE = "close", EMPTY_FN = () => {}, pl, isWindows2, isMacos, isLinux, isFreeBSD, isIBMi, EVENTS, EV, THROTTLE_MODE_WATCH = "watch", statMethods, KEY_LISTENERS = "listeners", KEY_ERR = "errHandlers", KEY_RAW = "rawEmitters", HANDLER_KEYS, binaryExtensions, isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase()), foreach = (val, fn) => {
- if (val instanceof Set) {
- val.forEach(fn);
- } else {
- fn(val);
- }
-}, addAndConvert = (main, prop, item) => {
- let container = main[prop];
- if (!(container instanceof Set)) {
- main[prop] = container = new Set([container]);
- }
- container.add(item);
-}, clearItem = (cont) => (key2) => {
- const set2 = cont[key2];
- if (set2 instanceof Set) {
- set2.clear();
- } else {
- delete cont[key2];
- }
-}, delFromSet = (main, prop, item) => {
- const container = main[prop];
- if (container instanceof Set) {
- container.delete(item);
- } else if (container === item) {
- delete main[prop];
- }
-}, isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val, FsWatchInstances, fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
- const cont = FsWatchInstances.get(fullPath);
- if (!cont)
- return;
- foreach(cont[listenerType], (listener) => {
- listener(val1, val2, val3);
- });
-}, setFsWatchListener = (path15, fullPath, options2, handlers) => {
- const { listener, errHandler, rawEmitter } = handlers;
- let cont = FsWatchInstances.get(fullPath);
- let watcher;
- if (!options2.persistent) {
- watcher = createFsWatchInstance(path15, options2, listener, errHandler, rawEmitter);
- if (!watcher)
- return;
- return watcher.close.bind(watcher);
- }
- if (cont) {
- addAndConvert(cont, KEY_LISTENERS, listener);
- addAndConvert(cont, KEY_ERR, errHandler);
- addAndConvert(cont, KEY_RAW, rawEmitter);
- } else {
- watcher = createFsWatchInstance(path15, options2, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
- if (!watcher)
- return;
- watcher.on(EV.ERROR, async (error46) => {
- const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
- if (cont)
- cont.watcherUnusable = true;
- if (isWindows2 && error46.code === "EPERM") {
- try {
- const fd2 = await open6(path15, "r");
- await fd2.close();
- broadcastErr(error46);
- } catch (err2) {}
- } else {
- broadcastErr(error46);
- }
- });
- cont = {
- listeners: listener,
- errHandlers: errHandler,
- rawEmitters: rawEmitter,
- watcher
- };
- FsWatchInstances.set(fullPath, cont);
- }
- return () => {
- delFromSet(cont, KEY_LISTENERS, listener);
- delFromSet(cont, KEY_ERR, errHandler);
- delFromSet(cont, KEY_RAW, rawEmitter);
- if (isEmptySet(cont.listeners)) {
- cont.watcher.close();
- FsWatchInstances.delete(fullPath);
- HANDLER_KEYS.forEach(clearItem(cont));
- cont.watcher = undefined;
- Object.freeze(cont);
- }
- };
-}, FsWatchFileInstances, setFsWatchFileListener = (path15, fullPath, options2, handlers) => {
- const { listener, rawEmitter } = handlers;
- let cont = FsWatchFileInstances.get(fullPath);
- const copts = cont && cont.options;
- if (copts && (copts.persistent < options2.persistent || copts.interval > options2.interval)) {
- unwatchFile3(fullPath);
- cont = undefined;
- }
- if (cont) {
- addAndConvert(cont, KEY_LISTENERS, listener);
- addAndConvert(cont, KEY_RAW, rawEmitter);
- } else {
- cont = {
- listeners: listener,
- rawEmitters: rawEmitter,
- options: options2,
- watcher: watchFile3(fullPath, options2, (curr, prev) => {
- foreach(cont.rawEmitters, (rawEmitter2) => {
- rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
- });
- const currmtime = curr.mtimeMs;
- if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
- foreach(cont.listeners, (listener2) => listener2(path15, curr));
- }
- })
- };
- FsWatchFileInstances.set(fullPath, cont);
- }
- return () => {
- delFromSet(cont, KEY_LISTENERS, listener);
- delFromSet(cont, KEY_RAW, rawEmitter);
- if (isEmptySet(cont.listeners)) {
- FsWatchFileInstances.delete(fullPath);
- unwatchFile3(fullPath);
- cont.options = cont.watcher = undefined;
- Object.freeze(cont);
- }
- };
-};
-var init_handler = __esm(() => {
- pl = process.platform;
- isWindows2 = pl === "win32";
- isMacos = pl === "darwin";
- isLinux = pl === "linux";
- isFreeBSD = pl === "freebsd";
- isIBMi = osType() === "OS400";
- EVENTS = {
- ALL: "all",
- READY: "ready",
- ADD: "add",
- CHANGE: "change",
- ADD_DIR: "addDir",
- UNLINK: "unlink",
- UNLINK_DIR: "unlinkDir",
- RAW: "raw",
- ERROR: "error"
- };
- EV = EVENTS;
- statMethods = { lstat: lstat2, stat: stat13 };
- HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
- binaryExtensions = new Set([
- "3dm",
- "3ds",
- "3g2",
- "3gp",
- "7z",
- "a",
- "aac",
- "adp",
- "afdesign",
- "afphoto",
- "afpub",
- "ai",
- "aif",
- "aiff",
- "alz",
- "ape",
- "apk",
- "appimage",
- "ar",
- "arj",
- "asf",
- "au",
- "avi",
- "bak",
- "baml",
- "bh",
- "bin",
- "bk",
- "bmp",
- "btif",
- "bz2",
- "bzip2",
- "cab",
- "caf",
- "cgm",
- "class",
- "cmx",
- "cpio",
- "cr2",
- "cur",
- "dat",
- "dcm",
- "deb",
- "dex",
- "djvu",
- "dll",
- "dmg",
- "dng",
- "doc",
- "docm",
- "docx",
- "dot",
- "dotm",
- "dra",
- "DS_Store",
- "dsk",
- "dts",
- "dtshd",
- "dvb",
- "dwg",
- "dxf",
- "ecelp4800",
- "ecelp7470",
- "ecelp9600",
- "egg",
- "eol",
- "eot",
- "epub",
- "exe",
- "f4v",
- "fbs",
- "fh",
- "fla",
- "flac",
- "flatpak",
- "fli",
- "flv",
- "fpx",
- "fst",
- "fvt",
- "g3",
- "gh",
- "gif",
- "graffle",
- "gz",
- "gzip",
- "h261",
- "h263",
- "h264",
- "icns",
- "ico",
- "ief",
- "img",
- "ipa",
- "iso",
- "jar",
- "jpeg",
- "jpg",
- "jpgv",
- "jpm",
- "jxr",
- "key",
- "ktx",
- "lha",
- "lib",
- "lvp",
- "lz",
- "lzh",
- "lzma",
- "lzo",
- "m3u",
- "m4a",
- "m4v",
- "mar",
- "mdi",
- "mht",
- "mid",
- "midi",
- "mj2",
- "mka",
- "mkv",
- "mmr",
- "mng",
- "mobi",
- "mov",
- "movie",
- "mp3",
- "mp4",
- "mp4a",
- "mpeg",
- "mpg",
- "mpga",
- "mxu",
- "nef",
- "npx",
- "numbers",
- "nupkg",
- "o",
- "odp",
- "ods",
- "odt",
- "oga",
- "ogg",
- "ogv",
- "otf",
- "ott",
- "pages",
- "pbm",
- "pcx",
- "pdb",
- "pdf",
- "pea",
- "pgm",
- "pic",
- "png",
- "pnm",
- "pot",
- "potm",
- "potx",
- "ppa",
- "ppam",
- "ppm",
- "pps",
- "ppsm",
- "ppsx",
- "ppt",
- "pptm",
- "pptx",
- "psd",
- "pya",
- "pyc",
- "pyo",
- "pyv",
- "qt",
- "rar",
- "ras",
- "raw",
- "resources",
- "rgb",
- "rip",
- "rlc",
- "rmf",
- "rmvb",
- "rpm",
- "rtf",
- "rz",
- "s3m",
- "s7z",
- "scpt",
- "sgi",
- "shar",
- "snap",
- "sil",
- "sketch",
- "slk",
- "smv",
- "snk",
- "so",
- "stl",
- "suo",
- "sub",
- "swf",
- "tar",
- "tbz",
- "tbz2",
- "tga",
- "tgz",
- "thmx",
- "tif",
- "tiff",
- "tlz",
- "ttc",
- "ttf",
- "txz",
- "udf",
- "uvh",
- "uvi",
- "uvm",
- "uvp",
- "uvs",
- "uvu",
- "viv",
- "vob",
- "war",
- "wav",
- "wax",
- "wbmp",
- "wdp",
- "weba",
- "webm",
- "webp",
- "whl",
- "wim",
- "wm",
- "wma",
- "wmv",
- "wmx",
- "woff",
- "woff2",
- "wrm",
- "wvx",
- "xbm",
- "xif",
- "xla",
- "xlam",
- "xls",
- "xlsb",
- "xlsm",
- "xlsx",
- "xlt",
- "xltm",
- "xltx",
- "xm",
- "xmind",
- "xpi",
- "xpm",
- "xwd",
- "xz",
- "z",
- "zip",
- "zipx"
- ]);
- FsWatchInstances = new Map;
- FsWatchFileInstances = new Map;
-});
-
-// node_modules/chokidar/esm/index.js
-import { stat as statcb } from "fs";
-import { stat as stat14, readdir as readdir7 } from "fs/promises";
-import { EventEmitter as EventEmitter4 } from "events";
-import * as sysPath2 from "path";
-function arrify(item) {
- return Array.isArray(item) ? item : [item];
-}
-function createPattern(matcher) {
- if (typeof matcher === "function")
- return matcher;
- if (typeof matcher === "string")
- return (string4) => matcher === string4;
- if (matcher instanceof RegExp)
- return (string4) => matcher.test(string4);
- if (typeof matcher === "object" && matcher !== null) {
- return (string4) => {
- if (matcher.path === string4)
- return true;
- if (matcher.recursive) {
- const relative7 = sysPath2.relative(matcher.path, string4);
- if (!relative7) {
- return false;
- }
- return !relative7.startsWith("..") && !sysPath2.isAbsolute(relative7);
- }
- return false;
- };
- }
- return () => false;
-}
-function normalizePath(path15) {
- if (typeof path15 !== "string")
- throw new Error("string expected");
- path15 = sysPath2.normalize(path15);
- path15 = path15.replace(/\\/g, "/");
- let prepend = false;
- if (path15.startsWith("//"))
- prepend = true;
- const DOUBLE_SLASH_RE2 = /\/\//;
- while (path15.match(DOUBLE_SLASH_RE2))
- path15 = path15.replace(DOUBLE_SLASH_RE2, "/");
- if (prepend)
- path15 = "/" + path15;
- return path15;
-}
-function matchPatterns(patterns, testString, stats) {
- const path15 = normalizePath(testString);
- for (let index2 = 0;index2 < patterns.length; index2++) {
- const pattern = patterns[index2];
- if (pattern(path15, stats)) {
- return true;
- }
- }
- return false;
-}
-function anymatch(matchers, testString) {
- if (matchers == null) {
- throw new TypeError("anymatch: specify first argument");
- }
- const matchersArray = arrify(matchers);
- const patterns = matchersArray.map((matcher) => createPattern(matcher));
- if (testString == null) {
- return (testString2, stats) => {
- return matchPatterns(patterns, testString2, stats);
- };
- }
- return matchPatterns(patterns, testString);
-}
-
-class DirEntry {
- constructor(dir, removeWatcher) {
- this.path = dir;
- this._removeWatcher = removeWatcher;
- this.items = new Set;
- }
- add(item) {
- const { items } = this;
- if (!items)
- return;
- if (item !== ONE_DOT && item !== TWO_DOTS)
- items.add(item);
- }
- async remove(item) {
- const { items } = this;
- if (!items)
- return;
- items.delete(item);
- if (items.size > 0)
- return;
- const dir = this.path;
- try {
- await readdir7(dir);
- } catch (err2) {
- if (this._removeWatcher) {
- this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir));
- }
- }
- }
- has(item) {
- const { items } = this;
- if (!items)
- return;
- return items.has(item);
- }
- getChildren() {
- const { items } = this;
- if (!items)
- return [];
- return [...items.values()];
- }
- dispose() {
- this.items.clear();
- this.path = "";
- this._removeWatcher = EMPTY_FN;
- this.items = EMPTY_SET;
- Object.freeze(this);
- }
-}
-
-class WatchHelper {
- constructor(path15, follow, fsw) {
- this.fsw = fsw;
- const watchPath = path15;
- this.path = path15 = path15.replace(REPLACER_RE, "");
- this.watchPath = watchPath;
- this.fullWatchPath = sysPath2.resolve(watchPath);
- this.dirParts = [];
- this.dirParts.forEach((parts) => {
- if (parts.length > 1)
- parts.pop();
- });
- this.followSymlinks = follow;
- this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
- }
- entryPath(entry) {
- return sysPath2.join(this.watchPath, sysPath2.relative(this.watchPath, entry.fullPath));
- }
- filterPath(entry) {
- const { stats } = entry;
- if (stats && stats.isSymbolicLink())
- return this.filterDir(entry);
- const resolvedPath5 = this.entryPath(entry);
- return this.fsw._isntIgnored(resolvedPath5, stats) && this.fsw._hasReadPermissions(stats);
- }
- filterDir(entry) {
- return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
- }
-}
-function watch(paths2, options2 = {}) {
- const watcher = new FSWatcher(options2);
- watcher.add(paths2);
- return watcher;
-}
-var SLASH = "/", SLASH_SLASH = "//", ONE_DOT = ".", TWO_DOTS = "..", STRING_TYPE = "string", BACK_SLASH_RE, DOUBLE_SLASH_RE, DOT_RE, REPLACER_RE, isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp), unifyPaths = (paths_) => {
- const paths2 = arrify(paths_).flat();
- if (!paths2.every((p4) => typeof p4 === STRING_TYPE)) {
- throw new TypeError(`Non-string provided as watch path: ${paths2}`);
- }
- return paths2.map(normalizePathToUnix);
-}, toUnix = (string4) => {
- let str = string4.replace(BACK_SLASH_RE, SLASH);
- let prepend = false;
- if (str.startsWith(SLASH_SLASH)) {
- prepend = true;
- }
- while (str.match(DOUBLE_SLASH_RE)) {
- str = str.replace(DOUBLE_SLASH_RE, SLASH);
- }
- if (prepend) {
- str = SLASH + str;
- }
- return str;
-}, normalizePathToUnix = (path15) => toUnix(sysPath2.normalize(toUnix(path15))), normalizeIgnored = (cwd2 = "") => (path15) => {
- if (typeof path15 === "string") {
- return normalizePathToUnix(sysPath2.isAbsolute(path15) ? path15 : sysPath2.join(cwd2, path15));
- } else {
- return path15;
- }
-}, getAbsolutePath = (path15, cwd2) => {
- if (sysPath2.isAbsolute(path15)) {
- return path15;
- }
- return sysPath2.join(cwd2, path15);
-}, EMPTY_SET, STAT_METHOD_F = "stat", STAT_METHOD_L = "lstat", FSWatcher, esm_default5;
-var init_esm20 = __esm(() => {
- init_esm19();
- init_handler();
- /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
- BACK_SLASH_RE = /\\/g;
- DOUBLE_SLASH_RE = /\/\//;
- DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
- REPLACER_RE = /^\.[/\\]/;
- EMPTY_SET = Object.freeze(new Set);
- FSWatcher = class FSWatcher extends EventEmitter4 {
- constructor(_opts = {}) {
- super();
- this.closed = false;
- this._closers = new Map;
- this._ignoredPaths = new Set;
- this._throttled = new Map;
- this._streams = new Set;
- this._symlinkPaths = new Map;
- this._watched = new Map;
- this._pendingWrites = new Map;
- this._pendingUnlinks = new Map;
- this._readyCount = 0;
- this._readyEmitted = false;
- const awf = _opts.awaitWriteFinish;
- const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };
- const opts = {
- persistent: true,
- ignoreInitial: false,
- ignorePermissionErrors: false,
- interval: 100,
- binaryInterval: 300,
- followSymlinks: true,
- usePolling: false,
- atomic: true,
- ..._opts,
- ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
- awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
- };
- if (isIBMi)
- opts.usePolling = true;
- if (opts.atomic === undefined)
- opts.atomic = !opts.usePolling;
- const envPoll = process.env.CHOKIDAR_USEPOLLING;
- if (envPoll !== undefined) {
- const envLower = envPoll.toLowerCase();
- if (envLower === "false" || envLower === "0")
- opts.usePolling = false;
- else if (envLower === "true" || envLower === "1")
- opts.usePolling = true;
- else
- opts.usePolling = !!envLower;
- }
- const envInterval = process.env.CHOKIDAR_INTERVAL;
- if (envInterval)
- opts.interval = Number.parseInt(envInterval, 10);
- let readyCalls = 0;
- this._emitReady = () => {
- readyCalls++;
- if (readyCalls >= this._readyCount) {
- this._emitReady = EMPTY_FN;
- this._readyEmitted = true;
- process.nextTick(() => this.emit(EVENTS.READY));
- }
- };
- this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
- this._boundRemove = this._remove.bind(this);
- this.options = opts;
- this._nodeFsHandler = new NodeFsHandler(this);
- Object.freeze(opts);
- }
- _addIgnoredPath(matcher) {
- if (isMatcherObject(matcher)) {
- for (const ignored of this._ignoredPaths) {
- if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
- return;
- }
- }
- }
- this._ignoredPaths.add(matcher);
- }
- _removeIgnoredPath(matcher) {
- this._ignoredPaths.delete(matcher);
- if (typeof matcher === "string") {
- for (const ignored of this._ignoredPaths) {
- if (isMatcherObject(ignored) && ignored.path === matcher) {
- this._ignoredPaths.delete(ignored);
- }
- }
- }
- }
- add(paths_, _origAdd, _internal) {
- const { cwd: cwd2 } = this.options;
- this.closed = false;
- this._closePromise = undefined;
- let paths2 = unifyPaths(paths_);
- if (cwd2) {
- paths2 = paths2.map((path15) => {
- const absPath = getAbsolutePath(path15, cwd2);
- return absPath;
- });
- }
- paths2.forEach((path15) => {
- this._removeIgnoredPath(path15);
- });
- this._userIgnored = undefined;
- if (!this._readyCount)
- this._readyCount = 0;
- this._readyCount += paths2.length;
- Promise.all(paths2.map(async (path15) => {
- const res = await this._nodeFsHandler._addToNodeFs(path15, !_internal, undefined, 0, _origAdd);
- if (res)
- this._emitReady();
- return res;
- })).then((results) => {
- if (this.closed)
- return;
- results.forEach((item) => {
- if (item)
- this.add(sysPath2.dirname(item), sysPath2.basename(_origAdd || item));
- });
- });
- return this;
- }
- unwatch(paths_) {
- if (this.closed)
- return this;
- const paths2 = unifyPaths(paths_);
- const { cwd: cwd2 } = this.options;
- paths2.forEach((path15) => {
- if (!sysPath2.isAbsolute(path15) && !this._closers.has(path15)) {
- if (cwd2)
- path15 = sysPath2.join(cwd2, path15);
- path15 = sysPath2.resolve(path15);
- }
- this._closePath(path15);
- this._addIgnoredPath(path15);
- if (this._watched.has(path15)) {
- this._addIgnoredPath({
- path: path15,
- recursive: true
- });
- }
- this._userIgnored = undefined;
- });
- return this;
- }
- close() {
- if (this._closePromise) {
- return this._closePromise;
- }
- this.closed = true;
- this.removeAllListeners();
- const closers = [];
- this._closers.forEach((closerList) => closerList.forEach((closer) => {
- const promise2 = closer();
- if (promise2 instanceof Promise)
- closers.push(promise2);
- }));
- this._streams.forEach((stream10) => stream10.destroy());
- this._userIgnored = undefined;
- this._readyCount = 0;
- this._readyEmitted = false;
- this._watched.forEach((dirent) => dirent.dispose());
- this._closers.clear();
- this._watched.clear();
- this._streams.clear();
- this._symlinkPaths.clear();
- this._throttled.clear();
- this._closePromise = closers.length ? Promise.all(closers).then(() => {
- return;
- }) : Promise.resolve();
- return this._closePromise;
- }
- getWatched() {
- const watchList = {};
- this._watched.forEach((entry, dir) => {
- const key2 = this.options.cwd ? sysPath2.relative(this.options.cwd, dir) : dir;
- const index2 = key2 || ONE_DOT;
- watchList[index2] = entry.getChildren().sort();
- });
- return watchList;
- }
- emitWithAll(event, args) {
- this.emit(event, ...args);
- if (event !== EVENTS.ERROR)
- this.emit(EVENTS.ALL, event, ...args);
- }
- async _emit(event, path15, stats) {
- if (this.closed)
- return;
- const opts = this.options;
- if (isWindows2)
- path15 = sysPath2.normalize(path15);
- if (opts.cwd)
- path15 = sysPath2.relative(opts.cwd, path15);
- const args = [path15];
- if (stats != null)
- args.push(stats);
- const awf = opts.awaitWriteFinish;
- let pw;
- if (awf && (pw = this._pendingWrites.get(path15))) {
- pw.lastChange = new Date;
- return this;
- }
- if (opts.atomic) {
- if (event === EVENTS.UNLINK) {
- this._pendingUnlinks.set(path15, [event, ...args]);
- setTimeout(() => {
- this._pendingUnlinks.forEach((entry, path16) => {
- this.emit(...entry);
- this.emit(EVENTS.ALL, ...entry);
- this._pendingUnlinks.delete(path16);
- });
- }, typeof opts.atomic === "number" ? opts.atomic : 100);
- return this;
- }
- if (event === EVENTS.ADD && this._pendingUnlinks.has(path15)) {
- event = EVENTS.CHANGE;
- this._pendingUnlinks.delete(path15);
- }
- }
- if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
- const awfEmit = (err2, stats2) => {
- if (err2) {
- event = EVENTS.ERROR;
- args[0] = err2;
- this.emitWithAll(event, args);
- } else if (stats2) {
- if (args.length > 1) {
- args[1] = stats2;
- } else {
- args.push(stats2);
- }
- this.emitWithAll(event, args);
- }
- };
- this._awaitWriteFinish(path15, awf.stabilityThreshold, event, awfEmit);
- return this;
- }
- if (event === EVENTS.CHANGE) {
- const isThrottled = !this._throttle(EVENTS.CHANGE, path15, 50);
- if (isThrottled)
- return this;
- }
- if (opts.alwaysStat && stats === undefined && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
- const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path15) : path15;
- let stats2;
- try {
- stats2 = await stat14(fullPath);
- } catch (err2) {}
- if (!stats2 || this.closed)
- return;
- args.push(stats2);
- }
- this.emitWithAll(event, args);
- return this;
- }
- _handleError(error46) {
- const code = error46 && error46.code;
- if (error46 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
- this.emit(EVENTS.ERROR, error46);
- }
- return error46 || this.closed;
- }
- _throttle(actionType, path15, timeout) {
- if (!this._throttled.has(actionType)) {
- this._throttled.set(actionType, new Map);
- }
- const action = this._throttled.get(actionType);
- if (!action)
- throw new Error("invalid throttle");
- const actionPath = action.get(path15);
- if (actionPath) {
- actionPath.count++;
- return false;
- }
- let timeoutObject;
- const clear = () => {
- const item = action.get(path15);
- const count3 = item ? item.count : 0;
- action.delete(path15);
- clearTimeout(timeoutObject);
- if (item)
- clearTimeout(item.timeoutObject);
- return count3;
- };
- timeoutObject = setTimeout(clear, timeout);
- const thr = { timeoutObject, clear, count: 0 };
- action.set(path15, thr);
- return thr;
- }
- _incrReadyCount() {
- return this._readyCount++;
- }
- _awaitWriteFinish(path15, threshold, event, awfEmit) {
- const awf = this.options.awaitWriteFinish;
- if (typeof awf !== "object")
- return;
- const pollInterval = awf.pollInterval;
- let timeoutHandler;
- let fullPath = path15;
- if (this.options.cwd && !sysPath2.isAbsolute(path15)) {
- fullPath = sysPath2.join(this.options.cwd, path15);
- }
- const now2 = new Date;
- const writes = this._pendingWrites;
- function awaitWriteFinishFn(prevStat) {
- statcb(fullPath, (err2, curStat) => {
- if (err2 || !writes.has(path15)) {
- if (err2 && err2.code !== "ENOENT")
- awfEmit(err2);
- return;
- }
- const now3 = Number(new Date);
- if (prevStat && curStat.size !== prevStat.size) {
- writes.get(path15).lastChange = now3;
- }
- const pw = writes.get(path15);
- const df = now3 - pw.lastChange;
- if (df >= threshold) {
- writes.delete(path15);
- awfEmit(undefined, curStat);
- } else {
- timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
- }
- });
- }
- if (!writes.has(path15)) {
- writes.set(path15, {
- lastChange: now2,
- cancelWait: () => {
- writes.delete(path15);
- clearTimeout(timeoutHandler);
- return event;
- }
- });
- timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
- }
- }
- _isIgnored(path15, stats) {
- if (this.options.atomic && DOT_RE.test(path15))
- return true;
- if (!this._userIgnored) {
- const { cwd: cwd2 } = this.options;
- const ign = this.options.ignored;
- const ignored = (ign || []).map(normalizeIgnored(cwd2));
- const ignoredPaths = [...this._ignoredPaths];
- const list2 = [...ignoredPaths.map(normalizeIgnored(cwd2)), ...ignored];
- this._userIgnored = anymatch(list2, undefined);
- }
- return this._userIgnored(path15, stats);
- }
- _isntIgnored(path15, stat15) {
- return !this._isIgnored(path15, stat15);
- }
- _getWatchHelpers(path15) {
- return new WatchHelper(path15, this.options.followSymlinks, this);
- }
- _getWatchedDir(directory) {
- const dir = sysPath2.resolve(directory);
- if (!this._watched.has(dir))
- this._watched.set(dir, new DirEntry(dir, this._boundRemove));
- return this._watched.get(dir);
- }
- _hasReadPermissions(stats) {
- if (this.options.ignorePermissionErrors)
- return true;
- return Boolean(Number(stats.mode) & 256);
- }
- _remove(directory, item, isDirectory) {
- const path15 = sysPath2.join(directory, item);
- const fullPath = sysPath2.resolve(path15);
- isDirectory = isDirectory != null ? isDirectory : this._watched.has(path15) || this._watched.has(fullPath);
- if (!this._throttle("remove", path15, 100))
- return;
- if (!isDirectory && this._watched.size === 1) {
- this.add(directory, item, true);
- }
- const wp = this._getWatchedDir(path15);
- const nestedDirectoryChildren = wp.getChildren();
- nestedDirectoryChildren.forEach((nested) => this._remove(path15, nested));
- const parent = this._getWatchedDir(directory);
- const wasTracked = parent.has(item);
- parent.remove(item);
- if (this._symlinkPaths.has(fullPath)) {
- this._symlinkPaths.delete(fullPath);
- }
- let relPath = path15;
- if (this.options.cwd)
- relPath = sysPath2.relative(this.options.cwd, path15);
- if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
- const event = this._pendingWrites.get(relPath).cancelWait();
- if (event === EVENTS.ADD)
- return;
- }
- this._watched.delete(path15);
- this._watched.delete(fullPath);
- const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
- if (wasTracked && !this._isIgnored(path15))
- this._emit(eventName, path15);
- this._closePath(path15);
- }
- _closePath(path15) {
- this._closeFile(path15);
- const dir = sysPath2.dirname(path15);
- this._getWatchedDir(dir).remove(sysPath2.basename(path15));
- }
- _closeFile(path15) {
- const closers = this._closers.get(path15);
- if (!closers)
- return;
- closers.forEach((closer) => closer());
- this._closers.delete(path15);
- }
- _addPathCloser(path15, closer) {
- if (!closer)
- return;
- let list2 = this._closers.get(path15);
- if (!list2) {
- list2 = [];
- this._closers.set(path15, list2);
- }
- list2.push(closer);
- }
- _readdirp(root2, opts) {
- if (this.closed)
- return;
- const options2 = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
- let stream10 = readdirp(root2, options2);
- this._streams.add(stream10);
- stream10.once(STR_CLOSE, () => {
- stream10 = undefined;
- });
- stream10.once(STR_END, () => {
- if (stream10) {
- this._streams.delete(stream10);
- stream10 = undefined;
- }
- });
- return stream10;
- }
- };
- esm_default5 = { watch, FSWatcher };
-});
-
-// src/utils/settings/changeDetector.ts
-import { stat as stat15 } from "fs/promises";
-import * as platformPath from "path";
-async function initialize() {
- if (getIsRemoteMode())
- return;
- if (initialized || disposed)
- return;
- initialized = true;
- startMdmPoll();
- registerCleanup(dispose);
- const { dirs, settingsFiles, dropInDir } = await getWatchTargets();
- if (disposed)
- return;
- if (dirs.length === 0)
- return;
- logForDebugging(`Watching for changes in setting files ${[...settingsFiles].join(", ")}...${dropInDir ? ` and drop-in directory ${dropInDir}` : ""}`);
- watcher = esm_default5.watch(dirs, {
- persistent: true,
- ignoreInitial: true,
- depth: 0,
- awaitWriteFinish: {
- stabilityThreshold: testOverrides?.stabilityThreshold ?? FILE_STABILITY_THRESHOLD_MS,
- pollInterval: testOverrides?.pollInterval ?? FILE_STABILITY_POLL_INTERVAL_MS
- },
- ignored: (path15, stats) => {
- if (stats && !stats.isFile() && !stats.isDirectory())
- return true;
- if (path15.split(platformPath.sep).some((dir) => dir === ".git"))
- return true;
- if (!stats || stats.isDirectory())
- return false;
- const normalized = platformPath.normalize(path15);
- if (settingsFiles.has(normalized))
- return false;
- if (dropInDir && normalized.startsWith(dropInDir + platformPath.sep) && normalized.endsWith(".json")) {
- return false;
- }
- return true;
- },
- ignorePermissionErrors: true,
- usePolling: false,
- atomic: true
- });
- watcher.on("change", handleChange2);
- watcher.on("unlink", handleDelete);
- watcher.on("add", handleAdd);
-}
-function dispose() {
- disposed = true;
- if (mdmPollTimer) {
- clearInterval(mdmPollTimer);
- mdmPollTimer = null;
- }
- for (const timer of pendingDeletions.values())
- clearTimeout(timer);
- pendingDeletions.clear();
- lastMdmSnapshot = null;
- clearInternalWrites();
- settingsChanged.clear();
- const w2 = watcher;
- watcher = null;
- return w2 ? w2.close() : Promise.resolve();
-}
-async function getWatchTargets() {
- const dirToSettingsFiles = new Map;
- const dirsWithExistingFiles = new Set;
- for (const source of SETTING_SOURCES) {
- if (source === "flagSettings") {
- continue;
- }
- const path15 = getSettingsFilePathForSource(source);
- if (!path15) {
- continue;
- }
- const dir = platformPath.dirname(path15);
- if (!dirToSettingsFiles.has(dir)) {
- dirToSettingsFiles.set(dir, new Set);
- }
- dirToSettingsFiles.get(dir).add(path15);
- try {
- const stats = await stat15(path15);
- if (stats.isFile()) {
- dirsWithExistingFiles.add(dir);
- }
- } catch {}
- }
- const settingsFiles = new Set;
- for (const dir of dirsWithExistingFiles) {
- const filesInDir = dirToSettingsFiles.get(dir);
- if (filesInDir) {
- for (const file2 of filesInDir) {
- settingsFiles.add(file2);
- }
- }
- }
- let dropInDir = null;
- const managedDropIn = getManagedSettingsDropInDir();
- try {
- const stats = await stat15(managedDropIn);
- if (stats.isDirectory()) {
- dirsWithExistingFiles.add(managedDropIn);
- dropInDir = managedDropIn;
- }
- } catch {}
- return { dirs: [...dirsWithExistingFiles], settingsFiles, dropInDir };
-}
-function settingSourceToConfigChangeSource(source) {
- switch (source) {
- case "userSettings":
- return "user_settings";
- case "projectSettings":
- return "project_settings";
- case "localSettings":
- return "local_settings";
- case "flagSettings":
- case "policySettings":
- return "policy_settings";
- }
-}
-function handleChange2(path15) {
- const source = getSourceForPath(path15);
- if (!source)
- return;
- const pendingTimer = pendingDeletions.get(path15);
- if (pendingTimer) {
- clearTimeout(pendingTimer);
- pendingDeletions.delete(path15);
- logForDebugging(`Cancelled pending deletion of ${path15} \u2014 file was recreated`);
- }
- if (consumeInternalWrite(path15, INTERNAL_WRITE_WINDOW_MS)) {
- return;
- }
- logForDebugging(`Detected change to ${path15}`);
- executeConfigChangeHooks(settingSourceToConfigChangeSource(source), path15).then((results) => {
- if (hasBlockingResult(results)) {
- logForDebugging(`ConfigChange hook blocked change to ${path15}`);
- return;
- }
- fanOut(source);
- });
-}
-function handleAdd(path15) {
- const source = getSourceForPath(path15);
- if (!source)
- return;
- const pendingTimer = pendingDeletions.get(path15);
- if (pendingTimer) {
- clearTimeout(pendingTimer);
- pendingDeletions.delete(path15);
- logForDebugging(`Cancelled pending deletion of ${path15} \u2014 file was re-added`);
- }
- handleChange2(path15);
-}
-function handleDelete(path15) {
- const source = getSourceForPath(path15);
- if (!source)
- return;
- logForDebugging(`Detected deletion of ${path15}`);
- if (pendingDeletions.has(path15))
- return;
- const timer = setTimeout((p4, src) => {
- pendingDeletions.delete(p4);
- executeConfigChangeHooks(settingSourceToConfigChangeSource(src), p4).then((results) => {
- if (hasBlockingResult(results)) {
- logForDebugging(`ConfigChange hook blocked deletion of ${p4}`);
- return;
- }
- fanOut(src);
- });
- }, testOverrides?.deletionGrace ?? DELETION_GRACE_MS, path15, source);
- pendingDeletions.set(path15, timer);
-}
-function getSourceForPath(path15) {
- const normalizedPath = platformPath.normalize(path15);
- const dropInDir = getManagedSettingsDropInDir();
- if (normalizedPath.startsWith(dropInDir + platformPath.sep)) {
- return "policySettings";
- }
- return SETTING_SOURCES.find((source) => getSettingsFilePathForSource(source) === normalizedPath);
-}
-function startMdmPoll() {
- const initial = getMdmSettings();
- const initialHkcu = getHkcuSettings();
- lastMdmSnapshot = jsonStringify({
- mdm: initial.settings,
- hkcu: initialHkcu.settings
- });
- mdmPollTimer = setInterval(() => {
- if (disposed)
- return;
- (async () => {
- try {
- const { mdm: current, hkcu: currentHkcu } = await refreshMdmSettings();
- if (disposed)
- return;
- const currentSnapshot = jsonStringify({
- mdm: current.settings,
- hkcu: currentHkcu.settings
- });
- if (currentSnapshot !== lastMdmSnapshot) {
- lastMdmSnapshot = currentSnapshot;
- setMdmSettingsCache(current, currentHkcu);
- logForDebugging("Detected MDM settings change via poll");
- fanOut("policySettings");
- }
- } catch (error46) {
- logForDebugging(`MDM poll error: ${errorMessage(error46)}`);
- }
- })();
- }, testOverrides?.mdmPollInterval ?? MDM_POLL_INTERVAL_MS);
- mdmPollTimer.unref();
-}
-function fanOut(source) {
- resetSettingsCache();
- settingsChanged.emit(source);
-}
-function notifyChange(source) {
- logForDebugging(`Programmatic settings change notification for ${source}`);
- fanOut(source);
-}
-function resetForTesting(overrides) {
- if (mdmPollTimer) {
- clearInterval(mdmPollTimer);
- mdmPollTimer = null;
- }
- for (const timer of pendingDeletions.values())
- clearTimeout(timer);
- pendingDeletions.clear();
- lastMdmSnapshot = null;
- initialized = false;
- disposed = false;
- testOverrides = overrides ?? null;
- const w2 = watcher;
- watcher = null;
- return w2 ? w2.close() : Promise.resolve();
-}
-var FILE_STABILITY_THRESHOLD_MS = 1000, FILE_STABILITY_POLL_INTERVAL_MS = 500, INTERNAL_WRITE_WINDOW_MS = 5000, MDM_POLL_INTERVAL_MS, DELETION_GRACE_MS, watcher = null, mdmPollTimer = null, lastMdmSnapshot = null, initialized = false, disposed = false, pendingDeletions, settingsChanged, testOverrides = null, subscribe2, settingsChangeDetector;
-var init_changeDetector = __esm(() => {
- init_esm20();
- init_state();
- init_cleanupRegistry();
- init_debug();
- init_errors();
- init_hooks3();
- init_slowOperations();
- init_constants2();
- init_internalWrites();
- init_managedPath();
- init_settings();
- init_settings2();
- init_settingsCache();
- MDM_POLL_INTERVAL_MS = 30 * 60 * 1000;
- DELETION_GRACE_MS = FILE_STABILITY_THRESHOLD_MS + FILE_STABILITY_POLL_INTERVAL_MS + 200;
- pendingDeletions = new Map;
- settingsChanged = createSignal();
- subscribe2 = settingsChanged.subscribe;
- settingsChangeDetector = {
- initialize,
- dispose,
- subscribe: subscribe2,
- notifyChange,
- resetForTesting
- };
-});
-
-// src/tools/WebFetchTool/prompt.ts
-function makeSecondaryModelPrompt(markdownContent, prompt, isPreapprovedDomain) {
- const guidelines = isPreapprovedDomain ? `Provide a concise response based on the content above. Include relevant details, code examples, and documentation excerpts as needed.` : `Provide a concise response based only on the content above. In your response:
- - Enforce a strict 125-character maximum for quotes from any source document. Open Source Software is ok as long as we respect the license.
- - Use quotation marks for exact language from articles; any language outside of the quotation should never be word-for-word the same.
- - You are not a lawyer and never comment on the legality of your own prompts and responses.
- - Never produce or reproduce exact song lyrics.`;
- return `
-Web page content:
----
-${markdownContent}
----
-
-${prompt}
-
-${guidelines}
-`;
-}
-var WEB_FETCH_TOOL_NAME = "WebFetch", DESCRIPTION4 = `
-- Fetches content from a specified URL and processes it using an AI model
-- Takes a URL and a prompt as input
-- Fetches the URL content, converts HTML to markdown
-- Processes the content with the prompt using a small, fast model
-- Returns the model's response about the content
-- Use this tool when you need to retrieve and analyze web content
-
-Usage notes:
- - IMPORTANT: If an MCP-provided web fetch tool is available, prefer using that tool instead of this one, as it may have fewer restrictions.
- - The URL must be a fully-formed valid URL
- - HTTP URLs will be automatically upgraded to HTTPS
- - The prompt should describe what information you want to extract from the page
- - This tool is read-only and does not modify any files
- - Results may be summarized if the content is very large
- - Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL
- - When a URL redirects to a different host, the tool will inform you and provide the redirect URL in a special format. You should then make a new WebFetch request with the redirect URL to fetch the content.
- - For GitHub URLs, prefer using the gh CLI via Bash instead (e.g., gh pr view, gh issue view, gh api).
-`;
-
-// src/utils/ripgrep.ts
-import { execFile as execFile9, spawn as spawn2 } from "child_process";
-import { homedir as homedir12 } from "os";
-import * as path15 from "path";
-import { fileURLToPath as fileURLToPath4 } from "url";
-function ripgrepCommand() {
- const config9 = getRipgrepConfig();
- return {
- rgPath: config9.command,
- rgArgs: config9.args,
- argv0: config9.argv0
- };
-}
-function isEagainError(stderr) {
- return stderr.includes("os error 11") || stderr.includes("Resource temporarily unavailable");
-}
-function ripGrepRaw(args, target, abortSignal, callback, singleThread = false) {
- const { rgPath, rgArgs, argv0 } = ripgrepCommand();
- const threadArgs = singleThread ? ["-j", "1"] : [];
- const fullArgs = [...rgArgs, ...threadArgs, ...args, target];
- const defaultTimeout = getPlatform() === "wsl" ? 60000 : 20000;
- const parsedSeconds = parseInt(process.env.CLAUDE_CODE_GLOB_TIMEOUT_SECONDS || "", 10) || 0;
- const timeout = parsedSeconds > 0 ? parsedSeconds * 1000 : defaultTimeout;
- if (argv0) {
- const child = spawn2(rgPath, fullArgs, {
- argv0,
- signal: abortSignal,
- windowsHide: true
- });
- let stdout = "";
- let stderr = "";
- let stdoutTruncated = false;
- let stderrTruncated = false;
- child.stdout?.on("data", (data) => {
- if (!stdoutTruncated) {
- stdout += data.toString();
- if (stdout.length > MAX_BUFFER_SIZE) {
- stdout = stdout.slice(0, MAX_BUFFER_SIZE);
- stdoutTruncated = true;
- }
- }
- });
- child.stderr?.on("data", (data) => {
- if (!stderrTruncated) {
- stderr += data.toString();
- if (stderr.length > MAX_BUFFER_SIZE) {
- stderr = stderr.slice(0, MAX_BUFFER_SIZE);
- stderrTruncated = true;
- }
- }
- });
- let killTimeoutId;
- const timeoutId = setTimeout(() => {
- if (process.platform === "win32") {
- child.kill();
- } else {
- child.kill("SIGTERM");
- killTimeoutId = setTimeout((c8) => c8.kill("SIGKILL"), 5000, child);
- }
- }, timeout);
- let settled = false;
- child.on("close", (code, signal) => {
- if (settled)
- return;
- settled = true;
- clearTimeout(timeoutId);
- clearTimeout(killTimeoutId);
- if (code === 0 || code === 1) {
- callback(null, stdout, stderr);
- } else {
- const error46 = new Error(`ripgrep exited with code ${code}`);
- error46.code = code ?? undefined;
- error46.signal = signal ?? undefined;
- callback(error46, stdout, stderr);
- }
- });
- child.on("error", (err2) => {
- if (settled)
- return;
- settled = true;
- clearTimeout(timeoutId);
- clearTimeout(killTimeoutId);
- const error46 = err2;
- callback(error46, stdout, stderr);
- });
- return child;
- }
- return execFile9(rgPath, fullArgs, {
- maxBuffer: MAX_BUFFER_SIZE,
- signal: abortSignal,
- timeout,
- killSignal: process.platform === "win32" ? undefined : "SIGKILL"
- }, callback);
-}
-async function ripGrepFileCount(args, target, abortSignal) {
- await codesignRipgrepIfNecessary();
- const { rgPath, rgArgs, argv0 } = ripgrepCommand();
- return new Promise((resolve17, reject) => {
- const child = spawn2(rgPath, [...rgArgs, ...args, target], {
- argv0,
- signal: abortSignal,
- windowsHide: true,
- stdio: ["ignore", "pipe", "ignore"]
- });
- let lines2 = 0;
- child.stdout?.on("data", (chunk) => {
- lines2 += countCharInString(chunk, `
-`);
- });
- let settled = false;
- child.on("close", (code) => {
- if (settled)
- return;
- settled = true;
- if (code === 0 || code === 1)
- resolve17(lines2);
- else
- reject(new Error(`rg --files exited ${code}`));
- });
- child.on("error", (err2) => {
- if (settled)
- return;
- settled = true;
- reject(err2);
- });
- });
-}
-async function ripGrep(args, target, abortSignal) {
- await codesignRipgrepIfNecessary();
- testRipgrepOnFirstUse().catch((error46) => {
- logError2(error46);
- });
- return new Promise((resolve17, reject) => {
- const handleResult3 = (error46, stdout, stderr, isRetry) => {
- if (!error46) {
- resolve17(stdout.trim().split(`
-`).map((line) => line.replace(/\r$/, "")).filter(Boolean));
- return;
- }
- if (error46.code === 1) {
- resolve17([]);
- return;
- }
- const CRITICAL_ERROR_CODES = ["ENOENT", "EACCES", "EPERM"];
- if (CRITICAL_ERROR_CODES.includes(error46.code)) {
- reject(error46);
- return;
- }
- if (!isRetry && isEagainError(stderr)) {
- logForDebugging(`rg EAGAIN error detected, retrying with single-threaded mode (-j 1)`);
- logEvent("tengu_ripgrep_eagain_retry", {});
- ripGrepRaw(args, target, abortSignal, (retryError, retryStdout, retryStderr) => {
- handleResult3(retryError, retryStdout, retryStderr, true);
- }, true);
- return;
- }
- const hasOutput = stdout && stdout.trim().length > 0;
- const isTimeout = error46.signal === "SIGTERM" || error46.signal === "SIGKILL" || error46.code === "ABORT_ERR";
- const isBufferOverflow = error46.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
- let lines2 = [];
- if (hasOutput) {
- lines2 = stdout.trim().split(`
-`).map((line) => line.replace(/\r$/, "")).filter(Boolean);
- if (lines2.length > 0 && (isTimeout || isBufferOverflow)) {
- lines2 = lines2.slice(0, -1);
- }
- }
- logForDebugging(`rg error (signal=${error46.signal}, code=${error46.code}, stderr: ${stderr}), ${lines2.length} results`);
- if (error46.code !== 2 && error46.code !== "ABORT_ERR") {
- logError2(error46);
- }
- if (isTimeout && lines2.length === 0) {
- reject(new RipgrepTimeoutError(`Ripgrep search timed out after ${getPlatform() === "wsl" ? 60 : 20} seconds. The search may have matched files but did not complete in time. Try searching a more specific path or pattern.`, lines2));
- return;
- }
- resolve17(lines2);
- };
- ripGrepRaw(args, target, abortSignal, (error46, stdout, stderr) => {
- handleResult3(error46, stdout, stderr, false);
- });
- });
-}
-function getRipgrepStatus() {
- const config9 = getRipgrepConfig();
- return {
- mode: config9.mode,
- path: config9.command,
- working: ripgrepStatus?.working ?? null
- };
-}
-async function codesignRipgrepIfNecessary() {
- if (process.platform !== "darwin" || alreadyDoneSignCheck) {
- return;
- }
- alreadyDoneSignCheck = true;
- const config9 = getRipgrepConfig();
- if (config9.mode !== "builtin") {
- return;
- }
- const builtinPath = config9.command;
- const lines2 = (await execFileNoThrow("codesign", ["-vv", "-d", builtinPath], {
- preserveOutputOnError: false
- })).stdout.split(`
-`);
- const needsSigned = lines2.find((line) => line.includes("linker-signed"));
- if (!needsSigned) {
- return;
- }
- try {
- const signResult = await execFileNoThrow("codesign", [
- "--sign",
- "-",
- "--force",
- "--preserve-metadata=entitlements,requirements,flags,runtime",
- builtinPath
- ]);
- if (signResult.code !== 0) {
- logError2(new Error(`Failed to sign ripgrep: ${signResult.stdout} ${signResult.stderr}`));
- }
- const quarantineResult = await execFileNoThrow("xattr", [
- "-d",
- "com.apple.quarantine",
- builtinPath
- ]);
- if (quarantineResult.code !== 0) {
- logError2(new Error(`Failed to remove quarantine: ${quarantineResult.stdout} ${quarantineResult.stderr}`));
- }
- } catch (e4) {
- logError2(e4);
- }
-}
-var __filename2, __dirname3, getRipgrepConfig, MAX_BUFFER_SIZE = 20000000, RipgrepTimeoutError, countFilesRoundedRg, ripgrepStatus = null, testRipgrepOnFirstUse, alreadyDoneSignCheck = false;
-var init_ripgrep = __esm(() => {
- init_memoize();
- init_analytics();
- init_debug();
- init_envUtils();
- init_execFileNoThrow();
- init_findExecutable();
- init_log2();
- init_platform2();
- init_stringUtils();
- __filename2 = fileURLToPath4(import.meta.url);
- __dirname3 = path15.join(__filename2, "../");
- getRipgrepConfig = memoize_default(() => {
- const userWantsSystemRipgrep = isEnvDefinedFalsy(process.env.USE_BUILTIN_RIPGREP);
- if (userWantsSystemRipgrep) {
- const { cmd: systemPath } = findExecutable("rg", []);
- if (systemPath !== "rg") {
- return { mode: "system", command: "rg", args: [] };
- }
- }
- if (isInBundledMode()) {
- return {
- mode: "embedded",
- command: process.execPath,
- args: ["--no-config"],
- argv0: "rg"
- };
- }
- const rgRoot = path15.resolve(__dirname3, "vendor", "ripgrep");
- const command12 = process.platform === "win32" ? path15.resolve(rgRoot, `${process.arch}-win32`, "rg.exe") : path15.resolve(rgRoot, `${process.arch}-${process.platform}`, "rg");
- return { mode: "builtin", command: command12, args: [] };
- });
- RipgrepTimeoutError = class RipgrepTimeoutError extends Error {
- partialResults;
- constructor(message, partialResults) {
- super(message);
- this.partialResults = partialResults;
- this.name = "RipgrepTimeoutError";
- }
- };
- countFilesRoundedRg = memoize_default(async (dirPath, abortSignal, ignorePatterns = []) => {
- if (path15.resolve(dirPath) === path15.resolve(homedir12())) {
- return;
- }
- try {
- const args = ["--files", "--hidden"];
- ignorePatterns.forEach((pattern) => {
- args.push("--glob", `!${pattern}`);
- });
- const count3 = await ripGrepFileCount(args, dirPath, abortSignal);
- if (count3 === 0)
- return 0;
- const magnitude = Math.floor(Math.log10(count3));
- const power = Math.pow(10, magnitude);
- return Math.round(count3 / power) * power;
- } catch (error46) {
- if (error46?.name !== "AbortError")
- logError2(error46);
- }
- }, (dirPath, _abortSignal, ignorePatterns = []) => `${dirPath}|${ignorePatterns.join(",")}`);
- testRipgrepOnFirstUse = memoize_default(async () => {
- if (ripgrepStatus !== null) {
- return;
- }
- const config9 = getRipgrepConfig();
- try {
- let test2;
- if (config9.argv0) {
- const proc = Bun.spawn([config9.command, "--version"], {
- argv0: config9.argv0,
- stderr: "ignore",
- stdout: "pipe"
- });
- const [stdout, code] = await Promise.all([
- proc.stdout.text(),
- proc.exited
- ]);
- test2 = {
- code,
- stdout
- };
- } else {
- test2 = await execFileNoThrow(config9.command, [...config9.args, "--version"], {
- timeout: 5000
- });
- }
- const working = test2.code === 0 && !!test2.stdout && test2.stdout.startsWith("ripgrep ");
- ripgrepStatus = {
- working,
- lastTested: Date.now(),
- config: config9
- };
- logForDebugging(`Ripgrep first use test: ${working ? "PASSED" : "FAILED"} (mode=${config9.mode}, path=${config9.command})`);
- logEvent("tengu_ripgrep_availability", {
- working: working ? 1 : 0,
- using_system: config9.mode === "system" ? 1 : 0
- });
- } catch (error46) {
- ripgrepStatus = {
- working: false,
- lastTested: Date.now(),
- config: config9
- };
- logError2(error46);
- }
- });
-});
-
-// src/utils/sandbox/sandbox-adapter.ts
-var exports_sandbox_adapter = {};
-__export(exports_sandbox_adapter, {
- shouldAllowManagedSandboxDomainsOnly: () => shouldAllowManagedSandboxDomainsOnly,
- resolveSandboxFilesystemPath: () => resolveSandboxFilesystemPath,
- resolvePathPatternForSandbox: () => resolvePathPatternForSandbox,
- convertToSandboxRuntimeConfig: () => convertToSandboxRuntimeConfig,
- addToExcludedCommands: () => addToExcludedCommands,
- SandboxViolationStore: () => import_sandbox_runtime.SandboxViolationStore,
- SandboxRuntimeConfigSchema: () => import_sandbox_runtime.SandboxRuntimeConfigSchema,
- SandboxManager: () => SandboxManager
-});
-import { rmSync as rmSync2, statSync as statSync8 } from "fs";
-import { readFile as readFile14 } from "fs/promises";
-import { join as join44, resolve as resolve17, sep as sep11 } from "path";
-function permissionRuleValueFromString2(ruleString) {
- const matches = ruleString.match(/^([^(]+)\(([^)]+)\)$/);
- if (!matches) {
- return { toolName: ruleString };
- }
- const toolName = matches[1];
- const ruleContent = matches[2];
- if (!toolName || !ruleContent) {
- return { toolName: ruleString };
- }
- return { toolName, ruleContent };
-}
-function permissionRuleExtractPrefix(permissionRule) {
- const match = permissionRule.match(/^(.+):\*$/);
- return match?.[1] ?? null;
-}
-function resolvePathPatternForSandbox(pattern, source) {
- if (pattern.startsWith("//")) {
- return pattern.slice(1);
- }
- if (pattern.startsWith("/") && !pattern.startsWith("//")) {
- const root2 = getSettingsRootPathForSource(source);
- return resolve17(root2, pattern.slice(1));
- }
- return pattern;
-}
-function resolveSandboxFilesystemPath(pattern, source) {
- if (pattern.startsWith("//"))
- return pattern.slice(1);
- return expandPath(pattern, getSettingsRootPathForSource(source));
-}
-function shouldAllowManagedSandboxDomainsOnly() {
- return getSettingsForSource("policySettings")?.sandbox?.network?.allowManagedDomainsOnly === true;
-}
-function shouldAllowManagedReadPathsOnly() {
- return getSettingsForSource("policySettings")?.sandbox?.filesystem?.allowManagedReadPathsOnly === true;
-}
-function convertToSandboxRuntimeConfig(settings) {
- const permissions = settings.permissions || {};
- const allowedDomains = [];
- const deniedDomains = [];
- if (shouldAllowManagedSandboxDomainsOnly()) {
- const policySettings = getSettingsForSource("policySettings");
- for (const domain2 of policySettings?.sandbox?.network?.allowedDomains || []) {
- allowedDomains.push(domain2);
- }
- for (const ruleString of policySettings?.permissions?.allow || []) {
- const rule = permissionRuleValueFromString2(ruleString);
- if (rule.toolName === WEB_FETCH_TOOL_NAME && rule.ruleContent?.startsWith("domain:")) {
- allowedDomains.push(rule.ruleContent.substring("domain:".length));
- }
- }
- } else {
- for (const domain2 of settings.sandbox?.network?.allowedDomains || []) {
- allowedDomains.push(domain2);
- }
- for (const ruleString of permissions.allow || []) {
- const rule = permissionRuleValueFromString2(ruleString);
- if (rule.toolName === WEB_FETCH_TOOL_NAME && rule.ruleContent?.startsWith("domain:")) {
- allowedDomains.push(rule.ruleContent.substring("domain:".length));
- }
- }
- }
- for (const ruleString of permissions.deny || []) {
- const rule = permissionRuleValueFromString2(ruleString);
- if (rule.toolName === WEB_FETCH_TOOL_NAME && rule.ruleContent?.startsWith("domain:")) {
- deniedDomains.push(rule.ruleContent.substring("domain:".length));
- }
- }
- const allowWrite = [".", getClaudeTempDir()];
- const denyWrite = [];
- const denyRead = [];
- const allowRead = [];
- const settingsPaths = SETTING_SOURCES.map((source) => getSettingsFilePathForSource(source)).filter((p4) => p4 !== undefined);
- denyWrite.push(...settingsPaths);
- denyWrite.push(getManagedSettingsDropInDir());
- const cwd2 = getCwdState();
- const originalCwd = getOriginalCwd();
- if (cwd2 !== originalCwd) {
- denyWrite.push(resolve17(cwd2, ".claude", "settings.json"));
- denyWrite.push(resolve17(cwd2, ".claude", "settings.local.json"));
- }
- denyWrite.push(resolve17(originalCwd, ".claude", "skills"));
- if (cwd2 !== originalCwd) {
- denyWrite.push(resolve17(cwd2, ".claude", "skills"));
- }
- bareGitRepoScrubPaths.length = 0;
- const bareGitRepoFiles = ["HEAD", "objects", "refs", "hooks", "config"];
- for (const dir of cwd2 === originalCwd ? [originalCwd] : [originalCwd, cwd2]) {
- for (const gitFile of bareGitRepoFiles) {
- const p4 = resolve17(dir, gitFile);
- try {
- statSync8(p4);
- denyWrite.push(p4);
- } catch {
- bareGitRepoScrubPaths.push(p4);
- }
- }
- }
- if (worktreeMainRepoPath && worktreeMainRepoPath !== cwd2) {
- allowWrite.push(worktreeMainRepoPath);
- }
- const additionalDirs = new Set([
- ...settings.permissions?.additionalDirectories || [],
- ...getAdditionalDirectoriesForClaudeMd()
- ]);
- allowWrite.push(...additionalDirs);
- for (const source of SETTING_SOURCES) {
- const sourceSettings = getSettingsForSource(source);
- if (sourceSettings?.permissions) {
- for (const ruleString of sourceSettings.permissions.allow || []) {
- const rule = permissionRuleValueFromString2(ruleString);
- if (rule.toolName === FILE_EDIT_TOOL_NAME && rule.ruleContent) {
- allowWrite.push(resolvePathPatternForSandbox(rule.ruleContent, source));
- }
- }
- for (const ruleString of sourceSettings.permissions.deny || []) {
- const rule = permissionRuleValueFromString2(ruleString);
- if (rule.toolName === FILE_EDIT_TOOL_NAME && rule.ruleContent) {
- denyWrite.push(resolvePathPatternForSandbox(rule.ruleContent, source));
- }
- if (rule.toolName === FILE_READ_TOOL_NAME && rule.ruleContent) {
- denyRead.push(resolvePathPatternForSandbox(rule.ruleContent, source));
- }
- }
- }
- const fs10 = sourceSettings?.sandbox?.filesystem;
- if (fs10) {
- for (const p4 of fs10.allowWrite || []) {
- allowWrite.push(resolveSandboxFilesystemPath(p4, source));
- }
- for (const p4 of fs10.denyWrite || []) {
- denyWrite.push(resolveSandboxFilesystemPath(p4, source));
- }
- for (const p4 of fs10.denyRead || []) {
- denyRead.push(resolveSandboxFilesystemPath(p4, source));
- }
- if (!shouldAllowManagedReadPathsOnly() || source === "policySettings") {
- for (const p4 of fs10.allowRead || []) {
- allowRead.push(resolveSandboxFilesystemPath(p4, source));
- }
- }
- }
- }
- const { rgPath, rgArgs, argv0 } = ripgrepCommand();
- const ripgrepConfig = settings.sandbox?.ripgrep ?? {
- command: rgPath,
- args: rgArgs,
- argv0
- };
- return {
- network: {
- allowedDomains,
- deniedDomains,
- allowUnixSockets: settings.sandbox?.network?.allowUnixSockets,
- allowAllUnixSockets: settings.sandbox?.network?.allowAllUnixSockets,
- allowLocalBinding: settings.sandbox?.network?.allowLocalBinding,
- httpProxyPort: settings.sandbox?.network?.httpProxyPort,
- socksProxyPort: settings.sandbox?.network?.socksProxyPort
- },
- filesystem: {
- denyRead,
- allowRead,
- allowWrite,
- denyWrite
- },
- ignoreViolations: settings.sandbox?.ignoreViolations,
- enableWeakerNestedSandbox: settings.sandbox?.enableWeakerNestedSandbox,
- enableWeakerNetworkIsolation: settings.sandbox?.enableWeakerNetworkIsolation,
- ripgrep: ripgrepConfig
- };
-}
-function scrubBareGitRepoFiles() {
- for (const p4 of bareGitRepoScrubPaths) {
- try {
- rmSync2(p4, { recursive: true });
- logForDebugging(`[Sandbox] scrubbed planted bare-repo file: ${p4}`);
- } catch {}
- }
-}
-async function detectWorktreeMainRepoPath(cwd2) {
- const gitPath = join44(cwd2, ".git");
- try {
- const gitContent = await readFile14(gitPath, { encoding: "utf8" });
- const gitdirMatch = gitContent.match(/^gitdir:\s*(.+)$/m);
- if (!gitdirMatch?.[1]) {
- return null;
- }
- const gitdir = resolve17(cwd2, gitdirMatch[1].trim());
- const marker = `${sep11}.git${sep11}worktrees${sep11}`;
- const markerIndex = gitdir.lastIndexOf(marker);
- if (markerIndex > 0) {
- return gitdir.substring(0, markerIndex);
- }
- return null;
- } catch {
- return null;
- }
-}
-function getSandboxEnabledSetting() {
- try {
- const settings = getSettings_DEPRECATED();
- return settings?.sandbox?.enabled ?? false;
- } catch (error46) {
- logForDebugging(`Failed to get settings for sandbox check: ${error46}`);
- return false;
- }
-}
-function isAutoAllowBashIfSandboxedEnabled() {
- const settings = getSettings_DEPRECATED();
- return settings?.sandbox?.autoAllowBashIfSandboxed ?? true;
-}
-function areUnsandboxedCommandsAllowed() {
- const settings = getSettings_DEPRECATED();
- return settings?.sandbox?.allowUnsandboxedCommands ?? true;
-}
-function isSandboxRequired() {
- const settings = getSettings_DEPRECATED();
- return getSandboxEnabledSetting() && (settings?.sandbox?.failIfUnavailable ?? false);
-}
-function isPlatformInEnabledList() {
- try {
- const settings = getInitialSettings();
- const enabledPlatforms = settings?.sandbox?.enabledPlatforms;
- if (enabledPlatforms === undefined) {
- return true;
- }
- if (enabledPlatforms.length === 0) {
- return false;
- }
- const currentPlatform = getPlatform();
- return enabledPlatforms.includes(currentPlatform);
- } catch (error46) {
- logForDebugging(`Failed to check enabledPlatforms: ${error46}`);
- return true;
- }
-}
-function isSandboxingEnabled() {
- if (!isSupportedPlatform()) {
- return false;
- }
- if (checkDependencies().errors.length > 0) {
- return false;
- }
- if (!isPlatformInEnabledList()) {
- return false;
- }
- return getSandboxEnabledSetting();
-}
-function getSandboxUnavailableReason() {
- if (!getSandboxEnabledSetting()) {
- return;
- }
- if (!isSupportedPlatform()) {
- const platform3 = getPlatform();
- if (platform3 === "wsl") {
- return "sandbox.enabled is set but WSL1 is not supported (requires WSL2)";
- }
- return `sandbox.enabled is set but ${platform3} is not supported (requires macOS, Linux, or WSL2)`;
- }
- if (!isPlatformInEnabledList()) {
- return `sandbox.enabled is set but ${getPlatform()} is not in sandbox.enabledPlatforms`;
- }
- const deps = checkDependencies();
- if (deps.errors.length > 0) {
- const platform3 = getPlatform();
- const hint = platform3 === "macos" ? "run /sandbox or /doctor for details" : "install missing tools (e.g. apt install bubblewrap socat) or run /sandbox for details";
- return `sandbox.enabled is set but dependencies are missing: ${deps.errors.join(", ")} \xB7 ${hint}`;
- }
- return;
-}
-function getLinuxGlobPatternWarnings() {
- const platform3 = getPlatform();
- if (platform3 !== "linux" && platform3 !== "wsl") {
- return [];
- }
- try {
- const settings = getSettings_DEPRECATED();
- if (!settings?.sandbox?.enabled) {
- return [];
- }
- const permissions = settings?.permissions || {};
- const warnings = [];
- const hasGlobs = (path16) => {
- const stripped = path16.replace(/\/\*\*$/, "");
- return /[*?[\]]/.test(stripped);
- };
- for (const ruleString of [
- ...permissions.allow || [],
- ...permissions.deny || []
- ]) {
- const rule = permissionRuleValueFromString2(ruleString);
- if ((rule.toolName === FILE_EDIT_TOOL_NAME || rule.toolName === FILE_READ_TOOL_NAME) && rule.ruleContent && hasGlobs(rule.ruleContent)) {
- warnings.push(ruleString);
- }
- }
- return warnings;
- } catch (error46) {
- logForDebugging(`Failed to get Linux glob pattern warnings: ${error46}`);
- return [];
- }
-}
-function areSandboxSettingsLockedByPolicy() {
- const overridingSources = ["flagSettings", "policySettings"];
- for (const source of overridingSources) {
- const settings = getSettingsForSource(source);
- if (settings?.sandbox?.enabled !== undefined || settings?.sandbox?.autoAllowBashIfSandboxed !== undefined || settings?.sandbox?.allowUnsandboxedCommands !== undefined) {
- return true;
- }
- }
- return false;
-}
-async function setSandboxSettings(options2) {
- const existingSettings = getSettingsForSource("localSettings");
- updateSettingsForSource("localSettings", {
- sandbox: {
- ...existingSettings?.sandbox,
- ...options2.enabled !== undefined && { enabled: options2.enabled },
- ...options2.autoAllowBashIfSandboxed !== undefined && {
- autoAllowBashIfSandboxed: options2.autoAllowBashIfSandboxed
- },
- ...options2.allowUnsandboxedCommands !== undefined && {
- allowUnsandboxedCommands: options2.allowUnsandboxedCommands
- }
- }
- });
-}
-function getExcludedCommands() {
- const settings = getSettings_DEPRECATED();
- return settings?.sandbox?.excludedCommands ?? [];
-}
-async function wrapWithSandbox(command12, binShell, customConfig, abortSignal) {
- if (isSandboxingEnabled()) {
- if (initializationPromise) {
- await initializationPromise;
- } else {
- throw new Error("Sandbox failed to initialize. ");
- }
- }
- return import_sandbox_runtime.SandboxManager.wrapWithSandbox(command12, binShell, customConfig, abortSignal);
-}
-async function initialize2(sandboxAskCallback) {
- if (initializationPromise) {
- return initializationPromise;
- }
- if (!isSandboxingEnabled()) {
- return;
- }
- const wrappedCallback = sandboxAskCallback ? async (hostPattern) => {
- if (shouldAllowManagedSandboxDomainsOnly()) {
- logForDebugging(`[sandbox] Blocked network request to ${hostPattern.host} (allowManagedDomainsOnly)`);
- return false;
- }
- return sandboxAskCallback(hostPattern);
- } : undefined;
- initializationPromise = (async () => {
- try {
- if (worktreeMainRepoPath === undefined) {
- worktreeMainRepoPath = await detectWorktreeMainRepoPath(getCwdState());
- }
- const settings = getSettings_DEPRECATED();
- const runtimeConfig = convertToSandboxRuntimeConfig(settings);
- await import_sandbox_runtime.SandboxManager.initialize(runtimeConfig, wrappedCallback);
- settingsSubscriptionCleanup = settingsChangeDetector.subscribe(() => {
- const settings2 = getSettings_DEPRECATED();
- const newConfig = convertToSandboxRuntimeConfig(settings2);
- import_sandbox_runtime.SandboxManager.updateConfig(newConfig);
- logForDebugging("Sandbox configuration updated from settings change");
- });
- } catch (error46) {
- initializationPromise = undefined;
- logForDebugging(`Failed to initialize sandbox: ${errorMessage(error46)}`);
- }
- })();
- return initializationPromise;
-}
-function refreshConfig() {
- if (!isSandboxingEnabled())
- return;
- const settings = getSettings_DEPRECATED();
- const newConfig = convertToSandboxRuntimeConfig(settings);
- import_sandbox_runtime.SandboxManager.updateConfig(newConfig);
-}
-async function reset2() {
- settingsSubscriptionCleanup?.();
- settingsSubscriptionCleanup = undefined;
- worktreeMainRepoPath = undefined;
- bareGitRepoScrubPaths.length = 0;
- checkDependencies.cache.clear?.();
- isSupportedPlatform.cache.clear?.();
- initializationPromise = undefined;
- return import_sandbox_runtime.SandboxManager.reset();
-}
-function addToExcludedCommands(command12, permissionUpdates) {
- const existingSettings = getSettingsForSource("localSettings");
- const existingExcludedCommands = existingSettings?.sandbox?.excludedCommands || [];
- let commandPattern = command12;
- if (permissionUpdates) {
- const bashSuggestions = permissionUpdates.filter((update) => update.type === "addRules" && update.rules.some((rule) => rule.toolName === BASH_TOOL_NAME));
- if (bashSuggestions.length > 0 && bashSuggestions[0].type === "addRules") {
- const firstBashRule = bashSuggestions[0].rules.find((rule) => rule.toolName === BASH_TOOL_NAME);
- if (firstBashRule?.ruleContent) {
- const prefix = permissionRuleExtractPrefix(firstBashRule.ruleContent);
- commandPattern = prefix || firstBashRule.ruleContent;
- }
- }
- }
- if (!existingExcludedCommands.includes(commandPattern)) {
- updateSettingsForSource("localSettings", {
- sandbox: {
- ...existingSettings?.sandbox,
- excludedCommands: [...existingExcludedCommands, commandPattern]
- }
- });
- }
- return commandPattern;
-}
-var import_sandbox_runtime, initializationPromise, settingsSubscriptionCleanup, worktreeMainRepoPath, bareGitRepoScrubPaths, checkDependencies, isSupportedPlatform, SandboxManager;
-var init_sandbox_adapter = __esm(() => {
- init_lodash();
- init_state();
- init_debug();
- init_path();
- init_platform2();
- init_changeDetector();
- init_constants2();
- init_managedPath();
- init_settings2();
- init_prompt2();
- init_errors();
- init_filesystem();
- init_ripgrep();
- import_sandbox_runtime = __toESM(require_sandbox_runtime(), 1);
- bareGitRepoScrubPaths = [];
- checkDependencies = memoize_default(() => {
- const { rgPath, rgArgs } = ripgrepCommand();
- return import_sandbox_runtime.SandboxManager.checkDependencies({
- command: rgPath,
- args: rgArgs
- });
- });
- isSupportedPlatform = memoize_default(() => {
- return import_sandbox_runtime.SandboxManager.isSupportedPlatform();
- });
- SandboxManager = {
- initialize: initialize2,
- isSandboxingEnabled,
- isSandboxEnabledInSettings: getSandboxEnabledSetting,
- isPlatformInEnabledList,
- getSandboxUnavailableReason,
- isAutoAllowBashIfSandboxedEnabled,
- areUnsandboxedCommandsAllowed,
- isSandboxRequired,
- areSandboxSettingsLockedByPolicy,
- setSandboxSettings,
- getExcludedCommands,
- wrapWithSandbox,
- refreshConfig,
- reset: reset2,
- checkDependencies,
- getFsReadConfig: import_sandbox_runtime.SandboxManager.getFsReadConfig,
- getFsWriteConfig: import_sandbox_runtime.SandboxManager.getFsWriteConfig,
- getNetworkRestrictionConfig: import_sandbox_runtime.SandboxManager.getNetworkRestrictionConfig,
- getIgnoreViolations: import_sandbox_runtime.SandboxManager.getIgnoreViolations,
- getLinuxGlobPatternWarnings,
- isSupportedPlatform,
- getAllowUnixSockets: import_sandbox_runtime.SandboxManager.getAllowUnixSockets,
- getAllowLocalBinding: import_sandbox_runtime.SandboxManager.getAllowLocalBinding,
- getEnableWeakerNestedSandbox: import_sandbox_runtime.SandboxManager.getEnableWeakerNestedSandbox,
- getProxyPort: import_sandbox_runtime.SandboxManager.getProxyPort,
- getSocksProxyPort: import_sandbox_runtime.SandboxManager.getSocksProxyPort,
- getLinuxHttpSocketPath: import_sandbox_runtime.SandboxManager.getLinuxHttpSocketPath,
- getLinuxSocksSocketPath: import_sandbox_runtime.SandboxManager.getLinuxSocksSocketPath,
- waitForNetworkInitialization: import_sandbox_runtime.SandboxManager.waitForNetworkInitialization,
- getSandboxViolationStore: import_sandbox_runtime.SandboxManager.getSandboxViolationStore,
- annotateStderrWithSandboxFailures: import_sandbox_runtime.SandboxManager.annotateStderrWithSandboxFailures,
- cleanupAfterCommand: () => {
- import_sandbox_runtime.SandboxManager.cleanupAfterCommand();
- scrubBareGitRepoFiles();
- }
- };
-});
-
-// src/utils/permissions/pathValidation.ts
-import { homedir as homedir13 } from "os";
-import { dirname as dirname18, isAbsolute as isAbsolute8, resolve as resolve18 } from "path";
-function formatDirectoryList(directories) {
- const dirCount = directories.length;
- if (dirCount <= MAX_DIRS_TO_LIST) {
- return directories.map((dir) => `'${dir}'`).join(", ");
- }
- const firstDirs = directories.slice(0, MAX_DIRS_TO_LIST).map((dir) => `'${dir}'`).join(", ");
- return `${firstDirs}, and ${dirCount - MAX_DIRS_TO_LIST} more`;
-}
-function getGlobBaseDirectory(path16) {
- const globMatch = path16.match(GLOB_PATTERN_REGEX);
- if (!globMatch || globMatch.index === undefined) {
- return path16;
- }
- const beforeGlob = path16.substring(0, globMatch.index);
- const lastSepIndex = getPlatform() === "windows" ? Math.max(beforeGlob.lastIndexOf("/"), beforeGlob.lastIndexOf("\\")) : beforeGlob.lastIndexOf("/");
- if (lastSepIndex === -1)
- return ".";
- return beforeGlob.substring(0, lastSepIndex) || "/";
-}
-function expandTilde(path16) {
- if (path16 === "~" || path16.startsWith("~/") || process.platform === "win32" && path16.startsWith("~\\")) {
- return homedir13() + path16.slice(1);
- }
- return path16;
-}
-function isPathInSandboxWriteAllowlist(resolvedPath5) {
- if (!SandboxManager.isSandboxingEnabled()) {
- return false;
- }
- const { allowOnly, denyWithinAllow } = SandboxManager.getFsWriteConfig();
- const pathsToCheck = getPathsForPermissionCheck(resolvedPath5);
- const resolvedAllow = allowOnly.flatMap(getResolvedSandboxConfigPath);
- const resolvedDeny = denyWithinAllow.flatMap(getResolvedSandboxConfigPath);
- return pathsToCheck.every((p4) => {
- for (const denyPath of resolvedDeny) {
- if (pathInWorkingPath(p4, denyPath))
- return false;
- }
- return resolvedAllow.some((allowPath) => pathInWorkingPath(p4, allowPath));
- });
-}
-function isPathAllowed(resolvedPath5, context4, operationType, precomputedPathsToCheck) {
- const permissionType = operationType === "read" ? "read" : "edit";
- const denyRule = matchingRuleForInput(resolvedPath5, context4, permissionType, "deny");
- if (denyRule !== null) {
- return {
- allowed: false,
- decisionReason: { type: "rule", rule: denyRule }
- };
- }
- if (operationType !== "read") {
- const internalEditResult = checkEditableInternalPath(resolvedPath5, {});
- if (internalEditResult.behavior === "allow") {
- return {
- allowed: true,
- decisionReason: internalEditResult.decisionReason
- };
- }
- }
- if (operationType !== "read") {
- const safetyCheck = checkPathSafetyForAutoEdit(resolvedPath5, precomputedPathsToCheck);
- if (!safetyCheck.safe) {
- return {
- allowed: false,
- decisionReason: {
- type: "safetyCheck",
- reason: safetyCheck.message,
- classifierApprovable: safetyCheck.classifierApprovable
- }
- };
- }
- }
- const isInWorkingDir = pathInAllowedWorkingPath(resolvedPath5, context4, precomputedPathsToCheck);
- if (isInWorkingDir) {
- if (operationType === "read" || context4.mode === "acceptEdits") {
- return { allowed: true };
- }
- }
- if (operationType === "read") {
- const internalReadResult = checkReadableInternalPath(resolvedPath5, {});
- if (internalReadResult.behavior === "allow") {
- return {
- allowed: true,
- decisionReason: internalReadResult.decisionReason
- };
- }
- }
- if (operationType !== "read" && !isInWorkingDir && isPathInSandboxWriteAllowlist(resolvedPath5)) {
- return {
- allowed: true,
- decisionReason: {
- type: "other",
- reason: "Path is in sandbox write allowlist"
- }
- };
- }
- const allowRule = matchingRuleForInput(resolvedPath5, context4, permissionType, "allow");
- if (allowRule !== null) {
- return {
- allowed: true,
- decisionReason: { type: "rule", rule: allowRule }
- };
- }
- return { allowed: false };
-}
-function validateGlobPattern(cleanPath, cwd2, toolPermissionContext, operationType) {
- if (containsPathTraversal(cleanPath)) {
- const absolutePath = isAbsolute8(cleanPath) ? cleanPath : resolve18(cwd2, cleanPath);
- const { resolvedPath: resolvedPath6, isCanonical: isCanonical2 } = safeResolvePath(getFsImplementation(), absolutePath);
- const result2 = isPathAllowed(resolvedPath6, toolPermissionContext, operationType, isCanonical2 ? [resolvedPath6] : undefined);
- return {
- allowed: result2.allowed,
- resolvedPath: resolvedPath6,
- decisionReason: result2.decisionReason
- };
- }
- const basePath = getGlobBaseDirectory(cleanPath);
- const absoluteBasePath = isAbsolute8(basePath) ? basePath : resolve18(cwd2, basePath);
- const { resolvedPath: resolvedPath5, isCanonical } = safeResolvePath(getFsImplementation(), absoluteBasePath);
- const result = isPathAllowed(resolvedPath5, toolPermissionContext, operationType, isCanonical ? [resolvedPath5] : undefined);
- return {
- allowed: result.allowed,
- resolvedPath: resolvedPath5,
- decisionReason: result.decisionReason
- };
-}
-function isDangerousRemovalPath(resolvedPath5) {
- const forwardSlashed = resolvedPath5.replace(/[\\/]+/g, "/");
- if (forwardSlashed === "*" || forwardSlashed.endsWith("/*")) {
- return true;
- }
- const normalizedPath = forwardSlashed === "/" ? forwardSlashed : forwardSlashed.replace(/\/$/, "");
- if (normalizedPath === "/") {
- return true;
- }
- if (WINDOWS_DRIVE_ROOT_REGEX.test(normalizedPath)) {
- return true;
- }
- const normalizedHome = homedir13().replace(/[\\/]+/g, "/");
- if (normalizedPath === normalizedHome) {
- return true;
- }
- const parentDir = dirname18(normalizedPath);
- if (parentDir === "/") {
- return true;
- }
- if (WINDOWS_DRIVE_CHILD_REGEX.test(normalizedPath)) {
- return true;
- }
- return false;
-}
-function validatePath(path16, cwd2, toolPermissionContext, operationType) {
- const cleanPath = expandTilde(path16.replace(/^['"]|['"]$/g, ""));
- if (containsVulnerableUncPath(cleanPath)) {
- return {
- allowed: false,
- resolvedPath: cleanPath,
- decisionReason: {
- type: "other",
- reason: "UNC network paths require manual approval"
- }
- };
- }
- if (cleanPath.startsWith("~")) {
- return {
- allowed: false,
- resolvedPath: cleanPath,
- decisionReason: {
- type: "other",
- reason: "Tilde expansion variants (~user, ~+, ~-) in paths require manual approval"
- }
- };
- }
- if (cleanPath.includes("$") || cleanPath.includes("%") || cleanPath.startsWith("=")) {
- return {
- allowed: false,
- resolvedPath: cleanPath,
- decisionReason: {
- type: "other",
- reason: "Shell expansion syntax in paths requires manual approval"
- }
- };
- }
- if (GLOB_PATTERN_REGEX.test(cleanPath)) {
- if (operationType === "write" || operationType === "create") {
- return {
- allowed: false,
- resolvedPath: cleanPath,
- decisionReason: {
- type: "other",
- reason: "Glob patterns are not allowed in write operations. Please specify an exact file path."
- }
- };
- }
- return validateGlobPattern(cleanPath, cwd2, toolPermissionContext, operationType);
- }
- const absolutePath = isAbsolute8(cleanPath) ? cleanPath : resolve18(cwd2, cleanPath);
- const { resolvedPath: resolvedPath5, isCanonical } = safeResolvePath(getFsImplementation(), absolutePath);
- const result = isPathAllowed(resolvedPath5, toolPermissionContext, operationType, isCanonical ? [resolvedPath5] : undefined);
- return {
- allowed: result.allowed,
- resolvedPath: resolvedPath5,
- decisionReason: result.decisionReason
- };
-}
-var MAX_DIRS_TO_LIST = 5, GLOB_PATTERN_REGEX, getResolvedSandboxConfigPath, WINDOWS_DRIVE_ROOT_REGEX, WINDOWS_DRIVE_CHILD_REGEX;
-var init_pathValidation = __esm(() => {
- init_memoize();
- init_platform2();
- init_fsOperations();
- init_path();
- init_sandbox_adapter();
- init_readOnlyCommandValidation();
- init_filesystem();
- GLOB_PATTERN_REGEX = /[*?[\]{}]/;
- getResolvedSandboxConfigPath = memoize_default(getPathsForPermissionCheck);
- WINDOWS_DRIVE_ROOT_REGEX = /^[A-Za-z]:\/?$/;
- WINDOWS_DRIVE_CHILD_REGEX = /^[A-Za-z]:\/[^/]+$/;
-});
-
-// src/utils/plugins/pluginDirectories.ts
-import { mkdirSync as mkdirSync5 } from "fs";
-import { readdir as readdir8, rm as rm3, stat as stat16 } from "fs/promises";
-import { delimiter, join as join45 } from "path";
-function getPluginsDirectoryName() {
- if (getUseCoworkPlugins()) {
- return COWORK_PLUGINS_DIR;
- }
- if (isEnvTruthy(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS)) {
- return COWORK_PLUGINS_DIR;
- }
- return PLUGINS_DIR;
-}
-function getPluginsDirectory() {
- const envOverride = process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR;
- if (envOverride) {
- return expandTilde(envOverride);
- }
- return join45(getClaudeConfigHomeDir(), getPluginsDirectoryName());
-}
-function getPluginSeedDirs() {
- const raw = process.env.CLAUDE_CODE_PLUGIN_SEED_DIR;
- if (!raw)
- return [];
- return raw.split(delimiter).filter(Boolean).map(expandTilde);
-}
-function sanitizePluginId(pluginId) {
- return pluginId.replace(/[^a-zA-Z0-9\-_]/g, "-");
-}
-function pluginDataDirPath(pluginId) {
- return join45(getPluginsDirectory(), "data", sanitizePluginId(pluginId));
-}
-function getPluginDataDir(pluginId) {
- const dir = pluginDataDirPath(pluginId);
- mkdirSync5(dir, { recursive: true });
- return dir;
-}
-async function getPluginDataDirSize(pluginId) {
- const dir = pluginDataDirPath(pluginId);
- let bytes = 0;
- const walk = async (p4) => {
- for (const entry of await readdir8(p4, { withFileTypes: true })) {
- const full = join45(p4, entry.name);
- if (entry.isDirectory()) {
- await walk(full);
- } else {
- try {
- bytes += (await stat16(full)).size;
- } catch {}
- }
- }
- };
- try {
- await walk(dir);
- } catch (e4) {
- if (isFsInaccessible(e4))
- return null;
- throw e4;
- }
- if (bytes === 0)
- return null;
- return { bytes, human: formatFileSize(bytes) };
-}
-async function deletePluginDataDir(pluginId) {
- const dir = pluginDataDirPath(pluginId);
- try {
- await rm3(dir, { recursive: true, force: true });
- } catch (e4) {
- logForDebugging(`Failed to delete plugin data dir ${dir}: ${errorMessage(e4)}`, { level: "warn" });
- }
-}
-var PLUGINS_DIR = "plugins", COWORK_PLUGINS_DIR = "cowork_plugins";
-var init_pluginDirectories = __esm(() => {
- init_state();
- init_debug();
- init_envUtils();
- init_errors();
- init_format();
- init_pathValidation();
-});
-
-// src/utils/plugins/pluginOptionsStorage.ts
-function getPluginStorageId(plugin) {
- return plugin.source;
-}
-function clearPluginOptionsCache() {
- loadPluginOptions.cache?.clear?.();
-}
-function savePluginOptions(pluginId, values2, schema5) {
- const nonSensitive = {};
- const sensitive = {};
- for (const [key2, value] of Object.entries(values2)) {
- if (schema5[key2]?.sensitive === true) {
- sensitive[key2] = String(value);
- } else {
- nonSensitive[key2] = value;
- }
- }
- const sensitiveKeysInThisSave = new Set(Object.keys(sensitive));
- const nonSensitiveKeysInThisSave = new Set(Object.keys(nonSensitive));
- const storage = getSecureStorage();
- const existingInSecureStorage = storage.read()?.pluginSecrets?.[pluginId] ?? undefined;
- const secureScrubbed = existingInSecureStorage ? Object.fromEntries(Object.entries(existingInSecureStorage).filter(([k4]) => !nonSensitiveKeysInThisSave.has(k4))) : undefined;
- const needSecureScrub = secureScrubbed && existingInSecureStorage && Object.keys(secureScrubbed).length !== Object.keys(existingInSecureStorage).length;
- if (Object.keys(sensitive).length > 0 || needSecureScrub) {
- const existing = storage.read() ?? {};
- if (!existing.pluginSecrets) {
- existing.pluginSecrets = {};
- }
- existing.pluginSecrets[pluginId] = {
- ...secureScrubbed,
- ...sensitive
- };
- const result = storage.update(existing);
- if (!result.success) {
- const err2 = new Error(`Failed to save sensitive plugin options for ${pluginId} to secure storage`);
- logError2(err2);
- throw err2;
- }
- if (result.warning) {
- logForDebugging(`Plugin secrets save warning: ${result.warning}`, {
- level: "warn"
- });
- }
- }
- const settings = getSettings_DEPRECATED();
- const existingInSettings = settings.pluginConfigs?.[pluginId]?.options ?? {};
- const keysToScrubFromSettings = Object.keys(existingInSettings).filter((k4) => sensitiveKeysInThisSave.has(k4));
- if (Object.keys(nonSensitive).length > 0 || keysToScrubFromSettings.length > 0) {
- if (!settings.pluginConfigs) {
- settings.pluginConfigs = {};
- }
- if (!settings.pluginConfigs[pluginId]) {
- settings.pluginConfigs[pluginId] = {};
- }
- const scrubbed = Object.fromEntries(keysToScrubFromSettings.map((k4) => [k4, undefined]));
- settings.pluginConfigs[pluginId].options = {
- ...nonSensitive,
- ...scrubbed
- };
- const result = updateSettingsForSource("userSettings", settings);
- if (result.error) {
- logError2(result.error);
- throw new Error(`Failed to save plugin options for ${pluginId}: ${result.error.message}`);
- }
- }
- clearPluginOptionsCache();
-}
-function deletePluginOptions(pluginId) {
- const settings = getSettings_DEPRECATED();
- if (settings.pluginConfigs?.[pluginId]) {
- const pluginConfigs = { [pluginId]: undefined };
- const { error: error46 } = updateSettingsForSource("userSettings", {
- pluginConfigs
- });
- if (error46) {
- logForDebugging(`deletePluginOptions: failed to clear settings.pluginConfigs[${pluginId}]: ${error46.message}`, { level: "warn" });
- }
- }
- const storage = getSecureStorage();
- const existing = storage.read();
- if (existing?.pluginSecrets) {
- const prefix = `${pluginId}/`;
- const survivingEntries = Object.entries(existing.pluginSecrets).filter(([k4]) => k4 !== pluginId && !k4.startsWith(prefix));
- if (survivingEntries.length !== Object.keys(existing.pluginSecrets).length) {
- const result = storage.update({
- ...existing,
- pluginSecrets: survivingEntries.length > 0 ? Object.fromEntries(survivingEntries) : undefined
- });
- if (!result.success) {
- logForDebugging(`deletePluginOptions: failed to clear pluginSecrets for ${pluginId} from keychain`, { level: "warn" });
- }
- }
- }
- clearPluginOptionsCache();
-}
-function getUnconfiguredOptions(plugin) {
- const manifestSchema = plugin.manifest.userConfig;
- if (!manifestSchema || Object.keys(manifestSchema).length === 0) {
- return {};
- }
- const saved = loadPluginOptions(getPluginStorageId(plugin));
- const validation = validateUserConfig(saved, manifestSchema);
- if (validation.valid) {
- return {};
- }
- const unconfigured = {};
- for (const [key2, fieldSchema] of Object.entries(manifestSchema)) {
- const single = validateUserConfig({ [key2]: saved[key2] }, { [key2]: fieldSchema });
- if (!single.valid) {
- unconfigured[key2] = fieldSchema;
- }
- }
- return unconfigured;
-}
-function substitutePluginVariables(value, plugin) {
- const normalize8 = (p4) => process.platform === "win32" ? p4.replace(/\\/g, "/") : p4;
- let out = value.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => normalize8(plugin.path));
- if (plugin.source) {
- const source = plugin.source;
- out = out.replace(/\$\{CLAUDE_PLUGIN_DATA\}/g, () => normalize8(getPluginDataDir(source)));
- }
- return out;
-}
-function substituteUserConfigVariables(value, userConfig) {
- return value.replace(/\$\{user_config\.([^}]+)\}/g, (_match, key2) => {
- const configValue = userConfig[key2];
- if (configValue === undefined) {
- throw new Error(`Missing required user configuration value: ${key2}. ` + `This should have been validated before variable substitution.`);
- }
- return String(configValue);
- });
-}
-function substituteUserConfigInContent(content, options2, schema5) {
- return content.replace(/\$\{user_config\.([^}]+)\}/g, (match, key2) => {
- if (schema5[key2]?.sensitive === true) {
- return `[sensitive option '${key2}' not available in skill content]`;
- }
- const value = options2[key2];
- if (value === undefined) {
- return match;
- }
- return String(value);
- });
-}
-var loadPluginOptions;
-var init_pluginOptionsStorage = __esm(() => {
- init_memoize();
- init_debug();
- init_log2();
- init_secureStorage();
- init_settings2();
- init_mcpbHandler();
- init_pluginDirectories();
- loadPluginOptions = memoize_default((pluginId) => {
- const settings = getSettings_DEPRECATED();
- const nonSensitive = settings.pluginConfigs?.[pluginId]?.options ?? {};
- const storage = getSecureStorage();
- const sensitive = storage.read()?.pluginSecrets?.[pluginId] ?? {};
- return { ...nonSensitive, ...sensitive };
- });
-});
-
-// src/utils/settings/pluginOnlyPolicy.ts
-function isRestrictedToPluginOnly(surface) {
- const policy = getSettingsForSource("policySettings")?.strictPluginOnlyCustomization;
- if (policy === true)
- return true;
- if (Array.isArray(policy))
- return policy.includes(surface);
- return false;
-}
-function isSourceAdminTrusted(source) {
- return source !== undefined && ADMIN_TRUSTED_SOURCES.has(source);
-}
-var ADMIN_TRUSTED_SOURCES;
-var init_pluginOnlyPolicy = __esm(() => {
- init_settings2();
- ADMIN_TRUSTED_SOURCES = new Set([
- "plugin",
- "policySettings",
- "built-in",
- "builtin",
- "bundled"
- ]);
-});
-
-// src/utils/hooks/hooksConfigSnapshot.ts
-function getHooksFromAllowedSources() {
- const policySettings = getSettingsForSource("policySettings");
- if (policySettings?.disableAllHooks === true) {
- return {};
- }
- if (policySettings?.allowManagedHooksOnly === true) {
- return policySettings.hooks ?? {};
- }
- if (isRestrictedToPluginOnly("hooks")) {
- return policySettings?.hooks ?? {};
- }
- const mergedSettings = getSettings_DEPRECATED();
- if (mergedSettings.disableAllHooks === true) {
- return policySettings?.hooks ?? {};
- }
- return mergedSettings.hooks ?? {};
-}
-function shouldAllowManagedHooksOnly() {
- const policySettings = getSettingsForSource("policySettings");
- if (policySettings?.allowManagedHooksOnly === true) {
- return true;
- }
- if (getSettings_DEPRECATED().disableAllHooks === true && policySettings?.disableAllHooks !== true) {
- return true;
- }
- return false;
-}
-function shouldDisableAllHooksIncludingManaged() {
- return getSettingsForSource("policySettings")?.disableAllHooks === true;
-}
-function captureHooksConfigSnapshot() {
- initialHooksConfig = getHooksFromAllowedSources();
-}
-function updateHooksConfigSnapshot() {
- resetSettingsCache();
- initialHooksConfig = getHooksFromAllowedSources();
-}
-function getHooksConfigFromSnapshot() {
- if (initialHooksConfig === null) {
- captureHooksConfigSnapshot();
- }
- return initialHooksConfig;
-}
-var initialHooksConfig = null;
-var init_hooksConfigSnapshot = __esm(() => {
- init_state();
- init_pluginOnlyPolicy();
- init_settings2();
- init_settingsCache();
-});
-
-// src/utils/taggedId.ts
-function base58Encode(n5) {
- const base2 = BigInt(BASE_58_CHARS.length);
- const result = new Array(ENCODED_LENGTH).fill(BASE_58_CHARS[0]);
- let i6 = ENCODED_LENGTH - 1;
- let value = n5;
- while (value > 0n) {
- const rem = Number(value % base2);
- result[i6] = BASE_58_CHARS[rem];
- value = value / base2;
- i6--;
- }
- return result.join("");
-}
-function uuidToBigInt(uuid8) {
- const hex = uuid8.replace(/-/g, "");
- if (hex.length !== 32) {
- throw new Error(`Invalid UUID hex length: ${hex.length}`);
- }
- return BigInt("0x" + hex);
-}
-function toTaggedId(tag2, uuid8) {
- const n5 = uuidToBigInt(uuid8);
- return `${tag2}_${VERSION7}${base58Encode(n5)}`;
-}
-var BASE_58_CHARS = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", VERSION7 = "01", ENCODED_LENGTH = 22;
-
-// src/utils/telemetryAttributes.ts
-function shouldIncludeAttribute(envVar) {
- const defaultValue = METRICS_CARDINALITY_DEFAULTS[envVar];
- const envValue = process.env[envVar];
- if (envValue === undefined) {
- return defaultValue;
- }
- return isEnvTruthy(envValue);
-}
-function getTelemetryAttributes() {
- const userId = getOrCreateUserID();
- const sessionId = getSessionId();
- const attributes = {
- "user.id": userId
- };
- if (shouldIncludeAttribute("OTEL_METRICS_INCLUDE_SESSION_ID")) {
- attributes["session.id"] = sessionId;
- }
- if (shouldIncludeAttribute("OTEL_METRICS_INCLUDE_VERSION")) {
- attributes["app.version"] = MACRO.VERSION;
- }
- const oauthAccount = getOauthAccountInfo();
- if (oauthAccount) {
- const orgId = oauthAccount.organizationUuid;
- const email3 = oauthAccount.emailAddress;
- const accountUuid = oauthAccount.accountUuid;
- if (orgId)
- attributes["organization.id"] = orgId;
- if (email3)
- attributes["user.email"] = email3;
- if (accountUuid && shouldIncludeAttribute("OTEL_METRICS_INCLUDE_ACCOUNT_UUID")) {
- attributes["user.account_uuid"] = accountUuid;
- attributes["user.account_id"] = process.env.CLAUDE_CODE_ACCOUNT_TAGGED_ID || toTaggedId("user", accountUuid);
- }
- }
- if (envDynamic.terminal) {
- attributes["terminal.type"] = envDynamic.terminal;
- }
- return attributes;
-}
-var METRICS_CARDINALITY_DEFAULTS;
-var init_telemetryAttributes = __esm(() => {
- init_state();
- init_auth14();
- init_config();
- init_envDynamic();
- init_envUtils();
- METRICS_CARDINALITY_DEFAULTS = {
- OTEL_METRICS_INCLUDE_SESSION_ID: true,
- OTEL_METRICS_INCLUDE_VERSION: false,
- OTEL_METRICS_INCLUDE_ACCOUNT_UUID: true
- };
-});
-
-// src/utils/telemetry/events.ts
-function isUserPromptLoggingEnabled() {
- return isEnvTruthy(process.env.OTEL_LOG_USER_PROMPTS);
-}
-function redactIfDisabled(content) {
- return isUserPromptLoggingEnabled() ? content : "";
-}
-async function logOTelEvent(eventName, metadata = {}) {
- const eventLogger = getEventLogger();
- if (!eventLogger) {
- if (!hasWarnedNoEventLogger) {
- hasWarnedNoEventLogger = true;
- logForDebugging(`[3P telemetry] Event dropped (no event logger initialized): ${eventName}`, { level: "warn" });
- }
- return;
- }
- if (false) {}
- const attributes = {
- ...getTelemetryAttributes(),
- "event.name": eventName,
- "event.timestamp": new Date().toISOString(),
- "event.sequence": eventSequence++
- };
- const promptId = getPromptId();
- if (promptId) {
- attributes["prompt.id"] = promptId;
- }
- const workspaceDir = process.env.CLAUDE_CODE_WORKSPACE_HOST_PATHS;
- if (workspaceDir) {
- attributes["workspace.host_paths"] = workspaceDir.split("|");
- }
- for (const [key2, value] of Object.entries(metadata)) {
- if (value !== undefined) {
- attributes[key2] = value;
- }
- }
- eventLogger.emit({
- body: `claude_code.${eventName}`,
- attributes
- });
-}
-var eventSequence = 0, hasWarnedNoEventLogger = false;
-var init_events = __esm(() => {
- init_state();
- init_debug();
- init_envUtils();
- init_telemetryAttributes();
-});
-
-// src/utils/telemetry/betaSessionTracing.ts
-import { createHash as createHash8 } from "crypto";
-function clearBetaTracingState() {
- seenHashes.clear();
- lastReportedMessageHash.clear();
-}
-function isBetaTracingEnabled() {
- const baseEnabled = isEnvTruthy(process.env.ENABLE_BETA_TRACING_DETAILED) && Boolean(process.env.BETA_TRACING_ENDPOINT);
- if (!baseEnabled) {
- return false;
- }
- if (process.env.USER_TYPE !== "ant") {
- return getIsNonInteractiveSession() || getFeatureValue_CACHED_MAY_BE_STALE("tengu_trace_lantern", false);
- }
- return true;
-}
-function truncateContent(content, maxSize = MAX_CONTENT_SIZE) {
- if (content.length <= maxSize) {
- return { content, truncated: false };
- }
- return {
- content: content.slice(0, maxSize) + `
-
-[TRUNCATED - Content exceeds 60KB limit]`,
- truncated: true
- };
-}
-function shortHash(content) {
- return createHash8("sha256").update(content).digest("hex").slice(0, 12);
-}
-function hashSystemPrompt(systemPrompt) {
- return `sp_${shortHash(systemPrompt)}`;
-}
-function hashMessage(message) {
- const content = jsonStringify(message.message.content);
- return `msg_${shortHash(content)}`;
-}
-function extractSystemReminderContent(text) {
- const match = text.trim().match(SYSTEM_REMINDER_REGEX);
- return match && match[1] ? match[1].trim() : null;
-}
-function formatMessagesForContext(messages) {
- const contextParts = [];
- const systemReminders = [];
- for (const message of messages) {
- const content = message.message.content;
- if (typeof content === "string") {
- const reminderContent = extractSystemReminderContent(content);
- if (reminderContent) {
- systemReminders.push(reminderContent);
- } else {
- contextParts.push(`[USER]
-${content}`);
- }
- } else if (Array.isArray(content)) {
- for (const block2 of content) {
- if (block2.type === "text") {
- const reminderContent = extractSystemReminderContent(block2.text);
- if (reminderContent) {
- systemReminders.push(reminderContent);
- } else {
- contextParts.push(`[USER]
-${block2.text}`);
- }
- } else if (block2.type === "tool_result") {
- const resultContent = typeof block2.content === "string" ? block2.content : jsonStringify(block2.content);
- const reminderContent = extractSystemReminderContent(resultContent);
- if (reminderContent) {
- systemReminders.push(reminderContent);
- } else {
- contextParts.push(`[TOOL RESULT: ${block2.tool_use_id}]
-${resultContent}`);
- }
- }
- }
- }
- }
- return { contextParts, systemReminders };
-}
-function addBetaInteractionAttributes(span, userPrompt) {
- if (!isBetaTracingEnabled()) {
- return;
- }
- const { content: truncatedPrompt, truncated } = truncateContent(`[USER PROMPT]
-${userPrompt}`);
- span.setAttributes({
- new_context: truncatedPrompt,
- ...truncated && {
- new_context_truncated: true,
- new_context_original_length: userPrompt.length
- }
- });
-}
-function addBetaLLMRequestAttributes(span, newContext, messagesForAPI) {
- if (!isBetaTracingEnabled()) {
- return;
- }
- if (newContext?.systemPrompt) {
- const promptHash = hashSystemPrompt(newContext.systemPrompt);
- const preview = newContext.systemPrompt.slice(0, 500);
- span.setAttribute("system_prompt_hash", promptHash);
- span.setAttribute("system_prompt_preview", preview);
- span.setAttribute("system_prompt_length", newContext.systemPrompt.length);
- if (!seenHashes.has(promptHash)) {
- seenHashes.add(promptHash);
- const { content: truncatedPrompt, truncated } = truncateContent(newContext.systemPrompt);
- logOTelEvent("system_prompt", {
- system_prompt_hash: promptHash,
- system_prompt: truncatedPrompt,
- system_prompt_length: String(newContext.systemPrompt.length),
- ...truncated && { system_prompt_truncated: "true" }
- });
- }
- }
- if (newContext?.tools) {
- try {
- const toolsArray = jsonParse(newContext.tools);
- const toolsWithHashes = toolsArray.map((tool) => {
- const toolJson = jsonStringify(tool);
- const toolHash = shortHash(toolJson);
- return {
- name: typeof tool.name === "string" ? tool.name : "unknown",
- hash: toolHash,
- json: toolJson
- };
- });
- span.setAttribute("tools", jsonStringify(toolsWithHashes.map(({ name: name3, hash: hash2 }) => ({ name: name3, hash: hash2 }))));
- span.setAttribute("tools_count", toolsWithHashes.length);
- for (const { name: name3, hash: hash2, json: json2 } of toolsWithHashes) {
- if (!seenHashes.has(`tool_${hash2}`)) {
- seenHashes.add(`tool_${hash2}`);
- const { content: truncatedTool, truncated } = truncateContent(json2);
- logOTelEvent("tool", {
- tool_name: sanitizeToolNameForAnalytics(name3),
- tool_hash: hash2,
- tool: truncatedTool,
- ...truncated && { tool_truncated: "true" }
- });
- }
- }
- } catch {
- span.setAttribute("tools_parse_error", true);
- }
- }
- if (messagesForAPI && messagesForAPI.length > 0 && newContext?.querySource) {
- const querySource = newContext.querySource;
- const lastHash = lastReportedMessageHash.get(querySource);
- let startIndex = 0;
- if (lastHash) {
- for (let i6 = 0;i6 < messagesForAPI.length; i6++) {
- const msg = messagesForAPI[i6];
- if (msg && hashMessage(msg) === lastHash) {
- startIndex = i6 + 1;
- break;
- }
- }
- }
- const newMessages = messagesForAPI.slice(startIndex).filter((m4) => m4.type === "user");
- if (newMessages.length > 0) {
- const { contextParts, systemReminders } = formatMessagesForContext(newMessages);
- if (contextParts.length > 0) {
- const fullContext = contextParts.join(`
-
----
-
-`);
- const { content: truncatedContext, truncated } = truncateContent(fullContext);
- span.setAttributes({
- new_context: truncatedContext,
- new_context_message_count: newMessages.length,
- ...truncated && {
- new_context_truncated: true,
- new_context_original_length: fullContext.length
- }
- });
- }
- if (systemReminders.length > 0) {
- const fullReminders = systemReminders.join(`
-
----
-
-`);
- const { content: truncatedReminders, truncated: remindersTruncated } = truncateContent(fullReminders);
- span.setAttributes({
- system_reminders: truncatedReminders,
- system_reminders_count: systemReminders.length,
- ...remindersTruncated && {
- system_reminders_truncated: true,
- system_reminders_original_length: fullReminders.length
- }
- });
- }
- const lastMessage = messagesForAPI[messagesForAPI.length - 1];
- if (lastMessage) {
- lastReportedMessageHash.set(querySource, hashMessage(lastMessage));
- }
- }
- }
-}
-function addBetaLLMResponseAttributes(endAttributes, metadata) {
- if (!isBetaTracingEnabled() || !metadata) {
- return;
- }
- if (metadata.modelOutput !== undefined) {
- const { content: modelOutput, truncated: outputTruncated } = truncateContent(metadata.modelOutput);
- endAttributes["response.model_output"] = modelOutput;
- if (outputTruncated) {
- endAttributes["response.model_output_truncated"] = true;
- endAttributes["response.model_output_original_length"] = metadata.modelOutput.length;
- }
- }
- if (process.env.USER_TYPE === "ant" && metadata.thinkingOutput !== undefined) {
- const { content: thinkingOutput, truncated: thinkingTruncated } = truncateContent(metadata.thinkingOutput);
- endAttributes["response.thinking_output"] = thinkingOutput;
- if (thinkingTruncated) {
- endAttributes["response.thinking_output_truncated"] = true;
- endAttributes["response.thinking_output_original_length"] = metadata.thinkingOutput.length;
- }
- }
-}
-function addBetaToolInputAttributes(span, toolName, toolInput) {
- if (!isBetaTracingEnabled()) {
- return;
- }
- const { content: truncatedInput, truncated } = truncateContent(`[TOOL INPUT: ${toolName}]
-${toolInput}`);
- span.setAttributes({
- tool_input: truncatedInput,
- ...truncated && {
- tool_input_truncated: true,
- tool_input_original_length: toolInput.length
- }
- });
-}
-function addBetaToolResultAttributes(endAttributes, toolName, toolResult) {
- if (!isBetaTracingEnabled()) {
- return;
- }
- const { content: truncatedResult, truncated } = truncateContent(`[TOOL RESULT: ${toolName}]
-${toolResult}`);
- endAttributes["new_context"] = truncatedResult;
- if (truncated) {
- endAttributes["new_context_truncated"] = true;
- endAttributes["new_context_original_length"] = toolResult.length;
- }
-}
-var seenHashes, lastReportedMessageHash, MAX_CONTENT_SIZE, SYSTEM_REMINDER_REGEX;
-var init_betaSessionTracing = __esm(() => {
- init_state();
- init_growthbook();
- init_metadata();
- init_envUtils();
- init_slowOperations();
- init_events();
- seenHashes = new Set;
- lastReportedMessageHash = new Map;
- MAX_CONTENT_SIZE = 60 * 1024;
- SYSTEM_REMINDER_REGEX = /^\n?([\s\S]*?)\n?<\/system-reminder>$/;
-});
-
-// src/utils/telemetry/perfettoTracing.ts
-function stringToNumericHash(str) {
- return Math.abs(djb2Hash(str)) || 1;
-}
-function getProcessIdForAgent(agentId) {
- const existing = agentIdToProcessId.get(agentId);
- if (existing !== undefined)
- return existing;
- processIdCounter++;
- agentIdToProcessId.set(agentId, processIdCounter);
- return processIdCounter;
-}
-function getCurrentAgentInfo() {
- const agentId = getAgentId() ?? getSessionId();
- const agentName = getAgentName() ?? "main";
- const parentSessionId = getParentSessionId2();
- const existing = agentRegistry.get(agentId);
- if (existing)
- return existing;
- const info = {
- agentId,
- agentName,
- parentAgentId: parentSessionId,
- processId: agentId === getSessionId() ? 1 : getProcessIdForAgent(agentId),
- threadId: stringToNumericHash(agentName)
- };
- agentRegistry.set(agentId, info);
- totalAgentCount++;
- return info;
-}
-function getTimestamp() {
- return (Date.now() - startTimeMs) * 1000;
-}
-function generateSpanId() {
- return `span_${++spanIdCounter}`;
-}
-function initializePerfettoTracing() {
- const envValue = process.env.CLAUDE_CODE_PERFETTO_TRACE;
- logForDebugging(`[Perfetto] initializePerfettoTracing called, env value: ${envValue}`);
- if (false) {}
-}
-function emitProcessMetadata(agentInfo) {
- if (!isEnabled)
- return;
- metadataEvents.push({
- name: "process_name",
- cat: "__metadata",
- ph: "M",
- ts: 0,
- pid: agentInfo.processId,
- tid: 0,
- args: { name: agentInfo.agentName }
- });
- metadataEvents.push({
- name: "thread_name",
- cat: "__metadata",
- ph: "M",
- ts: 0,
- pid: agentInfo.processId,
- tid: agentInfo.threadId,
- args: { name: agentInfo.agentName }
- });
- if (agentInfo.parentAgentId) {
- metadataEvents.push({
- name: "parent_agent",
- cat: "__metadata",
- ph: "M",
- ts: 0,
- pid: agentInfo.processId,
- tid: 0,
- args: {
- parent_agent_id: agentInfo.parentAgentId
- }
- });
- }
-}
-function isPerfettoTracingEnabled() {
- return isEnabled;
-}
-function registerAgent(agentId, agentName, parentAgentId) {
- if (!isEnabled)
- return;
- const info = {
- agentId,
- agentName,
- parentAgentId,
- processId: getProcessIdForAgent(agentId),
- threadId: stringToNumericHash(agentName)
- };
- agentRegistry.set(agentId, info);
- totalAgentCount++;
- emitProcessMetadata(info);
-}
-function unregisterAgent(agentId) {
- if (!isEnabled)
- return;
- agentRegistry.delete(agentId);
- agentIdToProcessId.delete(agentId);
-}
-function startLLMRequestPerfettoSpan(args) {
- if (!isEnabled)
- return "";
- const spanId = generateSpanId();
- const agentInfo = getCurrentAgentInfo();
- pendingSpans.set(spanId, {
- name: "API Call",
- category: "api",
- startTime: getTimestamp(),
- agentInfo,
- args: {
- model: args.model,
- prompt_tokens: args.promptTokens,
- message_id: args.messageId,
- is_speculative: args.isSpeculative ?? false,
- query_source: args.querySource
- }
- });
- events.push({
- name: "API Call",
- cat: "api",
- ph: "B",
- ts: pendingSpans.get(spanId).startTime,
- pid: agentInfo.processId,
- tid: agentInfo.threadId,
- args: pendingSpans.get(spanId).args
- });
- return spanId;
-}
-function endLLMRequestPerfettoSpan(spanId, metadata) {
- if (!isEnabled || !spanId)
- return;
- const pending = pendingSpans.get(spanId);
- if (!pending)
- return;
- const endTime = getTimestamp();
- const duration3 = endTime - pending.startTime;
- const promptTokens = metadata.promptTokens ?? pending.args.prompt_tokens;
- const ttftMs = metadata.ttftMs;
- const ttltMs = metadata.ttltMs;
- const outputTokens = metadata.outputTokens;
- const cacheReadTokens = metadata.cacheReadTokens;
- const itps = ttftMs !== undefined && promptTokens !== undefined && ttftMs > 0 ? Math.round(promptTokens / (ttftMs / 1000) * 100) / 100 : undefined;
- const samplingMs = ttltMs !== undefined && ttftMs !== undefined ? ttltMs - ttftMs : undefined;
- const otps = samplingMs !== undefined && outputTokens !== undefined && samplingMs > 0 ? Math.round(outputTokens / (samplingMs / 1000) * 100) / 100 : undefined;
- const cacheHitRate = cacheReadTokens !== undefined && promptTokens !== undefined && promptTokens > 0 ? Math.round(cacheReadTokens / promptTokens * 1e4) / 100 : undefined;
- const requestSetupMs = metadata.requestSetupMs;
- const attemptStartTimes = metadata.attemptStartTimes;
- const args = {
- ...pending.args,
- ttft_ms: ttftMs,
- ttlt_ms: ttltMs,
- prompt_tokens: promptTokens,
- output_tokens: outputTokens,
- cache_read_tokens: cacheReadTokens,
- cache_creation_tokens: metadata.cacheCreationTokens,
- message_id: metadata.messageId ?? pending.args.message_id,
- success: metadata.success ?? true,
- error: metadata.error,
- duration_ms: duration3 / 1000,
- request_setup_ms: requestSetupMs,
- itps,
- otps,
- cache_hit_rate_pct: cacheHitRate
- };
- const setupUs = requestSetupMs !== undefined && requestSetupMs > 0 ? requestSetupMs * 1000 : 0;
- if (setupUs > 0) {
- const setupEndTs = pending.startTime + setupUs;
- events.push({
- name: "Request Setup",
- cat: "api,setup",
- ph: "B",
- ts: pending.startTime,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId,
- args: {
- request_setup_ms: requestSetupMs,
- attempt_count: attemptStartTimes?.length ?? 1
- }
- });
- if (attemptStartTimes && attemptStartTimes.length > 1) {
- const baseWallMs = attemptStartTimes[0];
- for (let i6 = 0;i6 < attemptStartTimes.length - 1; i6++) {
- const attemptStartUs = pending.startTime + (attemptStartTimes[i6] - baseWallMs) * 1000;
- const attemptEndUs = pending.startTime + (attemptStartTimes[i6 + 1] - baseWallMs) * 1000;
- events.push({
- name: `Attempt ${i6 + 1} (retry)`,
- cat: "api,retry",
- ph: "B",
- ts: attemptStartUs,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId,
- args: { attempt: i6 + 1 }
- });
- events.push({
- name: `Attempt ${i6 + 1} (retry)`,
- cat: "api,retry",
- ph: "E",
- ts: attemptEndUs,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId
- });
- }
- }
- events.push({
- name: "Request Setup",
- cat: "api,setup",
- ph: "E",
- ts: setupEndTs,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId
- });
- }
- if (ttftMs !== undefined) {
- const firstTokenStartTs = pending.startTime + setupUs;
- const firstTokenEndTs = firstTokenStartTs + ttftMs * 1000;
- events.push({
- name: "First Token",
- cat: "api,ttft",
- ph: "B",
- ts: firstTokenStartTs,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId,
- args: {
- ttft_ms: ttftMs,
- prompt_tokens: promptTokens,
- itps,
- cache_hit_rate_pct: cacheHitRate
- }
- });
- events.push({
- name: "First Token",
- cat: "api,ttft",
- ph: "E",
- ts: firstTokenEndTs,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId
- });
- const actualSamplingMs = ttltMs !== undefined ? ttltMs - ttftMs - setupUs / 1000 : undefined;
- if (actualSamplingMs !== undefined && actualSamplingMs > 0) {
- events.push({
- name: "Sampling",
- cat: "api,sampling",
- ph: "B",
- ts: firstTokenEndTs,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId,
- args: {
- sampling_ms: actualSamplingMs,
- output_tokens: outputTokens,
- otps
- }
- });
- events.push({
- name: "Sampling",
- cat: "api,sampling",
- ph: "E",
- ts: firstTokenEndTs + actualSamplingMs * 1000,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId
- });
- }
- }
- events.push({
- name: pending.name,
- cat: pending.category,
- ph: "E",
- ts: endTime,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId,
- args
- });
- pendingSpans.delete(spanId);
-}
-function startToolPerfettoSpan(toolName, args) {
- if (!isEnabled)
- return "";
- const spanId = generateSpanId();
- const agentInfo = getCurrentAgentInfo();
- pendingSpans.set(spanId, {
- name: `Tool: ${toolName}`,
- category: "tool",
- startTime: getTimestamp(),
- agentInfo,
- args: {
- tool_name: toolName,
- ...args
- }
- });
- events.push({
- name: `Tool: ${toolName}`,
- cat: "tool",
- ph: "B",
- ts: pendingSpans.get(spanId).startTime,
- pid: agentInfo.processId,
- tid: agentInfo.threadId,
- args: pendingSpans.get(spanId).args
- });
- return spanId;
-}
-function endToolPerfettoSpan(spanId, metadata) {
- if (!isEnabled || !spanId)
- return;
- const pending = pendingSpans.get(spanId);
- if (!pending)
- return;
- const endTime = getTimestamp();
- const duration3 = endTime - pending.startTime;
- const args = {
- ...pending.args,
- success: metadata?.success ?? true,
- error: metadata?.error,
- result_tokens: metadata?.resultTokens,
- duration_ms: duration3 / 1000
- };
- events.push({
- name: pending.name,
- cat: pending.category,
- ph: "E",
- ts: endTime,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId,
- args
- });
- pendingSpans.delete(spanId);
-}
-function startUserInputPerfettoSpan(context4) {
- if (!isEnabled)
- return "";
- const spanId = generateSpanId();
- const agentInfo = getCurrentAgentInfo();
- pendingSpans.set(spanId, {
- name: "Waiting for User Input",
- category: "user_input",
- startTime: getTimestamp(),
- agentInfo,
- args: {
- context: context4
- }
- });
- events.push({
- name: "Waiting for User Input",
- cat: "user_input",
- ph: "B",
- ts: pendingSpans.get(spanId).startTime,
- pid: agentInfo.processId,
- tid: agentInfo.threadId,
- args: pendingSpans.get(spanId).args
- });
- return spanId;
-}
-function endUserInputPerfettoSpan(spanId, metadata) {
- if (!isEnabled || !spanId)
- return;
- const pending = pendingSpans.get(spanId);
- if (!pending)
- return;
- const endTime = getTimestamp();
- const duration3 = endTime - pending.startTime;
- const args = {
- ...pending.args,
- decision: metadata?.decision,
- source: metadata?.source,
- duration_ms: duration3 / 1000
- };
- events.push({
- name: pending.name,
- cat: pending.category,
- ph: "E",
- ts: endTime,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId,
- args
- });
- pendingSpans.delete(spanId);
-}
-function startInteractionPerfettoSpan(userPrompt) {
- if (!isEnabled)
- return "";
- const spanId = generateSpanId();
- const agentInfo = getCurrentAgentInfo();
- pendingSpans.set(spanId, {
- name: "Interaction",
- category: "interaction",
- startTime: getTimestamp(),
- agentInfo,
- args: {
- user_prompt_length: userPrompt?.length
- }
- });
- events.push({
- name: "Interaction",
- cat: "interaction",
- ph: "B",
- ts: pendingSpans.get(spanId).startTime,
- pid: agentInfo.processId,
- tid: agentInfo.threadId,
- args: pendingSpans.get(spanId).args
- });
- return spanId;
-}
-function endInteractionPerfettoSpan(spanId) {
- if (!isEnabled || !spanId)
- return;
- const pending = pendingSpans.get(spanId);
- if (!pending)
- return;
- const endTime = getTimestamp();
- const duration3 = endTime - pending.startTime;
- events.push({
- name: pending.name,
- cat: pending.category,
- ph: "E",
- ts: endTime,
- pid: pending.agentInfo.processId,
- tid: pending.agentInfo.threadId,
- args: {
- ...pending.args,
- duration_ms: duration3 / 1000
- }
- });
- pendingSpans.delete(spanId);
-}
-var isEnabled = false, metadataEvents, events, pendingSpans, agentRegistry, totalAgentCount = 0, startTimeMs = 0, spanIdCounter = 0, processIdCounter = 1, agentIdToProcessId, STALE_SPAN_TTL_MS, STALE_SPAN_CLEANUP_INTERVAL_MS;
-var init_perfettoTracing = __esm(() => {
- init_state();
- init_cleanupRegistry();
- init_debug();
- init_envUtils();
- init_errors();
- init_slowOperations();
- init_teammate();
- metadataEvents = [];
- events = [];
- pendingSpans = new Map;
- agentRegistry = new Map;
- agentIdToProcessId = new Map;
- STALE_SPAN_TTL_MS = 30 * 60 * 1000;
- STALE_SPAN_CLEANUP_INTERVAL_MS = 60 * 1000;
-});
-
-// src/utils/telemetry/sessionTracing.ts
-import { AsyncLocalStorage as AsyncLocalStorage6 } from "async_hooks";
-function getSpanId(span) {
- return span.spanContext().spanId || "";
-}
-function ensureCleanupInterval() {
- if (_cleanupIntervalStarted)
- return;
- _cleanupIntervalStarted = true;
- const interval = setInterval(() => {
- const cutoff = Date.now() - SPAN_TTL_MS;
- for (const [spanId, weakRef] of activeSpans) {
- const ctx = weakRef.deref();
- if (ctx === undefined) {
- activeSpans.delete(spanId);
- strongSpans.delete(spanId);
- } else if (ctx.startTime < cutoff) {
- if (!ctx.ended)
- ctx.span.end();
- activeSpans.delete(spanId);
- strongSpans.delete(spanId);
- }
- }
- }, 60000);
- if (typeof interval.unref === "function") {
- interval.unref();
- }
-}
-function isEnhancedTelemetryEnabled() {
- if (false) {}
- return false;
-}
-function isAnyTracingEnabled() {
- return isEnhancedTelemetryEnabled() || isBetaTracingEnabled();
-}
-function getTracer() {
- return import_api5.trace.getTracer("com.anthropic.claude_code.tracing", "1.0.0");
-}
-function createSpanAttributes(spanType, customAttributes = {}) {
- const baseAttributes = getTelemetryAttributes();
- const attributes = {
- ...baseAttributes,
- "span.type": spanType,
- ...customAttributes
- };
- return attributes;
-}
-function startInteractionSpan(userPrompt) {
- ensureCleanupInterval();
- const perfettoSpanId = isPerfettoTracingEnabled() ? startInteractionPerfettoSpan(userPrompt) : undefined;
- if (!isAnyTracingEnabled()) {
- if (perfettoSpanId) {
- const dummySpan = import_api5.trace.getActiveSpan() || getTracer().startSpan("dummy");
- const spanId2 = getSpanId(dummySpan);
- const spanContextObj2 = {
- span: dummySpan,
- startTime: Date.now(),
- attributes: {},
- perfettoSpanId
- };
- activeSpans.set(spanId2, new WeakRef(spanContextObj2));
- interactionContext.enterWith(spanContextObj2);
- return dummySpan;
- }
- return import_api5.trace.getActiveSpan() || getTracer().startSpan("dummy");
- }
- const tracer = getTracer();
- const isUserPromptLoggingEnabled2 = isEnvTruthy(process.env.OTEL_LOG_USER_PROMPTS);
- const promptToLog = isUserPromptLoggingEnabled2 ? userPrompt : "";
- interactionSequence++;
- const attributes = createSpanAttributes("interaction", {
- user_prompt: promptToLog,
- user_prompt_length: userPrompt.length,
- "interaction.sequence": interactionSequence
- });
- const span = tracer.startSpan("claude_code.interaction", {
- attributes
- });
- addBetaInteractionAttributes(span, userPrompt);
- const spanId = getSpanId(span);
- const spanContextObj = {
- span,
- startTime: Date.now(),
- attributes,
- perfettoSpanId
- };
- activeSpans.set(spanId, new WeakRef(spanContextObj));
- interactionContext.enterWith(spanContextObj);
- return span;
-}
-function endInteractionSpan() {
- const spanContext = interactionContext.getStore();
- if (!spanContext) {
- return;
- }
- if (spanContext.ended) {
- return;
- }
- if (spanContext.perfettoSpanId) {
- endInteractionPerfettoSpan(spanContext.perfettoSpanId);
- }
- if (!isAnyTracingEnabled()) {
- spanContext.ended = true;
- activeSpans.delete(getSpanId(spanContext.span));
- interactionContext.enterWith(undefined);
- return;
- }
- const duration3 = Date.now() - spanContext.startTime;
- spanContext.span.setAttributes({
- "interaction.duration_ms": duration3
- });
- spanContext.span.end();
- spanContext.ended = true;
- activeSpans.delete(getSpanId(spanContext.span));
- interactionContext.enterWith(undefined);
-}
-function startLLMRequestSpan(model, newContext, messagesForAPI, fastMode) {
- const perfettoSpanId = isPerfettoTracingEnabled() ? startLLMRequestPerfettoSpan({
- model,
- querySource: newContext?.querySource,
- messageId: undefined
- }) : undefined;
- if (!isAnyTracingEnabled()) {
- if (perfettoSpanId) {
- const dummySpan = import_api5.trace.getActiveSpan() || getTracer().startSpan("dummy");
- const spanId2 = getSpanId(dummySpan);
- const spanContextObj2 = {
- span: dummySpan,
- startTime: Date.now(),
- attributes: { model },
- perfettoSpanId
- };
- activeSpans.set(spanId2, new WeakRef(spanContextObj2));
- strongSpans.set(spanId2, spanContextObj2);
- return dummySpan;
- }
- return import_api5.trace.getActiveSpan() || getTracer().startSpan("dummy");
- }
- const tracer = getTracer();
- const parentSpanCtx = interactionContext.getStore();
- const attributes = createSpanAttributes("llm_request", {
- model,
- "llm_request.context": parentSpanCtx ? "interaction" : "standalone",
- speed: fastMode ? "fast" : "normal"
- });
- const ctx = parentSpanCtx ? import_api5.trace.setSpan(import_api5.context.active(), parentSpanCtx.span) : import_api5.context.active();
- const span = tracer.startSpan("claude_code.llm_request", { attributes }, ctx);
- if (newContext?.querySource) {
- span.setAttribute("query_source", newContext.querySource);
- }
- addBetaLLMRequestAttributes(span, newContext, messagesForAPI);
- const spanId = getSpanId(span);
- const spanContextObj = {
- span,
- startTime: Date.now(),
- attributes,
- perfettoSpanId
- };
- activeSpans.set(spanId, new WeakRef(spanContextObj));
- strongSpans.set(spanId, spanContextObj);
- return span;
-}
-function endLLMRequestSpan(span, metadata) {
- let llmSpanContext;
- if (span) {
- const spanId2 = getSpanId(span);
- llmSpanContext = activeSpans.get(spanId2)?.deref();
- } else {
- llmSpanContext = Array.from(activeSpans.values()).findLast((r4) => {
- const ctx = r4.deref();
- return ctx?.attributes["span.type"] === "llm_request" || ctx?.attributes["model"];
- })?.deref();
- }
- if (!llmSpanContext) {
- return;
- }
- const duration3 = Date.now() - llmSpanContext.startTime;
- if (llmSpanContext.perfettoSpanId) {
- endLLMRequestPerfettoSpan(llmSpanContext.perfettoSpanId, {
- ttftMs: metadata?.ttftMs,
- ttltMs: duration3,
- promptTokens: metadata?.inputTokens,
- outputTokens: metadata?.outputTokens,
- cacheReadTokens: metadata?.cacheReadTokens,
- cacheCreationTokens: metadata?.cacheCreationTokens,
- success: metadata?.success,
- error: metadata?.error,
- requestSetupMs: metadata?.requestSetupMs,
- attemptStartTimes: metadata?.attemptStartTimes
- });
- }
- if (!isAnyTracingEnabled()) {
- const spanId2 = getSpanId(llmSpanContext.span);
- activeSpans.delete(spanId2);
- strongSpans.delete(spanId2);
- return;
- }
- const endAttributes = {
- duration_ms: duration3
- };
- if (metadata) {
- if (metadata.inputTokens !== undefined)
- endAttributes["input_tokens"] = metadata.inputTokens;
- if (metadata.outputTokens !== undefined)
- endAttributes["output_tokens"] = metadata.outputTokens;
- if (metadata.cacheReadTokens !== undefined)
- endAttributes["cache_read_tokens"] = metadata.cacheReadTokens;
- if (metadata.cacheCreationTokens !== undefined)
- endAttributes["cache_creation_tokens"] = metadata.cacheCreationTokens;
- if (metadata.success !== undefined)
- endAttributes["success"] = metadata.success;
- if (metadata.statusCode !== undefined)
- endAttributes["status_code"] = metadata.statusCode;
- if (metadata.error !== undefined)
- endAttributes["error"] = metadata.error;
- if (metadata.attempt !== undefined)
- endAttributes["attempt"] = metadata.attempt;
- if (metadata.hasToolCall !== undefined)
- endAttributes["response.has_tool_call"] = metadata.hasToolCall;
- if (metadata.ttftMs !== undefined)
- endAttributes["ttft_ms"] = metadata.ttftMs;
- addBetaLLMResponseAttributes(endAttributes, metadata);
- }
- llmSpanContext.span.setAttributes(endAttributes);
- llmSpanContext.span.end();
- const spanId = getSpanId(llmSpanContext.span);
- activeSpans.delete(spanId);
- strongSpans.delete(spanId);
-}
-function startToolSpan(toolName, toolAttributes, toolInput) {
- const perfettoSpanId = isPerfettoTracingEnabled() ? startToolPerfettoSpan(toolName, toolAttributes) : undefined;
- if (!isAnyTracingEnabled()) {
- if (perfettoSpanId) {
- const dummySpan = import_api5.trace.getActiveSpan() || getTracer().startSpan("dummy");
- const spanId2 = getSpanId(dummySpan);
- const spanContextObj2 = {
- span: dummySpan,
- startTime: Date.now(),
- attributes: { "span.type": "tool", tool_name: toolName },
- perfettoSpanId
- };
- activeSpans.set(spanId2, new WeakRef(spanContextObj2));
- toolContext.enterWith(spanContextObj2);
- return dummySpan;
- }
- return import_api5.trace.getActiveSpan() || getTracer().startSpan("dummy");
- }
- const tracer = getTracer();
- const parentSpanCtx = interactionContext.getStore();
- const attributes = createSpanAttributes("tool", {
- tool_name: toolName,
- ...toolAttributes
- });
- const ctx = parentSpanCtx ? import_api5.trace.setSpan(import_api5.context.active(), parentSpanCtx.span) : import_api5.context.active();
- const span = tracer.startSpan("claude_code.tool", { attributes }, ctx);
- if (toolInput) {
- addBetaToolInputAttributes(span, toolName, toolInput);
- }
- const spanId = getSpanId(span);
- const spanContextObj = {
- span,
- startTime: Date.now(),
- attributes,
- perfettoSpanId
- };
- activeSpans.set(spanId, new WeakRef(spanContextObj));
- toolContext.enterWith(spanContextObj);
- return span;
-}
-function startToolBlockedOnUserSpan() {
- const perfettoSpanId = isPerfettoTracingEnabled() ? startUserInputPerfettoSpan("tool_permission") : undefined;
- if (!isAnyTracingEnabled()) {
- if (perfettoSpanId) {
- const dummySpan = import_api5.trace.getActiveSpan() || getTracer().startSpan("dummy");
- const spanId2 = getSpanId(dummySpan);
- const spanContextObj2 = {
- span: dummySpan,
- startTime: Date.now(),
- attributes: { "span.type": "tool.blocked_on_user" },
- perfettoSpanId
- };
- activeSpans.set(spanId2, new WeakRef(spanContextObj2));
- strongSpans.set(spanId2, spanContextObj2);
- return dummySpan;
- }
- return import_api5.trace.getActiveSpan() || getTracer().startSpan("dummy");
- }
- const tracer = getTracer();
- const parentSpanCtx = toolContext.getStore();
- const attributes = createSpanAttributes("tool.blocked_on_user");
- const ctx = parentSpanCtx ? import_api5.trace.setSpan(import_api5.context.active(), parentSpanCtx.span) : import_api5.context.active();
- const span = tracer.startSpan("claude_code.tool.blocked_on_user", { attributes }, ctx);
- const spanId = getSpanId(span);
- const spanContextObj = {
- span,
- startTime: Date.now(),
- attributes,
- perfettoSpanId
- };
- activeSpans.set(spanId, new WeakRef(spanContextObj));
- strongSpans.set(spanId, spanContextObj);
- return span;
-}
-function endToolBlockedOnUserSpan(decision, source) {
- const blockedSpanContext = Array.from(activeSpans.values()).findLast((r4) => r4.deref()?.attributes["span.type"] === "tool.blocked_on_user")?.deref();
- if (!blockedSpanContext) {
- return;
- }
- if (blockedSpanContext.perfettoSpanId) {
- endUserInputPerfettoSpan(blockedSpanContext.perfettoSpanId, {
- decision,
- source
- });
- }
- if (!isAnyTracingEnabled()) {
- const spanId2 = getSpanId(blockedSpanContext.span);
- activeSpans.delete(spanId2);
- strongSpans.delete(spanId2);
- return;
- }
- const duration3 = Date.now() - blockedSpanContext.startTime;
- const attributes = {
- duration_ms: duration3
- };
- if (decision) {
- attributes["decision"] = decision;
- }
- if (source) {
- attributes["source"] = source;
- }
- blockedSpanContext.span.setAttributes(attributes);
- blockedSpanContext.span.end();
- const spanId = getSpanId(blockedSpanContext.span);
- activeSpans.delete(spanId);
- strongSpans.delete(spanId);
-}
-function startToolExecutionSpan() {
- if (!isAnyTracingEnabled()) {
- return import_api5.trace.getActiveSpan() || getTracer().startSpan("dummy");
- }
- const tracer = getTracer();
- const parentSpanCtx = toolContext.getStore();
- const attributes = createSpanAttributes("tool.execution");
- const ctx = parentSpanCtx ? import_api5.trace.setSpan(import_api5.context.active(), parentSpanCtx.span) : import_api5.context.active();
- const span = tracer.startSpan("claude_code.tool.execution", { attributes }, ctx);
- const spanId = getSpanId(span);
- const spanContextObj = {
- span,
- startTime: Date.now(),
- attributes
- };
- activeSpans.set(spanId, new WeakRef(spanContextObj));
- strongSpans.set(spanId, spanContextObj);
- return span;
-}
-function endToolExecutionSpan(metadata) {
- if (!isAnyTracingEnabled()) {
- return;
- }
- const executionSpanContext = Array.from(activeSpans.values()).findLast((r4) => r4.deref()?.attributes["span.type"] === "tool.execution")?.deref();
- if (!executionSpanContext) {
- return;
- }
- const duration3 = Date.now() - executionSpanContext.startTime;
- const attributes = {
- duration_ms: duration3
- };
- if (metadata) {
- if (metadata.success !== undefined)
- attributes["success"] = metadata.success;
- if (metadata.error !== undefined)
- attributes["error"] = metadata.error;
- }
- executionSpanContext.span.setAttributes(attributes);
- executionSpanContext.span.end();
- const spanId = getSpanId(executionSpanContext.span);
- activeSpans.delete(spanId);
- strongSpans.delete(spanId);
-}
-function endToolSpan(toolResult, resultTokens) {
- const toolSpanContext = toolContext.getStore();
- if (!toolSpanContext) {
- return;
- }
- if (toolSpanContext.perfettoSpanId) {
- endToolPerfettoSpan(toolSpanContext.perfettoSpanId, {
- success: true,
- resultTokens
- });
- }
- if (!isAnyTracingEnabled()) {
- const spanId2 = getSpanId(toolSpanContext.span);
- activeSpans.delete(spanId2);
- toolContext.enterWith(undefined);
- return;
- }
- const duration3 = Date.now() - toolSpanContext.startTime;
- const endAttributes = {
- duration_ms: duration3
- };
- if (toolResult) {
- const toolName = toolSpanContext.attributes["tool_name"] || "unknown";
- addBetaToolResultAttributes(endAttributes, toolName, toolResult);
- }
- if (resultTokens !== undefined) {
- endAttributes["result_tokens"] = resultTokens;
- }
- toolSpanContext.span.setAttributes(endAttributes);
- toolSpanContext.span.end();
- const spanId = getSpanId(toolSpanContext.span);
- activeSpans.delete(spanId);
- toolContext.enterWith(undefined);
-}
-function isToolContentLoggingEnabled() {
- return isEnvTruthy(process.env.OTEL_LOG_TOOL_CONTENT);
-}
-function addToolContentEvent(eventName, attributes) {
- if (!isAnyTracingEnabled() || !isToolContentLoggingEnabled()) {
- return;
- }
- const currentSpanCtx = toolContext.getStore();
- if (!currentSpanCtx) {
- return;
- }
- const processedAttributes = {};
- for (const [key2, value] of Object.entries(attributes)) {
- if (typeof value === "string") {
- const { content, truncated } = truncateContent(value);
- processedAttributes[key2] = content;
- if (truncated) {
- processedAttributes[`${key2}_truncated`] = true;
- processedAttributes[`${key2}_original_length`] = value.length;
- }
- } else {
- processedAttributes[key2] = value;
- }
- }
- currentSpanCtx.span.addEvent(eventName, processedAttributes);
-}
-function startHookSpan(hookEvent, hookName, numHooks, hookDefinitions) {
- if (!isBetaTracingEnabled()) {
- return import_api5.trace.getActiveSpan() || getTracer().startSpan("dummy");
- }
- const tracer = getTracer();
- const parentSpanCtx = toolContext.getStore() ?? interactionContext.getStore();
- const attributes = createSpanAttributes("hook", {
- hook_event: hookEvent,
- hook_name: hookName,
- num_hooks: numHooks,
- hook_definitions: hookDefinitions
- });
- const ctx = parentSpanCtx ? import_api5.trace.setSpan(import_api5.context.active(), parentSpanCtx.span) : import_api5.context.active();
- const span = tracer.startSpan("claude_code.hook", { attributes }, ctx);
- const spanId = getSpanId(span);
- const spanContextObj = {
- span,
- startTime: Date.now(),
- attributes
- };
- activeSpans.set(spanId, new WeakRef(spanContextObj));
- strongSpans.set(spanId, spanContextObj);
- return span;
-}
-function endHookSpan(span, metadata) {
- if (!isBetaTracingEnabled()) {
- return;
- }
- const spanId = getSpanId(span);
- const spanContext = activeSpans.get(spanId)?.deref();
- if (!spanContext) {
- return;
- }
- const duration3 = Date.now() - spanContext.startTime;
- const endAttributes = {
- duration_ms: duration3
- };
- if (metadata) {
- if (metadata.numSuccess !== undefined)
- endAttributes["num_success"] = metadata.numSuccess;
- if (metadata.numBlocking !== undefined)
- endAttributes["num_blocking"] = metadata.numBlocking;
- if (metadata.numNonBlockingError !== undefined)
- endAttributes["num_non_blocking_error"] = metadata.numNonBlockingError;
- if (metadata.numCancelled !== undefined)
- endAttributes["num_cancelled"] = metadata.numCancelled;
- }
- spanContext.span.setAttributes(endAttributes);
- spanContext.span.end();
- activeSpans.delete(spanId);
- strongSpans.delete(spanId);
-}
-var import_api5, interactionContext, toolContext, activeSpans, strongSpans, interactionSequence = 0, _cleanupIntervalStarted = false, SPAN_TTL_MS;
-var init_sessionTracing = __esm(() => {
- init_growthbook();
- init_envUtils();
- init_telemetryAttributes();
- init_betaSessionTracing();
- init_perfettoTracing();
- import_api5 = __toESM(require_src7(), 1);
- interactionContext = new AsyncLocalStorage6;
- toolContext = new AsyncLocalStorage6;
- activeSpans = new Map;
- strongSpans = new Map;
- SPAN_TTL_MS = 30 * 60 * 1000;
-});
-
-// src/utils/permissions/PermissionRule.ts
-var permissionBehaviorSchema, permissionRuleValueSchema;
-var init_PermissionRule = __esm(() => {
- init_v4();
- permissionBehaviorSchema = lazySchema(() => v4_default.enum(["allow", "deny", "ask"]));
- permissionRuleValueSchema = lazySchema(() => v4_default.object({
- toolName: v4_default.string(),
- ruleContent: v4_default.string().optional()
- }));
-});
-
-// src/utils/permissions/PermissionUpdateSchema.ts
-var permissionUpdateDestinationSchema, permissionUpdateSchema;
-var init_PermissionUpdateSchema = __esm(() => {
- init_v4();
- init_PermissionMode();
- init_PermissionRule();
- permissionUpdateDestinationSchema = lazySchema(() => v4_default.enum([
- "userSettings",
- "projectSettings",
- "localSettings",
- "session",
- "cliArg"
- ]));
- permissionUpdateSchema = lazySchema(() => v4_default.discriminatedUnion("type", [
- v4_default.object({
- type: v4_default.literal("addRules"),
- rules: v4_default.array(permissionRuleValueSchema()),
- behavior: permissionBehaviorSchema(),
- destination: permissionUpdateDestinationSchema()
- }),
- v4_default.object({
- type: v4_default.literal("replaceRules"),
- rules: v4_default.array(permissionRuleValueSchema()),
- behavior: permissionBehaviorSchema(),
- destination: permissionUpdateDestinationSchema()
- }),
- v4_default.object({
- type: v4_default.literal("removeRules"),
- rules: v4_default.array(permissionRuleValueSchema()),
- behavior: permissionBehaviorSchema(),
- destination: permissionUpdateDestinationSchema()
- }),
- v4_default.object({
- type: v4_default.literal("setMode"),
- mode: externalPermissionModeSchema(),
- destination: permissionUpdateDestinationSchema()
- }),
- v4_default.object({
- type: v4_default.literal("addDirectories"),
- directories: v4_default.array(v4_default.string()),
- destination: permissionUpdateDestinationSchema()
- }),
- v4_default.object({
- type: v4_default.literal("removeDirectories"),
- directories: v4_default.array(v4_default.string()),
- destination: permissionUpdateDestinationSchema()
- })
- ]));
-});
-
-// src/types/hooks.ts
-function isSyncHookJSONOutput(json2) {
- return !(("async" in json2) && json2.async === true);
-}
-function isAsyncHookJSONOutput(json2) {
- return "async" in json2 && json2.async === true;
-}
-var promptRequestSchema, syncHookResponseSchema, hookJSONOutputSchema;
-var init_hooks2 = __esm(() => {
- init_v4();
- init_agentSdkTypes();
- init_PermissionRule();
- init_PermissionUpdateSchema();
- promptRequestSchema = lazySchema(() => exports_external.object({
- prompt: exports_external.string(),
- message: exports_external.string(),
- options: exports_external.array(exports_external.object({
- key: exports_external.string(),
- label: exports_external.string(),
- description: exports_external.string().optional()
- }))
- }));
- syncHookResponseSchema = lazySchema(() => exports_external.object({
- continue: exports_external.boolean().describe("Whether Claude should continue after hook (default: true)").optional(),
- suppressOutput: exports_external.boolean().describe("Hide stdout from transcript (default: false)").optional(),
- stopReason: exports_external.string().describe("Message shown when continue is false").optional(),
- decision: exports_external.enum(["approve", "block"]).optional(),
- reason: exports_external.string().describe("Explanation for the decision").optional(),
- systemMessage: exports_external.string().describe("Warning message shown to the user").optional(),
- hookSpecificOutput: exports_external.union([
- exports_external.object({
- hookEventName: exports_external.literal("PreToolUse"),
- permissionDecision: permissionBehaviorSchema().optional(),
- permissionDecisionReason: exports_external.string().optional(),
- updatedInput: exports_external.record(exports_external.string(), exports_external.unknown()).optional(),
- additionalContext: exports_external.string().optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("UserPromptSubmit"),
- additionalContext: exports_external.string().optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("SessionStart"),
- additionalContext: exports_external.string().optional(),
- initialUserMessage: exports_external.string().optional(),
- watchPaths: exports_external.array(exports_external.string()).describe("Absolute paths to watch for FileChanged hooks").optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("Setup"),
- additionalContext: exports_external.string().optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("SubagentStart"),
- additionalContext: exports_external.string().optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("PostToolUse"),
- additionalContext: exports_external.string().optional(),
- updatedMCPToolOutput: exports_external.unknown().describe("Updates the output for MCP tools").optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("PostToolUseFailure"),
- additionalContext: exports_external.string().optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("PermissionDenied"),
- retry: exports_external.boolean().optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("Notification"),
- additionalContext: exports_external.string().optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("PermissionRequest"),
- decision: exports_external.union([
- exports_external.object({
- behavior: exports_external.literal("allow"),
- updatedInput: exports_external.record(exports_external.string(), exports_external.unknown()).optional(),
- updatedPermissions: exports_external.array(permissionUpdateSchema()).optional()
- }),
- exports_external.object({
- behavior: exports_external.literal("deny"),
- message: exports_external.string().optional(),
- interrupt: exports_external.boolean().optional()
- })
- ])
- }),
- exports_external.object({
- hookEventName: exports_external.literal("Elicitation"),
- action: exports_external.enum(["accept", "decline", "cancel"]).optional(),
- content: exports_external.record(exports_external.string(), exports_external.unknown()).optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("ElicitationResult"),
- action: exports_external.enum(["accept", "decline", "cancel"]).optional(),
- content: exports_external.record(exports_external.string(), exports_external.unknown()).optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("CwdChanged"),
- watchPaths: exports_external.array(exports_external.string()).describe("Absolute paths to watch for FileChanged hooks").optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("FileChanged"),
- watchPaths: exports_external.array(exports_external.string()).describe("Absolute paths to watch for FileChanged hooks").optional()
- }),
- exports_external.object({
- hookEventName: exports_external.literal("WorktreeCreate"),
- worktreePath: exports_external.string()
- })
- ]).optional()
- }));
- hookJSONOutputSchema = lazySchema(() => {
- const asyncHookResponseSchema = exports_external.object({
- async: exports_external.literal(true),
- asyncTimeout: exports_external.number().optional()
- });
- return exports_external.union([asyncHookResponseSchema, syncHookResponseSchema()]);
- });
-});
-
-// src/utils/hooks/sessionHooks.ts
-function addSessionHook(setAppState, sessionId, event, matcher, hook, onHookSuccess, skillRoot) {
- addHookToSession(setAppState, sessionId, event, matcher, hook, onHookSuccess, skillRoot);
-}
-function addFunctionHook(setAppState, sessionId, event, matcher, callback, errorMessage2, options2) {
- const id = options2?.id || `function-hook-${Date.now()}-${Math.random()}`;
- const hook = {
- type: "function",
- id,
- timeout: options2?.timeout || 5000,
- callback,
- errorMessage: errorMessage2
- };
- addHookToSession(setAppState, sessionId, event, matcher, hook);
- return id;
-}
-function addHookToSession(setAppState, sessionId, event, matcher, hook, onHookSuccess, skillRoot) {
- setAppState((prev) => {
- const store = prev.sessionHooks.get(sessionId) ?? { hooks: {} };
- const eventMatchers = store.hooks[event] || [];
- const existingMatcherIndex = eventMatchers.findIndex((m4) => m4.matcher === matcher && m4.skillRoot === skillRoot);
- let updatedMatchers;
- if (existingMatcherIndex >= 0) {
- updatedMatchers = [...eventMatchers];
- const existingMatcher = updatedMatchers[existingMatcherIndex];
- updatedMatchers[existingMatcherIndex] = {
- matcher: existingMatcher.matcher,
- skillRoot: existingMatcher.skillRoot,
- hooks: [...existingMatcher.hooks, { hook, onHookSuccess }]
- };
- } else {
- updatedMatchers = [
- ...eventMatchers,
- {
- matcher,
- skillRoot,
- hooks: [{ hook, onHookSuccess }]
- }
- ];
- }
- const newHooks = { ...store.hooks, [event]: updatedMatchers };
- prev.sessionHooks.set(sessionId, { hooks: newHooks });
- return prev;
- });
- logForDebugging(`Added session hook for event ${event} in session ${sessionId}`);
-}
-function removeSessionHook(setAppState, sessionId, event, hook) {
- setAppState((prev) => {
- const store = prev.sessionHooks.get(sessionId);
- if (!store) {
- return prev;
- }
- const eventMatchers = store.hooks[event] || [];
- const updatedMatchers = eventMatchers.map((matcher) => {
- const updatedHooks = matcher.hooks.filter((h5) => !isHookEqual(h5.hook, hook));
- return updatedHooks.length > 0 ? { ...matcher, hooks: updatedHooks } : null;
- }).filter((m4) => m4 !== null);
- const newHooks = updatedMatchers.length > 0 ? { ...store.hooks, [event]: updatedMatchers } : { ...store.hooks };
- if (updatedMatchers.length === 0) {
- delete newHooks[event];
- }
- prev.sessionHooks.set(sessionId, { ...store, hooks: newHooks });
- return prev;
- });
- logForDebugging(`Removed session hook for event ${event} in session ${sessionId}`);
-}
-function convertToHookMatchers(sessionMatchers) {
- return sessionMatchers.map((sm) => ({
- matcher: sm.matcher,
- skillRoot: sm.skillRoot,
- hooks: sm.hooks.map((h5) => h5.hook).filter((h5) => h5.type !== "function")
- }));
-}
-function getSessionHooks(appState, sessionId, event) {
- const store = appState.sessionHooks.get(sessionId);
- if (!store) {
- return new Map;
- }
- const result = new Map;
- if (event) {
- const sessionMatchers = store.hooks[event];
- if (sessionMatchers) {
- result.set(event, convertToHookMatchers(sessionMatchers));
- }
- return result;
- }
- for (const evt of HOOK_EVENTS) {
- const sessionMatchers = store.hooks[evt];
- if (sessionMatchers) {
- result.set(evt, convertToHookMatchers(sessionMatchers));
- }
- }
- return result;
-}
-function getSessionFunctionHooks(appState, sessionId, event) {
- const store = appState.sessionHooks.get(sessionId);
- if (!store) {
- return new Map;
- }
- const result = new Map;
- const extractFunctionHooks = (sessionMatchers) => {
- return sessionMatchers.map((sm) => ({
- matcher: sm.matcher,
- hooks: sm.hooks.map((h5) => h5.hook).filter((h5) => h5.type === "function")
- })).filter((m4) => m4.hooks.length > 0);
- };
- if (event) {
- const sessionMatchers = store.hooks[event];
- if (sessionMatchers) {
- const functionMatchers = extractFunctionHooks(sessionMatchers);
- if (functionMatchers.length > 0) {
- result.set(event, functionMatchers);
- }
- }
- return result;
- }
- for (const evt of HOOK_EVENTS) {
- const sessionMatchers = store.hooks[evt];
- if (sessionMatchers) {
- const functionMatchers = extractFunctionHooks(sessionMatchers);
- if (functionMatchers.length > 0) {
- result.set(evt, functionMatchers);
- }
- }
- }
- return result;
-}
-function getSessionHookCallback(appState, sessionId, event, matcher, hook) {
- const store = appState.sessionHooks.get(sessionId);
- if (!store) {
- return;
- }
- const eventMatchers = store.hooks[event];
- if (!eventMatchers) {
- return;
- }
- for (const matcherEntry of eventMatchers) {
- if (matcherEntry.matcher === matcher || matcher === "") {
- const hookEntry = matcherEntry.hooks.find((h5) => isHookEqual(h5.hook, hook));
- if (hookEntry) {
- return hookEntry;
- }
- }
- }
- return;
-}
-function clearSessionHooks(setAppState, sessionId) {
- setAppState((prev) => {
- prev.sessionHooks.delete(sessionId);
- return prev;
- });
- logForDebugging(`Cleared all session hooks for session ${sessionId}`);
-}
-var init_sessionHooks = __esm(() => {
- init_agentSdkTypes();
- init_debug();
- init_hooksSettings();
-});
-
-// src/utils/hooks/hooksSettings.ts
-import { resolve as resolve19 } from "path";
-function isHookEqual(a5, b5) {
- if (a5.type !== b5.type)
- return false;
- const sameIf = (x4, y3) => (x4.if ?? "") === (y3.if ?? "");
- switch (a5.type) {
- case "command":
- return b5.type === "command" && a5.command === b5.command && (a5.shell ?? DEFAULT_HOOK_SHELL) === (b5.shell ?? DEFAULT_HOOK_SHELL) && sameIf(a5, b5);
- case "prompt":
- return b5.type === "prompt" && a5.prompt === b5.prompt && sameIf(a5, b5);
- case "agent":
- return b5.type === "agent" && a5.prompt === b5.prompt && sameIf(a5, b5);
- case "http":
- return b5.type === "http" && a5.url === b5.url && sameIf(a5, b5);
- case "function":
- return false;
- }
-}
-function getHookDisplayText(hook) {
- if ("statusMessage" in hook && hook.statusMessage) {
- return hook.statusMessage;
- }
- switch (hook.type) {
- case "command":
- return hook.command;
- case "prompt":
- return hook.prompt;
- case "agent":
- return hook.prompt;
- case "http":
- return hook.url;
- case "callback":
- return "callback";
- case "function":
- return "function";
- }
-}
-function getAllHooks(appState) {
- const hooks = [];
- const policySettings = getSettingsForSource("policySettings");
- const restrictedToManagedOnly = policySettings?.allowManagedHooksOnly === true;
- if (!restrictedToManagedOnly) {
- const sources = [
- "userSettings",
- "projectSettings",
- "localSettings"
- ];
- const seenFiles = new Set;
- for (const source of sources) {
- const filePath = getSettingsFilePathForSource(source);
- if (filePath) {
- const resolvedPath5 = resolve19(filePath);
- if (seenFiles.has(resolvedPath5)) {
- continue;
- }
- seenFiles.add(resolvedPath5);
- }
- const sourceSettings = getSettingsForSource(source);
- if (!sourceSettings?.hooks) {
- continue;
- }
- for (const [event, matchers] of Object.entries(sourceSettings.hooks)) {
- for (const matcher of matchers) {
- for (const hookCommand of matcher.hooks) {
- hooks.push({
- event,
- config: hookCommand,
- matcher: matcher.matcher,
- source
- });
- }
- }
- }
- }
- }
- const sessionId = getSessionId();
- const sessionHooks = getSessionHooks(appState, sessionId);
- for (const [event, matchers] of sessionHooks.entries()) {
- for (const matcher of matchers) {
- for (const hookCommand of matcher.hooks) {
- hooks.push({
- event,
- config: hookCommand,
- matcher: matcher.matcher,
- source: "sessionHook"
- });
- }
- }
- }
- return hooks;
-}
-function hookSourceDescriptionDisplayString(source) {
- switch (source) {
- case "userSettings":
- return "User settings (~/.claude/settings.json)";
- case "projectSettings":
- return "Project settings (.claude/settings.json)";
- case "localSettings":
- return "Local settings (.claude/settings.local.json)";
- case "pluginHook":
- return "Plugin hooks (~/.claude/plugins/*/hooks/hooks.json)";
- case "sessionHook":
- return "Session hooks (in-memory, temporary)";
- case "builtinHook":
- return "Built-in hooks (registered internally by Claude Code)";
- default:
- return source;
- }
-}
-function hookSourceHeaderDisplayString(source) {
- switch (source) {
- case "userSettings":
- return "User Settings";
- case "projectSettings":
- return "Project Settings";
- case "localSettings":
- return "Local Settings";
- case "pluginHook":
- return "Plugin Hooks";
- case "sessionHook":
- return "Session Hooks";
- case "builtinHook":
- return "Built-in Hooks";
- default:
- return source;
- }
-}
-function hookSourceInlineDisplayString(source) {
- switch (source) {
- case "userSettings":
- return "User";
- case "projectSettings":
- return "Project";
- case "localSettings":
- return "Local";
- case "pluginHook":
- return "Plugin";
- case "sessionHook":
- return "Session";
- case "builtinHook":
- return "Built-in";
- default:
- return source;
- }
-}
-function sortMatchersByPriority(matchers, hooksByEventAndMatcher, selectedEvent) {
- const sourcePriority = SOURCES.reduce((acc, source, index2) => {
- acc[source] = index2;
- return acc;
- }, {});
- return [...matchers].sort((a5, b5) => {
- const aHooks = hooksByEventAndMatcher[selectedEvent]?.[a5] || [];
- const bHooks = hooksByEventAndMatcher[selectedEvent]?.[b5] || [];
- const aSources = Array.from(new Set(aHooks.map((h5) => h5.source)));
- const bSources = Array.from(new Set(bHooks.map((h5) => h5.source)));
- const getSourcePriority = (source) => source === "pluginHook" || source === "builtinHook" ? 999 : sourcePriority[source];
- const aHighestPriority = Math.min(...aSources.map(getSourcePriority));
- const bHighestPriority = Math.min(...bSources.map(getSourcePriority));
- if (aHighestPriority !== bHighestPriority) {
- return aHighestPriority - bHighestPriority;
- }
- return a5.localeCompare(b5);
- });
-}
-var init_hooksSettings = __esm(() => {
- init_state();
- init_constants2();
- init_settings2();
- init_shellProvider();
- init_sessionHooks();
-});
-
-// src/utils/abortController.ts
-import { setMaxListeners as setMaxListeners2 } from "events";
-function createAbortController(maxListeners = DEFAULT_MAX_LISTENERS) {
- const controller = new AbortController;
- setMaxListeners2(maxListeners, controller.signal);
- return controller;
-}
-function propagateAbort(weakChild) {
- const parent = this.deref();
- weakChild.deref()?.abort(parent?.signal.reason);
-}
-function removeAbortHandler(weakHandler) {
- const parent = this.deref();
- const handler = weakHandler.deref();
- if (parent && handler) {
- parent.signal.removeEventListener("abort", handler);
- }
-}
-function createChildAbortController(parent, maxListeners) {
- const child = createAbortController(maxListeners);
- if (parent.signal.aborted) {
- child.abort(parent.signal.reason);
- return child;
- }
- const weakChild = new WeakRef(child);
- const weakParent = new WeakRef(parent);
- const handler = propagateAbort.bind(weakParent, weakChild);
- parent.signal.addEventListener("abort", handler, { once: true });
- child.signal.addEventListener("abort", removeAbortHandler.bind(weakParent, new WeakRef(handler)), { once: true });
- return child;
-}
-var DEFAULT_MAX_LISTENERS = 50;
-var init_abortController = () => {};
-
-// src/utils/combinedAbortSignal.ts
-function createCombinedAbortSignal(signal, opts) {
- const { signalB, timeoutMs } = opts ?? {};
- const combined = createAbortController();
- if (signal?.aborted || signalB?.aborted) {
- combined.abort();
- return { signal: combined.signal, cleanup: () => {} };
- }
- let timer;
- const abortCombined = () => {
- if (timer !== undefined)
- clearTimeout(timer);
- combined.abort();
- };
- if (timeoutMs !== undefined) {
- timer = setTimeout(abortCombined, timeoutMs);
- timer.unref?.();
- }
- signal?.addEventListener("abort", abortCombined);
- signalB?.addEventListener("abort", abortCombined);
- const cleanup = () => {
- if (timer !== undefined)
- clearTimeout(timer);
- signal?.removeEventListener("abort", abortCombined);
- signalB?.removeEventListener("abort", abortCombined);
- };
- return { signal: combined.signal, cleanup };
-}
-var init_combinedAbortSignal = __esm(() => {
- init_abortController();
-});
-
-// src/utils/hooks/hookEvents.ts
-function registerHookEventHandler(handler) {
- eventHandler = handler;
- if (handler && pendingEvents.length > 0) {
- for (const event of pendingEvents.splice(0)) {
- handler(event);
- }
- }
-}
-function emit(event) {
- if (eventHandler) {
- eventHandler(event);
- } else {
- pendingEvents.push(event);
- if (pendingEvents.length > MAX_PENDING_EVENTS) {
- pendingEvents.shift();
- }
- }
-}
-function shouldEmit(hookEvent) {
- if (ALWAYS_EMITTED_HOOK_EVENTS.includes(hookEvent)) {
- return true;
- }
- return allHookEventsEnabled && HOOK_EVENTS.includes(hookEvent);
-}
-function emitHookStarted(hookId, hookName, hookEvent) {
- if (!shouldEmit(hookEvent))
- return;
- emit({
- type: "started",
- hookId,
- hookName,
- hookEvent
- });
-}
-function emitHookProgress(data) {
- if (!shouldEmit(data.hookEvent))
- return;
- emit({
- type: "progress",
- ...data
- });
-}
-function startHookProgressInterval(params) {
- if (!shouldEmit(params.hookEvent))
- return () => {};
- let lastEmittedOutput = "";
- const interval = setInterval(() => {
- params.getOutput().then(({ stdout, stderr, output }) => {
- if (output === lastEmittedOutput)
- return;
- lastEmittedOutput = output;
- emitHookProgress({
- hookId: params.hookId,
- hookName: params.hookName,
- hookEvent: params.hookEvent,
- stdout,
- stderr,
- output
- });
- });
- }, params.intervalMs ?? 1000);
- interval.unref();
- return () => clearInterval(interval);
-}
-function emitHookResponse(data) {
- const outputToLog = data.stdout || data.stderr || data.output;
- if (outputToLog) {
- logForDebugging(`Hook ${data.hookName} (${data.hookEvent}) ${data.outcome}:
-${outputToLog}`);
- }
- if (!shouldEmit(data.hookEvent))
- return;
- emit({
- type: "response",
- ...data
- });
-}
-function setAllHookEventsEnabled(enabled2) {
- allHookEventsEnabled = enabled2;
-}
-var ALWAYS_EMITTED_HOOK_EVENTS, MAX_PENDING_EVENTS = 100, pendingEvents, eventHandler = null, allHookEventsEnabled = false;
-var init_hookEvents = __esm(() => {
- init_coreTypes();
- init_debug();
- ALWAYS_EMITTED_HOOK_EVENTS = ["SessionStart", "Setup"];
- pendingEvents = [];
-});
-
-// src/utils/hooks/AsyncHookRegistry.ts
-function registerPendingAsyncHook({
- processId,
- hookId,
- asyncResponse,
- hookName,
- hookEvent,
- command: command12,
- shellCommand,
- toolName,
- pluginId
-}) {
- const timeout = asyncResponse.asyncTimeout || 15000;
- logForDebugging(`Hooks: Registering async hook ${processId} (${hookName}) with timeout ${timeout}ms`);
- const stopProgressInterval = startHookProgressInterval({
- hookId,
- hookName,
- hookEvent,
- getOutput: async () => {
- const taskOutput = pendingHooks.get(processId)?.shellCommand?.taskOutput;
- if (!taskOutput) {
- return { stdout: "", stderr: "", output: "" };
- }
- const stdout = await taskOutput.getStdout();
- const stderr = taskOutput.getStderr();
- return { stdout, stderr, output: stdout + stderr };
- }
- });
- pendingHooks.set(processId, {
- processId,
- hookId,
- hookName,
- hookEvent,
- toolName,
- pluginId,
- command: command12,
- startTime: Date.now(),
- timeout,
- responseAttachmentSent: false,
- shellCommand,
- stopProgressInterval
- });
-}
-async function finalizeHook(hook, exitCode, outcome) {
- hook.stopProgressInterval();
- const taskOutput = hook.shellCommand?.taskOutput;
- const stdout = taskOutput ? await taskOutput.getStdout() : "";
- const stderr = taskOutput?.getStderr() ?? "";
- hook.shellCommand?.cleanup();
- emitHookResponse({
- hookId: hook.hookId,
- hookName: hook.hookName,
- hookEvent: hook.hookEvent,
- output: stdout + stderr,
- stdout,
- stderr,
- exitCode,
- outcome
- });
-}
-async function checkForAsyncHookResponses() {
- const responses = [];
- const pendingCount = pendingHooks.size;
- logForDebugging(`Hooks: Found ${pendingCount} total hooks in registry`);
- const hooks = Array.from(pendingHooks.values());
- const settled = await Promise.allSettled(hooks.map(async (hook) => {
- const stdout = await hook.shellCommand?.taskOutput.getStdout() ?? "";
- const stderr = hook.shellCommand?.taskOutput.getStderr() ?? "";
- logForDebugging(`Hooks: Checking hook ${hook.processId} (${hook.hookName}) - attachmentSent: ${hook.responseAttachmentSent}, stdout length: ${stdout.length}`);
- if (!hook.shellCommand) {
- logForDebugging(`Hooks: Hook ${hook.processId} has no shell command, removing from registry`);
- hook.stopProgressInterval();
- return { type: "remove", processId: hook.processId };
- }
- logForDebugging(`Hooks: Hook shell status ${hook.shellCommand.status}`);
- if (hook.shellCommand.status === "killed") {
- logForDebugging(`Hooks: Hook ${hook.processId} is ${hook.shellCommand.status}, removing from registry`);
- hook.stopProgressInterval();
- hook.shellCommand.cleanup();
- return { type: "remove", processId: hook.processId };
- }
- if (hook.shellCommand.status !== "completed") {
- return { type: "skip" };
- }
- if (hook.responseAttachmentSent || !stdout.trim()) {
- logForDebugging(`Hooks: Skipping hook ${hook.processId} - already delivered/sent or no stdout`);
- hook.stopProgressInterval();
- return { type: "remove", processId: hook.processId };
- }
- const lines2 = stdout.split(`
-`);
- logForDebugging(`Hooks: Processing ${lines2.length} lines of stdout for ${hook.processId}`);
- const execResult = await hook.shellCommand.result;
- const exitCode = execResult.code;
- let response7 = {};
- for (const line of lines2) {
- if (line.trim().startsWith("{")) {
- logForDebugging(`Hooks: Found JSON line: ${line.trim().substring(0, 100)}...`);
- try {
- const parsed = jsonParse(line.trim());
- if (!("async" in parsed)) {
- logForDebugging(`Hooks: Found sync response from ${hook.processId}: ${jsonStringify(parsed)}`);
- response7 = parsed;
- break;
- }
- } catch {
- logForDebugging(`Hooks: Failed to parse JSON from ${hook.processId}: ${line.trim()}`);
- }
- }
- }
- hook.responseAttachmentSent = true;
- await finalizeHook(hook, exitCode, exitCode === 0 ? "success" : "error");
- return {
- type: "response",
- processId: hook.processId,
- isSessionStart: hook.hookEvent === "SessionStart",
- payload: {
- processId: hook.processId,
- response: response7,
- hookName: hook.hookName,
- hookEvent: hook.hookEvent,
- toolName: hook.toolName,
- pluginId: hook.pluginId,
- stdout,
- stderr,
- exitCode
- }
- };
- }));
- let sessionStartCompleted = false;
- for (const s4 of settled) {
- if (s4.status !== "fulfilled") {
- logForDebugging(`Hooks: checkForAsyncHookResponses callback rejected: ${s4.reason}`, { level: "error" });
- continue;
- }
- const r4 = s4.value;
- if (r4.type === "remove") {
- pendingHooks.delete(r4.processId);
- } else if (r4.type === "response") {
- responses.push(r4.payload);
- pendingHooks.delete(r4.processId);
- if (r4.isSessionStart)
- sessionStartCompleted = true;
- }
- }
- if (sessionStartCompleted) {
- logForDebugging(`Invalidating session env cache after SessionStart hook completed`);
- invalidateSessionEnvCache();
- }
- logForDebugging(`Hooks: checkForNewResponses returning ${responses.length} responses`);
- return responses;
-}
-function removeDeliveredAsyncHooks(processIds) {
- for (const processId of processIds) {
- const hook = pendingHooks.get(processId);
- if (hook && hook.responseAttachmentSent) {
- logForDebugging(`Hooks: Removing delivered hook ${processId}`);
- hook.stopProgressInterval();
- pendingHooks.delete(processId);
- }
- }
-}
-async function finalizePendingAsyncHooks() {
- const hooks = Array.from(pendingHooks.values());
- await Promise.all(hooks.map(async (hook) => {
- if (hook.shellCommand?.status === "completed") {
- const result = await hook.shellCommand.result;
- await finalizeHook(hook, result.code, result.code === 0 ? "success" : "error");
- } else {
- if (hook.shellCommand && hook.shellCommand.status !== "killed") {
- hook.shellCommand.kill();
- }
- await finalizeHook(hook, 1, "cancelled");
- }
- }));
- pendingHooks.clear();
-}
-var pendingHooks;
-var init_AsyncHookRegistry = __esm(() => {
- init_debug();
- init_sessionEnvironment();
- init_slowOperations();
- init_hookEvents();
- pendingHooks = new Map;
-});
-
-// node_modules/lodash-es/last.js
-function last(array2) {
- var length = array2 == null ? 0 : array2.length;
- return length ? array2[length - 1] : undefined;
-}
-var last_default;
-var init_last = __esm(() => {
- last_default = last;
-});
-
-// src/buddy/types.ts
-var RARITIES, c8, duck, goose, blob, cat, dragon, octopus, owl, penguin, turtle, snail, ghost, axolotl, capybara, cactus, robot, rabbit, mushroom, chonk, SPECIES, EYES, HATS, STAT_NAMES, RARITY_WEIGHTS;
-var init_types16 = __esm(() => {
- RARITIES = [
- "common",
- "uncommon",
- "rare",
- "epic",
- "legendary"
- ];
- c8 = String.fromCharCode;
- duck = c8(100, 117, 99, 107);
- goose = c8(103, 111, 111, 115, 101);
- blob = c8(98, 108, 111, 98);
- cat = c8(99, 97, 116);
- dragon = c8(100, 114, 97, 103, 111, 110);
- octopus = c8(111, 99, 116, 111, 112, 117, 115);
- owl = c8(111, 119, 108);
- penguin = c8(112, 101, 110, 103, 117, 105, 110);
- turtle = c8(116, 117, 114, 116, 108, 101);
- snail = c8(115, 110, 97, 105, 108);
- ghost = c8(103, 104, 111, 115, 116);
- axolotl = c8(97, 120, 111, 108, 111, 116, 108);
- capybara = c8(99, 97, 112, 121, 98, 97, 114, 97);
- cactus = c8(99, 97, 99, 116, 117, 115);
- robot = c8(114, 111, 98, 111, 116);
- rabbit = c8(114, 97, 98, 98, 105, 116);
- mushroom = c8(109, 117, 115, 104, 114, 111, 111, 109);
- chonk = c8(99, 104, 111, 110, 107);
- SPECIES = [
- duck,
- goose,
- blob,
- cat,
- dragon,
- octopus,
- owl,
- penguin,
- turtle,
- snail,
- ghost,
- axolotl,
- capybara,
- cactus,
- robot,
- rabbit,
- mushroom,
- chonk
- ];
- EYES = ["\xB7", "\u2726", "\xD7", "\u25C9", "@", "\xB0"];
- HATS = [
- "none",
- "crown",
- "tophat",
- "propeller",
- "halo",
- "wizard",
- "beanie",
- "tinyduck"
- ];
- STAT_NAMES = [
- "DEBUGGING",
- "PATIENCE",
- "CHAOS",
- "WISDOM",
- "SNARK"
- ];
- RARITY_WEIGHTS = {
- common: 60,
- uncommon: 25,
- rare: 10,
- epic: 4,
- legendary: 1
- };
-});
-
-// src/buddy/companion.ts
-function mulberry32(seed) {
- let a5 = seed >>> 0;
- return function() {
- a5 |= 0;
- a5 = a5 + 1831565813 | 0;
- let t4 = Math.imul(a5 ^ a5 >>> 15, 1 | a5);
- t4 = t4 + Math.imul(t4 ^ t4 >>> 7, 61 | t4) ^ t4;
- return ((t4 ^ t4 >>> 14) >>> 0) / 4294967296;
- };
-}
-function hashString(s4) {
- if (typeof Bun !== "undefined") {
- return Number(BigInt(Bun.hash(s4)) & 0xffffffffn);
- }
- let h5 = 2166136261;
- for (let i6 = 0;i6 < s4.length; i6++) {
- h5 ^= s4.charCodeAt(i6);
- h5 = Math.imul(h5, 16777619);
- }
- return h5 >>> 0;
-}
-function pick2(rng, arr) {
- return arr[Math.floor(rng() * arr.length)];
-}
-function rollRarity(rng) {
- const total = Object.values(RARITY_WEIGHTS).reduce((a5, b5) => a5 + b5, 0);
- let roll = rng() * total;
- for (const rarity of RARITIES) {
- roll -= RARITY_WEIGHTS[rarity];
- if (roll < 0)
- return rarity;
- }
- return "common";
-}
-function rollStats(rng, rarity) {
- const floor = RARITY_FLOOR[rarity];
- const peak = pick2(rng, STAT_NAMES);
- let dump = pick2(rng, STAT_NAMES);
- while (dump === peak)
- dump = pick2(rng, STAT_NAMES);
- const stats = {};
- for (const name3 of STAT_NAMES) {
- if (name3 === peak) {
- stats[name3] = Math.min(100, floor + 50 + Math.floor(rng() * 30));
- } else if (name3 === dump) {
- stats[name3] = Math.max(1, floor - 10 + Math.floor(rng() * 15));
- } else {
- stats[name3] = floor + Math.floor(rng() * 40);
- }
- }
- return stats;
-}
-function rollFrom(rng) {
- const rarity = rollRarity(rng);
- const bones = {
- rarity,
- species: pick2(rng, SPECIES),
- eye: pick2(rng, EYES),
- hat: rarity === "common" ? "none" : pick2(rng, HATS),
- shiny: rng() < 0.01,
- stats: rollStats(rng, rarity)
- };
- return { bones, inspirationSeed: Math.floor(rng() * 1e9) };
-}
-function roll(userId) {
- const key2 = userId + SALT;
- if (rollCache?.key === key2)
- return rollCache.value;
- const value = rollFrom(mulberry32(hashString(key2)));
- rollCache = { key: key2, value };
- return value;
-}
-function companionUserId() {
- const config9 = getGlobalConfig();
- return config9.oauthAccount?.accountUuid ?? config9.userID ?? "anon";
-}
-function getCompanion() {
- const stored = getGlobalConfig().companion;
- if (!stored)
- return;
- const { bones } = roll(companionUserId());
- return { ...stored, ...bones };
-}
-var RARITY_FLOOR, SALT = "friend-2026-401", rollCache;
-var init_companion = __esm(() => {
- init_config();
- init_types16();
- RARITY_FLOOR = {
- common: 5,
- uncommon: 15,
- rare: 25,
- epic: 35,
- legendary: 50
- };
-});
-
-// src/buddy/prompt.ts
-function companionIntroText(name3, species) {
- return `# Companion
-
-A small ${species} named ${name3} sits beside the user's input box and occasionally comments in a speech bubble. You're not ${name3} \u2014 it's a separate watcher.
-
-When the user addresses ${name3} directly (by name), its bubble will answer. Your job in that moment is to stay out of the way: respond in ONE line or less, or just answer any part of the message meant for you. Don't explain that you're not ${name3} \u2014 they know. Don't narrate what ${name3} might say \u2014 the bubble handles that.`;
-}
-var init_prompt4 = __esm(() => {
- init_config();
- init_companion();
-});
-
-// src/constants/messages.ts
-var NO_CONTENT_MESSAGE = "(no content)";
-
-// node_modules/yaml/dist/nodes/identity.js
-var require_identity = __commonJS((exports) => {
- var ALIAS = Symbol.for("yaml.alias");
- var DOC = Symbol.for("yaml.document");
- var MAP = Symbol.for("yaml.map");
- var PAIR = Symbol.for("yaml.pair");
- var SCALAR = Symbol.for("yaml.scalar");
- var SEQ = Symbol.for("yaml.seq");
- var NODE_TYPE = Symbol.for("yaml.node.type");
- var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
- var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
- var isMap2 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
- var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
- var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
- var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
- function isCollection(node) {
- if (node && typeof node === "object")
- switch (node[NODE_TYPE]) {
- case MAP:
- case SEQ:
- return true;
- }
- return false;
- }
- function isNode2(node) {
- if (node && typeof node === "object")
- switch (node[NODE_TYPE]) {
- case ALIAS:
- case MAP:
- case SCALAR:
- case SEQ:
- return true;
- }
- return false;
- }
- var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
- exports.ALIAS = ALIAS;
- exports.DOC = DOC;
- exports.MAP = MAP;
- exports.NODE_TYPE = NODE_TYPE;
- exports.PAIR = PAIR;
- exports.SCALAR = SCALAR;
- exports.SEQ = SEQ;
- exports.hasAnchor = hasAnchor;
- exports.isAlias = isAlias;
- exports.isCollection = isCollection;
- exports.isDocument = isDocument;
- exports.isMap = isMap2;
- exports.isNode = isNode2;
- exports.isPair = isPair;
- exports.isScalar = isScalar;
- exports.isSeq = isSeq;
-});
-
-// node_modules/yaml/dist/visit.js
-var require_visit = __commonJS((exports) => {
- var identity16 = require_identity();
- var BREAK = Symbol("break visit");
- var SKIP = Symbol("skip children");
- var REMOVE = Symbol("remove node");
- function visit2(node, visitor) {
- const visitor_ = initVisitor(visitor);
- if (identity16.isDocument(node)) {
- const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
- if (cd === REMOVE)
- node.contents = null;
- } else
- visit_(null, node, visitor_, Object.freeze([]));
- }
- visit2.BREAK = BREAK;
- visit2.SKIP = SKIP;
- visit2.REMOVE = REMOVE;
- function visit_(key2, node, visitor, path16) {
- const ctrl = callVisitor(key2, node, visitor, path16);
- if (identity16.isNode(ctrl) || identity16.isPair(ctrl)) {
- replaceNode(key2, path16, ctrl);
- return visit_(key2, ctrl, visitor, path16);
- }
- if (typeof ctrl !== "symbol") {
- if (identity16.isCollection(node)) {
- path16 = Object.freeze(path16.concat(node));
- for (let i6 = 0;i6 < node.items.length; ++i6) {
- const ci = visit_(i6, node.items[i6], visitor, path16);
- if (typeof ci === "number")
- i6 = ci - 1;
- else if (ci === BREAK)
- return BREAK;
- else if (ci === REMOVE) {
- node.items.splice(i6, 1);
- i6 -= 1;
- }
- }
- } else if (identity16.isPair(node)) {
- path16 = Object.freeze(path16.concat(node));
- const ck = visit_("key", node.key, visitor, path16);
- if (ck === BREAK)
- return BREAK;
- else if (ck === REMOVE)
- node.key = null;
- const cv = visit_("value", node.value, visitor, path16);
- if (cv === BREAK)
- return BREAK;
- else if (cv === REMOVE)
- node.value = null;
- }
- }
- return ctrl;
- }
- async function visitAsync(node, visitor) {
- const visitor_ = initVisitor(visitor);
- if (identity16.isDocument(node)) {
- const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
- if (cd === REMOVE)
- node.contents = null;
- } else
- await visitAsync_(null, node, visitor_, Object.freeze([]));
- }
- visitAsync.BREAK = BREAK;
- visitAsync.SKIP = SKIP;
- visitAsync.REMOVE = REMOVE;
- async function visitAsync_(key2, node, visitor, path16) {
- const ctrl = await callVisitor(key2, node, visitor, path16);
- if (identity16.isNode(ctrl) || identity16.isPair(ctrl)) {
- replaceNode(key2, path16, ctrl);
- return visitAsync_(key2, ctrl, visitor, path16);
- }
- if (typeof ctrl !== "symbol") {
- if (identity16.isCollection(node)) {
- path16 = Object.freeze(path16.concat(node));
- for (let i6 = 0;i6 < node.items.length; ++i6) {
- const ci = await visitAsync_(i6, node.items[i6], visitor, path16);
- if (typeof ci === "number")
- i6 = ci - 1;
- else if (ci === BREAK)
- return BREAK;
- else if (ci === REMOVE) {
- node.items.splice(i6, 1);
- i6 -= 1;
- }
- }
- } else if (identity16.isPair(node)) {
- path16 = Object.freeze(path16.concat(node));
- const ck = await visitAsync_("key", node.key, visitor, path16);
- if (ck === BREAK)
- return BREAK;
- else if (ck === REMOVE)
- node.key = null;
- const cv = await visitAsync_("value", node.value, visitor, path16);
- if (cv === BREAK)
- return BREAK;
- else if (cv === REMOVE)
- node.value = null;
- }
- }
- return ctrl;
- }
- function initVisitor(visitor) {
- if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
- return Object.assign({
- Alias: visitor.Node,
- Map: visitor.Node,
- Scalar: visitor.Node,
- Seq: visitor.Node
- }, visitor.Value && {
- Map: visitor.Value,
- Scalar: visitor.Value,
- Seq: visitor.Value
- }, visitor.Collection && {
- Map: visitor.Collection,
- Seq: visitor.Collection
- }, visitor);
- }
- return visitor;
- }
- function callVisitor(key2, node, visitor, path16) {
- if (typeof visitor === "function")
- return visitor(key2, node, path16);
- if (identity16.isMap(node))
- return visitor.Map?.(key2, node, path16);
- if (identity16.isSeq(node))
- return visitor.Seq?.(key2, node, path16);
- if (identity16.isPair(node))
- return visitor.Pair?.(key2, node, path16);
- if (identity16.isScalar(node))
- return visitor.Scalar?.(key2, node, path16);
- if (identity16.isAlias(node))
- return visitor.Alias?.(key2, node, path16);
- return;
- }
- function replaceNode(key2, path16, node) {
- const parent = path16[path16.length - 1];
- if (identity16.isCollection(parent)) {
- parent.items[key2] = node;
- } else if (identity16.isPair(parent)) {
- if (key2 === "key")
- parent.key = node;
- else
- parent.value = node;
- } else if (identity16.isDocument(parent)) {
- parent.contents = node;
- } else {
- const pt = identity16.isAlias(parent) ? "alias" : "scalar";
- throw new Error(`Cannot replace node with ${pt} parent`);
- }
- }
- exports.visit = visit2;
- exports.visitAsync = visitAsync;
-});
-
-// node_modules/yaml/dist/doc/directives.js
-var require_directives = __commonJS((exports) => {
- var identity16 = require_identity();
- var visit2 = require_visit();
- var escapeChars = {
- "!": "%21",
- ",": "%2C",
- "[": "%5B",
- "]": "%5D",
- "{": "%7B",
- "}": "%7D"
- };
- var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch2) => escapeChars[ch2]);
-
- class Directives {
- constructor(yaml, tags) {
- this.docStart = null;
- this.docEnd = false;
- this.yaml = Object.assign({}, Directives.defaultYaml, yaml);
- this.tags = Object.assign({}, Directives.defaultTags, tags);
- }
- clone() {
- const copy = new Directives(this.yaml, this.tags);
- copy.docStart = this.docStart;
- return copy;
- }
- atDocument() {
- const res = new Directives(this.yaml, this.tags);
- switch (this.yaml.version) {
- case "1.1":
- this.atNextDocument = true;
- break;
- case "1.2":
- this.atNextDocument = false;
- this.yaml = {
- explicit: Directives.defaultYaml.explicit,
- version: "1.2"
- };
- this.tags = Object.assign({}, Directives.defaultTags);
- break;
- }
- return res;
- }
- add(line, onError) {
- if (this.atNextDocument) {
- this.yaml = { explicit: Directives.defaultYaml.explicit, version: "1.1" };
- this.tags = Object.assign({}, Directives.defaultTags);
- this.atNextDocument = false;
- }
- const parts = line.trim().split(/[ \t]+/);
- const name3 = parts.shift();
- switch (name3) {
- case "%TAG": {
- if (parts.length !== 2) {
- onError(0, "%TAG directive should contain exactly two parts");
- if (parts.length < 2)
- return false;
- }
- const [handle, prefix] = parts;
- this.tags[handle] = prefix;
- return true;
- }
- case "%YAML": {
- this.yaml.explicit = true;
- if (parts.length !== 1) {
- onError(0, "%YAML directive should contain exactly one part");
- return false;
- }
- const [version6] = parts;
- if (version6 === "1.1" || version6 === "1.2") {
- this.yaml.version = version6;
- return true;
- } else {
- const isValid2 = /^\d+\.\d+$/.test(version6);
- onError(6, `Unsupported YAML version ${version6}`, isValid2);
- return false;
- }
- }
- default:
- onError(0, `Unknown directive ${name3}`, true);
- return false;
- }
- }
- tagName(source, onError) {
- if (source === "!")
- return "!";
- if (source[0] !== "!") {
- onError(`Not a valid tag: ${source}`);
- return null;
- }
- if (source[1] === "<") {
- const verbatim = source.slice(2, -1);
- if (verbatim === "!" || verbatim === "!!") {
- onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
- return null;
- }
- if (source[source.length - 1] !== ">")
- onError("Verbatim tags must end with a >");
- return verbatim;
- }
- const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
- if (!suffix)
- onError(`The ${source} tag has no suffix`);
- const prefix = this.tags[handle];
- if (prefix) {
- try {
- return prefix + decodeURIComponent(suffix);
- } catch (error46) {
- onError(String(error46));
- return null;
- }
- }
- if (handle === "!")
- return source;
- onError(`Could not resolve tag: ${source}`);
- return null;
- }
- tagString(tag2) {
- for (const [handle, prefix] of Object.entries(this.tags)) {
- if (tag2.startsWith(prefix))
- return handle + escapeTagName(tag2.substring(prefix.length));
- }
- return tag2[0] === "!" ? tag2 : `!<${tag2}>`;
- }
- toString(doc2) {
- const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
- const tagEntries = Object.entries(this.tags);
- let tagNames;
- if (doc2 && tagEntries.length > 0 && identity16.isNode(doc2.contents)) {
- const tags = {};
- visit2.visit(doc2.contents, (_key, node) => {
- if (identity16.isNode(node) && node.tag)
- tags[node.tag] = true;
- });
- tagNames = Object.keys(tags);
- } else
- tagNames = [];
- for (const [handle, prefix] of tagEntries) {
- if (handle === "!!" && prefix === "tag:yaml.org,2002:")
- continue;
- if (!doc2 || tagNames.some((tn) => tn.startsWith(prefix)))
- lines2.push(`%TAG ${handle} ${prefix}`);
- }
- return lines2.join(`
-`);
- }
- }
- Directives.defaultYaml = { explicit: false, version: "1.2" };
- Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };
- exports.Directives = Directives;
-});
-
-// node_modules/yaml/dist/doc/anchors.js
-var require_anchors = __commonJS((exports) => {
- var identity16 = require_identity();
- var visit2 = require_visit();
- function anchorIsValid(anchor) {
- if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
- const sa = JSON.stringify(anchor);
- const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
- throw new Error(msg);
- }
- return true;
- }
- function anchorNames(root2) {
- const anchors = new Set;
- visit2.visit(root2, {
- Value(_key, node) {
- if (node.anchor)
- anchors.add(node.anchor);
- }
- });
- return anchors;
- }
- function findNewAnchor(prefix, exclude) {
- for (let i6 = 1;; ++i6) {
- const name3 = `${prefix}${i6}`;
- if (!exclude.has(name3))
- return name3;
- }
- }
- function createNodeAnchors(doc2, prefix) {
- const aliasObjects = [];
- const sourceObjects = new Map;
- let prevAnchors = null;
- return {
- onAnchor: (source) => {
- aliasObjects.push(source);
- prevAnchors ?? (prevAnchors = anchorNames(doc2));
- const anchor = findNewAnchor(prefix, prevAnchors);
- prevAnchors.add(anchor);
- return anchor;
- },
- setAnchors: () => {
- for (const source of aliasObjects) {
- const ref = sourceObjects.get(source);
- if (typeof ref === "object" && ref.anchor && (identity16.isScalar(ref.node) || identity16.isCollection(ref.node))) {
- ref.node.anchor = ref.anchor;
- } else {
- const error46 = new Error("Failed to resolve repeated object (this should not happen)");
- error46.source = source;
- throw error46;
- }
- }
- },
- sourceObjects
- };
- }
- exports.anchorIsValid = anchorIsValid;
- exports.anchorNames = anchorNames;
- exports.createNodeAnchors = createNodeAnchors;
- exports.findNewAnchor = findNewAnchor;
-});
-
-// node_modules/yaml/dist/doc/applyReviver.js
-var require_applyReviver = __commonJS((exports) => {
- function applyReviver(reviver, obj, key2, val) {
- if (val && typeof val === "object") {
- if (Array.isArray(val)) {
- for (let i6 = 0, len = val.length;i6 < len; ++i6) {
- const v0 = val[i6];
- const v12 = applyReviver(reviver, val, String(i6), v0);
- if (v12 === undefined)
- delete val[i6];
- else if (v12 !== v0)
- val[i6] = v12;
- }
- } else if (val instanceof Map) {
- for (const k4 of Array.from(val.keys())) {
- const v0 = val.get(k4);
- const v12 = applyReviver(reviver, val, k4, v0);
- if (v12 === undefined)
- val.delete(k4);
- else if (v12 !== v0)
- val.set(k4, v12);
- }
- } else if (val instanceof Set) {
- for (const v0 of Array.from(val)) {
- const v12 = applyReviver(reviver, val, v0, v0);
- if (v12 === undefined)
- val.delete(v0);
- else if (v12 !== v0) {
- val.delete(v0);
- val.add(v12);
- }
- }
- } else {
- for (const [k4, v0] of Object.entries(val)) {
- const v12 = applyReviver(reviver, val, k4, v0);
- if (v12 === undefined)
- delete val[k4];
- else if (v12 !== v0)
- val[k4] = v12;
- }
- }
- }
- return reviver.call(obj, key2, val);
- }
- exports.applyReviver = applyReviver;
-});
-
-// node_modules/yaml/dist/nodes/toJS.js
-var require_toJS = __commonJS((exports) => {
- var identity16 = require_identity();
- function toJS(value, arg, ctx) {
- if (Array.isArray(value))
- return value.map((v6, i6) => toJS(v6, String(i6), ctx));
- if (value && typeof value.toJSON === "function") {
- if (!ctx || !identity16.hasAnchor(value))
- return value.toJSON(arg, ctx);
- const data = { aliasCount: 0, count: 1, res: undefined };
- ctx.anchors.set(value, data);
- ctx.onCreate = (res2) => {
- data.res = res2;
- delete ctx.onCreate;
- };
- const res = value.toJSON(arg, ctx);
- if (ctx.onCreate)
- ctx.onCreate(res);
- return res;
- }
- if (typeof value === "bigint" && !ctx?.keep)
- return Number(value);
- return value;
- }
- exports.toJS = toJS;
-});
-
-// node_modules/yaml/dist/nodes/Node.js
-var require_Node = __commonJS((exports) => {
- var applyReviver = require_applyReviver();
- var identity16 = require_identity();
- var toJS = require_toJS();
-
- class NodeBase {
- constructor(type) {
- Object.defineProperty(this, identity16.NODE_TYPE, { value: type });
- }
- clone() {
- const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
- if (this.range)
- copy.range = this.range.slice();
- return copy;
- }
- toJS(doc2, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
- if (!identity16.isDocument(doc2))
- throw new TypeError("A document argument is required");
- const ctx = {
- anchors: new Map,
- doc: doc2,
- keep: true,
- mapAsMap: mapAsMap === true,
- mapKeyWarned: false,
- maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
- };
- const res = toJS.toJS(this, "", ctx);
- if (typeof onAnchor === "function")
- for (const { count: count3, res: res2 } of ctx.anchors.values())
- onAnchor(res2, count3);
- return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
- }
- }
- exports.NodeBase = NodeBase;
-});
-
-// node_modules/yaml/dist/nodes/Alias.js
-var require_Alias = __commonJS((exports) => {
- var anchors = require_anchors();
- var visit2 = require_visit();
- var identity16 = require_identity();
- var Node2 = require_Node();
- var toJS = require_toJS();
-
- class Alias extends Node2.NodeBase {
- constructor(source) {
- super(identity16.ALIAS);
- this.source = source;
- Object.defineProperty(this, "tag", {
- set() {
- throw new Error("Alias nodes cannot have tags");
- }
- });
- }
- resolve(doc2, ctx) {
- let nodes;
- if (ctx?.aliasResolveCache) {
- nodes = ctx.aliasResolveCache;
- } else {
- nodes = [];
- visit2.visit(doc2, {
- Node: (_key, node) => {
- if (identity16.isAlias(node) || identity16.hasAnchor(node))
- nodes.push(node);
- }
- });
- if (ctx)
- ctx.aliasResolveCache = nodes;
- }
- let found = undefined;
- for (const node of nodes) {
- if (node === this)
- break;
- if (node.anchor === this.source)
- found = node;
- }
- return found;
- }
- toJSON(_arg, ctx) {
- if (!ctx)
- return { source: this.source };
- const { anchors: anchors2, doc: doc2, maxAliasCount } = ctx;
- const source = this.resolve(doc2, ctx);
- if (!source) {
- const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
- throw new ReferenceError(msg);
- }
- let data = anchors2.get(source);
- if (!data) {
- toJS.toJS(source, null, ctx);
- data = anchors2.get(source);
- }
- if (data?.res === undefined) {
- const msg = "This should not happen: Alias anchor was not resolved?";
- throw new ReferenceError(msg);
- }
- if (maxAliasCount >= 0) {
- data.count += 1;
- if (data.aliasCount === 0)
- data.aliasCount = getAliasCount(doc2, source, anchors2);
- if (data.count * data.aliasCount > maxAliasCount) {
- const msg = "Excessive alias count indicates a resource exhaustion attack";
- throw new ReferenceError(msg);
- }
- }
- return data.res;
- }
- toString(ctx, _onComment, _onChompKeep) {
- const src = `*${this.source}`;
- if (ctx) {
- anchors.anchorIsValid(this.source);
- if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
- const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
- throw new Error(msg);
- }
- if (ctx.implicitKey)
- return `${src} `;
- }
- return src;
- }
- }
- function getAliasCount(doc2, node, anchors2) {
- if (identity16.isAlias(node)) {
- const source = node.resolve(doc2);
- const anchor = anchors2 && source && anchors2.get(source);
- return anchor ? anchor.count * anchor.aliasCount : 0;
- } else if (identity16.isCollection(node)) {
- let count3 = 0;
- for (const item of node.items) {
- const c9 = getAliasCount(doc2, item, anchors2);
- if (c9 > count3)
- count3 = c9;
- }
- return count3;
- } else if (identity16.isPair(node)) {
- const kc = getAliasCount(doc2, node.key, anchors2);
- const vc = getAliasCount(doc2, node.value, anchors2);
- return Math.max(kc, vc);
- }
- return 1;
- }
- exports.Alias = Alias;
-});
-
-// node_modules/yaml/dist/nodes/Scalar.js
-var require_Scalar = __commonJS((exports) => {
- var identity16 = require_identity();
- var Node2 = require_Node();
- var toJS = require_toJS();
- var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object";
-
- class Scalar extends Node2.NodeBase {
- constructor(value) {
- super(identity16.SCALAR);
- this.value = value;
- }
- toJSON(arg, ctx) {
- return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);
- }
- toString() {
- return String(this.value);
- }
- }
- Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
- Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
- Scalar.PLAIN = "PLAIN";
- Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
- Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";
- exports.Scalar = Scalar;
- exports.isScalarValue = isScalarValue;
-});
-
-// node_modules/yaml/dist/doc/createNode.js
-var require_createNode = __commonJS((exports) => {
- var Alias = require_Alias();
- var identity16 = require_identity();
- var Scalar = require_Scalar();
- var defaultTagPrefix = "tag:yaml.org,2002:";
- function findTagObject(value, tagName, tags) {
- if (tagName) {
- const match = tags.filter((t4) => t4.tag === tagName);
- const tagObj = match.find((t4) => !t4.format) ?? match[0];
- if (!tagObj)
- throw new Error(`Tag ${tagName} not found`);
- return tagObj;
- }
- return tags.find((t4) => t4.identify?.(value) && !t4.format);
- }
- function createNode2(value, tagName, ctx) {
- if (identity16.isDocument(value))
- value = value.contents;
- if (identity16.isNode(value))
- return value;
- if (identity16.isPair(value)) {
- const map7 = ctx.schema[identity16.MAP].createNode?.(ctx.schema, null, ctx);
- map7.items.push(value);
- return map7;
- }
- if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) {
- value = value.valueOf();
- }
- const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema5, sourceObjects } = ctx;
- let ref = undefined;
- if (aliasDuplicateObjects && value && typeof value === "object") {
- ref = sourceObjects.get(value);
- if (ref) {
- ref.anchor ?? (ref.anchor = onAnchor(value));
- return new Alias.Alias(ref.anchor);
- } else {
- ref = { anchor: null, node: null };
- sourceObjects.set(value, ref);
- }
- }
- if (tagName?.startsWith("!!"))
- tagName = defaultTagPrefix + tagName.slice(2);
- let tagObj = findTagObject(value, tagName, schema5.tags);
- if (!tagObj) {
- if (value && typeof value.toJSON === "function") {
- value = value.toJSON();
- }
- if (!value || typeof value !== "object") {
- const node2 = new Scalar.Scalar(value);
- if (ref)
- ref.node = node2;
- return node2;
- }
- tagObj = value instanceof Map ? schema5[identity16.MAP] : (Symbol.iterator in Object(value)) ? schema5[identity16.SEQ] : schema5[identity16.MAP];
- }
- if (onTagObj) {
- onTagObj(tagObj);
- delete ctx.onTagObj;
- }
- const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value);
- if (tagName)
- node.tag = tagName;
- else if (!tagObj.default)
- node.tag = tagObj.tag;
- if (ref)
- ref.node = node;
- return node;
- }
- exports.createNode = createNode2;
-});
-
-// node_modules/yaml/dist/nodes/Collection.js
-var require_Collection = __commonJS((exports) => {
- var createNode2 = require_createNode();
- var identity16 = require_identity();
- var Node2 = require_Node();
- function collectionFromPath(schema5, path16, value) {
- let v6 = value;
- for (let i6 = path16.length - 1;i6 >= 0; --i6) {
- const k4 = path16[i6];
- if (typeof k4 === "number" && Number.isInteger(k4) && k4 >= 0) {
- const a5 = [];
- a5[k4] = v6;
- v6 = a5;
- } else {
- v6 = new Map([[k4, v6]]);
- }
- }
- return createNode2.createNode(v6, undefined, {
- aliasDuplicateObjects: false,
- keepUndefined: false,
- onAnchor: () => {
- throw new Error("This should not happen, please report a bug.");
- },
- schema: schema5,
- sourceObjects: new Map
- });
- }
- var isEmptyPath = (path16) => path16 == null || typeof path16 === "object" && !!path16[Symbol.iterator]().next().done;
-
- class Collection extends Node2.NodeBase {
- constructor(type, schema5) {
- super(type);
- Object.defineProperty(this, "schema", {
- value: schema5,
- configurable: true,
- enumerable: false,
- writable: true
- });
- }
- clone(schema5) {
- const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
- if (schema5)
- copy.schema = schema5;
- copy.items = copy.items.map((it) => identity16.isNode(it) || identity16.isPair(it) ? it.clone(schema5) : it);
- if (this.range)
- copy.range = this.range.slice();
- return copy;
- }
- addIn(path16, value) {
- if (isEmptyPath(path16))
- this.add(value);
- else {
- const [key2, ...rest] = path16;
- const node = this.get(key2, true);
- if (identity16.isCollection(node))
- node.addIn(rest, value);
- else if (node === undefined && this.schema)
- this.set(key2, collectionFromPath(this.schema, rest, value));
- else
- throw new Error(`Expected YAML collection at ${key2}. Remaining path: ${rest}`);
- }
- }
- deleteIn(path16) {
- const [key2, ...rest] = path16;
- if (rest.length === 0)
- return this.delete(key2);
- const node = this.get(key2, true);
- if (identity16.isCollection(node))
- return node.deleteIn(rest);
- else
- throw new Error(`Expected YAML collection at ${key2}. Remaining path: ${rest}`);
- }
- getIn(path16, keepScalar) {
- const [key2, ...rest] = path16;
- const node = this.get(key2, true);
- if (rest.length === 0)
- return !keepScalar && identity16.isScalar(node) ? node.value : node;
- else
- return identity16.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
- }
- hasAllNullValues(allowScalar) {
- return this.items.every((node) => {
- if (!identity16.isPair(node))
- return false;
- const n5 = node.value;
- return n5 == null || allowScalar && identity16.isScalar(n5) && n5.value == null && !n5.commentBefore && !n5.comment && !n5.tag;
- });
- }
- hasIn(path16) {
- const [key2, ...rest] = path16;
- if (rest.length === 0)
- return this.has(key2);
- const node = this.get(key2, true);
- return identity16.isCollection(node) ? node.hasIn(rest) : false;
- }
- setIn(path16, value) {
- const [key2, ...rest] = path16;
- if (rest.length === 0) {
- this.set(key2, value);
- } else {
- const node = this.get(key2, true);
- if (identity16.isCollection(node))
- node.setIn(rest, value);
- else if (node === undefined && this.schema)
- this.set(key2, collectionFromPath(this.schema, rest, value));
- else
- throw new Error(`Expected YAML collection at ${key2}. Remaining path: ${rest}`);
- }
- }
- }
- exports.Collection = Collection;
- exports.collectionFromPath = collectionFromPath;
- exports.isEmptyPath = isEmptyPath;
-});
-
-// node_modules/yaml/dist/stringify/stringifyComment.js
-var require_stringifyComment = __commonJS((exports) => {
- var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
- function indentComment(comment, indent) {
- if (/^\n+$/.test(comment))
- return comment.substring(1);
- return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
- }
- var lineComment = (str, indent, comment) => str.endsWith(`
-`) ? indentComment(comment, indent) : comment.includes(`
-`) ? `
-` + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment;
- exports.indentComment = indentComment;
- exports.lineComment = lineComment;
- exports.stringifyComment = stringifyComment;
-});
-
-// node_modules/yaml/dist/stringify/foldFlowLines.js
-var require_foldFlowLines = __commonJS((exports) => {
- var FOLD_FLOW = "flow";
- var FOLD_BLOCK = "block";
- var FOLD_QUOTED = "quoted";
- function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth: lineWidth2 = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
- if (!lineWidth2 || lineWidth2 < 0)
- return text;
- if (lineWidth2 < minContentWidth)
- minContentWidth = 0;
- const endStep = Math.max(1 + minContentWidth, 1 + lineWidth2 - indent.length);
- if (text.length <= endStep)
- return text;
- const folds = [];
- const escapedFolds = {};
- let end = lineWidth2 - indent.length;
- if (typeof indentAtStart === "number") {
- if (indentAtStart > lineWidth2 - Math.max(2, minContentWidth))
- folds.push(0);
- else
- end = lineWidth2 - indentAtStart;
- }
- let split2 = undefined;
- let prev = undefined;
- let overflow = false;
- let i6 = -1;
- let escStart = -1;
- let escEnd = -1;
- if (mode === FOLD_BLOCK) {
- i6 = consumeMoreIndentedLines(text, i6, indent.length);
- if (i6 !== -1)
- end = i6 + endStep;
- }
- for (let ch2;ch2 = text[i6 += 1]; ) {
- if (mode === FOLD_QUOTED && ch2 === "\\") {
- escStart = i6;
- switch (text[i6 + 1]) {
- case "x":
- i6 += 3;
- break;
- case "u":
- i6 += 5;
- break;
- case "U":
- i6 += 9;
- break;
- default:
- i6 += 1;
- }
- escEnd = i6;
- }
- if (ch2 === `
-`) {
- if (mode === FOLD_BLOCK)
- i6 = consumeMoreIndentedLines(text, i6, indent.length);
- end = i6 + indent.length + endStep;
- split2 = undefined;
- } else {
- if (ch2 === " " && prev && prev !== " " && prev !== `
-` && prev !== "\t") {
- const next = text[i6 + 1];
- if (next && next !== " " && next !== `
-` && next !== "\t")
- split2 = i6;
- }
- if (i6 >= end) {
- if (split2) {
- folds.push(split2);
- end = split2 + endStep;
- split2 = undefined;
- } else if (mode === FOLD_QUOTED) {
- while (prev === " " || prev === "\t") {
- prev = ch2;
- ch2 = text[i6 += 1];
- overflow = true;
- }
- const j4 = i6 > escEnd + 1 ? i6 - 2 : escStart - 1;
- if (escapedFolds[j4])
- return text;
- folds.push(j4);
- escapedFolds[j4] = true;
- end = j4 + endStep;
- split2 = undefined;
- } else {
- overflow = true;
- }
- }
- }
- prev = ch2;
- }
- if (overflow && onOverflow)
- onOverflow();
- if (folds.length === 0)
- return text;
- if (onFold)
- onFold();
- let res = text.slice(0, folds[0]);
- for (let i7 = 0;i7 < folds.length; ++i7) {
- const fold = folds[i7];
- const end2 = folds[i7 + 1] || text.length;
- if (fold === 0)
- res = `
-${indent}${text.slice(0, end2)}`;
- else {
- if (mode === FOLD_QUOTED && escapedFolds[fold])
- res += `${text[fold]}\\`;
- res += `
-${indent}${text.slice(fold + 1, end2)}`;
- }
- }
- return res;
- }
- function consumeMoreIndentedLines(text, i6, indent) {
- let end = i6;
- let start = i6 + 1;
- let ch2 = text[start];
- while (ch2 === " " || ch2 === "\t") {
- if (i6 < start + indent) {
- ch2 = text[++i6];
- } else {
- do {
- ch2 = text[++i6];
- } while (ch2 && ch2 !== `
-`);
- end = i6;
- start = i6 + 1;
- ch2 = text[start];
- }
- }
- return end;
- }
- exports.FOLD_BLOCK = FOLD_BLOCK;
- exports.FOLD_FLOW = FOLD_FLOW;
- exports.FOLD_QUOTED = FOLD_QUOTED;
- exports.foldFlowLines = foldFlowLines;
-});
-
-// node_modules/yaml/dist/stringify/stringifyString.js
-var require_stringifyString = __commonJS((exports) => {
- var Scalar = require_Scalar();
- var foldFlowLines = require_foldFlowLines();
- var getFoldOptions = (ctx, isBlock) => ({
- indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
- lineWidth: ctx.options.lineWidth,
- minContentWidth: ctx.options.minContentWidth
- });
- var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
- function lineLengthOverLimit(str, lineWidth2, indentLength) {
- if (!lineWidth2 || lineWidth2 < 0)
- return false;
- const limit = lineWidth2 - indentLength;
- const strLen = str.length;
- if (strLen <= limit)
- return false;
- for (let i6 = 0, start = 0;i6 < strLen; ++i6) {
- if (str[i6] === `
-`) {
- if (i6 - start > limit)
- return true;
- start = i6 + 1;
- if (strLen - start <= limit)
- return false;
- }
- }
- return true;
- }
- function doubleQuotedString(value, ctx) {
- const json2 = JSON.stringify(value);
- if (ctx.options.doubleQuotedAsJSON)
- return json2;
- const { implicitKey } = ctx;
- const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
- const indent = ctx.indent || (containsDocumentMarker(value) ? " " : "");
- let str = "";
- let start = 0;
- for (let i6 = 0, ch2 = json2[i6];ch2; ch2 = json2[++i6]) {
- if (ch2 === " " && json2[i6 + 1] === "\\" && json2[i6 + 2] === "n") {
- str += json2.slice(start, i6) + "\\ ";
- i6 += 1;
- start = i6;
- ch2 = "\\";
- }
- if (ch2 === "\\")
- switch (json2[i6 + 1]) {
- case "u":
- {
- str += json2.slice(start, i6);
- const code = json2.substr(i6 + 2, 4);
- switch (code) {
- case "0000":
- str += "\\0";
- break;
- case "0007":
- str += "\\a";
- break;
- case "000b":
- str += "\\v";
- break;
- case "001b":
- str += "\\e";
- break;
- case "0085":
- str += "\\N";
- break;
- case "00a0":
- str += "\\_";
- break;
- case "2028":
- str += "\\L";
- break;
- case "2029":
- str += "\\P";
- break;
- default:
- if (code.substr(0, 2) === "00")
- str += "\\x" + code.substr(2);
- else
- str += json2.substr(i6, 6);
- }
- i6 += 5;
- start = i6 + 1;
- }
- break;
- case "n":
- if (implicitKey || json2[i6 + 2] === '"' || json2.length < minMultiLineLength) {
- i6 += 1;
- } else {
- str += json2.slice(start, i6) + `
-
-`;
- while (json2[i6 + 2] === "\\" && json2[i6 + 3] === "n" && json2[i6 + 4] !== '"') {
- str += `
-`;
- i6 += 2;
- }
- str += indent;
- if (json2[i6 + 2] === " ")
- str += "\\";
- i6 += 1;
- start = i6 + 1;
- }
- break;
- default:
- i6 += 1;
- }
- }
- str = start ? str + json2.slice(start) : json2;
- return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
- }
- function singleQuotedString(value, ctx) {
- if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes(`
-`) || /[ \t]\n|\n[ \t]/.test(value))
- return doubleQuotedString(value, ctx);
- const indent = ctx.indent || (containsDocumentMarker(value) ? " " : "");
- const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&
-${indent}`) + "'";
- return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
- }
- function quotedString(value, ctx) {
- const { singleQuote } = ctx.options;
- let qs;
- if (singleQuote === false)
- qs = doubleQuotedString;
- else {
- const hasDouble = value.includes('"');
- const hasSingle = value.includes("'");
- if (hasDouble && !hasSingle)
- qs = singleQuotedString;
- else if (hasSingle && !hasDouble)
- qs = doubleQuotedString;
- else
- qs = singleQuote ? singleQuotedString : doubleQuotedString;
- }
- return qs(value, ctx);
- }
- var blockEndNewlines;
- try {
- blockEndNewlines = new RegExp(`(^|(?
-`;
- let chomp;
- let endStart;
- for (endStart = value.length;endStart > 0; --endStart) {
- const ch2 = value[endStart - 1];
- if (ch2 !== `
-` && ch2 !== "\t" && ch2 !== " ")
- break;
- }
- let end = value.substring(endStart);
- const endNlPos = end.indexOf(`
-`);
- if (endNlPos === -1) {
- chomp = "-";
- } else if (value === end || endNlPos !== end.length - 1) {
- chomp = "+";
- if (onChompKeep)
- onChompKeep();
- } else {
- chomp = "";
- }
- if (end) {
- value = value.slice(0, -end.length);
- if (end[end.length - 1] === `
-`)
- end = end.slice(0, -1);
- end = end.replace(blockEndNewlines, `$&${indent}`);
- }
- let startWithSpace = false;
- let startEnd;
- let startNlPos = -1;
- for (startEnd = 0;startEnd < value.length; ++startEnd) {
- const ch2 = value[startEnd];
- if (ch2 === " ")
- startWithSpace = true;
- else if (ch2 === `
-`)
- startNlPos = startEnd;
- else
- break;
- }
- let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
- if (start) {
- value = value.substring(start.length);
- start = start.replace(/\n+/g, `$&${indent}`);
- }
- const indentSize = indent ? "2" : "1";
- let header = (startWithSpace ? indentSize : "") + chomp;
- if (comment) {
- header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
- if (onComment)
- onComment();
- }
- if (!literal2) {
- const foldedValue = value.replace(/\n+/g, `
-$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
- let literalFallback = false;
- const foldOptions = getFoldOptions(ctx, true);
- if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) {
- foldOptions.onOverflow = () => {
- literalFallback = true;
- };
- }
- const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
- if (!literalFallback)
- return `>${header}
-${indent}${body}`;
- }
- value = value.replace(/\n+/g, `$&${indent}`);
- return `|${header}
-${indent}${start}${value}${end}`;
- }
- function plainString(item, ctx, onComment, onChompKeep) {
- const { type, value } = item;
- const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
- if (implicitKey && value.includes(`
-`) || inFlow && /[[\]{},]/.test(value)) {
- return quotedString(value, ctx);
- }
- if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
- return implicitKey || inFlow || !value.includes(`
-`) ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
- }
- if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes(`
-`)) {
- return blockString(item, ctx, onComment, onChompKeep);
- }
- if (containsDocumentMarker(value)) {
- if (indent === "") {
- ctx.forceBlockIndent = true;
- return blockString(item, ctx, onComment, onChompKeep);
- } else if (implicitKey && indent === indentStep) {
- return quotedString(value, ctx);
- }
- }
- const str = value.replace(/\n+/g, `$&
-${indent}`);
- if (actualString) {
- const test2 = (tag2) => tag2.default && tag2.tag !== "tag:yaml.org,2002:str" && tag2.test?.test(str);
- const { compat: compat2, tags } = ctx.doc.schema;
- if (tags.some(test2) || compat2?.some(test2))
- return quotedString(value, ctx);
- }
- return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
- }
- function stringifyString(item, ctx, onComment, onChompKeep) {
- const { implicitKey, inFlow } = ctx;
- const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
- let { type } = item;
- if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
- if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
- type = Scalar.Scalar.QUOTE_DOUBLE;
- }
- const _stringify = (_type) => {
- switch (_type) {
- case Scalar.Scalar.BLOCK_FOLDED:
- case Scalar.Scalar.BLOCK_LITERAL:
- return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
- case Scalar.Scalar.QUOTE_DOUBLE:
- return doubleQuotedString(ss.value, ctx);
- case Scalar.Scalar.QUOTE_SINGLE:
- return singleQuotedString(ss.value, ctx);
- case Scalar.Scalar.PLAIN:
- return plainString(ss, ctx, onComment, onChompKeep);
- default:
- return null;
- }
- };
- let res = _stringify(type);
- if (res === null) {
- const { defaultKeyType, defaultStringType } = ctx.options;
- const t4 = implicitKey && defaultKeyType || defaultStringType;
- res = _stringify(t4);
- if (res === null)
- throw new Error(`Unsupported default string type ${t4}`);
- }
- return res;
- }
- exports.stringifyString = stringifyString;
-});
-
-// node_modules/yaml/dist/stringify/stringify.js
-var require_stringify4 = __commonJS((exports) => {
- var anchors = require_anchors();
- var identity16 = require_identity();
- var stringifyComment = require_stringifyComment();
- var stringifyString = require_stringifyString();
- function createStringifyContext(doc2, options2) {
- const opt = Object.assign({
- blockQuote: true,
- commentString: stringifyComment.stringifyComment,
- defaultKeyType: null,
- defaultStringType: "PLAIN",
- directives: null,
- doubleQuotedAsJSON: false,
- doubleQuotedMinMultiLineLength: 40,
- falseStr: "false",
- flowCollectionPadding: true,
- indentSeq: true,
- lineWidth: 80,
- minContentWidth: 20,
- nullStr: "null",
- simpleKeys: false,
- singleQuote: null,
- trailingComma: false,
- trueStr: "true",
- verifyAliasOrder: true
- }, doc2.schema.toStringOptions, options2);
- let inFlow;
- switch (opt.collectionStyle) {
- case "block":
- inFlow = false;
- break;
- case "flow":
- inFlow = true;
- break;
- default:
- inFlow = null;
- }
- return {
- anchors: new Set,
- doc: doc2,
- flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
- indent: "",
- indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ",
- inFlow,
- options: opt
- };
- }
- function getTagObject(tags, item) {
- if (item.tag) {
- const match = tags.filter((t4) => t4.tag === item.tag);
- if (match.length > 0)
- return match.find((t4) => t4.format === item.format) ?? match[0];
- }
- let tagObj = undefined;
- let obj;
- if (identity16.isScalar(item)) {
- obj = item.value;
- let match = tags.filter((t4) => t4.identify?.(obj));
- if (match.length > 1) {
- const testMatch = match.filter((t4) => t4.test);
- if (testMatch.length > 0)
- match = testMatch;
- }
- tagObj = match.find((t4) => t4.format === item.format) ?? match.find((t4) => !t4.format);
- } else {
- obj = item;
- tagObj = tags.find((t4) => t4.nodeClass && obj instanceof t4.nodeClass);
- }
- if (!tagObj) {
- const name3 = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj);
- throw new Error(`Tag not resolved for ${name3} value`);
- }
- return tagObj;
- }
- function stringifyProps(node, tagObj, { anchors: anchors$1, doc: doc2 }) {
- if (!doc2.directives)
- return "";
- const props = [];
- const anchor = (identity16.isScalar(node) || identity16.isCollection(node)) && node.anchor;
- if (anchor && anchors.anchorIsValid(anchor)) {
- anchors$1.add(anchor);
- props.push(`&${anchor}`);
- }
- const tag2 = node.tag ?? (tagObj.default ? null : tagObj.tag);
- if (tag2)
- props.push(doc2.directives.tagString(tag2));
- return props.join(" ");
- }
- function stringify2(item, ctx, onComment, onChompKeep) {
- if (identity16.isPair(item))
- return item.toString(ctx, onComment, onChompKeep);
- if (identity16.isAlias(item)) {
- if (ctx.doc.directives)
- return item.toString(ctx);
- if (ctx.resolvedAliases?.has(item)) {
- throw new TypeError(`Cannot stringify circular structure without alias nodes`);
- } else {
- if (ctx.resolvedAliases)
- ctx.resolvedAliases.add(item);
- else
- ctx.resolvedAliases = new Set([item]);
- item = item.resolve(ctx.doc);
- }
- }
- let tagObj = undefined;
- const node = identity16.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o5) => tagObj = o5 });
- tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
- const props = stringifyProps(node, tagObj, ctx);
- if (props.length > 0)
- ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
- const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity16.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
- if (!props)
- return str;
- return identity16.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}
-${ctx.indent}${str}`;
- }
- exports.createStringifyContext = createStringifyContext;
- exports.stringify = stringify2;
-});
-
-// node_modules/yaml/dist/stringify/stringifyPair.js
-var require_stringifyPair = __commonJS((exports) => {
- var identity16 = require_identity();
- var Scalar = require_Scalar();
- var stringify2 = require_stringify4();
- var stringifyComment = require_stringifyComment();
- function stringifyPair({ key: key2, value }, ctx, onComment, onChompKeep) {
- const { allNullValues, doc: doc2, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
- let keyComment = identity16.isNode(key2) && key2.comment || null;
- if (simpleKeys) {
- if (keyComment) {
- throw new Error("With simple keys, key nodes cannot have comments");
- }
- if (identity16.isCollection(key2) || !identity16.isNode(key2) && typeof key2 === "object") {
- const msg = "With simple keys, collection cannot be used as a key value";
- throw new Error(msg);
- }
- }
- let explicitKey = !simpleKeys && (!key2 || keyComment && value == null && !ctx.inFlow || identity16.isCollection(key2) || (identity16.isScalar(key2) ? key2.type === Scalar.Scalar.BLOCK_FOLDED || key2.type === Scalar.Scalar.BLOCK_LITERAL : typeof key2 === "object"));
- ctx = Object.assign({}, ctx, {
- allNullValues: false,
- implicitKey: !explicitKey && (simpleKeys || !allNullValues),
- indent: indent + indentStep
- });
- let keyCommentDone = false;
- let chompKeep = false;
- let str = stringify2.stringify(key2, ctx, () => keyCommentDone = true, () => chompKeep = true);
- if (!explicitKey && !ctx.inFlow && str.length > 1024) {
- if (simpleKeys)
- throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
- explicitKey = true;
- }
- if (ctx.inFlow) {
- if (allNullValues || value == null) {
- if (keyCommentDone && onComment)
- onComment();
- return str === "" ? "?" : explicitKey ? `? ${str}` : str;
- }
- } else if (allNullValues && !simpleKeys || value == null && explicitKey) {
- str = `? ${str}`;
- if (keyComment && !keyCommentDone) {
- str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
- } else if (chompKeep && onChompKeep)
- onChompKeep();
- return str;
- }
- if (keyCommentDone)
- keyComment = null;
- if (explicitKey) {
- if (keyComment)
- str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
- str = `? ${str}
-${indent}:`;
- } else {
- str = `${str}:`;
- if (keyComment)
- str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
- }
- let vsb, vcb, valueComment;
- if (identity16.isNode(value)) {
- vsb = !!value.spaceBefore;
- vcb = value.commentBefore;
- valueComment = value.comment;
- } else {
- vsb = false;
- vcb = null;
- valueComment = null;
- if (value && typeof value === "object")
- value = doc2.createNode(value);
- }
- ctx.implicitKey = false;
- if (!explicitKey && !keyComment && identity16.isScalar(value))
- ctx.indentAtStart = str.length + 1;
- chompKeep = false;
- if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity16.isSeq(value) && !value.flow && !value.tag && !value.anchor) {
- ctx.indent = ctx.indent.substring(2);
- }
- let valueCommentDone = false;
- const valueStr = stringify2.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true);
- let ws = " ";
- if (keyComment || vsb || vcb) {
- ws = vsb ? `
-` : "";
- if (vcb) {
- const cs = commentString(vcb);
- ws += `
-${stringifyComment.indentComment(cs, ctx.indent)}`;
- }
- if (valueStr === "" && !ctx.inFlow) {
- if (ws === `
-` && valueComment)
- ws = `
-
-`;
- } else {
- ws += `
-${ctx.indent}`;
- }
- } else if (!explicitKey && identity16.isCollection(value)) {
- const vs0 = valueStr[0];
- const nl0 = valueStr.indexOf(`
-`);
- const hasNewline = nl0 !== -1;
- const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
- if (hasNewline || !flow) {
- let hasPropsLine = false;
- if (hasNewline && (vs0 === "&" || vs0 === "!")) {
- let sp0 = valueStr.indexOf(" ");
- if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
- sp0 = valueStr.indexOf(" ", sp0 + 1);
- }
- if (sp0 === -1 || nl0 < sp0)
- hasPropsLine = true;
- }
- if (!hasPropsLine)
- ws = `
-${ctx.indent}`;
- }
- } else if (valueStr === "" || valueStr[0] === `
-`) {
- ws = "";
- }
- str += ws + valueStr;
- if (ctx.inFlow) {
- if (valueCommentDone && onComment)
- onComment();
- } else if (valueComment && !valueCommentDone) {
- str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));
- } else if (chompKeep && onChompKeep) {
- onChompKeep();
- }
- return str;
- }
- exports.stringifyPair = stringifyPair;
-});
-
-// node_modules/yaml/dist/log.js
-var require_log2 = __commonJS((exports) => {
- var node_process = __require("process");
- function debug2(logLevel, ...messages) {
- if (logLevel === "debug")
- console.log(...messages);
- }
- function warn(logLevel, warning) {
- if (logLevel === "debug" || logLevel === "warn") {
- if (typeof node_process.emitWarning === "function")
- node_process.emitWarning(warning);
- else
- console.warn(warning);
- }
- }
- exports.debug = debug2;
- exports.warn = warn;
-});
-
-// node_modules/yaml/dist/schema/yaml-1.1/merge.js
-var require_merge2 = __commonJS((exports) => {
- var identity16 = require_identity();
- var Scalar = require_Scalar();
- var MERGE_KEY = "<<";
- var merge3 = {
- identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY,
- default: "key",
- tag: "tag:yaml.org,2002:merge",
- test: /^<<$/,
- resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {
- addToJSMap: addMergeToJSMap
- }),
- stringify: () => MERGE_KEY
- };
- var isMergeKey = (ctx, key2) => (merge3.identify(key2) || identity16.isScalar(key2) && (!key2.type || key2.type === Scalar.Scalar.PLAIN) && merge3.identify(key2.value)) && ctx?.doc.schema.tags.some((tag2) => tag2.tag === merge3.tag && tag2.default);
- function addMergeToJSMap(ctx, map7, value) {
- value = ctx && identity16.isAlias(value) ? value.resolve(ctx.doc) : value;
- if (identity16.isSeq(value))
- for (const it of value.items)
- mergeValue(ctx, map7, it);
- else if (Array.isArray(value))
- for (const it of value)
- mergeValue(ctx, map7, it);
- else
- mergeValue(ctx, map7, value);
- }
- function mergeValue(ctx, map7, value) {
- const source = ctx && identity16.isAlias(value) ? value.resolve(ctx.doc) : value;
- if (!identity16.isMap(source))
- throw new Error("Merge sources must be maps or map aliases");
- const srcMap = source.toJSON(null, ctx, Map);
- for (const [key2, value2] of srcMap) {
- if (map7 instanceof Map) {
- if (!map7.has(key2))
- map7.set(key2, value2);
- } else if (map7 instanceof Set) {
- map7.add(key2);
- } else if (!Object.prototype.hasOwnProperty.call(map7, key2)) {
- Object.defineProperty(map7, key2, {
- value: value2,
- writable: true,
- enumerable: true,
- configurable: true
- });
- }
- }
- return map7;
- }
- exports.addMergeToJSMap = addMergeToJSMap;
- exports.isMergeKey = isMergeKey;
- exports.merge = merge3;
-});
-
-// node_modules/yaml/dist/nodes/addPairToJSMap.js
-var require_addPairToJSMap = __commonJS((exports) => {
- var log3 = require_log2();
- var merge3 = require_merge2();
- var stringify2 = require_stringify4();
- var identity16 = require_identity();
- var toJS = require_toJS();
- function addPairToJSMap(ctx, map7, { key: key2, value }) {
- if (identity16.isNode(key2) && key2.addToJSMap)
- key2.addToJSMap(ctx, map7, value);
- else if (merge3.isMergeKey(ctx, key2))
- merge3.addMergeToJSMap(ctx, map7, value);
- else {
- const jsKey = toJS.toJS(key2, "", ctx);
- if (map7 instanceof Map) {
- map7.set(jsKey, toJS.toJS(value, jsKey, ctx));
- } else if (map7 instanceof Set) {
- map7.add(jsKey);
- } else {
- const stringKey = stringifyKey(key2, jsKey, ctx);
- const jsValue = toJS.toJS(value, stringKey, ctx);
- if (stringKey in map7)
- Object.defineProperty(map7, stringKey, {
- value: jsValue,
- writable: true,
- enumerable: true,
- configurable: true
- });
- else
- map7[stringKey] = jsValue;
- }
- }
- return map7;
- }
- function stringifyKey(key2, jsKey, ctx) {
- if (jsKey === null)
- return "";
- if (typeof jsKey !== "object")
- return String(jsKey);
- if (identity16.isNode(key2) && ctx?.doc) {
- const strCtx = stringify2.createStringifyContext(ctx.doc, {});
- strCtx.anchors = new Set;
- for (const node of ctx.anchors.keys())
- strCtx.anchors.add(node.anchor);
- strCtx.inFlow = true;
- strCtx.inStringifyKey = true;
- const strKey = key2.toString(strCtx);
- if (!ctx.mapKeyWarned) {
- let jsonStr = JSON.stringify(strKey);
- if (jsonStr.length > 40)
- jsonStr = jsonStr.substring(0, 36) + '..."';
- log3.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
- ctx.mapKeyWarned = true;
- }
- return strKey;
- }
- return JSON.stringify(jsKey);
- }
- exports.addPairToJSMap = addPairToJSMap;
-});
-
-// node_modules/yaml/dist/nodes/Pair.js
-var require_Pair = __commonJS((exports) => {
- var createNode2 = require_createNode();
- var stringifyPair = require_stringifyPair();
- var addPairToJSMap = require_addPairToJSMap();
- var identity16 = require_identity();
- function createPair(key2, value, ctx) {
- const k4 = createNode2.createNode(key2, undefined, ctx);
- const v6 = createNode2.createNode(value, undefined, ctx);
- return new Pair(k4, v6);
- }
-
- class Pair {
- constructor(key2, value = null) {
- Object.defineProperty(this, identity16.NODE_TYPE, { value: identity16.PAIR });
- this.key = key2;
- this.value = value;
- }
- clone(schema5) {
- let { key: key2, value } = this;
- if (identity16.isNode(key2))
- key2 = key2.clone(schema5);
- if (identity16.isNode(value))
- value = value.clone(schema5);
- return new Pair(key2, value);
- }
- toJSON(_, ctx) {
- const pair = ctx?.mapAsMap ? new Map : {};
- return addPairToJSMap.addPairToJSMap(ctx, pair, this);
- }
- toString(ctx, onComment, onChompKeep) {
- return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
- }
- }
- exports.Pair = Pair;
- exports.createPair = createPair;
-});
-
-// node_modules/yaml/dist/stringify/stringifyCollection.js
-var require_stringifyCollection = __commonJS((exports) => {
- var identity16 = require_identity();
- var stringify2 = require_stringify4();
- var stringifyComment = require_stringifyComment();
- function stringifyCollection(collection, ctx, options2) {
- const flow = ctx.inFlow ?? collection.flow;
- const stringify3 = flow ? stringifyFlowCollection : stringifyBlockCollection;
- return stringify3(collection, ctx, options2);
- }
- function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
- const { indent, options: { commentString } } = ctx;
- const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
- let chompKeep = false;
- const lines2 = [];
- for (let i6 = 0;i6 < items.length; ++i6) {
- const item = items[i6];
- let comment2 = null;
- if (identity16.isNode(item)) {
- if (!chompKeep && item.spaceBefore)
- lines2.push("");
- addCommentBefore(ctx, lines2, item.commentBefore, chompKeep);
- if (item.comment)
- comment2 = item.comment;
- } else if (identity16.isPair(item)) {
- const ik = identity16.isNode(item.key) ? item.key : null;
- if (ik) {
- if (!chompKeep && ik.spaceBefore)
- lines2.push("");
- addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep);
- }
- }
- chompKeep = false;
- let str2 = stringify2.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true);
- if (comment2)
- str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2));
- if (chompKeep && comment2)
- chompKeep = false;
- lines2.push(blockItemPrefix + str2);
- }
- let str;
- if (lines2.length === 0) {
- str = flowChars.start + flowChars.end;
- } else {
- str = lines2[0];
- for (let i6 = 1;i6 < lines2.length; ++i6) {
- const line = lines2[i6];
- str += line ? `
-${indent}${line}` : `
-`;
- }
- }
- if (comment) {
- str += `
-` + stringifyComment.indentComment(commentString(comment), indent);
- if (onComment)
- onComment();
- } else if (chompKeep && onChompKeep)
- onChompKeep();
- return str;
- }
- function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
- const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
- itemIndent += indentStep;
- const itemCtx = Object.assign({}, ctx, {
- indent: itemIndent,
- inFlow: true,
- type: null
- });
- let reqNewline = false;
- let linesAtValue = 0;
- const lines2 = [];
- for (let i6 = 0;i6 < items.length; ++i6) {
- const item = items[i6];
- let comment = null;
- if (identity16.isNode(item)) {
- if (item.spaceBefore)
- lines2.push("");
- addCommentBefore(ctx, lines2, item.commentBefore, false);
- if (item.comment)
- comment = item.comment;
- } else if (identity16.isPair(item)) {
- const ik = identity16.isNode(item.key) ? item.key : null;
- if (ik) {
- if (ik.spaceBefore)
- lines2.push("");
- addCommentBefore(ctx, lines2, ik.commentBefore, false);
- if (ik.comment)
- reqNewline = true;
- }
- const iv = identity16.isNode(item.value) ? item.value : null;
- if (iv) {
- if (iv.comment)
- comment = iv.comment;
- if (iv.commentBefore)
- reqNewline = true;
- } else if (item.value == null && ik?.comment) {
- comment = ik.comment;
- }
- }
- if (comment)
- reqNewline = true;
- let str = stringify2.stringify(item, itemCtx, () => comment = null);
- reqNewline || (reqNewline = lines2.length > linesAtValue || str.includes(`
-`));
- if (i6 < items.length - 1) {
- str += ",";
- } else if (ctx.options.trailingComma) {
- if (ctx.options.lineWidth > 0) {
- reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth);
- }
- if (reqNewline) {
- str += ",";
- }
- }
- if (comment)
- str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
- lines2.push(str);
- linesAtValue = lines2.length;
- }
- const { start, end } = flowChars;
- if (lines2.length === 0) {
- return start + end;
- } else {
- if (!reqNewline) {
- const len = lines2.reduce((sum, line) => sum + line.length + 2, 2);
- reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
- }
- if (reqNewline) {
- let str = start;
- for (const line of lines2)
- str += line ? `
-${indentStep}${indent}${line}` : `
-`;
- return `${str}
-${indent}${end}`;
- } else {
- return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`;
- }
- }
- }
- function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) {
- if (comment && chompKeep)
- comment = comment.replace(/^\n+/, "");
- if (comment) {
- const ic = stringifyComment.indentComment(commentString(comment), indent);
- lines2.push(ic.trimStart());
- }
- }
- exports.stringifyCollection = stringifyCollection;
-});
-
-// node_modules/yaml/dist/nodes/YAMLMap.js
-var require_YAMLMap = __commonJS((exports) => {
- var stringifyCollection = require_stringifyCollection();
- var addPairToJSMap = require_addPairToJSMap();
- var Collection = require_Collection();
- var identity16 = require_identity();
- var Pair = require_Pair();
- var Scalar = require_Scalar();
- function findPair(items, key2) {
- const k4 = identity16.isScalar(key2) ? key2.value : key2;
- for (const it of items) {
- if (identity16.isPair(it)) {
- if (it.key === key2 || it.key === k4)
- return it;
- if (identity16.isScalar(it.key) && it.key.value === k4)
- return it;
- }
- }
- return;
- }
-
- class YAMLMap extends Collection.Collection {
- static get tagName() {
- return "tag:yaml.org,2002:map";
- }
- constructor(schema5) {
- super(identity16.MAP, schema5);
- this.items = [];
- }
- static from(schema5, obj, ctx) {
- const { keepUndefined, replacer } = ctx;
- const map7 = new this(schema5);
- const add = (key2, value) => {
- if (typeof replacer === "function")
- value = replacer.call(obj, key2, value);
- else if (Array.isArray(replacer) && !replacer.includes(key2))
- return;
- if (value !== undefined || keepUndefined)
- map7.items.push(Pair.createPair(key2, value, ctx));
- };
- if (obj instanceof Map) {
- for (const [key2, value] of obj)
- add(key2, value);
- } else if (obj && typeof obj === "object") {
- for (const key2 of Object.keys(obj))
- add(key2, obj[key2]);
- }
- if (typeof schema5.sortMapEntries === "function") {
- map7.items.sort(schema5.sortMapEntries);
- }
- return map7;
- }
- add(pair, overwrite) {
- let _pair;
- if (identity16.isPair(pair))
- _pair = pair;
- else if (!pair || typeof pair !== "object" || !("key" in pair)) {
- _pair = new Pair.Pair(pair, pair?.value);
- } else
- _pair = new Pair.Pair(pair.key, pair.value);
- const prev = findPair(this.items, _pair.key);
- const sortEntries = this.schema?.sortMapEntries;
- if (prev) {
- if (!overwrite)
- throw new Error(`Key ${_pair.key} already set`);
- if (identity16.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
- prev.value.value = _pair.value;
- else
- prev.value = _pair.value;
- } else if (sortEntries) {
- const i6 = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
- if (i6 === -1)
- this.items.push(_pair);
- else
- this.items.splice(i6, 0, _pair);
- } else {
- this.items.push(_pair);
- }
- }
- delete(key2) {
- const it = findPair(this.items, key2);
- if (!it)
- return false;
- const del = this.items.splice(this.items.indexOf(it), 1);
- return del.length > 0;
- }
- get(key2, keepScalar) {
- const it = findPair(this.items, key2);
- const node = it?.value;
- return (!keepScalar && identity16.isScalar(node) ? node.value : node) ?? undefined;
- }
- has(key2) {
- return !!findPair(this.items, key2);
- }
- set(key2, value) {
- this.add(new Pair.Pair(key2, value), true);
- }
- toJSON(_, ctx, Type) {
- const map7 = Type ? new Type : ctx?.mapAsMap ? new Map : {};
- if (ctx?.onCreate)
- ctx.onCreate(map7);
- for (const item of this.items)
- addPairToJSMap.addPairToJSMap(ctx, map7, item);
- return map7;
- }
- toString(ctx, onComment, onChompKeep) {
- if (!ctx)
- return JSON.stringify(this);
- for (const item of this.items) {
- if (!identity16.isPair(item))
- throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
- }
- if (!ctx.allNullValues && this.hasAllNullValues(false))
- ctx = Object.assign({}, ctx, { allNullValues: true });
- return stringifyCollection.stringifyCollection(this, ctx, {
- blockItemPrefix: "",
- flowChars: { start: "{", end: "}" },
- itemIndent: ctx.indent || "",
- onChompKeep,
- onComment
- });
- }
- }
- exports.YAMLMap = YAMLMap;
- exports.findPair = findPair;
-});
-
-// node_modules/yaml/dist/schema/common/map.js
-var require_map = __commonJS((exports) => {
- var identity16 = require_identity();
- var YAMLMap = require_YAMLMap();
- var map7 = {
- collection: "map",
- default: true,
- nodeClass: YAMLMap.YAMLMap,
- tag: "tag:yaml.org,2002:map",
- resolve(map8, onError) {
- if (!identity16.isMap(map8))
- onError("Expected a mapping for this tag");
- return map8;
- },
- createNode: (schema5, obj, ctx) => YAMLMap.YAMLMap.from(schema5, obj, ctx)
- };
- exports.map = map7;
-});
-
-// node_modules/yaml/dist/nodes/YAMLSeq.js
-var require_YAMLSeq = __commonJS((exports) => {
- var createNode2 = require_createNode();
- var stringifyCollection = require_stringifyCollection();
- var Collection = require_Collection();
- var identity16 = require_identity();
- var Scalar = require_Scalar();
- var toJS = require_toJS();
-
- class YAMLSeq extends Collection.Collection {
- static get tagName() {
- return "tag:yaml.org,2002:seq";
- }
- constructor(schema5) {
- super(identity16.SEQ, schema5);
- this.items = [];
- }
- add(value) {
- this.items.push(value);
- }
- delete(key2) {
- const idx = asItemIndex(key2);
- if (typeof idx !== "number")
- return false;
- const del = this.items.splice(idx, 1);
- return del.length > 0;
- }
- get(key2, keepScalar) {
- const idx = asItemIndex(key2);
- if (typeof idx !== "number")
- return;
- const it = this.items[idx];
- return !keepScalar && identity16.isScalar(it) ? it.value : it;
- }
- has(key2) {
- const idx = asItemIndex(key2);
- return typeof idx === "number" && idx < this.items.length;
- }
- set(key2, value) {
- const idx = asItemIndex(key2);
- if (typeof idx !== "number")
- throw new Error(`Expected a valid index, not ${key2}.`);
- const prev = this.items[idx];
- if (identity16.isScalar(prev) && Scalar.isScalarValue(value))
- prev.value = value;
- else
- this.items[idx] = value;
- }
- toJSON(_, ctx) {
- const seq = [];
- if (ctx?.onCreate)
- ctx.onCreate(seq);
- let i6 = 0;
- for (const item of this.items)
- seq.push(toJS.toJS(item, String(i6++), ctx));
- return seq;
- }
- toString(ctx, onComment, onChompKeep) {
- if (!ctx)
- return JSON.stringify(this);
- return stringifyCollection.stringifyCollection(this, ctx, {
- blockItemPrefix: "- ",
- flowChars: { start: "[", end: "]" },
- itemIndent: (ctx.indent || "") + " ",
- onChompKeep,
- onComment
- });
- }
- static from(schema5, obj, ctx) {
- const { replacer } = ctx;
- const seq = new this(schema5);
- if (obj && Symbol.iterator in Object(obj)) {
- let i6 = 0;
- for (let it of obj) {
- if (typeof replacer === "function") {
- const key2 = obj instanceof Set ? it : String(i6++);
- it = replacer.call(obj, key2, it);
- }
- seq.items.push(createNode2.createNode(it, undefined, ctx));
- }
- }
- return seq;
- }
- }
- function asItemIndex(key2) {
- let idx = identity16.isScalar(key2) ? key2.value : key2;
- if (idx && typeof idx === "string")
- idx = Number(idx);
- return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
- }
- exports.YAMLSeq = YAMLSeq;
-});
-
-// node_modules/yaml/dist/schema/common/seq.js
-var require_seq = __commonJS((exports) => {
- var identity16 = require_identity();
- var YAMLSeq = require_YAMLSeq();
- var seq = {
- collection: "seq",
- default: true,
- nodeClass: YAMLSeq.YAMLSeq,
- tag: "tag:yaml.org,2002:seq",
- resolve(seq2, onError) {
- if (!identity16.isSeq(seq2))
- onError("Expected a sequence for this tag");
- return seq2;
- },
- createNode: (schema5, obj, ctx) => YAMLSeq.YAMLSeq.from(schema5, obj, ctx)
- };
- exports.seq = seq;
-});
-
-// node_modules/yaml/dist/schema/common/string.js
-var require_string = __commonJS((exports) => {
- var stringifyString = require_stringifyString();
- var string4 = {
- identify: (value) => typeof value === "string",
- default: true,
- tag: "tag:yaml.org,2002:str",
- resolve: (str) => str,
- stringify(item, ctx, onComment, onChompKeep) {
- ctx = Object.assign({ actualString: true }, ctx);
- return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);
- }
- };
- exports.string = string4;
-});
-
-// node_modules/yaml/dist/schema/common/null.js
-var require_null = __commonJS((exports) => {
- var Scalar = require_Scalar();
- var nullTag2 = {
- identify: (value) => value == null,
- createNode: () => new Scalar.Scalar(null),
- default: true,
- tag: "tag:yaml.org,2002:null",
- test: /^(?:~|[Nn]ull|NULL)?$/,
- resolve: () => new Scalar.Scalar(null),
- stringify: ({ source }, ctx) => typeof source === "string" && nullTag2.test.test(source) ? source : ctx.options.nullStr
- };
- exports.nullTag = nullTag2;
-});
-
-// node_modules/yaml/dist/schema/core/bool.js
-var require_bool = __commonJS((exports) => {
- var Scalar = require_Scalar();
- var boolTag5 = {
- identify: (value) => typeof value === "boolean",
- default: true,
- tag: "tag:yaml.org,2002:bool",
- test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
- resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"),
- stringify({ source, value }, ctx) {
- if (source && boolTag5.test.test(source)) {
- const sv = source[0] === "t" || source[0] === "T";
- if (value === sv)
- return source;
- }
- return value ? ctx.options.trueStr : ctx.options.falseStr;
- }
- };
- exports.boolTag = boolTag5;
-});
-
-// node_modules/yaml/dist/stringify/stringifyNumber.js
-var require_stringifyNumber = __commonJS((exports) => {
- function stringifyNumber({ format: format4, minFractionDigits, tag: tag2, value }) {
- if (typeof value === "bigint")
- return String(value);
- const num = typeof value === "number" ? value : Number(value);
- if (!isFinite(num))
- return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
- let n5 = Object.is(value, -0) ? "-0" : JSON.stringify(value);
- if (!format4 && minFractionDigits && (!tag2 || tag2 === "tag:yaml.org,2002:float") && /^\d/.test(n5)) {
- let i6 = n5.indexOf(".");
- if (i6 < 0) {
- i6 = n5.length;
- n5 += ".";
- }
- let d4 = minFractionDigits - (n5.length - i6 - 1);
- while (d4-- > 0)
- n5 += "0";
- }
- return n5;
- }
- exports.stringifyNumber = stringifyNumber;
-});
-
-// node_modules/yaml/dist/schema/core/float.js
-var require_float = __commonJS((exports) => {
- var Scalar = require_Scalar();
- var stringifyNumber = require_stringifyNumber();
- var floatNaN = {
- identify: (value) => typeof value === "number",
- default: true,
- tag: "tag:yaml.org,2002:float",
- test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
- resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
- stringify: stringifyNumber.stringifyNumber
- };
- var floatExp = {
- identify: (value) => typeof value === "number",
- default: true,
- tag: "tag:yaml.org,2002:float",
- format: "EXP",
- test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
- resolve: (str) => parseFloat(str),
- stringify(node) {
- const num = Number(node.value);
- return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
- }
- };
- var float = {
- identify: (value) => typeof value === "number",
- default: true,
- tag: "tag:yaml.org,2002:float",
- test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
- resolve(str) {
- const node = new Scalar.Scalar(parseFloat(str));
- const dot = str.indexOf(".");
- if (dot !== -1 && str[str.length - 1] === "0")
- node.minFractionDigits = str.length - dot - 1;
- return node;
- },
- stringify: stringifyNumber.stringifyNumber
- };
- exports.float = float;
- exports.floatExp = floatExp;
- exports.floatNaN = floatNaN;
-});
-
-// node_modules/yaml/dist/schema/core/int.js
-var require_int = __commonJS((exports) => {
- var stringifyNumber = require_stringifyNumber();
- var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
- var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix);
- function intStringify(node, radix, prefix) {
- const { value } = node;
- if (intIdentify(value) && value >= 0)
- return prefix + value.toString(radix);
- return stringifyNumber.stringifyNumber(node);
- }
- var intOct = {
- identify: (value) => intIdentify(value) && value >= 0,
- default: true,
- tag: "tag:yaml.org,2002:int",
- format: "OCT",
- test: /^0o[0-7]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
- stringify: (node) => intStringify(node, 8, "0o")
- };
- var int2 = {
- identify: intIdentify,
- default: true,
- tag: "tag:yaml.org,2002:int",
- test: /^[-+]?[0-9]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
- stringify: stringifyNumber.stringifyNumber
- };
- var intHex = {
- identify: (value) => intIdentify(value) && value >= 0,
- default: true,
- tag: "tag:yaml.org,2002:int",
- format: "HEX",
- test: /^0x[0-9a-fA-F]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
- stringify: (node) => intStringify(node, 16, "0x")
- };
- exports.int = int2;
- exports.intHex = intHex;
- exports.intOct = intOct;
-});
-
-// node_modules/yaml/dist/schema/core/schema.js
-var require_schema2 = __commonJS((exports) => {
- var map7 = require_map();
- var _null4 = require_null();
- var seq = require_seq();
- var string4 = require_string();
- var bool = require_bool();
- var float = require_float();
- var int2 = require_int();
- var schema5 = [
- map7.map,
- seq.seq,
- string4.string,
- _null4.nullTag,
- bool.boolTag,
- int2.intOct,
- int2.int,
- int2.intHex,
- float.floatNaN,
- float.floatExp,
- float.float
- ];
- exports.schema = schema5;
-});
-
-// node_modules/yaml/dist/schema/json/schema.js
-var require_schema3 = __commonJS((exports) => {
- var Scalar = require_Scalar();
- var map7 = require_map();
- var seq = require_seq();
- function intIdentify(value) {
- return typeof value === "bigint" || Number.isInteger(value);
- }
- var stringifyJSON = ({ value }) => JSON.stringify(value);
- var jsonScalars = [
- {
- identify: (value) => typeof value === "string",
- default: true,
- tag: "tag:yaml.org,2002:str",
- resolve: (str) => str,
- stringify: stringifyJSON
- },
- {
- identify: (value) => value == null,
- createNode: () => new Scalar.Scalar(null),
- default: true,
- tag: "tag:yaml.org,2002:null",
- test: /^null$/,
- resolve: () => null,
- stringify: stringifyJSON
- },
- {
- identify: (value) => typeof value === "boolean",
- default: true,
- tag: "tag:yaml.org,2002:bool",
- test: /^true$|^false$/,
- resolve: (str) => str === "true",
- stringify: stringifyJSON
- },
- {
- identify: intIdentify,
- default: true,
- tag: "tag:yaml.org,2002:int",
- test: /^-?(?:0|[1-9][0-9]*)$/,
- resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
- stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
- },
- {
- identify: (value) => typeof value === "number",
- default: true,
- tag: "tag:yaml.org,2002:float",
- test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
- resolve: (str) => parseFloat(str),
- stringify: stringifyJSON
- }
- ];
- var jsonError = {
- default: true,
- tag: "",
- test: /^/,
- resolve(str, onError) {
- onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
- return str;
- }
- };
- var schema5 = [map7.map, seq.seq].concat(jsonScalars, jsonError);
- exports.schema = schema5;
-});
-
-// node_modules/yaml/dist/schema/yaml-1.1/binary.js
-var require_binary = __commonJS((exports) => {
- var node_buffer = __require("buffer");
- var Scalar = require_Scalar();
- var stringifyString = require_stringifyString();
- var binary = {
- identify: (value) => value instanceof Uint8Array,
- default: false,
- tag: "tag:yaml.org,2002:binary",
- resolve(src, onError) {
- if (typeof node_buffer.Buffer === "function") {
- return node_buffer.Buffer.from(src, "base64");
- } else if (typeof atob === "function") {
- const str = atob(src.replace(/[\n\r]/g, ""));
- const buffer = new Uint8Array(str.length);
- for (let i6 = 0;i6 < str.length; ++i6)
- buffer[i6] = str.charCodeAt(i6);
- return buffer;
- } else {
- onError("This environment does not support reading binary tags; either Buffer or atob is required");
- return src;
- }
- },
- stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
- if (!value)
- return "";
- const buf = value;
- let str;
- if (typeof node_buffer.Buffer === "function") {
- str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64");
- } else if (typeof btoa === "function") {
- let s4 = "";
- for (let i6 = 0;i6 < buf.length; ++i6)
- s4 += String.fromCharCode(buf[i6]);
- str = btoa(s4);
- } else {
- throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
- }
- type ?? (type = Scalar.Scalar.BLOCK_LITERAL);
- if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
- const lineWidth2 = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
- const n5 = Math.ceil(str.length / lineWidth2);
- const lines2 = new Array(n5);
- for (let i6 = 0, o5 = 0;i6 < n5; ++i6, o5 += lineWidth2) {
- lines2[i6] = str.substr(o5, lineWidth2);
- }
- str = lines2.join(type === Scalar.Scalar.BLOCK_LITERAL ? `
-` : " ");
- }
- return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
- }
- };
- exports.binary = binary;
-});
-
-// node_modules/yaml/dist/schema/yaml-1.1/pairs.js
-var require_pairs = __commonJS((exports) => {
- var identity16 = require_identity();
- var Pair = require_Pair();
- var Scalar = require_Scalar();
- var YAMLSeq = require_YAMLSeq();
- function resolvePairs(seq, onError) {
- if (identity16.isSeq(seq)) {
- for (let i6 = 0;i6 < seq.items.length; ++i6) {
- let item = seq.items[i6];
- if (identity16.isPair(item))
- continue;
- else if (identity16.isMap(item)) {
- if (item.items.length > 1)
- onError("Each pair must have its own sequence indicator");
- const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));
- if (item.commentBefore)
- pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}
-${pair.key.commentBefore}` : item.commentBefore;
- if (item.comment) {
- const cn = pair.value ?? pair.key;
- cn.comment = cn.comment ? `${item.comment}
-${cn.comment}` : item.comment;
- }
- item = pair;
- }
- seq.items[i6] = identity16.isPair(item) ? item : new Pair.Pair(item);
- }
- } else
- onError("Expected a sequence for this tag");
- return seq;
- }
- function createPairs(schema5, iterable, ctx) {
- const { replacer } = ctx;
- const pairs2 = new YAMLSeq.YAMLSeq(schema5);
- pairs2.tag = "tag:yaml.org,2002:pairs";
- let i6 = 0;
- if (iterable && Symbol.iterator in Object(iterable))
- for (let it of iterable) {
- if (typeof replacer === "function")
- it = replacer.call(iterable, String(i6++), it);
- let key2, value;
- if (Array.isArray(it)) {
- if (it.length === 2) {
- key2 = it[0];
- value = it[1];
- } else
- throw new TypeError(`Expected [key, value] tuple: ${it}`);
- } else if (it && it instanceof Object) {
- const keys2 = Object.keys(it);
- if (keys2.length === 1) {
- key2 = keys2[0];
- value = it[key2];
- } else {
- throw new TypeError(`Expected tuple with one key, not ${keys2.length} keys`);
- }
- } else {
- key2 = it;
- }
- pairs2.items.push(Pair.createPair(key2, value, ctx));
- }
- return pairs2;
- }
- var pairs = {
- collection: "seq",
- default: false,
- tag: "tag:yaml.org,2002:pairs",
- resolve: resolvePairs,
- createNode: createPairs
- };
- exports.createPairs = createPairs;
- exports.pairs = pairs;
- exports.resolvePairs = resolvePairs;
-});
-
-// node_modules/yaml/dist/schema/yaml-1.1/omap.js
-var require_omap = __commonJS((exports) => {
- var identity16 = require_identity();
- var toJS = require_toJS();
- var YAMLMap = require_YAMLMap();
- var YAMLSeq = require_YAMLSeq();
- var pairs = require_pairs();
-
- class YAMLOMap extends YAMLSeq.YAMLSeq {
- constructor() {
- super();
- this.add = YAMLMap.YAMLMap.prototype.add.bind(this);
- this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);
- this.get = YAMLMap.YAMLMap.prototype.get.bind(this);
- this.has = YAMLMap.YAMLMap.prototype.has.bind(this);
- this.set = YAMLMap.YAMLMap.prototype.set.bind(this);
- this.tag = YAMLOMap.tag;
- }
- toJSON(_, ctx) {
- if (!ctx)
- return super.toJSON(_);
- const map7 = new Map;
- if (ctx?.onCreate)
- ctx.onCreate(map7);
- for (const pair of this.items) {
- let key2, value;
- if (identity16.isPair(pair)) {
- key2 = toJS.toJS(pair.key, "", ctx);
- value = toJS.toJS(pair.value, key2, ctx);
- } else {
- key2 = toJS.toJS(pair, "", ctx);
- }
- if (map7.has(key2))
- throw new Error("Ordered maps must not include duplicate keys");
- map7.set(key2, value);
- }
- return map7;
- }
- static from(schema5, iterable, ctx) {
- const pairs$1 = pairs.createPairs(schema5, iterable, ctx);
- const omap2 = new this;
- omap2.items = pairs$1.items;
- return omap2;
- }
- }
- YAMLOMap.tag = "tag:yaml.org,2002:omap";
- var omap = {
- collection: "seq",
- identify: (value) => value instanceof Map,
- nodeClass: YAMLOMap,
- default: false,
- tag: "tag:yaml.org,2002:omap",
- resolve(seq, onError) {
- const pairs$1 = pairs.resolvePairs(seq, onError);
- const seenKeys = [];
- for (const { key: key2 } of pairs$1.items) {
- if (identity16.isScalar(key2)) {
- if (seenKeys.includes(key2.value)) {
- onError(`Ordered maps must not include duplicate keys: ${key2.value}`);
- } else {
- seenKeys.push(key2.value);
- }
- }
- }
- return Object.assign(new YAMLOMap, pairs$1);
- },
- createNode: (schema5, iterable, ctx) => YAMLOMap.from(schema5, iterable, ctx)
- };
- exports.YAMLOMap = YAMLOMap;
- exports.omap = omap;
-});
-
-// node_modules/yaml/dist/schema/yaml-1.1/bool.js
-var require_bool2 = __commonJS((exports) => {
- var Scalar = require_Scalar();
- function boolStringify({ value, source }, ctx) {
- const boolObj = value ? trueTag : falseTag;
- if (source && boolObj.test.test(source))
- return source;
- return value ? ctx.options.trueStr : ctx.options.falseStr;
- }
- var trueTag = {
- identify: (value) => value === true,
- default: true,
- tag: "tag:yaml.org,2002:bool",
- test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
- resolve: () => new Scalar.Scalar(true),
- stringify: boolStringify
- };
- var falseTag = {
- identify: (value) => value === false,
- default: true,
- tag: "tag:yaml.org,2002:bool",
- test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
- resolve: () => new Scalar.Scalar(false),
- stringify: boolStringify
- };
- exports.falseTag = falseTag;
- exports.trueTag = trueTag;
-});
-
-// node_modules/yaml/dist/schema/yaml-1.1/float.js
-var require_float2 = __commonJS((exports) => {
- var Scalar = require_Scalar();
- var stringifyNumber = require_stringifyNumber();
- var floatNaN = {
- identify: (value) => typeof value === "number",
- default: true,
- tag: "tag:yaml.org,2002:float",
- test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
- resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
- stringify: stringifyNumber.stringifyNumber
- };
- var floatExp = {
- identify: (value) => typeof value === "number",
- default: true,
- tag: "tag:yaml.org,2002:float",
- format: "EXP",
- test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
- resolve: (str) => parseFloat(str.replace(/_/g, "")),
- stringify(node) {
- const num = Number(node.value);
- return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
- }
- };
- var float = {
- identify: (value) => typeof value === "number",
- default: true,
- tag: "tag:yaml.org,2002:float",
- test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
- resolve(str) {
- const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, "")));
- const dot = str.indexOf(".");
- if (dot !== -1) {
- const f4 = str.substring(dot + 1).replace(/_/g, "");
- if (f4[f4.length - 1] === "0")
- node.minFractionDigits = f4.length;
- }
- return node;
- },
- stringify: stringifyNumber.stringifyNumber
- };
- exports.float = float;
- exports.floatExp = floatExp;
- exports.floatNaN = floatNaN;
-});
-
-// node_modules/yaml/dist/schema/yaml-1.1/int.js
-var require_int2 = __commonJS((exports) => {
- var stringifyNumber = require_stringifyNumber();
- var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
- function intResolve(str, offset, radix, { intAsBigInt }) {
- const sign3 = str[0];
- if (sign3 === "-" || sign3 === "+")
- offset += 1;
- str = str.substring(offset).replace(/_/g, "");
- if (intAsBigInt) {
- switch (radix) {
- case 2:
- str = `0b${str}`;
- break;
- case 8:
- str = `0o${str}`;
- break;
- case 16:
- str = `0x${str}`;
- break;
- }
- const n6 = BigInt(str);
- return sign3 === "-" ? BigInt(-1) * n6 : n6;
- }
- const n5 = parseInt(str, radix);
- return sign3 === "-" ? -1 * n5 : n5;
- }
- function intStringify(node, radix, prefix) {
- const { value } = node;
- if (intIdentify(value)) {
- const str = value.toString(radix);
- return value < 0 ? "-" + prefix + str.substr(1) : prefix + str;
- }
- return stringifyNumber.stringifyNumber(node);
- }
- var intBin = {
- identify: intIdentify,
- default: true,
- tag: "tag:yaml.org,2002:int",
- format: "BIN",
- test: /^[-+]?0b[0-1_]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
- stringify: (node) => intStringify(node, 2, "0b")
- };
- var intOct = {
- identify: intIdentify,
- default: true,
- tag: "tag:yaml.org,2002:int",
- format: "OCT",
- test: /^[-+]?0[0-7_]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
- stringify: (node) => intStringify(node, 8, "0")
- };
- var int2 = {
- identify: intIdentify,
- default: true,
- tag: "tag:yaml.org,2002:int",
- test: /^[-+]?[0-9][0-9_]*$/,
- resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
- stringify: stringifyNumber.stringifyNumber
- };
- var intHex = {
- identify: intIdentify,
- default: true,
- tag: "tag:yaml.org,2002:int",
- format: "HEX",
- test: /^[-+]?0x[0-9a-fA-F_]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
- stringify: (node) => intStringify(node, 16, "0x")
- };
- exports.int = int2;
- exports.intBin = intBin;
- exports.intHex = intHex;
- exports.intOct = intOct;
-});
-
-// node_modules/yaml/dist/schema/yaml-1.1/set.js
-var require_set = __commonJS((exports) => {
- var identity16 = require_identity();
- var Pair = require_Pair();
- var YAMLMap = require_YAMLMap();
-
- class YAMLSet extends YAMLMap.YAMLMap {
- constructor(schema5) {
- super(schema5);
- this.tag = YAMLSet.tag;
- }
- add(key2) {
- let pair;
- if (identity16.isPair(key2))
- pair = key2;
- else if (key2 && typeof key2 === "object" && "key" in key2 && "value" in key2 && key2.value === null)
- pair = new Pair.Pair(key2.key, null);
- else
- pair = new Pair.Pair(key2, null);
- const prev = YAMLMap.findPair(this.items, pair.key);
- if (!prev)
- this.items.push(pair);
- }
- get(key2, keepPair) {
- const pair = YAMLMap.findPair(this.items, key2);
- return !keepPair && identity16.isPair(pair) ? identity16.isScalar(pair.key) ? pair.key.value : pair.key : pair;
- }
- set(key2, value) {
- if (typeof value !== "boolean")
- throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
- const prev = YAMLMap.findPair(this.items, key2);
- if (prev && !value) {
- this.items.splice(this.items.indexOf(prev), 1);
- } else if (!prev && value) {
- this.items.push(new Pair.Pair(key2));
- }
- }
- toJSON(_, ctx) {
- return super.toJSON(_, ctx, Set);
- }
- toString(ctx, onComment, onChompKeep) {
- if (!ctx)
- return JSON.stringify(this);
- if (this.hasAllNullValues(true))
- return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
- else
- throw new Error("Set items must all have null values");
- }
- static from(schema5, iterable, ctx) {
- const { replacer } = ctx;
- const set3 = new this(schema5);
- if (iterable && Symbol.iterator in Object(iterable))
- for (let value of iterable) {
- if (typeof replacer === "function")
- value = replacer.call(iterable, value, value);
- set3.items.push(Pair.createPair(value, null, ctx));
- }
- return set3;
- }
- }
- YAMLSet.tag = "tag:yaml.org,2002:set";
- var set2 = {
- collection: "map",
- identify: (value) => value instanceof Set,
- nodeClass: YAMLSet,
- default: false,
- tag: "tag:yaml.org,2002:set",
- createNode: (schema5, iterable, ctx) => YAMLSet.from(schema5, iterable, ctx),
- resolve(map7, onError) {
- if (identity16.isMap(map7)) {
- if (map7.hasAllNullValues(true))
- return Object.assign(new YAMLSet, map7);
- else
- onError("Set items must all have null values");
- } else
- onError("Expected a mapping for this tag");
- return map7;
- }
- };
- exports.YAMLSet = YAMLSet;
- exports.set = set2;
-});
-
-// node_modules/yaml/dist/schema/yaml-1.1/timestamp.js
-var require_timestamp = __commonJS((exports) => {
- var stringifyNumber = require_stringifyNumber();
- function parseSexagesimal(str, asBigInt) {
- const sign3 = str[0];
- const parts = sign3 === "-" || sign3 === "+" ? str.substring(1) : str;
- const num = (n5) => asBigInt ? BigInt(n5) : Number(n5);
- const res = parts.replace(/_/g, "").split(":").reduce((res2, p4) => res2 * num(60) + num(p4), num(0));
- return sign3 === "-" ? num(-1) * res : res;
- }
- function stringifySexagesimal(node) {
- let { value } = node;
- let num = (n5) => n5;
- if (typeof value === "bigint")
- num = (n5) => BigInt(n5);
- else if (isNaN(value) || !isFinite(value))
- return stringifyNumber.stringifyNumber(node);
- let sign3 = "";
- if (value < 0) {
- sign3 = "-";
- value *= num(-1);
- }
- const _60 = num(60);
- const parts = [value % _60];
- if (value < 60) {
- parts.unshift(0);
- } else {
- value = (value - parts[0]) / _60;
- parts.unshift(value % _60);
- if (value >= 60) {
- value = (value - parts[0]) / _60;
- parts.unshift(value);
- }
- }
- return sign3 + parts.map((n5) => String(n5).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
- }
- var intTime = {
- identify: (value) => typeof value === "bigint" || Number.isInteger(value),
- default: true,
- tag: "tag:yaml.org,2002:int",
- format: "TIME",
- test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
- resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
- stringify: stringifySexagesimal
- };
- var floatTime = {
- identify: (value) => typeof value === "number",
- default: true,
- tag: "tag:yaml.org,2002:float",
- format: "TIME",
- test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
- resolve: (str) => parseSexagesimal(str, false),
- stringify: stringifySexagesimal
- };
- var timestamp = {
- identify: (value) => value instanceof Date,
- default: true,
- tag: "tag:yaml.org,2002:timestamp",
- test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})" + "(?:" + "(?:t|T|[ \\t]+)" + "([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)" + "(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?" + ")?$"),
- resolve(str) {
- const match = str.match(timestamp.test);
- if (!match)
- throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
- const [, year, month, day, hour, minute, second] = match.map(Number);
- const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0;
- let date5 = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
- const tz = match[8];
- if (tz && tz !== "Z") {
- let d4 = parseSexagesimal(tz, false);
- if (Math.abs(d4) < 30)
- d4 *= 60;
- date5 -= 60000 * d4;
- }
- return new Date(date5);
- },
- stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? ""
- };
- exports.floatTime = floatTime;
- exports.intTime = intTime;
- exports.timestamp = timestamp;
-});
-
-// node_modules/yaml/dist/schema/yaml-1.1/schema.js
-var require_schema4 = __commonJS((exports) => {
- var map7 = require_map();
- var _null4 = require_null();
- var seq = require_seq();
- var string4 = require_string();
- var binary = require_binary();
- var bool = require_bool2();
- var float = require_float2();
- var int2 = require_int2();
- var merge3 = require_merge2();
- var omap = require_omap();
- var pairs = require_pairs();
- var set2 = require_set();
- var timestamp = require_timestamp();
- var schema5 = [
- map7.map,
- seq.seq,
- string4.string,
- _null4.nullTag,
- bool.trueTag,
- bool.falseTag,
- int2.intBin,
- int2.intOct,
- int2.int,
- int2.intHex,
- float.floatNaN,
- float.floatExp,
- float.float,
- binary.binary,
- merge3.merge,
- omap.omap,
- pairs.pairs,
- set2.set,
- timestamp.intTime,
- timestamp.floatTime,
- timestamp.timestamp
- ];
- exports.schema = schema5;
-});
-
-// node_modules/yaml/dist/schema/tags.js
-var require_tags = __commonJS((exports) => {
- var map7 = require_map();
- var _null4 = require_null();
- var seq = require_seq();
- var string4 = require_string();
- var bool = require_bool();
- var float = require_float();
- var int2 = require_int();
- var schema5 = require_schema2();
- var schema$1 = require_schema3();
- var binary = require_binary();
- var merge3 = require_merge2();
- var omap = require_omap();
- var pairs = require_pairs();
- var schema$2 = require_schema4();
- var set2 = require_set();
- var timestamp = require_timestamp();
- var schemas4 = new Map([
- ["core", schema5.schema],
- ["failsafe", [map7.map, seq.seq, string4.string]],
- ["json", schema$1.schema],
- ["yaml11", schema$2.schema],
- ["yaml-1.1", schema$2.schema]
- ]);
- var tagsByName = {
- binary: binary.binary,
- bool: bool.boolTag,
- float: float.float,
- floatExp: float.floatExp,
- floatNaN: float.floatNaN,
- floatTime: timestamp.floatTime,
- int: int2.int,
- intHex: int2.intHex,
- intOct: int2.intOct,
- intTime: timestamp.intTime,
- map: map7.map,
- merge: merge3.merge,
- null: _null4.nullTag,
- omap: omap.omap,
- pairs: pairs.pairs,
- seq: seq.seq,
- set: set2.set,
- timestamp: timestamp.timestamp
- };
- var coreKnownTags = {
- "tag:yaml.org,2002:binary": binary.binary,
- "tag:yaml.org,2002:merge": merge3.merge,
- "tag:yaml.org,2002:omap": omap.omap,
- "tag:yaml.org,2002:pairs": pairs.pairs,
- "tag:yaml.org,2002:set": set2.set,
- "tag:yaml.org,2002:timestamp": timestamp.timestamp
- };
- function getTags(customTags, schemaName, addMergeTag) {
- const schemaTags = schemas4.get(schemaName);
- if (schemaTags && !customTags) {
- return addMergeTag && !schemaTags.includes(merge3.merge) ? schemaTags.concat(merge3.merge) : schemaTags.slice();
- }
- let tags = schemaTags;
- if (!tags) {
- if (Array.isArray(customTags))
- tags = [];
- else {
- const keys2 = Array.from(schemas4.keys()).filter((key2) => key2 !== "yaml11").map((key2) => JSON.stringify(key2)).join(", ");
- throw new Error(`Unknown schema "${schemaName}"; use one of ${keys2} or define customTags array`);
- }
- }
- if (Array.isArray(customTags)) {
- for (const tag2 of customTags)
- tags = tags.concat(tag2);
- } else if (typeof customTags === "function") {
- tags = customTags(tags.slice());
- }
- if (addMergeTag)
- tags = tags.concat(merge3.merge);
- return tags.reduce((tags2, tag2) => {
- const tagObj = typeof tag2 === "string" ? tagsByName[tag2] : tag2;
- if (!tagObj) {
- const tagName = JSON.stringify(tag2);
- const keys2 = Object.keys(tagsByName).map((key2) => JSON.stringify(key2)).join(", ");
- throw new Error(`Unknown custom tag ${tagName}; use one of ${keys2}`);
- }
- if (!tags2.includes(tagObj))
- tags2.push(tagObj);
- return tags2;
- }, []);
- }
- exports.coreKnownTags = coreKnownTags;
- exports.getTags = getTags;
-});
-
-// node_modules/yaml/dist/schema/Schema.js
-var require_Schema = __commonJS((exports) => {
- var identity16 = require_identity();
- var map7 = require_map();
- var seq = require_seq();
- var string4 = require_string();
- var tags = require_tags();
- var sortMapEntriesByKey = (a5, b5) => a5.key < b5.key ? -1 : a5.key > b5.key ? 1 : 0;
-
- class Schema {
- constructor({ compat: compat2, customTags, merge: merge3, resolveKnownTags, schema: schema5, sortMapEntries, toStringDefaults }) {
- this.compat = Array.isArray(compat2) ? tags.getTags(compat2, "compat") : compat2 ? tags.getTags(null, compat2) : null;
- this.name = typeof schema5 === "string" && schema5 || "core";
- this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
- this.tags = tags.getTags(customTags, this.name, merge3);
- this.toStringOptions = toStringDefaults ?? null;
- Object.defineProperty(this, identity16.MAP, { value: map7.map });
- Object.defineProperty(this, identity16.SCALAR, { value: string4.string });
- Object.defineProperty(this, identity16.SEQ, { value: seq.seq });
- this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
- }
- clone() {
- const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
- copy.tags = this.tags.slice();
- return copy;
- }
- }
- exports.Schema = Schema;
-});
-
-// node_modules/yaml/dist/stringify/stringifyDocument.js
-var require_stringifyDocument = __commonJS((exports) => {
- var identity16 = require_identity();
- var stringify2 = require_stringify4();
- var stringifyComment = require_stringifyComment();
- function stringifyDocument(doc2, options2) {
- const lines2 = [];
- let hasDirectives = options2.directives === true;
- if (options2.directives !== false && doc2.directives) {
- const dir = doc2.directives.toString(doc2);
- if (dir) {
- lines2.push(dir);
- hasDirectives = true;
- } else if (doc2.directives.docStart)
- hasDirectives = true;
- }
- if (hasDirectives)
- lines2.push("---");
- const ctx = stringify2.createStringifyContext(doc2, options2);
- const { commentString } = ctx.options;
- if (doc2.commentBefore) {
- if (lines2.length !== 1)
- lines2.unshift("");
- const cs = commentString(doc2.commentBefore);
- lines2.unshift(stringifyComment.indentComment(cs, ""));
- }
- let chompKeep = false;
- let contentComment = null;
- if (doc2.contents) {
- if (identity16.isNode(doc2.contents)) {
- if (doc2.contents.spaceBefore && hasDirectives)
- lines2.push("");
- if (doc2.contents.commentBefore) {
- const cs = commentString(doc2.contents.commentBefore);
- lines2.push(stringifyComment.indentComment(cs, ""));
- }
- ctx.forceBlockIndent = !!doc2.comment;
- contentComment = doc2.contents.comment;
- }
- const onChompKeep = contentComment ? undefined : () => chompKeep = true;
- let body = stringify2.stringify(doc2.contents, ctx, () => contentComment = null, onChompKeep);
- if (contentComment)
- body += stringifyComment.lineComment(body, "", commentString(contentComment));
- if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") {
- lines2[lines2.length - 1] = `--- ${body}`;
- } else
- lines2.push(body);
- } else {
- lines2.push(stringify2.stringify(doc2.contents, ctx));
- }
- if (doc2.directives?.docEnd) {
- if (doc2.comment) {
- const cs = commentString(doc2.comment);
- if (cs.includes(`
-`)) {
- lines2.push("...");
- lines2.push(stringifyComment.indentComment(cs, ""));
- } else {
- lines2.push(`... ${cs}`);
- }
- } else {
- lines2.push("...");
- }
- } else {
- let dc = doc2.comment;
- if (dc && chompKeep)
- dc = dc.replace(/^\n+/, "");
- if (dc) {
- if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "")
- lines2.push("");
- lines2.push(stringifyComment.indentComment(commentString(dc), ""));
- }
- }
- return lines2.join(`
-`) + `
-`;
- }
- exports.stringifyDocument = stringifyDocument;
-});
-
-// node_modules/yaml/dist/doc/Document.js
-var require_Document = __commonJS((exports) => {
- var Alias = require_Alias();
- var Collection = require_Collection();
- var identity16 = require_identity();
- var Pair = require_Pair();
- var toJS = require_toJS();
- var Schema = require_Schema();
- var stringifyDocument = require_stringifyDocument();
- var anchors = require_anchors();
- var applyReviver = require_applyReviver();
- var createNode2 = require_createNode();
- var directives = require_directives();
-
- class Document {
- constructor(value, replacer, options2) {
- this.commentBefore = null;
- this.comment = null;
- this.errors = [];
- this.warnings = [];
- Object.defineProperty(this, identity16.NODE_TYPE, { value: identity16.DOC });
- let _replacer = null;
- if (typeof replacer === "function" || Array.isArray(replacer)) {
- _replacer = replacer;
- } else if (options2 === undefined && replacer) {
- options2 = replacer;
- replacer = undefined;
- }
- const opt = Object.assign({
- intAsBigInt: false,
- keepSourceTokens: false,
- logLevel: "warn",
- prettyErrors: true,
- strict: true,
- stringKeys: false,
- uniqueKeys: true,
- version: "1.2"
- }, options2);
- this.options = opt;
- let { version: version6 } = opt;
- if (options2?._directives) {
- this.directives = options2._directives.atDocument();
- if (this.directives.yaml.explicit)
- version6 = this.directives.yaml.version;
- } else
- this.directives = new directives.Directives({ version: version6 });
- this.setSchema(version6, options2);
- this.contents = value === undefined ? null : this.createNode(value, _replacer, options2);
- }
- clone() {
- const copy = Object.create(Document.prototype, {
- [identity16.NODE_TYPE]: { value: identity16.DOC }
- });
- copy.commentBefore = this.commentBefore;
- copy.comment = this.comment;
- copy.errors = this.errors.slice();
- copy.warnings = this.warnings.slice();
- copy.options = Object.assign({}, this.options);
- if (this.directives)
- copy.directives = this.directives.clone();
- copy.schema = this.schema.clone();
- copy.contents = identity16.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents;
- if (this.range)
- copy.range = this.range.slice();
- return copy;
- }
- add(value) {
- if (assertCollection(this.contents))
- this.contents.add(value);
- }
- addIn(path16, value) {
- if (assertCollection(this.contents))
- this.contents.addIn(path16, value);
- }
- createAlias(node, name3) {
- if (!node.anchor) {
- const prev = anchors.anchorNames(this);
- node.anchor = !name3 || prev.has(name3) ? anchors.findNewAnchor(name3 || "a", prev) : name3;
- }
- return new Alias.Alias(node.anchor);
- }
- createNode(value, replacer, options2) {
- let _replacer = undefined;
- if (typeof replacer === "function") {
- value = replacer.call({ "": value }, "", value);
- _replacer = replacer;
- } else if (Array.isArray(replacer)) {
- const keyToStr = (v6) => typeof v6 === "number" || v6 instanceof String || v6 instanceof Number;
- const asStr = replacer.filter(keyToStr).map(String);
- if (asStr.length > 0)
- replacer = replacer.concat(asStr);
- _replacer = replacer;
- } else if (options2 === undefined && replacer) {
- options2 = replacer;
- replacer = undefined;
- }
- const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag: tag2 } = options2 ?? {};
- const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, anchorPrefix || "a");
- const ctx = {
- aliasDuplicateObjects: aliasDuplicateObjects ?? true,
- keepUndefined: keepUndefined ?? false,
- onAnchor,
- onTagObj,
- replacer: _replacer,
- schema: this.schema,
- sourceObjects
- };
- const node = createNode2.createNode(value, tag2, ctx);
- if (flow && identity16.isCollection(node))
- node.flow = true;
- setAnchors();
- return node;
- }
- createPair(key2, value, options2 = {}) {
- const k4 = this.createNode(key2, null, options2);
- const v6 = this.createNode(value, null, options2);
- return new Pair.Pair(k4, v6);
- }
- delete(key2) {
- return assertCollection(this.contents) ? this.contents.delete(key2) : false;
- }
- deleteIn(path16) {
- if (Collection.isEmptyPath(path16)) {
- if (this.contents == null)
- return false;
- this.contents = null;
- return true;
- }
- return assertCollection(this.contents) ? this.contents.deleteIn(path16) : false;
- }
- get(key2, keepScalar) {
- return identity16.isCollection(this.contents) ? this.contents.get(key2, keepScalar) : undefined;
- }
- getIn(path16, keepScalar) {
- if (Collection.isEmptyPath(path16))
- return !keepScalar && identity16.isScalar(this.contents) ? this.contents.value : this.contents;
- return identity16.isCollection(this.contents) ? this.contents.getIn(path16, keepScalar) : undefined;
- }
- has(key2) {
- return identity16.isCollection(this.contents) ? this.contents.has(key2) : false;
- }
- hasIn(path16) {
- if (Collection.isEmptyPath(path16))
- return this.contents !== undefined;
- return identity16.isCollection(this.contents) ? this.contents.hasIn(path16) : false;
- }
- set(key2, value) {
- if (this.contents == null) {
- this.contents = Collection.collectionFromPath(this.schema, [key2], value);
- } else if (assertCollection(this.contents)) {
- this.contents.set(key2, value);
- }
- }
- setIn(path16, value) {
- if (Collection.isEmptyPath(path16)) {
- this.contents = value;
- } else if (this.contents == null) {
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path16), value);
- } else if (assertCollection(this.contents)) {
- this.contents.setIn(path16, value);
- }
- }
- setSchema(version6, options2 = {}) {
- if (typeof version6 === "number")
- version6 = String(version6);
- let opt;
- switch (version6) {
- case "1.1":
- if (this.directives)
- this.directives.yaml.version = "1.1";
- else
- this.directives = new directives.Directives({ version: "1.1" });
- opt = { resolveKnownTags: false, schema: "yaml-1.1" };
- break;
- case "1.2":
- case "next":
- if (this.directives)
- this.directives.yaml.version = version6;
- else
- this.directives = new directives.Directives({ version: version6 });
- opt = { resolveKnownTags: true, schema: "core" };
- break;
- case null:
- if (this.directives)
- delete this.directives;
- opt = null;
- break;
- default: {
- const sv = JSON.stringify(version6);
- throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
- }
- }
- if (options2.schema instanceof Object)
- this.schema = options2.schema;
- else if (opt)
- this.schema = new Schema.Schema(Object.assign(opt, options2));
- else
- throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
- }
- toJS({ json: json2, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
- const ctx = {
- anchors: new Map,
- doc: this,
- keep: !json2,
- mapAsMap: mapAsMap === true,
- mapKeyWarned: false,
- maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
- };
- const res = toJS.toJS(this.contents, jsonArg ?? "", ctx);
- if (typeof onAnchor === "function")
- for (const { count: count3, res: res2 } of ctx.anchors.values())
- onAnchor(res2, count3);
- return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
- }
- toJSON(jsonArg, onAnchor) {
- return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
- }
- toString(options2 = {}) {
- if (this.errors.length > 0)
- throw new Error("Document with errors cannot be stringified");
- if ("indent" in options2 && (!Number.isInteger(options2.indent) || Number(options2.indent) <= 0)) {
- const s4 = JSON.stringify(options2.indent);
- throw new Error(`"indent" option must be a positive integer, not ${s4}`);
- }
- return stringifyDocument.stringifyDocument(this, options2);
- }
- }
- function assertCollection(contents) {
- if (identity16.isCollection(contents))
- return true;
- throw new Error("Expected a YAML collection as document contents");
- }
- exports.Document = Document;
-});
-
-// node_modules/yaml/dist/errors.js
-var require_errors6 = __commonJS((exports) => {
- class YAMLError extends Error {
- constructor(name3, pos, code, message) {
- super();
- this.name = name3;
- this.code = code;
- this.message = message;
- this.pos = pos;
- }
- }
-
- class YAMLParseError extends YAMLError {
- constructor(pos, code, message) {
- super("YAMLParseError", pos, code, message);
- }
- }
-
- class YAMLWarning extends YAMLError {
- constructor(pos, code, message) {
- super("YAMLWarning", pos, code, message);
- }
- }
- var prettifyError2 = (src, lc2) => (error46) => {
- if (error46.pos[0] === -1)
- return;
- error46.linePos = error46.pos.map((pos) => lc2.linePos(pos));
- const { line, col } = error46.linePos[0];
- error46.message += ` at line ${line}, column ${col}`;
- let ci = col - 1;
- let lineStr = src.substring(lc2.lineStarts[line - 1], lc2.lineStarts[line]).replace(/[\n\r]+$/, "");
- if (ci >= 60 && lineStr.length > 80) {
- const trimStart = Math.min(ci - 39, lineStr.length - 79);
- lineStr = "\u2026" + lineStr.substring(trimStart);
- ci -= trimStart - 1;
- }
- if (lineStr.length > 80)
- lineStr = lineStr.substring(0, 79) + "\u2026";
- if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
- let prev = src.substring(lc2.lineStarts[line - 2], lc2.lineStarts[line - 1]);
- if (prev.length > 80)
- prev = prev.substring(0, 79) + `\u2026
-`;
- lineStr = prev + lineStr;
- }
- if (/[^ ]/.test(lineStr)) {
- let count3 = 1;
- const end = error46.linePos[1];
- if (end?.line === line && end.col > col) {
- count3 = Math.max(1, Math.min(end.col - col, 80 - ci));
- }
- const pointer = " ".repeat(ci) + "^".repeat(count3);
- error46.message += `:
-
-${lineStr}
-${pointer}
-`;
- }
- };
- exports.YAMLError = YAMLError;
- exports.YAMLParseError = YAMLParseError;
- exports.YAMLWarning = YAMLWarning;
- exports.prettifyError = prettifyError2;
-});
-
-// node_modules/yaml/dist/compose/resolve-props.js
-var require_resolve_props = __commonJS((exports) => {
- function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {
- let spaceBefore = false;
- let atNewline = startOnNewline;
- let hasSpace = startOnNewline;
- let comment = "";
- let commentSep = "";
- let hasNewline = false;
- let reqSpace = false;
- let tab = null;
- let anchor = null;
- let tag2 = null;
- let newlineAfterProp = null;
- let comma = null;
- let found = null;
- let start = null;
- for (const token of tokens) {
- if (reqSpace) {
- if (token.type !== "space" && token.type !== "newline" && token.type !== "comma")
- onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
- reqSpace = false;
- }
- if (tab) {
- if (atNewline && token.type !== "comment" && token.type !== "newline") {
- onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
- }
- tab = null;
- }
- switch (token.type) {
- case "space":
- if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes("\t")) {
- tab = token;
- }
- hasSpace = true;
- break;
- case "comment": {
- if (!hasSpace)
- onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
- const cb = token.source.substring(1) || " ";
- if (!comment)
- comment = cb;
- else
- comment += commentSep + cb;
- commentSep = "";
- atNewline = false;
- break;
- }
- case "newline":
- if (atNewline) {
- if (comment)
- comment += token.source;
- else if (!found || indicator !== "seq-item-ind")
- spaceBefore = true;
- } else
- commentSep += token.source;
- atNewline = true;
- hasNewline = true;
- if (anchor || tag2)
- newlineAfterProp = token;
- hasSpace = true;
- break;
- case "anchor":
- if (anchor)
- onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
- if (token.source.endsWith(":"))
- onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
- anchor = token;
- start ?? (start = token.offset);
- atNewline = false;
- hasSpace = false;
- reqSpace = true;
- break;
- case "tag": {
- if (tag2)
- onError(token, "MULTIPLE_TAGS", "A node can have at most one tag");
- tag2 = token;
- start ?? (start = token.offset);
- atNewline = false;
- hasSpace = false;
- reqSpace = true;
- break;
- }
- case indicator:
- if (anchor || tag2)
- onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`);
- if (found)
- onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`);
- found = token;
- atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
- hasSpace = false;
- break;
- case "comma":
- if (flow) {
- if (comma)
- onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`);
- comma = token;
- atNewline = false;
- hasSpace = false;
- break;
- }
- default:
- onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`);
- atNewline = false;
- hasSpace = false;
- }
- }
- const last2 = tokens[tokens.length - 1];
- const end = last2 ? last2.offset + last2.source.length : offset;
- if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) {
- onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
- }
- if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq"))
- onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
- return {
- comma,
- found,
- spaceBefore,
- comment,
- hasNewline,
- anchor,
- tag: tag2,
- newlineAfterProp,
- end,
- start: start ?? end
- };
- }
- exports.resolveProps = resolveProps;
-});
-
-// node_modules/yaml/dist/compose/util-contains-newline.js
-var require_util_contains_newline = __commonJS((exports) => {
- function containsNewline(key2) {
- if (!key2)
- return null;
- switch (key2.type) {
- case "alias":
- case "scalar":
- case "double-quoted-scalar":
- case "single-quoted-scalar":
- if (key2.source.includes(`
-`))
- return true;
- if (key2.end) {
- for (const st of key2.end)
- if (st.type === "newline")
- return true;
- }
- return false;
- case "flow-collection":
- for (const it of key2.items) {
- for (const st of it.start)
- if (st.type === "newline")
- return true;
- if (it.sep) {
- for (const st of it.sep)
- if (st.type === "newline")
- return true;
- }
- if (containsNewline(it.key) || containsNewline(it.value))
- return true;
- }
- return false;
- default:
- return true;
- }
- }
- exports.containsNewline = containsNewline;
-});
-
-// node_modules/yaml/dist/compose/util-flow-indent-check.js
-var require_util_flow_indent_check = __commonJS((exports) => {
- var utilContainsNewline = require_util_contains_newline();
- function flowIndentCheck(indent, fc, onError) {
- if (fc?.type === "flow-collection") {
- const end = fc.end[0];
- if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) {
- const msg = "Flow end indicator should be more indented than parent";
- onError(end, "BAD_INDENT", msg, true);
- }
- }
- }
- exports.flowIndentCheck = flowIndentCheck;
-});
-
-// node_modules/yaml/dist/compose/util-map-includes.js
-var require_util_map_includes = __commonJS((exports) => {
- var identity16 = require_identity();
- function mapIncludes(ctx, items, search) {
- const { uniqueKeys } = ctx.options;
- if (uniqueKeys === false)
- return false;
- const isEqual2 = typeof uniqueKeys === "function" ? uniqueKeys : (a5, b5) => a5 === b5 || identity16.isScalar(a5) && identity16.isScalar(b5) && a5.value === b5.value;
- return items.some((pair) => isEqual2(pair.key, search));
- }
- exports.mapIncludes = mapIncludes;
-});
-
-// node_modules/yaml/dist/compose/resolve-block-map.js
-var require_resolve_block_map = __commonJS((exports) => {
- var Pair = require_Pair();
- var YAMLMap = require_YAMLMap();
- var resolveProps = require_resolve_props();
- var utilContainsNewline = require_util_contains_newline();
- var utilFlowIndentCheck = require_util_flow_indent_check();
- var utilMapIncludes = require_util_map_includes();
- var startColMsg = "All mapping items must start at the same column";
- function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag2) {
- const NodeClass = tag2?.nodeClass ?? YAMLMap.YAMLMap;
- const map7 = new NodeClass(ctx.schema);
- if (ctx.atRoot)
- ctx.atRoot = false;
- let offset = bm.offset;
- let commentEnd = null;
- for (const collItem of bm.items) {
- const { start, key: key2, sep: sep12, value } = collItem;
- const keyProps = resolveProps.resolveProps(start, {
- indicator: "explicit-key-ind",
- next: key2 ?? sep12?.[0],
- offset,
- onError,
- parentIndent: bm.indent,
- startOnNewline: true
- });
- const implicitKey = !keyProps.found;
- if (implicitKey) {
- if (key2) {
- if (key2.type === "block-seq")
- onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key");
- else if ("indent" in key2 && key2.indent !== bm.indent)
- onError(offset, "BAD_INDENT", startColMsg);
- }
- if (!keyProps.anchor && !keyProps.tag && !sep12) {
- commentEnd = keyProps.end;
- if (keyProps.comment) {
- if (map7.comment)
- map7.comment += `
-` + keyProps.comment;
- else
- map7.comment = keyProps.comment;
- }
- continue;
- }
- if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key2)) {
- onError(key2 ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line");
- }
- } else if (keyProps.found?.indent !== bm.indent) {
- onError(offset, "BAD_INDENT", startColMsg);
- }
- ctx.atKey = true;
- const keyStart = keyProps.end;
- const keyNode = key2 ? composeNode(ctx, key2, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
- if (ctx.schema.compat)
- utilFlowIndentCheck.flowIndentCheck(bm.indent, key2, onError);
- ctx.atKey = false;
- if (utilMapIncludes.mapIncludes(ctx, map7.items, keyNode))
- onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
- const valueProps = resolveProps.resolveProps(sep12 ?? [], {
- indicator: "map-value-ind",
- next: value,
- offset: keyNode.range[2],
- onError,
- parentIndent: bm.indent,
- startOnNewline: !key2 || key2.type === "block-scalar"
- });
- offset = valueProps.end;
- if (valueProps.found) {
- if (implicitKey) {
- if (value?.type === "block-map" && !valueProps.hasNewline)
- onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings");
- if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
- onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
- }
- const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep12, null, valueProps, onError);
- if (ctx.schema.compat)
- utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
- offset = valueNode.range[2];
- const pair = new Pair.Pair(keyNode, valueNode);
- if (ctx.options.keepSourceTokens)
- pair.srcToken = collItem;
- map7.items.push(pair);
- } else {
- if (implicitKey)
- onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
- if (valueProps.comment) {
- if (keyNode.comment)
- keyNode.comment += `
-` + valueProps.comment;
- else
- keyNode.comment = valueProps.comment;
- }
- const pair = new Pair.Pair(keyNode);
- if (ctx.options.keepSourceTokens)
- pair.srcToken = collItem;
- map7.items.push(pair);
- }
- }
- if (commentEnd && commentEnd < offset)
- onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
- map7.range = [bm.offset, offset, commentEnd ?? offset];
- return map7;
- }
- exports.resolveBlockMap = resolveBlockMap;
-});
-
-// node_modules/yaml/dist/compose/resolve-block-seq.js
-var require_resolve_block_seq = __commonJS((exports) => {
- var YAMLSeq = require_YAMLSeq();
- var resolveProps = require_resolve_props();
- var utilFlowIndentCheck = require_util_flow_indent_check();
- function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag2) {
- const NodeClass = tag2?.nodeClass ?? YAMLSeq.YAMLSeq;
- const seq = new NodeClass(ctx.schema);
- if (ctx.atRoot)
- ctx.atRoot = false;
- if (ctx.atKey)
- ctx.atKey = false;
- let offset = bs.offset;
- let commentEnd = null;
- for (const { start, value } of bs.items) {
- const props = resolveProps.resolveProps(start, {
- indicator: "seq-item-ind",
- next: value,
- offset,
- onError,
- parentIndent: bs.indent,
- startOnNewline: true
- });
- if (!props.found) {
- if (props.anchor || props.tag || value) {
- if (value?.type === "block-seq")
- onError(props.end, "BAD_INDENT", "All sequence items must start at the same column");
- else
- onError(offset, "MISSING_CHAR", "Sequence item without - indicator");
- } else {
- commentEnd = props.end;
- if (props.comment)
- seq.comment = props.comment;
- continue;
- }
- }
- const node = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError);
- if (ctx.schema.compat)
- utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);
- offset = node.range[2];
- seq.items.push(node);
- }
- seq.range = [bs.offset, offset, commentEnd ?? offset];
- return seq;
- }
- exports.resolveBlockSeq = resolveBlockSeq;
-});
-
-// node_modules/yaml/dist/compose/resolve-end.js
-var require_resolve_end = __commonJS((exports) => {
- function resolveEnd(end, offset, reqSpace, onError) {
- let comment = "";
- if (end) {
- let hasSpace = false;
- let sep12 = "";
- for (const token of end) {
- const { source, type } = token;
- switch (type) {
- case "space":
- hasSpace = true;
- break;
- case "comment": {
- if (reqSpace && !hasSpace)
- onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
- const cb = source.substring(1) || " ";
- if (!comment)
- comment = cb;
- else
- comment += sep12 + cb;
- sep12 = "";
- break;
- }
- case "newline":
- if (comment)
- sep12 += source;
- hasSpace = true;
- break;
- default:
- onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`);
- }
- offset += source.length;
- }
- }
- return { comment, offset };
- }
- exports.resolveEnd = resolveEnd;
-});
-
-// node_modules/yaml/dist/compose/resolve-flow-collection.js
-var require_resolve_flow_collection = __commonJS((exports) => {
- var identity16 = require_identity();
- var Pair = require_Pair();
- var YAMLMap = require_YAMLMap();
- var YAMLSeq = require_YAMLSeq();
- var resolveEnd = require_resolve_end();
- var resolveProps = require_resolve_props();
- var utilContainsNewline = require_util_contains_newline();
- var utilMapIncludes = require_util_map_includes();
- var blockMsg = "Block collections are not allowed within flow collections";
- var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
- function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag2) {
- const isMap2 = fc.start.source === "{";
- const fcName = isMap2 ? "flow map" : "flow sequence";
- const NodeClass = tag2?.nodeClass ?? (isMap2 ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
- const coll = new NodeClass(ctx.schema);
- coll.flow = true;
- const atRoot = ctx.atRoot;
- if (atRoot)
- ctx.atRoot = false;
- if (ctx.atKey)
- ctx.atKey = false;
- let offset = fc.offset + fc.start.source.length;
- for (let i6 = 0;i6 < fc.items.length; ++i6) {
- const collItem = fc.items[i6];
- const { start, key: key2, sep: sep12, value } = collItem;
- const props = resolveProps.resolveProps(start, {
- flow: fcName,
- indicator: "explicit-key-ind",
- next: key2 ?? sep12?.[0],
- offset,
- onError,
- parentIndent: fc.indent,
- startOnNewline: false
- });
- if (!props.found) {
- if (!props.anchor && !props.tag && !sep12 && !value) {
- if (i6 === 0 && props.comma)
- onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
- else if (i6 < fc.items.length - 1)
- onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`);
- if (props.comment) {
- if (coll.comment)
- coll.comment += `
-` + props.comment;
- else
- coll.comment = props.comment;
- }
- offset = props.end;
- continue;
- }
- if (!isMap2 && ctx.options.strict && utilContainsNewline.containsNewline(key2))
- onError(key2, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
- }
- if (i6 === 0) {
- if (props.comma)
- onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
- } else {
- if (!props.comma)
- onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
- if (props.comment) {
- let prevItemComment = "";
- loop:
- for (const st of start) {
- switch (st.type) {
- case "comma":
- case "space":
- break;
- case "comment":
- prevItemComment = st.source.substring(1);
- break loop;
- default:
- break loop;
- }
- }
- if (prevItemComment) {
- let prev = coll.items[coll.items.length - 1];
- if (identity16.isPair(prev))
- prev = prev.value ?? prev.key;
- if (prev.comment)
- prev.comment += `
-` + prevItemComment;
- else
- prev.comment = prevItemComment;
- props.comment = props.comment.substring(prevItemComment.length + 1);
- }
- }
- }
- if (!isMap2 && !sep12 && !props.found) {
- const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep12, null, props, onError);
- coll.items.push(valueNode);
- offset = valueNode.range[2];
- if (isBlock(value))
- onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
- } else {
- ctx.atKey = true;
- const keyStart = props.end;
- const keyNode = key2 ? composeNode(ctx, key2, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError);
- if (isBlock(key2))
- onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
- ctx.atKey = false;
- const valueProps = resolveProps.resolveProps(sep12 ?? [], {
- flow: fcName,
- indicator: "map-value-ind",
- next: value,
- offset: keyNode.range[2],
- onError,
- parentIndent: fc.indent,
- startOnNewline: false
- });
- if (valueProps.found) {
- if (!isMap2 && !props.found && ctx.options.strict) {
- if (sep12)
- for (const st of sep12) {
- if (st === valueProps.found)
- break;
- if (st.type === "newline") {
- onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
- break;
- }
- }
- if (props.start < valueProps.found.offset - 1024)
- onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
- }
- } else if (value) {
- if ("source" in value && value.source?.[0] === ":")
- onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`);
- else
- onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
- }
- const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep12, null, valueProps, onError) : null;
- if (valueNode) {
- if (isBlock(value))
- onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
- } else if (valueProps.comment) {
- if (keyNode.comment)
- keyNode.comment += `
-` + valueProps.comment;
- else
- keyNode.comment = valueProps.comment;
- }
- const pair = new Pair.Pair(keyNode, valueNode);
- if (ctx.options.keepSourceTokens)
- pair.srcToken = collItem;
- if (isMap2) {
- const map7 = coll;
- if (utilMapIncludes.mapIncludes(ctx, map7.items, keyNode))
- onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
- map7.items.push(pair);
- } else {
- const map7 = new YAMLMap.YAMLMap(ctx.schema);
- map7.flow = true;
- map7.items.push(pair);
- const endRange = (valueNode ?? keyNode).range;
- map7.range = [keyNode.range[0], endRange[1], endRange[2]];
- coll.items.push(map7);
- }
- offset = valueNode ? valueNode.range[2] : valueProps.end;
- }
- }
- const expectedEnd = isMap2 ? "}" : "]";
- const [ce, ...ee] = fc.end;
- let cePos = offset;
- if (ce?.source === expectedEnd)
- cePos = ce.offset + ce.source.length;
- else {
- const name3 = fcName[0].toUpperCase() + fcName.substring(1);
- const msg = atRoot ? `${name3} must end with a ${expectedEnd}` : `${name3} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
- onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg);
- if (ce && ce.source.length !== 1)
- ee.unshift(ce);
- }
- if (ee.length > 0) {
- const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);
- if (end.comment) {
- if (coll.comment)
- coll.comment += `
-` + end.comment;
- else
- coll.comment = end.comment;
- }
- coll.range = [fc.offset, cePos, end.offset];
- } else {
- coll.range = [fc.offset, cePos, cePos];
- }
- return coll;
- }
- exports.resolveFlowCollection = resolveFlowCollection;
-});
-
-// node_modules/yaml/dist/compose/compose-collection.js
-var require_compose_collection = __commonJS((exports) => {
- var identity16 = require_identity();
- var Scalar = require_Scalar();
- var YAMLMap = require_YAMLMap();
- var YAMLSeq = require_YAMLSeq();
- var resolveBlockMap = require_resolve_block_map();
- var resolveBlockSeq = require_resolve_block_seq();
- var resolveFlowCollection = require_resolve_flow_collection();
- function resolveCollection(CN, ctx, token, onError, tagName, tag2) {
- const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag2) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag2) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag2);
- const Coll = coll.constructor;
- if (tagName === "!" || tagName === Coll.tagName) {
- coll.tag = Coll.tagName;
- return coll;
- }
- if (tagName)
- coll.tag = tagName;
- return coll;
- }
- function composeCollection(CN, ctx, token, props, onError) {
- const tagToken = props.tag;
- const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg));
- if (token.type === "block-seq") {
- const { anchor, newlineAfterProp: nl } = props;
- const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken;
- if (lastProp && (!nl || nl.offset < lastProp.offset)) {
- const message = "Missing newline after block sequence props";
- onError(lastProp, "MISSING_CHAR", message);
- }
- }
- const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
- if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") {
- return resolveCollection(CN, ctx, token, onError, tagName);
- }
- let tag2 = ctx.schema.tags.find((t4) => t4.tag === tagName && t4.collection === expType);
- if (!tag2) {
- const kt = ctx.schema.knownTags[tagName];
- if (kt?.collection === expType) {
- ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
- tag2 = kt;
- } else {
- if (kt) {
- onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true);
- } else {
- onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
- }
- return resolveCollection(CN, ctx, token, onError, tagName);
- }
- }
- const coll = resolveCollection(CN, ctx, token, onError, tagName, tag2);
- const res = tag2.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll;
- const node = identity16.isNode(res) ? res : new Scalar.Scalar(res);
- node.range = coll.range;
- node.tag = tagName;
- if (tag2?.format)
- node.format = tag2.format;
- return node;
- }
- exports.composeCollection = composeCollection;
-});
-
-// node_modules/yaml/dist/compose/resolve-block-scalar.js
-var require_resolve_block_scalar = __commonJS((exports) => {
- var Scalar = require_Scalar();
- function resolveBlockScalar(ctx, scalar, onError) {
- const start = scalar.offset;
- const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
- if (!header)
- return { value: "", type: null, comment: "", range: [start, start, start] };
- const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;
- const lines2 = scalar.source ? splitLines(scalar.source) : [];
- let chompStart = lines2.length;
- for (let i6 = lines2.length - 1;i6 >= 0; --i6) {
- const content = lines2[i6][1];
- if (content === "" || content === "\r")
- chompStart = i6;
- else
- break;
- }
- if (chompStart === 0) {
- const value2 = header.chomp === "+" && lines2.length > 0 ? `
-`.repeat(Math.max(1, lines2.length - 1)) : "";
- let end2 = start + header.length;
- if (scalar.source)
- end2 += scalar.source.length;
- return { value: value2, type, comment: header.comment, range: [start, end2, end2] };
- }
- let trimIndent = scalar.indent + header.indent;
- let offset = scalar.offset + header.length;
- let contentStart = 0;
- for (let i6 = 0;i6 < chompStart; ++i6) {
- const [indent, content] = lines2[i6];
- if (content === "" || content === "\r") {
- if (header.indent === 0 && indent.length > trimIndent)
- trimIndent = indent.length;
- } else {
- if (indent.length < trimIndent) {
- const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
- onError(offset + indent.length, "MISSING_CHAR", message);
- }
- if (header.indent === 0)
- trimIndent = indent.length;
- contentStart = i6;
- if (trimIndent === 0 && !ctx.atRoot) {
- const message = "Block scalar values in collections must be indented";
- onError(offset, "BAD_INDENT", message);
- }
- break;
- }
- offset += indent.length + content.length + 1;
- }
- for (let i6 = lines2.length - 1;i6 >= chompStart; --i6) {
- if (lines2[i6][0].length > trimIndent)
- chompStart = i6 + 1;
- }
- let value = "";
- let sep12 = "";
- let prevMoreIndented = false;
- for (let i6 = 0;i6 < contentStart; ++i6)
- value += lines2[i6][0].slice(trimIndent) + `
-`;
- for (let i6 = contentStart;i6 < chompStart; ++i6) {
- let [indent, content] = lines2[i6];
- offset += indent.length + content.length + 1;
- const crlf = content[content.length - 1] === "\r";
- if (crlf)
- content = content.slice(0, -1);
- if (content && indent.length < trimIndent) {
- const src = header.indent ? "explicit indentation indicator" : "first line";
- const message = `Block scalar lines must not be less indented than their ${src}`;
- onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
- indent = "";
- }
- if (type === Scalar.Scalar.BLOCK_LITERAL) {
- value += sep12 + indent.slice(trimIndent) + content;
- sep12 = `
-`;
- } else if (indent.length > trimIndent || content[0] === "\t") {
- if (sep12 === " ")
- sep12 = `
-`;
- else if (!prevMoreIndented && sep12 === `
-`)
- sep12 = `
-
-`;
- value += sep12 + indent.slice(trimIndent) + content;
- sep12 = `
-`;
- prevMoreIndented = true;
- } else if (content === "") {
- if (sep12 === `
-`)
- value += `
-`;
- else
- sep12 = `
-`;
- } else {
- value += sep12 + content;
- sep12 = " ";
- prevMoreIndented = false;
- }
- }
- switch (header.chomp) {
- case "-":
- break;
- case "+":
- for (let i6 = chompStart;i6 < lines2.length; ++i6)
- value += `
-` + lines2[i6][0].slice(trimIndent);
- if (value[value.length - 1] !== `
-`)
- value += `
-`;
- break;
- default:
- value += `
-`;
- }
- const end = start + header.length + scalar.source.length;
- return { value, type, comment: header.comment, range: [start, end, end] };
- }
- function parseBlockScalarHeader({ offset, props }, strict, onError) {
- if (props[0].type !== "block-scalar-header") {
- onError(props[0], "IMPOSSIBLE", "Block scalar header not found");
- return null;
- }
- const { source } = props[0];
- const mode = source[0];
- let indent = 0;
- let chomp = "";
- let error46 = -1;
- for (let i6 = 1;i6 < source.length; ++i6) {
- const ch2 = source[i6];
- if (!chomp && (ch2 === "-" || ch2 === "+"))
- chomp = ch2;
- else {
- const n5 = Number(ch2);
- if (!indent && n5)
- indent = n5;
- else if (error46 === -1)
- error46 = offset + i6;
- }
- }
- if (error46 !== -1)
- onError(error46, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`);
- let hasSpace = false;
- let comment = "";
- let length = source.length;
- for (let i6 = 1;i6 < props.length; ++i6) {
- const token = props[i6];
- switch (token.type) {
- case "space":
- hasSpace = true;
- case "newline":
- length += token.source.length;
- break;
- case "comment":
- if (strict && !hasSpace) {
- const message = "Comments must be separated from other tokens by white space characters";
- onError(token, "MISSING_CHAR", message);
- }
- length += token.source.length;
- comment = token.source.substring(1);
- break;
- case "error":
- onError(token, "UNEXPECTED_TOKEN", token.message);
- length += token.source.length;
- break;
- default: {
- const message = `Unexpected token in block scalar header: ${token.type}`;
- onError(token, "UNEXPECTED_TOKEN", message);
- const ts = token.source;
- if (ts && typeof ts === "string")
- length += ts.length;
- }
- }
- }
- return { mode, indent, chomp, comment, length };
- }
- function splitLines(source) {
- const split2 = source.split(/\n( *)/);
- const first = split2[0];
- const m4 = first.match(/^( *)/);
- const line0 = m4?.[1] ? [m4[1], first.slice(m4[1].length)] : ["", first];
- const lines2 = [line0];
- for (let i6 = 1;i6 < split2.length; i6 += 2)
- lines2.push([split2[i6], split2[i6 + 1]]);
- return lines2;
- }
- exports.resolveBlockScalar = resolveBlockScalar;
-});
-
-// node_modules/yaml/dist/compose/resolve-flow-scalar.js
-var require_resolve_flow_scalar = __commonJS((exports) => {
- var Scalar = require_Scalar();
- var resolveEnd = require_resolve_end();
- function resolveFlowScalar(scalar, strict, onError) {
- const { offset, type, source, end } = scalar;
- let _type;
- let value;
- const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
- switch (type) {
- case "scalar":
- _type = Scalar.Scalar.PLAIN;
- value = plainValue(source, _onError);
- break;
- case "single-quoted-scalar":
- _type = Scalar.Scalar.QUOTE_SINGLE;
- value = singleQuotedValue(source, _onError);
- break;
- case "double-quoted-scalar":
- _type = Scalar.Scalar.QUOTE_DOUBLE;
- value = doubleQuotedValue(source, _onError);
- break;
- default:
- onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
- return {
- value: "",
- type: null,
- comment: "",
- range: [offset, offset + source.length, offset + source.length]
- };
- }
- const valueEnd = offset + source.length;
- const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);
- return {
- value,
- type: _type,
- comment: re.comment,
- range: [offset, valueEnd, re.offset]
- };
- }
- function plainValue(source, onError) {
- let badChar = "";
- switch (source[0]) {
- case "\t":
- badChar = "a tab character";
- break;
- case ",":
- badChar = "flow indicator character ,";
- break;
- case "%":
- badChar = "directive indicator character %";
- break;
- case "|":
- case ">": {
- badChar = `block scalar indicator ${source[0]}`;
- break;
- }
- case "@":
- case "`": {
- badChar = `reserved character ${source[0]}`;
- break;
- }
- }
- if (badChar)
- onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
- return foldLines(source);
- }
- function singleQuotedValue(source, onError) {
- if (source[source.length - 1] !== "'" || source.length === 1)
- onError(source.length, "MISSING_CHAR", "Missing closing 'quote");
- return foldLines(source.slice(1, -1)).replace(/''/g, "'");
- }
- function foldLines(source) {
- let first, line;
- try {
- first = new RegExp(`(.*?)(? wsStart ? source.slice(wsStart, i6 + 1) : ch2;
- } else {
- res += ch2;
- }
- }
- if (source[source.length - 1] !== '"' || source.length === 1)
- onError(source.length, "MISSING_CHAR", 'Missing closing "quote');
- return res;
- }
- function foldNewline(source, offset) {
- let fold = "";
- let ch2 = source[offset + 1];
- while (ch2 === " " || ch2 === "\t" || ch2 === `
-` || ch2 === "\r") {
- if (ch2 === "\r" && source[offset + 2] !== `
-`)
- break;
- if (ch2 === `
-`)
- fold += `
-`;
- offset += 1;
- ch2 = source[offset + 1];
- }
- if (!fold)
- fold = " ";
- return { fold, offset };
- }
- var escapeCodes = {
- "0": "\x00",
- a: "\x07",
- b: "\b",
- e: "\x1B",
- f: "\f",
- n: `
-`,
- r: "\r",
- t: "\t",
- v: "\v",
- N: "\x85",
- _: "\xA0",
- L: "\u2028",
- P: "\u2029",
- " ": " ",
- '"': '"',
- "/": "/",
- "\\": "\\",
- "\t": "\t"
- };
- function parseCharCode(source, offset, length, onError) {
- const cc = source.substr(offset, length);
- const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
- const code = ok ? parseInt(cc, 16) : NaN;
- if (isNaN(code)) {
- const raw = source.substr(offset - 2, length + 2);
- onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
- return raw;
- }
- return String.fromCodePoint(code);
- }
- exports.resolveFlowScalar = resolveFlowScalar;
-});
-
-// node_modules/yaml/dist/compose/compose-scalar.js
-var require_compose_scalar = __commonJS((exports) => {
- var identity16 = require_identity();
- var Scalar = require_Scalar();
- var resolveBlockScalar = require_resolve_block_scalar();
- var resolveFlowScalar = require_resolve_flow_scalar();
- function composeScalar(ctx, token, tagToken, onError) {
- const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);
- const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null;
- let tag2;
- if (ctx.options.stringKeys && ctx.atKey) {
- tag2 = ctx.schema[identity16.SCALAR];
- } else if (tagName)
- tag2 = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);
- else if (token.type === "scalar")
- tag2 = findScalarTagByTest(ctx, value, token, onError);
- else
- tag2 = ctx.schema[identity16.SCALAR];
- let scalar;
- try {
- const res = tag2.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options);
- scalar = identity16.isScalar(res) ? res : new Scalar.Scalar(res);
- } catch (error46) {
- const msg = error46 instanceof Error ? error46.message : String(error46);
- onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg);
- scalar = new Scalar.Scalar(value);
- }
- scalar.range = range;
- scalar.source = value;
- if (type)
- scalar.type = type;
- if (tagName)
- scalar.tag = tagName;
- if (tag2.format)
- scalar.format = tag2.format;
- if (comment)
- scalar.comment = comment;
- return scalar;
- }
- function findScalarTagByName(schema5, value, tagName, tagToken, onError) {
- if (tagName === "!")
- return schema5[identity16.SCALAR];
- const matchWithTest = [];
- for (const tag2 of schema5.tags) {
- if (!tag2.collection && tag2.tag === tagName) {
- if (tag2.default && tag2.test)
- matchWithTest.push(tag2);
- else
- return tag2;
- }
- }
- for (const tag2 of matchWithTest)
- if (tag2.test?.test(value))
- return tag2;
- const kt = schema5.knownTags[tagName];
- if (kt && !kt.collection) {
- schema5.tags.push(Object.assign({}, kt, { default: false, test: undefined }));
- return kt;
- }
- onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
- return schema5[identity16.SCALAR];
- }
- function findScalarTagByTest({ atKey, directives, schema: schema5 }, value, token, onError) {
- const tag2 = schema5.tags.find((tag3) => (tag3.default === true || atKey && tag3.default === "key") && tag3.test?.test(value)) || schema5[identity16.SCALAR];
- if (schema5.compat) {
- const compat2 = schema5.compat.find((tag3) => tag3.default && tag3.test?.test(value)) ?? schema5[identity16.SCALAR];
- if (tag2.tag !== compat2.tag) {
- const ts = directives.tagString(tag2.tag);
- const cs = directives.tagString(compat2.tag);
- const msg = `Value may be parsed as either ${ts} or ${cs}`;
- onError(token, "TAG_RESOLVE_FAILED", msg, true);
- }
- }
- return tag2;
- }
- exports.composeScalar = composeScalar;
-});
-
-// node_modules/yaml/dist/compose/util-empty-scalar-position.js
-var require_util_empty_scalar_position = __commonJS((exports) => {
- function emptyScalarPosition(offset, before, pos) {
- if (before) {
- pos ?? (pos = before.length);
- for (let i6 = pos - 1;i6 >= 0; --i6) {
- let st = before[i6];
- switch (st.type) {
- case "space":
- case "comment":
- case "newline":
- offset -= st.source.length;
- continue;
- }
- st = before[++i6];
- while (st?.type === "space") {
- offset += st.source.length;
- st = before[++i6];
- }
- break;
- }
- }
- return offset;
- }
- exports.emptyScalarPosition = emptyScalarPosition;
-});
-
-// node_modules/yaml/dist/compose/compose-node.js
-var require_compose_node = __commonJS((exports) => {
- var Alias = require_Alias();
- var identity16 = require_identity();
- var composeCollection = require_compose_collection();
- var composeScalar = require_compose_scalar();
- var resolveEnd = require_resolve_end();
- var utilEmptyScalarPosition = require_util_empty_scalar_position();
- var CN = { composeNode, composeEmptyNode };
- function composeNode(ctx, token, props, onError) {
- const atKey = ctx.atKey;
- const { spaceBefore, comment, anchor, tag: tag2 } = props;
- let node;
- let isSrcToken = true;
- switch (token.type) {
- case "alias":
- node = composeAlias(ctx, token, onError);
- if (anchor || tag2)
- onError(token, "ALIAS_PROPS", "An alias node must not specify any properties");
- break;
- case "scalar":
- case "single-quoted-scalar":
- case "double-quoted-scalar":
- case "block-scalar":
- node = composeScalar.composeScalar(ctx, token, tag2, onError);
- if (anchor)
- node.anchor = anchor.source.substring(1);
- break;
- case "block-map":
- case "block-seq":
- case "flow-collection":
- try {
- node = composeCollection.composeCollection(CN, ctx, token, props, onError);
- if (anchor)
- node.anchor = anchor.source.substring(1);
- } catch (error46) {
- const message = error46 instanceof Error ? error46.message : String(error46);
- onError(token, "RESOURCE_EXHAUSTION", message);
- }
- break;
- default: {
- const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
- onError(token, "UNEXPECTED_TOKEN", message);
- isSrcToken = false;
- }
- }
- node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));
- if (anchor && node.anchor === "")
- onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
- if (atKey && ctx.options.stringKeys && (!identity16.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) {
- const msg = "With stringKeys, all keys must be strings";
- onError(tag2 ?? token, "NON_STRING_KEY", msg);
- }
- if (spaceBefore)
- node.spaceBefore = true;
- if (comment) {
- if (token.type === "scalar" && token.source === "")
- node.comment = comment;
- else
- node.commentBefore = comment;
- }
- if (ctx.options.keepSourceTokens && isSrcToken)
- node.srcToken = token;
- return node;
- }
- function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag: tag2, end }, onError) {
- const token = {
- type: "scalar",
- offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),
- indent: -1,
- source: ""
- };
- const node = composeScalar.composeScalar(ctx, token, tag2, onError);
- if (anchor) {
- node.anchor = anchor.source.substring(1);
- if (node.anchor === "")
- onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
- }
- if (spaceBefore)
- node.spaceBefore = true;
- if (comment) {
- node.comment = comment;
- node.range[2] = end;
- }
- return node;
- }
- function composeAlias({ options: options2 }, { offset, source, end }, onError) {
- const alias = new Alias.Alias(source.substring(1));
- if (alias.source === "")
- onError(offset, "BAD_ALIAS", "Alias cannot be an empty string");
- if (alias.source.endsWith(":"))
- onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
- const valueEnd = offset + source.length;
- const re = resolveEnd.resolveEnd(end, valueEnd, options2.strict, onError);
- alias.range = [offset, valueEnd, re.offset];
- if (re.comment)
- alias.comment = re.comment;
- return alias;
- }
- exports.composeEmptyNode = composeEmptyNode;
- exports.composeNode = composeNode;
-});
-
-// node_modules/yaml/dist/compose/compose-doc.js
-var require_compose_doc = __commonJS((exports) => {
- var Document = require_Document();
- var composeNode = require_compose_node();
- var resolveEnd = require_resolve_end();
- var resolveProps = require_resolve_props();
- function composeDoc(options2, directives, { offset, start, value, end }, onError) {
- const opts = Object.assign({ _directives: directives }, options2);
- const doc2 = new Document.Document(undefined, opts);
- const ctx = {
- atKey: false,
- atRoot: true,
- directives: doc2.directives,
- options: doc2.options,
- schema: doc2.schema
- };
- const props = resolveProps.resolveProps(start, {
- indicator: "doc-start",
- next: value ?? end?.[0],
- offset,
- onError,
- parentIndent: 0,
- startOnNewline: true
- });
- if (props.found) {
- doc2.directives.docStart = true;
- if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline)
- onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
- }
- doc2.contents = value ? composeNode.composeNode(ctx, value, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);
- const contentEnd = doc2.contents.range[2];
- const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);
- if (re.comment)
- doc2.comment = re.comment;
- doc2.range = [offset, contentEnd, re.offset];
- return doc2;
- }
- exports.composeDoc = composeDoc;
-});
-
-// node_modules/yaml/dist/compose/composer.js
-var require_composer = __commonJS((exports) => {
- var node_process = __require("process");
- var directives = require_directives();
- var Document = require_Document();
- var errors8 = require_errors6();
- var identity16 = require_identity();
- var composeDoc = require_compose_doc();
- var resolveEnd = require_resolve_end();
- function getErrorPos(src) {
- if (typeof src === "number")
- return [src, src + 1];
- if (Array.isArray(src))
- return src.length === 2 ? src : [src[0], src[1]];
- const { offset, source } = src;
- return [offset, offset + (typeof source === "string" ? source.length : 1)];
- }
- function parsePrelude(prelude) {
- let comment = "";
- let atComment = false;
- let afterEmptyLine = false;
- for (let i6 = 0;i6 < prelude.length; ++i6) {
- const source = prelude[i6];
- switch (source[0]) {
- case "#":
- comment += (comment === "" ? "" : afterEmptyLine ? `
-
-` : `
-`) + (source.substring(1) || " ");
- atComment = true;
- afterEmptyLine = false;
- break;
- case "%":
- if (prelude[i6 + 1]?.[0] !== "#")
- i6 += 1;
- atComment = false;
- break;
- default:
- if (!atComment)
- afterEmptyLine = true;
- atComment = false;
- }
- }
- return { comment, afterEmptyLine };
- }
-
- class Composer {
- constructor(options2 = {}) {
- this.doc = null;
- this.atDirectives = false;
- this.prelude = [];
- this.errors = [];
- this.warnings = [];
- this.onError = (source, code, message, warning) => {
- const pos = getErrorPos(source);
- if (warning)
- this.warnings.push(new errors8.YAMLWarning(pos, code, message));
- else
- this.errors.push(new errors8.YAMLParseError(pos, code, message));
- };
- this.directives = new directives.Directives({ version: options2.version || "1.2" });
- this.options = options2;
- }
- decorate(doc2, afterDoc) {
- const { comment, afterEmptyLine } = parsePrelude(this.prelude);
- if (comment) {
- const dc = doc2.contents;
- if (afterDoc) {
- doc2.comment = doc2.comment ? `${doc2.comment}
-${comment}` : comment;
- } else if (afterEmptyLine || doc2.directives.docStart || !dc) {
- doc2.commentBefore = comment;
- } else if (identity16.isCollection(dc) && !dc.flow && dc.items.length > 0) {
- let it = dc.items[0];
- if (identity16.isPair(it))
- it = it.key;
- const cb = it.commentBefore;
- it.commentBefore = cb ? `${comment}
-${cb}` : comment;
- } else {
- const cb = dc.commentBefore;
- dc.commentBefore = cb ? `${comment}
-${cb}` : comment;
- }
- }
- if (afterDoc) {
- Array.prototype.push.apply(doc2.errors, this.errors);
- Array.prototype.push.apply(doc2.warnings, this.warnings);
- } else {
- doc2.errors = this.errors;
- doc2.warnings = this.warnings;
- }
- this.prelude = [];
- this.errors = [];
- this.warnings = [];
- }
- streamInfo() {
- return {
- comment: parsePrelude(this.prelude).comment,
- directives: this.directives,
- errors: this.errors,
- warnings: this.warnings
- };
- }
- *compose(tokens, forceDoc = false, endOffset = -1) {
- for (const token of tokens)
- yield* this.next(token);
- yield* this.end(forceDoc, endOffset);
- }
- *next(token) {
- if (node_process.env.LOG_STREAM)
- console.dir(token, { depth: null });
- switch (token.type) {
- case "directive":
- this.directives.add(token.source, (offset, message, warning) => {
- const pos = getErrorPos(token);
- pos[0] += offset;
- this.onError(pos, "BAD_DIRECTIVE", message, warning);
- });
- this.prelude.push(token.source);
- this.atDirectives = true;
- break;
- case "document": {
- const doc2 = composeDoc.composeDoc(this.options, this.directives, token, this.onError);
- if (this.atDirectives && !doc2.directives.docStart)
- this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
- this.decorate(doc2, false);
- if (this.doc)
- yield this.doc;
- this.doc = doc2;
- this.atDirectives = false;
- break;
- }
- case "byte-order-mark":
- case "space":
- break;
- case "comment":
- case "newline":
- this.prelude.push(token.source);
- break;
- case "error": {
- const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message;
- const error46 = new errors8.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg);
- if (this.atDirectives || !this.doc)
- this.errors.push(error46);
- else
- this.doc.errors.push(error46);
- break;
- }
- case "doc-end": {
- if (!this.doc) {
- const msg = "Unexpected doc-end without preceding document";
- this.errors.push(new errors8.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg));
- break;
- }
- this.doc.directives.docEnd = true;
- const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
- this.decorate(this.doc, true);
- if (end.comment) {
- const dc = this.doc.comment;
- this.doc.comment = dc ? `${dc}
-${end.comment}` : end.comment;
- }
- this.doc.range[2] = end.offset;
- break;
- }
- default:
- this.errors.push(new errors8.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`));
- }
- }
- *end(forceDoc = false, endOffset = -1) {
- if (this.doc) {
- this.decorate(this.doc, true);
- yield this.doc;
- this.doc = null;
- } else if (forceDoc) {
- const opts = Object.assign({ _directives: this.directives }, this.options);
- const doc2 = new Document.Document(undefined, opts);
- if (this.atDirectives)
- this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
- doc2.range = [0, endOffset, endOffset];
- this.decorate(doc2, false);
- yield doc2;
- }
- }
- }
- exports.Composer = Composer;
-});
-
-// node_modules/yaml/dist/parse/cst-scalar.js
-var require_cst_scalar = __commonJS((exports) => {
- var resolveBlockScalar = require_resolve_block_scalar();
- var resolveFlowScalar = require_resolve_flow_scalar();
- var errors8 = require_errors6();
- var stringifyString = require_stringifyString();
- function resolveAsScalar(token, strict = true, onError) {
- if (token) {
- const _onError = (pos, code, message) => {
- const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
- if (onError)
- onError(offset, code, message);
- else
- throw new errors8.YAMLParseError([offset, offset + 1], code, message);
- };
- switch (token.type) {
- case "scalar":
- case "single-quoted-scalar":
- case "double-quoted-scalar":
- return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
- case "block-scalar":
- return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);
- }
- }
- return null;
- }
- function createScalarToken(value, context4) {
- const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context4;
- const source = stringifyString.stringifyString({ type, value }, {
- implicitKey,
- indent: indent > 0 ? " ".repeat(indent) : "",
- inFlow,
- options: { blockQuote: true, lineWidth: -1 }
- });
- const end = context4.end ?? [
- { type: "newline", offset: -1, indent, source: `
-` }
- ];
- switch (source[0]) {
- case "|":
- case ">": {
- const he = source.indexOf(`
-`);
- const head = source.substring(0, he);
- const body = source.substring(he + 1) + `
-`;
- const props = [
- { type: "block-scalar-header", offset, indent, source: head }
- ];
- if (!addEndtoBlockProps(props, end))
- props.push({ type: "newline", offset: -1, indent, source: `
-` });
- return { type: "block-scalar", offset, indent, props, source: body };
- }
- case '"':
- return { type: "double-quoted-scalar", offset, indent, source, end };
- case "'":
- return { type: "single-quoted-scalar", offset, indent, source, end };
- default:
- return { type: "scalar", offset, indent, source, end };
- }
- }
- function setScalarValue(token, value, context4 = {}) {
- let { afterKey = false, implicitKey = false, inFlow = false, type } = context4;
- let indent = "indent" in token ? token.indent : null;
- if (afterKey && typeof indent === "number")
- indent += 2;
- if (!type)
- switch (token.type) {
- case "single-quoted-scalar":
- type = "QUOTE_SINGLE";
- break;
- case "double-quoted-scalar":
- type = "QUOTE_DOUBLE";
- break;
- case "block-scalar": {
- const header = token.props[0];
- if (header.type !== "block-scalar-header")
- throw new Error("Invalid block scalar header");
- type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL";
- break;
- }
- default:
- type = "PLAIN";
- }
- const source = stringifyString.stringifyString({ type, value }, {
- implicitKey: implicitKey || indent === null,
- indent: indent !== null && indent > 0 ? " ".repeat(indent) : "",
- inFlow,
- options: { blockQuote: true, lineWidth: -1 }
- });
- switch (source[0]) {
- case "|":
- case ">":
- setBlockScalarValue(token, source);
- break;
- case '"':
- setFlowScalarValue(token, source, "double-quoted-scalar");
- break;
- case "'":
- setFlowScalarValue(token, source, "single-quoted-scalar");
- break;
- default:
- setFlowScalarValue(token, source, "scalar");
- }
- }
- function setBlockScalarValue(token, source) {
- const he = source.indexOf(`
-`);
- const head = source.substring(0, he);
- const body = source.substring(he + 1) + `
-`;
- if (token.type === "block-scalar") {
- const header = token.props[0];
- if (header.type !== "block-scalar-header")
- throw new Error("Invalid block scalar header");
- header.source = head;
- token.source = body;
- } else {
- const { offset } = token;
- const indent = "indent" in token ? token.indent : -1;
- const props = [
- { type: "block-scalar-header", offset, indent, source: head }
- ];
- if (!addEndtoBlockProps(props, "end" in token ? token.end : undefined))
- props.push({ type: "newline", offset: -1, indent, source: `
-` });
- for (const key2 of Object.keys(token))
- if (key2 !== "type" && key2 !== "offset")
- delete token[key2];
- Object.assign(token, { type: "block-scalar", indent, props, source: body });
- }
- }
- function addEndtoBlockProps(props, end) {
- if (end)
- for (const st of end)
- switch (st.type) {
- case "space":
- case "comment":
- props.push(st);
- break;
- case "newline":
- props.push(st);
- return true;
- }
- return false;
- }
- function setFlowScalarValue(token, source, type) {
- switch (token.type) {
- case "scalar":
- case "double-quoted-scalar":
- case "single-quoted-scalar":
- token.type = type;
- token.source = source;
- break;
- case "block-scalar": {
- const end = token.props.slice(1);
- let oa = source.length;
- if (token.props[0].type === "block-scalar-header")
- oa -= token.props[0].source.length;
- for (const tok of end)
- tok.offset += oa;
- delete token.props;
- Object.assign(token, { type, source, end });
- break;
- }
- case "block-map":
- case "block-seq": {
- const offset = token.offset + source.length;
- const nl = { type: "newline", offset, indent: token.indent, source: `
-` };
- delete token.items;
- Object.assign(token, { type, source, end: [nl] });
- break;
- }
- default: {
- const indent = "indent" in token ? token.indent : -1;
- const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : [];
- for (const key2 of Object.keys(token))
- if (key2 !== "type" && key2 !== "offset")
- delete token[key2];
- Object.assign(token, { type, indent, source, end });
- }
- }
- }
- exports.createScalarToken = createScalarToken;
- exports.resolveAsScalar = resolveAsScalar;
- exports.setScalarValue = setScalarValue;
-});
-
-// node_modules/yaml/dist/parse/cst-stringify.js
-var require_cst_stringify = __commonJS((exports) => {
- var stringify2 = (cst) => ("type" in cst) ? stringifyToken(cst) : stringifyItem(cst);
- function stringifyToken(token) {
- switch (token.type) {
- case "block-scalar": {
- let res = "";
- for (const tok of token.props)
- res += stringifyToken(tok);
- return res + token.source;
- }
- case "block-map":
- case "block-seq": {
- let res = "";
- for (const item of token.items)
- res += stringifyItem(item);
- return res;
- }
- case "flow-collection": {
- let res = token.start.source;
- for (const item of token.items)
- res += stringifyItem(item);
- for (const st of token.end)
- res += st.source;
- return res;
- }
- case "document": {
- let res = stringifyItem(token);
- if (token.end)
- for (const st of token.end)
- res += st.source;
- return res;
- }
- default: {
- let res = token.source;
- if ("end" in token && token.end)
- for (const st of token.end)
- res += st.source;
- return res;
- }
- }
- }
- function stringifyItem({ start, key: key2, sep: sep12, value }) {
- let res = "";
- for (const st of start)
- res += st.source;
- if (key2)
- res += stringifyToken(key2);
- if (sep12)
- for (const st of sep12)
- res += st.source;
- if (value)
- res += stringifyToken(value);
- return res;
- }
- exports.stringify = stringify2;
-});
-
-// node_modules/yaml/dist/parse/cst-visit.js
-var require_cst_visit = __commonJS((exports) => {
- var BREAK = Symbol("break visit");
- var SKIP = Symbol("skip children");
- var REMOVE = Symbol("remove item");
- function visit2(cst, visitor) {
- if ("type" in cst && cst.type === "document")
- cst = { start: cst.start, value: cst.value };
- _visit(Object.freeze([]), cst, visitor);
- }
- visit2.BREAK = BREAK;
- visit2.SKIP = SKIP;
- visit2.REMOVE = REMOVE;
- visit2.itemAtPath = (cst, path16) => {
- let item = cst;
- for (const [field, index2] of path16) {
- const tok = item?.[field];
- if (tok && "items" in tok) {
- item = tok.items[index2];
- } else
- return;
- }
- return item;
- };
- visit2.parentCollection = (cst, path16) => {
- const parent = visit2.itemAtPath(cst, path16.slice(0, -1));
- const field = path16[path16.length - 1][0];
- const coll = parent?.[field];
- if (coll && "items" in coll)
- return coll;
- throw new Error("Parent collection not found");
- };
- function _visit(path16, item, visitor) {
- let ctrl = visitor(item, path16);
- if (typeof ctrl === "symbol")
- return ctrl;
- for (const field of ["key", "value"]) {
- const token = item[field];
- if (token && "items" in token) {
- for (let i6 = 0;i6 < token.items.length; ++i6) {
- const ci = _visit(Object.freeze(path16.concat([[field, i6]])), token.items[i6], visitor);
- if (typeof ci === "number")
- i6 = ci - 1;
- else if (ci === BREAK)
- return BREAK;
- else if (ci === REMOVE) {
- token.items.splice(i6, 1);
- i6 -= 1;
- }
- }
- if (typeof ctrl === "function" && field === "key")
- ctrl = ctrl(item, path16);
- }
- }
- return typeof ctrl === "function" ? ctrl(item, path16) : ctrl;
- }
- exports.visit = visit2;
-});
-
-// node_modules/yaml/dist/parse/cst.js
-var require_cst = __commonJS((exports) => {
- var cstScalar = require_cst_scalar();
- var cstStringify = require_cst_stringify();
- var cstVisit = require_cst_visit();
- var BOM = "\uFEFF";
- var DOCUMENT = "\x02";
- var FLOW_END = "\x18";
- var SCALAR = "\x1F";
- var isCollection = (token) => !!token && ("items" in token);
- var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
- function prettyToken(token) {
- switch (token) {
- case BOM:
- return "";
- case DOCUMENT:
- return "";
- case FLOW_END:
- return "";
- case SCALAR:
- return "";
- default:
- return JSON.stringify(token);
- }
- }
- function tokenType(source) {
- switch (source) {
- case BOM:
- return "byte-order-mark";
- case DOCUMENT:
- return "doc-mode";
- case FLOW_END:
- return "flow-error-end";
- case SCALAR:
- return "scalar";
- case "---":
- return "doc-start";
- case "...":
- return "doc-end";
- case "":
- case `
-`:
- case `\r
-`:
- return "newline";
- case "-":
- return "seq-item-ind";
- case "?":
- return "explicit-key-ind";
- case ":":
- return "map-value-ind";
- case "{":
- return "flow-map-start";
- case "}":
- return "flow-map-end";
- case "[":
- return "flow-seq-start";
- case "]":
- return "flow-seq-end";
- case ",":
- return "comma";
- }
- switch (source[0]) {
- case " ":
- case "\t":
- return "space";
- case "#":
- return "comment";
- case "%":
- return "directive-line";
- case "*":
- return "alias";
- case "&":
- return "anchor";
- case "!":
- return "tag";
- case "'":
- return "single-quoted-scalar";
- case '"':
- return "double-quoted-scalar";
- case "|":
- case ">":
- return "block-scalar-header";
- }
- return null;
- }
- exports.createScalarToken = cstScalar.createScalarToken;
- exports.resolveAsScalar = cstScalar.resolveAsScalar;
- exports.setScalarValue = cstScalar.setScalarValue;
- exports.stringify = cstStringify.stringify;
- exports.visit = cstVisit.visit;
- exports.BOM = BOM;
- exports.DOCUMENT = DOCUMENT;
- exports.FLOW_END = FLOW_END;
- exports.SCALAR = SCALAR;
- exports.isCollection = isCollection;
- exports.isScalar = isScalar;
- exports.prettyToken = prettyToken;
- exports.tokenType = tokenType;
-});
-
-// node_modules/yaml/dist/parse/lexer.js
-var require_lexer = __commonJS((exports) => {
- var cst = require_cst();
- function isEmpty(ch2) {
- switch (ch2) {
- case undefined:
- case " ":
- case `
-`:
- case "\r":
- case "\t":
- return true;
- default:
- return false;
- }
- }
- var hexDigits = new Set("0123456789ABCDEFabcdef");
- var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
- var flowIndicatorChars = new Set(",[]{}");
- var invalidAnchorChars = new Set(` ,[]{}
-\r `);
- var isNotAnchorChar = (ch2) => !ch2 || invalidAnchorChars.has(ch2);
-
- class Lexer {
- constructor() {
- this.atEnd = false;
- this.blockScalarIndent = -1;
- this.blockScalarKeep = false;
- this.buffer = "";
- this.flowKey = false;
- this.flowLevel = 0;
- this.indentNext = 0;
- this.indentValue = 0;
- this.lineEndPos = null;
- this.next = null;
- this.pos = 0;
- }
- *lex(source, incomplete = false) {
- if (source) {
- if (typeof source !== "string")
- throw TypeError("source is not a string");
- this.buffer = this.buffer ? this.buffer + source : source;
- this.lineEndPos = null;
- }
- this.atEnd = !incomplete;
- let next = this.next ?? "stream";
- while (next && (incomplete || this.hasChars(1)))
- next = yield* this.parseNext(next);
- }
- atLineEnd() {
- let i6 = this.pos;
- let ch2 = this.buffer[i6];
- while (ch2 === " " || ch2 === "\t")
- ch2 = this.buffer[++i6];
- if (!ch2 || ch2 === "#" || ch2 === `
-`)
- return true;
- if (ch2 === "\r")
- return this.buffer[i6 + 1] === `
-`;
- return false;
- }
- charAt(n5) {
- return this.buffer[this.pos + n5];
- }
- continueScalar(offset) {
- let ch2 = this.buffer[offset];
- if (this.indentNext > 0) {
- let indent = 0;
- while (ch2 === " ")
- ch2 = this.buffer[++indent + offset];
- if (ch2 === "\r") {
- const next = this.buffer[indent + offset + 1];
- if (next === `
-` || !next && !this.atEnd)
- return offset + indent + 1;
- }
- return ch2 === `
-` || indent >= this.indentNext || !ch2 && !this.atEnd ? offset + indent : -1;
- }
- if (ch2 === "-" || ch2 === ".") {
- const dt = this.buffer.substr(offset, 3);
- if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3]))
- return -1;
- }
- return offset;
- }
- getLine() {
- let end = this.lineEndPos;
- if (typeof end !== "number" || end !== -1 && end < this.pos) {
- end = this.buffer.indexOf(`
-`, this.pos);
- this.lineEndPos = end;
- }
- if (end === -1)
- return this.atEnd ? this.buffer.substring(this.pos) : null;
- if (this.buffer[end - 1] === "\r")
- end -= 1;
- return this.buffer.substring(this.pos, end);
- }
- hasChars(n5) {
- return this.pos + n5 <= this.buffer.length;
- }
- setNext(state3) {
- this.buffer = this.buffer.substring(this.pos);
- this.pos = 0;
- this.lineEndPos = null;
- this.next = state3;
- return null;
- }
- peek(n5) {
- return this.buffer.substr(this.pos, n5);
- }
- *parseNext(next) {
- switch (next) {
- case "stream":
- return yield* this.parseStream();
- case "line-start":
- return yield* this.parseLineStart();
- case "block-start":
- return yield* this.parseBlockStart();
- case "doc":
- return yield* this.parseDocument();
- case "flow":
- return yield* this.parseFlowCollection();
- case "quoted-scalar":
- return yield* this.parseQuotedScalar();
- case "block-scalar":
- return yield* this.parseBlockScalar();
- case "plain-scalar":
- return yield* this.parsePlainScalar();
- }
- }
- *parseStream() {
- let line = this.getLine();
- if (line === null)
- return this.setNext("stream");
- if (line[0] === cst.BOM) {
- yield* this.pushCount(1);
- line = line.substring(1);
- }
- if (line[0] === "%") {
- let dirEnd = line.length;
- let cs = line.indexOf("#");
- while (cs !== -1) {
- const ch2 = line[cs - 1];
- if (ch2 === " " || ch2 === "\t") {
- dirEnd = cs - 1;
- break;
- } else {
- cs = line.indexOf("#", cs + 1);
- }
- }
- while (true) {
- const ch2 = line[dirEnd - 1];
- if (ch2 === " " || ch2 === "\t")
- dirEnd -= 1;
- else
- break;
- }
- const n5 = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
- yield* this.pushCount(line.length - n5);
- this.pushNewline();
- return "stream";
- }
- if (this.atLineEnd()) {
- const sp = yield* this.pushSpaces(true);
- yield* this.pushCount(line.length - sp);
- yield* this.pushNewline();
- return "stream";
- }
- yield cst.DOCUMENT;
- return yield* this.parseLineStart();
- }
- *parseLineStart() {
- const ch2 = this.charAt(0);
- if (!ch2 && !this.atEnd)
- return this.setNext("line-start");
- if (ch2 === "-" || ch2 === ".") {
- if (!this.atEnd && !this.hasChars(4))
- return this.setNext("line-start");
- const s4 = this.peek(3);
- if ((s4 === "---" || s4 === "...") && isEmpty(this.charAt(3))) {
- yield* this.pushCount(3);
- this.indentValue = 0;
- this.indentNext = 0;
- return s4 === "---" ? "doc" : "stream";
- }
- }
- this.indentValue = yield* this.pushSpaces(false);
- if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
- this.indentNext = this.indentValue;
- return yield* this.parseBlockStart();
- }
- *parseBlockStart() {
- const [ch0, ch1] = this.peek(2);
- if (!ch1 && !this.atEnd)
- return this.setNext("block-start");
- if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) {
- const n5 = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
- this.indentNext = this.indentValue + 1;
- this.indentValue += n5;
- return yield* this.parseBlockStart();
- }
- return "doc";
- }
- *parseDocument() {
- yield* this.pushSpaces(true);
- const line = this.getLine();
- if (line === null)
- return this.setNext("doc");
- let n5 = yield* this.pushIndicators();
- switch (line[n5]) {
- case "#":
- yield* this.pushCount(line.length - n5);
- case undefined:
- yield* this.pushNewline();
- return yield* this.parseLineStart();
- case "{":
- case "[":
- yield* this.pushCount(1);
- this.flowKey = false;
- this.flowLevel = 1;
- return "flow";
- case "}":
- case "]":
- yield* this.pushCount(1);
- return "doc";
- case "*":
- yield* this.pushUntil(isNotAnchorChar);
- return "doc";
- case '"':
- case "'":
- return yield* this.parseQuotedScalar();
- case "|":
- case ">":
- n5 += yield* this.parseBlockScalarHeader();
- n5 += yield* this.pushSpaces(true);
- yield* this.pushCount(line.length - n5);
- yield* this.pushNewline();
- return yield* this.parseBlockScalar();
- default:
- return yield* this.parsePlainScalar();
- }
- }
- *parseFlowCollection() {
- let nl, sp;
- let indent = -1;
- do {
- nl = yield* this.pushNewline();
- if (nl > 0) {
- sp = yield* this.pushSpaces(false);
- this.indentValue = indent = sp;
- } else {
- sp = 0;
- }
- sp += yield* this.pushSpaces(true);
- } while (nl + sp > 0);
- const line = this.getLine();
- if (line === null)
- return this.setNext("flow");
- if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) {
- const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
- if (!atFlowEndMarker) {
- this.flowLevel = 0;
- yield cst.FLOW_END;
- return yield* this.parseLineStart();
- }
- }
- let n5 = 0;
- while (line[n5] === ",") {
- n5 += yield* this.pushCount(1);
- n5 += yield* this.pushSpaces(true);
- this.flowKey = false;
- }
- n5 += yield* this.pushIndicators();
- switch (line[n5]) {
- case undefined:
- return "flow";
- case "#":
- yield* this.pushCount(line.length - n5);
- return "flow";
- case "{":
- case "[":
- yield* this.pushCount(1);
- this.flowKey = false;
- this.flowLevel += 1;
- return "flow";
- case "}":
- case "]":
- yield* this.pushCount(1);
- this.flowKey = true;
- this.flowLevel -= 1;
- return this.flowLevel ? "flow" : "doc";
- case "*":
- yield* this.pushUntil(isNotAnchorChar);
- return "flow";
- case '"':
- case "'":
- this.flowKey = true;
- return yield* this.parseQuotedScalar();
- case ":": {
- const next = this.charAt(1);
- if (this.flowKey || isEmpty(next) || next === ",") {
- this.flowKey = false;
- yield* this.pushCount(1);
- yield* this.pushSpaces(true);
- return "flow";
- }
- }
- default:
- this.flowKey = false;
- return yield* this.parsePlainScalar();
- }
- }
- *parseQuotedScalar() {
- const quote2 = this.charAt(0);
- let end = this.buffer.indexOf(quote2, this.pos + 1);
- if (quote2 === "'") {
- while (end !== -1 && this.buffer[end + 1] === "'")
- end = this.buffer.indexOf("'", end + 2);
- } else {
- while (end !== -1) {
- let n5 = 0;
- while (this.buffer[end - 1 - n5] === "\\")
- n5 += 1;
- if (n5 % 2 === 0)
- break;
- end = this.buffer.indexOf('"', end + 1);
- }
- }
- const qb = this.buffer.substring(0, end);
- let nl = qb.indexOf(`
-`, this.pos);
- if (nl !== -1) {
- while (nl !== -1) {
- const cs = this.continueScalar(nl + 1);
- if (cs === -1)
- break;
- nl = qb.indexOf(`
-`, cs);
- }
- if (nl !== -1) {
- end = nl - (qb[nl - 1] === "\r" ? 2 : 1);
- }
- }
- if (end === -1) {
- if (!this.atEnd)
- return this.setNext("quoted-scalar");
- end = this.buffer.length;
- }
- yield* this.pushToIndex(end + 1, false);
- return this.flowLevel ? "flow" : "doc";
- }
- *parseBlockScalarHeader() {
- this.blockScalarIndent = -1;
- this.blockScalarKeep = false;
- let i6 = this.pos;
- while (true) {
- const ch2 = this.buffer[++i6];
- if (ch2 === "+")
- this.blockScalarKeep = true;
- else if (ch2 > "0" && ch2 <= "9")
- this.blockScalarIndent = Number(ch2) - 1;
- else if (ch2 !== "-")
- break;
- }
- return yield* this.pushUntil((ch2) => isEmpty(ch2) || ch2 === "#");
- }
- *parseBlockScalar() {
- let nl = this.pos - 1;
- let indent = 0;
- let ch2;
- loop:
- for (let i7 = this.pos;ch2 = this.buffer[i7]; ++i7) {
- switch (ch2) {
- case " ":
- indent += 1;
- break;
- case `
-`:
- nl = i7;
- indent = 0;
- break;
- case "\r": {
- const next = this.buffer[i7 + 1];
- if (!next && !this.atEnd)
- return this.setNext("block-scalar");
- if (next === `
-`)
- break;
- }
- default:
- break loop;
- }
- }
- if (!ch2 && !this.atEnd)
- return this.setNext("block-scalar");
- if (indent >= this.indentNext) {
- if (this.blockScalarIndent === -1)
- this.indentNext = indent;
- else {
- this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
- }
- do {
- const cs = this.continueScalar(nl + 1);
- if (cs === -1)
- break;
- nl = this.buffer.indexOf(`
-`, cs);
- } while (nl !== -1);
- if (nl === -1) {
- if (!this.atEnd)
- return this.setNext("block-scalar");
- nl = this.buffer.length;
- }
- }
- let i6 = nl + 1;
- ch2 = this.buffer[i6];
- while (ch2 === " ")
- ch2 = this.buffer[++i6];
- if (ch2 === "\t") {
- while (ch2 === "\t" || ch2 === " " || ch2 === "\r" || ch2 === `
-`)
- ch2 = this.buffer[++i6];
- nl = i6 - 1;
- } else if (!this.blockScalarKeep) {
- do {
- let i7 = nl - 1;
- let ch3 = this.buffer[i7];
- if (ch3 === "\r")
- ch3 = this.buffer[--i7];
- const lastChar = i7;
- while (ch3 === " ")
- ch3 = this.buffer[--i7];
- if (ch3 === `
-` && i7 >= this.pos && i7 + 1 + indent > lastChar)
- nl = i7;
- else
- break;
- } while (true);
- }
- yield cst.SCALAR;
- yield* this.pushToIndex(nl + 1, true);
- return yield* this.parseLineStart();
- }
- *parsePlainScalar() {
- const inFlow = this.flowLevel > 0;
- let end = this.pos - 1;
- let i6 = this.pos - 1;
- let ch2;
- while (ch2 = this.buffer[++i6]) {
- if (ch2 === ":") {
- const next = this.buffer[i6 + 1];
- if (isEmpty(next) || inFlow && flowIndicatorChars.has(next))
- break;
- end = i6;
- } else if (isEmpty(ch2)) {
- let next = this.buffer[i6 + 1];
- if (ch2 === "\r") {
- if (next === `
-`) {
- i6 += 1;
- ch2 = `
-`;
- next = this.buffer[i6 + 1];
- } else
- end = i6;
- }
- if (next === "#" || inFlow && flowIndicatorChars.has(next))
- break;
- if (ch2 === `
-`) {
- const cs = this.continueScalar(i6 + 1);
- if (cs === -1)
- break;
- i6 = Math.max(i6, cs - 2);
- }
- } else {
- if (inFlow && flowIndicatorChars.has(ch2))
- break;
- end = i6;
- }
- }
- if (!ch2 && !this.atEnd)
- return this.setNext("plain-scalar");
- yield cst.SCALAR;
- yield* this.pushToIndex(end + 1, true);
- return inFlow ? "flow" : "doc";
- }
- *pushCount(n5) {
- if (n5 > 0) {
- yield this.buffer.substr(this.pos, n5);
- this.pos += n5;
- return n5;
- }
- return 0;
- }
- *pushToIndex(i6, allowEmpty) {
- const s4 = this.buffer.slice(this.pos, i6);
- if (s4) {
- yield s4;
- this.pos += s4.length;
- return s4.length;
- } else if (allowEmpty)
- yield "";
- return 0;
- }
- *pushIndicators() {
- switch (this.charAt(0)) {
- case "!":
- return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
- case "&":
- return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
- case "-":
- case "?":
- case ":": {
- const inFlow = this.flowLevel > 0;
- const ch1 = this.charAt(1);
- if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
- if (!inFlow)
- this.indentNext = this.indentValue + 1;
- else if (this.flowKey)
- this.flowKey = false;
- return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
- }
- }
- }
- return 0;
- }
- *pushTag() {
- if (this.charAt(1) === "<") {
- let i6 = this.pos + 2;
- let ch2 = this.buffer[i6];
- while (!isEmpty(ch2) && ch2 !== ">")
- ch2 = this.buffer[++i6];
- return yield* this.pushToIndex(ch2 === ">" ? i6 + 1 : i6, false);
- } else {
- let i6 = this.pos + 1;
- let ch2 = this.buffer[i6];
- while (ch2) {
- if (tagChars.has(ch2))
- ch2 = this.buffer[++i6];
- else if (ch2 === "%" && hexDigits.has(this.buffer[i6 + 1]) && hexDigits.has(this.buffer[i6 + 2])) {
- ch2 = this.buffer[i6 += 3];
- } else
- break;
- }
- return yield* this.pushToIndex(i6, false);
- }
- }
- *pushNewline() {
- const ch2 = this.buffer[this.pos];
- if (ch2 === `
-`)
- return yield* this.pushCount(1);
- else if (ch2 === "\r" && this.charAt(1) === `
-`)
- return yield* this.pushCount(2);
- else
- return 0;
- }
- *pushSpaces(allowTabs) {
- let i6 = this.pos - 1;
- let ch2;
- do {
- ch2 = this.buffer[++i6];
- } while (ch2 === " " || allowTabs && ch2 === "\t");
- const n5 = i6 - this.pos;
- if (n5 > 0) {
- yield this.buffer.substr(this.pos, n5);
- this.pos = i6;
- }
- return n5;
- }
- *pushUntil(test2) {
- let i6 = this.pos;
- let ch2 = this.buffer[i6];
- while (!test2(ch2))
- ch2 = this.buffer[++i6];
- return yield* this.pushToIndex(i6, false);
- }
- }
- exports.Lexer = Lexer;
-});
-
-// node_modules/yaml/dist/parse/line-counter.js
-var require_line_counter = __commonJS((exports) => {
- class LineCounter {
- constructor() {
- this.lineStarts = [];
- this.addNewLine = (offset) => this.lineStarts.push(offset);
- this.linePos = (offset) => {
- let low = 0;
- let high = this.lineStarts.length;
- while (low < high) {
- const mid = low + high >> 1;
- if (this.lineStarts[mid] < offset)
- low = mid + 1;
- else
- high = mid;
- }
- if (this.lineStarts[low] === offset)
- return { line: low + 1, col: 1 };
- if (low === 0)
- return { line: 0, col: offset };
- const start = this.lineStarts[low - 1];
- return { line: low, col: offset - start + 1 };
- };
- }
- }
- exports.LineCounter = LineCounter;
-});
-
-// node_modules/yaml/dist/parse/parser.js
-var require_parser = __commonJS((exports) => {
- var node_process = __require("process");
- var cst = require_cst();
- var lexer2 = require_lexer();
- function includesToken(list2, type) {
- for (let i6 = 0;i6 < list2.length; ++i6)
- if (list2[i6].type === type)
- return true;
- return false;
- }
- function findNonEmptyIndex(list2) {
- for (let i6 = 0;i6 < list2.length; ++i6) {
- switch (list2[i6].type) {
- case "space":
- case "comment":
- case "newline":
- break;
- default:
- return i6;
- }
- }
- return -1;
- }
- function isFlowToken(token) {
- switch (token?.type) {
- case "alias":
- case "scalar":
- case "single-quoted-scalar":
- case "double-quoted-scalar":
- case "flow-collection":
- return true;
- default:
- return false;
- }
- }
- function getPrevProps(parent) {
- switch (parent.type) {
- case "document":
- return parent.start;
- case "block-map": {
- const it = parent.items[parent.items.length - 1];
- return it.sep ?? it.start;
- }
- case "block-seq":
- return parent.items[parent.items.length - 1].start;
- default:
- return [];
- }
- }
- function getFirstKeyStartProps(prev) {
- if (prev.length === 0)
- return [];
- let i6 = prev.length;
- loop:
- while (--i6 >= 0) {
- switch (prev[i6].type) {
- case "doc-start":
- case "explicit-key-ind":
- case "map-value-ind":
- case "seq-item-ind":
- case "newline":
- break loop;
- }
- }
- while (prev[++i6]?.type === "space") {}
- return prev.splice(i6, prev.length);
- }
- function fixFlowSeqItems(fc) {
- if (fc.start.type === "flow-seq-start") {
- for (const it of fc.items) {
- if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) {
- if (it.key)
- it.value = it.key;
- delete it.key;
- if (isFlowToken(it.value)) {
- if (it.value.end)
- Array.prototype.push.apply(it.value.end, it.sep);
- else
- it.value.end = it.sep;
- } else
- Array.prototype.push.apply(it.start, it.sep);
- delete it.sep;
- }
- }
- }
- }
-
- class Parser2 {
- constructor(onNewLine) {
- this.atNewLine = true;
- this.atScalar = false;
- this.indent = 0;
- this.offset = 0;
- this.onKeyLine = false;
- this.stack = [];
- this.source = "";
- this.type = "";
- this.lexer = new lexer2.Lexer;
- this.onNewLine = onNewLine;
- }
- *parse(source, incomplete = false) {
- if (this.onNewLine && this.offset === 0)
- this.onNewLine(0);
- for (const lexeme of this.lexer.lex(source, incomplete))
- yield* this.next(lexeme);
- if (!incomplete)
- yield* this.end();
- }
- *next(source) {
- this.source = source;
- if (node_process.env.LOG_TOKENS)
- console.log("|", cst.prettyToken(source));
- if (this.atScalar) {
- this.atScalar = false;
- yield* this.step();
- this.offset += source.length;
- return;
- }
- const type = cst.tokenType(source);
- if (!type) {
- const message = `Not a YAML token: ${source}`;
- yield* this.pop({ type: "error", offset: this.offset, message, source });
- this.offset += source.length;
- } else if (type === "scalar") {
- this.atNewLine = false;
- this.atScalar = true;
- this.type = "scalar";
- } else {
- this.type = type;
- yield* this.step();
- switch (type) {
- case "newline":
- this.atNewLine = true;
- this.indent = 0;
- if (this.onNewLine)
- this.onNewLine(this.offset + source.length);
- break;
- case "space":
- if (this.atNewLine && source[0] === " ")
- this.indent += source.length;
- break;
- case "explicit-key-ind":
- case "map-value-ind":
- case "seq-item-ind":
- if (this.atNewLine)
- this.indent += source.length;
- break;
- case "doc-mode":
- case "flow-error-end":
- return;
- default:
- this.atNewLine = false;
- }
- this.offset += source.length;
- }
- }
- *end() {
- while (this.stack.length > 0)
- yield* this.pop();
- }
- get sourceToken() {
- const st = {
- type: this.type,
- offset: this.offset,
- indent: this.indent,
- source: this.source
- };
- return st;
- }
- *step() {
- const top = this.peek(1);
- if (this.type === "doc-end" && top?.type !== "doc-end") {
- while (this.stack.length > 0)
- yield* this.pop();
- this.stack.push({
- type: "doc-end",
- offset: this.offset,
- source: this.source
- });
- return;
- }
- if (!top)
- return yield* this.stream();
- switch (top.type) {
- case "document":
- return yield* this.document(top);
- case "alias":
- case "scalar":
- case "single-quoted-scalar":
- case "double-quoted-scalar":
- return yield* this.scalar(top);
- case "block-scalar":
- return yield* this.blockScalar(top);
- case "block-map":
- return yield* this.blockMap(top);
- case "block-seq":
- return yield* this.blockSequence(top);
- case "flow-collection":
- return yield* this.flowCollection(top);
- case "doc-end":
- return yield* this.documentEnd(top);
- }
- yield* this.pop();
- }
- peek(n5) {
- return this.stack[this.stack.length - n5];
- }
- *pop(error46) {
- const token = error46 ?? this.stack.pop();
- if (!token) {
- const message = "Tried to pop an empty stack";
- yield { type: "error", offset: this.offset, source: "", message };
- } else if (this.stack.length === 0) {
- yield token;
- } else {
- const top = this.peek(1);
- if (token.type === "block-scalar") {
- token.indent = "indent" in top ? top.indent : 0;
- } else if (token.type === "flow-collection" && top.type === "document") {
- token.indent = 0;
- }
- if (token.type === "flow-collection")
- fixFlowSeqItems(token);
- switch (top.type) {
- case "document":
- top.value = token;
- break;
- case "block-scalar":
- top.props.push(token);
- break;
- case "block-map": {
- const it = top.items[top.items.length - 1];
- if (it.value) {
- top.items.push({ start: [], key: token, sep: [] });
- this.onKeyLine = true;
- return;
- } else if (it.sep) {
- it.value = token;
- } else {
- Object.assign(it, { key: token, sep: [] });
- this.onKeyLine = !it.explicitKey;
- return;
- }
- break;
- }
- case "block-seq": {
- const it = top.items[top.items.length - 1];
- if (it.value)
- top.items.push({ start: [], value: token });
- else
- it.value = token;
- break;
- }
- case "flow-collection": {
- const it = top.items[top.items.length - 1];
- if (!it || it.value)
- top.items.push({ start: [], key: token, sep: [] });
- else if (it.sep)
- it.value = token;
- else
- Object.assign(it, { key: token, sep: [] });
- return;
- }
- default:
- yield* this.pop();
- yield* this.pop(token);
- }
- if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) {
- const last2 = token.items[token.items.length - 1];
- if (last2 && !last2.sep && !last2.value && last2.start.length > 0 && findNonEmptyIndex(last2.start) === -1 && (token.indent === 0 || last2.start.every((st) => st.type !== "comment" || st.indent < token.indent))) {
- if (top.type === "document")
- top.end = last2.start;
- else
- top.items.push({ start: last2.start });
- token.items.splice(-1, 1);
- }
- }
- }
- }
- *stream() {
- switch (this.type) {
- case "directive-line":
- yield { type: "directive", offset: this.offset, source: this.source };
- return;
- case "byte-order-mark":
- case "space":
- case "comment":
- case "newline":
- yield this.sourceToken;
- return;
- case "doc-mode":
- case "doc-start": {
- const doc2 = {
- type: "document",
- offset: this.offset,
- start: []
- };
- if (this.type === "doc-start")
- doc2.start.push(this.sourceToken);
- this.stack.push(doc2);
- return;
- }
- }
- yield {
- type: "error",
- offset: this.offset,
- message: `Unexpected ${this.type} token in YAML stream`,
- source: this.source
- };
- }
- *document(doc2) {
- if (doc2.value)
- return yield* this.lineEnd(doc2);
- switch (this.type) {
- case "doc-start": {
- if (findNonEmptyIndex(doc2.start) !== -1) {
- yield* this.pop();
- yield* this.step();
- } else
- doc2.start.push(this.sourceToken);
- return;
- }
- case "anchor":
- case "tag":
- case "space":
- case "comment":
- case "newline":
- doc2.start.push(this.sourceToken);
- return;
- }
- const bv = this.startBlockValue(doc2);
- if (bv)
- this.stack.push(bv);
- else {
- yield {
- type: "error",
- offset: this.offset,
- message: `Unexpected ${this.type} token in YAML document`,
- source: this.source
- };
- }
- }
- *scalar(scalar) {
- if (this.type === "map-value-ind") {
- const prev = getPrevProps(this.peek(2));
- const start = getFirstKeyStartProps(prev);
- let sep12;
- if (scalar.end) {
- sep12 = scalar.end;
- sep12.push(this.sourceToken);
- delete scalar.end;
- } else
- sep12 = [this.sourceToken];
- const map7 = {
- type: "block-map",
- offset: scalar.offset,
- indent: scalar.indent,
- items: [{ start, key: scalar, sep: sep12 }]
- };
- this.onKeyLine = true;
- this.stack[this.stack.length - 1] = map7;
- } else
- yield* this.lineEnd(scalar);
- }
- *blockScalar(scalar) {
- switch (this.type) {
- case "space":
- case "comment":
- case "newline":
- scalar.props.push(this.sourceToken);
- return;
- case "scalar":
- scalar.source = this.source;
- this.atNewLine = true;
- this.indent = 0;
- if (this.onNewLine) {
- let nl = this.source.indexOf(`
-`) + 1;
- while (nl !== 0) {
- this.onNewLine(this.offset + nl);
- nl = this.source.indexOf(`
-`, nl) + 1;
- }
- }
- yield* this.pop();
- break;
- default:
- yield* this.pop();
- yield* this.step();
- }
- }
- *blockMap(map7) {
- const it = map7.items[map7.items.length - 1];
- switch (this.type) {
- case "newline":
- this.onKeyLine = false;
- if (it.value) {
- const end = "end" in it.value ? it.value.end : undefined;
- const last2 = Array.isArray(end) ? end[end.length - 1] : undefined;
- if (last2?.type === "comment")
- end?.push(this.sourceToken);
- else
- map7.items.push({ start: [this.sourceToken] });
- } else if (it.sep) {
- it.sep.push(this.sourceToken);
- } else {
- it.start.push(this.sourceToken);
- }
- return;
- case "space":
- case "comment":
- if (it.value) {
- map7.items.push({ start: [this.sourceToken] });
- } else if (it.sep) {
- it.sep.push(this.sourceToken);
- } else {
- if (this.atIndentedComment(it.start, map7.indent)) {
- const prev = map7.items[map7.items.length - 2];
- const end = prev?.value?.end;
- if (Array.isArray(end)) {
- Array.prototype.push.apply(end, it.start);
- end.push(this.sourceToken);
- map7.items.pop();
- return;
- }
- }
- it.start.push(this.sourceToken);
- }
- return;
- }
- if (this.indent >= map7.indent) {
- const atMapIndent = !this.onKeyLine && this.indent === map7.indent;
- const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind";
- let start = [];
- if (atNextItem && it.sep && !it.value) {
- const nl = [];
- for (let i6 = 0;i6 < it.sep.length; ++i6) {
- const st = it.sep[i6];
- switch (st.type) {
- case "newline":
- nl.push(i6);
- break;
- case "space":
- break;
- case "comment":
- if (st.indent > map7.indent)
- nl.length = 0;
- break;
- default:
- nl.length = 0;
- }
- }
- if (nl.length >= 2)
- start = it.sep.splice(nl[1]);
- }
- switch (this.type) {
- case "anchor":
- case "tag":
- if (atNextItem || it.value) {
- start.push(this.sourceToken);
- map7.items.push({ start });
- this.onKeyLine = true;
- } else if (it.sep) {
- it.sep.push(this.sourceToken);
- } else {
- it.start.push(this.sourceToken);
- }
- return;
- case "explicit-key-ind":
- if (!it.sep && !it.explicitKey) {
- it.start.push(this.sourceToken);
- it.explicitKey = true;
- } else if (atNextItem || it.value) {
- start.push(this.sourceToken);
- map7.items.push({ start, explicitKey: true });
- } else {
- this.stack.push({
- type: "block-map",
- offset: this.offset,
- indent: this.indent,
- items: [{ start: [this.sourceToken], explicitKey: true }]
- });
- }
- this.onKeyLine = true;
- return;
- case "map-value-ind":
- if (it.explicitKey) {
- if (!it.sep) {
- if (includesToken(it.start, "newline")) {
- Object.assign(it, { key: null, sep: [this.sourceToken] });
- } else {
- const start2 = getFirstKeyStartProps(it.start);
- this.stack.push({
- type: "block-map",
- offset: this.offset,
- indent: this.indent,
- items: [{ start: start2, key: null, sep: [this.sourceToken] }]
- });
- }
- } else if (it.value) {
- map7.items.push({ start: [], key: null, sep: [this.sourceToken] });
- } else if (includesToken(it.sep, "map-value-ind")) {
- this.stack.push({
- type: "block-map",
- offset: this.offset,
- indent: this.indent,
- items: [{ start, key: null, sep: [this.sourceToken] }]
- });
- } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
- const start2 = getFirstKeyStartProps(it.start);
- const key2 = it.key;
- const sep12 = it.sep;
- sep12.push(this.sourceToken);
- delete it.key;
- delete it.sep;
- this.stack.push({
- type: "block-map",
- offset: this.offset,
- indent: this.indent,
- items: [{ start: start2, key: key2, sep: sep12 }]
- });
- } else if (start.length > 0) {
- it.sep = it.sep.concat(start, this.sourceToken);
- } else {
- it.sep.push(this.sourceToken);
- }
- } else {
- if (!it.sep) {
- Object.assign(it, { key: null, sep: [this.sourceToken] });
- } else if (it.value || atNextItem) {
- map7.items.push({ start, key: null, sep: [this.sourceToken] });
- } else if (includesToken(it.sep, "map-value-ind")) {
- this.stack.push({
- type: "block-map",
- offset: this.offset,
- indent: this.indent,
- items: [{ start: [], key: null, sep: [this.sourceToken] }]
- });
- } else {
- it.sep.push(this.sourceToken);
- }
- }
- this.onKeyLine = true;
- return;
- case "alias":
- case "scalar":
- case "single-quoted-scalar":
- case "double-quoted-scalar": {
- const fs10 = this.flowScalar(this.type);
- if (atNextItem || it.value) {
- map7.items.push({ start, key: fs10, sep: [] });
- this.onKeyLine = true;
- } else if (it.sep) {
- this.stack.push(fs10);
- } else {
- Object.assign(it, { key: fs10, sep: [] });
- this.onKeyLine = true;
- }
- return;
- }
- default: {
- const bv = this.startBlockValue(map7);
- if (bv) {
- if (bv.type === "block-seq") {
- if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) {
- yield* this.pop({
- type: "error",
- offset: this.offset,
- message: "Unexpected block-seq-ind on same line with key",
- source: this.source
- });
- return;
- }
- } else if (atMapIndent) {
- map7.items.push({ start });
- }
- this.stack.push(bv);
- return;
- }
- }
- }
- }
- yield* this.pop();
- yield* this.step();
- }
- *blockSequence(seq) {
- const it = seq.items[seq.items.length - 1];
- switch (this.type) {
- case "newline":
- if (it.value) {
- const end = "end" in it.value ? it.value.end : undefined;
- const last2 = Array.isArray(end) ? end[end.length - 1] : undefined;
- if (last2?.type === "comment")
- end?.push(this.sourceToken);
- else
- seq.items.push({ start: [this.sourceToken] });
- } else
- it.start.push(this.sourceToken);
- return;
- case "space":
- case "comment":
- if (it.value)
- seq.items.push({ start: [this.sourceToken] });
- else {
- if (this.atIndentedComment(it.start, seq.indent)) {
- const prev = seq.items[seq.items.length - 2];
- const end = prev?.value?.end;
- if (Array.isArray(end)) {
- Array.prototype.push.apply(end, it.start);
- end.push(this.sourceToken);
- seq.items.pop();
- return;
- }
- }
- it.start.push(this.sourceToken);
- }
- return;
- case "anchor":
- case "tag":
- if (it.value || this.indent <= seq.indent)
- break;
- it.start.push(this.sourceToken);
- return;
- case "seq-item-ind":
- if (this.indent !== seq.indent)
- break;
- if (it.value || includesToken(it.start, "seq-item-ind"))
- seq.items.push({ start: [this.sourceToken] });
- else
- it.start.push(this.sourceToken);
- return;
- }
- if (this.indent > seq.indent) {
- const bv = this.startBlockValue(seq);
- if (bv) {
- this.stack.push(bv);
- return;
- }
- }
- yield* this.pop();
- yield* this.step();
- }
- *flowCollection(fc) {
- const it = fc.items[fc.items.length - 1];
- if (this.type === "flow-error-end") {
- let top;
- do {
- yield* this.pop();
- top = this.peek(1);
- } while (top?.type === "flow-collection");
- } else if (fc.end.length === 0) {
- switch (this.type) {
- case "comma":
- case "explicit-key-ind":
- if (!it || it.sep)
- fc.items.push({ start: [this.sourceToken] });
- else
- it.start.push(this.sourceToken);
- return;
- case "map-value-ind":
- if (!it || it.value)
- fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
- else if (it.sep)
- it.sep.push(this.sourceToken);
- else
- Object.assign(it, { key: null, sep: [this.sourceToken] });
- return;
- case "space":
- case "comment":
- case "newline":
- case "anchor":
- case "tag":
- if (!it || it.value)
- fc.items.push({ start: [this.sourceToken] });
- else if (it.sep)
- it.sep.push(this.sourceToken);
- else
- it.start.push(this.sourceToken);
- return;
- case "alias":
- case "scalar":
- case "single-quoted-scalar":
- case "double-quoted-scalar": {
- const fs10 = this.flowScalar(this.type);
- if (!it || it.value)
- fc.items.push({ start: [], key: fs10, sep: [] });
- else if (it.sep)
- this.stack.push(fs10);
- else
- Object.assign(it, { key: fs10, sep: [] });
- return;
- }
- case "flow-map-end":
- case "flow-seq-end":
- fc.end.push(this.sourceToken);
- return;
- }
- const bv = this.startBlockValue(fc);
- if (bv)
- this.stack.push(bv);
- else {
- yield* this.pop();
- yield* this.step();
- }
- } else {
- const parent = this.peek(2);
- if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) {
- yield* this.pop();
- yield* this.step();
- } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") {
- const prev = getPrevProps(parent);
- const start = getFirstKeyStartProps(prev);
- fixFlowSeqItems(fc);
- const sep12 = fc.end.splice(1, fc.end.length);
- sep12.push(this.sourceToken);
- const map7 = {
- type: "block-map",
- offset: fc.offset,
- indent: fc.indent,
- items: [{ start, key: fc, sep: sep12 }]
- };
- this.onKeyLine = true;
- this.stack[this.stack.length - 1] = map7;
- } else {
- yield* this.lineEnd(fc);
- }
- }
- }
- flowScalar(type) {
- if (this.onNewLine) {
- let nl = this.source.indexOf(`
-`) + 1;
- while (nl !== 0) {
- this.onNewLine(this.offset + nl);
- nl = this.source.indexOf(`
-`, nl) + 1;
- }
- }
- return {
- type,
- offset: this.offset,
- indent: this.indent,
- source: this.source
- };
- }
- startBlockValue(parent) {
- switch (this.type) {
- case "alias":
- case "scalar":
- case "single-quoted-scalar":
- case "double-quoted-scalar":
- return this.flowScalar(this.type);
- case "block-scalar-header":
- return {
- type: "block-scalar",
- offset: this.offset,
- indent: this.indent,
- props: [this.sourceToken],
- source: ""
- };
- case "flow-map-start":
- case "flow-seq-start":
- return {
- type: "flow-collection",
- offset: this.offset,
- indent: this.indent,
- start: this.sourceToken,
- items: [],
- end: []
- };
- case "seq-item-ind":
- return {
- type: "block-seq",
- offset: this.offset,
- indent: this.indent,
- items: [{ start: [this.sourceToken] }]
- };
- case "explicit-key-ind": {
- this.onKeyLine = true;
- const prev = getPrevProps(parent);
- const start = getFirstKeyStartProps(prev);
- start.push(this.sourceToken);
- return {
- type: "block-map",
- offset: this.offset,
- indent: this.indent,
- items: [{ start, explicitKey: true }]
- };
- }
- case "map-value-ind": {
- this.onKeyLine = true;
- const prev = getPrevProps(parent);
- const start = getFirstKeyStartProps(prev);
- return {
- type: "block-map",
- offset: this.offset,
- indent: this.indent,
- items: [{ start, key: null, sep: [this.sourceToken] }]
- };
- }
- }
- return null;
- }
- atIndentedComment(start, indent) {
- if (this.type !== "comment")
- return false;
- if (this.indent <= indent)
- return false;
- return start.every((st) => st.type === "newline" || st.type === "space");
- }
- *documentEnd(docEnd) {
- if (this.type !== "doc-mode") {
- if (docEnd.end)
- docEnd.end.push(this.sourceToken);
- else
- docEnd.end = [this.sourceToken];
- if (this.type === "newline")
- yield* this.pop();
- }
- }
- *lineEnd(token) {
- switch (this.type) {
- case "comma":
- case "doc-start":
- case "doc-end":
- case "flow-seq-end":
- case "flow-map-end":
- case "map-value-ind":
- yield* this.pop();
- yield* this.step();
- break;
- case "newline":
- this.onKeyLine = false;
- case "space":
- case "comment":
- default:
- if (token.end)
- token.end.push(this.sourceToken);
- else
- token.end = [this.sourceToken];
- if (this.type === "newline")
- yield* this.pop();
- }
- }
- }
- exports.Parser = Parser2;
-});
-
-// node_modules/yaml/dist/public-api.js
-var require_public_api = __commonJS((exports) => {
- var composer = require_composer();
- var Document = require_Document();
- var errors8 = require_errors6();
- var log3 = require_log2();
- var identity16 = require_identity();
- var lineCounter = require_line_counter();
- var parser2 = require_parser();
- function parseOptions(options2) {
- const prettyErrors = options2.prettyErrors !== false;
- const lineCounter$1 = options2.lineCounter || prettyErrors && new lineCounter.LineCounter || null;
- return { lineCounter: lineCounter$1, prettyErrors };
- }
- function parseAllDocuments(source, options2 = {}) {
- const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options2);
- const parser$1 = new parser2.Parser(lineCounter2?.addNewLine);
- const composer$1 = new composer.Composer(options2);
- const docs = Array.from(composer$1.compose(parser$1.parse(source)));
- if (prettyErrors && lineCounter2)
- for (const doc2 of docs) {
- doc2.errors.forEach(errors8.prettifyError(source, lineCounter2));
- doc2.warnings.forEach(errors8.prettifyError(source, lineCounter2));
- }
- if (docs.length > 0)
- return docs;
- return Object.assign([], { empty: true }, composer$1.streamInfo());
- }
- function parseDocument(source, options2 = {}) {
- const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options2);
- const parser$1 = new parser2.Parser(lineCounter2?.addNewLine);
- const composer$1 = new composer.Composer(options2);
- let doc2 = null;
- for (const _doc3 of composer$1.compose(parser$1.parse(source), true, source.length)) {
- if (!doc2)
- doc2 = _doc3;
- else if (doc2.options.logLevel !== "silent") {
- doc2.errors.push(new errors8.YAMLParseError(_doc3.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
- break;
- }
- }
- if (prettyErrors && lineCounter2) {
- doc2.errors.forEach(errors8.prettifyError(source, lineCounter2));
- doc2.warnings.forEach(errors8.prettifyError(source, lineCounter2));
- }
- return doc2;
- }
- function parse10(src, reviver, options2) {
- let _reviver = undefined;
- if (typeof reviver === "function") {
- _reviver = reviver;
- } else if (options2 === undefined && reviver && typeof reviver === "object") {
- options2 = reviver;
- }
- const doc2 = parseDocument(src, options2);
- if (!doc2)
- return null;
- doc2.warnings.forEach((warning) => log3.warn(doc2.options.logLevel, warning));
- if (doc2.errors.length > 0) {
- if (doc2.options.logLevel !== "silent")
- throw doc2.errors[0];
- else
- doc2.errors = [];
- }
- return doc2.toJS(Object.assign({ reviver: _reviver }, options2));
- }
- function stringify2(value, replacer, options2) {
- let _replacer = null;
- if (typeof replacer === "function" || Array.isArray(replacer)) {
- _replacer = replacer;
- } else if (options2 === undefined && replacer) {
- options2 = replacer;
- }
- if (typeof options2 === "string")
- options2 = options2.length;
- if (typeof options2 === "number") {
- const indent = Math.round(options2);
- options2 = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };
- }
- if (value === undefined) {
- const { keepUndefined } = options2 ?? replacer ?? {};
- if (!keepUndefined)
- return;
- }
- if (identity16.isDocument(value) && !_replacer)
- return value.toString(options2);
- return new Document.Document(value, _replacer, options2).toString(options2);
- }
- exports.parse = parse10;
- exports.parseAllDocuments = parseAllDocuments;
- exports.parseDocument = parseDocument;
- exports.stringify = stringify2;
-});
-
-// node_modules/yaml/dist/index.js
-var require_dist6 = __commonJS((exports) => {
- var composer = require_composer();
- var Document = require_Document();
- var Schema = require_Schema();
- var errors8 = require_errors6();
- var Alias = require_Alias();
- var identity16 = require_identity();
- var Pair = require_Pair();
- var Scalar = require_Scalar();
- var YAMLMap = require_YAMLMap();
- var YAMLSeq = require_YAMLSeq();
- var cst = require_cst();
- var lexer2 = require_lexer();
- var lineCounter = require_line_counter();
- var parser2 = require_parser();
- var publicApi = require_public_api();
- var visit2 = require_visit();
- exports.Composer = composer.Composer;
- exports.Document = Document.Document;
- exports.Schema = Schema.Schema;
- exports.YAMLError = errors8.YAMLError;
- exports.YAMLParseError = errors8.YAMLParseError;
- exports.YAMLWarning = errors8.YAMLWarning;
- exports.Alias = Alias.Alias;
- exports.isAlias = identity16.isAlias;
- exports.isCollection = identity16.isCollection;
- exports.isDocument = identity16.isDocument;
- exports.isMap = identity16.isMap;
- exports.isNode = identity16.isNode;
- exports.isPair = identity16.isPair;
- exports.isScalar = identity16.isScalar;
- exports.isSeq = identity16.isSeq;
- exports.Pair = Pair.Pair;
- exports.Scalar = Scalar.Scalar;
- exports.YAMLMap = YAMLMap.YAMLMap;
- exports.YAMLSeq = YAMLSeq.YAMLSeq;
- exports.CST = cst;
- exports.Lexer = lexer2.Lexer;
- exports.LineCounter = lineCounter.LineCounter;
- exports.Parser = parser2.Parser;
- exports.parse = publicApi.parse;
- exports.parseAllDocuments = publicApi.parseAllDocuments;
- exports.parseDocument = publicApi.parseDocument;
- exports.stringify = publicApi.stringify;
- exports.visit = visit2.visit;
- exports.visitAsync = visit2.visitAsync;
-});
-
-// src/utils/yaml.ts
-function parseYaml(input) {
- if (typeof Bun !== "undefined") {
- return Bun.YAML.parse(input);
- }
- return require_dist6().parse(input);
-}
-
-// src/utils/frontmatterParser.ts
-function quoteProblematicValues(frontmatterText) {
- const lines2 = frontmatterText.split(`
-`);
- const result = [];
- for (const line of lines2) {
- const match = line.match(/^([a-zA-Z_-]+):\s+(.+)$/);
- if (match) {
- const [, key2, value] = match;
- if (!key2 || !value) {
- result.push(line);
- continue;
- }
- if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
- result.push(line);
- continue;
- }
- if (YAML_SPECIAL_CHARS.test(value)) {
- const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
- result.push(`${key2}: "${escaped}"`);
- continue;
- }
- }
- result.push(line);
- }
- return result.join(`
-`);
-}
-function parseFrontmatter(markdown, sourcePath) {
- const match = markdown.match(FRONTMATTER_REGEX);
- if (!match) {
- return {
- frontmatter: {},
- content: markdown
- };
- }
- const frontmatterText = match[1] || "";
- const content = markdown.slice(match[0].length);
- let frontmatter = {};
- try {
- const parsed = parseYaml(frontmatterText);
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
- frontmatter = parsed;
- }
- } catch {
- try {
- const quotedText = quoteProblematicValues(frontmatterText);
- const parsed = parseYaml(quotedText);
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
- frontmatter = parsed;
- }
- } catch (retryError) {
- const location = sourcePath ? ` in ${sourcePath}` : "";
- logForDebugging(`Failed to parse YAML frontmatter${location}: ${retryError instanceof Error ? retryError.message : retryError}`, { level: "warn" });
- }
- }
- return {
- frontmatter,
- content
- };
-}
-function splitPathInFrontmatter(input) {
- if (Array.isArray(input)) {
- return input.flatMap(splitPathInFrontmatter);
- }
- if (typeof input !== "string") {
- return [];
- }
- const parts = [];
- let current = "";
- let braceDepth = 0;
- for (let i6 = 0;i6 < input.length; i6++) {
- const char = input[i6];
- if (char === "{") {
- braceDepth++;
- current += char;
- } else if (char === "}") {
- braceDepth--;
- current += char;
- } else if (char === "," && braceDepth === 0) {
- const trimmed2 = current.trim();
- if (trimmed2) {
- parts.push(trimmed2);
- }
- current = "";
- } else {
- current += char;
- }
- }
- const trimmed = current.trim();
- if (trimmed) {
- parts.push(trimmed);
- }
- return parts.filter((p4) => p4.length > 0).flatMap((pattern) => expandBraces(pattern));
-}
-function expandBraces(pattern) {
- const braceMatch = pattern.match(/^([^{]*)\{([^}]+)\}(.*)$/);
- if (!braceMatch) {
- return [pattern];
- }
- const prefix = braceMatch[1] || "";
- const alternatives = braceMatch[2] || "";
- const suffix = braceMatch[3] || "";
- const parts = alternatives.split(",").map((alt) => alt.trim());
- const expanded = [];
- for (const part of parts) {
- const combined = prefix + part + suffix;
- const furtherExpanded = expandBraces(combined);
- expanded.push(...furtherExpanded);
- }
- return expanded;
-}
-function parsePositiveIntFromFrontmatter(value) {
- if (value === undefined || value === null) {
- return;
- }
- const parsed = typeof value === "number" ? value : parseInt(String(value), 10);
- if (Number.isInteger(parsed) && parsed > 0) {
- return parsed;
- }
- return;
-}
-function coerceDescriptionToString(value, componentName, pluginName) {
- if (value == null) {
- return null;
- }
- if (typeof value === "string") {
- return value.trim() || null;
- }
- if (typeof value === "number" || typeof value === "boolean") {
- return String(value);
- }
- const source = pluginName ? `${pluginName}:${componentName}` : componentName ?? "unknown";
- logForDebugging(`Description invalid for ${source} - omitting`, {
- level: "warn"
- });
- return null;
-}
-function parseBooleanFrontmatter(value) {
- return value === true || value === "true";
-}
-function parseShellFrontmatter(value, source) {
- if (value == null) {
- return;
- }
- const normalized = String(value).trim().toLowerCase();
- if (normalized === "") {
- return;
- }
- if (FRONTMATTER_SHELLS.includes(normalized)) {
- return normalized;
- }
- logForDebugging(`Frontmatter 'shell: ${value}' in ${source} is not recognized. Valid values: ${FRONTMATTER_SHELLS.join(", ")}. Falling back to bash.`, { level: "warn" });
- return;
-}
-var YAML_SPECIAL_CHARS, FRONTMATTER_REGEX, FRONTMATTER_SHELLS;
-var init_frontmatterParser = __esm(() => {
- init_debug();
- YAML_SPECIAL_CHARS = /[{}[\]*!|>%@`]|: /;
- FRONTMATTER_REGEX = /^---\s*\n([\s\S]*?)---\s*\n?/;
- FRONTMATTER_SHELLS = ["bash", "powershell"];
-});
-
-// src/tools/PowerShellTool/toolName.ts
-var POWERSHELL_TOOL_NAME = "PowerShell";
-
-// src/utils/promptCategory.ts
-function getQuerySourceForAgent(agentType, isBuiltInAgent) {
- if (isBuiltInAgent) {
- return agentType ? `agent:builtin:${agentType}` : "agent:default";
- } else {
- return "agent:custom";
- }
-}
-function getQuerySourceForREPL() {
- const settings = getSettings_DEPRECATED();
- const style = settings?.outputStyle ?? DEFAULT_OUTPUT_STYLE_NAME;
- if (style === DEFAULT_OUTPUT_STYLE_NAME) {
- return "repl_main_thread";
- }
- const isBuiltIn = style in OUTPUT_STYLE_CONFIG;
- return isBuiltIn ? `repl_main_thread:outputStyle:${style}` : "repl_main_thread:outputStyle:custom";
-}
-var init_promptCategory = __esm(() => {
- init_outputStyles();
- init_settings2();
-});
-
-// src/tools/EnterPlanModeTool/constants.ts
-var ENTER_PLAN_MODE_TOOL_NAME = "EnterPlanMode";
-
-// src/tools/AskUserQuestionTool/prompt.ts
-var ASK_USER_QUESTION_TOOL_NAME = "AskUserQuestion", ASK_USER_QUESTION_TOOL_CHIP_WIDTH = 12, DESCRIPTION5 = "Asks the user multiple choice questions to gather information, clarify ambiguity, understand preferences, make decisions or offer them choices.", PREVIEW_FEATURE_PROMPT, ASK_USER_QUESTION_TOOL_PROMPT;
-var init_prompt5 = __esm(() => {
- PREVIEW_FEATURE_PROMPT = {
- markdown: `
-Preview feature:
-Use the optional \`preview\` field on options when presenting concrete artifacts that users need to visually compare:
-- ASCII mockups of UI layouts or components
-- Code snippets showing different implementations
-- Diagram variations
-- Configuration examples
-
-Preview content is rendered as markdown in a monospace box. Multi-line text with newlines is supported. When any option has a preview, the UI switches to a side-by-side layout with a vertical option list on the left and preview on the right. Do not use previews for simple preference questions where labels and descriptions suffice. Note: previews are only supported for single-select questions (not multiSelect).
-`,
- html: `
-Preview feature:
-Use the optional \`preview\` field on options when presenting concrete artifacts that users need to visually compare:
-- HTML mockups of UI layouts or components
-- Formatted code snippets showing different implementations
-- Visual comparisons or diagrams
-
-Preview content must be a self-contained HTML fragment (no / wrapper, no